mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
Merge craft-libs main 07a8c471ed into the port (skeleton: conflict markers left in for the area merges)
Cargo.toml takes main's egui pin (932a73b2) and vendor list; Cargo.lock is main's, resolved again after the combine. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
a3bd3e5e07
1709 files changed
+179384
-10423
No files matched your search
@@ -69,8 +69,8 @@ workflows:
|
||||
'.github/workflows/menu.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'dtolnay/rust-toolchain@stable'
|
||||
'.github/workflows/nightly.yml':
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/pbr.yml': []
|
||||
'.github/workflows/pcraft-format.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
|
||||
|
||||
@@ -3,7 +3,7 @@ name: AI model
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml']
|
||||
pull_request:
|
||||
paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml']
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Atomic file writes
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml']
|
||||
pull_request:
|
||||
paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared audio
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Colour management
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml']
|
||||
pull_request:
|
||||
paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared CRW
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"]
|
||||
@@ -52,7 +52,7 @@ jobs:
|
||||
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
# Pull requests restore the entry main or next saved and never write their own: the same
|
||||
# Pull requests restore the entry main saved and never write their own: the same
|
||||
# files saved once per pull request took a share of the 10 GB cache budget.
|
||||
- name: Restore the CC0 sample files
|
||||
id: samples
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Dialogs
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml']
|
||||
pull_request:
|
||||
paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml']
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Craft documents
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml']
|
||||
pull_request:
|
||||
paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml']
|
||||
|
||||
@@ -6,7 +6,7 @@ name: Docs
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml']
|
||||
pull_request:
|
||||
paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml']
|
||||
|
||||
@@ -3,7 +3,7 @@ name: EffectCraft project format
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml']
|
||||
pull_request:
|
||||
paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml']
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Font store
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml']
|
||||
pull_request:
|
||||
paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared format crates
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths:
|
||||
- "crates/xml/**"
|
||||
- "crates/mime/**"
|
||||
@@ -15,8 +15,10 @@ on:
|
||||
- "crates/silhouette-studio/**"
|
||||
- "crates/tiff/**"
|
||||
- "crates/heif/**"
|
||||
- "crates/pst/**"
|
||||
- "crates/cms/**"
|
||||
- "crates/cdr/**"
|
||||
- "crates/texture/**"
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- ".github/workflows/formats.yml"
|
||||
@@ -33,8 +35,10 @@ on:
|
||||
- "crates/silhouette-studio/**"
|
||||
- "crates/tiff/**"
|
||||
- "crates/heif/**"
|
||||
- "crates/pst/**"
|
||||
- "crates/cms/**"
|
||||
- "crates/cdr/**"
|
||||
- "crates/texture/**"
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- ".github/workflows/formats.yml"
|
||||
@@ -67,9 +71,11 @@ jobs:
|
||||
- { crate: craft-svg-paths, features: "" }
|
||||
- { crate: craft-silhouette-studio, features: "" }
|
||||
- { crate: craft-tiff, features: "" }
|
||||
- { crate: craft-heif, features: "testdata" }
|
||||
- { crate: craft-heif, features: "testdata test-support" }
|
||||
- { crate: craft-pst, features: "test-writer test-support" }
|
||||
- { crate: craft-cms, features: "" }
|
||||
- { crate: craft-cdr, features: "synth" }
|
||||
- { crate: craft-texture, features: "dds parallel" }
|
||||
# fmt, clippy with default and with all features, and the tests run in the Workspace gate on
|
||||
# every OS; this lints each feature alone and checks the web build.
|
||||
name: ${{ matrix.crate }} feature sets, WASM
|
||||
|
||||
@@ -32,7 +32,9 @@ jobs:
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
linux-env: WGPU_BACKEND=vulkan
|
||||
windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1
|
||||
env: CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
env: |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
CRAFT_HOSTILE_DIVISOR=1
|
||||
setup-command: bash scripts/ci-test-inputs.sh
|
||||
command: |
|
||||
python scripts/test-full-validation.py
|
||||
|
||||
@@ -2,7 +2,7 @@ name: House rules
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared JPEG
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"]
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Keymap
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared media
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Menu
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Nightly full tests
|
||||
|
||||
# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep
|
||||
# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The
|
||||
# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The
|
||||
# rest of the workspace's tests run with them, on Linux, with the gate's setup.
|
||||
on:
|
||||
schedule:
|
||||
@@ -26,37 +26,12 @@ jobs:
|
||||
packages: mesa-vulkan-drivers libvulkan1
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
linux-env: WGPU_BACKEND=vulkan
|
||||
env: CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
env: |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
CRAFT_HOSTILE_DIVISOR=1
|
||||
setup-command: bash scripts/ci-test-inputs.sh
|
||||
cache-paths: .test-inputs/photocraft/corpus
|
||||
cache-key: photocraft-corpus
|
||||
cache-key-files: scripts/ci-test-inputs.sh
|
||||
# The gate's build (the same targets and profile overrides), with every test at its full count.
|
||||
command: bash scripts/ci-workspace-tests.sh full
|
||||
|
||||
# The scheduled run is main's; this starts the full tests above on next too, where the gate
|
||||
# runs the same fractions. It also starts one Workspace run on next a day that nothing cancels
|
||||
# (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's
|
||||
# macOS and Windows legs then run in full at least once a day, and its Linux leg builds from
|
||||
# source and saves next's own workspace-crates cache entry, which pull requests into next
|
||||
# restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with
|
||||
# `actions: write`; it checks out and runs nothing from the repository.
|
||||
workspace-next:
|
||||
name: Workspace on next
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Start the Workspace workflow and these full tests on next
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
gh workflow run workspace.yml --repo "$REPO" --ref next
|
||||
gh workflow run nightly.yml --repo "$REPO" --ref next
|
||||
@@ -0,0 +1,29 @@
|
||||
name: PBR feature tests
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml']
|
||||
pull_request:
|
||||
paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
features:
|
||||
name: PBR ${{ matrix.mode }} tests
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { mode: serial, arguments: '' }
|
||||
- { mode: parallel, arguments: '--features parallel' }
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["ubuntu-latest"]'
|
||||
craft-fonts-ref: ''
|
||||
require-craft-fonts: false
|
||||
timeout-minutes: 30
|
||||
command: cargo test -p craft-pbr --locked ${{ matrix.arguments }}
|
||||
@@ -3,7 +3,7 @@ name: PhotoCraft format
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml']
|
||||
pull_request:
|
||||
paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared PDF
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"]
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Proofing
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"]
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Suite themes
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml']
|
||||
pull_request:
|
||||
paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml']
|
||||
|
||||
@@ -3,7 +3,7 @@ name: App updates
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml']
|
||||
pull_request:
|
||||
paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml']
|
||||
|
||||
@@ -3,7 +3,7 @@ name: VectorCraft format
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml']
|
||||
pull_request:
|
||||
paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared video
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Web API (page command API)
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml']
|
||||
pull_request:
|
||||
paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Shared web host
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"]
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Window decorations
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml']
|
||||
pull_request:
|
||||
paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml']
|
||||
|
||||
@@ -2,7 +2,7 @@ name: Workspace
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
@@ -16,13 +16,12 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
# A pull request, main and next each have one group, so a newer push cancels the run it
|
||||
# supersedes; the newest push's run still tests everything before it. Every other run (a release
|
||||
# tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is
|
||||
# neither cancelled nor replaced while queued: a release run always finishes, the scheduled run
|
||||
# saves the caches, and next gets one complete macOS and Windows run a day.
|
||||
group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }}
|
||||
# A pull request and main each have one group, so a newer push cancels the run it supersedes; the
|
||||
# newest push's run still tests everything before it. Every other run (a release tag, a manual
|
||||
# run, the scheduled run) gets a group of its own and is neither cancelled nor replaced while
|
||||
# queued: a release run always finishes, and the scheduled run saves the caches.
|
||||
group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
# Whether this run needs the macOS and Windows legs, and which tests every leg runs
|
||||
@@ -71,7 +70,7 @@ jobs:
|
||||
# The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the
|
||||
# settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every
|
||||
# other override names a workspace crate (scripts/test-workspace-tests.py), so changing one
|
||||
# keeps those entries, and next's runs restore main's.
|
||||
# keeps those entries.
|
||||
- uses: actions/checkout@v7.0.1
|
||||
if: github.event_name != 'pull_request'
|
||||
with:
|
||||
@@ -104,13 +103,10 @@ jobs:
|
||||
# The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each
|
||||
# main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo
|
||||
# rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight
|
||||
# scheduled run builds from source (`cold-build`) and starts the entry afresh. next has an entry
|
||||
# of its own, since main's is built from different code and lockfile and a pull request into next
|
||||
# rebuilt nearly everything from it (15.5 minutes): nightly.yml's daily manual run on next builds
|
||||
# from source and saves it (`cache-save-on-dispatch`), and pull requests into next restore it
|
||||
# before main's. The macOS and Windows legs keep a dependency-only entry: their workspace crates
|
||||
# would not fit the 10 GB cache budget beside Linux's. The lint legs keep no cache
|
||||
# (`lint-cache: false`) for the same reason; a cold lint leg is still shorter than its gate leg.
|
||||
# scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and
|
||||
# Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache
|
||||
# budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a
|
||||
# cold lint leg is still shorter than its gate leg.
|
||||
native:
|
||||
name: Workspace
|
||||
needs: platforms
|
||||
@@ -118,9 +114,8 @@ jobs:
|
||||
with:
|
||||
os: '["ubuntu-latest"]'
|
||||
cache-workspace-crates: true
|
||||
cache-save-on-dispatch: true
|
||||
cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}
|
||||
cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }}
|
||||
cold-build: ${{ github.event.schedule == '17 0 * * *' }}
|
||||
lint-cache: false
|
||||
# The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a
|
||||
# workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them.
|
||||
@@ -182,7 +177,7 @@ jobs:
|
||||
|
||||
# The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux
|
||||
# leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on
|
||||
# every push to main and next, on main's scheduled runs and on nightly.yml's daily run on next.
|
||||
# every push to main and on main's scheduled runs.
|
||||
# A pull request that needs them before it merges gets the full-ci label.
|
||||
native-platforms:
|
||||
name: Workspace
|
||||
@@ -192,7 +187,7 @@ jobs:
|
||||
with:
|
||||
os: '["windows-latest","macos-latest"]'
|
||||
lint-cache: false
|
||||
# Named by the dependency settings alone (`deps-profile`), so next restores main's entries.
|
||||
# Named by the dependency settings alone (`deps-profile`).
|
||||
cache-version: v2-${{ needs.platforms.outputs.deps-profile }}
|
||||
timeout-minutes: *timeout
|
||||
tools: *tools
|
||||
@@ -212,15 +207,14 @@ jobs:
|
||||
lint-command: *lint
|
||||
command: *command
|
||||
|
||||
# Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as
|
||||
# does the daily manual run on next, and every run restores only the newest. This deletes the
|
||||
# older ones of the run's branch as soon as the Linux leg is done, instead of leaving them to the
|
||||
# 10 GB budget's eviction, which would evict other entries too. The only job with
|
||||
# `actions: write`; it checks out and runs nothing from the repository.
|
||||
# Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and
|
||||
# every run restores only the newest. This deletes the older ones as soon as the Linux leg is
|
||||
# done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries
|
||||
# too. The only job with `actions: write`; it checks out and runs nothing from the repository.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
needs: native
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }}
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
@@ -234,11 +228,10 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
REF: ${{ github.ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, newest first.
|
||||
gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \
|
||||
gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \
|
||||
--jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches"
|
||||
declare -A kept
|
||||
while read -r id key; do
|
||||
|
||||
@@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 |
|
||||
| Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT |
|
||||
| Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 |
|
||||
| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) |
|
||||
| `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
| `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) |
|
||||
| `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
@@ -39,6 +40,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/font-subset/tests/data/{abeezee,abel,bbhbartle,librefranklin,orbitron,sarabun}/` (unmodified; each with its `OFL.txt`) | The ABeeZee, Abel, BBH, Libre Franklin, Orbitron and Sarabun Project Authors | [google/fonts@e7db6ca `ofl/`](https://github.com/google/fonts/tree/e7db6ca/ofl) | OFL-1.1 |
|
||||
| `crates/font-subset/tests/data/ubuntu/Ubuntu-Regular.ttf` (unmodified; with `LICENCE.txt`) | Canonical Ltd. (Dalton Maag) | [google/fonts@e7db6ca `ufl/ubuntu`](https://github.com/google/fonts/tree/e7db6ca/ufl/ubuntu) | Ubuntu-font-1.0 |
|
||||
| `crates/font-subset/tests/data/notosanscjk/NotoSansCJKsc-test.otf` (subset to the test strings; with `OFL.txt`) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via storytold/font-preview-service | OFL-1.1 |
|
||||
| `crates/ui-contract/fonts/inter/Inter-Regular.ttf`, `crates/ui-contract/fonts/inter/Inter-SemiBold.ttf` (subset to 1,298 Latin, Greek, and Cyrillic codepoints with `fontTools` 4.62.1: `hinting=True`, `notdef_outline=True`, `layout_features=["*"]`, `name_IDs=["*"]`, `glyph_names=False`) | The Inter Project Authors | `storytold/craft-fonts` (`fonts/inter/Inter-Regular.ttf` sha256 `40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82`, `fonts/inter/Inter-SemiBold.ttf` sha256 `78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3`, Inter 4.001 `git-9221beed3`) | OFL-1.1 (`crates/ui-contract/fonts/inter/OFL.txt`) |
|
||||
|
||||
Original assets are covered by the repository licence.
|
||||
|
||||
@@ -94,6 +96,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso
|
||||
| `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | <https://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt>, via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) |
|
||||
| `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 |
|
||||
| `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 |
|
||||
| `crates/i18n-build/tests/fixture/` | craft-libs contributors (original work: nine hand-written catalogs of a few common interface words, in craft-i18n's catalog format; not copied from craft-i18n or any app) | this repository | MIT OR Apache-2.0 |
|
||||
| `crates/pkcs7/tests/data/` | PdfCraft contributors (original work: throw-away test keys and certificates made with OpenSSL 3 for these tests, as seven PKCS #12 files with the password `test` and two PEM certificates; they protect nothing; commands in `crates/pkcs7/tests/data/README.md`) | [PdfCraft `crates/sign/tests/data`](https://github.com/storytold/pdfcraft/tree/1d7a9f9f/crates/sign/tests/data) | MIT OR Apache-2.0 |
|
||||
| `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 113 files, 90 of them documents, are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), satoshoe-dev (affinity-samples), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; every name from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/affinity_corpus.rs) and [PhotoCraft `xtask/affinity-corpus.sha256`](https://github.com/storytold/photocraft/blob/629751503165118d5fec5f70e64fe2d6592f7b53/xtask/affinity-corpus.sha256) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) |
|
||||
| `crates/raw/docs/coverage/adobe-cameras.tsv` | Facts (maker, model, extension, profile, minimum Camera Raw version) parsed by LightCraft contributors from Adobe's published list | [Adobe Camera Raw supported cameras](https://helpx.adobe.com/camera-raw/desktop/dng-and-file-formats/camera-raw-plug-supported-cameras.html), Wayback capture 20261003133011; moved from [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | Facts, not copyrightable expression; the file is MIT OR Apache-2.0 |
|
||||
@@ -124,6 +127,8 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper
|
||||
|
||||
`crates/audio-dsp` combines FilmCraft `crates/audio-dsp` at `3f137a7ed420cac79b32145f5243b7f98b31f71c` and SoundCraft `crates/dsp` at `648ed9db9a0e98cc55643babffac381521a556c8` (both MIT OR Apache-2.0). `crates/audio-dsp/NOTICE` keeps the copyright notices of both projects.
|
||||
|
||||
`crates/audio-dsp/src/effects/voice.rs` adapts the two crossfaded read taps of SoundCraft `crates/dsp/src/plugins/pitch.rs` and the YIN pitch tracker of `crates/dsp/src/pitch_detect.rs` at `915481be1b49d7e0502e07b059d0c0198c61911a` (MIT OR Apache-2.0). The taps are centered on a fixed 10 ms latency and spaced by whole periods of the tracked pitch, and the tracker runs on a decimated copy of the input in buffers sized at creation.
|
||||
|
||||
## GIMP palette reader
|
||||
|
||||
`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes.
|
||||
@@ -171,6 +176,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
|
||||
|
||||
`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned.
|
||||
|
||||
## GPU device selection
|
||||
|
||||
`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both.
|
||||
|
||||
## Dalvik DEX inspection
|
||||
|
||||
`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained.
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
All crates share the workspace version. See [the versioning policy](docs/versioning.md).
|
||||
|
||||
## Unreleased
|
||||
|
||||
### StencilCraft document model
|
||||
|
||||
- Geometry is stored once in `Document.shapes`. Organizational layers reference shape IDs
|
||||
through `Layer.members`, and the independent, ordered `Document.operations` hold production
|
||||
passes with their own `OperationSettings` and shape memberships. Guide operations are non-output.
|
||||
- The native header now uses format version 2. This pre-release format supersedes the earlier
|
||||
schema: readers reject version 1 and other unsupported versions. Builds predating this change
|
||||
cannot open version 2 files.
|
||||
|
||||
## v0.1.0 — 2026-10-12
|
||||
|
||||
First coordinated Git release of craft-libs. Applications can pin a named baseline instead of
|
||||
|
||||
Generated
+227
-55
@@ -1125,32 +1125,36 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "candle-core"
|
||||
version = "0.9.2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091"
|
||||
checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"float8",
|
||||
"gemm",
|
||||
"half",
|
||||
"libc",
|
||||
"libm",
|
||||
"memmap2",
|
||||
"num-traits",
|
||||
"num_cpus",
|
||||
"parking_lot",
|
||||
"rand 0.9.5",
|
||||
"rand_distr",
|
||||
"rayon",
|
||||
"safetensors",
|
||||
"thiserror 2.0.21",
|
||||
"tokenizers",
|
||||
"yoke",
|
||||
"zip 7.4.0",
|
||||
"zerocopy",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "candle-nn"
|
||||
version = "0.9.2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03"
|
||||
checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e"
|
||||
dependencies = [
|
||||
"candle-core",
|
||||
"half",
|
||||
@@ -1164,14 +1168,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "candle-transformers"
|
||||
version = "0.9.2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b538ec4aa807c416a2ddd3621044888f188827862e2a6fcacba4738e89795d01"
|
||||
checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"candle-core",
|
||||
"candle-nn",
|
||||
"fancy-regex 0.17.0",
|
||||
"fancy-regex 0.19.2",
|
||||
"num-traits",
|
||||
"rand 0.9.5",
|
||||
"rayon",
|
||||
@@ -1786,6 +1790,7 @@ dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-ease",
|
||||
"craft-ecproj-format",
|
||||
"craft-elf",
|
||||
"craft-eps",
|
||||
@@ -1814,9 +1819,11 @@ dependencies = [
|
||||
"craft-geom",
|
||||
"craft-gif",
|
||||
"craft-gpu",
|
||||
"craft-gpu-device",
|
||||
"craft-gpu-null",
|
||||
"craft-gpu-providers",
|
||||
"craft-gpu-wgpu",
|
||||
"craft-gpu-yuv",
|
||||
"craft-gridcraft-format",
|
||||
"craft-gzip",
|
||||
"craft-har",
|
||||
@@ -1826,6 +1833,7 @@ dependencies = [
|
||||
"craft-html",
|
||||
"craft-http-url",
|
||||
"craft-i18n",
|
||||
"craft-i18n-build",
|
||||
"craft-ical",
|
||||
"craft-idml",
|
||||
"craft-image-codecs",
|
||||
@@ -1857,6 +1865,7 @@ dependencies = [
|
||||
"craft-media-source",
|
||||
"craft-menu",
|
||||
"craft-mesh",
|
||||
"craft-mesh-ops",
|
||||
"craft-metadata",
|
||||
"craft-metafile",
|
||||
"craft-midi",
|
||||
@@ -1869,6 +1878,7 @@ dependencies = [
|
||||
"craft-ora",
|
||||
"craft-pages",
|
||||
"craft-palette",
|
||||
"craft-pbr",
|
||||
"craft-pcap",
|
||||
"craft-pcraft-bundle",
|
||||
"craft-pcraft-format",
|
||||
@@ -1898,10 +1908,12 @@ dependencies = [
|
||||
"craft-review",
|
||||
"craft-rtf",
|
||||
"craft-sbs",
|
||||
"craft-scopes",
|
||||
"craft-score",
|
||||
"craft-scraft-format",
|
||||
"craft-settings",
|
||||
"craft-sf2",
|
||||
"craft-shared-vec",
|
||||
"craft-sheet",
|
||||
"craft-shx",
|
||||
"craft-silhouette-studio",
|
||||
@@ -2040,6 +2052,7 @@ name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
@@ -2251,7 +2264,6 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
"craft-drawingml",
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-keymap",
|
||||
@@ -2272,13 +2284,15 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
@@ -2286,6 +2300,7 @@ dependencies = [
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
"subtle",
|
||||
]
|
||||
@@ -2340,7 +2355,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2411,6 +2426,7 @@ name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
@@ -2479,7 +2495,7 @@ dependencies = [
|
||||
"craft-zip",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2490,6 +2506,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
"craft-drawingml",
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
"craft-offcrypto",
|
||||
"craft-opc",
|
||||
@@ -2504,7 +2521,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"zeroize",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2564,6 +2581,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ease"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
@@ -2599,7 +2624,7 @@ dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2638,6 +2663,7 @@ dependencies = [
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -2663,7 +2689,7 @@ dependencies = [
|
||||
"ruzstd",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2674,7 +2700,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2899,6 +2925,18 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-device"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"log",
|
||||
"pollster 0.4.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-null"
|
||||
version = "0.1.0"
|
||||
@@ -2924,6 +2962,17 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-yuv"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-null",
|
||||
"pollster 0.4.0",
|
||||
"wgpu",
|
||||
"yuv",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
@@ -3021,6 +3070,21 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n-build"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-i18n",
|
||||
"craft-i18n-build-consumer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n-build-consumer"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-i18n-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ical"
|
||||
version = "0.1.0"
|
||||
@@ -3036,7 +3100,7 @@ dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3044,6 +3108,7 @@ name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"avif-serialize",
|
||||
"craft-cms",
|
||||
"craft-dds",
|
||||
"craft-heif",
|
||||
"craft-jpeg",
|
||||
@@ -3203,7 +3268,7 @@ dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3335,6 +3400,7 @@ dependencies = [
|
||||
"craft-frame",
|
||||
"craft-media",
|
||||
"craft-time",
|
||||
"craft-video",
|
||||
"craft-y4m",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3380,6 +3446,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mesh-ops"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.30.10",
|
||||
"mikktspace",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
@@ -3434,6 +3511,8 @@ dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
"craft-markdown",
|
||||
"craft-math",
|
||||
"craft-metafile",
|
||||
"craft-wordmodel",
|
||||
@@ -3449,7 +3528,7 @@ dependencies = [
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zeroize",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3457,6 +3536,7 @@ name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-ods",
|
||||
"craft-sheet",
|
||||
"craft-xml",
|
||||
"thiserror 2.0.21",
|
||||
@@ -3486,7 +3566,7 @@ dependencies = [
|
||||
"craft-zip",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3512,7 +3592,7 @@ dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3535,6 +3615,20 @@ dependencies = [
|
||||
name = "craft-palette"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-materialx",
|
||||
"craft-mesh",
|
||||
"craft-pbr",
|
||||
"craft-texture",
|
||||
"glam 0.30.10",
|
||||
"naga",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pcap"
|
||||
version = "0.1.0"
|
||||
@@ -3638,7 +3732,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3988,6 +4082,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-scopes"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-color",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-score"
|
||||
version = "0.1.0"
|
||||
@@ -4037,6 +4140,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-shared-vec"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-shared-vec",
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
@@ -4062,7 +4175,7 @@ dependencies = [
|
||||
"kurbo",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4156,6 +4269,7 @@ dependencies = [
|
||||
name = "craft-suite-account"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
@@ -4229,6 +4343,16 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"png 0.18.1",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tempfile",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
@@ -4261,8 +4385,12 @@ name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-exr",
|
||||
"craft-hdr",
|
||||
"craft-image-codecs",
|
||||
"dds",
|
||||
"half",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -4398,7 +4526,6 @@ name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-keymap",
|
||||
@@ -4608,11 +4735,13 @@ dependencies = [
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"craft-host",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"dunce",
|
||||
"ed25519-dalek 2.2.0",
|
||||
"egui",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -4625,11 +4754,12 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4862,8 +4992,14 @@ name = "craft-xtask"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"flate2",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml_edit",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4886,7 +5022,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.3",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5117,6 +5253,12 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "daachorse"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d"
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.20.11"
|
||||
@@ -5190,7 +5332,7 @@ checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068"
|
||||
dependencies = [
|
||||
"astc-decode",
|
||||
"bitflags 2.13.2",
|
||||
"glam",
|
||||
"glam 0.25.0",
|
||||
"resize",
|
||||
"zerocopy",
|
||||
]
|
||||
@@ -5583,6 +5725,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5638,6 +5781,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5672,6 +5816,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5690,6 +5835,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5708,6 +5854,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5727,6 +5874,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5739,6 +5887,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5815,6 +5964,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5887,6 +6037,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5912,6 +6063,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -6186,9 +6338,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "float8"
|
||||
version = "0.6.1"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5"
|
||||
checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc"
|
||||
dependencies = [
|
||||
"half",
|
||||
"num-traits",
|
||||
@@ -6721,12 +6873,27 @@ dependencies = [
|
||||
"xml-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b"
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.25.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3"
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.30.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
version = "0.1.1"
|
||||
@@ -8254,8 +8421,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"euclid",
|
||||
@@ -8571,6 +8736,15 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
|
||||
|
||||
[[package]]
|
||||
name = "mikktspace"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0"
|
||||
dependencies = [
|
||||
"glam 0.15.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
@@ -11411,13 +11585,15 @@ checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714"
|
||||
|
||||
[[package]]
|
||||
name = "safetensors"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5"
|
||||
checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846"
|
||||
dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -12811,16 +12987,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokenizers"
|
||||
version = "0.22.2"
|
||||
version = "0.23.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"
|
||||
checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"aho-corasick",
|
||||
"compact_str",
|
||||
"daachorse",
|
||||
"dary_heap",
|
||||
"derive_builder",
|
||||
"esaxx-rs",
|
||||
"fancy-regex 0.17.0",
|
||||
"getrandom 0.3.4",
|
||||
"itertools 0.14.0",
|
||||
"log",
|
||||
@@ -13066,12 +13243,6 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typed-path"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c"
|
||||
|
||||
[[package]]
|
||||
name = "typed-path"
|
||||
version = "0.13.0"
|
||||
@@ -14947,6 +15118,15 @@ dependencies = [
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yuv"
|
||||
version = "0.8.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus"
|
||||
version = "5.19.0"
|
||||
@@ -15126,18 +15306,6 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "7.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"typed-path 0.12.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.3"
|
||||
@@ -15150,7 +15318,7 @@ dependencies = [
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"nix",
|
||||
"typed-path 0.13.0",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
@@ -15243,15 +15411,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
+24
-15
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -32,11 +32,14 @@ craft-ssip = { path = "crates/ssip" }
|
||||
craft-ber = { path = "crates/ber" }
|
||||
craft-proto = { path = "crates/proto" }
|
||||
craft-render-parity = { path = "crates/render-parity" }
|
||||
craft-shared-vec = { path = "crates/shared-vec" }
|
||||
acadrust = "=0.6.6"
|
||||
log = "0.4"
|
||||
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
|
||||
craft-plist = { path = "crates/plist" }
|
||||
craft-gpu-device = { path = "crates/gpu-device" }
|
||||
craft-wasm = { path = "crates/wasm" }
|
||||
craft-gpu-yuv = { path = "crates/gpu-yuv" }
|
||||
craft-platform = { path = "crates/platform" }
|
||||
craft-png = { path = "crates/png" }
|
||||
craft-aep = { path = "crates/aep" }
|
||||
@@ -81,6 +84,7 @@ craft-cloud = { path = "crates/cloud" }
|
||||
craft-cloud-local = { path = "crates/cloud-local" }
|
||||
craft-cloud-ui = { path = "crates/cloud-ui" }
|
||||
craft-color = { path = "crates/color" }
|
||||
craft-scopes = { path = "crates/scopes" }
|
||||
craft-color-ui = { path = "crates/color-ui" }
|
||||
craft-color-transform = { path = "crates/color-transform" }
|
||||
craft-frame = { path = "crates/frame" }
|
||||
@@ -102,6 +106,7 @@ craft-deckcraft-format = { path = "crates/deckcraft-format" }
|
||||
craft-designcraft-format = { path = "crates/designcraft-format" }
|
||||
craft-dxf = { path = "crates/dxf" }
|
||||
craft-drawingml = { path = "crates/drawingml" }
|
||||
craft-ease = { path = "crates/ease" }
|
||||
craft-eps = { path = "crates/eps" }
|
||||
craft-elf = { path = "crates/elf" }
|
||||
craft-file-formats = { path = "crates/file-formats" }
|
||||
@@ -131,6 +136,7 @@ craft-gcode = { path = "crates/gcode" }
|
||||
craft-gif = { path = "crates/gif" }
|
||||
craft-hdr = { path = "crates/hdr" }
|
||||
craft-mesh = { path = "crates/mesh" }
|
||||
craft-mesh-ops = { path = "crates/mesh-ops" }
|
||||
craft-html = { path = "crates/html" }
|
||||
craft-ipp = { path = "crates/ipp" }
|
||||
craft-heif = { path = "crates/heif" }
|
||||
@@ -145,6 +151,7 @@ craft-gpu-null = { path = "crates/gpu-null" }
|
||||
craft-gpu-providers = { path = "crates/gpu-providers" }
|
||||
craft-gpu-wgpu = { path = "crates/gpu-wgpu" }
|
||||
craft-i18n = { path = "crates/i18n" }
|
||||
craft-i18n-build = { path = "crates/i18n-build" }
|
||||
craft-ipc = { path = "crates/ipc" }
|
||||
craft-idml = { path = "crates/idml" }
|
||||
craft-indd = { path = "crates/indd" }
|
||||
@@ -227,6 +234,7 @@ craft-testkit = { path = "crates/testkit" }
|
||||
craft-text = { path = "crates/text" }
|
||||
craft-tcraft = { path = "crates/tcraft" }
|
||||
craft-texture = { path = "crates/texture" }
|
||||
craft-pbr = { path = "crates/pbr" }
|
||||
craft-tga = { path = "crates/tga" }
|
||||
craft-timeline = { path = "crates/timeline" }
|
||||
craft-tiff = { path = "crates/tiff" }
|
||||
@@ -317,20 +325,21 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
ecolor = { path = "../egui/crates/ecolor" }
|
||||
emath = { path = "../egui/crates/emath" }
|
||||
epaint = { path = "../egui/crates/epaint" }
|
||||
epaint_default_fonts = { path = "../egui/crates/epaint_default_fonts" }
|
||||
egui = { path = "../egui/crates/egui" }
|
||||
egui-winit = { path = "../egui/crates/egui-winit" }
|
||||
egui-wgpu = { path = "../egui/crates/egui-wgpu" }
|
||||
egui_glow = { path = "../egui/crates/egui_glow" }
|
||||
egui_extras = { path = "../egui/crates/egui_extras" }
|
||||
egui_kittest = { path = "../egui/crates/egui_kittest" }
|
||||
egui_system_font_provider = { path = "../egui/crates/egui_system_font_provider" }
|
||||
eframe = { path = "../egui/crates/eframe" }
|
||||
egui_demo_lib = { path = "../egui/crates/egui_demo_lib" }
|
||||
egui_inspection = { path = "../egui/crates/egui_inspection" }
|
||||
kurbo = { path = "vendor/kurbo" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops,
|
||||
is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C
|
||||
MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or
|
||||
altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full.
|
||||
crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer.
|
||||
crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists)
|
||||
2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/.
|
||||
@@ -229,6 +233,37 @@ The colour management module in crates/cms is extracted from:
|
||||
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
|
||||
(CC0-1.0); see ATTRIBUTION.md.
|
||||
|
||||
The mesh operations in crates/mesh-ops are moved from:
|
||||
- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs,
|
||||
camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2.
|
||||
https://github.com/storytold/texturecraft
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
|
||||
- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision
|
||||
3133062968b8a1566eda12a357cb06062db16687.
|
||||
https://github.com/storytold/materialcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
|
||||
All licensed MIT OR Apache-2.0.
|
||||
|
||||
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
|
||||
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
|
||||
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
|
||||
https://github.com/storytold/texturecraft
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
|
||||
- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88,
|
||||
whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs.
|
||||
https://github.com/storytold/materialcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
|
||||
The BRDF, environment BRDF and default environment in crates/pbr are adapted from:
|
||||
- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision
|
||||
41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment
|
||||
are copied to crates/pbr/tests/it/reference/effectcraft.rs.
|
||||
https://github.com/storytold/effectcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
|
||||
The WGSL text in crates/pbr/src/shade.wgsl is adapted from:
|
||||
- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision
|
||||
f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above).
|
||||
All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them.
|
||||
|
||||
Optional PDF writer
|
||||
|
||||
Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0.
|
||||
@@ -268,10 +303,18 @@ 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,
|
||||
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.
|
||||
vendor/linesweeper with its upstream license files and local changes. 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
|
||||
changes and the files left out.
|
||||
|
||||
kurbo
|
||||
|
||||
kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR
|
||||
Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to
|
||||
src/stroke.rs. Its source files carry "Copyright <year> the Kurbo Authors" lines (2018 to 2026),
|
||||
and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and
|
||||
vendor/kurbo/SOURCE.json for provenance and the local patches.
|
||||
|
||||
Platform lifecycle source provenance
|
||||
|
||||
|
||||
@@ -72,11 +72,14 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
|
||||
- [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target).
|
||||
- [`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-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), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft.
|
||||
- [`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
|
||||
FilmCraft.
|
||||
- [`craft-cdr`](crates/cdr/README.md): bounded reader and writer of `.cdr` drawings: versions 1 to
|
||||
27 and `.cmx` files read into one drawing model (pages, layers, groups, shapes, fills and
|
||||
outlines), and version 15 `.cdr` files written.
|
||||
- [`craft-cfb`](crates/cfb/README.md): clean-room Compound File Binary ([MS-CFB], OLE structured
|
||||
storage) reader and writer: the container of legacy Office files, Outlook messages, encrypted
|
||||
OOXML packages and AAF. Bounded on hostile input; what the streams hold stays with each format.
|
||||
@@ -126,6 +129,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines
|
||||
(`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps
|
||||
(`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format.
|
||||
- [`craft-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths
|
||||
and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence,
|
||||
editable custom and sampled curves, hold keys and a spring stepped by its exact solution.
|
||||
From AniCraft and EffectCraft. No dependencies without the optional `serde` feature.
|
||||
- [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names.
|
||||
- [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary
|
||||
preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`),
|
||||
@@ -204,6 +211,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
every frame's position, delay, disposal and transparent colour, the loop count and the first
|
||||
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
|
||||
a file can hold the picture it declares before a decoder runs.
|
||||
- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to
|
||||
NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full
|
||||
range, through the `craft-gpu` job registry on the null context or on a device. Each output texel
|
||||
averages the part of the source it covers. The crate also has the render passes for a caller's
|
||||
own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the
|
||||
CPU. Encoders and scopes stay in each app.
|
||||
- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto,
|
||||
low power, a named adapter that survives a reordered list and a driver update, or software;
|
||||
corrections for drivers that crash; the next adapter and then a software one when a device fails
|
||||
to open; a capability report; device-loss and error recording without panics; and what to reopen
|
||||
after a loss. Settings pages and the window stay in each app.
|
||||
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
|
||||
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
|
||||
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
|
||||
@@ -219,6 +237,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and
|
||||
a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their
|
||||
language setting.
|
||||
- [`craft-i18n-build`](crates/i18n-build/README.md): embeds the optional craft-i18n catalogs
|
||||
from an app's `build.rs` (`CRAFT_I18N_DIR`, `CRAFT_I18N_REQUIRED`) as the table `craft-i18n`
|
||||
reads, with each regional locale's parent and the app's own catalogs merged in. No
|
||||
dependencies.
|
||||
- [`craft-raw`](crates/raw/README.md): camera raw files, the file-format layer, from LightCraft with
|
||||
what PhotoCraft's and FilmCraft's readers added: container parsing and decompression to a neutral
|
||||
raw image (samples, CFA, black and white levels, active area, crop, orientation, colour tags,
|
||||
@@ -291,7 +313,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
- [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model.
|
||||
- [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format.
|
||||
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
|
||||
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and
|
||||
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`), Bink (`bink`) and
|
||||
MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and
|
||||
video codecs will go in a separate crate.
|
||||
- [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of
|
||||
@@ -307,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY,
|
||||
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-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals,
|
||||
MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a
|
||||
BVH for ray casts, and an orbit camera. From 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.
|
||||
@@ -366,8 +391,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item
|
||||
means stays in each app.
|
||||
|
||||
- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional
|
||||
app menu. Unsaved-document decisions and save prompts stay in each app.
|
||||
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
|
||||
documents, the Quit menu item id and the unsaved-changes question one document at a time
|
||||
(`CloseGuard`). The prompt and the saving stay in each app.
|
||||
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
|
||||
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
|
||||
for a small neutral model (paragraphs, character formatting, outline levels, tables).
|
||||
@@ -377,6 +403,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui`
|
||||
feature).
|
||||
- [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md).
|
||||
- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`.
|
||||
- [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies.
|
||||
- [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft.
|
||||
- [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused.
|
||||
@@ -399,11 +426,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
reference picking, selection statistics, error tags and filter buttons (`ui` feature).
|
||||
- [`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.
|
||||
out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts
|
||||
from font bytes the caller supplies: a face with a renamed family and a TrueType collection. 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. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module
|
||||
prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the
|
||||
test when the variable the caller names is `1`. Any other value of that variable except empty fails
|
||||
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
|
||||
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
|
||||
under `target/fixtures` and publishes each one under a lock. Not published.
|
||||
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
|
||||
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
|
||||
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
|
||||
@@ -411,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
(ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find`
|
||||
(regex) are features.
|
||||
- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are
|
||||
bounded by `Limits`. From MaterialCraft.
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and
|
||||
(optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float
|
||||
samples. Sizes are bounded by `Limits`. From MaterialCraft.
|
||||
- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates,
|
||||
timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE,
|
||||
CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel,
|
||||
|
||||
@@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran
|
||||
/// to give each character run its paragraph's format.
|
||||
pub fn count_paragraph_lookups<T>(f: impl FnOnce() -> T) -> (T, usize) {
|
||||
crate::text::MATCH_READS.with(|reads| reads.set(0));
|
||||
let value = f();
|
||||
(value, crate::text::MATCH_READS.with(std::cell::Cell::get))
|
||||
}
|
||||
@@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
// Sorted by end (they are in order in every file), so both lookups below are binary
|
||||
// searches: a block can have as many paragraphs and runs as characters.
|
||||
paragraphs.sort_by_key(|(end, _)| *end);
|
||||
let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
|
||||
let align_at = |i: usize| {
|
||||
let at = paragraphs.partition_point(|(end, _)| {
|
||||
count_match_read();
|
||||
*end <= i
|
||||
});
|
||||
paragraphs.get(at).map(|(_, a)| *a).or(open).unwrap_or_default()
|
||||
};
|
||||
let mut cuts: Vec<usize> = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
|
||||
cuts.dedup();
|
||||
let push = |r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, from: usize, to: usize, budget: &mut Option<usize>| {
|
||||
// Split at paragraph ends so every run has one paragraph format.
|
||||
let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
|
||||
let first = cuts.partition_point(|c| {
|
||||
count_match_read();
|
||||
*c <= from
|
||||
});
|
||||
let past = cuts.partition_point(|c| {
|
||||
count_match_read();
|
||||
*c < to
|
||||
});
|
||||
let inside = cuts.get(first..past).unwrap_or_default();
|
||||
let mut a = from;
|
||||
for &c in inside.iter().chain(std::iter::once(&to)) {
|
||||
push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
|
||||
@@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
(runs, first_align.unwrap_or(Align::Left))
|
||||
}
|
||||
|
||||
// Each paragraph end `story_runs` reads to match character runs to paragraphs, on this thread.
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
std::thread_local! {
|
||||
pub(crate) static MATCH_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_match_read() {
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
fn characters(chars: &[char], start: usize, end: usize) -> String {
|
||||
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
|
||||
}
|
||||
|
||||
@@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() {
|
||||
|
||||
#[test]
|
||||
fn many_paragraphs_and_runs_are_matched_in_about_linear_time() {
|
||||
// 200 000 paragraphs, each with its own run and format.
|
||||
let n = 200_000;
|
||||
let text = "a\u{2029}".repeat(n);
|
||||
let fmt =
|
||||
|end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))];
|
||||
let blk = F::Obj(
|
||||
tag(b"StBl"),
|
||||
vec![
|
||||
(tag(b"Glyp"), utf8(&text)),
|
||||
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
|
||||
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
|
||||
],
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]);
|
||||
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
|
||||
assert_eq!(t.runs.len(), n);
|
||||
// (About half a second; quadratic matching took over half a minute on the same machine.)
|
||||
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
|
||||
// `n` paragraphs, each with its own run and format, and how many paragraph ends matching
|
||||
// them looks up.
|
||||
let lookups = |n: usize| {
|
||||
let text = "a\u{2029}".repeat(n);
|
||||
let fmt = |end: usize| {
|
||||
vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]
|
||||
};
|
||||
let blk = F::Obj(
|
||||
tag(b"StBl"),
|
||||
vec![
|
||||
(tag(b"Glyp"), utf8(&text)),
|
||||
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
|
||||
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
|
||||
],
|
||||
);
|
||||
let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]));
|
||||
let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story]));
|
||||
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
|
||||
assert_eq!(t.runs.len(), n);
|
||||
lookups
|
||||
};
|
||||
// Four times the paragraphs and runs: a few binary searches each, so about four times the
|
||||
// lookups (a little more for the longer searches), where matching each run against every
|
||||
// paragraph is sixteen times.
|
||||
let (quarter, full) = (lookups(50_000), lookups(200_000));
|
||||
assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000");
|
||||
}
|
||||
|
||||
/// A shape node of `size` px.
|
||||
|
||||
@@ -19,10 +19,10 @@ dirs = "7"
|
||||
sysinfo = "0.39"
|
||||
ureq = { version = "3", features = ["json"] }
|
||||
sha2 = "0.11"
|
||||
candle-core = { version = "0.9", optional = true }
|
||||
candle-nn = { version = "0.9", optional = true }
|
||||
candle-transformers = { version = "0.9", optional = true }
|
||||
tokenizers = { version = "0.22", optional = true, default-features = false, features = ["onig"] }
|
||||
candle-core = { version = "0.11.1", optional = true }
|
||||
candle-nn = { version = "0.11.1", optional = true }
|
||||
candle-transformers = { version = "0.11.1", optional = true }
|
||||
tokenizers = { version = "0.23", optional = true, default-features = false, features = ["onig"] }
|
||||
|
||||
[features]
|
||||
# Local GGUF inference on candle. Heavy dependency tree; apps opt in.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-appkit"
|
||||
description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,11 +8,12 @@ rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
|
||||
# `NSNotificationCenter` with a block.
|
||||
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6.2"
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
|
||||
|
||||
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
|
||||
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS
|
||||
//! only; the crate is empty elsewhere.
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
|
||||
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
|
||||
//!
|
||||
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
|
||||
//! block says why it is sound.
|
||||
@@ -14,6 +14,8 @@ use block2::RcBlock;
|
||||
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
|
||||
use objc2_foundation::{NSNotification, NSNotificationCenter};
|
||||
|
||||
pub mod save_panel;
|
||||
|
||||
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
|
||||
/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once
|
||||
/// for the process; a later call replaces nothing and does nothing.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action.
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::AnyObject;
|
||||
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
|
||||
use objc2_app_kit::{NSPopUpButton, NSSavePanel};
|
||||
use objc2_foundation::{NSObject, NSObjectProtocol};
|
||||
|
||||
/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems
|
||||
/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it.
|
||||
pub fn new_save_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
|
||||
// SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as
|
||||
// `Option`, so nil is `None`.
|
||||
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
|
||||
if panel.is_some() {
|
||||
return panel;
|
||||
}
|
||||
// SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`.
|
||||
unsafe { msg_send![NSSavePanel::class(), savePanel] }
|
||||
}
|
||||
|
||||
/// The closure a [`PopUpChoice`] calls.
|
||||
pub struct Ivars {
|
||||
on_choose: Box<dyn Fn(usize)>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`.
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = Ivars]
|
||||
#[name = "CraftPopUpChoice"]
|
||||
/// The target of a pop-up menu's action; see [`on_choose`].
|
||||
pub struct PopUpChoice;
|
||||
|
||||
// SAFETY: NSObjectProtocol has no additional requirements.
|
||||
unsafe impl NSObjectProtocol for PopUpChoice {}
|
||||
|
||||
impl PopUpChoice {
|
||||
// SAFETY: NSControl's target-action sends the pop-up button as the one object argument.
|
||||
#[unsafe(method(choose:))]
|
||||
fn choose(&self, sender: &NSPopUpButton) {
|
||||
if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) {
|
||||
(self.ivars().on_choose)(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target,
|
||||
/// so the caller keeps the returned object for as long as `popup` can send its action.
|
||||
pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained<PopUpChoice> {
|
||||
let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) });
|
||||
// SAFETY: NSObject's designated initializer, called once on the allocated subclass.
|
||||
let target: Retained<PopUpChoice> = unsafe { msg_send![super(this), init] };
|
||||
let object: &AnyObject = ⌖
|
||||
// SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps
|
||||
// `target` alive while `popup` can send it (the documentation above).
|
||||
unsafe {
|
||||
popup.setTarget(Some(object));
|
||||
popup.setAction(Some(sel!(choose:)));
|
||||
}
|
||||
target
|
||||
}
|
||||
+22
-1
@@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee
|
||||
|
||||
## Core Guarantees: Atomicity vs. Durability
|
||||
|
||||
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted.
|
||||
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted.
|
||||
2. **Durability & Ordering Boundaries**:
|
||||
- **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback).
|
||||
- **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced.
|
||||
@@ -63,6 +63,27 @@ let path = Path::new("export.png");
|
||||
write_new(path, b"png bytes...").expect("exclusive write");
|
||||
```
|
||||
|
||||
### Removing Orphaned Staging Files
|
||||
|
||||
```rust
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use craft_atomic::sweep_temp_files;
|
||||
|
||||
// Removes staging files in scenes/ that were last modified an hour or more ago.
|
||||
// Returns how many were removed.
|
||||
let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0);
|
||||
```
|
||||
|
||||
`sweep_temp_files` removes only regular files whose names have the staging form, never follows
|
||||
a symbolic link, and does not search subfolders. A save updates its staging file's modification
|
||||
time only while it writes bytes, not while it flushes or renames, and removing the staging file
|
||||
makes that save fail. Choose a minimum age longer than the longest time any save into the folder,
|
||||
by any process including the calling one, may go without writing, counting the final flush and
|
||||
rename. On Windows, a write may not update the modification time until the staging file's handle
|
||||
closes, so choose a minimum age longer than the longest whole save, from the staging file's
|
||||
creation through the rename. Entries that cannot be removed are left in place.
|
||||
|
||||
### Document Permissions and Private Data
|
||||
|
||||
The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`.
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
//! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs
|
||||
//! during staging or rename, the target remains unmodified and the staging file is removed in user space.
|
||||
//! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and
|
||||
//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the
|
||||
//! consuming application; the library does not perform background sweeping. The destination file itself is
|
||||
//! never corrupted.
|
||||
//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming
|
||||
//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging
|
||||
//! files. The destination file itself is never corrupted.
|
||||
//! - **Durability & Ordering Boundaries**:
|
||||
//! Data persistence across power failures involves two sync points:
|
||||
//! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage
|
||||
@@ -818,6 +818,57 @@ pub fn temp_name(file: &str) -> String {
|
||||
format!(".{stem}.{pid}-{n}.craft_tmp")
|
||||
}
|
||||
|
||||
/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed.
|
||||
///
|
||||
/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a
|
||||
/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process
|
||||
/// id in the name is not used to decide, since the system reuses process ids. A save updates its
|
||||
/// staging file's modification time only while it writes bytes, not while it flushes or renames,
|
||||
/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest
|
||||
/// time any save into `dir`, by any process including the calling one, may go without writing,
|
||||
/// counting the final flush and rename. On Windows, a write may not update the modification time
|
||||
/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save,
|
||||
/// from the staging file's creation through the rename. Entries that cannot be read or removed are
|
||||
/// left in place. Subfolders are not searched.
|
||||
/// On `wasm32` this returns an `Unsupported` error.
|
||||
pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result<usize> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (dir, min_age);
|
||||
Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform"))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let now = std::time::SystemTime::now();
|
||||
let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?;
|
||||
let mut removed = 0;
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_str().is_some_and(is_temp_name) {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
|
||||
let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age);
|
||||
if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem
|
||||
/// of at most [`TEMP_STEM_BYTES`] bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn is_temp_name(name: &str) -> bool {
|
||||
// Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed.
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'));
|
||||
let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else {
|
||||
return false;
|
||||
};
|
||||
let Some((pid, n)) = tail.split_once('-') else { return false };
|
||||
stem.len() <= TEMP_STEM_BYTES && digits(pid) && digits(n) && pid.parse::<u32>().is_ok() && n.parse::<u64>().is_ok()
|
||||
}
|
||||
|
||||
/// The end of an error message: whether an original file was left as it was.
|
||||
fn unchanged(existed: bool) -> &'static str {
|
||||
if existed { "; the original file was not changed" } else { "" }
|
||||
|
||||
@@ -582,3 +582,79 @@ fn wasm_atomic_write_returns_unsupported() {
|
||||
let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[test]
|
||||
fn wasm_sweep_temp_files_returns_unsupported() {
|
||||
let err = sweep_temp_files(Path::new("scenes"), std::time::Duration::ZERO).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
|
||||
}
|
||||
|
||||
/// Writes the file `name` in `dir` and dates its modification time `age` in the past.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn leftover(dir: &Path, name: &str, age: std::time::Duration) -> io::Result<PathBuf> {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, b"interrupted save")?;
|
||||
File::options().write(true).open(&p)?.set_modified(std::time::SystemTime::now() - age)?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sweep_removes_only_old_staging_files() -> io::Result<()> {
|
||||
let d = TempDir::new("sweep_old");
|
||||
let other = std::process::id().wrapping_add(1);
|
||||
let hour = std::time::Duration::from_secs(3600);
|
||||
let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?;
|
||||
// A process id the system reused for this process does not protect an old orphan.
|
||||
let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?;
|
||||
let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), std::time::Duration::ZERO)?;
|
||||
let document = leftover(&d.0, "scene.json", 2 * hour)?;
|
||||
|
||||
assert_eq!(sweep_temp_files(&d.0, hour)?, 2);
|
||||
assert!(!orphan.exists() && !same_pid.exists());
|
||||
assert!(recent.exists() && document.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> {
|
||||
let d = TempDir::new("sweep_lookalike");
|
||||
let other = std::process::id().wrapping_add(1);
|
||||
let old = std::time::Duration::from_secs(7200);
|
||||
let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?;
|
||||
let kept = [
|
||||
leftover(&d.0, "notes.craft_tmp", old)?,
|
||||
leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?,
|
||||
leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?,
|
||||
leftover(&d.0, ".scene.json.-3.craft_tmp", old)?,
|
||||
leftover(&d.0, ".12-3.craft_tmp", old)?,
|
||||
leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?,
|
||||
leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?,
|
||||
// temp_name writes the process id and the counter without leading zeros.
|
||||
leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?,
|
||||
leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?,
|
||||
// temp_name keeps at most TEMP_STEM_BYTES bytes of the destination's name.
|
||||
leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(TEMP_STEM_BYTES + 1)), old)?,
|
||||
];
|
||||
// The longest stem temp_name writes, in ASCII and in two-byte characters.
|
||||
let longest = leftover(&d.0, &temp_name(&"s".repeat(200)), old)?;
|
||||
let longest_wide = leftover(&d.0, &temp_name(&"é".repeat(100)), old)?;
|
||||
let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp"));
|
||||
std::fs::create_dir(&folder)?;
|
||||
|
||||
assert_eq!(sweep_temp_files(&d.0, std::time::Duration::ZERO)?, 3);
|
||||
assert!(!orphan.exists() && !longest.exists() && !longest_wide.exists());
|
||||
assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed");
|
||||
assert!(folder.is_dir());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sweep_of_a_missing_folder_is_an_error() {
|
||||
let d = TempDir::new("sweep_missing");
|
||||
let err = sweep_temp_files(&d.0.join("absent"), std::time::Duration::ZERO).err().map(|e| e.kind());
|
||||
assert_eq!(err, Some(io::ErrorKind::NotFound));
|
||||
}
|
||||
@@ -12,7 +12,19 @@ and contains no `unsafe` code.
|
||||
(compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors),
|
||||
delays and reverbs (including convolution and surround), modulation, restoration (denoise,
|
||||
dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion,
|
||||
dither, a signal generator and a loudness meter.
|
||||
dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of
|
||||
latency, a formant shifter for a live voice with 10.7 ms of latency, and noise suppression for
|
||||
a live voice with 5.3 ms of latency that follows the noise floor without first learning it.
|
||||
These latencies are at 48 kHz (the STFT sizes depend on the sample rate; `latency()` reports
|
||||
them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency,
|
||||
and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic
|
||||
voices (ring, frequency modulation, and positive or negative comb resonators, with the
|
||||
frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and
|
||||
neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits,
|
||||
or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato
|
||||
that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds
|
||||
no latency either: the delay is 0 at the start of each cycle, except while it glides to new
|
||||
settings.
|
||||
- `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated
|
||||
loudness, loudness range (EBU Tech 3342), sample peak and true peak.
|
||||
- `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order
|
||||
@@ -27,6 +39,14 @@ and contains no `unsafe` code.
|
||||
- `biquad` and `design`: biquad filters with their magnitude response, and IIR filter design from
|
||||
Butterworth, Bessel, Chebyshev and elliptic prototypes.
|
||||
|
||||
`noise_suppression` estimates the noise floor from minimum spectral power over 1.5 s. The first
|
||||
noise estimate after a reset starts from the median bin's power. Each bin's value is clamped
|
||||
between 30 dB below its own estimate and its own estimate. Windows that overlap a run of at
|
||||
least one hop of zeros (64 samples at 48 kHz) do not enter the noise estimate. The gain floor
|
||||
moves from 0 dB toward the attenuation set by `reduction` during the first search window
|
||||
of sound. Continuous voiced or tonal audio present from startup can enter the noise estimate
|
||||
and be attenuated afterward.
|
||||
|
||||
## Conventions
|
||||
|
||||
Audio is planar `f32`: one slice per channel, all the same length. `AudioEffect::process`,
|
||||
@@ -76,6 +96,10 @@ The crate combines two crates from the ArtCraft apps, with changes:
|
||||
`648ed9db9a0e98cc55643babffac381521a556c8`: the tail length, offline mode, events, saved state
|
||||
and editor parts of the trait, the maximizer, dither, panning, the signal generator and the
|
||||
offline resampler.
|
||||
- [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at
|
||||
`915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch
|
||||
shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`), and the
|
||||
ring modulator (`src/plugins/modulation.rs`).
|
||||
|
||||
`NOTICE` keeps the copyright notices of both projects.
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Audio effects and their registry.
|
||||
|
||||
pub(crate) mod channel;
|
||||
pub(crate) mod character;
|
||||
pub(crate) mod declick;
|
||||
pub(crate) mod dither;
|
||||
pub(crate) mod dynamics;
|
||||
@@ -15,10 +16,13 @@ pub(crate) mod restoration;
|
||||
pub(crate) mod reverbs;
|
||||
pub(crate) mod special;
|
||||
mod stft;
|
||||
pub(crate) mod suppress;
|
||||
pub(crate) mod time;
|
||||
pub(crate) mod util;
|
||||
pub(crate) mod voice;
|
||||
|
||||
pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};
|
||||
pub use character::{Bitcrusher, RingMod, Tremolo, Vibrato};
|
||||
pub(crate) use declick::ClickRemover;
|
||||
pub use dither::Dither;
|
||||
pub use dynamics::{Compressor, Gate, Limiter, Maximizer};
|
||||
@@ -34,7 +38,9 @@ pub(crate) use restoration::{DeHum, DeNoise};
|
||||
pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb};
|
||||
pub use special::LoudnessMeterFx;
|
||||
pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer};
|
||||
pub use suppress::NoiseSuppression;
|
||||
pub(crate) use time::{Delay, Reverb};
|
||||
pub use voice::{VoiceFormant, VoicePitch};
|
||||
|
||||
use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate};
|
||||
|
||||
@@ -123,7 +129,10 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
},
|
||||
entry!("dehum", "DeHum", Restoration, DeHum),
|
||||
entry!("denoise", "DeNoise", Restoration, DeNoise),
|
||||
entry!("noise_suppression", "Noise Suppression", Restoration, NoiseSuppression),
|
||||
entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter),
|
||||
entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch),
|
||||
entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant),
|
||||
entry!("deesser", "DeEsser", Restoration, DeEsser),
|
||||
entry!("dereverb", "DeReverb", Restoration, DeReverb),
|
||||
entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance),
|
||||
@@ -141,6 +150,9 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger),
|
||||
entry!("flanger", "Flanger", Modulation, Flanger),
|
||||
entry!("phaser", "Phaser", Modulation, Phaser),
|
||||
entry!("ring_mod", "Ring Modulator", Modulation, RingMod),
|
||||
entry!("tremolo", "Tremolo", Modulation, Tremolo),
|
||||
entry!("vibrato", "Vibrato", Modulation, Vibrato),
|
||||
entry!("analog_delay", "Analog Delay", Time, AnalogDelay),
|
||||
entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay),
|
||||
entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb),
|
||||
@@ -148,6 +160,7 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover),
|
||||
entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer),
|
||||
entry!("distortion", "Distortion", Special, Distortion),
|
||||
entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher),
|
||||
entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite),
|
||||
entry!("mastering", "Mastering", Special, Mastering),
|
||||
entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer),
|
||||
|
||||
@@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() {
|
||||
f
|
||||
};
|
||||
let lat0 = (e.create)(SR, 2).latency();
|
||||
// Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency.
|
||||
let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 };
|
||||
let mut a = mk();
|
||||
let mut b = mk();
|
||||
assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id);
|
||||
assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id);
|
||||
let ya = run(a.as_mut(), &l, &r);
|
||||
let yb = run(b.as_mut(), &l, &r);
|
||||
assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id);
|
||||
@@ -147,7 +149,14 @@ fn latency_is_where_the_impulse_lands() {
|
||||
// settings (FFT filter / convolution / existing STFT effects). The click remover repairs a
|
||||
// lone impulse in silence as a click, so its latency is checked on noise by
|
||||
// `neutral_settings_are_delayed_identity`.
|
||||
for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)])] {
|
||||
for (id, p) in [
|
||||
("fft_filter", vec![]),
|
||||
("convolution_reverb", vec![("mix", 0.0)]),
|
||||
("voice_pitch", vec![]),
|
||||
("voice_pitch", vec![("formant_follow", 1.0)]),
|
||||
("voice_formant", vec![]),
|
||||
("noise_suppression", vec![("reduction", 0.0)]),
|
||||
] {
|
||||
let mut e = fx(id, &p);
|
||||
let lat = e.latency();
|
||||
assert!(lat > 0, "{id}");
|
||||
@@ -906,6 +915,8 @@ fn delays_and_reverbs_report_their_tails() {
|
||||
("chorus_flanger", &[("mode", 1.0), ("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]),
|
||||
("chorus_flanger", &[("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]),
|
||||
("flanger", &[("final_delay", 20.0), ("feedback", 100.0), ("mix", 100.0)][..]),
|
||||
("ring_mod", &[("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)][..]),
|
||||
("ring_mod", &[("effect", 3.0), ("frequency", 60.0), ("resonance", 95.0), ("mod_source", 1.0), ("mod_depth", 100.0)][..]),
|
||||
] {
|
||||
let mut e = fx(id, params);
|
||||
let tail = e.tail_samples();
|
||||
@@ -976,6 +987,13 @@ fn direct_constructors_cap_the_channel_count() {
|
||||
channel::Amplify,
|
||||
filters::FullParametricEq,
|
||||
pitch::PitchShifter,
|
||||
voice::VoicePitch,
|
||||
voice::VoiceFormant,
|
||||
suppress::NoiseSuppression,
|
||||
character::RingMod,
|
||||
character::Bitcrusher,
|
||||
character::Tremolo,
|
||||
character::Vibrato,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -402,7 +402,7 @@ mod tests {
|
||||
#[test]
|
||||
fn paired_effects_match_mono_on_transients() {
|
||||
use crate::AudioEffect;
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter};
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter};
|
||||
const SR: f32 = 48_000.0;
|
||||
let len = 48_000;
|
||||
let material = |f: f64, amp: f32, phase: f64, click_every: usize, click_at: usize, noise: f32, seed: u64| -> Vec<f32> {
|
||||
@@ -427,6 +427,7 @@ mod tests {
|
||||
"DeReverb" => Box::new(DeReverb::new(SR, ch)),
|
||||
"FftFilter" => Box::new(FftFilter::new(SR, ch)),
|
||||
"DeNoise" => Box::new(DeNoise::new(SR, ch)),
|
||||
"NoiseSuppression" => Box::new(NoiseSuppression::new(SR, ch)),
|
||||
_ => Box::new(PitchShifter::new(SR, ch)),
|
||||
};
|
||||
if name == "PitchShifter" {
|
||||
@@ -445,7 +446,7 @@ mod tests {
|
||||
y
|
||||
};
|
||||
let mut failures = Vec::new();
|
||||
for name in ["PitchShifter", "DeNoise", "DeReverb", "FftFilter"] {
|
||||
for name in ["PitchShifter", "DeNoise", "NoiseSuppression", "DeReverb", "FftFilter"] {
|
||||
for (label, src) in [("identical", &identical), ("different", &different)] {
|
||||
let joint = run(name, src);
|
||||
for (ch, chan) in src.iter().enumerate() {
|
||||
@@ -502,17 +503,18 @@ mod tests {
|
||||
#[test]
|
||||
fn non_finite_sample_stays_in_its_channel() {
|
||||
use crate::AudioEffect;
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter};
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter};
|
||||
const SR: f32 = 48_000.0;
|
||||
let len = 24_000;
|
||||
let mut rng = Rng::new(5);
|
||||
let clean_a: Vec<f32> = crate::testutil::sine(440.0, 0.4, SR as f64, len, 0.0).iter().map(|v| v + 0.05 * rng.uniform()).collect();
|
||||
let clean_b: Vec<f32> = crate::testutil::sine(1250.0, 0.4, SR as f64, len, 0.3).iter().map(|v| v + 0.05 * rng.uniform()).collect();
|
||||
type Make = fn() -> Box<dyn AudioEffect>;
|
||||
let make: [(&str, Make, usize); 4] = [
|
||||
let make: [(&str, Make, usize); 5] = [
|
||||
("DeReverb", || Box::new(DeReverb::new(SR, 2)), 1),
|
||||
("FftFilter", || Box::new(FftFilter::new(SR, 2)), 1),
|
||||
("DeNoise", || Box::new(DeNoise::new(SR, 2)), 1),
|
||||
("NoiseSuppression", || Box::new(NoiseSuppression::new(SR, 2)), 1),
|
||||
("PitchShifter", || Box::new(PitchShifter::new(SR, 2)), 1),
|
||||
];
|
||||
let mono = |name: &str, src: &[f32]| -> Vec<f32> {
|
||||
@@ -520,6 +522,7 @@ mod tests {
|
||||
"DeReverb" => Box::new(DeReverb::new(SR, 1)),
|
||||
"FftFilter" => Box::new(FftFilter::new(SR, 1)),
|
||||
"DeNoise" => Box::new(DeNoise::new(SR, 1)),
|
||||
"NoiseSuppression" => Box::new(NoiseSuppression::new(SR, 1)),
|
||||
_ => Box::new(PitchShifter::new(SR, 1)),
|
||||
};
|
||||
if name == "PitchShifter" {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -81,7 +81,14 @@ impl DelayLine {
|
||||
let i0 = self.w + len - 1 - di as usize;
|
||||
let i0 = if i0 >= len { i0 - len } else { i0 };
|
||||
let i1 = if i0 == 0 { len - 1 } else { i0 - 1 };
|
||||
self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac
|
||||
let (a, b) = (self.buf[i0], self.buf[i1]);
|
||||
let y = a + (b - a) * frac;
|
||||
if y.is_finite() {
|
||||
y
|
||||
} else {
|
||||
// Two large samples of opposite sign overflow `b - a` in f32.
|
||||
(a as f64 + (b as f64 - a as f64) * frac as f64) as f32
|
||||
}
|
||||
}
|
||||
/// Integer read (`d` samples ago, 0 = newest).
|
||||
#[inline]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -171,8 +171,10 @@ pub trait AudioEffect: Send {
|
||||
/// Parameter descriptions (same as the registry entry's).
|
||||
fn params(&self) -> &'static [ParamSpec];
|
||||
/// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids.
|
||||
/// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to
|
||||
/// the new value smoothly; the crate documentation lists which other parameters change at once.
|
||||
/// Updates the target immediately. Sample-based effects use the target from the next processed
|
||||
/// sample. Frame-based effects may apply it at the next frame callback while earlier output
|
||||
/// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the
|
||||
/// crate documentation lists which other parameters change at once.
|
||||
fn set_param(&mut self, id: &str, value: f32) -> bool;
|
||||
/// Current (target) value of a parameter.
|
||||
fn param(&self, id: &str) -> Option<f32>;
|
||||
@@ -182,7 +184,11 @@ pub trait AudioEffect: Send {
|
||||
/// Process one block in place. All channel slices must have the same length (the shortest
|
||||
/// length is used otherwise). Zero-length blocks are allowed.
|
||||
fn process(&mut self, channels: &mut [&mut [f32]]);
|
||||
/// Processing latency in samples (look-ahead / STFT delay) for delay compensation.
|
||||
/// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does
|
||||
/// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep
|
||||
/// Formants), which adds the formant stage's latency while it is on. The value changes as
|
||||
/// soon as the switch changes, while the output crossfades between the two delays over the
|
||||
/// next 20 ms, so during that fade the output does not match the reported latency.
|
||||
fn latency(&self) -> usize {
|
||||
0
|
||||
}
|
||||
@@ -197,7 +203,13 @@ pub trait AudioEffect: Send {
|
||||
None
|
||||
}
|
||||
/// How long the output keeps sounding after the input stops, in samples (reverb and delay
|
||||
/// tails), so an offline render can run past the end of its input.
|
||||
/// tails), so an offline render can run past the end of its input. The count starts after
|
||||
/// the latency: a render that keeps the tail runs `latency() + tail_samples()` samples past
|
||||
/// the end of its input. An effect whose output decays without reaching zero (a feedback
|
||||
/// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start
|
||||
/// for the feedback delays and resonators, so quieter output can still follow that point.
|
||||
/// Those effects also cap the tail they report at 60 s, which is what a feedback of 1 or more
|
||||
/// reports.
|
||||
fn tail_samples(&self) -> usize {
|
||||
0
|
||||
}
|
||||
@@ -460,6 +472,37 @@ pub(crate) mod testutil {
|
||||
}
|
||||
}
|
||||
|
||||
/// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope),
|
||||
/// noise bursts (consonants) and pauses.
|
||||
pub fn speechy(sr: f64, secs: f64, seed: u64) -> Vec<f32> {
|
||||
let n = (sr * secs) as usize;
|
||||
let mut rng = Rng::new(seed);
|
||||
let mut out = vec![0.0f32; n];
|
||||
let mut i = 0usize;
|
||||
while i < n {
|
||||
let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize;
|
||||
let kind = rng.uniform();
|
||||
let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5);
|
||||
let glide = 1.0 + 0.3 * rng.uniform() as f64;
|
||||
let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5);
|
||||
for k in 0..len.min(n - i) {
|
||||
let t = k as f64 / sr;
|
||||
let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32;
|
||||
let v = if kind > 0.3 {
|
||||
let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64);
|
||||
(1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::<f32>()
|
||||
} else if kind > -0.4 {
|
||||
rng.uniform()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
out[i + k] = v * env * amp;
|
||||
}
|
||||
i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec<f32> {
|
||||
(0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect()
|
||||
}
|
||||
|
||||
@@ -354,38 +354,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) -
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::Rng;
|
||||
|
||||
/// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope),
|
||||
/// noise bursts (consonants) and pauses.
|
||||
fn speechy(sr: f64, secs: f64, seed: u64) -> Vec<f32> {
|
||||
let n = (sr * secs) as usize;
|
||||
let mut rng = Rng::new(seed);
|
||||
let mut out = vec![0.0f32; n];
|
||||
let mut i = 0usize;
|
||||
while i < n {
|
||||
let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize;
|
||||
let kind = rng.uniform();
|
||||
let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5);
|
||||
let glide = 1.0 + 0.3 * rng.uniform() as f64;
|
||||
let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5);
|
||||
for k in 0..len.min(n - i) {
|
||||
let t = k as f64 / sr;
|
||||
let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32;
|
||||
let v = if kind > 0.3 {
|
||||
let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64);
|
||||
(1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::<f32>()
|
||||
} else if kind > -0.4 {
|
||||
rng.uniform()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
out[i + k] = v * env * amp;
|
||||
}
|
||||
i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize;
|
||||
}
|
||||
out
|
||||
}
|
||||
use crate::testutil::{Rng, speechy};
|
||||
|
||||
/// `x` delayed by `delay` samples (fractional: windowed-sinc interpolation), scaled by `gain`,
|
||||
/// optionally colored by a zero-phase low-pass (`[k, 1-2k, k]`, so the delay stays exact), with
|
||||
|
||||
@@ -24,7 +24,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-
|
||||
# The symphonia fallback for the formats with no native decoder yet.
|
||||
symphonia = ["decode-native", "dep:symphonia"]
|
||||
# Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders.
|
||||
# All but Opus are also file formats of `encode` and `FileEncoder`.
|
||||
# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`.
|
||||
encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"]
|
||||
# Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files.
|
||||
lossless-encode = ["pcm-encode", "flac-encode"]
|
||||
@@ -44,6 +44,8 @@ aac-decode = ["craft-media/bitstream"]
|
||||
# The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`.
|
||||
aac-encode = ["craft-media/bitstream", "craft-media/isobmff"]
|
||||
opus-decode = []
|
||||
# SMPTE ST 302M (AES3 audio in MPEG-2 transport streams): packet decoder and encoder.
|
||||
s302m = []
|
||||
# ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders.
|
||||
adpcm = ["craft-media/bitstream"]
|
||||
# QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own.
|
||||
@@ -54,6 +56,7 @@ qoa-encode = []
|
||||
g722 = []
|
||||
# ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s).
|
||||
g726 = []
|
||||
# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`.
|
||||
opus-encode = []
|
||||
# GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own.
|
||||
gsm = ["gsm-decode", "gsm-encode"]
|
||||
|
||||
+110
-13
@@ -31,22 +31,23 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
|
||||
| `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia |
|
||||
| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` |
|
||||
| `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` |
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `repair_wav` (size fields of a WAV left unfinished by a crash); `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none |
|
||||
| `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
| `alac-decode` | `alac::Decoder` | none |
|
||||
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` |
|
||||
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none |
|
||||
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` |
|
||||
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | none |
|
||||
| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` |
|
||||
| `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` |
|
||||
| `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` |
|
||||
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` |
|
||||
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` |
|
||||
| `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` |
|
||||
| `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` |
|
||||
| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` |
|
||||
| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` |
|
||||
| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` |
|
||||
| `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` |
|
||||
| `s302m` | `s302m::{decode, Encoder}`: SMPTE ST 302M packets (AES3 audio in MPEG-2 transport streams), 2 to 8 channels of 16, 20 or 24 bits | none |
|
||||
| `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none |
|
||||
| `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none |
|
||||
| `peaks` | `peaks::Peaks` | none |
|
||||
@@ -214,9 +215,13 @@ packet. Opus with empty `extradata` and 1 or 2 channels (RTP, MPEG-TS) needs no
|
||||
To seek: position your demuxer at the packet that starts `preroll()` frames or more before the
|
||||
target, call `reset()`, decode from there, and drop the output before the target.
|
||||
|
||||
The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the
|
||||
codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to
|
||||
WAV order. `ac3::Decoder` and `mpa::Decoder` output WAV order.
|
||||
The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and
|
||||
`vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`,
|
||||
`opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and
|
||||
`vorbis::layout(channels)` gives the speakers of the result. `opus::wav_order` applies only to
|
||||
mapping family 1. Family 0 is mono or stereo, which is already in WAV order. For other families,
|
||||
`TrackDecoder` assigns no conventional speaker mapping and leaves channels in stream order.
|
||||
`ac3::Decoder` and `mpa::Decoder` output WAV order.
|
||||
|
||||
### Encode a file
|
||||
|
||||
@@ -311,12 +316,76 @@ file needs that step before it is written again.
|
||||
|
||||
An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame
|
||||
written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no
|
||||
place for that (see [Limits](#limits)). For a container of your own, use the codec modules below.
|
||||
place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below.
|
||||
|
||||
### Encode packets for your own container
|
||||
|
||||
`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC,
|
||||
ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export
|
||||
to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded
|
||||
formats through it.
|
||||
|
||||
```rust
|
||||
use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder};
|
||||
|
||||
let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000);
|
||||
let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?;
|
||||
for block in blocks { // planar f32 in WAV order, any length
|
||||
for p in enc.encode(&block.channels, block.frames())? {
|
||||
mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate
|
||||
}
|
||||
}
|
||||
for p in enc.finish()? {
|
||||
mux.write(p.pts, p.duration, &p.data)?;
|
||||
}
|
||||
let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes
|
||||
let priming = enc.priming(); // decoded samples before the first input frame
|
||||
let padding = enc.padding(); // decoded samples after the last one
|
||||
```
|
||||
|
||||
It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC
|
||||
`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will
|
||||
do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the
|
||||
channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth.
|
||||
`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count
|
||||
(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose.
|
||||
|
||||
| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` |
|
||||
|---|---|---|---|---|
|
||||
| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 |
|
||||
| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 |
|
||||
| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 |
|
||||
| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 |
|
||||
| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip |
|
||||
|
||||
The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name;
|
||||
Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec
|
||||
with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take
|
||||
get the error `EncodeOptions::check` gives for the format.
|
||||
|
||||
Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample,
|
||||
so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder
|
||||
returns every input frame, and the durations add up to `priming() + frames() + padding()`. With no
|
||||
input there are no packets: the durations add up to 0 and `padding()` is 0, while `priming()` still
|
||||
reports the codec's delay. A muxer
|
||||
skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus:
|
||||
the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit,
|
||||
Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit
|
||||
rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by
|
||||
quality); `bit_depth()` is ALAC's.
|
||||
|
||||
`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`,
|
||||
and encodes nothing; the encoder stays usable, so the caller can correct the block and call again.
|
||||
After `finish`, or after encoding itself failed (the block's packets are lost), every call returns
|
||||
an error.
|
||||
E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see
|
||||
[Limits](#limits)).
|
||||
|
||||
### Encode AAC packets
|
||||
|
||||
For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it,
|
||||
for muxing into a container of your own:
|
||||
For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order,
|
||||
`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings
|
||||
`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS):
|
||||
|
||||
```rust
|
||||
use craft_audio::AudioError;
|
||||
@@ -573,7 +642,35 @@ Each codec module's rustdoc lists the coding tools it implements.
|
||||
| MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches |
|
||||
| MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) |
|
||||
| MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode |
|
||||
| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways |
|
||||
| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways |
|
||||
|
||||
### ALAC encoding
|
||||
|
||||
Apple's reference encoder stores the low byte (24-bit) or low two bytes (32-bit) of every sample
|
||||
uncompressed. This encoder shifts off fewer bytes, per element and per packet, when the samples
|
||||
allow it: at 24 bits a packet that peaks below −54 dBFS keeps no uncompressed byte; at 32 bits one
|
||||
below −54 dBFS keeps one, and a mono or LFE element below −102 dBFS none (a 32-bit pair always keeps
|
||||
one). Other packets are the same as the reference's, and decoders need no change.
|
||||
|
||||
Stream sizes in MB (10⁶ bytes) for 4 minutes at 48 kHz in 4096-frame packets. "Reference" is this
|
||||
encoder with the reference's fixed shift; Apple's `afconvert` gives the same sizes for the 24-bit stereo rows. The
|
||||
music is synthetic (decaying harmonic notes over a noise floor, peaking at −3 dBFS); a stem plays
|
||||
5 or 10 seconds in every 20.
|
||||
|
||||
| Material | Depth / ch | PCM | Reference | This encoder | Saved |
|
||||
|---|---|---|---|---|---|
|
||||
| Music throughout | 24 / 2 | 69.1 | 45.5 | 45.5 | 0% |
|
||||
| Music, 2 s of digital silence at each end | 24 / 2 | 69.1 | 45.1 | 44.7 | 0.8% |
|
||||
| Stem playing half the time, digital silence between | 24 / 2 | 69.1 | 34.3 | 22.8 | 33% |
|
||||
| Stem playing a quarter of the time, digital silence between | 24 / 2 | 69.1 | 28.7 | 11.5 | 60% |
|
||||
| The same, noise at −110 dBFS in place of silence | 24 / 2 | 69.1 | 32.6 | 25.1 | 23% |
|
||||
| Quiet music, peaking at −60 dBFS | 24 / 2 | 69.1 | 27.7 | 20.1 | 27% |
|
||||
| Digital silence | 24 / 2 | 69.1 | 23.1 | 0.09 | 99.6% |
|
||||
| 5.1: music in front, surrounds a quarter of the time, silent LFE | 24 / 6 | 207.4 | 108.7 | 79.9 | 26% |
|
||||
| Stem playing a quarter of the time, digital silence between | 32 / 1 | 46.1 | 25.9 | 8.7 | 66% |
|
||||
| Stem playing a quarter of the time, digital silence between | 32 / 2 | 92.2 | 51.7 | 34.5 | 33% |
|
||||
| Quiet music, peaking at −60 dBFS | 32 / 2 | 92.2 | 50.7 | 43.2 | 15% |
|
||||
| Digital silence | 32 / 2 | 92.2 | 46.2 | 23.1 | 50% |
|
||||
|
||||
### MP3 encoding
|
||||
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
//!
|
||||
//! The search (stereo matrixing, 4 or 8 predictor coefficients) and the state kept across
|
||||
//! packets (coefficients, the last matrixing, and the buffers the trial runs read stale parts of)
|
||||
//! follow the reference, so for the same input this writes the same packets as it.
|
||||
//! follow the reference, so for the same input this writes the same packets as it, with one
|
||||
//! exception: the shifted-off low bytes. The reference passes 1 (24-bit) or 2 (32-bit) low bytes
|
||||
//! of every sample through uncompressed, even for silence. Here an element shifts off fewer bytes
|
||||
//! in a packet whose samples fit well within the width the reference predicts (see
|
||||
//! [`packet_shift`]), so silence and quiet passages are not padded with a byte or two per sample.
|
||||
|
||||
use super::ag::{self, AgParams};
|
||||
use super::bits::{BitCounter, BitSink, BitWriter};
|
||||
@@ -100,6 +104,25 @@ fn bytes_shifted(bit_depth: u32) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes an element shifts off in one packet: the fewest, down from the reference's
|
||||
/// [`bytes_shifted`], that leave every sample at least one bit narrower than the width the
|
||||
/// reference predicts (`bit_depth − 8 · bytes_shifted`). The predictor then works on values no
|
||||
/// wider than in the reference, so its arithmetic stays in the same range; only fewer low bytes go
|
||||
/// out uncompressed. The spare bit is there because at the full width, coding the low byte through
|
||||
/// the predictor costs about as much as storing it, and for 24-bit mono measured 2% more.
|
||||
/// A 32-bit pair keeps at least 1: with none, its prediction width (33 bits) exceeds the 32 the
|
||||
/// format allows.
|
||||
fn packet_shift(bit_depth: u32, channels: &[&[i32]]) -> u32 {
|
||||
let reference = bytes_shifted(bit_depth);
|
||||
let width = bit_depth - reference * 8 - 1;
|
||||
let floor = u32::from(bit_depth == 32 && channels.len() == 2);
|
||||
let fits = |bytes: u32| {
|
||||
let (lo, hi) = (-(1i64 << (width - 1)), (1i64 << (width - 1)) - 1);
|
||||
channels.iter().flat_map(|c| c.iter()).all(|&x| (lo..=hi).contains(&i64::from(x >> (bytes * 8))))
|
||||
};
|
||||
(floor..reference).find(|&b| fits(b)).unwrap_or(reference)
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
/// An encoder for `cfg`.
|
||||
pub fn new(cfg: EncoderConfig) -> Result<Self> {
|
||||
@@ -191,11 +214,12 @@ impl Encoder {
|
||||
w.put(cpe_tag, 4);
|
||||
cpe_tag += 1;
|
||||
let (l, r) = (channels[index], channels[index + 1]);
|
||||
let bs = packet_shift(self.bit_depth, &[l, r]);
|
||||
// as in the reference, fast mode applies to stereo streams only
|
||||
if self.cfg.fast && channels.len() == 2 {
|
||||
self.encode_stereo_fast(&mut w, index, l, r)?;
|
||||
self.encode_stereo_fast(&mut w, index, l, r, bs)?;
|
||||
} else {
|
||||
self.encode_stereo(&mut w, index, l, r)?;
|
||||
self.encode_stereo(&mut w, index, l, r, bs)?;
|
||||
}
|
||||
index += 2;
|
||||
}
|
||||
@@ -203,7 +227,8 @@ impl Encoder {
|
||||
let tag = if element == ID_LFE { &mut lfe_tag } else { &mut sce_tag };
|
||||
w.put(*tag, 4);
|
||||
*tag += 1;
|
||||
self.encode_mono(&mut w, index, channels[index])?;
|
||||
let bs = packet_shift(self.bit_depth, &[channels[index]]);
|
||||
self.encode_mono(&mut w, index, channels[index], bs)?;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
@@ -231,10 +256,10 @@ impl Encoder {
|
||||
}
|
||||
|
||||
/// `EncodeStereo`: a channel pair with the matrixing and coefficient search.
|
||||
fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> {
|
||||
/// `bs`: the bytes shifted off, from [`packet_shift`].
|
||||
fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> {
|
||||
let start = w.bit_len();
|
||||
let n = l.len();
|
||||
let bs = bytes_shifted(self.bit_depth);
|
||||
let chan_bits = self.bit_depth - bs * 8 + 1;
|
||||
let partial = self.partial(n);
|
||||
let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0);
|
||||
@@ -329,10 +354,9 @@ impl Encoder {
|
||||
}
|
||||
|
||||
/// `EncodeStereoFast`: a channel pair without matrixing or search.
|
||||
fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> {
|
||||
fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> {
|
||||
let start = w.bit_len();
|
||||
let n = l.len();
|
||||
let bs = bytes_shifted(self.bit_depth);
|
||||
let chan_bits = self.bit_depth - bs * 8 + 1;
|
||||
let partial = self.partial(n);
|
||||
let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0);
|
||||
@@ -396,10 +420,9 @@ impl Encoder {
|
||||
}
|
||||
|
||||
/// `EncodeMono`: one channel (SCE or LFE).
|
||||
fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32]) -> Result<()> {
|
||||
fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32], bs: u32) -> Result<()> {
|
||||
let start = w.bit_len();
|
||||
let n = input.len();
|
||||
let bs = bytes_shifted(self.bit_depth);
|
||||
let shift = bs * 8;
|
||||
let chan_bits = self.bit_depth - shift;
|
||||
let partial = self.partial(n);
|
||||
@@ -563,4 +586,84 @@ mod tests {
|
||||
let mut dec = Decoder::new(&enc.cookie()).unwrap();
|
||||
assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]);
|
||||
}
|
||||
|
||||
/// One packet of `frames` frames per element, encoded and decoded back; its size in bytes.
|
||||
fn packet_bytes(cfg: EncoderConfig, input: &[Vec<i32>]) -> usize {
|
||||
let mut enc = Encoder::new(cfg).unwrap();
|
||||
let chunk: Vec<&[i32]> = input.iter().map(Vec::as_slice).collect();
|
||||
let p = enc.encode(&chunk).unwrap();
|
||||
let mut dec = Decoder::new(&enc.cookie()).unwrap();
|
||||
assert_eq!(dec.decode(&p).unwrap(), input, "{cfg:?}");
|
||||
p.len()
|
||||
}
|
||||
|
||||
/// The reference shifts 1 (24-bit) or 2 (32-bit) low bytes of every sample off and stores them
|
||||
/// uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes (#1368).
|
||||
#[test]
|
||||
fn silence_is_a_few_bytes_at_every_depth() {
|
||||
for bits in [16, 20, 24, 32] {
|
||||
for ch in [1, 2, 6] {
|
||||
for fast in [false, true] {
|
||||
let cfg = EncoderConfig::new(48_000, ch, bits).with_fast(fast);
|
||||
let bytes = packet_bytes(cfg, &vec![vec![0; 4096]; usize::from(ch)]);
|
||||
// a 32-bit pair keeps one shifted byte per sample: the format allows no less
|
||||
let floor = if bits == 32 { 4096 * 2 * (usize::from(ch) / 2) } else { 0 };
|
||||
assert!(bytes <= floor + 40 * usize::from(ch), "{bits} bits, {ch} ch, fast {fast}: {bytes} bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quiet audio (within 12 bits) at 24 and 32 bits shifts nothing off and comes within 10% of
|
||||
/// the same audio at 16 bits (the wider prediction width makes the coder's escapes longer);
|
||||
/// the reference stored a byte or two more per sample. Samples at the edges of each width and
|
||||
/// loud audio decode exactly.
|
||||
#[test]
|
||||
fn quiet_packets_compress_like_16_bit_audio_and_loud_ones_round_trip() {
|
||||
let quiet = signal(4096, 2, 12);
|
||||
let at16 = packet_bytes(EncoderConfig::new(48_000, 2, 16), &quiet);
|
||||
let at24 = packet_bytes(EncoderConfig::new(48_000, 2, 24), &quiet);
|
||||
assert!(at24 * 10 <= at16 * 11, "24-bit {at24} bytes, 16-bit {at16}");
|
||||
let mono = vec![quiet[0].clone()];
|
||||
let at16 = packet_bytes(EncoderConfig::new(48_000, 1, 16), &mono);
|
||||
let at32 = packet_bytes(EncoderConfig::new(48_000, 1, 32), &mono);
|
||||
assert!(at32 * 10 <= at16 * 11, "32-bit mono {at32} bytes, 16-bit {at16}");
|
||||
// the samples just past each narrower width, and loud audio, decode exactly
|
||||
for bits in [24u32, 32] {
|
||||
for ch in [1u8, 2] {
|
||||
let edge: Vec<Vec<i32>> = (0..ch)
|
||||
.map(|c| {
|
||||
(0..4096)
|
||||
.map(|i| match (i + usize::from(c)) % 4 {
|
||||
0 => (16_384 << (bits - 24)) - 1,
|
||||
1 => -(16_384 << (bits - 24)),
|
||||
2 => 16_384 << (bits - 24),
|
||||
_ => -(16_384 << (bits - 24)) - 1,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &edge);
|
||||
packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &signal(4096, usize::from(ch), bits));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shift_is_the_fewest_bytes_that_keep_the_reference_width() {
|
||||
let z = [0i32; 4];
|
||||
assert_eq!(packet_shift(16, &[&z]), 0);
|
||||
assert_eq!(packet_shift(24, &[&z, &z]), 0);
|
||||
assert_eq!(packet_shift(24, &[&[16_383, -16_384], &z]), 0);
|
||||
assert_eq!(packet_shift(24, &[&[16_384], &z]), 1);
|
||||
assert_eq!(packet_shift(24, &[&[-16_385]]), 1);
|
||||
assert_eq!(packet_shift(24, &[&[32_767]]), 1);
|
||||
assert_eq!(packet_shift(32, &[&z]), 0);
|
||||
assert_eq!(packet_shift(32, &[&[16_383]]), 0);
|
||||
assert_eq!(packet_shift(32, &[&z, &z]), 1);
|
||||
assert_eq!(packet_shift(32, &[&[1 << 21]]), 1);
|
||||
assert_eq!(packet_shift(32, &[&[1 << 22]]), 2);
|
||||
assert_eq!(packet_shift(32, &[&[i32::MIN]]), 2);
|
||||
assert_eq!(packet_shift(32, &[&[i32::MAX], &z]), 2);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,9 @@
|
||||
//! reference: hostile input returns errors instead of reading or writing out of bounds, integer
|
||||
//! arithmetic wraps where C would overflow, the 4- and 8-tap predictor loops are folded into the
|
||||
//! general one (same values), the sample-width variants of the matrix routines into one routine
|
||||
//! over `i32`, and the encoder fills in the cookie's average bit rate.
|
||||
//! over `i32`, the encoder fills in the cookie's average bit rate, and it shifts off fewer low
|
||||
//! bytes in packets whose samples fit a narrower width (silence and quiet passages at 24 and 32
|
||||
//! bits), where the reference always passes them through uncompressed.
|
||||
|
||||
// The bit I/O, coder, predictor and matrix modules serve both halves; with only one of
|
||||
// `alac-decode` and `alac-encode` built, the other half's routines are unused.
|
||||
|
||||
+30
-6
@@ -19,10 +19,13 @@
|
||||
//! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar
|
||||
//! `f32` in WAV channel order.
|
||||
//! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also
|
||||
//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A
|
||||
//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] and [`repair_wav`]), FLAC (feature
|
||||
//! `flac-encode`), AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3
|
||||
//! streams (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder.
|
||||
//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC,
|
||||
//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer.
|
||||
//! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`],
|
||||
//! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF
|
||||
//! file bit for bit, and minimal files around such PCM, for essence embedded in other containers.
|
||||
@@ -32,7 +35,8 @@
|
||||
//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`]
|
||||
//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder;
|
||||
//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`]
|
||||
//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM),
|
||||
//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`s302m`] (`s302m`: SMPTE 302M packets),
|
||||
//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM),
|
||||
//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`:
|
||||
//! Sierra VMD sound).
|
||||
//!
|
||||
@@ -64,6 +68,15 @@ pub mod mp3;
|
||||
pub mod mpa;
|
||||
#[cfg(any(feature = "opus-decode", feature = "opus-encode"))]
|
||||
pub mod opus;
|
||||
#[cfg(any(
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode",
|
||||
feature = "opus-encode"
|
||||
))]
|
||||
mod packet;
|
||||
#[cfg(any(
|
||||
feature = "aac-decode",
|
||||
feature = "alac-decode",
|
||||
@@ -79,6 +92,8 @@ pub mod peaks;
|
||||
pub mod qoa;
|
||||
#[cfg(feature = "decode-native")]
|
||||
mod read;
|
||||
#[cfg(feature = "s302m")]
|
||||
pub mod s302m;
|
||||
#[cfg(feature = "sbc")]
|
||||
pub mod sbc;
|
||||
#[cfg(any(
|
||||
@@ -157,6 +172,15 @@ pub use buffer::AudioBuffer;
|
||||
pub use craft_media;
|
||||
pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource};
|
||||
pub use layout::{ChannelLayout, Speaker};
|
||||
#[cfg(any(
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode",
|
||||
feature = "opus-encode"
|
||||
))]
|
||||
pub use packet::{EncodedPacket, PacketEncoder};
|
||||
#[cfg(feature = "decode-native")]
|
||||
pub use read::SharedSource;
|
||||
#[cfg(feature = "decode-native")]
|
||||
@@ -185,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder};
|
||||
feature = "eac3-encode"
|
||||
))]
|
||||
pub use write::FileEncoder;
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::wav_float_header;
|
||||
#[cfg(any(
|
||||
feature = "pcm-encode",
|
||||
feature = "flac-encode",
|
||||
@@ -199,6 +221,8 @@ pub use write::wav_float_header;
|
||||
))]
|
||||
pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for};
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf};
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header};
|
||||
|
||||
/// Errors from probing, decoding and encoding.
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for
|
||||
//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order,
|
||||
//! maps the channels onto the codec's order, and returns packets with their timing; the coded
|
||||
//! formats of [`FileEncoder`](crate::FileEncoder) are written through it.
|
||||
|
||||
// Each codec is its own feature: with only some of them built, the other halves of the shared
|
||||
// code are unused.
|
||||
#![cfg_attr(
|
||||
not(all(
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode",
|
||||
feature = "opus-encode"
|
||||
)),
|
||||
allow(dead_code, unused_imports, unused_variables, unused_mut)
|
||||
)]
|
||||
|
||||
use crate::layout::channel_map;
|
||||
use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result};
|
||||
|
||||
/// Maximum frames handed to a codec per internal call, bounding that call's input and output.
|
||||
/// `PacketEncoder::encode` collects packets across all chunks, so its returned vector grows with
|
||||
/// the caller's input block. Also the frames of an ALAC packet.
|
||||
pub(crate) const CHUNK: usize = 4096;
|
||||
|
||||
/// Bits per second per channel when no rate is asked for: AAC and Opus.
|
||||
const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
|
||||
const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
|
||||
/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per
|
||||
/// full-bandwidth channel).
|
||||
const DEFAULT_KBPS_PER_CHANNEL: u32 = 96;
|
||||
|
||||
/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R).
|
||||
const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]];
|
||||
|
||||
/// One packet from a [`PacketEncoder`].
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EncodedPacket {
|
||||
/// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame,
|
||||
/// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet.
|
||||
pub data: Vec<u8>,
|
||||
/// Where the packet's decoded audio starts, in samples at the sample rate from the first
|
||||
/// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first,
|
||||
/// so input frame `n` is at `n + priming`.
|
||||
pub pts: u64,
|
||||
/// The samples per channel the packet decodes to, the last packet's padding included.
|
||||
pub duration: u32,
|
||||
}
|
||||
|
||||
/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side
|
||||
/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the
|
||||
/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control,
|
||||
/// the layout, and for ALAC the bit depth and dither.
|
||||
///
|
||||
/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets
|
||||
/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container
|
||||
/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec,
|
||||
/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout),
|
||||
/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding).
|
||||
///
|
||||
/// | Codec | Feature | Packet | `extradata` | Priming |
|
||||
/// |---|---|---|---|---|
|
||||
/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 |
|
||||
/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 |
|
||||
/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 |
|
||||
/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 |
|
||||
/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip |
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] {
|
||||
/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder};
|
||||
///
|
||||
/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000);
|
||||
/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?;
|
||||
/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel
|
||||
/// let mut packets = enc.encode(&block, 4800)?;
|
||||
/// packets.extend(enc.finish()?);
|
||||
/// assert_eq!(enc.priming(), 1024);
|
||||
/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::<u64>(), 1024 + 4800 + enc.padding());
|
||||
///
|
||||
/// // The description a muxer writes is what a decoder reads.
|
||||
/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?;
|
||||
/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024);
|
||||
/// # }
|
||||
/// # Ok::<(), craft_audio::AudioError>(())
|
||||
/// ```
|
||||
pub struct PacketEncoder {
|
||||
codec: CodecId,
|
||||
inner: Inner,
|
||||
sample_rate: u32,
|
||||
/// The speakers of the channels encoded, in WAV order.
|
||||
layout: ChannelLayout,
|
||||
/// For each codec channel, the caller's channel that feeds it.
|
||||
map: Vec<usize>,
|
||||
bitrate: Option<u32>,
|
||||
/// The integer depth of a lossless codec.
|
||||
bit_depth: Option<u8>,
|
||||
/// Where the next packet starts.
|
||||
pts: u64,
|
||||
/// Frames of input taken.
|
||||
frames: u64,
|
||||
finished: bool,
|
||||
/// Set when a call failed: the packets of that block are lost, so the stream has a gap and
|
||||
/// every later call is refused.
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PacketEncoder {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PacketEncoder")
|
||||
.field("codec", &self.codec)
|
||||
.field("sample_rate", &self.sample_rate)
|
||||
.field("layout", &self.layout)
|
||||
.field("frames", &self.frames)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order.
|
||||
enum Inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Aac(Box<crate::aac::Encoder>),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Alac {
|
||||
enc: Box<crate::alac::Encoder>,
|
||||
quantizers: Vec<crate::write::pcm::Quantizer>,
|
||||
/// Quantized samples of the packet being filled, per channel.
|
||||
pending: Vec<Vec<i32>>,
|
||||
},
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Mp3 {
|
||||
enc: Box<crate::mp3::Encoder>,
|
||||
/// Bytes the encoder returned that do not yet make a whole frame.
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Ac3 {
|
||||
enc: Box<crate::ac3::encoder::Encoder>,
|
||||
/// The block with every sample finite and within ±1, as the encoder requires.
|
||||
planes: Vec<Vec<f32>>,
|
||||
},
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Opus {
|
||||
enc: Box<crate::opus::encoder::Encoder>,
|
||||
/// Interleaved samples of the frame being filled.
|
||||
pending: Vec<f32>,
|
||||
/// Frames of the decoded stream the packets so far cover.
|
||||
coded: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`.
|
||||
fn labels(mask: u32) -> String {
|
||||
ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// The speakers of the caller's layout, for an error message.
|
||||
fn given(layout: &ChannelLayout) -> String {
|
||||
layout.mask().map_or_else(|| "without speaker assignment".into(), labels)
|
||||
}
|
||||
|
||||
/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and
|
||||
/// that layout; or why the audio does not fit.
|
||||
fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec<usize>, ChannelLayout)> {
|
||||
let Some(&mask) = masks.first() else {
|
||||
return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels())));
|
||||
};
|
||||
let map = channel_map(mask, order, layout).ok_or_else(|| {
|
||||
AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout)))
|
||||
})?;
|
||||
Ok((map, ChannelLayout::from_mask(mask)))
|
||||
}
|
||||
|
||||
/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for
|
||||
/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> {
|
||||
if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) }
|
||||
}
|
||||
|
||||
/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256
|
||||
/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a
|
||||
/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s).
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_floor_per_channel(sample_rate: u32) -> u32 {
|
||||
(sample_rate / 4).max(6000)
|
||||
}
|
||||
|
||||
/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a
|
||||
/// quality of 0–1 spans the encoder's VBR range.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
pub(super) fn aac_mode(rate: Option<RateControl>, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode {
|
||||
use crate::aac::BitrateMode;
|
||||
let (lo, hi) = crate::aac::cbr_range(sample_rate, channels);
|
||||
let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo));
|
||||
// An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone.
|
||||
let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps };
|
||||
match rate {
|
||||
None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))),
|
||||
Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)),
|
||||
// NaN stays NaN, which the encoder refuses.
|
||||
Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit rate in bits per second for a codec with constant bit rates only.
|
||||
fn constant_bps(name: &str, rate: Option<RateControl>, default: u32) -> Result<u32> {
|
||||
match rate {
|
||||
None => Ok(default),
|
||||
Some(RateControl::Bitrate(bps)) => Ok(bps),
|
||||
Some(RateControl::Quality(_)) => {
|
||||
Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding
|
||||
/// mode whose speakers the layout names, at the nearest bit rate the stream can carry.
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
pub(super) fn ac3_config(
|
||||
codec: crate::ac3::encoder::Codec,
|
||||
sample_rate: u32,
|
||||
layout: &ChannelLayout,
|
||||
rate: Option<RateControl>,
|
||||
) -> Result<(crate::ac3::encoder::Config, Vec<usize>)> {
|
||||
use crate::ac3::encoder::{Codec, CodingMode, Config};
|
||||
use CodingMode::*;
|
||||
let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" };
|
||||
let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71];
|
||||
let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| {
|
||||
// 7.1 is an E-AC-3 programme with an LFE; the encoder has no other.
|
||||
if mode == Surround71 && (codec != Codec::Eac3 || !lfe) {
|
||||
return None;
|
||||
}
|
||||
let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe };
|
||||
let map = channel_map(config.channel_layout().mask()?, None, layout)?;
|
||||
Some((config, map))
|
||||
});
|
||||
let Some((mut config, map)) = found else {
|
||||
return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout))));
|
||||
};
|
||||
let full = config.mode.channels() as u32;
|
||||
let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000;
|
||||
// What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of
|
||||
// the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold.
|
||||
let least = if config.mode == Surround71 { 384 } else { 32 * full };
|
||||
config.bitrate_kbps = match codec {
|
||||
Codec::Ac3 => {
|
||||
let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least);
|
||||
crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor)
|
||||
}
|
||||
Codec::Eac3 => {
|
||||
let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 };
|
||||
want.clamp(least, most.max(least))
|
||||
}
|
||||
};
|
||||
Ok((config, map))
|
||||
}
|
||||
|
||||
/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here.
|
||||
fn feature(codec: CodecId) -> Option<&'static str> {
|
||||
Some(match codec {
|
||||
CodecId::Aac => "aac-encode",
|
||||
CodecId::Alac => "alac-encode",
|
||||
CodecId::Mp3 => "mp3-encode",
|
||||
CodecId::Ac3 => "ac3-encode",
|
||||
CodecId::Eac3 => "eac3-encode",
|
||||
CodecId::Opus => "opus-encode",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl PacketEncoder {
|
||||
/// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads
|
||||
/// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of
|
||||
/// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and
|
||||
/// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored.
|
||||
///
|
||||
/// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none
|
||||
/// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has
|
||||
/// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A
|
||||
/// rate, channel count, layout or rate control the codec cannot take is refused with the error
|
||||
/// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control).
|
||||
pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result<PacketEncoder> {
|
||||
let Some(feature) = feature(codec) else {
|
||||
return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name())));
|
||||
};
|
||||
let built = [
|
||||
(CodecId::Aac, cfg!(feature = "aac-encode")),
|
||||
(CodecId::Alac, cfg!(feature = "alac-encode")),
|
||||
(CodecId::Mp3, cfg!(feature = "mp3-encode")),
|
||||
(CodecId::Ac3, cfg!(feature = "ac3-encode")),
|
||||
(CodecId::Eac3, cfg!(feature = "eac3-encode")),
|
||||
(CodecId::Opus, cfg!(feature = "opus-encode")),
|
||||
];
|
||||
if !built.contains(&(codec, true)) {
|
||||
return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name())));
|
||||
}
|
||||
let n = usize::from(channels);
|
||||
// As the file writers word it.
|
||||
if channels == 0 {
|
||||
return Err(AudioError::Encode("buffer has no channels".into()));
|
||||
}
|
||||
if sample_rate == 0 {
|
||||
return Err(AudioError::Encode("sample rate is 0".into()));
|
||||
}
|
||||
if let Some(layout) = &opts.layout
|
||||
&& layout.channels() != channels
|
||||
{
|
||||
return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels())));
|
||||
}
|
||||
let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels));
|
||||
let (inner, map, layout, bitrate, bit_depth) = match codec {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
CodecId::Aac => {
|
||||
let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?;
|
||||
let mode = aac_mode(opts.rate_control, sample_rate, n);
|
||||
let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) };
|
||||
let bitrate = match mode {
|
||||
crate::aac::BitrateMode::Cbr(bps) => Some(bps),
|
||||
crate::aac::BitrateMode::Vbr(_) => None,
|
||||
};
|
||||
(Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None)
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
CodecId::Alac => {
|
||||
let count = u8::try_from(channels).unwrap_or(u8::MAX);
|
||||
let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?;
|
||||
let bits = match opts.bit_depth {
|
||||
crate::BitDepth::Int16 => 16,
|
||||
crate::BitDepth::Int24 => 24,
|
||||
crate::BitDepth::Int32 => 32,
|
||||
crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())),
|
||||
};
|
||||
let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32);
|
||||
let enc = crate::alac::Encoder::new(config)?;
|
||||
let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n);
|
||||
(Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits))
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
CodecId::Mp3 => {
|
||||
let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?;
|
||||
let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000;
|
||||
// A sample rate MP3 has not is the encoder's to refuse.
|
||||
let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want);
|
||||
let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?;
|
||||
(Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None)
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
CodecId::Ac3 | CodecId::Eac3 => {
|
||||
let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 };
|
||||
let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?;
|
||||
let enc = crate::ac3::encoder::Encoder::new(config)?;
|
||||
let layout = enc.channel_layout();
|
||||
let bitrate = Some(config.bitrate_kbps.saturating_mul(1000));
|
||||
(Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None)
|
||||
}
|
||||
#[cfg(feature = "opus-encode")]
|
||||
CodecId::Opus => {
|
||||
let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default();
|
||||
let (map, layout) = fixed_map(masks, "Opus", None, &given)?;
|
||||
if sample_rate != 48_000 {
|
||||
return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz")));
|
||||
}
|
||||
let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?;
|
||||
let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?;
|
||||
let bitrate = Some(enc.bitrate());
|
||||
(Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None)
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))),
|
||||
};
|
||||
Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false })
|
||||
}
|
||||
|
||||
/// The codec of the packets.
|
||||
pub fn codec(&self) -> CodecId {
|
||||
self.codec
|
||||
}
|
||||
|
||||
/// The sample rate of the audio and of the packets' timing.
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
/// The number of channels.
|
||||
pub fn channels(&self) -> u16 {
|
||||
self.layout.channels()
|
||||
}
|
||||
|
||||
/// The speakers of the channels encoded, in WAV order: the codec's layout for the channel
|
||||
/// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the
|
||||
/// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back
|
||||
/// ones), whichever pair the caller's layout named.
|
||||
pub fn layout(&self) -> ChannelLayout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// The constant bit rate in bits per second for all channels together, as
|
||||
/// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and
|
||||
/// for AAC at a constant quality.
|
||||
pub fn bitrate(&self) -> Option<u32> {
|
||||
self.bitrate
|
||||
}
|
||||
|
||||
/// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones.
|
||||
pub fn bit_depth(&self) -> Option<u8> {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
/// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds`
|
||||
/// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box
|
||||
/// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3.
|
||||
/// ALAC's records the largest packet and the average bit rate so far, so read it after
|
||||
/// [`finish`](Self::finish).
|
||||
pub fn extradata(&self) -> Vec<u8> {
|
||||
match &self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => enc.audio_specific_config(),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Inner::Alac { enc, .. } => enc.cookie(),
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, .. } => enc.opus_head(),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The codec, sample rate, channels and [`extradata`](Self::extradata): the description
|
||||
/// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs.
|
||||
pub fn codec_params(&self) -> CodecParams {
|
||||
CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata())
|
||||
}
|
||||
|
||||
/// Decoded samples before the first input frame: the encoder's delay, which a container
|
||||
/// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which
|
||||
/// `OpusHead` already holds). 0 for ALAC.
|
||||
///
|
||||
/// This is the codec's delay and does not depend on the input. An encoder that is given no
|
||||
/// input returns no packets, and this still reports the delay.
|
||||
pub fn priming(&self) -> u32 {
|
||||
match &self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => enc.priming_samples(),
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Inner::Mp3 { enc, .. } => enc.delay(),
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Inner::Ac3 { enc, .. } => enc.priming_samples(),
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, .. } => u32::from(enc.pre_skip()),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames of input taken so far.
|
||||
pub fn frames(&self) -> u64 {
|
||||
self.frames
|
||||
}
|
||||
|
||||
/// Decoded samples after the last input frame, which a container trims (the end of an MP4
|
||||
/// edit, Matroska's DiscardPadding): the packets' durations add up to
|
||||
/// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after
|
||||
/// [`finish`](Self::finish).
|
||||
///
|
||||
/// The sum holds once there is input. With none, [`finish`](Self::finish) returns no packets,
|
||||
/// so the durations add up to 0 and this is 0, while `priming` is still the codec's delay: a
|
||||
/// muxer writes an empty track and has no priming to skip.
|
||||
pub fn padding(&self) -> u64 {
|
||||
self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames))
|
||||
}
|
||||
|
||||
/// Encodes the first `frames` frames of `block`, one slice per channel in WAV order
|
||||
/// (`&[Vec<f32>]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale
|
||||
/// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped.
|
||||
///
|
||||
/// Internal codec calls process at most 4096 frames at a time, but this method collects their
|
||||
/// packets in one returned vector whose memory use grows with `frames`. For streaming with
|
||||
/// bounded memory, pass bounded input blocks and consume each returned batch before encoding
|
||||
/// the next block, as [`FileEncoder`](crate::FileEncoder) does for coded formats.
|
||||
///
|
||||
/// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is
|
||||
/// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is
|
||||
/// an error too. When encoding itself fails, the packets of the block are lost, and every
|
||||
/// later call fails rather than return a stream with a gap.
|
||||
pub fn encode<C: AsRef<[f32]>>(&mut self, block: &[C], frames: usize) -> Result<Vec<EncodedPacket>> {
|
||||
self.usable()?;
|
||||
let channels = usize::from(self.channels());
|
||||
if block.len() != channels {
|
||||
return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len())));
|
||||
}
|
||||
if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() {
|
||||
return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}")));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for at in (0..frames).step_by(CHUNK) {
|
||||
let end = frames.min(at + CHUNK);
|
||||
let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect();
|
||||
if let Err(e) = self.push(&planes, &mut out) {
|
||||
self.failed = true;
|
||||
return Err(e);
|
||||
}
|
||||
self.frames = self.frames.saturating_add((end - at) as u64);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Encodes what the encoder still holds, padded with silence to whole packets and as far as
|
||||
/// a decoder needs to return every input frame after the priming, and returns the last
|
||||
/// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description
|
||||
/// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable.
|
||||
pub fn finish(&mut self) -> Result<Vec<EncodedPacket>> {
|
||||
self.usable()?;
|
||||
self.finished = true;
|
||||
let mut out = Vec::new();
|
||||
let done = self.drain(&mut out);
|
||||
if done.is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
done.map(|()| out)
|
||||
}
|
||||
|
||||
fn usable(&self) -> Result<()> {
|
||||
if self.failed {
|
||||
Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into()))
|
||||
} else if self.finished {
|
||||
Err(AudioError::Encode("the packet encoder is finished".into()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a packet of `duration` decoded samples at the current position.
|
||||
fn emit(pts: &mut u64, out: &mut Vec<EncodedPacket>, data: Vec<u8>, duration: u32) {
|
||||
out.push(EncodedPacket { data, pts: *pts, duration });
|
||||
*pts = pts.saturating_add(u64::from(duration));
|
||||
}
|
||||
|
||||
/// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames)
|
||||
/// and appends the packets completed.
|
||||
fn push(&mut self, planes: &[&[f32]], out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let pts = &mut self.pts;
|
||||
match &mut self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => {
|
||||
for data in enc.encode(planes) {
|
||||
Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Inner::Alac { enc, quantizers, pending } => {
|
||||
let frames = planes.first().map_or(0, |p| p.len());
|
||||
let mut at = 0;
|
||||
while at < frames {
|
||||
let filled = pending.first().map_or(0, Vec::len);
|
||||
let end = frames.min(at + CHUNK.saturating_sub(filled).max(1));
|
||||
for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) {
|
||||
dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s)));
|
||||
}
|
||||
at = end;
|
||||
if pending.first().is_some_and(|p| p.len() >= CHUNK) {
|
||||
alac_packet(enc, pending, pts, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Inner::Mp3 { enc, bytes } => {
|
||||
bytes.extend(enc.encode(planes));
|
||||
mp3_frames(enc, bytes, pts, out)?;
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Inner::Ac3 { enc, planes: clean } => {
|
||||
for (dst, src) in clean.iter_mut().zip(planes) {
|
||||
dst.clear();
|
||||
dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }));
|
||||
}
|
||||
let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect();
|
||||
for p in enc.push(&refs)? {
|
||||
Self::emit(pts, out, p.data, p.samples);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, pending, coded } => {
|
||||
let frames = planes.first().map_or(0, |p| p.len());
|
||||
for i in 0..frames {
|
||||
pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })));
|
||||
if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() {
|
||||
opus_packet(enc, pending, coded, pts, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes what the codec still holds and appends the last packets.
|
||||
fn drain(&mut self, out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let pts = &mut self.pts;
|
||||
match &mut self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => {
|
||||
for data in enc.flush() {
|
||||
Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Inner::Alac { enc, pending, .. } => {
|
||||
if pending.first().is_some_and(|p| !p.is_empty()) {
|
||||
alac_packet(enc, pending, pts, out)?;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Inner::Mp3 { enc, bytes } => {
|
||||
bytes.extend(enc.flush());
|
||||
mp3_frames(enc, bytes, pts, out)?;
|
||||
if !bytes.is_empty() {
|
||||
return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len())));
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Inner::Ac3 { enc, .. } => {
|
||||
for p in enc.finish()?.packets {
|
||||
Self::emit(pts, out, p.data, p.samples);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, pending, coded } => {
|
||||
// Every input frame decodes after the pre-skip: as many packets as that takes.
|
||||
let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64;
|
||||
let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size };
|
||||
let width = usize::from(enc.channels());
|
||||
while *coded < needed {
|
||||
pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0);
|
||||
opus_packet(enc, pending, coded, pts, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes the pending samples as one ALAC packet and empties them.
|
||||
#[cfg(feature = "alac-encode")]
|
||||
fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec<i32>], pts: &mut u64, out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect();
|
||||
let frames = refs.first().map_or(0, |p| p.len()) as u32;
|
||||
let data = enc.encode(&refs)?;
|
||||
pending.iter_mut().for_each(Vec::clear);
|
||||
PacketEncoder::emit(pts, out, data, frames);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them.
|
||||
#[cfg(feature = "opus-encode")]
|
||||
fn opus_packet(
|
||||
enc: &mut crate::opus::encoder::Encoder,
|
||||
pending: &mut Vec<f32>,
|
||||
coded: &mut u64,
|
||||
pts: &mut u64,
|
||||
out: &mut Vec<EncodedPacket>,
|
||||
) -> Result<()> {
|
||||
let data = enc.encode_float(pending)?;
|
||||
pending.clear();
|
||||
let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32;
|
||||
*coded += u64::from(size);
|
||||
PacketEncoder::emit(pts, out, data, size);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames
|
||||
/// back to back, so each one's length follows from its header's padding bit.
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec<u8>, pts: &mut u64, out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let samples = enc.frame_samples();
|
||||
let config = enc.config();
|
||||
// Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot.
|
||||
let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize;
|
||||
let mut at = 0;
|
||||
while let Some(header) = bytes.get(at..at + 4) {
|
||||
if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 {
|
||||
return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into()));
|
||||
}
|
||||
let len = base + usize::from((header[2] >> 1) & 1);
|
||||
let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break };
|
||||
PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32);
|
||||
at += len;
|
||||
}
|
||||
bytes.drain(..at);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
use crate::Speaker;
|
||||
use crate::{CodecId, Speaker};
|
||||
|
||||
fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option<Vec<usize>> {
|
||||
channel_map(mask, order, &ChannelLayout::from_mask(layout))
|
||||
@@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() {
|
||||
assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES));
|
||||
assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES));
|
||||
}
|
||||
|
||||
/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format.
|
||||
#[test]
|
||||
fn unbuilt_codecs_are_unsupported() {
|
||||
let built = [
|
||||
(CodecId::Aac, cfg!(feature = "aac-encode")),
|
||||
(CodecId::Alac, cfg!(feature = "alac-encode")),
|
||||
(CodecId::Mp3, cfg!(feature = "mp3-encode")),
|
||||
(CodecId::Ac3, cfg!(feature = "ac3-encode")),
|
||||
(CodecId::Eac3, cfg!(feature = "eac3-encode")),
|
||||
(CodecId::Opus, cfg!(feature = "opus-encode")),
|
||||
];
|
||||
let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16);
|
||||
for (codec, built) in built {
|
||||
let made = PacketEncoder::new(codec, &opts, 48_000, 2);
|
||||
if built {
|
||||
assert!(made.is_ok(), "{codec:?}: {made:?}");
|
||||
} else {
|
||||
assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,9 @@
|
||||
|
||||
use super::source::Src;
|
||||
use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag};
|
||||
use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat};
|
||||
|
||||
/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well.
|
||||
const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00];
|
||||
|
||||
/// Parsed WAV layout (no sample data decoded yet).
|
||||
pub(crate) struct WavLayout {
|
||||
pub info: AudioInfo,
|
||||
@@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result<WavParse> {
|
||||
ixml_time = ixml_time_reference(&small(IXML_MAX as u64));
|
||||
}
|
||||
}
|
||||
b"ds64" => ds64_data = le_u64(&small(64), 8),
|
||||
// The sizes come from the first `ds64` chunk that holds them.
|
||||
b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
//! SMPTE ST 302M: AES3 audio carried in MPEG-2 transport stream packets (feature `s302m`): a
|
||||
//! packet decoder ([`decode`]) and encoder ([`Encoder`]) for the payload of one PES packet.
|
||||
//!
|
||||
//! A packet is a 4-byte header and the audio. The header is the size in bytes of the audio (16 bits,
|
||||
//! big-endian), then 16 bits: the channel count code (2 bits; 0 to 3 for 2, 4, 6 or 8 channels), the
|
||||
//! identification of the first channel (8 bits), the sample size code (2 bits; 0, 1 and 2 for 16, 20
|
||||
//! and 24 bits) and 4 alignment bits. The audio is, for every frame, one 40-, 48- or 56-bit group
|
||||
//! per channel pair, the pairs in order: each pair is two AES3 subframes, the left channel then the
|
||||
//! right one, each of the sample (least significant bit first) and four flag bits (V, U, C and a
|
||||
//! frame-start flag set on the left subframe of each channel pair in the first frame of every block of 192 frames). The
|
||||
//! bits go out in transmission order, so a byte holds them most significant bit first.
|
||||
//!
|
||||
//! Samples are signed `i32` in the stream's own range (16, 20 or 24 bits, not scaled). The
|
||||
//! decoder reads the flags and ignores them; the encoder writes the validity, user and channel
|
||||
//! status bits as zero and sets the frame-start flag.
|
||||
//!
|
||||
//! Written from the standard's description of the packet and the AES3 subframe. ffmpeg is only run
|
||||
//! as a black-box oracle in the tests.
|
||||
|
||||
/// The most audio bytes one packet can hold (the size field is 16 bits).
|
||||
pub const MAX_AUDIO_BYTES: usize = 0xFFFF;
|
||||
|
||||
/// What went wrong decoding or encoding.
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The packet is damaged, truncated, or uses a reserved code.
|
||||
#[error("malformed SMPTE 302M packet: {0}")]
|
||||
Malformed(&'static str),
|
||||
/// The settings or samples given to the encoder cannot be written.
|
||||
#[error("SMPTE 302M cannot encode: {0}")]
|
||||
InvalidInput(&'static str),
|
||||
}
|
||||
|
||||
/// `Result` of this module.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// The header of a packet.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
/// 2, 4, 6 or 8.
|
||||
pub channels: usize,
|
||||
/// The identification of the first channel (as the stream gives it).
|
||||
pub channel_id: u8,
|
||||
/// 16, 20 or 24.
|
||||
pub bits: u32,
|
||||
/// The alignment bits as written.
|
||||
pub alignment: u8,
|
||||
/// Bytes of audio after the header.
|
||||
pub audio_bytes: usize,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
/// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow.
|
||||
pub fn frame_bytes(&self) -> usize {
|
||||
if !matches!(self.channels, 2 | 4 | 6 | 8) {
|
||||
return 0;
|
||||
}
|
||||
let pair_bytes = match self.bits {
|
||||
16 => 5,
|
||||
20 => 6,
|
||||
24 => 7,
|
||||
_ => return 0,
|
||||
};
|
||||
(self.channels / 2).checked_mul(pair_bytes).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the 4-byte header at the start of `packet`.
|
||||
pub fn parse_header(packet: &[u8]) -> Result<Header> {
|
||||
let [a, b, c, d, ..] = *packet else { return Err(Error::Malformed("shorter than the header")) };
|
||||
let size = usize::from(u16::from_be_bytes([a, b]));
|
||||
let word = u16::from_be_bytes([c, d]);
|
||||
let channels = 2 * (usize::from(word >> 14) + 1);
|
||||
let bits = match (word >> 4) & 3 {
|
||||
0 => 16,
|
||||
1 => 20,
|
||||
2 => 24,
|
||||
_ => return Err(Error::Malformed("reserved sample size code")),
|
||||
};
|
||||
Ok(Header { channels, channel_id: ((word >> 6) & 0xFF) as u8, bits, alignment: (word & 0xF) as u8, audio_bytes: size })
|
||||
}
|
||||
|
||||
/// One decoded packet.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Decoded {
|
||||
/// The packet header.
|
||||
pub header: Header,
|
||||
/// Interleaved samples, `header.channels` per frame.
|
||||
pub samples: Vec<i32>,
|
||||
}
|
||||
|
||||
/// Bit `i` of a byte string in transmission order (the first bit sent is the least significant bit of the sample, held in the most significant bit of the byte).
|
||||
fn bit(bytes: &[u8], i: usize) -> u32 {
|
||||
bytes.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1))
|
||||
}
|
||||
|
||||
/// Decode the payload of one PES packet.
|
||||
pub fn decode(packet: &[u8]) -> Result<Decoded> {
|
||||
let header = parse_header(packet)?;
|
||||
let audio = packet.get(4..).unwrap_or(&[]);
|
||||
if audio.len() < header.audio_bytes {
|
||||
return Err(Error::Malformed("the audio is shorter than the header says"));
|
||||
}
|
||||
let audio = audio.get(..header.audio_bytes).unwrap_or(&[]);
|
||||
let frame_bytes = header.frame_bytes();
|
||||
if frame_bytes == 0 || audio.len() % frame_bytes != 0 {
|
||||
return Err(Error::Malformed("the audio is not a whole number of frames"));
|
||||
}
|
||||
let n = header.bits as usize;
|
||||
let mut samples = Vec::with_capacity(audio.len() / (n + 4) * 8 / 2);
|
||||
for frame in audio.chunks_exact(frame_bytes) {
|
||||
for pos in (0..header.channels).map(|c| c * (n + 4)) {
|
||||
let mut v = 0u32;
|
||||
for k in 0..n {
|
||||
v |= bit(frame, pos + k) << k;
|
||||
}
|
||||
// sign-extend the n-bit sample
|
||||
let shift = 32 - n as u32;
|
||||
samples.push(((v << shift) as i32) >> shift);
|
||||
}
|
||||
}
|
||||
Ok(Decoded { header, samples })
|
||||
}
|
||||
|
||||
/// A packet encoder. It counts frames so that the frame-start flag falls on the first frame of
|
||||
/// every block of 192.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Encoder {
|
||||
channels: usize,
|
||||
bits: u32,
|
||||
channel_id: u8,
|
||||
frames: u64,
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
/// An encoder for `channels` (2, 4, 6 or 8) channels of `bits` (16, 20 or 24) bits.
|
||||
pub fn new(channels: usize, bits: u32) -> Result<Encoder> {
|
||||
if !matches!(channels, 2 | 4 | 6 | 8) {
|
||||
return Err(Error::InvalidInput("SMPTE 302M carries 2, 4, 6 or 8 channels"));
|
||||
}
|
||||
if !matches!(bits, 16 | 20 | 24) {
|
||||
return Err(Error::InvalidInput("SMPTE 302M samples have 16, 20 or 24 bits"));
|
||||
}
|
||||
Ok(Encoder { channels, bits, channel_id: 0, frames: 0 })
|
||||
}
|
||||
|
||||
/// Set the identification of the first channel written in the header (0 by default).
|
||||
pub fn channel_id(mut self, id: u8) -> Encoder {
|
||||
self.channel_id = id;
|
||||
self
|
||||
}
|
||||
|
||||
/// The most frames one packet can hold.
|
||||
pub fn max_frames(&self) -> usize {
|
||||
MAX_AUDIO_BYTES / (self.channels / 2 * ((self.bits as usize + 4) * 2 / 8))
|
||||
}
|
||||
|
||||
/// Encode interleaved samples (a whole number of frames, at most [`Encoder::max_frames`], each
|
||||
/// within the sample size) as one packet payload.
|
||||
pub fn encode(&mut self, samples: &[i32]) -> Result<Vec<u8>> {
|
||||
if samples.is_empty() || !samples.len().is_multiple_of(self.channels) {
|
||||
return Err(Error::InvalidInput("the samples are not a whole number of frames"));
|
||||
}
|
||||
let frames = samples.len() / self.channels;
|
||||
if frames > self.max_frames() {
|
||||
return Err(Error::InvalidInput("too many frames for one packet"));
|
||||
}
|
||||
let n = self.bits as usize;
|
||||
let limit = 1i64 << (n - 1);
|
||||
if samples.iter().any(|&s| i64::from(s) < -limit || i64::from(s) >= limit) {
|
||||
return Err(Error::InvalidInput("a sample is outside the sample size"));
|
||||
}
|
||||
let frame_bytes = self.channels / 2 * ((n + 4) * 2 / 8);
|
||||
let audio_bytes = frames * frame_bytes;
|
||||
let code = match self.bits {
|
||||
16 => 0u16,
|
||||
20 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
let word = (((self.channels / 2 - 1) as u16) << 14) | (u16::from(self.channel_id) << 6) | (code << 4);
|
||||
let mut out = Vec::with_capacity(4 + audio_bytes);
|
||||
out.extend((audio_bytes as u16).to_be_bytes());
|
||||
out.extend(word.to_be_bytes());
|
||||
out.resize(4 + audio_bytes, 0);
|
||||
for (f, frame) in samples.chunks_exact(self.channels).enumerate() {
|
||||
let start = (self.frames + f as u64).is_multiple_of(192);
|
||||
let base = 4 + f * frame_bytes;
|
||||
for (c, &s) in frame.iter().enumerate() {
|
||||
let pos = c * (n + 4);
|
||||
let v = (s as u32) & ((1u32 << n) - 1);
|
||||
for k in 0..n {
|
||||
set_bit(&mut out, base, pos + k, (v >> k) & 1);
|
||||
}
|
||||
// flags V, U, C, then the frame-start flag on the left subframe of each pair
|
||||
if c % 2 == 0 && start {
|
||||
set_bit(&mut out, base, pos + n + 3, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.frames += frames as u64;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn set_bit(out: &mut [u8], base: usize, i: usize, v: u32) {
|
||||
if v != 0
|
||||
&& let Some(b) = out.get_mut(base + i / 8)
|
||||
{
|
||||
*b |= 0x80 >> (i % 8);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_packet() {
|
||||
// stereo 16-bit, one frame: L = 0x1234, R = 0xFEFF, the first frame of a block
|
||||
let packet = [0x00, 0x05, 0x00, 0x00, 0x2c, 0x48, 0x1f, 0xf7, 0xf0];
|
||||
let d = decode(&packet).unwrap();
|
||||
assert_eq!(d.samples, vec![0x1234, -257]);
|
||||
assert_eq!((d.header.channels, d.header.bits), (2, 16));
|
||||
let mut e = Encoder::new(2, 16).unwrap();
|
||||
assert_eq!(e.encode(&[0x1234, -257]).unwrap(), packet);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_and_packets_are_checked() {
|
||||
assert!(Encoder::new(1, 16).is_err());
|
||||
assert!(Encoder::new(2, 18).is_err());
|
||||
let mut e = Encoder::new(2, 16).unwrap();
|
||||
assert!(e.encode(&[]).is_err());
|
||||
assert!(e.encode(&[1]).is_err());
|
||||
assert!(e.encode(&[40_000, 0]).is_err());
|
||||
assert!(decode(&[0, 1]).is_err());
|
||||
assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err());
|
||||
assert!(decode(&[0, 5, 0, 0, 0, 0]).is_err());
|
||||
assert!(decode(&[0, 4, 0, 0, 0, 0, 0, 0]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_overflow_does_not_panic() {
|
||||
let h = Header { channels: usize::MAX, channel_id: 0, bits: 24, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h.frame_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_rejects_unsupported_channels() {
|
||||
for bits in [16, 20, 24] {
|
||||
for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] {
|
||||
let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 };
|
||||
assert!(Encoder::new(channels, bits).is_err());
|
||||
assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_rejects_unsupported_depth() {
|
||||
let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h_max.frame_bytes(), 0);
|
||||
|
||||
let h_unsupported = Header { channels: 2, channel_id: 0, bits: 18, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h_unsupported.frame_bytes(), 0);
|
||||
|
||||
let h_zero = Header { channels: 2, channel_id: 0, bits: 0, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h_zero.frame_bytes(), 0);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,83 @@
|
||||
//! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature
|
||||
//! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia.
|
||||
//!
|
||||
//! Both work in Vorbis channel order (Vorbis I §4.3.9). [`wav_order`] maps decoded channels to the
|
||||
//! WAV order the rest of craft-audio uses, and [`layout`] gives the speakers they then feed.
|
||||
|
||||
use crate::ChannelLayout;
|
||||
|
||||
#[cfg(feature = "vorbis-decode")]
|
||||
pub mod decoder;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
pub mod encoder;
|
||||
|
||||
/// Channel order for Vorbis surround (Vorbis I §4.3.9: L C R for three, L C R Ls Rs for five,
|
||||
/// L C R Ls Rs LFE for 5.1, L C R Ls Rs Cb LFE for 6.1, L C R Ls Rs Lb Rb LFE for 7.1): output
|
||||
/// channel → decoded channel, giving the WAV order (L R C LFE back… side…) of [`layout`]. `None` for
|
||||
/// 1, 2 and 4 channels, which are already in WAV order, and for more than 8, whose order the
|
||||
/// specification leaves to the application.
|
||||
///
|
||||
/// ```
|
||||
/// let vorbis: Vec<Vec<f32>> = (0..6).map(|c| vec![c as f32]).collect(); // L C R Ls Rs LFE
|
||||
/// let order = craft_audio::vorbis::wav_order(6).unwrap();
|
||||
/// let wav: Vec<Vec<f32>> = order.iter().map(|&c| vorbis[c].clone()).collect(); // L R C LFE Ls Rs
|
||||
/// assert_eq!(wav[3], vec![5.0]);
|
||||
/// ```
|
||||
pub fn wav_order(channels: usize) -> Option<&'static [usize]> {
|
||||
Some(match channels {
|
||||
3 => &[0, 2, 1],
|
||||
5 => &[0, 2, 1, 3, 4],
|
||||
6 => &[0, 2, 1, 5, 3, 4],
|
||||
7 => &[0, 2, 1, 6, 5, 3, 4],
|
||||
8 => &[0, 2, 1, 7, 5, 6, 3, 4],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The speakers of a Vorbis stream with `channels` channels, in WAV order (after [`wav_order`]):
|
||||
/// mono, stereo, L R C, quad, 5.0, 5.1, 6.1 with a back center and side surrounds, and 7.1 with
|
||||
/// backs and sides. Other counts are unordered. For 7 channels this differs from
|
||||
/// [`ChannelLayout::default_for`], which puts the surrounds at the back.
|
||||
pub fn layout(channels: u16) -> ChannelLayout {
|
||||
match channels {
|
||||
1 => ChannelLayout::MONO,
|
||||
2 => ChannelLayout::STEREO,
|
||||
3 => ChannelLayout::SURROUND_3_0,
|
||||
4 => ChannelLayout::QUAD,
|
||||
5 => ChannelLayout::SURROUND_5_0,
|
||||
6 => ChannelLayout::SURROUND_5_1,
|
||||
7 => ChannelLayout::SURROUND_6_1,
|
||||
8 => ChannelLayout::SURROUND_7_1,
|
||||
_ => ChannelLayout::unordered(channels),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Speaker::{self, *};
|
||||
|
||||
/// Vorbis I §4.3.9, one row per channel count, in the order a stream carries the channels.
|
||||
const VORBIS_ORDER: [&[Speaker]; 8] = [
|
||||
&[FrontCenter],
|
||||
&[FrontLeft, FrontRight],
|
||||
&[FrontLeft, FrontCenter, FrontRight],
|
||||
&[FrontLeft, FrontRight, BackLeft, BackRight],
|
||||
&[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight],
|
||||
&[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe],
|
||||
&[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackCenter, Lfe],
|
||||
&[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackLeft, BackRight, Lfe],
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn reordered_channels_feed_the_layout_speakers() {
|
||||
for (i, stream) in VORBIS_ORDER.iter().enumerate() {
|
||||
let channels = i + 1;
|
||||
let wav: Vec<Speaker> = match wav_order(channels) {
|
||||
Some(order) => order.iter().map(|&c| stream[c]).collect(),
|
||||
None => stream.to_vec(),
|
||||
};
|
||||
assert_eq!(wav, layout(channels as u16).speakers(), "{channels} channels");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
|
||||
pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
|
||||
/// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag.
|
||||
pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71];
|
||||
/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well.
|
||||
pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00];
|
||||
+60
-351
@@ -1,7 +1,7 @@
|
||||
//! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through
|
||||
//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's
|
||||
//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the
|
||||
//! encoder's priming and the exact length in the edit list.
|
||||
//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a
|
||||
//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for
|
||||
//! M4A records the encoder's priming and the exact length in the edit list.
|
||||
|
||||
// Each codec is its own feature, and so are the two sinks: with only some of them built, the
|
||||
// other halves of the shared code are unused.
|
||||
@@ -11,271 +11,10 @@
|
||||
)]
|
||||
|
||||
use super::failed_write_error;
|
||||
use super::pcm::validate_layout;
|
||||
use crate::layout::channel_map;
|
||||
use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result};
|
||||
use crate::packet::{EncodedPacket, PacketEncoder};
|
||||
use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result};
|
||||
use std::io::{Cursor, Seek, Write};
|
||||
|
||||
/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written
|
||||
/// stay small however long a block is. Also the frames of an ALAC packet.
|
||||
const CHUNK: usize = 4096;
|
||||
|
||||
/// Bits per second per channel when no rate is asked for: AAC.
|
||||
const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
|
||||
/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per
|
||||
/// full-bandwidth channel).
|
||||
const DEFAULT_KBPS_PER_CHANNEL: u32 = 96;
|
||||
|
||||
/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`.
|
||||
fn labels(mask: u32) -> String {
|
||||
ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]),
|
||||
/// or why the audio does not fit.
|
||||
fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<Vec<usize>> {
|
||||
let Some(&mask) = format.layout_masks(layout.channels()).first() else {
|
||||
return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels())));
|
||||
};
|
||||
channel_map(mask, order, layout).ok_or_else(|| {
|
||||
AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The speakers of the caller's layout, for an error message.
|
||||
fn given(layout: &ChannelLayout) -> String {
|
||||
layout.mask().map_or_else(|| "without speaker assignment".into(), labels)
|
||||
}
|
||||
|
||||
/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels
|
||||
/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_order(channels: usize) -> Option<&'static [usize]> {
|
||||
if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) }
|
||||
}
|
||||
|
||||
/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample
|
||||
/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes
|
||||
/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s).
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_floor_per_channel(sample_rate: u32) -> u32 {
|
||||
(sample_rate / 4).max(6000)
|
||||
}
|
||||
|
||||
/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a
|
||||
/// quality of 0–1 spans the encoder's VBR range.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_mode(rate: Option<RateControl>, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode {
|
||||
use crate::aac::BitrateMode;
|
||||
let (lo, hi) = crate::aac::cbr_range(sample_rate, channels);
|
||||
let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo));
|
||||
// An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone.
|
||||
let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps };
|
||||
match rate {
|
||||
None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))),
|
||||
Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)),
|
||||
// NaN stays NaN, which the encoder refuses.
|
||||
Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit rate in kbit/s for a codec with constant bit rates only.
|
||||
fn constant_kbps(name: &str, rate: Option<RateControl>, default: u32) -> Result<u32> {
|
||||
match rate {
|
||||
None => Ok(default),
|
||||
Some(RateControl::Bitrate(bps)) => Ok(bps / 1000),
|
||||
Some(RateControl::Quality(_)) => {
|
||||
Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding
|
||||
/// mode whose speakers the layout names, at the nearest bit rate the stream can carry.
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
fn ac3_config(
|
||||
codec: crate::ac3::encoder::Codec,
|
||||
sample_rate: u32,
|
||||
layout: &ChannelLayout,
|
||||
rate: Option<RateControl>,
|
||||
) -> Result<(crate::ac3::encoder::Config, Vec<usize>)> {
|
||||
use crate::ac3::encoder::{Codec, CodingMode, Config};
|
||||
use CodingMode::*;
|
||||
let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" };
|
||||
let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71];
|
||||
let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| {
|
||||
// 7.1 is an E-AC-3 programme with an LFE; the encoder has no other.
|
||||
if mode == Surround71 && (codec != Codec::Eac3 || !lfe) {
|
||||
return None;
|
||||
}
|
||||
let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe };
|
||||
let map = channel_map(config.channel_layout().mask()?, None, layout)?;
|
||||
Some((config, map))
|
||||
});
|
||||
let Some((mut config, map)) = found else {
|
||||
return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout))));
|
||||
};
|
||||
let full = config.mode.channels() as u32;
|
||||
let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?;
|
||||
// What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of
|
||||
// the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold.
|
||||
let least = if config.mode == Surround71 { 384 } else { 32 * full };
|
||||
config.bitrate_kbps = match codec {
|
||||
Codec::Ac3 => {
|
||||
let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least);
|
||||
crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor)
|
||||
}
|
||||
Codec::Eac3 => {
|
||||
let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 };
|
||||
want.clamp(least, most.max(least))
|
||||
}
|
||||
};
|
||||
Ok((config, map))
|
||||
}
|
||||
|
||||
/// One encoded packet and the frames it decodes to.
|
||||
struct Packet {
|
||||
data: Vec<u8>,
|
||||
frames: u32,
|
||||
}
|
||||
|
||||
/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order.
|
||||
enum Codec {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Aac(Box<crate::aac::Encoder>),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Alac {
|
||||
enc: Box<crate::alac::Encoder>,
|
||||
quantizers: Vec<super::pcm::Quantizer>,
|
||||
/// Quantized samples of the packet being filled, per channel.
|
||||
pending: Vec<Vec<i32>>,
|
||||
},
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Mp3(Box<crate::mp3::Encoder>),
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Ac3 {
|
||||
enc: Box<crate::ac3::encoder::Encoder>,
|
||||
/// The block with every sample finite and within ±1, as the encoder requires.
|
||||
planes: Vec<Vec<f32>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Codec {
|
||||
/// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames)
|
||||
/// and appends the packets completed.
|
||||
fn push(&mut self, planes: &[&[f32]], out: &mut Vec<Packet>) -> Result<()> {
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Codec::Alac { enc, quantizers, pending } => {
|
||||
let frames = planes.first().map_or(0, |p| p.len());
|
||||
let mut at = 0;
|
||||
while at < frames {
|
||||
let filled = pending.first().map_or(0, Vec::len);
|
||||
let end = frames.min(at + CHUNK.saturating_sub(filled).max(1));
|
||||
for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) {
|
||||
dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s)));
|
||||
}
|
||||
at = end;
|
||||
if pending.first().is_some_and(|p| p.len() >= CHUNK) {
|
||||
alac_packet(enc, pending, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Codec::Mp3(enc) => {
|
||||
let data = enc.encode(planes);
|
||||
if !data.is_empty() {
|
||||
out.push(Packet { data, frames: 0 });
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Codec::Ac3 { enc, planes: clean } => {
|
||||
for (dst, src) in clean.iter_mut().zip(planes) {
|
||||
dst.clear();
|
||||
dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }));
|
||||
}
|
||||
let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect();
|
||||
out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples }));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes what the encoder still holds and appends the last packets.
|
||||
fn finish(&mut self, out: &mut Vec<Packet>) -> Result<()> {
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Codec::Alac { enc, pending, .. } => {
|
||||
if pending.first().is_some_and(|p| !p.is_empty()) {
|
||||
alac_packet(enc, pending, out)?;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Codec::Mp3(enc) => {
|
||||
let data = enc.flush();
|
||||
if !data.is_empty() {
|
||||
out.push(Packet { data, frames: 0 });
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decoded frames before the first frame of the audio.
|
||||
fn priming(&self) -> u32 {
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => enc.priming_samples(),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames`
|
||||
/// frames in all): the configuration a decoder needs, with the average bit rate.
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option<craft_media::isobmff::SampleEntry> {
|
||||
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry};
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => {
|
||||
let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate);
|
||||
if let CodecConfig::Aac(config) = &mut entry.codec
|
||||
&& frames > 0
|
||||
{
|
||||
let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames);
|
||||
config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX);
|
||||
}
|
||||
Some(entry)
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Codec::Alac { enc, .. } => {
|
||||
let bits = u16::from(enc.encoder_config().bit_depth);
|
||||
Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits))
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes the pending samples as one ALAC packet and empties them.
|
||||
#[cfg(feature = "alac-encode")]
|
||||
fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec<i32>], out: &mut Vec<Packet>) -> Result<()> {
|
||||
let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect();
|
||||
let frames = refs.first().map_or(0, |p| p.len()) as u32;
|
||||
let data = enc.encode(&refs)?;
|
||||
pending.iter_mut().for_each(Vec::clear);
|
||||
out.push(Packet { data, frames });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A muxer's error as this crate's: a failed write stays an I/O error.
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
fn mux_error(e: craft_media::isobmff::Error) -> AudioError {
|
||||
@@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError {
|
||||
}
|
||||
}
|
||||
|
||||
/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in
|
||||
/// all): the configuration a decoder needs, with the average bit rate.
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option<craft_media::isobmff::SampleEntry> {
|
||||
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry};
|
||||
let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels()));
|
||||
match enc.codec() {
|
||||
CodecId::Aac => {
|
||||
let mut entry = SampleEntry::aac(enc.extradata(), channels, rate);
|
||||
if let CodecConfig::Aac(config) = &mut entry.codec
|
||||
&& frames > 0
|
||||
{
|
||||
let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames);
|
||||
config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX);
|
||||
}
|
||||
Some(entry)
|
||||
}
|
||||
CodecId::Alac => {
|
||||
let bits = u16::from(enc.bit_depth().unwrap_or(16));
|
||||
Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An M4A file being written: one audio track whose samples are the packets.
|
||||
///
|
||||
/// The last packet is held back until the length is known: its duration is cut to the audio's
|
||||
@@ -298,9 +62,8 @@ struct M4a<W: Write + Seek> {
|
||||
track: Option<usize>,
|
||||
entry: craft_media::isobmff::SampleEntry,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
priming: u32,
|
||||
held: Option<Packet>,
|
||||
held: Option<EncodedPacket>,
|
||||
/// Frames and bytes of the packets written, the held one not counted.
|
||||
frames: u64,
|
||||
bytes: u64,
|
||||
@@ -308,13 +71,14 @@ struct M4a<W: Write + Seek> {
|
||||
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
impl<W: Write + Seek> M4a<W> {
|
||||
fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result<Self> {
|
||||
fn new(out: W, enc: &PacketEncoder) -> Result<Self> {
|
||||
use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions};
|
||||
let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?;
|
||||
let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?;
|
||||
let sample_rate = enc.sample_rate();
|
||||
let mut options = WriterOptions::new(Brand::Mp4);
|
||||
options.movie_timescale = sample_rate;
|
||||
let mux = Mp4Writer::new(out, options).map_err(mux_error)?;
|
||||
Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 })
|
||||
Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 })
|
||||
}
|
||||
|
||||
fn track(&mut self, has_audio: bool) -> Result<usize> {
|
||||
@@ -333,7 +97,7 @@ impl<W: Write + Seek> M4a<W> {
|
||||
Ok(track)
|
||||
}
|
||||
|
||||
fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> {
|
||||
fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> {
|
||||
let track = self.track(true)?;
|
||||
let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true };
|
||||
self.mux.write_sample(track, sample).map_err(mux_error)?;
|
||||
@@ -342,22 +106,22 @@ impl<W: Write + Seek> M4a<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write(&mut self, packet: Packet) -> Result<()> {
|
||||
fn write(&mut self, packet: EncodedPacket) -> Result<()> {
|
||||
if let Some(held) = self.held.replace(packet) {
|
||||
self.sample(&held, held.frames)?;
|
||||
self.sample(&held, held.duration)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`.
|
||||
fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result<W> {
|
||||
/// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`.
|
||||
fn finish(mut self, enc: &PacketEncoder) -> Result<W> {
|
||||
if let Some(held) = self.held.take() {
|
||||
let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames);
|
||||
self.sample(&held, rest.min(u64::from(held.frames)) as u32)?;
|
||||
let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames);
|
||||
self.sample(&held, rest.min(u64::from(held.duration)) as u32)?;
|
||||
}
|
||||
let track = self.track(false)?;
|
||||
// The configuration is complete only now: the bit rate, and ALAC's largest packet.
|
||||
if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) {
|
||||
if let Some(entry) = sample_entry(enc, self.bytes, self.frames) {
|
||||
self.mux.set_sample_entry(track, entry).map_err(mux_error)?;
|
||||
}
|
||||
self.mux.finish().map_err(mux_error)
|
||||
@@ -374,15 +138,8 @@ enum Sink<W: Write + Seek> {
|
||||
|
||||
/// A file of one of the coded formats written block by block.
|
||||
pub(crate) struct Writer<W: Write + Seek> {
|
||||
codec: Codec,
|
||||
enc: PacketEncoder,
|
||||
sink: Sink<W>,
|
||||
/// For each encoder channel, the caller's channel that feeds it.
|
||||
map: Vec<usize>,
|
||||
/// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for
|
||||
/// AAC at a constant quality.
|
||||
bitrate: Option<u32>,
|
||||
frames: u64,
|
||||
packets: Vec<Packet>,
|
||||
/// Set when a write has failed: the encoder and the sink no longer agree, so the writer
|
||||
/// refuses every later call.
|
||||
failed: bool,
|
||||
@@ -390,68 +147,23 @@ pub(crate) struct Writer<W: Write + Seek> {
|
||||
|
||||
impl<W: Write + Seek> Writer<W> {
|
||||
pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result<Self> {
|
||||
validate_layout(channels, sample_rate)?;
|
||||
let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16));
|
||||
let (codec, map, bitrate) = match opts.format {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
EncodeFormat::Aac => {
|
||||
let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?;
|
||||
let mode = aac_mode(opts.rate_control, sample_rate, channels);
|
||||
let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) };
|
||||
let bitrate = match mode {
|
||||
crate::aac::BitrateMode::Cbr(bps) => Some(bps),
|
||||
crate::aac::BitrateMode::Vbr(_) => None,
|
||||
};
|
||||
(Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate)
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
EncodeFormat::Alac => {
|
||||
let count = u8::try_from(channels).unwrap_or(u8::MAX);
|
||||
let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?;
|
||||
let bits = match opts.bit_depth {
|
||||
crate::BitDepth::Int16 => 16,
|
||||
crate::BitDepth::Int24 => 24,
|
||||
crate::BitDepth::Int32 => 32,
|
||||
crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())),
|
||||
};
|
||||
let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?;
|
||||
let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels);
|
||||
(Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None)
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
EncodeFormat::Mp3 => {
|
||||
let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?;
|
||||
let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?;
|
||||
// A sample rate MP3 has not is the encoder's to refuse.
|
||||
let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want);
|
||||
let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?;
|
||||
(Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000)))
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
EncodeFormat::Ac3 | EncodeFormat::Eac3 => {
|
||||
let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 };
|
||||
let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?;
|
||||
let enc = crate::ac3::encoder::Encoder::new(config)?;
|
||||
(Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000)))
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
f => return Err(AudioError::Unsupported(format!("writing {f:?}"))),
|
||||
};
|
||||
let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?;
|
||||
let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?;
|
||||
let sink = match opts.format {
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)),
|
||||
EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)),
|
||||
_ => Sink::Raw(out),
|
||||
};
|
||||
Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false })
|
||||
Ok(Writer { enc, sink, failed: false })
|
||||
}
|
||||
|
||||
pub(crate) fn bitrate(&self) -> Option<u32> {
|
||||
self.bitrate
|
||||
self.enc.bitrate()
|
||||
}
|
||||
|
||||
/// Hands the packets waiting to the sink.
|
||||
fn drain(&mut self) -> Result<()> {
|
||||
for packet in self.packets.drain(..) {
|
||||
/// Hands `packets` to the sink.
|
||||
fn drain(&mut self, packets: Vec<EncodedPacket>) -> Result<()> {
|
||||
for packet in packets {
|
||||
match &mut self.sink {
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
Sink::M4a(m4a) => m4a.write(packet)?,
|
||||
@@ -466,16 +178,16 @@ impl<W: Write + Seek> Writer<W> {
|
||||
if self.failed {
|
||||
return Err(failed_write_error());
|
||||
}
|
||||
for at in (0..frames).step_by(CHUNK) {
|
||||
let end = frames.min(at + CHUNK);
|
||||
let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect();
|
||||
let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain());
|
||||
// A block at a time, so the packets waiting for the sink stay few however long it is.
|
||||
for at in (0..frames).step_by(crate::packet::CHUNK) {
|
||||
let end = frames.min(at + crate::packet::CHUNK);
|
||||
let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect();
|
||||
let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets));
|
||||
if let Err(e) = written {
|
||||
self.failed = true;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
self.frames = self.frames.saturating_add(frames as u64);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -483,11 +195,11 @@ impl<W: Write + Seek> Writer<W> {
|
||||
if self.failed {
|
||||
return Err(failed_write_error());
|
||||
}
|
||||
self.codec.finish(&mut self.packets)?;
|
||||
self.drain()?;
|
||||
let last = self.enc.finish()?;
|
||||
self.drain(last)?;
|
||||
match self.sink {
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames),
|
||||
Sink::M4a(m4a) => m4a.finish(&self.enc),
|
||||
Sink::Raw(mut out) => {
|
||||
out.flush()?;
|
||||
Ok(out)
|
||||
@@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result<Vec<u8>>
|
||||
w.write(&buf.channels, buf.frames())?;
|
||||
Ok(w.finish()?.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -8,7 +8,7 @@ mod aiff;
|
||||
mod coded;
|
||||
#[cfg(feature = "flac-encode")]
|
||||
pub(crate) mod flac;
|
||||
mod pcm;
|
||||
pub(crate) mod pcm;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
mod vorbis;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
@@ -449,8 +449,99 @@ impl EncodeOptions {
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result<Vec<u8>> {
|
||||
float_header(sample_rate, channels, None, frames)
|
||||
}
|
||||
|
||||
/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length
|
||||
/// still doesn't depend on `frames`, so the header is rewritten in place the same way.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_audio::{BwfInfo, wav_float_header_with_bwf};
|
||||
///
|
||||
/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600);
|
||||
/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap();
|
||||
/// let samples = [0.25f32, -0.25, 0.5, -0.5];
|
||||
/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes()));
|
||||
/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap();
|
||||
/// file[..header.len()].copy_from_slice(&header);
|
||||
/// assert!(header.windows(4).any(|id| id == b"bext"));
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result<Vec<u8>> {
|
||||
float_header(sample_rate, channels, Some(bwf), frames)
|
||||
}
|
||||
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result<Vec<u8>> {
|
||||
if channels == 0 || sample_rate == 0 {
|
||||
return Err(AudioError::Encode("a WAV needs channels and a sample rate".into()));
|
||||
}
|
||||
wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false)
|
||||
wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false)
|
||||
}
|
||||
|
||||
/// What [`repair_wav`] wrote into a file.
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct WavRepair {
|
||||
/// The whole frames the data chunk holds.
|
||||
pub frames: u64,
|
||||
/// The length of the repaired file. Bytes past it are a partial last frame; truncate the
|
||||
/// file to this length (`File::set_len`) to drop them.
|
||||
pub len: u64,
|
||||
}
|
||||
|
||||
/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such
|
||||
/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in
|
||||
/// its data chunk: everything after the data chunk's header counts as samples, whatever its size
|
||||
/// field says.
|
||||
///
|
||||
/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext`
|
||||
/// and unknown chunks included:
|
||||
///
|
||||
/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file);
|
||||
/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames);
|
||||
/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk;
|
||||
/// - the pad byte after an odd data length.
|
||||
///
|
||||
/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that
|
||||
/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk
|
||||
/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the
|
||||
/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way.
|
||||
///
|
||||
/// Errors:
|
||||
///
|
||||
/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within
|
||||
/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter
|
||||
/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size
|
||||
/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize
|
||||
/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a
|
||||
/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk).
|
||||
/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format
|
||||
/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits,
|
||||
/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte
|
||||
/// may be a sample or a pad byte).
|
||||
/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or
|
||||
/// `ds64` chunk.
|
||||
/// - [`AudioError::Io`] when reading, writing or seeking `file` fails.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_audio::{repair_wav, wav_float_header};
|
||||
/// use std::io::Cursor;
|
||||
///
|
||||
/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped.
|
||||
/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap();
|
||||
/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes()));
|
||||
/// let mut file = Cursor::new(bytes);
|
||||
/// let repaired = repair_wav(&mut file).unwrap();
|
||||
/// assert_eq!(repaired.frames, 2);
|
||||
/// let mut bytes = file.into_inner();
|
||||
/// bytes.truncate(repaired.len as usize);
|
||||
/// let header = wav_float_header(48_000, 2, 2).unwrap();
|
||||
/// assert_eq!(bytes[..header.len()], header[..]);
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn repair_wav<F: std::io::Read + Write + Seek>(file: &mut F) -> Result<WavRepair> {
|
||||
let (frames, len) = wav::repair(file)?;
|
||||
Ok(WavRepair { frames, len })
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
//! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306).
|
||||
|
||||
use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved};
|
||||
use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result};
|
||||
use std::io::{Cursor, Seek, SeekFrom, Write};
|
||||
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
|
||||
|
||||
const BEXT_MIN_LEN: usize = 602;
|
||||
|
||||
@@ -239,3 +239,175 @@ pub(crate) fn header(
|
||||
head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes());
|
||||
Ok(head)
|
||||
}
|
||||
|
||||
/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`.
|
||||
struct Layout {
|
||||
rf64: bool,
|
||||
/// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte
|
||||
/// `JUNK` or `ds64` chunk right after `WAVE` that can become one.
|
||||
ds64: Option<u64>,
|
||||
junk: bool,
|
||||
fact: Option<u64>,
|
||||
block_align: u64,
|
||||
data: u64,
|
||||
}
|
||||
|
||||
fn read_at<F: Read + Seek>(file: &mut F, pos: u64, buf: &mut [u8]) -> Result<bool> {
|
||||
file.seek(SeekFrom::Start(pos))?;
|
||||
match file.read_exact(buf) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_at<F: Write + Seek>(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> {
|
||||
file.seek(SeekFrom::Start(pos))?;
|
||||
file.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes.
|
||||
fn pcm_block_align<F: Read + Seek>(file: &mut F, pos: u64, size: u32) -> Result<u64> {
|
||||
let mut fmt = [0u8; 40];
|
||||
let n = if size >= 40 { 40 } else { 16 };
|
||||
if size < 16 || !read_at(file, pos, &mut fmt[..n])? {
|
||||
return Err(AudioError::Malformed("WAV fmt chunk is cut short".into()));
|
||||
}
|
||||
let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]);
|
||||
let mut tag = field(0);
|
||||
if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 {
|
||||
// The extensible fields the reader checks.
|
||||
if field(16) < 22 || field(18) > field(14) {
|
||||
return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into()));
|
||||
}
|
||||
if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL {
|
||||
tag = field(24);
|
||||
}
|
||||
}
|
||||
if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT {
|
||||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}")));
|
||||
}
|
||||
let (channels, align, bits) = (field(2), field(12), field(14));
|
||||
if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) {
|
||||
return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits")));
|
||||
}
|
||||
// The widths the WAV reader decodes.
|
||||
if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) {
|
||||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample")));
|
||||
}
|
||||
Ok(u64::from(align))
|
||||
}
|
||||
|
||||
fn layout<F: Read + Seek>(file: &mut F, len: u64) -> Result<Layout> {
|
||||
let mut riff = [0u8; 12];
|
||||
if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" {
|
||||
return Err(AudioError::Malformed("not a WAV file".into()));
|
||||
}
|
||||
let rf64 = riff.starts_with(b"RF64");
|
||||
let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None);
|
||||
let mut pos = 12u64;
|
||||
let mut chunk = [0u8; 8];
|
||||
// The same bound as the reader's, so a file of tiny chunks can't spin forever.
|
||||
for _ in 0..100_000 {
|
||||
if pos >= len || !read_at(file, pos, &mut chunk)? {
|
||||
break;
|
||||
}
|
||||
let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
|
||||
let body = pos + 8;
|
||||
match &chunk[..4] {
|
||||
b"data" => {
|
||||
let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?;
|
||||
return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body });
|
||||
}
|
||||
// The first `ds64` and `fact` chunks take the sizes; later ones are left as they are.
|
||||
// The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more.
|
||||
b"ds64" if rf64 && size >= 16 && ds64.is_none() => {
|
||||
if size < 28 {
|
||||
return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into()));
|
||||
}
|
||||
ds64 = Some(body);
|
||||
}
|
||||
// A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id.
|
||||
b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true),
|
||||
b"fact" if size >= 4 && fact.is_none() => fact = Some(body),
|
||||
b"fmt " => block_align = Some(pcm_block_align(file, body, size)?),
|
||||
_ => {}
|
||||
}
|
||||
pos = body + u64::from(size) + u64::from(size & 1);
|
||||
}
|
||||
Err(AudioError::Malformed("WAV has no data chunk".into()))
|
||||
}
|
||||
|
||||
/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's.
|
||||
fn stored_data_len<F: Read + Seek>(file: &mut F, l: &Layout) -> Result<Option<u64>> {
|
||||
let mut size = [0u8; 8];
|
||||
Ok(match (l.rf64, l.ds64) {
|
||||
(true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)),
|
||||
(true, None) => None,
|
||||
(false, _) => read_at(file, l.data - 4, &mut size[..4])?
|
||||
.then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]]))
|
||||
.filter(|&s| s != u32::MAX)
|
||||
.map(u64::from),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds.
|
||||
/// Returns the frame count and the length the file should have; bytes past it are a partial frame.
|
||||
pub(crate) fn repair<F: Read + Write + Seek>(file: &mut F) -> Result<(u64, u64)> {
|
||||
let len = file.seek(SeekFrom::End(0))?;
|
||||
let l = layout(file, len)?;
|
||||
let held = len.saturating_sub(l.data);
|
||||
// A finished file's own size, which also tells its pad byte from a frame of one byte.
|
||||
let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held));
|
||||
if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 {
|
||||
// The last byte may be a sample or the pad byte after an odd count of them.
|
||||
return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into()));
|
||||
}
|
||||
let frames = stored.unwrap_or(held) / l.block_align;
|
||||
let data_len = frames * l.block_align;
|
||||
let pad = data_len & 1;
|
||||
let new_len = l.data + data_len + pad;
|
||||
let riff_len = new_len - 8;
|
||||
let rf64 = l.rf64 || u32::try_from(riff_len).is_err();
|
||||
let ds64 = match (rf64, l.ds64) {
|
||||
(false, _) => None,
|
||||
(true, Some(at)) if l.rf64 || l.junk => Some(at),
|
||||
(true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())),
|
||||
(true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())),
|
||||
};
|
||||
if let Some(at) = l.fact {
|
||||
write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?;
|
||||
}
|
||||
match ds64 {
|
||||
Some(at) => {
|
||||
let mut body = Vec::with_capacity(28);
|
||||
body.extend_from_slice(&riff_len.to_le_bytes());
|
||||
body.extend_from_slice(&data_len.to_le_bytes());
|
||||
body.extend_from_slice(&frames.to_le_bytes());
|
||||
if !l.rf64 {
|
||||
// The `JUNK` chunk's last 4 bytes become the table length: no table entries.
|
||||
body.extend_from_slice(&0u32.to_le_bytes());
|
||||
}
|
||||
write_at(file, at, &body)?;
|
||||
if !l.rf64 {
|
||||
write_at(file, at - 8, b"ds64")?;
|
||||
write_at(file, 0, b"RF64")?;
|
||||
}
|
||||
write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?;
|
||||
write_at(file, 4, &u32::MAX.to_le_bytes())?;
|
||||
}
|
||||
None => {
|
||||
write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?;
|
||||
write_at(file, 4, &(riff_len as u32).to_le_bytes())?;
|
||||
}
|
||||
}
|
||||
// The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a
|
||||
// repeated repair can count.
|
||||
if pad == 1 {
|
||||
write_at(file, l.data + data_len, &[0])?;
|
||||
}
|
||||
file.seek(SeekFrom::Start(new_len))?;
|
||||
file.flush()?;
|
||||
Ok((frames, new_len))
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe};
|
||||
use craft_audio::{
|
||||
AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header,
|
||||
wav_float_header_with_bwf,
|
||||
};
|
||||
|
||||
fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer {
|
||||
let mut b = AudioBuffer::new(sr, channels as u16, frames);
|
||||
@@ -64,3 +67,335 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that stopped growing before its header was rewritten: the header for 0 frames, the
|
||||
/// samples of `buf`, then `extra` bytes of a frame that was never finished.
|
||||
fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec<u8>, Vec<u8>) {
|
||||
let finished = encode(buf, opts).unwrap();
|
||||
let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap();
|
||||
let head = file.len();
|
||||
let sample_bytes = match opts.bit_depth {
|
||||
BitDepth::Int16 => 2,
|
||||
BitDepth::Int24 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes;
|
||||
file.extend_from_slice(&finished[head..head + data_len]);
|
||||
file.extend(std::iter::repeat_n(0x55, extra));
|
||||
(file, finished)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() {
|
||||
let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600);
|
||||
let cases = [
|
||||
(sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5),
|
||||
// 3 bytes a frame and an odd frame count: the data needs a pad byte.
|
||||
(sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2),
|
||||
(sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0),
|
||||
(sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11),
|
||||
(sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3),
|
||||
];
|
||||
for (buf, opts, extra) in cases {
|
||||
let (file, finished) = unfinished_wav(&buf, &opts, extra);
|
||||
assert_ne!(file, finished);
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
let repaired = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(repaired.frames, buf.frames() as u64);
|
||||
let mut file = file.into_inner();
|
||||
assert!(file.len() as u64 >= repaired.len);
|
||||
file.truncate(repaired.len as usize);
|
||||
assert_eq!(file, finished, "{opts:?}");
|
||||
// A finished file stays as it is.
|
||||
let mut again = std::io::Cursor::new(file.clone());
|
||||
assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired);
|
||||
assert_eq!(again.into_inner(), file);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory.
|
||||
struct SparseWav {
|
||||
head: Vec<u8>,
|
||||
len: u64,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl std::io::Read for SparseWav {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize;
|
||||
for (i, b) in buf[..n].iter_mut().enumerate() {
|
||||
*b = self.head.get(self.pos as usize + i).copied().unwrap_or(0);
|
||||
}
|
||||
self.pos += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for SparseWav {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let end = self.pos as usize + buf.len();
|
||||
if end <= self.head.len() {
|
||||
self.head[self.pos as usize..end].copy_from_slice(buf);
|
||||
} else {
|
||||
assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header");
|
||||
}
|
||||
self.pos += buf.len() as u64;
|
||||
self.len = self.len.max(self.pos);
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for SparseWav {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.pos = match to {
|
||||
std::io::SeekFrom::Start(p) => p,
|
||||
std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(),
|
||||
std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(),
|
||||
};
|
||||
Ok(self.pos)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_turns_a_file_past_4_gib_into_rf64() {
|
||||
let frames = 600_000_000u64; // 4.8 GB of stereo float
|
||||
let head = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let len = head.len() as u64 + frames * 8 + 3;
|
||||
let mut file = SparseWav { head: head.clone(), len, pos: 0 };
|
||||
let repaired = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!((repaired.frames, repaired.len), (frames, len - 3));
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table.
|
||||
let mut dirty = head.clone();
|
||||
assert_eq!(&dirty[12..16], b"JUNK");
|
||||
dirty[20..48].fill(0xAA);
|
||||
let mut file = SparseWav { head: dirty, len, pos: 0 };
|
||||
craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time.
|
||||
let mut half = head.clone();
|
||||
half[12..16].copy_from_slice(b"ds64");
|
||||
let mut file = SparseWav { head: half, len, pos: 0 };
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired);
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is.
|
||||
let at = head.windows(4).position(|w| w == b"data").unwrap();
|
||||
let later: Vec<u8> = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat();
|
||||
let mut two = head.clone();
|
||||
two.splice(at..at, later.iter().copied());
|
||||
let mut file = SparseWav { head: two, len: len + 36, pos: 0 };
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames);
|
||||
assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..]));
|
||||
assert_eq!(file.head[at..at + 36], later[..]);
|
||||
|
||||
// In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is.
|
||||
let finished = wav_float_header(48_000, 2, frames).unwrap();
|
||||
assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..]));
|
||||
let mut stale = finished.clone();
|
||||
stale[20..44].fill(0);
|
||||
stale.splice(at..at, later.iter().copied());
|
||||
let mut file = SparseWav { head: stale, len: len + 36, pos: 0 };
|
||||
let r = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!((r.frames, r.len), (frames, len + 33));
|
||||
let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap());
|
||||
assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames));
|
||||
assert_eq!(file.head[at..at + 36], later[..]);
|
||||
|
||||
// A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB.
|
||||
let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16);
|
||||
assert_eq!(&bare[12..16], b"fmt ");
|
||||
let len = bare.len() as u64 + (1u64 << 32);
|
||||
let mut file = SparseWav { head: bare, len, pos: 0 };
|
||||
assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() {
|
||||
let mut file = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8;
|
||||
let at = file.windows(4).position(|w| w == b"data").unwrap();
|
||||
let later: Vec<u8> = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat();
|
||||
file.splice(at..at, later.iter().copied());
|
||||
file.extend(std::iter::repeat_n(0, 100 * 8));
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100);
|
||||
let file = file.into_inner();
|
||||
assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes());
|
||||
assert_eq!(file[at..at + 12], later[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true);
|
||||
let wav = encode(&sine(48_000, 2, 300), &opts).unwrap();
|
||||
assert_eq!(&wav[12..16], b"ds64");
|
||||
// A later ds64 chunk that gives the data 4 bytes, one frame.
|
||||
let mut body = [0u8; 28];
|
||||
body[8..16].copy_from_slice(&4u64.to_le_bytes());
|
||||
let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat();
|
||||
let at = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
let mut two = wav.clone();
|
||||
two.splice(at..at, later);
|
||||
let (info, buf) = decode(&two, Some("wav")).unwrap();
|
||||
assert_eq!((info.frames, buf.frames()), (300, 300));
|
||||
|
||||
// A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one.
|
||||
let mut short = two;
|
||||
short[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short[28..36].copy_from_slice(&4u64.to_le_bytes());
|
||||
short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat());
|
||||
assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1);
|
||||
let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short));
|
||||
assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}");
|
||||
}
|
||||
|
||||
/// A file whose writes fail once `writes` of them have gone through.
|
||||
struct FailingWrites {
|
||||
file: std::io::Cursor<Vec<u8>>,
|
||||
writes: usize,
|
||||
}
|
||||
|
||||
impl std::io::Read for FailingWrites {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
std::io::Read::read(&mut self.file, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for FailingWrites {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if self.writes == 0 {
|
||||
return Err(std::io::Error::other("disk full"));
|
||||
}
|
||||
self.writes -= 1;
|
||||
std::io::Write::write(&mut self.file, buf)
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for FailingWrites {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
std::io::Seek::seek(&mut self.file, to)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_runs_again_after_a_write_error() {
|
||||
let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8);
|
||||
u8_mono.extend([0x80; 3]);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24);
|
||||
let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2);
|
||||
for (file, frames) in [(u8_mono, 3), (int24, 999)] {
|
||||
let mut whole = std::io::Cursor::new(file.clone());
|
||||
let repaired = craft_audio::repair_wav(&mut whole).unwrap();
|
||||
assert_eq!(repaired.frames, frames);
|
||||
for writes in 0.. {
|
||||
let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes };
|
||||
if craft_audio::repair_wav(&mut failing).is_ok() {
|
||||
break;
|
||||
}
|
||||
let mut again = failing.file;
|
||||
assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes");
|
||||
assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_refuses_what_it_cannot_repair() {
|
||||
use craft_audio::AudioError;
|
||||
let repair = |bytes: Vec<u8>| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes));
|
||||
let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap();
|
||||
assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_))));
|
||||
// Every cut inside the header is an error, not a panic.
|
||||
let data = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
for cut in 0..data + 8 {
|
||||
assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}");
|
||||
}
|
||||
// A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by.
|
||||
let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
|
||||
let mut adpcm = wav.clone();
|
||||
adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes());
|
||||
assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_))));
|
||||
// The chunk walk stops, as the reader's does, after 100,000 chunks.
|
||||
let mut many = wav[..12].to_vec();
|
||||
many.extend(b"JUNK\0\0\0\0".repeat(100_001));
|
||||
many.extend_from_slice(&wav[12..]);
|
||||
assert!(matches!(repair(many), Err(AudioError::Malformed(_))));
|
||||
// 8-bit mono: an even data length could end in a sample or in the pad after an odd count.
|
||||
let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8);
|
||||
for (samples, ok) in [(3, true), (4, false)] {
|
||||
let mut file = u8_mono.clone();
|
||||
file.extend(std::iter::repeat_n(0x80, samples));
|
||||
assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes");
|
||||
if ok {
|
||||
// Once repaired, the size settles it.
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
let r = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(repair(file.into_inner()).unwrap(), r);
|
||||
}
|
||||
}
|
||||
// A block size that is not channels × sample bytes would count the wrong frames.
|
||||
let mut odd_align = wav.clone();
|
||||
odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes());
|
||||
assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_))));
|
||||
// Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits.
|
||||
let mut float16 = wav.clone();
|
||||
float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes());
|
||||
let mut pcm40 = wav.clone();
|
||||
pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]);
|
||||
for bad in [float16, pcm40] {
|
||||
assert!(craft_audio::decode(&bad, Some("wav")).is_err());
|
||||
assert!(matches!(repair(bad), Err(AudioError::Unsupported(_))));
|
||||
}
|
||||
// An extensible file whose subformat is PCM's tag under another GUID is not PCM.
|
||||
let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap();
|
||||
let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
|
||||
assert!(repair(ext.clone()).is_ok());
|
||||
let mut other_guid = ext.clone();
|
||||
other_guid[fmt + 39] ^= 0xFF;
|
||||
assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_))));
|
||||
// Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds.
|
||||
let mut short_cb = ext.clone();
|
||||
short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes());
|
||||
let mut wide_valid = ext.clone();
|
||||
wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes());
|
||||
for bad in [short_cb, wide_valid] {
|
||||
assert!(craft_audio::decode(&bad, Some("wav")).is_err());
|
||||
assert!(matches!(repair(bad), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
// The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM.
|
||||
let mut ambisonic = ext;
|
||||
ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]);
|
||||
assert_eq!(repair(ambisonic).unwrap().frames, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() {
|
||||
let take = sine(48_000, 2, 1_000);
|
||||
let bwf = BwfInfo::default()
|
||||
.with_description("take 3")
|
||||
.with_originator("recorder")
|
||||
.with_origination("2026-11-20", "18:30:00")
|
||||
.with_time_reference(48_000 * 66_600);
|
||||
let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap();
|
||||
let len = file.len();
|
||||
assert!(len > wav_float_header(48_000, 2, 0).unwrap().len());
|
||||
file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes()));
|
||||
file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap());
|
||||
let (info, decoded) = decode(&file, None).unwrap();
|
||||
assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600));
|
||||
file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap());
|
||||
let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone());
|
||||
assert_eq!(file, encode(&take, &opts).unwrap());
|
||||
let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap();
|
||||
assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len));
|
||||
assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err());
|
||||
}
|
||||
@@ -153,3 +153,39 @@ fn ffmpeg_decodes_our_alac_exactly() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quiet and silent passages at 24 and 32 bits, which our encoder codes with fewer shifted-off
|
||||
/// low bytes than Apple's reference (#1368), decode exactly in ffmpeg. The packets alternate
|
||||
/// between silence, audio within 12 bits, audio at the narrower widths' edges and full scale, so
|
||||
/// one stream changes its shift from packet to packet.
|
||||
#[test]
|
||||
fn ffmpeg_decodes_our_quiet_alac_exactly() {
|
||||
let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return };
|
||||
for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] {
|
||||
let full = input(channels, bits, 4 * 4096);
|
||||
let wav: Vec<Vec<i32>> = full
|
||||
.iter()
|
||||
.map(|c| {
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &x)| match i / 4096 {
|
||||
0 => 0,
|
||||
1 => x >> (bits - 12),
|
||||
2 => (x >> (bits - 15)) << (bits - 24),
|
||||
_ => x,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
// ffmpeg does not decode escaped 32-bit stereo frames: keep the full-scale packet for 24
|
||||
let wav: Vec<Vec<i32>> = if bits == 32 { wav.iter().map(|c| c[..3 * 4096].to_vec()).collect() } else { wav };
|
||||
let m4a = our_m4a(&wav, bits, 4096);
|
||||
let path = dir().join(format!("ours_quiet_{channels}ch_{bits}.m4a"));
|
||||
std::fs::write(&path, &m4a).unwrap();
|
||||
let theirs = ffmpeg_decode(&ff, &path, channels, bits);
|
||||
assert!(theirs == wav, "{channels} ch, {bits} bits: ffmpeg's decode differs from the input");
|
||||
if bits <= 24 {
|
||||
assert!(our_decode(&m4a, bits) == wav, "{channels} ch, {bits} bits: our decode differs");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod mp3_encoder_oracle;
|
||||
mod mpa_oracle;
|
||||
mod opus;
|
||||
mod opusenc;
|
||||
mod packet_encoder;
|
||||
mod routing_oracle;
|
||||
mod track_decoder;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
|
||||
@@ -268,9 +268,7 @@ fn extreme_inputs_stay_decodable() {
|
||||
let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw).unwrap(), &planar);
|
||||
assert!(packets.iter().all(|p| p.len() >= 3 && p.len() <= 1276), "{name} {mode:?}: packet sizes");
|
||||
let dec = decode(&enc.opus_head(), &packets);
|
||||
let peak = dec.iter().flatten().fold(0f32, |m, v| m.max(v.abs()));
|
||||
let snr = if name == "nan" { f64::NAN } else { snr_search(&planar[0], &dec[0], 2).0 };
|
||||
eprintln!("{name} {mode:?}/{bw:?} {c} ch: peak {peak:.2}, SNR {snr:.1} dB, {:.1} kb/s", bitrate(&packets) / 1000.0);
|
||||
assert_eq!(dec.len(), c, "{name} {mode:?}/{bw:?} {c} ch: decoded channels");
|
||||
assert!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the
|
||||
//! encoder gives, at the length that was encoded and with each channel on its speaker.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use craft_audio::{
|
||||
AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder,
|
||||
};
|
||||
|
||||
/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE.
|
||||
fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec<Vec<f32>> {
|
||||
(0..channels)
|
||||
.map(|c| {
|
||||
let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32;
|
||||
(0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Normalised correlation of two signals over the samples both have.
|
||||
fn correlation(a: &[f32], b: &[f32]) -> f64 {
|
||||
let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64);
|
||||
for (&x, &y) in a.iter().zip(b) {
|
||||
let (x, y) = (f64::from(x), f64::from(y));
|
||||
ab += x * y;
|
||||
aa += x * x;
|
||||
bb += y * y;
|
||||
}
|
||||
ab / (aa * bb).sqrt().max(1e-30)
|
||||
}
|
||||
|
||||
/// Encodes `input` in uneven blocks and returns the packets.
|
||||
fn encode(enc: &mut PacketEncoder, input: &[Vec<f32>]) -> Vec<EncodedPacket> {
|
||||
let frames = input[0].len();
|
||||
let mut packets = Vec::new();
|
||||
let mut at = 0;
|
||||
for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() {
|
||||
let n = n.min(frames - at);
|
||||
let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect();
|
||||
packets.extend(enc.encode(&block, n).unwrap());
|
||||
at += n;
|
||||
if at == frames {
|
||||
break;
|
||||
}
|
||||
}
|
||||
packets.extend(enc.finish().unwrap());
|
||||
packets
|
||||
}
|
||||
|
||||
/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and
|
||||
/// returns the decoded audio from the first input frame on, cut to the input's length, and the
|
||||
/// layout the decoder reports.
|
||||
fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec<f32>]) -> (PacketEncoder, Vec<Vec<f32>>, ChannelLayout) {
|
||||
let frames = input[0].len();
|
||||
let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap();
|
||||
let packets = encode(&mut enc, input);
|
||||
assert_eq!(enc.frames(), frames as u64);
|
||||
// The packets follow one another, and add up to the priming, the audio and the padding.
|
||||
let mut pts = 0;
|
||||
for p in &packets {
|
||||
assert_eq!(p.pts, pts, "{codec:?}");
|
||||
pts += u64::from(p.duration);
|
||||
}
|
||||
assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}");
|
||||
let last = packets.last().map_or(0, |p| u64::from(p.duration));
|
||||
assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding());
|
||||
|
||||
let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect();
|
||||
let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap();
|
||||
assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}");
|
||||
let mut out = vec![Vec::new(); usize::from(dec.channels())];
|
||||
for p in &packets {
|
||||
let block = dec.decode(&p.data).unwrap();
|
||||
assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to");
|
||||
for (o, c) in out.iter_mut().zip(block.channels) {
|
||||
o.extend(c);
|
||||
}
|
||||
}
|
||||
let skip = enc.priming() as usize;
|
||||
let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect();
|
||||
(enc, out, dec.layout())
|
||||
}
|
||||
|
||||
/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded.
|
||||
fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec<f32>]) -> (PacketEncoder, Vec<Vec<f32>>) {
|
||||
let (enc, out, layout) = decode_back(codec, opts, sample_rate, input);
|
||||
assert_eq!(layout, enc.layout(), "{codec:?}");
|
||||
(enc, out)
|
||||
}
|
||||
|
||||
/// Each decoded channel is its input channel, in place: it matches that channel and no other. The
|
||||
/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude.
|
||||
fn assert_in_place(codec: CodecId, input: &[Vec<f32>], output: &[Vec<f32>], least: f64) {
|
||||
for (c, got) in output.iter().enumerate() {
|
||||
let scores: Vec<f64> = input.iter().map(|want| correlation(want, got).abs()).collect();
|
||||
let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least };
|
||||
assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}");
|
||||
for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) {
|
||||
assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aac_round_trips_in_place() {
|
||||
let input = tones(48_000, 6, 30_001);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000);
|
||||
let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input);
|
||||
assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000)));
|
||||
assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6");
|
||||
assert_in_place(CodecId::Aac, &input, &out, 0.95);
|
||||
}
|
||||
|
||||
/// 16-bit ALAC is lossless: the input comes back bit for bit.
|
||||
#[test]
|
||||
fn alac_round_trips_exactly() {
|
||||
let input = tones(44_100, 6, 10_000);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1);
|
||||
let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input);
|
||||
assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1));
|
||||
assert_eq!(out, input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mp3_round_trips_in_place() {
|
||||
for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] {
|
||||
let input = tones(rate, 2, 20_000);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000);
|
||||
let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap();
|
||||
let packets = encode(&mut enc, &input);
|
||||
assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz");
|
||||
let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input);
|
||||
assert_eq!((enc.priming(), enc.extradata()), (1057, vec![]));
|
||||
assert_in_place(CodecId::Mp3, &input, &out, 0.95);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ac3_round_trips_in_place() {
|
||||
let input = tones(48_000, 6, 20_000);
|
||||
let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input);
|
||||
assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000)));
|
||||
assert_in_place(CodecId::Ac3, &input, &out, 0.9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac3_round_trips_in_place() {
|
||||
let input = tones(48_000, 6, 20_000);
|
||||
let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input);
|
||||
assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE));
|
||||
assert_in_place(CodecId::Eac3, &input, &out, 0.9);
|
||||
}
|
||||
|
||||
/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the
|
||||
/// README), at the same length.
|
||||
#[test]
|
||||
fn eac3_7_1_decodes_as_its_5_1_substream() {
|
||||
let input = tones(48_000, 8, 20_000);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1);
|
||||
let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input);
|
||||
assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE));
|
||||
assert!(out.iter().all(|c| c.len() == 20_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opus_round_trips_in_place() {
|
||||
for channels in [1, 2] {
|
||||
let input = tones(48_000, channels, 20_000);
|
||||
let opts = EncodeOptions::default().with_bitrate(128_000);
|
||||
let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input);
|
||||
let head = enc.extradata();
|
||||
assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming()));
|
||||
assert_in_place(CodecId::Opus, &input, &out, 0.9);
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw streams `FileEncoder` writes are the packets in a row.
|
||||
#[test]
|
||||
fn file_encoder_writes_the_packets() {
|
||||
for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] {
|
||||
let input = tones(48_000, usize::from(layout.channels()), 12_345);
|
||||
let opts = EncodeOptions::new(format).with_layout(layout);
|
||||
let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap();
|
||||
file.write(&input, 12_345).unwrap();
|
||||
let file = file.finish().unwrap().into_inner();
|
||||
let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap();
|
||||
let packets: Vec<u8> = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect();
|
||||
assert_eq!(file, packets, "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format.
|
||||
#[test]
|
||||
fn unsupported_settings_are_refused() {
|
||||
let unsupported =
|
||||
|codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_)));
|
||||
let opts = EncodeOptions::default();
|
||||
assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2));
|
||||
assert!(unsupported(CodecId::Flac, &opts, 48_000, 2));
|
||||
assert!(unsupported(CodecId::Opus, &opts, 44_100, 2));
|
||||
assert!(unsupported(CodecId::Opus, &opts, 48_000, 3));
|
||||
assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2));
|
||||
for (codec, format, rate, channels) in [
|
||||
(CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2),
|
||||
(CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0),
|
||||
(CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6),
|
||||
(CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8),
|
||||
(CodecId::Aac, EncodeFormat::Aac, 44_000, 2),
|
||||
] {
|
||||
let opts = EncodeOptions::new(format);
|
||||
let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels));
|
||||
assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}");
|
||||
assert!(packets.is_err());
|
||||
}
|
||||
assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2));
|
||||
assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2));
|
||||
// A layout for another channel count is the caller's mistake.
|
||||
assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_))));
|
||||
}
|
||||
|
||||
/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was.
|
||||
#[test]
|
||||
fn misuse_is_an_error() {
|
||||
let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap();
|
||||
let short = [vec![0.0f32; 10], vec![0.0; 5]];
|
||||
assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_))));
|
||||
assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_))));
|
||||
assert_eq!(enc.frames(), 0);
|
||||
assert!(enc.encode(&short, 5).unwrap().is_empty());
|
||||
assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets");
|
||||
assert!(matches!(enc.finish(), Err(AudioError::Encode(_))));
|
||||
assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_))));
|
||||
// An encoder given nothing returns nothing: no packets, no frames and no padding. `priming`
|
||||
// is the codec's delay either way, so it equals that of an encoder that was given input.
|
||||
for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] {
|
||||
let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap();
|
||||
assert!(enc.finish().unwrap().is_empty(), "{codec:?}");
|
||||
assert_eq!((enc.frames(), enc.padding()), (0, 0), "{codec:?}");
|
||||
let mut fed = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap();
|
||||
fed.encode(&short, 5).unwrap();
|
||||
fed.finish().unwrap();
|
||||
assert_eq!(enc.priming(), fed.priming(), "{codec:?}");
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,9 @@ mod mp2_encoder_oracle;
|
||||
#[cfg(feature = "qoa")]
|
||||
#[path = "qoa_oracle.rs"]
|
||||
mod qoa_oracle;
|
||||
#[cfg(feature = "s302m")]
|
||||
#[path = "s302m_oracle.rs"]
|
||||
mod s302m_oracle;
|
||||
#[cfg(feature = "sbc")]
|
||||
#[path = "sbc_oracle.rs"]
|
||||
mod sbc_oracle;
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! SMPTE 302M (feature `s302m`) against ffmpeg (oracle; skipped when ffmpeg is absent, a failure
|
||||
//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): we decode the packets ffmpeg's encoder puts in a transport
|
||||
//! stream to the samples ffmpeg decodes, our encoder writes the same bytes, and ffmpeg decodes
|
||||
//! packets of ours (patched into a transport stream) to our samples.
|
||||
|
||||
use craft_audio::s302m::{Encoder, decode, parse_header};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn signal(channels: usize, frames: usize, seed: u32) -> Vec<i32> {
|
||||
let mut x = seed | 1;
|
||||
let mut out = Vec::with_capacity(frames * channels);
|
||||
for i in 0..frames {
|
||||
for c in 0..channels {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
let tone = ((i as f64) * (0.03 + 0.011 * c as f64)).sin() * 0.6;
|
||||
let noise = f64::from(x % 2000) / 2000.0 - 0.5;
|
||||
out.push(((tone + 0.3 * noise) * f64::from(i32::MAX)) as i32);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_every_size_and_channel_count() {
|
||||
for channels in [2usize, 4, 6, 8] {
|
||||
for bits in [16u32, 20, 24] {
|
||||
let max = 1i64 << (bits - 1);
|
||||
let mut e = Encoder::new(channels, bits).expect("encoder");
|
||||
let frames = 500;
|
||||
let samples: Vec<i32> = signal(channels, frames, 3).iter().map(|&v| (i64::from(v) * max / (1 << 31)) as i32).collect();
|
||||
let mut all = Vec::new();
|
||||
for chunk in samples.chunks(channels * 193) {
|
||||
let p = e.encode(chunk).expect("encode");
|
||||
let d = decode(&p).expect("decode");
|
||||
assert_eq!((d.header.channels, d.header.bits), (channels, bits));
|
||||
all.extend(d.samples);
|
||||
}
|
||||
assert_eq!(all, samples, "{channels}ch {bits} bits");
|
||||
}
|
||||
}
|
||||
// the extremes
|
||||
for bits in [16u32, 20, 24] {
|
||||
let (lo, hi) = (-(1i32 << (bits - 1)), (1i32 << (bits - 1)) - 1);
|
||||
let mut e = Encoder::new(2, bits).expect("encoder");
|
||||
assert_eq!(decode(&e.encode(&[lo, hi, hi, lo, 0, -1]).expect("encode")).expect("decode").samples, vec![lo, hi, hi, lo, 0, -1]);
|
||||
assert!(e.encode(&[hi + 1, 0]).is_err());
|
||||
assert!(e.encode(&[lo - 1, 0]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_packet_size_limit_and_headers_are_checked() {
|
||||
let mut e = Encoder::new(2, 16).expect("encoder");
|
||||
let max = e.max_frames();
|
||||
assert!(e.encode(&vec![0; max * 2]).is_ok());
|
||||
assert!(e.encode(&vec![0; (max + 1) * 2]).is_err());
|
||||
let p = Encoder::new(8, 24).expect("encoder").channel_id(0x55).encode(&[0; 8]).expect("encode");
|
||||
let h = parse_header(&p).expect("header");
|
||||
assert_eq!((h.channels, h.channel_id, h.bits, h.audio_bytes), (8, 0x55, 24, 28));
|
||||
assert_eq!(h.frame_bytes(), 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_packets_are_errors_never_panics() {
|
||||
let mut e = Encoder::new(4, 24).expect("encoder");
|
||||
let p = e.encode(&signal(4, 40, 5).iter().map(|&v| v >> 8).collect::<Vec<_>>()).expect("encode");
|
||||
for n in 0..p.len() {
|
||||
let _ = decode(&p[..n]);
|
||||
}
|
||||
let mut x = 9u32;
|
||||
for i in 0..p.len() {
|
||||
let mut d = p.clone();
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
d[i] ^= (x >> 8) as u8 | 1;
|
||||
let _ = decode(&d);
|
||||
}
|
||||
assert!(decode(&[]).is_err());
|
||||
assert!(decode(&[0xFF, 0xFF, 0, 0, 1, 2, 3]).is_err());
|
||||
assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err(), "the reserved size code");
|
||||
}
|
||||
|
||||
// ---- ffmpeg as the reference
|
||||
|
||||
fn ffmpeg(ff: &Path, args: &[&str]) {
|
||||
let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg");
|
||||
assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_str().expect("path").to_string()
|
||||
}
|
||||
|
||||
/// The elementary-stream bytes of every PES packet of PID 0x100 in a transport stream, each as
|
||||
/// the list of (offset in the file, length) pieces it is spread over.
|
||||
fn pes_pieces(ts: &[u8]) -> Vec<Vec<(usize, usize)>> {
|
||||
let mut out: Vec<Vec<(usize, usize)>> = Vec::new();
|
||||
for (i, p) in ts.as_chunks::<188>().0.iter().enumerate() {
|
||||
if p[0] != 0x47 || ((usize::from(p[1] & 0x1F) << 8) | usize::from(p[2])) != 0x100 {
|
||||
continue;
|
||||
}
|
||||
let mut off = 4;
|
||||
if p[3] & 0x20 != 0 {
|
||||
off += 1 + usize::from(p[4]);
|
||||
}
|
||||
if p[3] & 0x10 == 0 || off >= 188 {
|
||||
continue;
|
||||
}
|
||||
let mut start = off;
|
||||
if p[1] & 0x40 != 0 {
|
||||
// a new PES packet: skip its header (00 00 01 id, length, flags, flags, header length, header)
|
||||
assert_eq!(&p[off..off + 3], &[0, 0, 1]);
|
||||
start = off + 9 + usize::from(p[off + 8]);
|
||||
out.push(Vec::new());
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.push((i * 188 + start, 188 - start));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn gather(ts: &[u8], pieces: &[(usize, usize)]) -> Vec<u8> {
|
||||
pieces.iter().flat_map(|&(o, n)| ts[o..o + n].iter().copied()).collect()
|
||||
}
|
||||
|
||||
fn pcm_bytes(samples: &[i32], wide: bool) -> Vec<u8> {
|
||||
if wide {
|
||||
samples.iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
} else {
|
||||
samples.iter().flat_map(|&v| ((v >> 16) as i16).to_le_bytes()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn decoded_by_ffmpeg(ff: &Path, ts: &Path, out: &Path, wide: bool) -> Vec<i32> {
|
||||
ffmpeg(ff, &["-i", &s(ts), "-f", if wide { "s32le" } else { "s16le" }, "-acodec", if wide { "pcm_s32le" } else { "pcm_s16le" }, &s(out)]);
|
||||
let bytes = std::fs::read(out).expect("read");
|
||||
if wide {
|
||||
bytes.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect()
|
||||
} else {
|
||||
bytes.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("s302m");
|
||||
for (channels, bits) in [(2usize, 16u32), (2, 20), (2, 24), (4, 20), (4, 24), (6, 16), (6, 20), (8, 20), (8, 24)] {
|
||||
let name = format!("{channels}ch{bits}");
|
||||
let frames = 6000;
|
||||
let wide = bits > 16;
|
||||
let pcm = signal(channels, frames, 17);
|
||||
let raw = dir.join(format!("{name}.pcm"));
|
||||
std::fs::write(&raw, pcm_bytes(&pcm, wide)).expect("write");
|
||||
let ts = dir.join(format!("{name}.ts"));
|
||||
let ch_str = channels.to_string();
|
||||
let raw_str = s(&raw);
|
||||
let ts_str = s(&ts);
|
||||
let mut ff_args = vec![
|
||||
"-f",
|
||||
if wide { "s32le" } else { "s16le" },
|
||||
"-ar",
|
||||
"48000",
|
||||
"-ac",
|
||||
&ch_str,
|
||||
"-i",
|
||||
&raw_str,
|
||||
"-af",
|
||||
"asetnsamples=n=1024:p=0",
|
||||
"-c:a",
|
||||
"s302m",
|
||||
"-strict",
|
||||
"-2",
|
||||
];
|
||||
if bits == 20 {
|
||||
ff_args.extend(["-bits_per_raw_sample", "20"]);
|
||||
}
|
||||
ff_args.extend(["-f", "mpegts", &ts_str]);
|
||||
ffmpeg(&ff, &ff_args);
|
||||
let bytes = std::fs::read(&ts).expect("read");
|
||||
let pieces = pes_pieces(&bytes);
|
||||
assert!(pieces.len() >= 2, "{name}: {} packets", pieces.len());
|
||||
let theirs = decoded_by_ffmpeg(&ff, &ts, &dir.join(format!("{name}.out.pcm")), wide);
|
||||
|
||||
let mut enc = Encoder::new(channels, bits).expect("encoder");
|
||||
let mut ours: Vec<i32> = Vec::new();
|
||||
let mut frames_seen = 0usize;
|
||||
for pes in &pieces {
|
||||
// the ES bytes of the packet: its own size field says how much of them is the packet
|
||||
let es = gather(&bytes, pes);
|
||||
let h = parse_header(&es).expect("header");
|
||||
let packet = &es[..4 + h.audio_bytes];
|
||||
let d = decode(packet).expect("decode");
|
||||
assert_eq!((d.header.channels, d.header.bits), (channels, bits), "{name}");
|
||||
// our encoder writes the same bytes ffmpeg's does
|
||||
assert!(enc.encode(&d.samples).expect("encode") == packet, "{name}: our packet differs from ffmpeg's at frame {frames_seen}");
|
||||
frames_seen += d.samples.len() / channels;
|
||||
// 20-bit and 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not
|
||||
ours.extend(d.samples.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) }));
|
||||
}
|
||||
let n = ours.len().min(theirs.len());
|
||||
assert!(n >= (frames - 1600) * channels, "{name}: {n} samples");
|
||||
assert!(ours[..n] == theirs[..n], "{name}: our decode differs from ffmpeg's");
|
||||
|
||||
// ffmpeg decodes our packets: patch them over the same-sized ones in the stream
|
||||
let mine = signal(channels, frames, 23);
|
||||
let mut patched = bytes.clone();
|
||||
let mut enc = Encoder::new(channels, bits).expect("encoder");
|
||||
let mut expect: Vec<i32> = Vec::new();
|
||||
for pes in &pieces {
|
||||
let es = gather(&bytes, pes);
|
||||
let h = parse_header(&es).expect("header");
|
||||
let n_frames = h.audio_bytes / h.frame_bytes();
|
||||
let at = expect.len();
|
||||
let src: Vec<i32> = mine[at..at + n_frames * channels].iter().map(|&v| v >> (32 - bits)).collect();
|
||||
let packet = enc.encode(&src).expect("encode");
|
||||
assert_eq!(packet.len(), 4 + h.audio_bytes);
|
||||
expect.extend(src.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) }));
|
||||
let mut k = 0;
|
||||
for &(o, len) in pes {
|
||||
let take = len.min(packet.len() - k);
|
||||
patched[o..o + take].copy_from_slice(&packet[k..k + take]);
|
||||
k += take;
|
||||
}
|
||||
assert!(k >= packet.len());
|
||||
}
|
||||
let ours_ts = dir.join(format!("{name}.ours.ts"));
|
||||
std::fs::write(&ours_ts, patched).expect("write");
|
||||
let theirs = decoded_by_ffmpeg(&ff, &ours_ts, &dir.join(format!("{name}.ours.pcm")), wide);
|
||||
let n = expect.len().min(theirs.len());
|
||||
assert!(n >= (frames - 1600) * channels, "{name}: {n} samples");
|
||||
assert!(expect[..n] == theirs[..n], "{name}: ffmpeg decodes our packets differently");
|
||||
println!("{name}: {} PES packets, {n} samples identical both ways", pieces.len());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,11 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
|
||||
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
|
||||
| `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. |
|
||||
| `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. |
|
||||
<<<<<<< HEAD
|
||||
| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move` (also to the centre of a node named by `label` or `id`), `ui.drag` (a held press, `steps` moves and the release), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
|
||||
=======
|
||||
| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
|
||||
>>>>>>> 07a8c471ed
|
||||
| `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. |
|
||||
| `server` | `listen` (bind a port) and `serve` (a listener bound earlier), or `listen_with` / `serve_with` with `ServerLimits`: the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. |
|
||||
| `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. |
|
||||
|
||||
@@ -16,7 +16,7 @@ use crate::security;
|
||||
use crate::server::{self, Listening};
|
||||
|
||||
/// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so
|
||||
/// freeing a taken port is enough.
|
||||
/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`].
|
||||
pub const RETRY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence
|
||||
@@ -123,6 +123,10 @@ pub struct AgentLink {
|
||||
applied: Option<Option<AgentSettings>>,
|
||||
retry_at: Option<Instant>,
|
||||
retry: Duration,
|
||||
/// The token a failed start already read and checked, for its retries with the same settings;
|
||||
/// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms
|
||||
/// on the UI thread, which every retry of a taken port would otherwise pay again.
|
||||
checked_token: Option<String>,
|
||||
status: AgentLinkStatus,
|
||||
}
|
||||
|
||||
@@ -144,6 +148,7 @@ impl AgentLink {
|
||||
applied: None,
|
||||
retry_at: None,
|
||||
retry: RETRY,
|
||||
checked_token: None,
|
||||
status: AgentLinkStatus::default(),
|
||||
}
|
||||
}
|
||||
@@ -166,7 +171,12 @@ impl AgentLink {
|
||||
|
||||
/// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it
|
||||
/// on another port, stop it, or keep it while other settings change. Does nothing while `want`
|
||||
/// equals the last call's and no retry of a failed start is due.
|
||||
/// equals the last call's and no retry of a failed start is due. A token file refused as it is
|
||||
/// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still
|
||||
/// can't be used (a folder in its place, a folder that can't be written) schedules no retry:
|
||||
/// that lasts until someone changes it, and on Windows each check blocks the UI thread for
|
||||
/// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`]
|
||||
/// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again.
|
||||
pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate {
|
||||
let mut update = LinkUpdate::default();
|
||||
if self.launch.is_some() {
|
||||
@@ -174,9 +184,15 @@ impl AgentLink {
|
||||
}
|
||||
let now = motion::now();
|
||||
let retry_due = self.retry_at.is_some_and(|at| now >= at);
|
||||
if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due {
|
||||
let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want);
|
||||
if unchanged && !retry_due {
|
||||
return update;
|
||||
}
|
||||
// Only a retry with the same settings reuses the token its failed start checked: after a
|
||||
// change (agents off and on again, another port) the file may hold another token by now.
|
||||
if !unchanged {
|
||||
self.checked_token = None;
|
||||
}
|
||||
let before = (self.status.clone(), self.applied.clone().flatten());
|
||||
self.applied = Some(want.cloned());
|
||||
self.retry_at = None;
|
||||
@@ -218,6 +234,10 @@ impl AgentLink {
|
||||
update.requests = Some(requests);
|
||||
Ok(())
|
||||
}
|
||||
Err(problem @ LinkProblem::TokenFile(_)) => {
|
||||
log::warn!("{problem}");
|
||||
Err(problem)
|
||||
}
|
||||
Err(problem) => {
|
||||
log::warn!("{problem}");
|
||||
self.retry_at = Some(motion::now() + self.retry);
|
||||
@@ -229,13 +249,21 @@ impl AgentLink {
|
||||
|
||||
/// The token from the settings folder (created `0600` when missing), the server, then the
|
||||
/// connection file. Any failure leaves nothing running.
|
||||
fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
|
||||
/// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]).
|
||||
/// The token file is the link's own, so one refused as it is gets a new token (see
|
||||
/// [`fresh_token`]).
|
||||
fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?;
|
||||
let token = match self.checked_token.clone() {
|
||||
Some(token) => token,
|
||||
None => fresh_token(&token_file)?,
|
||||
};
|
||||
self.checked_token = Some(token.clone());
|
||||
let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?;
|
||||
let running = Running { server, dir: dir.to_path_buf(), port_pref };
|
||||
let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone());
|
||||
write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?;
|
||||
self.checked_token = None;
|
||||
Ok((running, requests))
|
||||
}
|
||||
|
||||
@@ -250,3 +278,22 @@ impl AgentLink {
|
||||
self.status.problem = Some(problem);
|
||||
}
|
||||
}
|
||||
|
||||
/// The token in `token_file`, created when missing. A regular file the check refuses (one an
|
||||
/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged
|
||||
/// token) is replaced with a new token, once: the token is only this link's secret, and a client
|
||||
/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted
|
||||
/// the file. Anything else in the way (a folder, a link) is reported, not removed.
|
||||
fn fresh_token(token_file: &Path) -> Result<String, LinkProblem> {
|
||||
let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()));
|
||||
let problem = match read() {
|
||||
Ok(token) => return Ok(token),
|
||||
Err(problem) => problem,
|
||||
};
|
||||
if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) {
|
||||
return Err(problem);
|
||||
}
|
||||
log::warn!("{problem}; writing a new token file");
|
||||
std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?;
|
||||
read()
|
||||
}
|
||||
@@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() {
|
||||
let mut client = ControlClient::connect(addr, TOKEN).unwrap();
|
||||
assert!(client.is_usable(), "an idle connection with nothing pending is usable");
|
||||
said.send(()).unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while client.is_usable() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
// A blocking peek (under the client's read timeout) returns once the line has arrived.
|
||||
assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived");
|
||||
assert!(!client.is_usable(), "the unasked line makes the connection unusable");
|
||||
assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()));
|
||||
assert!(client.is_broken(), "the unusable connection is closed");
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
//! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the
|
||||
//! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued
|
||||
//! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees
|
||||
//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes
|
||||
//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]).
|
||||
//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's
|
||||
//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through
|
||||
//! [`crate::screenshot::Captures`]).
|
||||
//!
|
||||
//! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch
|
||||
//! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave
|
||||
@@ -15,6 +16,7 @@
|
||||
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
use craft_ui::dialog::{DialogHost, DialogId, HeldOk};
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
@@ -133,6 +135,19 @@ pub enum Reply {
|
||||
/// A `ui.accessTree`: hold the reply until the window's settled access tree can be read
|
||||
/// ([`ControlChannel::poll_access_trees`]).
|
||||
AccessTree,
|
||||
/// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the
|
||||
/// app answers it ([`ControlChannel::poll_held`]).
|
||||
#[non_exhaustive]
|
||||
AfterHeldOk {
|
||||
/// The dialog whose OK is held.
|
||||
dialog: DialogId,
|
||||
/// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog
|
||||
/// is not the one the request confirmed.
|
||||
open: u64,
|
||||
/// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it:
|
||||
/// the earlier confirms still held for this open are answered with it.
|
||||
refused: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Reply {
|
||||
@@ -176,6 +191,7 @@ pub struct ControlChannel {
|
||||
input_waiters: Vec<Sender<ControlResponse>>,
|
||||
job_waiters: Vec<(JobId, Sender<ControlResponse>)>,
|
||||
tree_waiters: Vec<Sender<ControlResponse>>,
|
||||
held_waiters: Vec<(DialogId, u64, Sender<ControlResponse>)>,
|
||||
/// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases.
|
||||
pub captures: Captures,
|
||||
}
|
||||
@@ -183,7 +199,18 @@ pub struct ControlChannel {
|
||||
impl ControlChannel {
|
||||
/// Attach a transport's receiver (TCP, stdin, tests).
|
||||
pub fn new(rx: Receiver<ControlRequest>) -> Self {
|
||||
<<<<<<< HEAD
|
||||
Self { rx, held: None, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() }
|
||||
=======
|
||||
Self {
|
||||
rx,
|
||||
input_waiters: Vec::new(),
|
||||
job_waiters: Vec::new(),
|
||||
tree_waiters: Vec::new(),
|
||||
held_waiters: Vec::new(),
|
||||
captures: Captures::default(),
|
||||
}
|
||||
>>>>>>> 07a8c471ed
|
||||
}
|
||||
|
||||
/// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned
|
||||
@@ -202,8 +229,16 @@ impl ControlChannel {
|
||||
|
||||
/// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the
|
||||
/// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time);
|
||||
/// `document` the identity a screenshot is attributed to.
|
||||
/// `document` the identity a screenshot is attributed to. A screenshot is admitted at
|
||||
/// [`motion::now`]; [`Self::settle_at`] takes the time instead.
|
||||
pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64) {
|
||||
self.settle_at(req, outcome, document, settle_ms, motion::now());
|
||||
}
|
||||
|
||||
/// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its
|
||||
/// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to
|
||||
/// [`Captures::issue`] and [`Captures::drain`].
|
||||
pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64, now: Instant) {
|
||||
let reply = req.reply;
|
||||
match outcome {
|
||||
Reply::Done(v) => {
|
||||
@@ -212,9 +247,21 @@ impl ControlChannel {
|
||||
Reply::AfterInput => self.input_waiters.push(reply),
|
||||
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
|
||||
Reply::AccessTree => self.tree_waiters.push(reply),
|
||||
Reply::AfterHeldOk { dialog, open, refused } => {
|
||||
if let Some(reason) = refused {
|
||||
self.held_waiters.retain(|(earlier, earlier_open, tx)| {
|
||||
let answered = (*earlier, *earlier_open) == (dialog, open);
|
||||
if answered {
|
||||
let _ = tx.send(json!({"ok": false, "error": reason}));
|
||||
}
|
||||
!answered
|
||||
});
|
||||
}
|
||||
self.held_waiters.push((dialog, open, reply));
|
||||
}
|
||||
Reply::Screenshot { token, path, region, viewport } => {
|
||||
let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms };
|
||||
if let Err((reply, e)) = self.captures.admit(request, motion::now()) {
|
||||
if let Err((reply, e)) = self.captures.admit(request, now) {
|
||||
let _ = reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
}
|
||||
@@ -303,6 +350,29 @@ impl ControlChannel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success
|
||||
/// once the app accepted the dialog's held OK; once it refused it, an error whose text is the
|
||||
/// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed
|
||||
/// while it waited, also when the same dialog opened again since. A request stays held while
|
||||
/// the app has not answered. Call it in every pass after the app answered the held OKs it
|
||||
/// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a
|
||||
/// dialog the app accepted; calling it more than once in a pass is harmless.
|
||||
pub fn poll_held(&mut self, host: &DialogHost) {
|
||||
self.held_waiters.retain(|(dialog, open, reply)| {
|
||||
let answer = match host.held_state(*dialog) {
|
||||
_ if host.open_serial(*dialog) != Some(*open) => {
|
||||
json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"})
|
||||
}
|
||||
Some(HeldOk::Waiting) => return true,
|
||||
Some(HeldOk::Accepted) => json!({"ok": true, "result": null}),
|
||||
Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}),
|
||||
_ => json!({"ok": false, "error": "the app refused OK"}),
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
/// Drops the host's queued input and the step in flight, and fails every
|
||||
/// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters
|
||||
/// remain (their input was already consumed). True when anything was pending or waiting.
|
||||
@@ -343,6 +413,6 @@ impl ControlChannel {
|
||||
|
||||
/// Waiters of every kind, for `ui.inspect`'s `pending` count and tests.
|
||||
pub fn waiting(&self) -> usize {
|
||||
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending()
|
||||
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type.
|
||||
//!
|
||||
//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s
|
||||
//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its
|
||||
//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits
|
||||
//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the
|
||||
//! `id` `inspect` lists, or `"top"` for the top one; its fields are its
|
||||
//! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and
|
||||
//! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a
|
||||
//! click's would.
|
||||
@@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt};
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::control::Reply;
|
||||
use crate::protocol::Params;
|
||||
|
||||
/// The most `fields` one `ui.dialog.set` call takes.
|
||||
@@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value {
|
||||
/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field,
|
||||
/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]).
|
||||
/// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field
|
||||
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it.
|
||||
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it;
|
||||
/// a second confirm while that answer waits is refused.
|
||||
/// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape
|
||||
/// answer gives that answer, with its tag; any other dialog closes with its children with Cancel.
|
||||
pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
@@ -49,6 +52,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params:
|
||||
Some(run(host, ctx, method, params, fields))
|
||||
}
|
||||
|
||||
/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a
|
||||
/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it
|
||||
/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal
|
||||
/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once.
|
||||
pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Reply> {
|
||||
// The dialog is named before the call: a confirm that closes it may leave another dialog on top.
|
||||
let named = dialog_id(host, params).ok();
|
||||
// A refusal this confirm replaces still answers the confirms it refused.
|
||||
let refused = match named.and_then(|id| host.held_state(id)) {
|
||||
Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()),
|
||||
_ => None,
|
||||
};
|
||||
let result = dialog_method(host, ctx, method, params)?;
|
||||
let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting));
|
||||
Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) {
|
||||
Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused },
|
||||
None => Reply::from_result(result),
|
||||
})
|
||||
}
|
||||
|
||||
fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result<Value, String> {
|
||||
let params = Params(params).only(None, fields)?;
|
||||
let read = Params(¶ms);
|
||||
@@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field
|
||||
}
|
||||
},
|
||||
"ui.dialog.confirm" => {
|
||||
// A second OK while the first waits files nothing, as the disabled button shows.
|
||||
if host.held_state(id) == Some(HeldOk::Waiting) {
|
||||
return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned());
|
||||
}
|
||||
if let Some(choice) = params.get("choice") {
|
||||
host.set_json_field(ctx, id, "choice", choice.clone())?;
|
||||
}
|
||||
|
||||
@@ -9,8 +9,11 @@
|
||||
//! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept
|
||||
//! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it.
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{BufRead, Write};
|
||||
use std::io::BufRead;
|
||||
#[cfg(not(windows))]
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -322,30 +325,34 @@ fn read_token_file(path: &Path) -> Result<String, AutomationError> {
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one
|
||||
/// that caused it, with the path in its message.
|
||||
fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> {
|
||||
let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display()));
|
||||
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?;
|
||||
}
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
|
||||
// On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token
|
||||
// is written, and a file that cannot be restricted is removed rather than left for the token to go into later.
|
||||
// On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's
|
||||
// access list, and the token is written through the handle that created it.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) {
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display())));
|
||||
owner_only::current_user_sid()
|
||||
.and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes()))
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display())))
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| at(path, e))?;
|
||||
writeln!(file, "{token}").map_err(|e| at(path, e))
|
||||
}
|
||||
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// The server's token, lower-cased. Both given is
|
||||
@@ -358,8 +365,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// file can be reached by others: <why>; restrict it to its owner`), and its trimmed content is
|
||||
/// validated. A missing one is created with a generated token (parent directories created,
|
||||
/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a
|
||||
/// newline); losing that create race to another process reads the winner's file instead.
|
||||
/// newline); losing that create race to another process reads the winner's file instead. On
|
||||
/// Windows a create that does not finish in time fails (`I/O: <path>: cannot create the control
|
||||
/// token file for its owner only: <why>`), and a file it left at the path is not read as a winner's.
|
||||
pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result<String, AutomationError> {
|
||||
server_token_with(supplied, token_file, create_token_file)
|
||||
}
|
||||
|
||||
/// [`server_token`], with `create` making a missing token file.
|
||||
fn server_token_with(
|
||||
supplied: Option<&str>,
|
||||
token_file: Option<&Path>,
|
||||
create: impl FnOnce(&Path, &str) -> std::io::Result<()>,
|
||||
) -> Result<String, AutomationError> {
|
||||
if supplied.is_some() && token_file.is_some() {
|
||||
return Err(token_conflict());
|
||||
}
|
||||
@@ -373,11 +391,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result
|
||||
};
|
||||
match read_token_file(path) {
|
||||
Ok(existing) => Ok(existing.to_ascii_lowercase()),
|
||||
Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) {
|
||||
Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) {
|
||||
Ok(()) => Ok(token),
|
||||
// Another process won the create-new race.
|
||||
Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
|
||||
Err(e) => Err(e),
|
||||
// Another process won the create-new race. A file left by a create that ran out of time is this one's.
|
||||
Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
|
||||
Err(e) => Err(AutomationError::Io(e.to_string())),
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
@@ -472,21 +490,47 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> {
|
||||
stream.set_write_timeout(Some(IO_TIMEOUT))
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// A read wrapper that fails once the supplied `ServerLimits::auth_deadline` ([`AUTH_DEADLINE`] by default)
|
||||
/// passes without [`Self::authenticated`] being called, whatever the client sends meanwhile;
|
||||
/// after that only [`IO_TIMEOUT`] applies.
|
||||
#[derive(Debug)]
|
||||
=======
|
||||
/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets
|
||||
/// by hand.
|
||||
pub type DeadlineClock = std::sync::Arc<dyn Fn() -> Instant + Send + Sync>;
|
||||
|
||||
/// The real clock, [`Instant::now`].
|
||||
pub fn real_clock() -> DeadlineClock {
|
||||
std::sync::Arc::new(Instant::now)
|
||||
}
|
||||
|
||||
/// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being
|
||||
/// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies.
|
||||
>>>>>>> 07a8c471ed
|
||||
pub struct AuthDeadlineStream {
|
||||
inner: std::net::TcpStream,
|
||||
deadline: Option<std::time::Instant>,
|
||||
clock: DeadlineClock,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AuthDeadlineStream {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthDeadlineStream {
|
||||
/// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated.
|
||||
pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self {
|
||||
Self::with_clock(inner, auth_deadline, real_clock())
|
||||
}
|
||||
|
||||
/// [`Self::new`] with the deadline read against `clock` instead of the real clock.
|
||||
pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self {
|
||||
// A limit too large to represent expires at once rather than never.
|
||||
let now = Instant::now();
|
||||
Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) }
|
||||
let now = clock();
|
||||
Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock }
|
||||
}
|
||||
|
||||
/// The handshake succeeded: lift the deadline and restore the idle timeout.
|
||||
@@ -499,7 +543,7 @@ impl AuthDeadlineStream {
|
||||
impl std::io::Read for AuthDeadlineStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(deadline) = self.deadline {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
let left = deadline.saturating_duration_since((self.clock)());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time"));
|
||||
}
|
||||
|
||||
@@ -141,6 +141,12 @@ fn server_token_sources_and_validation() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
let sddl = owner_only::sddl_of(&file).unwrap();
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
|
||||
}
|
||||
assert_eq!(server_token(None, Some(&file)).unwrap(), created);
|
||||
|
||||
// An existing file's content is trimmed and lower-cased.
|
||||
@@ -163,3 +169,56 @@ fn server_token_sources_and_validation() {
|
||||
"bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE"
|
||||
);
|
||||
}
|
||||
|
||||
// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the
|
||||
// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies.
|
||||
#[trial]
|
||||
fn the_authentication_deadline_holds_whatever_the_client_sends() {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (server, _) = listener.accept().unwrap();
|
||||
server.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let start = Instant::now();
|
||||
let at = std::sync::Arc::new(std::sync::Mutex::new(start));
|
||||
let read_at = std::sync::Arc::clone(&at);
|
||||
let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap());
|
||||
let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock);
|
||||
let mut byte = [0];
|
||||
// Blank lines and partial frames, each read while the deadline is ahead.
|
||||
for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() {
|
||||
*at.lock().unwrap() = start + Duration::from_secs(3 * step as u64);
|
||||
client.write_all(sent).unwrap();
|
||||
assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline");
|
||||
}
|
||||
*at.lock().unwrap() = start + Duration::from_secs(10);
|
||||
client.write_all(b"\n").unwrap();
|
||||
let late = stream.read(&mut byte).unwrap_err();
|
||||
assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}");
|
||||
|
||||
stream.authenticated().unwrap();
|
||||
*at.lock().unwrap() = start + Duration::from_secs(60);
|
||||
assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline");
|
||||
}
|
||||
|
||||
// A token file create that runs out of time fails with its own error, even when it left a file at
|
||||
// the path: that file is not read as another process's. A create that another process beat to the
|
||||
// path reads that process's token.
|
||||
#[trial]
|
||||
fn a_token_file_create_that_runs_out_of_time_is_an_error() {
|
||||
let dir = scratch_dir("token-limit");
|
||||
let file = dir.join("token");
|
||||
let late = |p: &Path, _: &str| {
|
||||
std::fs::write(p, "partial").unwrap();
|
||||
Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display())))
|
||||
};
|
||||
let err = server_token_with(None, Some(&file), late).unwrap_err().to_string();
|
||||
assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}");
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
let beaten = |p: &Path, _: &str| {
|
||||
create_token_file(p, TOKEN).unwrap();
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"))
|
||||
};
|
||||
assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -16,8 +16,13 @@ use serde_json::{Value, json};
|
||||
use crate::control::{ControlRequest, REPLY_DEADLINE};
|
||||
use crate::protocol::{MAX_RESPONSE_BYTES, write_reply};
|
||||
use crate::security::{
|
||||
<<<<<<< HEAD
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, ConnectionPermit, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake,
|
||||
configure_stream, read_bounded_line, repeat_auth_reply,
|
||||
=======
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake,
|
||||
configure_stream, read_bounded_line, real_clock, repeat_auth_reply,
|
||||
>>>>>>> 07a8c471ed
|
||||
};
|
||||
|
||||
/// Caps on authenticated request and reply lines, and the time a connection has to authenticate.
|
||||
@@ -177,14 +182,105 @@ pub fn serve(listener: TcpListener, token: String, host: WindowHost) -> std::io:
|
||||
serve_with(listener, token, host, ServerLimits::default())
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// Serve one connection: it must authenticate ([`ServerHandshake`]) within `limits.auth_deadline` of
|
||||
/// connecting, however much it sends meanwhile; after that only the idle timeout applies.
|
||||
fn serve_connection(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, limits: ServerLimits) {
|
||||
=======
|
||||
/// [`serve`] with `auth_deadline` in place of [`AUTH_DEADLINE`], so a test sees a connection closed at the deadline
|
||||
/// without waiting the real one.
|
||||
#[doc(hidden)]
|
||||
pub fn serve_with_deadline(
|
||||
listener: TcpListener,
|
||||
token: String,
|
||||
host: WindowHost,
|
||||
auth_deadline: Duration,
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() })
|
||||
}
|
||||
|
||||
/// What a test sets on a server [`serve_with`] starts.
|
||||
#[doc(hidden)]
|
||||
pub struct ServeOptions {
|
||||
/// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]).
|
||||
pub auth_deadline: Duration,
|
||||
/// The clock the authentication deadline is read against.
|
||||
pub clock: DeadlineClock,
|
||||
/// Sent `()` each time a connection has ended: its request sender is dropped and its place under
|
||||
/// [`MAX_CONNECTIONS`] is free again.
|
||||
pub ended: Option<Sender<()>>,
|
||||
}
|
||||
|
||||
impl Default for ServeOptions {
|
||||
fn default() -> Self {
|
||||
Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test.
|
||||
#[doc(hidden)]
|
||||
pub fn serve_with(
|
||||
listener: TcpListener,
|
||||
token: String,
|
||||
host: WindowHost,
|
||||
options: ServeOptions,
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
let ServeOptions { auth_deadline, clock, ended } = options;
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let addr = listener.local_addr()?;
|
||||
// `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept
|
||||
// from before the first connection, so the first request already finds it.
|
||||
host.keep_access_tree();
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stopped = Arc::clone(&stop);
|
||||
let accept = std::thread::Builder::new().name("control server".into()).spawn(move || {
|
||||
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
|
||||
let token = Arc::new(token);
|
||||
for mut stream in listener.incoming().flatten() {
|
||||
if stopped.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
let Some(permit) = limiter.try_acquire() else {
|
||||
let _ = configure_stream(&stream);
|
||||
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"}));
|
||||
close_after_reply(&stream);
|
||||
continue;
|
||||
};
|
||||
let tx = tx.clone();
|
||||
let host = host.clone();
|
||||
let token = Arc::clone(&token);
|
||||
let clock = Arc::clone(&clock);
|
||||
let ended = ended.clone();
|
||||
std::thread::spawn(move || {
|
||||
serve_connection(stream, &token, &tx, &host, auth_deadline, clock);
|
||||
drop(tx);
|
||||
// What the last client held down would otherwise stay held with no one left to
|
||||
// release it; while another connection is live, its input is left alone.
|
||||
if permit.release() {
|
||||
host.end_injection();
|
||||
}
|
||||
if let Some(ended) = ended {
|
||||
let _ = ended.send(());
|
||||
}
|
||||
});
|
||||
}
|
||||
})?;
|
||||
Ok((rx, Listening { addr, stop, accept: Some(accept) }))
|
||||
}
|
||||
|
||||
/// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of
|
||||
/// connecting, however much it sends meanwhile; after that only the idle timeout applies.
|
||||
fn serve_connection(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) {
|
||||
>>>>>>> 07a8c471ed
|
||||
if configure_stream(&stream).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
<<<<<<< HEAD
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::new(read, limits.auth_deadline));
|
||||
=======
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock));
|
||||
>>>>>>> 07a8c471ed
|
||||
let mut out = stream;
|
||||
let mut line = String::new();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
//! when the node is gone ([`gone`]).
|
||||
//!
|
||||
//! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a
|
||||
//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves
|
||||
//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps
|
||||
//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves
|
||||
//! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go.
|
||||
//!
|
||||
//! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application
|
||||
@@ -24,9 +25,13 @@
|
||||
//!
|
||||
//! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action
|
||||
//! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a
|
||||
<<<<<<< HEAD
|
||||
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. `ui.move` to a node goes to the
|
||||
//! centre of its rect ([`access::node_rect`]). `ui.drag` is a held press, moves and a release in one request; a drag
|
||||
//! with modifiers or a pause is `ui.click {hold}`, `ui.move` and `ui.release`.
|
||||
=======
|
||||
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued.
|
||||
>>>>>>> 07a8c471ed
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -46,6 +51,12 @@ pub const MAX_CLICKS: u64 = 256;
|
||||
/// display, yet small enough that egui's pointer delta between two such points stays finite.
|
||||
pub const MAX_SCREEN_POINT: f64 = 1e6;
|
||||
|
||||
/// Most moves one `ui.drag` may ask for (`steps`).
|
||||
pub const MAX_DRAG_STEPS: u64 = 200;
|
||||
|
||||
/// The moves a `ui.drag` makes when its request names no `steps`.
|
||||
pub const DRAG_STEPS: u64 = 12;
|
||||
|
||||
/// The longest hover rest one `ui.move` may ask for (`rest`, seconds).
|
||||
pub const MAX_REST: f64 = 10.0;
|
||||
|
||||
@@ -319,6 +330,7 @@ impl Move {
|
||||
}
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// The most moves one `ui.drag` may ask for (`steps`).
|
||||
pub const MAX_DRAG_STEPS: u64 = 120;
|
||||
|
||||
@@ -365,6 +377,69 @@ impl Drag {
|
||||
host.inject_move(viewport, from.lerp(to, step as f32 / self.steps as f32), Mods::default(), 0.0);
|
||||
}
|
||||
host.inject_release(viewport, Some(to), Released::Button(self.button));
|
||||
=======
|
||||
/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release
|
||||
/// there.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Drag {
|
||||
/// Where the button goes down.
|
||||
pub from: At,
|
||||
/// Where the button comes up.
|
||||
pub to: At,
|
||||
/// The button pressed.
|
||||
pub button: PointerButton,
|
||||
/// Moves from `from` to `to`; the last one lands on `to`.
|
||||
pub steps: u64,
|
||||
/// Modifiers held from the press to the release.
|
||||
pub mods: Mods,
|
||||
}
|
||||
|
||||
impl Drag {
|
||||
/// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object
|
||||
/// `{x?, y?, coordinates?, page?, control?}` in its own space, as `ui.click` reads its point; a missing one is
|
||||
/// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button`
|
||||
/// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`];
|
||||
/// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``.
|
||||
pub fn from_params(params: &Value) -> Result<Self, String> {
|
||||
let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?;
|
||||
let p = Params(&p);
|
||||
let point = |name: &str| -> Result<At, String> {
|
||||
let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) };
|
||||
let point = Params(point).only(Some(name), &POINT)?;
|
||||
At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}"))
|
||||
};
|
||||
let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS);
|
||||
if !(1..=MAX_DRAG_STEPS).contains(&steps) {
|
||||
return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})"));
|
||||
}
|
||||
Ok(Self {
|
||||
from: point("from")?,
|
||||
to: point("to")?,
|
||||
button: button(&p)?.unwrap_or(PointerButton::Primary),
|
||||
steps,
|
||||
mods: p.modifiers(&KEY_MODIFIERS)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the
|
||||
/// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click.
|
||||
/// Both points are placed before anything is queued (a control point against the access tree the host kept for
|
||||
/// `viewport`), so a point that cannot be placed leaves no press down. When the host withdraws the rest of the
|
||||
/// gesture after its press ran, the button stays down until `ui.release`, as any held input does.
|
||||
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
|
||||
let (from, to) = (self.from.place(host, viewport, map)?, self.to.place(host, viewport, map)?);
|
||||
let steps = u16::try_from(self.steps).unwrap_or(u16::MAX);
|
||||
host.inject_click(viewport, from, self.button, 1, self.mods, true);
|
||||
for step in 1..=steps {
|
||||
let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) };
|
||||
host.inject_move(viewport, at, self.mods, 0.0);
|
||||
}
|
||||
host.inject_release(viewport, Some(to), Released::Button(self.button));
|
||||
// A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing
|
||||
// stays held.
|
||||
host.inject_click(viewport, to, self.button, 0, self.mods, false);
|
||||
>>>>>>> 07a8c471ed
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::agents::AgentLinkStatus;
|
||||
@@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::testing::Fixture;
|
||||
use craft_ui::testing::trial;
|
||||
@@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir")
|
||||
}
|
||||
|
||||
/// Waits up to five seconds for `done`.
|
||||
fn wait_for(mut done: impl FnMut() -> bool) -> bool {
|
||||
let started = motion::now();
|
||||
while !done() {
|
||||
if started.elapsed() > Duration::from_secs(5) {
|
||||
return false;
|
||||
/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has
|
||||
/// finished it and waits for the next.
|
||||
struct Ticks {
|
||||
tick: mpsc::SyncSender<()>,
|
||||
waiting: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
impl Ticks {
|
||||
/// The clock and the `tick` to give [`AgentSwitch::watch_with`].
|
||||
fn new() -> (Self, impl FnMut() -> bool + Send + 'static) {
|
||||
let (tick, ticks) = mpsc::sync_channel(0);
|
||||
let (waits, waiting) = mpsc::channel();
|
||||
let wait = move || {
|
||||
let _ = waits.send(());
|
||||
ticks.recv().is_ok()
|
||||
};
|
||||
(Self { tick, waiting }, wait)
|
||||
}
|
||||
|
||||
/// Blocks until the watch thread waits for its next poll; `false` once the thread has ended.
|
||||
fn waiting(&self) -> bool {
|
||||
// A hang guard only: the thread answers at once, so the limit is never reached by a run that works.
|
||||
match self.waiting.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(()) => true,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => false,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"),
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
|
||||
/// Runs one poll; `false` when the thread ended in it instead of waiting for the next one.
|
||||
fn poll(&self) -> bool {
|
||||
self.tick.send(()).unwrap();
|
||||
self.waiting()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent.
|
||||
@@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() {
|
||||
assert!(!AgentSwitch::fixed(false, true).allows(false));
|
||||
}
|
||||
|
||||
/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and
|
||||
/// its thread ends once the last clone is dropped.
|
||||
/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll,
|
||||
/// and its thread ends at the first poll after the last clone is dropped.
|
||||
#[trial]
|
||||
fn the_switch_wakes_once_per_change() {
|
||||
let launcher = Arc::new(AtomicBool::new(false));
|
||||
@@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
};
|
||||
let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake);
|
||||
let (ticks, tick) = Ticks::new();
|
||||
let switch = AgentSwitch::watch_with(true, probe, tick, wake);
|
||||
let clone = switch.clone();
|
||||
assert!(ticks.waiting());
|
||||
assert!(!switch.launcher());
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start");
|
||||
|
||||
launcher.store(true, Ordering::Relaxed);
|
||||
assert!(wait_for(|| clone.launcher()), "the switch follows the launcher");
|
||||
assert!(ticks.poll());
|
||||
assert!(clone.launcher(), "the switch follows the launcher");
|
||||
assert!(switch.allows(false));
|
||||
// Many polls with nothing changed.
|
||||
let polled = probes.load(Ordering::Relaxed);
|
||||
assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10));
|
||||
for _ in 0..10 {
|
||||
assert!(ticks.poll());
|
||||
}
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll");
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll");
|
||||
launcher.store(false, Ordering::Relaxed);
|
||||
assert!(wait_for(|| !switch.launcher()));
|
||||
assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2));
|
||||
assert!(ticks.poll());
|
||||
assert!(!switch.launcher());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll");
|
||||
|
||||
drop(switch);
|
||||
assert!(ticks.poll(), "a clone keeps the watch");
|
||||
drop(clone);
|
||||
// The thread sees the switch gone at its next poll and stops probing.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let after_drop = probes.load(Ordering::Relaxed);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch");
|
||||
// The thread probes once more, sees the switch gone and ends, so nothing probes after it.
|
||||
assert!(!ticks.poll(), "the watch ended with the last switch");
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended");
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
/// A published connection reads back in its documented shape, and only the process that wrote it removes it.
|
||||
@@ -308,6 +338,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() {
|
||||
TcpListener::bind(("127.0.0.1", port)).expect("the port was let go");
|
||||
}
|
||||
|
||||
/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the
|
||||
/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every
|
||||
/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again.
|
||||
#[trial]
|
||||
fn a_refused_token_file_is_not_retried_until_the_settings_change() {
|
||||
let dir = temp_dir("link-token-no-retry");
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let wanted = free_port();
|
||||
assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
|
||||
// The file is fixed, but the same settings don't look at it again.
|
||||
std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
let same = link.sync(Some(&on(u32::from(wanted))), &host);
|
||||
assert!(same.requests.is_none() && !same.changed, "no retry with the same settings");
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
|
||||
let changed = link.sync(Some(&on(0)), &host);
|
||||
assert!(changed.requests.is_some(), "a settings change tries again");
|
||||
assert_eq!(link.status().problem, None);
|
||||
}
|
||||
|
||||
/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its
|
||||
/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can
|
||||
/// connect instead of staying out until someone deletes the file (photocraft#17006).
|
||||
#[trial]
|
||||
fn a_refused_token_file_is_replaced_with_a_new_token() {
|
||||
let dir = temp_dir("link-token-refresh");
|
||||
let file = dir.path().join(TOKEN_FILE);
|
||||
std::fs::write(&file, "not a token\n").unwrap();
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
|
||||
assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status());
|
||||
assert_eq!(link.status().problem, None);
|
||||
let token = std::fs::read_to_string(&file).unwrap();
|
||||
assert_ne!(token.trim(), "not a token");
|
||||
assert_eq!(token.trim().len(), 64, "a new token: {token:?}");
|
||||
assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening"));
|
||||
}
|
||||
|
||||
/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows
|
||||
/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time.
|
||||
#[trial]
|
||||
fn a_taken_port_retry_reuses_the_checked_token() {
|
||||
let dir = temp_dir("link-token-reuse");
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = u32::from(taken.local_addr().unwrap().port());
|
||||
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
|
||||
|
||||
// Reading the file now fails, so a retry that read it would report a token file problem.
|
||||
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
drop(taken);
|
||||
let retried = link.sync(Some(&on(port)), &host);
|
||||
assert!(retried.requests.is_some(), "{:?}", link.status());
|
||||
assert_eq!(link.status().problem, None);
|
||||
|
||||
// Once a start succeeded, the next one reads the file again.
|
||||
let moved = link.sync(Some(&on(0)), &host);
|
||||
assert!(moved.requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
}
|
||||
|
||||
/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token
|
||||
/// file again, so a server never listens with a token the file no longer holds.
|
||||
#[trial]
|
||||
fn a_settings_change_reads_the_token_file_again() {
|
||||
let dir = temp_dir("link-token-settings");
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = u32::from(taken.local_addr().unwrap().port());
|
||||
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
|
||||
|
||||
assert!(!link.sync(None, &host).stopped, "nothing was running");
|
||||
// While agents are off the token file changes; here it can't be read at all, which the next start must report.
|
||||
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
drop(taken);
|
||||
let back = link.sync(Some(&on(port)), &host);
|
||||
assert!(back.requests.is_none(), "started with the token the file no longer holds");
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
}
|
||||
|
||||
/// Dropping the link stops its server and removes its connection file.
|
||||
#[trial]
|
||||
fn dropping_the_link_removes_its_connection_file() {
|
||||
|
||||
@@ -2,14 +2,19 @@
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::client::ControlClient;
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error};
|
||||
use craft_automation::protocol::{MAX_RESPONSE_BYTES, write_reply};
|
||||
use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
<<<<<<< HEAD
|
||||
use craft_automation::server::{self, ServerLimits};
|
||||
=======
|
||||
use craft_automation::server::{self, ServeOptions};
|
||||
>>>>>>> 07a8c471ed
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::testing::trial;
|
||||
@@ -130,39 +135,98 @@ fn host() -> WindowHost {
|
||||
/// sent is dispatched.
|
||||
#[trial]
|
||||
fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
|
||||
<<<<<<< HEAD
|
||||
// A short deadline, so the test does not wait out the real one.
|
||||
let deadline = Duration::from_millis(400);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bound");
|
||||
let (rx, server) = server::serve_with(listener, TOKEN.into(), host(), ServerLimits::default().auth_deadline(deadline)).expect("started");
|
||||
// Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout.
|
||||
=======
|
||||
let start = motion::now();
|
||||
let at = Arc::new(Mutex::new(start));
|
||||
let read_at = Arc::clone(&at);
|
||||
let (ended, connection_ended) = channel();
|
||||
// Each read of the clock is announced, so the test moves it only after the connection has set its deadline.
|
||||
let (read, clock_read) = channel();
|
||||
let clock = Arc::new(move || {
|
||||
let now = *read_at.lock().expect("the clock");
|
||||
let _ = read.send(());
|
||||
now
|
||||
});
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
>>>>>>> 07a8c471ed
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
let started = motion::now();
|
||||
let mut closed = false;
|
||||
for i in 0..1000 {
|
||||
let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " };
|
||||
if stream.write_all(byte).is_err() {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let served = started.elapsed();
|
||||
assert!(closed, "the trickle did not keep the connection open");
|
||||
assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline");
|
||||
// Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses.
|
||||
stream.write_all(b"\n \n ").expect("written");
|
||||
*at.lock().expect("the clock") = start + Duration::from_secs(10);
|
||||
// The server may already have closed when this is written; if not, it wakes the server's read.
|
||||
let _ = stream.write_all(b" ");
|
||||
assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline");
|
||||
assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error.
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout.
|
||||
/// A server that closes with input still unread makes the kernel send a reset, so the read fails with
|
||||
/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows).
|
||||
fn is_closed(reader: &mut impl BufRead) -> bool {
|
||||
let mut line = String::new();
|
||||
matches!(reader.read_line(&mut line), Ok(0))
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(read) => read == 0,
|
||||
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader whose every read fails with the given error kind.
|
||||
struct Failing(std::io::ErrorKind);
|
||||
|
||||
impl std::io::Read for Failing {
|
||||
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A reset or aborted connection counts as closed; a read timeout does not.
|
||||
#[trial]
|
||||
fn a_reset_connection_counts_as_closed() {
|
||||
use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock};
|
||||
assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close");
|
||||
assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close");
|
||||
assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close");
|
||||
assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close");
|
||||
}
|
||||
|
||||
/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no
|
||||
/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not
|
||||
/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle
|
||||
/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout
|
||||
/// instead of after 10 seconds.
|
||||
fn serve_counting_ends() -> (Receiver<ControlRequest>, server::Listening, Receiver<()>) {
|
||||
let (ended, connection_ended) = channel();
|
||||
let start = motion::now();
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
(rx, server, connection_ended)
|
||||
}
|
||||
|
||||
/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected
|
||||
/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched.
|
||||
fn nothing_more_dispatched(rx: &Receiver<ControlRequest>, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool {
|
||||
drop(server);
|
||||
for _ in 0..connections {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended");
|
||||
}
|
||||
rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected)
|
||||
}
|
||||
|
||||
/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of
|
||||
/// the open ones ends, its place serves a new connection.
|
||||
#[trial]
|
||||
fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let connect = || {
|
||||
let stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
@@ -181,20 +245,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
|
||||
drop(open.pop());
|
||||
// The server frees the place when it reads the close; a new connection is served once it has.
|
||||
let started = motion::now();
|
||||
let served = loop {
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let reply = read_json(&mut reader).expect("a reply");
|
||||
if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) {
|
||||
break reply;
|
||||
}
|
||||
assert_eq!(reply["error"], "connection limit reached", "{reply}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended");
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let served = read_json(&mut reader).expect("a reply");
|
||||
assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
drop((stream, reader));
|
||||
drop(open);
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// Peers refused at the connection limit that stay connected without sending anything do not hold up the refusals after
|
||||
@@ -248,6 +306,7 @@ fn a_refused_first_frame_closes_the_connection() {
|
||||
/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app.
|
||||
#[trial]
|
||||
fn a_browser_post_never_reaches_the_app() {
|
||||
<<<<<<< HEAD
|
||||
// Far longer than the trial, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server) = server::serve_with(
|
||||
TcpListener::bind("127.0.0.1:0").expect("bound"),
|
||||
@@ -256,6 +315,10 @@ fn a_browser_post_never_reaches_the_app() {
|
||||
ServerLimits::default().auth_deadline(Duration::from_secs(60)),
|
||||
)
|
||||
.expect("started");
|
||||
=======
|
||||
// The server's clock stands still, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
>>>>>>> 07a8c471ed
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
@@ -273,7 +336,8 @@ fn a_browser_post_never_reaches_the_app() {
|
||||
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
|
||||
};
|
||||
assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}");
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app");
|
||||
drop((stream, reader));
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app");
|
||||
}
|
||||
|
||||
/// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed.
|
||||
@@ -473,19 +537,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() {
|
||||
let mut client = ControlClient::connect(addr, TOKEN).expect("connected");
|
||||
capture_state(&mut client, &client_doc, &client_doc["states"][0], "new")
|
||||
});
|
||||
let mut channel = ControlChannel::new(requests);
|
||||
// Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it.
|
||||
let (forward, forwarded) = channel();
|
||||
let mut channel = ControlChannel::new(forwarded);
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
let started = motion::now();
|
||||
while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) {
|
||||
while let Some(req) = channel.next_request() {
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))),
|
||||
_ => Reply::from_result(Ok(Value::Null)),
|
||||
};
|
||||
channel.settle(req, reply, None, 0.0);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
while seen.len() < 4 {
|
||||
forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded");
|
||||
let req = channel.next_request().expect("the forwarded request is dispatched");
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))),
|
||||
_ => Reply::from_result(Ok(Value::Null)),
|
||||
};
|
||||
channel.settle(req, reply, None, 0.0);
|
||||
}
|
||||
let reply = client.join().expect("client ran").expect("the capture replied");
|
||||
assert_eq!(
|
||||
@@ -588,12 +652,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() {
|
||||
/// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped.
|
||||
#[trial]
|
||||
fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app");
|
||||
assert_eq!(req.method, "test.once");
|
||||
req.reply.send(json!({"ok": true, "result": "once"})).expect("replied");
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once");
|
||||
rx
|
||||
});
|
||||
let (mut stream, mut reader) = authenticated(server.addr);
|
||||
stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written");
|
||||
@@ -602,7 +666,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once")));
|
||||
let mut rest = String::new();
|
||||
assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}");
|
||||
handler.join().expect("handler ran");
|
||||
let rx = handler.join().expect("handler ran");
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once");
|
||||
}
|
||||
|
||||
/// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new
|
||||
@@ -610,6 +675,7 @@ fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
#[trial]
|
||||
fn idle_unauthenticated_connections_are_limited() {
|
||||
use craft_automation::security::MAX_CONNECTIONS;
|
||||
<<<<<<< HEAD
|
||||
// Far longer than the trial, so only the limit refuses.
|
||||
let (rx, server) = server::serve_with(
|
||||
TcpListener::bind("127.0.0.1:0").expect("bound"),
|
||||
@@ -618,6 +684,10 @@ fn idle_unauthenticated_connections_are_limited() {
|
||||
ServerLimits::default().auth_deadline(Duration::from_secs(60)),
|
||||
)
|
||||
.expect("started");
|
||||
=======
|
||||
// The server's clock stands still, so only the limit refuses.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
>>>>>>> 07a8c471ed
|
||||
let idle: Vec<TcpStream> = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect();
|
||||
// Admission is counted by the accept thread: it is done once the next connection is answered.
|
||||
let refused = |addr| {
|
||||
@@ -630,18 +700,14 @@ fn idle_unauthenticated_connections_are_limited() {
|
||||
assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}");
|
||||
drop(idle);
|
||||
// The freed slots go back as the closed connections are noticed.
|
||||
let started = motion::now();
|
||||
loop {
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
// A refused connection may already be closed when the request is written (Windows resets it).
|
||||
let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}});
|
||||
if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) {
|
||||
break;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "no slot came back");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
for _ in 0..MAX_CONNECTIONS {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended");
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again");
|
||||
drop((stream, reader));
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1));
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
//! `ui.dialog.*` on typed dialogs through one generic path.
|
||||
|
||||
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse};
|
||||
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect};
|
||||
use craft_ui::contract::{Bind, SaveKey};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt};
|
||||
use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt};
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use craft_ui::runtime::env::{Label, Word};
|
||||
use craft_ui::testing::trial;
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
@@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() {
|
||||
assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom")));
|
||||
}
|
||||
|
||||
const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists");
|
||||
|
||||
/// The open parameter dialog `id` names.
|
||||
fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog {
|
||||
host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::<HostedParamDialog>()).expect("the held dialog is open")
|
||||
}
|
||||
|
||||
/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered,
|
||||
/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog
|
||||
/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a
|
||||
/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once.
|
||||
#[trial]
|
||||
fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() {
|
||||
let ctx = Context::default();
|
||||
let mut host = DialogHost::new();
|
||||
let (_requests, rx) = channel();
|
||||
let mut control = ControlChannel::new(rx);
|
||||
let dialog = |ctx: &Context, held: bool| {
|
||||
let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| {
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields))
|
||||
});
|
||||
if held { dialog.held_ok() } else { dialog }
|
||||
};
|
||||
let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver<ControlResponse> {
|
||||
let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()}));
|
||||
let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method");
|
||||
control.settle(request, outcome, None, 0.0);
|
||||
reply
|
||||
};
|
||||
|
||||
let id = host.open(dialog(&ctx, true));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
control.poll_held(&host);
|
||||
assert!(reply.try_recv().is_err(), "the reply waits for the app's answer");
|
||||
assert_eq!(control.waiting(), 1);
|
||||
let again = confirm(&mut host, &mut control, id);
|
||||
assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused");
|
||||
assert_eq!(control.waiting(), 1);
|
||||
assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app");
|
||||
held(&mut host, id).answer_ok(Err(Label::from(TAKEN)));
|
||||
control.poll_held(&host);
|
||||
assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"})));
|
||||
assert_eq!(control.waiting(), 0);
|
||||
|
||||
// A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal.
|
||||
let first = confirm(&mut host, &mut control, id);
|
||||
assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal");
|
||||
held(&mut host, id).answer_ok(Err(Label::from(TAKEN)));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"})));
|
||||
assert_eq!(control.waiting(), 1);
|
||||
assert!(held(&mut host, id).take_ok().is_some());
|
||||
held(&mut host, id).answer_ok(Ok(()));
|
||||
control.poll_held(&host);
|
||||
assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})));
|
||||
assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes");
|
||||
assert!(matches!(host.take_keyed::<HostedParamDialog>(), Some((DialogResult::Ok(_), _))));
|
||||
|
||||
let id = host.open(dialog(&ctx, true));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
control.poll_held(&host);
|
||||
let closed = reply.try_recv().expect("a closed dialog answers the held confirm");
|
||||
assert_eq!(closed["ok"], false);
|
||||
assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}");
|
||||
host.take_keyed::<HostedParamDialog>();
|
||||
|
||||
// The same dialog opened again is a new open: its answer is not the closed one's.
|
||||
let id = host.open(dialog(&ctx, true));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id");
|
||||
assert_eq!(control.waiting(), 1);
|
||||
control.poll_held(&host);
|
||||
let closed = reply.try_recv().expect("the closed open's confirm is answered");
|
||||
assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}");
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
host.take_keyed::<HostedParamDialog>();
|
||||
|
||||
let id = host.open(dialog(&ctx, false));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once");
|
||||
assert_eq!(control.waiting(), 0);
|
||||
}
|
||||
|
||||
/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that
|
||||
/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread.
|
||||
#[trial]
|
||||
|
||||
@@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app
|
||||
/// also passes to `issue` and `drain`, not from the wall clock.
|
||||
#[trial]
|
||||
fn a_screenshot_settled_at_a_time_counts_from_that_time() {
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
|
||||
use craft_automation::screenshot::ScreenshotParams;
|
||||
use serde_json::json;
|
||||
|
||||
let ctx = Context::default();
|
||||
// An app clock ahead of the wall clock.
|
||||
let arrived = motion::now() + Duration::from_secs(60);
|
||||
let (_transport, requests) = channel();
|
||||
let mut control = ControlChannel::new(requests);
|
||||
control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0));
|
||||
let (request, rx) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
let params = ScreenshotParams::from_params(&json!({})).expect("no params");
|
||||
control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived);
|
||||
assert!(rx.try_recv().is_err(), "the reply waits for the capture");
|
||||
|
||||
let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None);
|
||||
assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::<Vec<_>>());
|
||||
assert!(callbacks.is_empty(), "not issued inside its settle delay");
|
||||
assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline");
|
||||
let finished = control.captures.drain(arrived + DEADLINE, None);
|
||||
assert_eq!(finished.len(), 1);
|
||||
assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0]));
|
||||
}
|
||||
|
||||
/// Cancelling releases the budget at once; an image that arrives afterwards is dropped.
|
||||
#[trial]
|
||||
fn cancellation_releases_the_budget_and_drops_a_late_image() {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest,
|
||||
//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest,
|
||||
//! document coordinates and input-method compositions, as the passes see them, and the params refused before
|
||||
//! anything is queued.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
<<<<<<< HEAD
|
||||
use craft_automation::access::NO_TREE;
|
||||
=======
|
||||
use craft_automation::access::{NO_CONTROL, NO_TREE};
|
||||
>>>>>>> 07a8c471ed
|
||||
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::runtime::egui::injected::hook_without_pass;
|
||||
@@ -123,6 +127,7 @@ fn a_held_press_stays_down_until_its_release() {
|
||||
assert!(!rig.now().primary_down, "a click without hold releases");
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// `ui.drag` presses at its start, moves with the button down through `steps` points towards its end, each on a pass
|
||||
/// of its own, and lets go at the end. Its points are mapped as every request's are.
|
||||
#[trial]
|
||||
@@ -144,6 +149,52 @@ fn a_drag_presses_moves_held_and_releases_at_its_end() {
|
||||
});
|
||||
assert_eq!(released, Some(to), "the release is at the mapped end");
|
||||
assert!(passes.last().is_some_and(|pass| !pass.primary_down), "nothing stays held");
|
||||
=======
|
||||
/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its
|
||||
/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point.
|
||||
#[trial]
|
||||
fn a_drag_presses_moves_in_steps_and_releases_at_its_end() {
|
||||
let mut rig = Rig::new();
|
||||
rig.fx.settle();
|
||||
rig.take();
|
||||
let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point");
|
||||
rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true}));
|
||||
let after = rig.now();
|
||||
let events: Vec<Event> = rig.take().into_iter().flat_map(|pass| pass.events).collect();
|
||||
let buttons: Vec<(Pos2, bool, bool)> = events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift");
|
||||
let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. }));
|
||||
let moves: Vec<Pos2> = held
|
||||
.take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. }))
|
||||
.filter_map(|event| match event {
|
||||
Event::PointerMoved(at) => Some(*at),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}");
|
||||
assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}");
|
||||
assert_eq!(moves.last(), Some(&to), "the last step lands on `to`");
|
||||
assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held");
|
||||
}
|
||||
|
||||
/// A drag keeps its modifiers held after its release while other input stays down, as a click does.
|
||||
#[trial]
|
||||
fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() {
|
||||
let mut rig = Rig::new();
|
||||
rig.send("ui.key", json!({"key": "Space", "hold": true}));
|
||||
rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true}));
|
||||
let after = rig.now();
|
||||
assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up");
|
||||
assert!(after.shift, "the modifiers stay with the held key");
|
||||
rig.send("ui.release", json!({}));
|
||||
assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go");
|
||||
>>>>>>> 07a8c471ed
|
||||
}
|
||||
|
||||
/// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go.
|
||||
@@ -315,6 +366,7 @@ fn document_points_need_a_canvas() {
|
||||
assert_eq!(screen, Some(Ok(())));
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// The reply a waiter on `method` gets once `channel` polls `rig`'s host after its passes ran out of input.
|
||||
fn answer_after_input(rig: &mut Rig, channel: &mut craft_automation::control::ControlChannel, reply: &std::sync::mpsc::Receiver<Value>) -> Value {
|
||||
let host = rig.host();
|
||||
@@ -332,6 +384,30 @@ fn answer_after_input(rig: &mut Rig, channel: &mut craft_automation::control::Co
|
||||
/// application withdraws the input because its document or layout changed: its point now means another place. The
|
||||
/// integration's preserved copy leaves the input, the rest of the click goes with it, no button stays down, and the
|
||||
/// waiter fails with `TARGET_CHANGED`.
|
||||
=======
|
||||
/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. That holds
|
||||
/// for a document end without a canvas and for a control end that names no control of the window.
|
||||
#[trial]
|
||||
fn a_drag_with_an_end_it_cannot_place_queues_no_press() {
|
||||
let mut rig = Rig::new();
|
||||
rig.fx.settle();
|
||||
let (host, ctx) = (rig.host(), rig.fx.ctx().clone());
|
||||
let none = |_: usize, _: Pos2| None;
|
||||
let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}});
|
||||
assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned())));
|
||||
assert!(host.injected_idle());
|
||||
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing");
|
||||
let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}});
|
||||
let answer = input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &map);
|
||||
assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}");
|
||||
assert!(host.injected_idle());
|
||||
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control queued nothing");
|
||||
}
|
||||
|
||||
/// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application
|
||||
/// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key
|
||||
/// stays down, and the waiters fail with `TARGET_CHANGED`.
|
||||
>>>>>>> 07a8c471ed
|
||||
#[trial]
|
||||
fn a_click_at_a_point_is_withdrawn_when_its_target_changes() {
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
|
||||
@@ -419,6 +495,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() {
|
||||
("ui.move", json!({"x": 10, "y": 10, "rest": "long"})),
|
||||
("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})),
|
||||
("ui.move", json!({"x": 10, "y": -far})),
|
||||
("ui.drag", json!({"from": {"x": 10}})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})),
|
||||
("ui.key", json!({"key": "A", "hold": true, "nudge": 1})),
|
||||
("ui.key", json!({"key": 5})),
|
||||
("ui.key", json!({"key": "NoSuchKey", "hold": true})),
|
||||
|
||||
@@ -101,10 +101,12 @@ impl RulerUnits {
|
||||
(position - zero) * self.per_doc
|
||||
}
|
||||
|
||||
/// The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers;
|
||||
/// a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under [`TickLabels::Distance`] a
|
||||
/// smaller step takes at least two (PhotoCraft's `0.50`), more when it has them (0.025), and every tick takes them
|
||||
/// all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a sixteenth-inch ruler).
|
||||
/// The least and most decimals a ruler writes a tick of labelled step `step` with.
|
||||
///
|
||||
/// Whole ticks are whole numbers; a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under
|
||||
/// [`TickLabels::Distance`] a smaller step takes at least two (PhotoCraft's `0.50`), more when it has them
|
||||
/// (0.025), and every tick takes them all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a
|
||||
/// sixteenth-inch ruler).
|
||||
pub fn label_decimals(&self, step: f64) -> RangeInclusive<usize> {
|
||||
let most = match self.ticks {
|
||||
Ticks::Decimal { whole: true } => 0,
|
||||
|
||||
@@ -154,10 +154,10 @@ impl Codec for PlainText {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader a caller adds for words that stand for numbers.
|
||||
/// A caller's text-to-number reader.
|
||||
type Custom = Arc<dyn Fn(&str) -> Option<f64> + Send + Sync>;
|
||||
|
||||
/// An optional number: empty text is `None`; anything else reads through a [`Reader`].
|
||||
/// An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`].
|
||||
#[derive(Clone)]
|
||||
pub struct NumberCodec {
|
||||
reader: Reader,
|
||||
@@ -165,6 +165,8 @@ pub struct NumberCodec {
|
||||
/// Every decimal place is written, trailing zeros included.
|
||||
fixed: bool,
|
||||
custom: Option<Custom>,
|
||||
/// An authoritative reader for the complete, trimmed, non-empty input.
|
||||
primary: Option<Custom>,
|
||||
/// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]).
|
||||
zoom: bool,
|
||||
/// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]).
|
||||
@@ -182,6 +184,7 @@ impl fmt::Debug for NumberCodec {
|
||||
.field("share", &self.share)
|
||||
.field("signed_zoom", &self.signed_zoom)
|
||||
.field("custom", &self.custom.is_some())
|
||||
.field("primary", &self.primary.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -193,6 +196,11 @@ impl PartialEq for NumberCodec {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
_ => false,
|
||||
};
|
||||
let same_primary = match (&self.primary, &other.primary) {
|
||||
(None, None) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
_ => false,
|
||||
};
|
||||
self.reader == other.reader
|
||||
&& self.decimals == other.decimals
|
||||
&& self.fixed == other.fixed
|
||||
@@ -200,6 +208,7 @@ impl PartialEq for NumberCodec {
|
||||
&& self.share == other.share
|
||||
&& self.signed_zoom == other.signed_zoom
|
||||
&& same_custom
|
||||
&& same_primary
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,7 +242,7 @@ const NUMBER_SAMPLE: &str = "0000.00";
|
||||
impl NumberCodec {
|
||||
/// A codec reading with `reader` and writing at most `decimals` decimal places.
|
||||
pub fn new(reader: Reader, decimals: usize) -> Self {
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false, signed_zoom: false }
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false }
|
||||
}
|
||||
|
||||
/// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown
|
||||
@@ -303,6 +312,16 @@ impl NumberCodec {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same codec with an authoritative reader for the complete, trimmed, non-empty input. It replaces the
|
||||
/// reader's expressions/relative input, zoom parsing and `or_parse`: `None` or a non-finite result rejects the
|
||||
/// input without fallback. Empty text still means `None`. Formatting and the character filter are unchanged.
|
||||
///
|
||||
/// Use this when a domain's existing grammar must own the whole value, rather than adding a word with `or_parse`.
|
||||
pub fn parse_with(mut self, parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static) -> Self {
|
||||
self.primary = Some(Arc::new(parse));
|
||||
self
|
||||
}
|
||||
|
||||
/// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of
|
||||
/// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized
|
||||
/// for any value it shows in it.
|
||||
@@ -367,6 +386,9 @@ impl Codec for NumberCodec {
|
||||
if trimmed.is_empty() {
|
||||
return Ok((None, ParseNote::default()));
|
||||
}
|
||||
if let Some(parse) = &self.primary {
|
||||
return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue);
|
||||
}
|
||||
if self.zoom {
|
||||
return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note));
|
||||
}
|
||||
|
||||
@@ -449,8 +449,9 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = column.groups.remove(group);
|
||||
let part = !column.groups.is_empty();
|
||||
let id = self.drop_if_empty(&place);
|
||||
return Ok(Moving { id, ..Moving::taken(taken, source) });
|
||||
return Ok(Moving { id, part, ..Moving::taken(taken, source) });
|
||||
};
|
||||
if let Some(Node::Stack { entries }) = self.node_of_mut(&place)
|
||||
&& entries.len() > 1
|
||||
@@ -478,14 +479,14 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
if columns.is_empty() {
|
||||
self.take_node(&path);
|
||||
}
|
||||
Ok(Moving { column: taken, id: None })
|
||||
Ok(Moving { column: taken, id: None, part: false })
|
||||
}
|
||||
Some(PanelPlace::Floating { window, .. }) => {
|
||||
if window >= self.floating.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = self.floating.remove(window);
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) })
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id), part: false })
|
||||
}
|
||||
Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement),
|
||||
}
|
||||
@@ -500,7 +501,8 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating,
|
||||
/// keeps the moving column's state; groups that join a column take that column's.
|
||||
/// keeps the moving column's state, expanded when they are part of a collapsed column; groups that join a column
|
||||
/// take that column's.
|
||||
/// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]).
|
||||
pub(super) fn insert_moving(&mut self, moving: Moving<P>, to: Target<P>, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> {
|
||||
let mut moving = moving;
|
||||
@@ -517,7 +519,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
Some(id) => id,
|
||||
None => self.fresh_window_id(),
|
||||
};
|
||||
let window = Floating::new(id, Column { width: None, ..moving.column }, rect);
|
||||
let window = Floating::new(id, moving.into_window_column(), rect);
|
||||
let edge = edge.filter(|_| window.column.iconic);
|
||||
self.floating.push(Floating { edge, ..window });
|
||||
Ok(())
|
||||
@@ -578,7 +580,17 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
moving.column.groups.iter_mut().for_each(|group| group.height = height);
|
||||
}
|
||||
let index = place.group_index().ok_or(DockError::InvalidPlacement)?;
|
||||
let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups;
|
||||
let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?;
|
||||
// Groups shown at a width of their own, in a floating window or an expanded column, keep it
|
||||
// as the flyout width of the collapsed column they join.
|
||||
if column.iconic
|
||||
&& !moving.column.iconic
|
||||
&& let Some(width) = moving.column.width
|
||||
{
|
||||
let flyout = (column.width != Some(width)).then_some(width);
|
||||
moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout);
|
||||
}
|
||||
let groups = &mut column.groups;
|
||||
let index = (index + usize::from(below)).min(groups.len());
|
||||
groups.splice(index..index, moving.column.groups);
|
||||
Ok(())
|
||||
|
||||
@@ -330,12 +330,14 @@ pub(super) enum Unit {
|
||||
}
|
||||
|
||||
/// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or
|
||||
/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they
|
||||
/// join keeps its own.
|
||||
/// floating, keeps that state, except that part of a collapsed column makes an expanded one (the last group of a
|
||||
/// collapsed column stays icons); a column they join keeps its own.
|
||||
pub(super) struct Moving<P> {
|
||||
pub column: Column<P>,
|
||||
/// The id of a floating window whose last group is in transit, which a new window keeps.
|
||||
pub id: Option<u64>,
|
||||
/// Panels stay in the column the groups left, so a new column made of them is expanded.
|
||||
pub part: bool,
|
||||
}
|
||||
|
||||
impl<P> Moving<P> {
|
||||
@@ -344,14 +346,26 @@ impl<P> Moving<P> {
|
||||
Self::taken(group, Column::new(Vec::new()))
|
||||
}
|
||||
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]).
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]), as all of that column.
|
||||
pub(super) fn taken(group: Group<P>, source: Column<P>) -> Self {
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None }
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None, part: false }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width.
|
||||
/// `panel` alone, taken out of a column whose state is `source`, with whether other panels stay in it.
|
||||
pub(super) fn panel(panel: P, source: (Column<P>, bool)) -> Self {
|
||||
let (column, part) = source;
|
||||
Self { part, ..Self::taken(Group::new(vec![panel], 0), column) }
|
||||
}
|
||||
|
||||
/// The column a new floating window gets: the moving column, expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_window_column(self) -> Column<P> {
|
||||
Column { width: None, iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width, and
|
||||
/// expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_column(self, width: Option<f32>) -> Column<P> {
|
||||
Column { width: self.column.width.or(width), ..self.column }
|
||||
Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
let source = self.source_of(&panel);
|
||||
// A panel the layout does not hold opens in the new window.
|
||||
let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None });
|
||||
let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) };
|
||||
let moving = Moving { id: lone, ..Moving::panel(entry.panel, source) };
|
||||
self.insert_moving(moving, Target::Float { rect, edge: None }, canvas)
|
||||
}
|
||||
Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel),
|
||||
@@ -72,7 +72,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
let entry = StackEntry { panel, open: true, height: None };
|
||||
if let Some(anchor) = anchor {
|
||||
self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
self.insert(entry, (Column::new(Vec::new()), false), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
} else if self.root.is_none() {
|
||||
self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 });
|
||||
Ok(())
|
||||
@@ -89,7 +89,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
{
|
||||
return Err(DockError::MissingTarget);
|
||||
}
|
||||
self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas)
|
||||
self.insert(StackEntry { panel, open: true, height: None }, (Column::new(Vec::new()), false), &anchor, placement, canvas)
|
||||
}
|
||||
Action::MoveFloating { panel, rect, edge } => {
|
||||
if !valid_rect(rect) {
|
||||
@@ -142,7 +142,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
to => {
|
||||
let source = self.source_of(&panel);
|
||||
let entry = self.take(&panel).ok_or(DockError::MissingPanel)?;
|
||||
self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas)
|
||||
self.insert_moving(Moving::panel(entry.panel, source), to, canvas)
|
||||
}
|
||||
},
|
||||
Action::Restore { panel, location } => {
|
||||
@@ -256,9 +256,11 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel
|
||||
/// outside a column or absent.
|
||||
pub(super) fn source_of(&self, panel: &P) -> Column<P> {
|
||||
self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place))
|
||||
/// outside a column or absent; and whether other panels stay in that column ([`Moving::part`]).
|
||||
pub(super) fn source_of(&self, panel: &P) -> (Column<P>, bool) {
|
||||
let Some(place) = self.place(panel) else { return (Column::new(Vec::new()), false) };
|
||||
let part = self.column(&place).is_some_and(|column| column.panels().any(|other| other != panel));
|
||||
(self.source_column(&place), part)
|
||||
}
|
||||
|
||||
/// The accordion entry of `panel` in the docked tree.
|
||||
@@ -327,7 +329,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
pub(super) fn insert(
|
||||
&mut self,
|
||||
entry: StackEntry<P>,
|
||||
source: Column<P>,
|
||||
source: (Column<P>, bool),
|
||||
anchor: &P,
|
||||
placement: DockPlacement<P>,
|
||||
canvas: &dyn Fn(&P) -> bool,
|
||||
@@ -338,8 +340,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
.filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_)))
|
||||
.map(<[bool]>::to_vec)
|
||||
else {
|
||||
let moving = Moving::taken(Group::new(vec![entry.panel], 0), source);
|
||||
return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
return self.insert_moving(Moving::panel(entry.panel, source), Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
};
|
||||
let root = self.root.as_mut().ok_or(DockError::MissingTarget)?;
|
||||
if let DockPlacement::Split(zone) = placement
|
||||
|
||||
@@ -42,7 +42,8 @@ pub struct Workspace<P> {
|
||||
#[serde(default)]
|
||||
hidden: Vec<(P, Location<P>)>,
|
||||
/// Floating panels, and closed panels that were floating, with the docked location each one left, so Dock Panel
|
||||
/// can return it. A closed panel's record lives as long as its `hidden` record. Saved with the workspace.
|
||||
/// can return it; a closed panel that floats records the place it would reopen at. A closed panel's record lives
|
||||
/// as long as its `hidden` record. Saved with the workspace.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
floated: Vec<(P, Location<P>)>,
|
||||
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
|
||||
@@ -264,6 +265,16 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?,
|
||||
_ => false,
|
||||
};
|
||||
// Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel
|
||||
// that would reopen in a floating window has no docked place.
|
||||
let hidden_place = match &action {
|
||||
Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed
|
||||
.restored(panel, &policy)
|
||||
.filter(|restored| !floats(&restored.layout, panel))
|
||||
.and_then(|restored| restored.layout.location(panel).ok())
|
||||
.map(|location| (panel.clone(), location)),
|
||||
_ => None,
|
||||
};
|
||||
if !reopened {
|
||||
// SetNative records where the window system has a floating window, so a lock
|
||||
// does not refuse it.
|
||||
@@ -278,6 +289,12 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
proposed.hidden.push((panel, location));
|
||||
}
|
||||
proposed.track_floated(&before);
|
||||
if let Some((panel, location)) = hidden_place
|
||||
&& floats(&proposed.layout, &panel)
|
||||
&& !proposed.floated.iter().any(|(p, _)| p == &panel)
|
||||
{
|
||||
proposed.floated.push((panel, location));
|
||||
}
|
||||
all_closed.extend(closed);
|
||||
}
|
||||
let visible: HashSet<P> = proposed.layout.panels().into_iter().cloned().collect();
|
||||
|
||||
+47
-16
@@ -1,6 +1,7 @@
|
||||
//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and
|
||||
//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens
|
||||
//! items that have a short form, then drops command items and titles from the end. All of them read no egui types.
|
||||
//! items that have a short form, in the order their host ranks, and drops command items and titles from the end.
|
||||
//! All of them read no egui types.
|
||||
|
||||
/// Tabs visible on a strip and tabs that need an overflow menu, all in original order.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -230,19 +231,39 @@ pub struct FitItem {
|
||||
pub keep: FitKeep,
|
||||
/// The extent of the item's shorter form, if it has one.
|
||||
pub short: Option<f32>,
|
||||
/// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first.
|
||||
pub short_order: u16,
|
||||
/// Whether the item keeps its full form until no more free items can leave.
|
||||
pub short_late: bool,
|
||||
}
|
||||
|
||||
impl FitItem {
|
||||
/// An item `extent` long in `section`.
|
||||
pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self {
|
||||
FitItem { extent, section, keep, short: None }
|
||||
FitItem { extent, section, keep, short: None, short_order: 0, short_late: false }
|
||||
}
|
||||
|
||||
/// The item with a shorter form `extent` long, which it takes before any free item leaves.
|
||||
/// The item with a shorter form `extent` long, which it takes before any free item leaves unless it is late.
|
||||
/// An item marked [`FitItem::short_late`] takes that form only after no free item is left to leave.
|
||||
pub const fn short(mut self, extent: f32) -> Self {
|
||||
self.short = Some(extent);
|
||||
self
|
||||
}
|
||||
|
||||
/// The item with its short form ranked `order`: lower ranks shorten first, and the last item of a rank first.
|
||||
/// Every item ranks 0 by default.
|
||||
pub const fn short_order(mut self, order: u16) -> Self {
|
||||
self.short_order = order;
|
||||
self
|
||||
}
|
||||
|
||||
/// The item takes its short form only after every free item that can leave has left.
|
||||
/// The other items go to the overflow menu before this one shortens. A free item with a late short form leaves
|
||||
/// in its turn instead.
|
||||
pub const fn short_late(mut self) -> Self {
|
||||
self.short_late = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order.
|
||||
@@ -277,11 +298,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64)
|
||||
}
|
||||
|
||||
/// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show.
|
||||
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last
|
||||
/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then
|
||||
/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long,
|
||||
/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are
|
||||
/// never listed as short. Negative and non-finite lengths count as zero.
|
||||
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest
|
||||
/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a
|
||||
/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the
|
||||
/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the
|
||||
/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back.
|
||||
/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short.
|
||||
/// Negative and non-finite lengths count as zero.
|
||||
pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit {
|
||||
let (available, gap, section_gap, overflow_extent) =
|
||||
(item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent));
|
||||
@@ -302,19 +325,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32,
|
||||
// The shadow run holds each item at the extent it takes: shortened items at their `short` extent.
|
||||
let mut run: Vec<FitItem> = items.to_vec();
|
||||
let mut short = vec![false; items.len()];
|
||||
while !fits(&run, &shown) {
|
||||
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else {
|
||||
break;
|
||||
};
|
||||
short[last] = true;
|
||||
if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) {
|
||||
item.extent = extent;
|
||||
// Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank
|
||||
// first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits.
|
||||
let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| {
|
||||
while !fits(run, shown) {
|
||||
let next = (0..items.len())
|
||||
.rev()
|
||||
.filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late)
|
||||
.min_by_key(|&at| items[at].short_order);
|
||||
let Some(next) = next else { break };
|
||||
short[next] = true;
|
||||
if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) {
|
||||
item.extent = extent;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
shorten(false, &mut run, &mut short, &shown);
|
||||
while !fits(&run, &shown) {
|
||||
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break };
|
||||
shown[last] = false;
|
||||
}
|
||||
shorten(true, &mut run, &mut short, &shown);
|
||||
let (kept, left): (Vec<usize>, Vec<usize>) = (0..items.len()).partition(|&at| shown[at]);
|
||||
let short = kept.iter().copied().filter(|&at| short[at]).collect();
|
||||
Fit { shown: kept, overflow: left, short }
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
/// The longest step motion integrates, in seconds, so a stalled pass never jumps the view.
|
||||
pub const FRAME_STEP_MAX: f64 = 0.1;
|
||||
|
||||
/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the
|
||||
/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number.
|
||||
/// The step of a pass that came `dt` seconds after the previous one, kept within `0..=FRAME_STEP_MAX`.
|
||||
///
|
||||
/// `dt` is the time between two readings of the caller's pass clock; where it is not a number, the step is 0.
|
||||
pub fn frame_step(dt: f64) -> f64 {
|
||||
if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 }
|
||||
}
|
||||
Loaded 100 of 1709 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user