mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 10:15:00 +01:00
Merge main into feat/craft-gpu-yuv
Expose the GPU YUV provider through the craft facade and keep its feature table consistent with the workspace.
This commit is contained in:
576 files changed
+33606
-2185
No files matched your search
@@ -69,8 +69,7 @@ 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/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/**"
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
Generated
+20
@@ -1822,6 +1822,7 @@ dependencies = [
|
||||
"craft-gpu-null",
|
||||
"craft-gpu-providers",
|
||||
"craft-gpu-wgpu",
|
||||
"craft-gpu-yuv",
|
||||
"craft-gridcraft-format",
|
||||
"craft-gzip",
|
||||
"craft-har",
|
||||
@@ -1909,6 +1910,7 @@ dependencies = [
|
||||
"craft-scraft-format",
|
||||
"craft-settings",
|
||||
"craft-sf2",
|
||||
"craft-shared-vec",
|
||||
"craft-sheet",
|
||||
"craft-shx",
|
||||
"craft-silhouette-studio",
|
||||
@@ -2047,6 +2049,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",
|
||||
]
|
||||
@@ -2280,12 +2283,14 @@ dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
@@ -2418,6 +2423,7 @@ name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
@@ -2653,6 +2659,7 @@ dependencies = [
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -3477,6 +3484,8 @@ dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
"craft-markdown",
|
||||
"craft-math",
|
||||
"craft-metafile",
|
||||
"craft-wordmodel",
|
||||
@@ -4093,6 +4102,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"
|
||||
@@ -4212,6 +4231,7 @@ dependencies = [
|
||||
name = "craft-suite-account"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
|
||||
@@ -32,6 +32,7 @@ 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>" }`
|
||||
|
||||
@@ -308,7 +308,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
|
||||
@@ -394,6 +394,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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"]
|
||||
|
||||
+102
-9
@@ -34,19 +34,20 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none |
|
||||
| `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
| `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 |
|
||||
@@ -313,12 +314,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;
|
||||
@@ -575,7 +640,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.
|
||||
|
||||
+25
-1
@@ -23,6 +23,9 @@
|
||||
//! (`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")]
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! 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 {
|
||||
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_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);
|
||||
}
|
||||
}
|
||||
+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")]
|
||||
|
||||
@@ -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,7 @@ 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. |
|
||||
| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `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. |
|
||||
| `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): 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()
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -174,6 +189,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,
|
||||
}
|
||||
@@ -181,7 +197,14 @@ pub struct ControlChannel {
|
||||
impl ControlChannel {
|
||||
/// Attach a transport's receiver (TCP, stdin, tests).
|
||||
pub fn new(rx: Receiver<ControlRequest>) -> Self {
|
||||
Self { rx, 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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned
|
||||
@@ -200,8 +223,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) => {
|
||||
@@ -210,9 +241,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}));
|
||||
}
|
||||
}
|
||||
@@ -291,6 +334,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.
|
||||
@@ -331,6 +397,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())?;
|
||||
}
|
||||
|
||||
@@ -8,8 +8,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};
|
||||
@@ -319,30 +322,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
|
||||
@@ -355,8 +362,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());
|
||||
}
|
||||
@@ -370,11 +388,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),
|
||||
}
|
||||
|
||||
@@ -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,25 @@ fn server_token_sources_and_validation() {
|
||||
"bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE"
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`,
|
||||
//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
|
||||
//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
|
||||
//!
|
||||
//! This module reads and validates the protocol's parameters; the window host queues the input
|
||||
//! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`],
|
||||
@@ -12,7 +12,8 @@
|
||||
//! withdraws a step queued for a document or focus that changed before the pass consumed it.
|
||||
//!
|
||||
//! 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
|
||||
@@ -22,8 +23,7 @@
|
||||
//!
|
||||
//! 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
|
||||
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a
|
||||
//! drag is `ui.click {hold}`, `ui.move` and `ui.release`.
|
||||
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -43,6 +43,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;
|
||||
|
||||
@@ -302,6 +308,71 @@ impl Move {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The most notches one `ui.wheel` turn in lines may ask for, either way.
|
||||
pub const MAX_NOTCHES: f32 = 100.0;
|
||||
|
||||
@@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V
|
||||
"ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)),
|
||||
"ui.drop" => drop_files(params, host, viewport, map),
|
||||
"ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)),
|
||||
"ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)),
|
||||
"ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)),
|
||||
"ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)),
|
||||
"ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)),
|
||||
|
||||
@@ -308,6 +308,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() {
|
||||
|
||||
@@ -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,12 +1,12 @@
|
||||
//! 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;
|
||||
|
||||
use craft_automation::access::NO_TREE;
|
||||
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
|
||||
use craft_automation::access::{NO_CONTROL, NO_TREE};
|
||||
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;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
@@ -123,6 +123,52 @@ fn a_held_press_stays_down_until_its_release() {
|
||||
assert!(!rig.now().primary_down, "a click without hold releases");
|
||||
}
|
||||
|
||||
/// `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");
|
||||
}
|
||||
|
||||
/// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go.
|
||||
#[trial]
|
||||
fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() {
|
||||
@@ -292,6 +338,25 @@ fn document_points_need_a_canvas() {
|
||||
assert_eq!(screen, Some(Ok(())));
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
@@ -358,6 +423,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})),
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -85,15 +85,12 @@ pub struct GridCursor {
|
||||
impl GridCursor {
|
||||
/// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A
|
||||
/// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share
|
||||
/// does not go below it.
|
||||
/// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns.
|
||||
pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self {
|
||||
let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0);
|
||||
let content: Vec<f32> = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect();
|
||||
let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width })
|
||||
.collect();
|
||||
let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x);
|
||||
keep_fill_least(columns, &mut widths, least);
|
||||
let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect();
|
||||
GridCursor {
|
||||
flow,
|
||||
@@ -266,6 +263,44 @@ impl GridCursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a
|
||||
/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight.
|
||||
/// The fill columns together take more than their room only when their least widths do not fit in it.
|
||||
fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) {
|
||||
let fills: Vec<(usize, f32)> = columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None })
|
||||
.collect();
|
||||
let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum();
|
||||
if !room.is_finite() {
|
||||
// Room with no bound leaves every share above its least.
|
||||
for (i, _) in &fills {
|
||||
widths[*i] = widths[*i].max(least(*i));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut raised = vec![false; columns.len()];
|
||||
loop {
|
||||
let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::<f32>();
|
||||
let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum();
|
||||
let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 };
|
||||
let mut more = false;
|
||||
for (i, weight) in &fills {
|
||||
if !raised[*i] && share(*weight) < least(*i) {
|
||||
raised[*i] = true;
|
||||
more = true;
|
||||
}
|
||||
}
|
||||
if !more {
|
||||
for (i, weight) in &fills {
|
||||
widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) };
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `columns` with each `Fill` column as a `Content` column.
|
||||
fn as_content(columns: &[ColumnWidth]) -> Vec<ColumnWidth> {
|
||||
columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect()
|
||||
@@ -288,4 +323,43 @@ mod tests {
|
||||
cursor.cell(Vec2::new(150.0, 100.0));
|
||||
assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds");
|
||||
}
|
||||
|
||||
/// The widths of one row of `columns` placed by `last`, read from the cells.
|
||||
fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec<f32> {
|
||||
let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last);
|
||||
columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
|
||||
let shares = row_widths(&columns, &fitting);
|
||||
let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0]));
|
||||
assert!(shares[0] < 120.0, "the first column's share is below its least");
|
||||
assert!(raised[0] >= 120.0, "the first column keeps its least");
|
||||
assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow");
|
||||
assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights");
|
||||
assert_eq!(raised[3], shares[3], "the content column keeps its width");
|
||||
assert_eq!(raised.iter().sum::<f32>(), 300.0, "the row fills the grid and no more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]);
|
||||
let widths = row_widths(&columns, &last);
|
||||
assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least");
|
||||
assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room");
|
||||
assert_eq!(widths.iter().sum::<f32>(), 330.0, "the row is as wide as the least widths and no wider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
|
||||
let shares = row_widths(&columns, &last);
|
||||
let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0]));
|
||||
assert_eq!(kept, shares);
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool {
|
||||
}
|
||||
|
||||
/// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can
|
||||
/// tell it from a number or an operator.
|
||||
/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch).
|
||||
pub fn is_unit_spelling(spelling: &str) -> bool {
|
||||
!spelling.is_empty() && spelling.chars().all(is_unit_char)
|
||||
let letters = spelling.strip_prefix('/').unwrap_or(spelling);
|
||||
!letters.is_empty() && letters.chars().all(is_unit_char)
|
||||
}
|
||||
|
||||
/// A unit spelling and the factor that turns its quantity into the base unit.
|
||||
@@ -41,7 +42,9 @@ struct Unit {
|
||||
/// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it
|
||||
/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest
|
||||
/// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a
|
||||
/// quantity when `px` is registered. A group separator counts only before exactly three digits.
|
||||
/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after
|
||||
/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before
|
||||
/// exactly three digits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Reader {
|
||||
decimal: char,
|
||||
@@ -213,8 +216,9 @@ impl Parse<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no
|
||||
/// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it.
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a
|
||||
/// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them,
|
||||
/// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide.
|
||||
fn quantity(&mut self, scaled: bool) -> Result<f64, NotAValue> {
|
||||
let number = self.number()?;
|
||||
self.tag = None;
|
||||
@@ -223,8 +227,11 @@ impl Parse<'_> {
|
||||
return Ok(number / 100.0);
|
||||
}
|
||||
let reader = self.reader;
|
||||
let run: Vec<char> = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect();
|
||||
let unit = (1..=run.len()).rev().find_map(|len| {
|
||||
let after = &self.chars[self.at..];
|
||||
let slash = usize::from(after.first() == Some(&'/'));
|
||||
let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count();
|
||||
let run = &after[..slash + letters];
|
||||
let unit = (1 + slash..=run.len()).rev().find_map(|len| {
|
||||
let lowered = run[..len].iter().collect::<String>().to_lowercase();
|
||||
reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit))
|
||||
});
|
||||
@@ -326,6 +333,20 @@ mod tests {
|
||||
near(&percent, "2%", 14.0);
|
||||
assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share");
|
||||
|
||||
let per_inch = Reader::new().unit_tagged("/in", 1.0, 0);
|
||||
assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in"));
|
||||
for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] {
|
||||
near(&per_inch, text, 40.0);
|
||||
}
|
||||
assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit");
|
||||
assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product");
|
||||
assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value");
|
||||
for bad in ["", "/in", "40/inch", "40/"] {
|
||||
assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value");
|
||||
}
|
||||
near(&lengths, "144/2in", 1.0);
|
||||
assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number");
|
||||
|
||||
let german = Reader::new().decimal(',').group('.');
|
||||
near(&german, "1.234,5", 1234.5);
|
||||
near(&german, "1.234.567", 1_234_567.0);
|
||||
|
||||
@@ -247,6 +247,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() {
|
||||
assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record");
|
||||
}
|
||||
|
||||
/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old
|
||||
/// group keeps its front tab; docking it then returns it to that group at its old index.
|
||||
#[test]
|
||||
fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() {
|
||||
let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0));
|
||||
let mut opened = Workspace::new(docked());
|
||||
opened.apply(Action::close(2), false, allow).unwrap();
|
||||
opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap();
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(2), false, allow).unwrap();
|
||||
workspace.apply(float, false, allow).unwrap();
|
||||
let layout = workspace.layout();
|
||||
assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. })));
|
||||
assert_eq!(group_members(layout, 3), [3]);
|
||||
assert_eq!(front(layout, 3), 3, "the old group keeps its front tab");
|
||||
assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives");
|
||||
|
||||
let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) };
|
||||
let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone());
|
||||
workspace.apply(back, false, allow).unwrap();
|
||||
assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index");
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(6), false, allow).unwrap();
|
||||
workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place");
|
||||
}
|
||||
|
||||
/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6].
|
||||
fn columns() -> Layout<u32> {
|
||||
let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]);
|
||||
|
||||
@@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() {
|
||||
assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}");
|
||||
}
|
||||
|
||||
/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a
|
||||
/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order.
|
||||
#[test]
|
||||
fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() {
|
||||
let item = |extent| FitItem::new(extent, 0, FitKeep::Free);
|
||||
let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)];
|
||||
let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0);
|
||||
assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}");
|
||||
assert!(fit.overflow.is_empty(), "{fit:?}");
|
||||
|
||||
// Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second.
|
||||
let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late();
|
||||
let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)];
|
||||
let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0);
|
||||
|
||||
let roomy = at(180.0);
|
||||
assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}");
|
||||
assert!(roomy.short.is_empty(), "{roomy:?}");
|
||||
|
||||
let tight = at(130.0);
|
||||
assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}");
|
||||
assert!(tight.short.is_empty(), "{tight:?}");
|
||||
|
||||
let narrow = at(100.0);
|
||||
assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}");
|
||||
assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}");
|
||||
|
||||
let narrowest = at(50.0);
|
||||
assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() {
|
||||
let natural = [80.0, 90.0, 85.0, 95.0, 70.0];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-captions"
|
||||
description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML/IMSC1/DFXP readers and writers with exact time, and CEA-608/708 coding"
|
||||
description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL, ASS, TTML/IMSC1/DFXP and the legacy text formats (MicroDVD, MPL2, SubViewer, VPlayer, SAMI) readers and writers with exact time, and CEA-608/708 coding"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -60,6 +60,11 @@ lists at most 20 characters per stream.
|
||||
| TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `<p>` per cue, `<br/>`, styled `<span>`s for `<i>` / `<b>` / `<u>`, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. |
|
||||
| DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). |
|
||||
| ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as `<i>`, `<b>`, `<u>`); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. |
|
||||
| MicroDVD `.sub` | yes | yes | `{first}{last}text` with frame numbers; the `{1}{1}fps` line or 23.976 fps. `\|` breaks a line; `{y:i,b,u}` and `{c:$BBGGRR}` style a line (capital `Y` / `C`: the rest of the cue too); other controls are dropped. Writing always names the rate (`WriteOptions::rate`, 23.976 by default) and styles only a line that `<i>`, `<b>` or `<u>` wraps whole. |
|
||||
| MPL2 `.mpl` | yes | yes | `[start][end]text` in tenths of a second; `\|` breaks a line, a leading `/` makes it italic. |
|
||||
| SubViewer 2 `.sbv` (also `.sub`) | yes | yes | `start,end` in hundredths of a second after the `[INFORMATION]` header; `[br]` breaks a line. Text only; no styles. |
|
||||
| VPlayer `.vpl` (also `.txt`) | yes | yes | `HH:MM:SS[.cc]=text` (`:` or a space also separate); only start times, a caption lasts to the next line (empty text clears), four seconds for the last. Text only. |
|
||||
| SAMI `.smi` | yes | yes | `<SYNC Start=ms>` blocks, ` ` clears; `<br>`, `<i>`, `<b>`, `<u>`, `<font color>` kept; first language class only. |
|
||||
|
||||
All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC
|
||||
frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`,
|
||||
//! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc)
|
||||
//! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU
|
||||
//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a
|
||||
//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`), the legacy text formats [MicroDVD](microdvd) (`.sub`), [MPL2](mpl2) (`.mpl`), [SubViewer 2](subviewer) (`.sub`), [VPlayer](vplayer) (`.vpl`) and [SAMI](sami) (`.smi`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a
|
||||
//! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252
|
||||
//! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank
|
||||
//! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `<v Speaker>`
|
||||
@@ -36,17 +36,22 @@ pub mod ass;
|
||||
pub mod cea608;
|
||||
pub mod jacosub;
|
||||
pub mod mcc;
|
||||
pub mod microdvd;
|
||||
#[cfg(feature = "mov-text")]
|
||||
pub mod mov_text;
|
||||
pub mod mpl2;
|
||||
pub mod pjs;
|
||||
pub mod realtext;
|
||||
pub mod sami;
|
||||
pub mod scc;
|
||||
pub mod srt;
|
||||
pub mod stl;
|
||||
pub mod subviewer;
|
||||
mod text;
|
||||
/// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields.
|
||||
pub use craft_timeline::time;
|
||||
pub mod ttml;
|
||||
pub mod vplayer;
|
||||
pub mod vtt;
|
||||
|
||||
pub use text::{decode_entities, entity_at, plain_text};
|
||||
@@ -77,6 +82,16 @@ pub enum Format {
|
||||
Dfxp,
|
||||
/// Advanced SubStation Alpha (also reads SubStation Alpha).
|
||||
Ass,
|
||||
/// MicroDVD (frame-numbered text).
|
||||
MicroDvd,
|
||||
/// MPL2 (times in tenths of a second).
|
||||
Mpl2,
|
||||
/// SubViewer 2.
|
||||
SubViewer,
|
||||
/// VPlayer (start times only).
|
||||
VPlayer,
|
||||
/// SAMI (HTML-like).
|
||||
Sami,
|
||||
/// Phoenix Japanimation Society (PJS) subtitles.
|
||||
Pjs,
|
||||
/// RealText streaming timed text markup.
|
||||
@@ -86,7 +101,7 @@ pub enum Format {
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub const ALL: [Format; 11] = [
|
||||
pub const ALL: [Format; 16] = [
|
||||
Format::Srt,
|
||||
Format::WebVtt,
|
||||
Format::Scc,
|
||||
@@ -95,6 +110,11 @@ impl Format {
|
||||
Format::Ttml,
|
||||
Format::Dfxp,
|
||||
Format::Ass,
|
||||
Format::MicroDvd,
|
||||
Format::Mpl2,
|
||||
Format::SubViewer,
|
||||
Format::VPlayer,
|
||||
Format::Sami,
|
||||
Format::Pjs,
|
||||
Format::RealText,
|
||||
Format::JacoSub,
|
||||
@@ -109,6 +129,11 @@ impl Format {
|
||||
Format::Ttml => "TTML (IMSC1)",
|
||||
Format::Dfxp => "DFXP (TTML1)",
|
||||
Format::Ass => "Advanced SubStation Alpha (ASS)",
|
||||
Format::MicroDvd => "MicroDVD",
|
||||
Format::Mpl2 => "MPL2",
|
||||
Format::SubViewer => "SubViewer 2",
|
||||
Format::VPlayer => "VPlayer",
|
||||
Format::Sami => "SAMI",
|
||||
Format::Pjs => "PJS",
|
||||
Format::RealText => "RealText",
|
||||
Format::JacoSub => "JACOsub",
|
||||
@@ -124,6 +149,12 @@ impl Format {
|
||||
Format::Ttml => "ttml",
|
||||
Format::Dfxp => "dfxp",
|
||||
Format::Ass => "ass",
|
||||
Format::MicroDvd => "sub",
|
||||
Format::Mpl2 => "mpl",
|
||||
// SubViewer files are `.sub` too, as MicroDVD ones are; `.sbv` tells the two apart.
|
||||
Format::SubViewer => "sbv",
|
||||
Format::VPlayer => "vpl",
|
||||
Format::Sami => "smi",
|
||||
Format::Pjs => "pjs",
|
||||
Format::RealText => "rt",
|
||||
Format::JacoSub => "jss",
|
||||
@@ -139,6 +170,11 @@ impl Format {
|
||||
"ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml),
|
||||
"dfxp" => Some(Format::Dfxp),
|
||||
"ass" | "ssa" => Some(Format::Ass),
|
||||
"sub" | "microdvd" => Some(Format::MicroDvd),
|
||||
"mpl" | "mpl2" => Some(Format::Mpl2),
|
||||
"subviewer" | "sbv" => Some(Format::SubViewer),
|
||||
"vplayer" | "vpl" => Some(Format::VPlayer),
|
||||
"smi" | "sami" => Some(Format::Sami),
|
||||
"pjs" => Some(Format::Pjs),
|
||||
"rt" | "realtext" => Some(Format::RealText),
|
||||
"jss" | "js" | "jacosub" => Some(Format::JacoSub),
|
||||
@@ -292,28 +328,51 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option<Format> {
|
||||
if head.starts_with("[Script Info]") {
|
||||
return Some(Format::Ass);
|
||||
}
|
||||
if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("<sami"))
|
||||
&& head.as_bytes().get(5).is_some_and(|&b| b.is_ascii_whitespace() || b == b'>' || b == b'/')
|
||||
{
|
||||
return Some(Format::Sami);
|
||||
}
|
||||
if subviewer::is_header(head) {
|
||||
return Some(Format::SubViewer);
|
||||
}
|
||||
if realtext::is_realtext(head) {
|
||||
return Some(Format::RealText);
|
||||
}
|
||||
let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase());
|
||||
let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some());
|
||||
let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect();
|
||||
if first_lines.first().is_some_and(|l| microdvd::is_cue(l)) {
|
||||
return Some(Format::MicroDvd);
|
||||
}
|
||||
if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) {
|
||||
return Some(Format::Mpl2);
|
||||
}
|
||||
if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) {
|
||||
return Some(Format::SubViewer);
|
||||
}
|
||||
if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) {
|
||||
return Some(Format::VPlayer);
|
||||
}
|
||||
if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) {
|
||||
return Some(Format::Pjs);
|
||||
}
|
||||
if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) {
|
||||
return Some(Format::JacoSub);
|
||||
}
|
||||
let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase());
|
||||
if (head.starts_with('<') && (head.contains("<tt ") || head.contains("<tt>") || head.contains(":tt ")))
|
||||
&& (head.contains("ns/ttml") || head.contains("ttaf1"))
|
||||
{
|
||||
let legacy = head.contains("ttaf1") || head.contains("dfxp");
|
||||
return Some(if ext.as_deref() == Some("dfxp") || (legacy && ext.as_deref() != Some("ttml")) { Format::Dfxp } else { Format::Ttml });
|
||||
}
|
||||
let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some());
|
||||
match ext.as_deref() {
|
||||
Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt),
|
||||
Some("vtt") if has_arrow_timing => Some(Format::WebVtt),
|
||||
Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None,
|
||||
Some(
|
||||
"srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami" | "pjs" | "rt"
|
||||
| "jss" | "js",
|
||||
) => None,
|
||||
_ if has_arrow_timing => Some(Format::Srt),
|
||||
_ => None,
|
||||
}
|
||||
@@ -348,6 +407,11 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result<Document> {
|
||||
Format::Mcc => mcc::parse(&text),
|
||||
Format::Ttml | Format::Dfxp => ttml::parse(&text),
|
||||
Format::Ass => ass::parse(&text),
|
||||
Format::MicroDvd => microdvd::parse(&text),
|
||||
Format::Mpl2 => mpl2::parse(&text),
|
||||
Format::SubViewer => subviewer::parse(&text),
|
||||
Format::VPlayer => vplayer::parse(&text),
|
||||
Format::Sami => sami::parse(&text),
|
||||
Format::Pjs => pjs::parse(&text),
|
||||
Format::RealText => realtext::parse(&text),
|
||||
Format::JacoSub => jacosub::parse(&text),
|
||||
@@ -389,6 +453,11 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec<u8> {
|
||||
Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(),
|
||||
Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(),
|
||||
Format::Ass => ass::write(doc).into_bytes(),
|
||||
Format::MicroDvd => microdvd::write(doc, opts.rate).into_bytes(),
|
||||
Format::Mpl2 => mpl2::write(doc).into_bytes(),
|
||||
Format::SubViewer => subviewer::write(doc).into_bytes(),
|
||||
Format::VPlayer => vplayer::write(doc).into_bytes(),
|
||||
Format::Sami => sami::write(doc).into_bytes(),
|
||||
Format::Pjs => pjs::write(doc).into_bytes(),
|
||||
Format::RealText => realtext::write(doc).into_bytes(),
|
||||
Format::JacoSub => jacosub::write(doc).into_bytes(),
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
//! MicroDVD (`.sub`): frame-numbered text.
|
||||
//!
|
||||
//! ```text
|
||||
//! {1}{1}23.976
|
||||
//! {24}{72}First line|{y:i}second line in italics
|
||||
//! ```
|
||||
//!
|
||||
//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` or `{0}{0}`
|
||||
//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other
|
||||
//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together)
|
||||
//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}`
|
||||
//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …)
|
||||
//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when
|
||||
//! `<i>`, `<b>` or `<u>` wraps all of it; other tags are dropped, and `{`, `}` and `|` in the
|
||||
//! text become the full-width `{`, `}` and `|`.
|
||||
|
||||
use crate::text::{LineStyle, escape_markup, number, plain_text, whole_line_style, wrap_style};
|
||||
use crate::time::FrameRate;
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
/// The frame rate of a file that does not name one.
|
||||
pub const DEFAULT_RATE: FrameRate = FrameRate::FPS_23_976;
|
||||
|
||||
/// `{a}{b}text` as its parts.
|
||||
fn split_cue(line: &str) -> Option<(i64, i64, &str)> {
|
||||
let rest = line.strip_prefix('{')?;
|
||||
let (a, rest) = rest.split_once('}')?;
|
||||
let rest = rest.strip_prefix('{')?;
|
||||
let (b, text) = rest.split_once('}')?;
|
||||
Some((number(a.trim())?, number(b.trim())?, text))
|
||||
}
|
||||
|
||||
/// Whether `line` is a `{first}{last}text` cue line.
|
||||
pub(crate) fn is_cue(line: &str) -> bool {
|
||||
split_cue(line).is_some()
|
||||
}
|
||||
|
||||
/// The frame rate a header cue's text names.
|
||||
fn header_rate(text: &str) -> Option<FrameRate> {
|
||||
let fps: f64 = text.trim().parse().ok()?;
|
||||
(fps.is_finite() && (1.0..=1000.0).contains(&fps)).then(|| FrameRate::from_f64(fps))
|
||||
}
|
||||
|
||||
/// A `$BBGGRR` colour as `#rrggbb`.
|
||||
fn colour(value: &str) -> Option<String> {
|
||||
let hex = value.trim().strip_prefix('$')?;
|
||||
if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let (b, rest) = hex.split_at(2);
|
||||
let (g, r) = rest.split_at(2);
|
||||
Some(format!("#{}{}{}", r.to_ascii_lowercase(), g.to_ascii_lowercase(), b.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
/// What the styling controls of a cue's lines set.
|
||||
#[derive(Default)]
|
||||
struct Sticky {
|
||||
style: LineStyle,
|
||||
colour: Option<String>,
|
||||
}
|
||||
|
||||
/// The text of one line without its `{x:…}` controls, and the controls in order.
|
||||
fn split_controls(line: &str) -> (String, Vec<(char, String)>) {
|
||||
let mut text = String::new();
|
||||
let mut controls = Vec::new();
|
||||
let mut rest = line;
|
||||
while let Some(open) = rest.find('{') {
|
||||
text.push_str(rest.get(..open).unwrap_or(""));
|
||||
let after = rest.get(open + 1..).unwrap_or("");
|
||||
// Check the fixed-size control prefix before scanning its body. Invalid opening
|
||||
// braces must not repeatedly scan the same suffix for a closing brace.
|
||||
let name = after.as_bytes().first().copied().filter(u8::is_ascii_alphabetic);
|
||||
if let Some(name) = name.filter(|_| after.as_bytes().get(1) == Some(&b':')) {
|
||||
if let Some((body, tail)) = after.get(2..).and_then(|s| s.split_once('}')) {
|
||||
controls.push((char::from(name), body.to_string()));
|
||||
rest = tail;
|
||||
} else {
|
||||
// No later control can close either: preserve the entire remaining text.
|
||||
text.push('{');
|
||||
text.push_str(after);
|
||||
rest = "";
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
text.push('{');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
text.push_str(rest);
|
||||
(text, controls)
|
||||
}
|
||||
|
||||
fn apply_style(value: &str, style: &mut LineStyle) {
|
||||
for flag in value.split([',', ' ', '/']) {
|
||||
match flag.trim().to_ascii_lowercase().as_str() {
|
||||
"i" => style.italic = true,
|
||||
"b" => style.bold = true,
|
||||
"u" => style.underline = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cue_text(raw: &str) -> String {
|
||||
let mut sticky = Sticky::default();
|
||||
let mut lines = Vec::new();
|
||||
for line in raw.split('|') {
|
||||
let (text, controls) = split_controls(line);
|
||||
let mut style = sticky.style;
|
||||
let mut line_colour = sticky.colour.clone();
|
||||
for (name, value) in controls {
|
||||
match name {
|
||||
'y' => apply_style(&value, &mut style),
|
||||
'Y' => {
|
||||
apply_style(&value, &mut style);
|
||||
apply_style(&value, &mut sticky.style);
|
||||
}
|
||||
'c' => line_colour = colour(&value).or(line_colour),
|
||||
'C' => {
|
||||
line_colour = colour(&value).or(line_colour);
|
||||
sticky.colour = line_colour.clone();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
lines.push(wrap_style(style, line_colour.as_deref(), &escape_markup(text)));
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let mut rows = Vec::new();
|
||||
let mut rate = DEFAULT_RATE;
|
||||
let mut has_rate_line = false;
|
||||
let mut doc = Document::default();
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match split_cue(line) {
|
||||
Some((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => {
|
||||
rate = header_rate(t).unwrap_or(rate);
|
||||
has_rate_line = true;
|
||||
}
|
||||
Some(row) => rows.push(row),
|
||||
None => doc.warnings.push(format!("line {}: not a MicroDVD cue, skipped", n + 1)),
|
||||
}
|
||||
}
|
||||
if rows.is_empty() && !has_rate_line && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("MicroDVD"));
|
||||
}
|
||||
for (first, last, raw) in rows {
|
||||
let (start, end) = (rate.tick_of(first), rate.tick_of(last));
|
||||
let text = cue_text(raw);
|
||||
if end <= start || text.is_empty() {
|
||||
doc.warnings.push(format!("the cue at frame {first} is empty or ends at frame {last}; skipped"));
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start, end, text, ..Default::default() });
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// Write `doc` with its frames counted at `rate` (None: [`DEFAULT_RATE`]).
|
||||
pub fn write(doc: &Document, rate: Option<FrameRate>) -> String {
|
||||
let rate = rate.map_or(DEFAULT_RATE, FrameRate::sane);
|
||||
let mut out = format!("{{1}}{{1}}{:.3}\n", rate.as_f64());
|
||||
let frame = |t| rate.frame_at(rate.snap_nearest(t)).max(0);
|
||||
for c in &doc.cues {
|
||||
let first = frame(c.start);
|
||||
let last = frame(c.end).max(first.saturating_add(1));
|
||||
let mut lines = Vec::new();
|
||||
for line in c.text.lines() {
|
||||
let (style, inner) = whole_line_style(line);
|
||||
let text = plain_text(inner).trim().replace('{', "\u{ff5b}").replace('}', "\u{ff5d}").replace('|', "\u{ff5c}");
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut flags = Vec::new();
|
||||
for (on, f) in [(style.italic, "i"), (style.bold, "b"), (style.underline, "u")] {
|
||||
if on {
|
||||
flags.push(f);
|
||||
}
|
||||
}
|
||||
lines.push(if flags.is_empty() { text } else { format!("{{y:{}}}{text}", flags.join(",")) });
|
||||
}
|
||||
if lines.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push_str(&format!("{{{first}}}{{{last}}}{}\n", lines.join("|")));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controls_style_lines() {
|
||||
assert_eq!(cue_text("{y:i,b}x|plain"), "<i><b>x</b></i>\nplain");
|
||||
assert_eq!(cue_text("{Y:i}a|b"), "<i>a</i>\n<i>b</i>");
|
||||
assert_eq!(cue_text("{c:$0000ff}red"), "<font color=\"#ff0000\">red</font>");
|
||||
assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & b {x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_controls_inside_valid_cues_are_preserved() {
|
||||
for raw in ["{".repeat(32_768), "{y:".repeat(16_384)] {
|
||||
let doc = parse(&format!("{{0}}{{25}}{raw}")).unwrap();
|
||||
assert_eq!(doc.cues.len(), 1);
|
||||
assert_eq!(doc.cues[0].text, raw);
|
||||
}
|
||||
assert_eq!(cue_text("{{y:i}hello"), "<i>{hello</i>");
|
||||
assert_eq!(cue_text("{xx:no}{y:b}hello"), "<b>{xx:no}hello</b>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_header() {
|
||||
let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap();
|
||||
assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25));
|
||||
let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap();
|
||||
assert_eq!(d.cues.len(), 2);
|
||||
assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25));
|
||||
assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50));
|
||||
assert_eq!(d.cues[1].text, "29.97");
|
||||
let d = parse("{25}{50}x\n").unwrap();
|
||||
assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("hello\nworld\n").is_err());
|
||||
assert!(parse("").unwrap().cues.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! MPL2 (`.txt`, `.mpl`): times in tenths of a second.
|
||||
//!
|
||||
//! ```text
|
||||
//! [10][35]First line|/second line in italics
|
||||
//! ```
|
||||
//!
|
||||
//! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the
|
||||
//! start of a line makes it italic. Writing marks a line italic only when `<i>` wraps all of it,
|
||||
//! drops other tags, rounds times to a tenth of a second, writes `|` in text as `|`, and writes
|
||||
//! a leading `/` in non-italic text as `/`.
|
||||
|
||||
use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style};
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
/// `[a][b]text` as its parts.
|
||||
pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> {
|
||||
let rest = line.strip_prefix('[')?;
|
||||
let (a, rest) = rest.split_once(']')?;
|
||||
let rest = rest.strip_prefix('[')?;
|
||||
let (b, text) = rest.split_once(']')?;
|
||||
Some((number(a.trim())?, number(b.trim())?, text))
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let mut doc = Document::default();
|
||||
let mut found = false;
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((a, b, raw)) = split_cue(line) else {
|
||||
doc.warnings.push(format!("line {}: not an MPL2 cue, skipped", n + 1));
|
||||
continue;
|
||||
};
|
||||
found = true;
|
||||
let mut lines = Vec::new();
|
||||
for l in raw.split('|') {
|
||||
let (italic, l) = match l.trim().strip_prefix('/') {
|
||||
Some(r) => (true, r.trim().to_string()),
|
||||
None => {
|
||||
let t = l.trim();
|
||||
if let Some(rest) = t.strip_prefix('\u{ff0f}') { (false, format!("/{rest}")) } else { (false, t.to_string()) }
|
||||
}
|
||||
};
|
||||
if !l.is_empty() {
|
||||
lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(&l)));
|
||||
}
|
||||
}
|
||||
let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.saturating_mul(100)));
|
||||
if end <= start || lines.is_empty() {
|
||||
doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1));
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() });
|
||||
}
|
||||
if !found && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("MPL2"));
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let mut out = String::new();
|
||||
let ds = |t| (tick_to_ms(t) + 50) / 100;
|
||||
for c in &doc.cues {
|
||||
let start = ds(c.start);
|
||||
let end = ds(c.end).max(start + 1);
|
||||
let mut lines = Vec::new();
|
||||
for line in c.text.lines() {
|
||||
let (style, inner) = whole_line_style(line);
|
||||
let mut text = plain_text(inner).trim().replace('|', "\u{ff5c}");
|
||||
if !style.italic && text.starts_with('/') {
|
||||
text.replace_range(..1, "\u{ff0f}");
|
||||
}
|
||||
if !text.is_empty() {
|
||||
lines.push(if style.italic { format!("/{text}") } else { text });
|
||||
}
|
||||
}
|
||||
if !lines.is_empty() {
|
||||
out.push_str(&format!("[{start}][{end}]{}\n", lines.join("|")));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn italics_and_lines() {
|
||||
let d = parse("[10][35]Hello|/italic\n").unwrap();
|
||||
assert_eq!(d.cues[0].text, "Hello\n<i>italic</i>");
|
||||
assert_eq!(d.cues[0].end, ms_to_tick(3500));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_italic_leading_slash_roundtrip() {
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: ms_to_tick(1000), end: ms_to_tick(2000), text: "/not italic\n<i>/italic</i>".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "[10][20]/not italic|//italic\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues[0].text, "/not italic\n<i>/italic</i>");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions.
|
||||
//!
|
||||
//! ```text
|
||||
//! <SAMI><BODY>
|
||||
//! <SYNC Start=1000><P Class=ENCC>First line<br>second line
|
||||
//! <SYNC Start=3500><P Class=ENCC>
|
||||
//! </BODY></SAMI>
|
||||
//! ```
|
||||
//!
|
||||
//! A `<SYNC Start=ms>` block shows its text from that millisecond until the next block; a block
|
||||
//! holding only ` ` clears the screen. The last caption lasts four seconds if nothing clears
|
||||
//! it. `<br>` starts a new line; `<i>`, `<b>`, `<u>` and `<font color>` are kept, other tags
|
||||
//! dropped; `&`, `<`, `>`, ` ` and numeric references are read. A file can hold
|
||||
//! several language classes (`<P Class=ENCC>`, `<P Class=KRCC>`): the first one named is read and
|
||||
//! the others skipped with a warning. Writing makes one `ENCC` class, an ` ` block where a
|
||||
//! caption ends before the next starts, and rounds to milliseconds.
|
||||
|
||||
use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, sequential, tick_to_ms};
|
||||
use crate::time::Tick;
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
/// The value of attribute `name` in the tag text `tag` (quotes optional).
|
||||
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
||||
let lower = tag.to_ascii_lowercase();
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower.get(from..).and_then(|r| r.find(name)) {
|
||||
let at = from + i;
|
||||
from = at + name.len();
|
||||
let before_ok = at == 0 || lower.as_bytes().get(at - 1).is_some_and(|b| !b.is_ascii_alphanumeric());
|
||||
let rest = tag.get(from..).unwrap_or("").trim_start();
|
||||
let Some(rest) = rest.strip_prefix('=').filter(|_| before_ok) else { continue };
|
||||
let rest = rest.trim_start();
|
||||
return Some(match rest.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => {
|
||||
let inner = rest.get(1..).unwrap_or("");
|
||||
inner.split(q).next().unwrap_or("")
|
||||
}
|
||||
_ => rest.split(|c: char| c.is_whitespace() || c == '>').next().unwrap_or(""),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A numeric character reference body (`#65`, `#x41`) as its character.
|
||||
fn numeric_reference(body: &str) -> Option<char> {
|
||||
let digits = body.strip_prefix('#')?;
|
||||
let code = match digits.strip_prefix(['x', 'X']) {
|
||||
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
|
||||
None => digits.parse().ok()?,
|
||||
};
|
||||
char::from_u32(code).filter(|c| !c.is_control() || *c == '\n')
|
||||
}
|
||||
|
||||
/// HTML text as cue text: entities the cue model keeps stay, numeric ones are decoded, a stray
|
||||
/// `&` is escaped, whitespace runs collapse.
|
||||
fn text_run(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = s;
|
||||
let mut space = false;
|
||||
while let Some(c) = rest.chars().next() {
|
||||
let mut advance = c.len_utf8();
|
||||
if c.is_whitespace() && c != '\u{a0}' {
|
||||
space = true;
|
||||
rest = rest.get(advance..).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
if space {
|
||||
out.push(' ');
|
||||
}
|
||||
space = false;
|
||||
if c == '&' {
|
||||
if let Some((_, len)) = crate::entity_at(rest) {
|
||||
out.push_str(rest.get(..len).unwrap_or(""));
|
||||
advance = len;
|
||||
} else if let Some(body) = rest.get(1..).and_then(|r| {
|
||||
// Numeric entities have at most eight body bytes. Never scan the
|
||||
// unbounded remainder again for each malformed ampersand.
|
||||
let end = r.bytes().take(9).position(|b| b == b';')?;
|
||||
r.get(..end)
|
||||
}) && let Some(ch) = numeric_reference(body)
|
||||
{
|
||||
out.push_str(&escape_markup(&ch.to_string()));
|
||||
advance = body.len() + 2;
|
||||
} else {
|
||||
out.push_str("&");
|
||||
}
|
||||
} else {
|
||||
out.push_str(&escape_markup(&c.to_string()));
|
||||
}
|
||||
rest = rest.get(advance..).unwrap_or("");
|
||||
}
|
||||
if space {
|
||||
out.push(' ');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One `<SYNC>` block's body as (class, cue text) segments, one per `<P>`.
|
||||
fn segments(body: &str) -> Vec<(String, String)> {
|
||||
let mut segs: Vec<(String, String)> = vec![(String::new(), String::new())];
|
||||
let mut open_fonts = 0usize;
|
||||
let mut rest = body;
|
||||
while !rest.is_empty() {
|
||||
let Some(lt) = rest.find('<') else {
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.1.push_str(&text_run(rest));
|
||||
}
|
||||
break;
|
||||
};
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.1.push_str(&text_run(rest.get(..lt).unwrap_or("")));
|
||||
}
|
||||
let after = rest.get(lt + 1..).unwrap_or("");
|
||||
let Some(gt) = after.find('>') else {
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.1.push_str("<");
|
||||
last.1.push_str(&text_run(after));
|
||||
}
|
||||
break;
|
||||
};
|
||||
let tag = after.get(..gt).unwrap_or("");
|
||||
rest = after.get(gt + 1..).unwrap_or("");
|
||||
let closing = tag.starts_with('/');
|
||||
let name: String = tag.trim_start_matches('/').chars().take_while(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
|
||||
let Some(last) = segs.last_mut() else { continue };
|
||||
match (name.as_str(), closing) {
|
||||
("br", _) => last.1.push('\n'),
|
||||
("p", false) => segs.push((attribute(tag, "class").unwrap_or("").to_string(), String::new())),
|
||||
("i" | "b" | "u", false) => last.1.push_str(&format!("<{name}>")),
|
||||
("i" | "b" | "u", true) => last.1.push_str(&format!("</{name}>")),
|
||||
("font", false) => {
|
||||
if let Some(c) = attribute(tag, "color").filter(|c| c.len() <= 20 && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#')) {
|
||||
open_fonts += 1;
|
||||
last.1.push_str(&format!("<font color=\"{c}\">"));
|
||||
}
|
||||
}
|
||||
("font", true) if open_fonts > 0 => {
|
||||
open_fonts -= 1;
|
||||
last.1.push_str("</font>");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
/// A caption text without the whitespace and non-breaking spaces round its lines.
|
||||
fn tidy(text: &str) -> String {
|
||||
let lines: Vec<String> = text
|
||||
.split('\n')
|
||||
.map(|l| l.replace(" ", " ").trim().to_string())
|
||||
.filter(|l| !l.is_empty() && !crate::plain_text(l).trim().is_empty())
|
||||
.collect();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
let mut starts: Vec<usize> = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower.get(from..).and_then(|r| r.find("<sync")) {
|
||||
starts.push(from + i);
|
||||
from += i + 5;
|
||||
}
|
||||
if starts.is_empty() {
|
||||
return if text.trim().is_empty() || lower.contains("<sami") { Ok(Document::default()) } else { Err(Error::NotFormat("SAMI")) };
|
||||
}
|
||||
let mut doc = Document::default();
|
||||
let mut class: Option<String> = None;
|
||||
let mut skipped_class = false;
|
||||
let mut syncs: Vec<(Tick, String)> = Vec::new();
|
||||
for (k, &at) in starts.iter().enumerate() {
|
||||
let stop = starts.get(k + 1).copied().unwrap_or(text.len());
|
||||
let chunk = text.get(at..stop).unwrap_or("");
|
||||
let chunk = match chunk.to_ascii_lowercase().find("</body") {
|
||||
Some(i) => chunk.get(..i).unwrap_or(chunk),
|
||||
None => chunk,
|
||||
};
|
||||
let Some((tag, body)) = chunk.get(1..).and_then(|c| c.split_once('>')) else { continue };
|
||||
let Some(start) = attribute(tag, "start").and_then(|v| number(v.trim())) else {
|
||||
doc.warnings.push("a <SYNC> without a Start time was skipped".to_string());
|
||||
continue;
|
||||
};
|
||||
let mut shown = String::new();
|
||||
for (cls, seg) in segments(body) {
|
||||
if class.is_none() && !cls.is_empty() {
|
||||
class = Some(cls.to_ascii_lowercase());
|
||||
}
|
||||
if class.as_deref().is_none_or(|c| c == cls.to_ascii_lowercase() || cls.is_empty()) {
|
||||
shown.push_str(&seg);
|
||||
} else {
|
||||
skipped_class = true;
|
||||
}
|
||||
}
|
||||
syncs.push((ms_to_tick(start), tidy(&shown)));
|
||||
}
|
||||
if skipped_class {
|
||||
doc.warnings.push("the file has other language classes; only the first was read".to_string());
|
||||
}
|
||||
syncs.sort_by_key(|(t, _)| *t);
|
||||
for (i, (start, text)) in syncs.iter().enumerate() {
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let end = syncs.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next);
|
||||
if end <= *start {
|
||||
doc.warnings.push("two captions start at the same time; the first was skipped".to_string());
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() });
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let cues = sequential(doc);
|
||||
let mut out = String::from(
|
||||
"<SAMI>\n<HEAD>\n<TITLE></TITLE>\n<STYLE TYPE=\"text/css\">\n<!--\nP { margin-left: 8pt; margin-right: 8pt; text-align: center; font-size: 20pt; color: white; }\n.ENCC { Name: English; lang: en-US; SAMIType: CC; }\n-->\n</STYLE>\n</HEAD>\n<BODY>\n",
|
||||
);
|
||||
let active_cues: Vec<(&Cue, Vec<&str>)> = cues
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
if lines.is_empty() { None } else { Some((c, lines)) }
|
||||
})
|
||||
.collect();
|
||||
let mut resolved_cues: Vec<(i64, i64, &Vec<&str>)> = Vec::with_capacity(active_cues.len());
|
||||
let mut prev_end = 0i64;
|
||||
for (c, lines) in &active_cues {
|
||||
let start_ms = tick_to_ms(c.start).max(prev_end);
|
||||
let end_ms = tick_to_ms(c.end).max(start_ms + 1);
|
||||
prev_end = end_ms;
|
||||
resolved_cues.push((start_ms, end_ms, lines));
|
||||
}
|
||||
for (i, &(start_ms, end_ms, lines)) in resolved_cues.iter().enumerate() {
|
||||
out.push_str(&format!("<SYNC Start={start_ms}><P Class=ENCC>{}\n", lines.join("<br>")));
|
||||
let next_start = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s);
|
||||
if next_start != Some(end_ms) {
|
||||
out.push_str(&format!("<SYNC Start={end_ms}><P Class=ENCC> \n"));
|
||||
}
|
||||
}
|
||||
out.push_str("</BODY>\n</SAMI>\n");
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blocks_clear_and_style() {
|
||||
let d = parse("<SAMI><BODY>\n<SYNC Start=1000><P Class=ENCC>Hello<br>world & <i>you</i>\n<SYNC Start=3500><P Class=ENCC> \n<SYNC Start=4000><P Class=ENCC>x A y\n</BODY></SAMI>").unwrap();
|
||||
assert_eq!(d.cues.len(), 2);
|
||||
assert_eq!(d.cues[0].text, "Hello\nworld & <i>you</i>");
|
||||
assert_eq!(d.cues[0].end, ms_to_tick(3500));
|
||||
assert_eq!(d.cues[1].text, "x A y");
|
||||
assert_eq!(d.cues[1].end, last_cue_end(ms_to_tick(4000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_entities_inside_valid_cues_are_bounded() {
|
||||
let raw = "&".repeat(32_768);
|
||||
let doc = parse(&format!("<SAMI><SYNC Start=0><P>{raw}<SYNC Start=1000><P> ")).unwrap();
|
||||
assert_eq!(doc.cues.len(), 1);
|
||||
assert_eq!(doc.cues[0].text, "&".repeat(32_768));
|
||||
assert_eq!(text_run("A A A &é;"), "A &#00000065; A &é;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_first_class_is_read() {
|
||||
let d = parse("<SAMI><BODY><SYNC Start=1000><P Class=ENCC>en<P Class=KRCC>kr<SYNC Start=2000><P Class=ENCC> </BODY></SAMI>").unwrap();
|
||||
assert_eq!(d.cues.len(), 1);
|
||||
assert_eq!(d.cues[0].text, "en");
|
||||
assert_eq!(d.warnings.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("hello").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_duration_and_empty_cues() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: ms_to_tick(100), end: Tick(ms_to_tick(100).0 + 1), text: "Brief".into(), ..Default::default() },
|
||||
Cue { start: ms_to_tick(101), end: ms_to_tick(200), text: " ".into(), ..Default::default() },
|
||||
Cue { start: ms_to_tick(500), end: ms_to_tick(600), text: "After gap".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert!(written.contains("<SYNC Start=100><P Class=ENCC>Brief\n<SYNC Start=101><P Class=ENCC> \n"));
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].start, ms_to_tick(100));
|
||||
assert_eq!(parsed.cues[0].end, ms_to_tick(101));
|
||||
assert_eq!(parsed.cues[1].start, ms_to_tick(500));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_short_cues_do_not_collide_after_rounding() {
|
||||
let t100 = ms_to_tick(100);
|
||||
let t100_1 = Tick(t100.0 + crate::TICKS_PER_MS / 10);
|
||||
let t200 = ms_to_tick(200);
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: t100, end: t100_1, text: "First".into(), ..Default::default() },
|
||||
Cue { start: t100_1, end: t200, text: "Second".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let encoded = write(&doc);
|
||||
let back = parse(&encoded).unwrap();
|
||||
assert_eq!(back.cues.len(), 2);
|
||||
assert_eq!(back.cues[0].text, "First");
|
||||
assert_eq!(tick_to_ms(back.cues[0].start), 100);
|
||||
assert_eq!(tick_to_ms(back.cues[0].end), 101);
|
||||
assert_eq!(back.cues[1].text, "Second");
|
||||
assert_eq!(tick_to_ms(back.cues[1].start), 101);
|
||||
assert_eq!(tick_to_ms(back.cues[1].end), 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! SubViewer 2 (`.sub`): hundredths of a second, with an information header.
|
||||
//!
|
||||
//! ```text
|
||||
//! [INFORMATION]
|
||||
//! [TITLE]…
|
||||
//! [END INFORMATION]
|
||||
//! [SUBTITLE]
|
||||
//! 00:00:01.00,00:00:03.50
|
||||
//! First line[br]second line
|
||||
//!
|
||||
//! ```
|
||||
//!
|
||||
//! Reading skips the bracketed header lines and takes every `start,end` time line as a cue whose
|
||||
//! text runs to the next blank line; `[br]` starts a new line. Fractions of one to three digits
|
||||
//! are accepted. Writing adds a minimal header, rounds times to a hundredth of a second, drops
|
||||
//! tags, writes `[br]` inside text as `[br]`, and writes `,` in lines that match the timing
|
||||
//! syntax as `,`.
|
||||
|
||||
use crate::text::{escape_markup, plain_lines};
|
||||
use crate::time::{TICKS_PER_SECOND, Tick};
|
||||
use crate::{Cue, Document, Error, Result, parse_clock};
|
||||
|
||||
const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100;
|
||||
|
||||
/// Returns true if `head` begins with a genuine SubViewer header structure.
|
||||
pub(crate) fn is_header(head: &str) -> bool {
|
||||
let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
match lines.next() {
|
||||
Some("[INFORMATION]") => lines.any(|l| {
|
||||
l == "[SUBTITLE]"
|
||||
|| l == "[END INFORMATION]"
|
||||
|| l.starts_with("[TITLE")
|
||||
|| l.starts_with("[AUTHOR")
|
||||
|| l.starts_with("[SOURCE")
|
||||
|| l.starts_with("[FILEPATH")
|
||||
|| l.starts_with("[DELAY")
|
||||
|| l.starts_with("[CD TRACK")
|
||||
|| l.starts_with("[COMMENT")
|
||||
|| (l.starts_with('[') && l.contains(']'))
|
||||
}),
|
||||
Some("[SUBTITLE]") => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `h:mm:ss.cc,h:mm:ss.cc` as its two times.
|
||||
pub(crate) fn parse_timing(line: &str) -> Option<(Tick, Tick)> {
|
||||
let (a, b) = line.trim().split_once(',')?;
|
||||
let ok = |s: &str| s.contains(':') && s.contains('.');
|
||||
if !ok(a) || !ok(b) {
|
||||
return None;
|
||||
}
|
||||
Some((parse_clock(a)?, parse_clock(b)?))
|
||||
}
|
||||
|
||||
/// Split `s` at each `[br]`, whatever its case.
|
||||
fn split_br(s: &str) -> Vec<&str> {
|
||||
let lower = s.to_ascii_lowercase();
|
||||
let mut parts = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower.get(from..).and_then(|r| r.find("[br]")) {
|
||||
parts.push(s.get(from..from + i).unwrap_or(""));
|
||||
from += i + 4;
|
||||
}
|
||||
parts.push(s.get(from..).unwrap_or(""));
|
||||
parts
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut doc = Document::default();
|
||||
let mut found = false;
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let Some((start, end)) = lines.get(i).and_then(|l| parse_timing(l)) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
found = true;
|
||||
i += 1;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
while let Some(l) = lines.get(i).filter(|l| !l.trim().is_empty()) {
|
||||
if parse_timing(l).is_some() {
|
||||
break;
|
||||
}
|
||||
out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup));
|
||||
i += 1;
|
||||
}
|
||||
if end <= start || out.is_empty() {
|
||||
doc.warnings.push(format!("the cue at line {i} is empty or ends before it starts; skipped"));
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start, end, text: out.join("\n"), ..Default::default() });
|
||||
}
|
||||
let has_header = text.contains("[INFORMATION]") || text.contains("[SUBTITLE]");
|
||||
if !found && !has_header && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("SubViewer"));
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
fn cs(t: Tick) -> u64 {
|
||||
((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as u64
|
||||
}
|
||||
|
||||
fn clock(cs: u64) -> String {
|
||||
format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let mut out = String::from(
|
||||
"[INFORMATION]\n[TITLE]\n[AUTHOR]\n[SOURCE]\n[PRG]\n[FILEPATH]\n[DELAY]0\n[CD TRACK]0\n[COMMENT]\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]no,[SIZE]18,[FONT]Arial\n",
|
||||
);
|
||||
for c in &doc.cues {
|
||||
let lines = plain_lines(&c.text);
|
||||
if lines.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let start_cs = cs(c.start);
|
||||
let end_cs = cs(c.end).max(start_cs + 1);
|
||||
out.push_str(&format!("{},{}\n", clock(start_cs), clock(end_cs)));
|
||||
let lines: Vec<String> = lines
|
||||
.into_iter()
|
||||
.map(|mut l| {
|
||||
if parse_timing(&l).is_some() {
|
||||
l = l.replacen(',', "\u{ff0c}", 1);
|
||||
}
|
||||
l.replace("[br]", "\u{ff3b}br\u{ff3d}")
|
||||
.replace("[BR]", "\u{ff3b}BR\u{ff3d}")
|
||||
.replace("[Br]", "\u{ff3b}Br\u{ff3d}")
|
||||
.replace("[bR]", "\u{ff3b}bR\u{ff3d}")
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&lines.join("[br]"));
|
||||
out.push_str("\n\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn header_and_breaks() {
|
||||
let d = parse("[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:03.50\nHello[BR]world\n\n").unwrap();
|
||||
assert_eq!(d.cues[0].text, "Hello\nworld");
|
||||
assert_eq!(d.cues[0].end, crate::text::ms_to_tick(3500));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_escapes_every_case_of_literal_break_tokens() {
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: Tick(0), end: crate::text::ms_to_tick(1000), text: "a[br]b[BR]c[Br]d[bR]é".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
let decoded = parse(&write(&doc)).unwrap();
|
||||
assert_eq!(decoded.cues[0].text, "a[br]b[BR]c[Br]d[bR]é");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn centisecond_rounding_without_double_rounding_error() {
|
||||
// 1.0046s is 255_184_473_600 ticks (at 254_016_000_000 ticks/sec).
|
||||
// Direct rounding to hundredths gives 100cs (00:00:01.00).
|
||||
// Double-rounding through ms gives 1005ms -> 101cs (00:00:01.01).
|
||||
let t = Tick(255_184_473_600);
|
||||
assert_eq!(clock(cs(t)), "00:00:01.00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timing_shaped_text_escaped_and_roundtripped() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: Tick(TICKS_PER_SECOND), end: Tick(3 * TICKS_PER_SECOND), text: "00:00:01.00,00:00:02.00".into(), ..Default::default() },
|
||||
Cue { start: Tick(4 * TICKS_PER_SECOND), end: Tick(5 * TICKS_PER_SECOND), text: "Second cue".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert!(written.contains("00:00:01.00,00:00:02.00"));
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00");
|
||||
assert_eq!(parsed.cues[1].text, "Second cue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_fullwidth_comma_preserved_on_read() {
|
||||
let raw = "[INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:02.00\n00:00:01.00\u{ff0c}00:00:02.00\n\n";
|
||||
let doc = parse(raw).unwrap();
|
||||
assert_eq!(doc.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00");
|
||||
}
|
||||
}
|
||||
@@ -85,8 +85,8 @@ pub fn plain_text(s: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
use crate::TICKS_PER_MS;
|
||||
use crate::time::{TICKS_PER_SECOND, Tick};
|
||||
use crate::{Cue, Document, TICKS_PER_MS};
|
||||
|
||||
/// How long the last cue of a format that gives only start times lasts: such a file says when a
|
||||
/// caption appears, and the next one ends it.
|
||||
@@ -131,6 +131,62 @@ pub(crate) fn plain_lines(text: &str) -> Vec<String> {
|
||||
text.lines().map(plain_text).map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// The style a whole line of cue text carries: `<i>`, `<b>` and `<u>` around all of it.
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LineStyle {
|
||||
pub italic: bool,
|
||||
pub bold: bool,
|
||||
pub underline: bool,
|
||||
}
|
||||
|
||||
/// The style that wraps the whole of `line`, and the line without it. `<i>a</i> b <i>c</i>` is not
|
||||
/// italic as a whole.
|
||||
pub(crate) fn whole_line_style(line: &str) -> (LineStyle, &str) {
|
||||
let mut style = LineStyle::default();
|
||||
let mut rest = line.trim();
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for (open, close, flag) in [("<i>", "</i>", 0), ("<b>", "</b>", 1), ("<u>", "</u>", 2)] {
|
||||
if let Some(inner) = rest.strip_prefix(open).and_then(|r| r.strip_suffix(close))
|
||||
&& !inner.contains(open)
|
||||
&& !inner.contains(close)
|
||||
{
|
||||
match flag {
|
||||
0 => style.italic = true,
|
||||
1 => style.bold = true,
|
||||
_ => style.underline = true,
|
||||
}
|
||||
rest = inner.trim();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return (style, rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cue text from a line's style and its (already escaped) text.
|
||||
pub(crate) fn wrap_style(style: LineStyle, color: Option<&str>, text: &str) -> String {
|
||||
let mut out = text.to_string();
|
||||
for (on, tag) in [(style.underline, "u"), (style.bold, "b"), (style.italic, "i")] {
|
||||
if on {
|
||||
out = format!("<{tag}>{out}</{tag}>");
|
||||
}
|
||||
}
|
||||
match color {
|
||||
Some(c) => format!("<font color=\"{c}\">{out}</font>"),
|
||||
None => out,
|
||||
}
|
||||
}
|
||||
|
||||
/// The cues of `doc` in time order with no overlaps, for a format that holds one caption at a time.
|
||||
pub(crate) fn sequential(doc: &Document) -> Vec<Cue> {
|
||||
let mut copy = Document { cues: doc.cues.clone(), ..Default::default() };
|
||||
copy.normalize();
|
||||
copy.cues
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! VPlayer (`.txt`, `.vpl`): one start time per caption.
|
||||
//!
|
||||
//! ```text
|
||||
//! 00:00:01.00=First line|second line
|
||||
//! 00:00:04.00=
|
||||
//! ```
|
||||
//!
|
||||
//! A line is `HH:MM:SS`, an optional `.cc` fraction, one of `:`, `=` or a space, and the text; `|`
|
||||
//! starts a new line. The file gives only when each caption appears: it stays until the next
|
||||
//! line, whose empty text clears it. The last caption lasts four seconds if no line ends it.
|
||||
//! Writing puts a clearing line where a caption ends before the next one starts, drops tags,
|
||||
//! rounds to a hundredth of a second and writes `|` in text as `|`.
|
||||
|
||||
use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential};
|
||||
use crate::time::{TICKS_PER_SECOND, Tick};
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100;
|
||||
|
||||
/// `HH:MM:SS[.cc]` then a separator and text: the time and the text.
|
||||
pub(crate) fn split_line(line: &str) -> Option<(Tick, &str)> {
|
||||
let mut parts = line.splitn(3, ':');
|
||||
let h = number(parts.next()?)?;
|
||||
let m = number(parts.next()?)?;
|
||||
let tail = parts.next()?;
|
||||
let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
|
||||
let s = number(tail.get(..digits)?)?;
|
||||
let mut rest = tail.get(digits..)?;
|
||||
let mut ms = 0;
|
||||
if let Some(frac) = rest.strip_prefix('.') {
|
||||
let n = frac.bytes().take_while(u8::is_ascii_digit).count().min(3);
|
||||
let f = frac.get(..n).filter(|f| !f.is_empty())?;
|
||||
ms = number(f)? * 10_i64.pow(3 - n as u32);
|
||||
rest = frac.get(n..)?;
|
||||
// further digits of a long fraction are below a millisecond
|
||||
rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
|
||||
}
|
||||
if m >= 60 || s >= 60 || h > 9999 {
|
||||
return None;
|
||||
}
|
||||
let text = rest.strip_prefix([':', '=', ' '])?;
|
||||
Some((ms_to_tick(((h * 60 + m) * 60 + s) * 1000 + ms), text))
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let mut doc = Document::default();
|
||||
let mut starts: Vec<(Tick, String)> = Vec::new();
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
match split_line(line.trim()) {
|
||||
Some((t, raw)) => {
|
||||
let lines: Vec<String> = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect();
|
||||
starts.push((t, lines.join("\n")));
|
||||
}
|
||||
None => doc.warnings.push(format!("line {}: not a VPlayer line, skipped", n + 1)),
|
||||
}
|
||||
}
|
||||
if starts.is_empty() && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("VPlayer"));
|
||||
}
|
||||
for (i, (start, text)) in starts.iter().enumerate() {
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let end = starts.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next);
|
||||
if end <= *start {
|
||||
doc.warnings.push("a caption is followed by a line at the same time; skipped".to_string());
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() });
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
fn cs(t: Tick) -> i64 {
|
||||
((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as i64
|
||||
}
|
||||
|
||||
fn clock(cs: i64) -> String {
|
||||
format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let cues = sequential(doc);
|
||||
let mut out = String::new();
|
||||
let active_cues: Vec<(&Cue, Vec<String>)> = cues
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let lines = plain_lines(&c.text);
|
||||
if lines.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let lines = lines.into_iter().map(|l| l.replace('|', "\u{ff5c}")).collect();
|
||||
Some((c, lines))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut resolved_cues: Vec<(i64, i64, &Vec<String>)> = Vec::with_capacity(active_cues.len());
|
||||
let mut prev_end = 0i64;
|
||||
for (c, lines) in &active_cues {
|
||||
let start_cs = cs(c.start).max(prev_end);
|
||||
let end_cs = cs(c.end).max(start_cs + 1);
|
||||
prev_end = end_cs;
|
||||
resolved_cues.push((start_cs, end_cs, lines));
|
||||
}
|
||||
|
||||
for (i, &(start_cs, end_cs, lines)) in resolved_cues.iter().enumerate() {
|
||||
out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|")));
|
||||
let next_start_cs = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s);
|
||||
if next_start_cs != Some(end_cs) {
|
||||
out.push_str(&format!("{}=\n", clock(end_cs)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn short_duration_cue_preserves_positive_duration_on_write_and_read() {
|
||||
let mut doc = Document::default();
|
||||
// A cue from 0 to 1 ms collapses to 00:00:00.00 under centisecond rounding.
|
||||
doc.cues.push(Cue { start: ms_to_tick(0), end: ms_to_tick(1), text: "Short".to_string(), ..Default::default() });
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "00:00:00.00=Short\n00:00:00.01=\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 1);
|
||||
assert_eq!(parsed.cues[0].text, "Short");
|
||||
assert_eq!(parsed.cues[0].start, ms_to_tick(0));
|
||||
assert_eq!(parsed.cues[0].end, ms_to_tick(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_short_cues_do_not_collide_after_rounding() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: ms_to_tick(1000), end: ms_to_tick(1001), text: "First".to_string(), ..Default::default() },
|
||||
Cue { start: ms_to_tick(1001), end: ms_to_tick(1020), text: "Second".to_string(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "00:00:01.00=First\n00:00:01.01=Second\n00:00:01.02=\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].text, "First");
|
||||
assert_eq!(parsed.cues[0].start, ms_to_tick(1000));
|
||||
assert_eq!(parsed.cues[0].end, ms_to_tick(1010));
|
||||
assert_eq!(parsed.cues[1].text, "Second");
|
||||
assert_eq!(parsed.cues[1].start, ms_to_tick(1010));
|
||||
assert_eq!(parsed.cues[1].end, ms_to_tick(1020));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separators_and_ends() {
|
||||
let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap();
|
||||
assert_eq!(d.cues.len(), 2);
|
||||
assert_eq!(d.cues[0].text, "Hello\nworld");
|
||||
assert_eq!(d.cues[0].end, ms_to_tick(4500));
|
||||
assert_eq!(d.cues[1].end, ms_to_tick(9000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("hello\n").is_err());
|
||||
assert!(parse("00:00:01,000 --> 00:00:02,000\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_cue_skipped_and_numerical_timestamp_order() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue {
|
||||
start: Tick(99 * 3600 * TICKS_PER_SECOND),
|
||||
end: Tick(99 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND),
|
||||
text: "At 99h".into(),
|
||||
..Default::default()
|
||||
},
|
||||
Cue {
|
||||
start: Tick(99 * 3600 * TICKS_PER_SECOND + 3 * TICKS_PER_SECOND),
|
||||
end: Tick(99 * 3600 * TICKS_PER_SECOND + 4 * TICKS_PER_SECOND),
|
||||
text: " ".into(),
|
||||
..Default::default()
|
||||
},
|
||||
Cue {
|
||||
start: Tick(100 * 3600 * TICKS_PER_SECOND),
|
||||
end: Tick(100 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND),
|
||||
text: "At 100h".into(),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "99:00:00.00=At 99h\n99:00:02.00=\n100:00:00.00=At 100h\n100:00:02.00=\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].text, "At 99h");
|
||||
assert_eq!(parsed.cues[1].text, "At 100h");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! The legacy text formats (MicroDVD, MPL2, SubViewer 2, VPlayer, SAMI): reading, writing, and
|
||||
//! ffmpeg as the reference (oracle; skipped when ffmpeg is absent, a failure with
|
||||
//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
|
||||
|
||||
use craft_captions::time::FrameRate;
|
||||
use craft_captions::{Cue, Document, Format, TICKS_PER_SECOND, Tick, WriteOptions, detect, parse, plain_text, write};
|
||||
use std::process::Command;
|
||||
|
||||
const T: i64 = TICKS_PER_SECOND;
|
||||
const MS: i64 = T / 1000;
|
||||
|
||||
fn ms(v: i64) -> Tick {
|
||||
Tick(v * MS)
|
||||
}
|
||||
|
||||
/// The five formats, with the ffmpeg format name each is read and written through.
|
||||
const FORMATS: [(Format, &str, &str); 5] = [
|
||||
(Format::MicroDvd, "microdvd", "sub"),
|
||||
(Format::Mpl2, "mpl2", "txt"),
|
||||
(Format::SubViewer, "subviewer", "sbv"),
|
||||
(Format::VPlayer, "vplayer", "txt"),
|
||||
(Format::Sami, "sami", "smi"),
|
||||
];
|
||||
|
||||
const MICRODVD: &str = "{1}{1}23.976\n{24}{72}Hello|{y:i}second bold\n{100}{150}{c:$0000ff}red\n{200}{250}a & b < c\n";
|
||||
const MPL2: &str = "[10][35]Hello|/italic\n[40][60]plain\n[70][90]/a|/b\n";
|
||||
const SUBVIEWER: &str = "[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]bd,[SIZE]18,[FONT]Arial\n00:00:01.00,00:00:03.50\nHello[br]world\n\n00:00:04.00,00:00:05.00\nplain\n";
|
||||
const VPLAYER: &str = "00:00:01.00=Hello|world\n00:00:04.00=\n00:00:05:plain\n00:00:09 later\n";
|
||||
const SAMI: &str = "<SAMI>\n<HEAD><TITLE>x</TITLE></HEAD>\n<BODY>\n<SYNC Start=1000><P Class=ENCC>Hello<br>world\n<SYNC Start=3500><P Class=ENCC> \n<SYNC Start=4000><P Class=ENCC><i>plain</i> & more\n<SYNC Start=5000><P Class=ENCC> \n</BODY>\n</SAMI>\n";
|
||||
|
||||
fn samples() -> [(Format, &'static str); 5] {
|
||||
[(Format::MicroDvd, MICRODVD), (Format::Mpl2, MPL2), (Format::SubViewer, SUBVIEWER), (Format::VPlayer, VPLAYER), (Format::Sami, SAMI)]
|
||||
}
|
||||
|
||||
fn run(ff: &std::path::Path, args: &[&str]) {
|
||||
let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg");
|
||||
assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
/// What ffmpeg reads from `bytes` as `ffmpeg_format`, as cues.
|
||||
fn ffmpeg_reads(ff: &std::path::Path, name: &str, ffmpeg_format: &str, ext: &str, bytes: &[u8]) -> Document {
|
||||
let dir = craft_media_testkit::fixture_subdir("captions_legacy");
|
||||
let (input, out) = (dir.join(format!("{name}.{ext}")), dir.join(format!("{name}.srt")));
|
||||
std::fs::write(&input, bytes).expect("write");
|
||||
run(ff, &["-f", ffmpeg_format, "-i", input.to_str().expect("path"), out.to_str().expect("path")]);
|
||||
parse(&std::fs::read(&out).expect("read"), Format::Srt).expect("parse ffmpeg's srt")
|
||||
}
|
||||
|
||||
/// The lines of a cue's text as plain text, tags and entities gone.
|
||||
fn plain(c: &Cue) -> String {
|
||||
c.text.lines().map(|l| plain_text(l).trim().to_string()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn we_read_what_ffmpeg_reads() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
for (format, text) in samples() {
|
||||
let (_, name, ext) = FORMATS.iter().copied().find(|f| f.0 == format).expect("format");
|
||||
let ours = parse(text.as_bytes(), format).expect("parse");
|
||||
let theirs = ffmpeg_reads(&ff, &format!("read_{name}"), name, ext, text.as_bytes());
|
||||
assert_eq!(ours.cues.len(), theirs.cues.len(), "{format:?}: {:?} against {:?}", ours.cues, theirs.cues);
|
||||
for (i, (o, t)) in ours.cues.iter().zip(&theirs.cues).enumerate() {
|
||||
// ffmpeg gives a last caption of a start-only format no end (an enormous one).
|
||||
let last = i + 1 == ours.cues.len();
|
||||
let open_ended = matches!(format, Format::VPlayer | Format::Sami) && last;
|
||||
assert!((o.start.0 - t.start.0).abs() <= MS, "{format:?} start of {:?}: {:?} against {:?}", o.text, o.start, t.start);
|
||||
if !open_ended {
|
||||
assert!((o.end.0 - t.end.0).abs() <= MS, "{format:?} end of {:?}: {:?} against {:?}", o.text, o.end, t.end);
|
||||
}
|
||||
assert_eq!(plain(o), plain(t), "{format:?} text of the cue at {:?}", o.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_document() -> Document {
|
||||
let cue = |a: i64, b: i64, text: &str| Cue { start: ms(a), end: ms(b), text: text.into(), ..Default::default() };
|
||||
Document {
|
||||
cues: vec![
|
||||
cue(1000, 3500, "Hello\n<i>second line</i>"),
|
||||
cue(3500, 5000, "straight after, with & and <"),
|
||||
cue(7000, 9000, "after a gap [br] { } |"),
|
||||
cue(3_600_000, 3_601_500, "an hour in"),
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_reads_what_we_write() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
// ffmpeg's own readers mangle the look-alike characters a writer uses for what a format cannot hold,
|
||||
// so the cue that has those is left out here (write_then_read covers it).
|
||||
let mut doc = sample_document();
|
||||
doc.cues[2].text = "after a gap".into();
|
||||
for (format, name, ext) in FORMATS {
|
||||
let bytes = write(&doc, format, WriteOptions::default());
|
||||
let theirs = ffmpeg_reads(&ff, &format!("write_{name}"), name, ext, &bytes);
|
||||
assert_eq!(theirs.cues.len(), doc.cues.len(), "{format:?}: {:?}", String::from_utf8_lossy(&bytes));
|
||||
for (t, d) in theirs.cues.iter().zip(&doc.cues) {
|
||||
let tolerance = if format == Format::MicroDvd { 45 * MS } else { 10 * MS };
|
||||
assert!((t.start.0 - d.start.0).abs() <= tolerance, "{format:?} start of {:?}: {:?}", d.text, t.start);
|
||||
// the characters a format cannot hold are written as look-alikes: compare without them
|
||||
let bare = |c: &Cue| {
|
||||
plain(c)
|
||||
.replace('\u{ff3b}', "[")
|
||||
.replace('\u{ff3d}', "]")
|
||||
.replace("[br]", "")
|
||||
.replace(['{', '}', '|', '\u{ff5b}', '\u{ff5d}', '\u{ff5c}'], "")
|
||||
.replace(" ", " ")
|
||||
};
|
||||
assert_eq!(bare(t), bare(d), "{format:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_then_read_keeps_times_and_text() {
|
||||
let doc = sample_document();
|
||||
for (format, _, _) in FORMATS {
|
||||
let bytes = write(&doc, format, WriteOptions::default());
|
||||
let back = parse(&bytes, format).unwrap_or_else(|e| panic!("{format:?}: {e}"));
|
||||
assert_eq!(back.cues.len(), doc.cues.len(), "{format:?}");
|
||||
let tolerance = match format {
|
||||
Format::MicroDvd => 25 * MS,
|
||||
Format::Mpl2 => 50 * MS,
|
||||
_ => 5 * MS,
|
||||
};
|
||||
for (b, d) in back.cues.iter().zip(&doc.cues) {
|
||||
assert!((b.start.0 - d.start.0).abs() <= tolerance, "{format:?} start {:?} against {:?}", b.start, d.start);
|
||||
assert!((b.end.0 - d.end.0).abs() <= tolerance, "{format:?} end {:?} against {:?}", b.end, d.end);
|
||||
}
|
||||
assert_eq!(back.cues[0].text.lines().count(), 2, "{format:?} keeps the line break");
|
||||
assert_eq!(plain(&back.cues[1]), "straight after, with & and <", "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_survive_where_the_format_has_them() {
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: ms(0), end: ms(2000), text: "plain\n<i>slanted</i>".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
for format in [Format::MicroDvd, Format::Mpl2] {
|
||||
let back = parse(&write(&doc, format, WriteOptions::default()), format).expect("parse");
|
||||
assert_eq!(back.cues[0].text, "plain\n<i>slanted</i>", "{format:?}");
|
||||
}
|
||||
// SAMI keeps inline tags too.
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: ms(0), end: ms(2000), text: "a <b>bold</b> <i>and</i> <u>more</u>".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(parse(&write(&doc, Format::Sami, WriteOptions::default()), Format::Sami).expect("parse").cues[0].text, doc.cues[0].text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn microdvd_counts_frames_at_the_given_rate() {
|
||||
let doc = Document { cues: vec![Cue { start: Tick(2 * T), end: Tick(4 * T), text: "x".into(), ..Default::default() }], ..Default::default() };
|
||||
let bytes = write(&doc, Format::MicroDvd, WriteOptions { rate: Some(FrameRate::FPS_25), ..Default::default() });
|
||||
assert_eq!(String::from_utf8(bytes.clone()).expect("utf8"), "{1}{1}25.000\n{50}{100}x\n");
|
||||
let back = parse(&bytes, Format::MicroDvd).expect("parse");
|
||||
assert_eq!((back.cues[0].start, back.cues[0].end), (Tick(2 * T), Tick(4 * T)));
|
||||
|
||||
for header in ["{1}{1}25.000", "{0}{0}25.000"] {
|
||||
let fixture = format!("{header}\n{{50}}{{100}}First cue\n{{100}}{{150}}23.976\n");
|
||||
let parsed = parse(fixture.as_bytes(), Format::MicroDvd).expect("parse rate header fixture");
|
||||
assert_eq!(parsed.cues.len(), 2, "{header}");
|
||||
assert_eq!((parsed.cues[0].start, parsed.cues[0].end), (Tick(2 * T), Tick(4 * T)), "{header}");
|
||||
assert_eq!((parsed.cues[1].start, parsed.cues[1].end), (Tick(4 * T), Tick(6 * T)), "{header}");
|
||||
assert_eq!(parsed.cues[1].text, "23.976", "{header}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_finds_each_format() {
|
||||
for (format, text) in samples() {
|
||||
assert_eq!(detect(text.as_bytes(), None), Some(format), "{format:?}");
|
||||
let ext = FORMATS.iter().find(|f| f.0 == format).map(|f| f.2);
|
||||
assert_eq!(detect(text.as_bytes(), ext), Some(format), "{format:?} with its extension");
|
||||
}
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nx\n", None), Some(Format::Srt));
|
||||
// Cue text containing literal SubViewer markers must not hijack SRT detection
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nHere is a [SUBTITLE] tag\n", None), Some(Format::Srt));
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt));
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", None), Some(Format::Srt));
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", Some("srt")), Some(Format::Srt));
|
||||
// TTML with namespaced sami element is not SAMI
|
||||
assert_ne!(detect(b"<sami:tt xmlns:sami=\"http://www.w3.org/ns/ttml\"><head></head><body></body></sami:tt>", None), Some(Format::Sami));
|
||||
// Genuine SubViewer with only [SUBTITLE] header
|
||||
assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer));
|
||||
// Genuine SubViewer with long/truncated [TITLE] line
|
||||
let truncated_sv = format!("[INFORMATION]\n[TITLE]{}", "A".repeat(5000));
|
||||
assert_eq!(detect(truncated_sv.as_bytes(), None), Some(Format::SubViewer));
|
||||
assert_eq!(detect(b"just some prose\n", Some("txt")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_text_is_not_one_of_these_formats() {
|
||||
for (format, _, _) in FORMATS {
|
||||
assert!(parse(b"hello there\nthis is not a subtitle file\n", format).is_err(), "{format:?}");
|
||||
assert!(parse(b"", format).expect("empty").cues.is_empty(), "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_is_an_error_or_a_warning_never_a_panic() {
|
||||
let mut inputs: Vec<Vec<u8>> = vec![
|
||||
"{".repeat(10_000).into_bytes(),
|
||||
"{1}{1}".repeat(2000).into_bytes(),
|
||||
"{999999999}{999999999}x\n{1}{99999999999999999999}y\n{5}{3}z\n".into(),
|
||||
"[999999999][999999999]x\n[1][2".into(),
|
||||
"99999:99:99.99,99999:99:99.99\nx\n\n00:00:01.00,00:00:00.00\ny\n".into(),
|
||||
"99999999:00:00=x\n00:60:00=y\n00:00:00.=z\n".into(),
|
||||
"<sync start=".repeat(5000).into_bytes(),
|
||||
"<SAMI><SYNC Start=999999999999999999999><P>x<SYNC Start=-5>y<SYNC Start=1><<<<&&&&�&#x;".into(),
|
||||
format!("<SYNC Start=1>{}", "<font color=\"#fff\">".repeat(10_000)).into_bytes(),
|
||||
format!("<SYNC Start=1>{}", "<".repeat(10_000)).into_bytes(),
|
||||
vec![0xff, 0xfe, 0x00, 0xd8, 0x00],
|
||||
vec![0u8; 1000],
|
||||
];
|
||||
// deterministic noise
|
||||
let mut x = 0x9e37_79b9u32;
|
||||
for len in [10usize, 100, 1000] {
|
||||
let alphabet = b"{}[]<>:=,. \n|&#;0123456789abSYNC";
|
||||
let noise: Vec<u8> = (0..len)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
alphabet[x as usize % alphabet.len()]
|
||||
})
|
||||
.collect();
|
||||
inputs.push(noise);
|
||||
}
|
||||
for (format, _, _) in FORMATS {
|
||||
for input in &inputs {
|
||||
if let Ok(doc) = parse(input, format) {
|
||||
// what was read writes and reads again
|
||||
let again = write(&doc, format, WriteOptions::default());
|
||||
parse(&again, format).expect("a written file reads back");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cue_limit_applies() {
|
||||
let mut text = String::new();
|
||||
for i in 0..200 {
|
||||
text.push_str(&format!("[{}][{}]x\n", i * 10, i * 10 + 5));
|
||||
}
|
||||
assert_eq!(parse(text.as_bytes(), Format::Mpl2).expect("parse").cues.len(), 200);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod ass;
|
||||
mod legacy_text;
|
||||
mod limits;
|
||||
mod literal_roundtrips;
|
||||
mod mcc_708_timing;
|
||||
|
||||
+54
-14
@@ -319,23 +319,33 @@ fn solve_cmy_by<F: Forward + ?Sized>(model: &F, k: f64, limit: f64, seeds: &[[f6
|
||||
|
||||
const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]];
|
||||
|
||||
/// Black for a gray component `g` (the smallest of C, M, Y without black).
|
||||
/// Black for a gray component `g` (the smallest of C, M, Y without black), at most the total ink
|
||||
/// limit: the CMY solve gets `tac - k`, so black above `tac` would break the limit on its own.
|
||||
fn gcr(p: &CmykParams, g: f64) -> f64 {
|
||||
let Some(first) = p.gcr_curve.first() else {
|
||||
let k = match p.gcr_curve.first() {
|
||||
// The Photocraft profile's curve.
|
||||
return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) };
|
||||
};
|
||||
let mut k = first[1];
|
||||
for w in p.gcr_curve.windows(2) {
|
||||
let ([g0, k0], [g1, k1]) = (w[0], w[1]);
|
||||
if g >= g1 {
|
||||
k = k1;
|
||||
} else if g > g0 {
|
||||
k = k0 + (k1 - k0) * (g - g0) / (g1 - g0);
|
||||
break;
|
||||
None => {
|
||||
if g <= p.gcr_start {
|
||||
0.0
|
||||
} else {
|
||||
p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma)
|
||||
}
|
||||
}
|
||||
}
|
||||
k.clamp(0.0, 1.0)
|
||||
Some(first) => {
|
||||
let mut k = first[1];
|
||||
for w in p.gcr_curve.windows(2) {
|
||||
let ([g0, k0], [g1, k1]) = (w[0], w[1]);
|
||||
if g >= g1 {
|
||||
k = k1;
|
||||
} else if g > g0 {
|
||||
k = k0 + (k1 - k0) * (g - g0) / (g1 - g0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
k
|
||||
}
|
||||
};
|
||||
k.clamp(0.0, 1.0).min(p.tac.max(0.0))
|
||||
}
|
||||
|
||||
/// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve.
|
||||
@@ -712,6 +722,9 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> {
|
||||
if p.white_on_node && p.grid_b2a.is_multiple_of(2) {
|
||||
return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a)));
|
||||
}
|
||||
if !(p.tac.is_finite() && p.tac >= 0.0) {
|
||||
return Err(invalid_arg(format!("total ink limit {} must be finite and not negative", p.tac)));
|
||||
}
|
||||
let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x));
|
||||
if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) {
|
||||
return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve)));
|
||||
@@ -847,6 +860,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn total_ink_limit_must_be_finite_and_not_negative() {
|
||||
for tac in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
let p = CmykParams { grid_a2b: 2, grid_b2a: 2, tac, ..CmykParams::default() };
|
||||
assert!(cmyk_profile(&p).is_err(), "tac {tac}");
|
||||
}
|
||||
// `separate` is public and does not validate: black is still never negative.
|
||||
let p = CmykParams { tac: -0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() };
|
||||
assert_eq!(gcr(&p, 0.5), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curve_black_stays_within_the_ink_limit() {
|
||||
// Black from either the profile curve or the default empty-curve fallback never exceeds the ink limit.
|
||||
let m = CmykModel::coated(CmykParams::default().tvi);
|
||||
for gcr_curve in [vec![[0.0, 0.75]], vec![]] {
|
||||
for tac in [0.5, 0.0] {
|
||||
let p = CmykParams { tac, gcr_curve: gcr_curve.clone(), ..CmykParams::default() };
|
||||
assert!(gcr(&p, 1.0) <= p.tac, "tac {tac} curve {gcr_curve:?}");
|
||||
for target in [[50.0, 0.0, 0.0], [90.0, 0.0, 0.0], [30.0, 20.0, -10.0]] {
|
||||
let (cmyk, _) = separate(&m, &p, target, None);
|
||||
assert!(cmyk.iter().sum::<f64>() <= p.tac + 1e-6, "{target:?} -> {cmyk:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oklab_round_trips() {
|
||||
let m = CmykModel::coated(CmykParams::default().tvi);
|
||||
|
||||
@@ -430,6 +430,8 @@ fn separates_like_the_reference_application() {
|
||||
for (rgb, want) in REFERENCE_SEPARATIONS {
|
||||
for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) {
|
||||
let got = separation(intent, bpc, rgb);
|
||||
// `f32::max` drops a NaN, so a NaN ink would otherwise count as no difference.
|
||||
assert!(got.iter().all(|v| v.is_finite()), "{rgb:?} {intent:?} bpc {bpc}: {got:?}");
|
||||
let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max);
|
||||
eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})");
|
||||
worst = worst.max(diff);
|
||||
|
||||
@@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
Variation::WarmCool => (&words.cool, &words.warm),
|
||||
Variation::VividMuted => (&words.muted, &words.vivid),
|
||||
};
|
||||
Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Text::new(left.clone()).show(ui);
|
||||
Text::new(right.clone()).show(ui);
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::{Button, PopupMark};
|
||||
use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring};
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band};
|
||||
use craft_ui::contract::{
|
||||
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi,
|
||||
Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
|
||||
@@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra
|
||||
if style.ring {
|
||||
let ground =
|
||||
ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) });
|
||||
ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground);
|
||||
ui.draw().surface_styled(well.shrink(ring_band(well)), &ground);
|
||||
} else {
|
||||
ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge);
|
||||
}
|
||||
|
||||
@@ -448,7 +448,7 @@ pub struct ColorPanel<'a> {
|
||||
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: &'a [Srgba],
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
@@ -471,7 +471,7 @@ struct Inputs<'a> {
|
||||
wells: Option<&'a [PairWell; 2]>,
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: &'a [Srgba],
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> {
|
||||
wells: None,
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: &[],
|
||||
recent: None,
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags.
|
||||
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row
|
||||
/// for a host that gives them, an empty list included; without them it shows no row.
|
||||
pub fn recent(mut self, colors: &'a [Srgba]) -> Self {
|
||||
self.recent = colors;
|
||||
self.recent = Some(colors);
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{Swatch, SwatchSpacing};
|
||||
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::text::{HexField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
@@ -131,8 +132,8 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and
|
||||
/// picks nothing; a Shift click moves to the next mode.
|
||||
/// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end
|
||||
/// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode.
|
||||
fn spectrum(&mut self, ui: &mut Ui) {
|
||||
let mode = self.shown_mode();
|
||||
let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum };
|
||||
@@ -145,6 +146,7 @@ impl Body<'_> {
|
||||
.gamut(gamut)
|
||||
.gamut_revision(revision)
|
||||
.web_safe(self.now.web_safe_ramp)
|
||||
.square_boxes(true)
|
||||
.sizing(Sizing::Fill)
|
||||
.show(ui);
|
||||
self.ramp_events(ramp.edit.events);
|
||||
@@ -154,14 +156,19 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Recent Colors as a spaced palette; a pick sets the colour.
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
|
||||
/// is empty, where the first applied color will go.
|
||||
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
|
||||
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
|
||||
fn recent(&mut self, ui: &mut Ui) {
|
||||
if self.inputs.recent.is_empty() {
|
||||
let Some(recent) = self.inputs.recent else {
|
||||
return;
|
||||
};
|
||||
Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
if recent.is_empty() {
|
||||
return;
|
||||
}
|
||||
let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let mut current = self.color();
|
||||
let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced);
|
||||
if let Some(setup) = self.inputs.recent_setup {
|
||||
|
||||
@@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
use craft_ui::canvas::context_click;
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx,
|
||||
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi,
|
||||
PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{Marker, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
@@ -240,6 +240,11 @@ pub struct ColorRamp<'a> {
|
||||
/// Whether the white and black boxes follow the bar; on by default.
|
||||
#[prop]
|
||||
boxes: bool,
|
||||
/// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a
|
||||
/// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by
|
||||
/// its content and in a short one.
|
||||
#[prop]
|
||||
square_boxes: bool,
|
||||
/// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value.
|
||||
#[prop(into)]
|
||||
kind_name: Option<Label>,
|
||||
@@ -265,6 +270,7 @@ impl<'a> ColorRamp<'a> {
|
||||
web_safe: false,
|
||||
recolor_clicks: false,
|
||||
boxes: true,
|
||||
square_boxes: false,
|
||||
kind_name: None,
|
||||
colors: Arc::default(),
|
||||
shown_ends: ends,
|
||||
@@ -416,6 +422,12 @@ impl Component for ColorRamp<'_> {
|
||||
Some(Axis::X)
|
||||
}
|
||||
|
||||
/// With [`square_boxes`](ColorRamp::square_boxes), as tall as its two end boxes stacked, each as tall as it is wide;
|
||||
/// else the style's least, a color band.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
if self.square_boxes { Vec2::new(0.0, cx.style.boxes * 2.0) } else { Vec2::ZERO }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
@@ -136,11 +136,19 @@ pub(super) fn group_rename(groups: &[SwatchGroup], index: usize, text: &str) ->
|
||||
(!name.is_empty() && !groups.iter().enumerate().any(|(i, g)| i != index && g.name == name)).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header, then its swatches.
|
||||
/// Whether the browser shows a header row for `group`: every group but the one with an empty name, which holds the
|
||||
/// swatches outside every group.
|
||||
fn has_header(group: &SwatchGroup) -> bool {
|
||||
!group.name.is_empty()
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header (none for the swatches outside every group), then its swatches.
|
||||
fn flat<'a>(groups: impl IntoIterator<Item = &'a SwatchGroup>) -> Vec<SwatchKey> {
|
||||
let mut rows = Vec::new();
|
||||
for group in groups {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
if has_header(group) {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
}
|
||||
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
|
||||
}
|
||||
rows
|
||||
@@ -167,10 +175,21 @@ fn resolve_move(groups: &[SwatchGroup], names: &[&str], to: usize, parent: Optio
|
||||
(group < groups.len()).then_some((group, slot))
|
||||
}
|
||||
|
||||
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay.
|
||||
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay: each staying group
|
||||
/// whose first row (its header, or its first swatch when it has none) is above `to`. Groups never land above the
|
||||
/// swatches outside every group when those come first.
|
||||
fn group_slot(groups: &[SwatchGroup], names: &[&str], to: usize) -> usize {
|
||||
let remaining = flat(groups.iter().filter(|g| !names.contains(&g.name.as_str())));
|
||||
remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count()
|
||||
let mut row = 0;
|
||||
let mut slot = 0;
|
||||
let mut staying = groups.iter().filter(|g| !names.contains(&g.name.as_str())).peekable();
|
||||
let floor = usize::from(staying.peek().is_some_and(|g| !has_header(g)));
|
||||
for group in staying {
|
||||
if row < to {
|
||||
slot += 1;
|
||||
}
|
||||
row += usize::from(has_header(group)) + group.entries.len();
|
||||
}
|
||||
slot.max(floor)
|
||||
}
|
||||
|
||||
/// The `at` of each edit that moves `moved` (in library order) one by one within `order`, so that they end up together
|
||||
@@ -352,8 +371,8 @@ impl SwatchLibrary {
|
||||
}
|
||||
|
||||
/// Applies a reorder of the browser: swatches go into a group at a place, or groups to a place among the
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches) that remain once the moved ones are
|
||||
/// taken out. Anything else leaves the library as it is.
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches; no header for the group with an empty
|
||||
/// name) that remain once the moved ones are taken out. Anything else leaves the library as it is.
|
||||
pub fn apply_reorder(&mut self, mv: &ReorderMove<SwatchKey>) -> bool {
|
||||
if mv.copy {
|
||||
return false;
|
||||
@@ -641,17 +660,24 @@ fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>
|
||||
}
|
||||
|
||||
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
|
||||
/// colour value (the name alone for a swatch without a colour).
|
||||
/// colour value (the name alone for a swatch without a colour). A group with an empty name holds the swatches outside
|
||||
/// every group: its swatches show at the top level, with no header.
|
||||
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
|
||||
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
|
||||
for group in groups {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
let header = has_header(group);
|
||||
let depth = usize::from(header);
|
||||
if header {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
}
|
||||
for entry in &group.entries {
|
||||
let named = match entry.color() {
|
||||
Some(color) => format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())),
|
||||
None => entry.name.clone(),
|
||||
};
|
||||
rows.push(PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named));
|
||||
rows.push(
|
||||
PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), depth).tooltip(named.clone()).accessible_name(named),
|
||||
);
|
||||
}
|
||||
}
|
||||
rows
|
||||
@@ -676,6 +702,27 @@ pub(crate) mod tests {
|
||||
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
|
||||
}
|
||||
|
||||
/// The swatches outside every group (the group with an empty name) have no header row, so a place below them
|
||||
/// counts them as rows: a group dropped there lands after them, and a swatch dropped there joins them. A group
|
||||
/// dropped above them lands after them too.
|
||||
#[trial]
|
||||
fn drops_below_the_ungrouped_swatches_land_after_them() {
|
||||
let library = SwatchLibrary::new(vec![group("", &["A", "B"]), group("G", &["C"]), group("H", &["D"])]);
|
||||
let rows: Vec<_> = swatch_rows(&library.groups, &SwatchesWords::default()).into_iter().map(|row| row.key).collect();
|
||||
assert_eq!(rows, flat(&library.groups), "the reorder counts the rows the browser shows");
|
||||
|
||||
for to in [0, 2] {
|
||||
let mut moved = library.clone();
|
||||
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Group("H".to_owned()), vec![SwatchKey::Group("H".to_owned())], to, false)));
|
||||
let order: Vec<_> = moved.groups.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(order, ["", "H", "G"], "H dropped at row {to} lands below the ungrouped swatches, above G");
|
||||
}
|
||||
|
||||
let mut moved = library.clone();
|
||||
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Swatch("C".to_owned()), vec![SwatchKey::Swatch("C".to_owned())], 2, false)));
|
||||
assert_eq!(moved.find("C"), Some(SwatchAt::new(0, 2)), "C joins the ungrouped swatches, after B");
|
||||
}
|
||||
|
||||
/// Edits that move several items down or up give the order the browser's own reorder gives.
|
||||
#[trial]
|
||||
fn multi_item_moves_apply_as_the_reorder_does() {
|
||||
|
||||
@@ -18,7 +18,7 @@ use craft_ui::patterns::presets::{
|
||||
};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use egui::{Response, Ui};
|
||||
use egui::{AsIdSalt, IdSalt, Response, Ui};
|
||||
|
||||
use super::library::{HostThumb, find_swatch, has, panel_source};
|
||||
use super::menu::event_edits;
|
||||
@@ -77,6 +77,8 @@ type PayloadAdder<'a> = Box<dyn for<'b> Fn(PresetBrowser<'b, SwatchKey>) -> Pres
|
||||
/// [`search`](SwatchesPanel::search), [`row_icons`](SwatchesPanel::row_icons), [`takes_drop`](SwatchesPanel::takes_drop)
|
||||
/// and [`row_items`](SwatchesPanel::row_items) pass through; the events they cause come out in
|
||||
/// [`SwatchesPanelOutput::events`].
|
||||
/// - [`document`](SwatchesPanel::document) keeps the browser's own state (an open rename field, the scroll position)
|
||||
/// per document, so a host that shows one panel for several documents does not carry it from one to another.
|
||||
/// - It fills the room it is given, and its browser scrolls the swatches: show it outside a body that scrolls.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
@@ -96,6 +98,7 @@ pub struct SwatchesPanel<'a> {
|
||||
takes_drop: Option<DropMaker<'a>>,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
document: Option<IdSalt>,
|
||||
}
|
||||
|
||||
/// What the body decided; `show` stores the state and reports the rest after the real run.
|
||||
@@ -126,6 +129,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
takes_drop: None,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
document: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +220,14 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll
|
||||
/// position) for each document, so a rename left open in one document does not open on another document's
|
||||
/// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in.
|
||||
pub fn document(mut self, document: impl AsIdSalt) -> Self {
|
||||
self.document = Some(IdSalt::new(document));
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws the panel and returns the user's actions this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
|
||||
let SwatchesPanel {
|
||||
@@ -234,12 +246,15 @@ impl<'a> SwatchesPanel<'a> {
|
||||
takes_drop,
|
||||
payloads,
|
||||
row_items,
|
||||
document,
|
||||
} = self;
|
||||
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
let words = Env::of(ui).words::<SwatchesWords>();
|
||||
let mut held_state = Held::new(state);
|
||||
let ctx = ui.ctx().clone();
|
||||
let browser_id = ui.scope_id();
|
||||
// A document's browser has an id of its own; otherwise the browser takes the scope id of the `Ui` it is shown in.
|
||||
let document_id = document.map(|document| ui.scope_id().with(document));
|
||||
let browser_id = document_id.unwrap_or_else(|| ui.scope_id());
|
||||
let icons: BTreeMap<&str, Vec<(IconSpec<'static>, String)>> = match &row_icons {
|
||||
Some(icons) => {
|
||||
groups.iter().flat_map(|g| g.entries.iter()).map(|e| (e.name.as_str(), icons(&SwatchKey::Swatch(e.name.clone())))).collect()
|
||||
@@ -267,6 +282,9 @@ impl<'a> SwatchesPanel<'a> {
|
||||
.select(select)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.selection(Bind::bound(&mut st.selection));
|
||||
if let Some(id) = document_id {
|
||||
browser = browser.browser_id(id);
|
||||
}
|
||||
if let Some(options) = footer_options {
|
||||
browser = browser.footer(options);
|
||||
}
|
||||
|
||||
@@ -202,6 +202,50 @@ impl WheelRig {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names focus takes from the hue ring of a wheel shown in an arena (a split area's body) between two buttons,
|
||||
/// one per Tab in `keys` (with its modifiers).
|
||||
fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>> {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = craft_ui::buttons::Button::new("Before").show(ui);
|
||||
let limits = |_: &usize| craft_ui::contract::SizeLimits::default();
|
||||
let rules = craft_ui::docking::tree::FrameRules::new(&limits);
|
||||
let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0));
|
||||
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| {
|
||||
let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui);
|
||||
});
|
||||
let _ = craft_ui::buttons::Button::new("After").show(ui);
|
||||
});
|
||||
fixture.room(vec2(420.0, 420.0));
|
||||
fixture.settle();
|
||||
let hue = fixture.by_label("Hue").expect("the ring");
|
||||
fixture.access(AccessActionKind::Focus, &hue);
|
||||
fixture.idle(2);
|
||||
let focused = |fixture: &Fixture| {
|
||||
let tree = fixture.tree();
|
||||
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
|
||||
};
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("Hue"), "{inner:?}: the ring takes focus");
|
||||
keys.iter()
|
||||
.map(|mods| {
|
||||
fixture.key(Key::Tab, *mods);
|
||||
fixture.idle(2);
|
||||
focused(&fixture)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// In an arena, as in a docked panel, Tab from the hue ring lands on the saturation and brightness control, also when a
|
||||
/// square shows it through its own folded picker, then goes on past the wheel; Shift-Tab comes back the same way.
|
||||
#[trial]
|
||||
fn in_an_arena_tab_from_the_ring_reaches_the_saturation_and_brightness_control() {
|
||||
let (on, back) = (Modifiers::NONE, Modifiers::SHIFT);
|
||||
for inner in [WheelInner::Triangle, WheelInner::Square] {
|
||||
let walk = arena_tab_walk(inner, &[on, on, back, back]);
|
||||
let expected = ["Saturation and brightness", "After", "Saturation and brightness", "Hue"].map(|name| Some(name.to_owned()));
|
||||
assert_eq!(walk, expected, "{inner:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A square wheel hands a press between the square and the ring to the square; its named markers speak their colour,
|
||||
/// pick on a click, and a press held on one still drags the ring; Shift snaps a ring drag to 45 degrees, in both
|
||||
/// variants.
|
||||
|
||||
@@ -1,13 +1,49 @@
|
||||
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, and its swatch size.
|
||||
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, its swatch size and its ring.
|
||||
|
||||
use craft_color_ui::ui::{Paint, PaintChip, PaintChipSize};
|
||||
use craft_color_ui::ui::{GradientPreview, Paint, PaintChip, PaintChipSize};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::PopupMark;
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, Shape};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Every shape of the frame, groups opened.
|
||||
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
|
||||
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
|
||||
}
|
||||
|
||||
/// A ring chip wider than it is high keeps an open middle: the hole inside the band is at least a third of the chip's
|
||||
/// height, and the band is as thick at the sides as at the top and bottom. Checked for a solid paint, drawn as a band
|
||||
/// of the colour, and for a gradient, whose middle is covered by the surface the chip sits on.
|
||||
#[trial]
|
||||
fn a_wide_ring_chip_keeps_an_open_middle() {
|
||||
let gradient = GradientPreview::new(vec![(0.0, Srgba::rgb(0.2, 0.4, 0.8)), (1.0, Srgba::WHITE)]);
|
||||
for paint in [Paint::Solid(Srgba::rgb(0.2, 0.4, 0.8)), Paint::Gradient(gradient)] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut paint = paint.clone();
|
||||
let _ = PaintChip::new("Stroke", Bind::bound(&mut paint), Srgba::BLACK).ring(true).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let well = fixture.by_role(Role::COLOR_WELL).first().copied().expect("the chip is a colour well").rect;
|
||||
assert!(well.width() > well.height(), "the chip is wider than it is high");
|
||||
// The hole is the smallest rect drawn round the well's centre.
|
||||
let hole = flat(fixture.frame_shapes())
|
||||
.into_iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::Rect(rect) => Some(rect.rect),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|rect: &Rect| rect.center().distance(well.center()) < 0.5 && rect.width() < well.width() - 2.0)
|
||||
.min_by(|a, b| a.area().total_cmp(&b.area()))
|
||||
.expect("a hole inside the band");
|
||||
assert!(hole.height() >= well.height() / 3.0, "the hole is {:?} in a {:?} well", hole.size(), well.size());
|
||||
let (side, top) = (hole.left() - well.left(), hole.top() - well.top());
|
||||
assert!((side - top).abs() < 0.5, "the band is {side} at the sides and {top} at the top");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the menu mark, past the well, opens the chip's popover, as a click on the well does.
|
||||
#[trial]
|
||||
fn a_click_on_the_menu_mark_opens_the_popover() {
|
||||
|
||||
@@ -7,15 +7,17 @@ use std::rc::Rc;
|
||||
use craft_behavior::{EditEvent, Mixed, Selection};
|
||||
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
|
||||
use craft_color_ui::ui::{
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey,
|
||||
SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows,
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
|
||||
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
SwatchesWords, swatch_rows,
|
||||
};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::{ColorModel as _, HsbModel, Srgba};
|
||||
use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::{Label, Scale};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
@@ -254,6 +256,36 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
|
||||
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
|
||||
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
|
||||
#[trial]
|
||||
fn a_fill_stroke_spectrum_keeps_its_end_boxes_square_in_a_content_sized_host() {
|
||||
for (room, content_sized) in [(COLOR_ROOM, true), (Vec2::new(280.0, 96.0), false)] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let show = |ui: &mut egui::Ui, state: &mut ColorPanelState| {
|
||||
let _ = ColorPanel::new(Bind::bound(state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke).show(ui);
|
||||
};
|
||||
if content_sized {
|
||||
let _ = Stack::new().show(ui, |ui, _| show(ui, &mut state));
|
||||
} else {
|
||||
show(ui, &mut state);
|
||||
}
|
||||
});
|
||||
fixture.room(room).settle();
|
||||
let bar = fixture.by_label("Color Ramp").expect("the spectrum").rect;
|
||||
let ends: Vec<_> = fixture
|
||||
.by_role(Role::BUTTON)
|
||||
.into_iter()
|
||||
.filter(|button| button.rect.left() >= bar.right() - 0.5 && button.rect.y_range().intersects(bar.y_range()))
|
||||
.collect();
|
||||
assert_eq!(ends.len(), 2, "{room:?}: the white and black boxes beside the bar ({bar:?})");
|
||||
for end in ends {
|
||||
assert!(end.rect.height() >= end.rect.width() - 0.5, "{room:?}: an end box at least square ({:?} beside {bar:?})", end.rect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SWATCHES: [(&str, [f32; 3]); 6] = [
|
||||
("Red", [0.90, 0.28, 0.30]),
|
||||
("Orange", [0.97, 0.42, 0.08]),
|
||||
@@ -408,6 +440,28 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
|
||||
}
|
||||
|
||||
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
|
||||
/// it; a host that gives no recent colors gets no row.
|
||||
#[trial]
|
||||
fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() {
|
||||
let caption = |recent: Option<&'static [Srgba]>| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
|
||||
let _ = match recent {
|
||||
Some(colors) => panel.recent(colors),
|
||||
None => panel,
|
||||
}
|
||||
.show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
fixture.texts().iter().any(|run| run.text == "Recent Colors")
|
||||
};
|
||||
assert!(caption(Some(&[])), "an empty list shows the row's caption");
|
||||
assert!(caption(Some(&RECENT)), "a list with a color shows it");
|
||||
assert!(!caption(None), "a host with no recent colors shows no row");
|
||||
}
|
||||
|
||||
/// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first;
|
||||
/// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`.
|
||||
#[trial]
|
||||
@@ -541,6 +595,30 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
|
||||
}
|
||||
|
||||
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
|
||||
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
|
||||
#[trial]
|
||||
fn swatches_outside_every_group_show_without_a_header() {
|
||||
let entry = |name: &str, rgb: [f32; 3]| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(rgb));
|
||||
let groups = vec![
|
||||
SwatchGroup { name: String::new(), entries: vec![entry("Red", [1.0, 0.0, 0.0]), entry("Blue", [0.0, 0.0, 1.0])] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Green", [0.0, 1.0, 0.0])] },
|
||||
];
|
||||
let (fixture, _) = swatches_rig(groups, SwatchesState::default());
|
||||
let tree = fixture.tree();
|
||||
let unnamed: Vec<_> = tree
|
||||
.keys()
|
||||
.into_iter()
|
||||
.filter(|&key| matches!(tree.role_of(key), Some(Role::HEADING | Role::BUTTON)))
|
||||
.filter(|&key| tree.name_of(key).is_none_or(|name| name.is_empty() || name.starts_with(',')))
|
||||
.map(|key| (tree.role_of(key), tree.name_of(key), tree.bounds_of(key)))
|
||||
.collect();
|
||||
assert!(unnamed.is_empty(), "every heading and button is named, starting with a label: {unnamed:?}");
|
||||
assert!(fixture.by_label("Red, #ff0000").is_some(), "the ungrouped swatches show");
|
||||
let headings: Vec<_> = tree.with_role(Role::HEADING).into_iter().filter_map(|key| tree.name_of(key)).collect();
|
||||
assert!(headings.iter().any(|name| name.starts_with("Other")), "a named group keeps its header: {headings:?}");
|
||||
}
|
||||
|
||||
/// Tb-8 (5): a click uses any swatch, as production applied every one: a colour swatch reports its colour, and a
|
||||
/// gradient, pattern or None swatch reports where it is with no colour, for the host to apply its paint. The panel
|
||||
/// reported only colour swatches.
|
||||
@@ -628,6 +706,34 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
|
||||
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
|
||||
/// swatch of the same name opens no field, and Enter there renames nothing.
|
||||
#[trial]
|
||||
fn a_rename_left_open_stays_with_its_document() {
|
||||
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
|
||||
let groups = vec![SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] }];
|
||||
let document = Rc::new(Cell::new(1_u32));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let (shown, seen) = (Rc::clone(&document), Rc::clone(&edits));
|
||||
let mut state = SwatchesState::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED).document(shown.get()).show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
});
|
||||
fixture.room(Vec2::new(320.0, 400.0)).settle();
|
||||
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
|
||||
fixture.click(&red).key(Key::F2, Modifiers::NONE).type_text("X").settle();
|
||||
let typed = |fixture: &Fixture, text: &str| {
|
||||
let tree = fixture.tree();
|
||||
tree.keys().into_iter().any(|key| tree.value_of(key) == Some(text))
|
||||
};
|
||||
assert!(typed(&fixture, "X"), "the rename field is open in the first document");
|
||||
document.set(2);
|
||||
fixture.settle();
|
||||
fixture.type_text("Y").key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
|
||||
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
|
||||
}
|
||||
@@ -768,3 +874,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() {
|
||||
fixture.click(&marker).idle(1);
|
||||
assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker");
|
||||
}
|
||||
|
||||
/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its
|
||||
/// right edge.
|
||||
#[trial]
|
||||
fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
|
||||
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let grid = fixture.by_label("Variations").expect("the variations grid").rect;
|
||||
let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted"));
|
||||
let (shades, tints) = (run("Shades"), run("Tints"));
|
||||
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
|
||||
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
|
||||
}
|
||||
@@ -34,10 +34,18 @@ craft-flags = { workspace = true, optional = true }
|
||||
dirs = { version = "7", optional = true }
|
||||
log = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours).
|
||||
craft-platform = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
# Reserve an unused control port without opening a listener, including between assertions.
|
||||
socket2 = "0.6.5"
|
||||
|
||||
[[test]]
|
||||
name = "agents"
|
||||
required-features = ["agents"]
|
||||
+268
-119
@@ -101,7 +101,7 @@ impl App {
|
||||
/// Record `port` as the running app's, readable only by the user like the token files.
|
||||
pub fn write_current_port(&self, port: u16) -> Result<PathBuf> {
|
||||
let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;
|
||||
self.write_token_file(&path, &port.to_string())?;
|
||||
self.write_private(&path, &port.to_string(), true)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -141,16 +141,27 @@ impl App {
|
||||
}
|
||||
|
||||
/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`
|
||||
/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one
|
||||
/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file
|
||||
/// is removed and no token is written. A file left by an earlier launch is replaced. The process
|
||||
/// file beside it ([`pid_path`]) records this process, best effort.
|
||||
/// and the file `0600` on Unix; on Windows the file is created with an access list of the user
|
||||
/// and SYSTEM only and the token is written through the handle that created it
|
||||
/// (`create_for_user`), so the file never has its folder's access list. A file left by an
|
||||
/// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process,
|
||||
/// best effort.
|
||||
pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> {
|
||||
self.write_private(path, token, false)
|
||||
}
|
||||
|
||||
/// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while
|
||||
/// this one was being created is replaced (the discovery file, which names the latest launch);
|
||||
/// otherwise this write fails and that launch's token stays.
|
||||
fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some());
|
||||
let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace);
|
||||
#[cfg(not(windows))]
|
||||
let restrict = |_: &Path| Ok(());
|
||||
write_token_file_with(path, token, restrict)
|
||||
let create = {
|
||||
let _ = replace;
|
||||
create_new_file
|
||||
};
|
||||
write_token_file_with(path, token, create)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows).
|
||||
fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
|
||||
/// [`App::write_token_file`], with `create` making the new file with its contents, readable only
|
||||
/// by the user.
|
||||
fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> {
|
||||
let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let _ = std::fs::remove_file(path);
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let opened = opts.open(path)?;
|
||||
// On a refusal the file goes with the closure, so it is closed before it is removed.
|
||||
let mut f = match restrict(path).map(|()| opened) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
f.write_all(token.as_bytes())?;
|
||||
f.write_all(b"\n")?;
|
||||
f.sync_all()?;
|
||||
create(path, format!("{token}\n").as_bytes())?;
|
||||
let pid = std::process::id();
|
||||
let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));
|
||||
let _ = std::fs::write(pid_path(path), line);
|
||||
@@ -369,74 +367,148 @@ fn held_by_another(path: &Path, token: &str) -> bool {
|
||||
read_token(path).is_some_and(|held| !tokens_match(&held, token.trim()))
|
||||
}
|
||||
|
||||
/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process
|
||||
/// is left suspended (security software holding it), and waiting on it without a limit froze
|
||||
/// the app.
|
||||
#[cfg(windows)]
|
||||
const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// How a run of `icacls` ended.
|
||||
#[cfg(any(windows, test))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum IcaclsEnd {
|
||||
Succeeded,
|
||||
Failed,
|
||||
/// It didn't finish within [`ICACLS_LIMIT`] and was ended.
|
||||
TimedOut,
|
||||
/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a
|
||||
/// file created this way has its folder's access list; the token file there is made by
|
||||
/// `create_for_user`.
|
||||
fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let mut f = opts.open(path)?;
|
||||
f.write_all(contents)?;
|
||||
f.sync_all()
|
||||
}
|
||||
|
||||
/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is
|
||||
/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder,
|
||||
/// the user's own local app data, which other users can't read by default; nothing is known about
|
||||
/// the permissions of any other folder.
|
||||
/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell;
|
||||
/// on some computers a new process is left suspended (security software holding it), and waiting
|
||||
/// on it without a limit froze the app.
|
||||
#[cfg(windows)]
|
||||
const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Windows: create `path` with the current user as owner and an access list of that user and
|
||||
/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written
|
||||
/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`.
|
||||
/// Another account never gets a moment in which the file has its folder's access list and could be
|
||||
/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names;
|
||||
/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and
|
||||
/// what `replace` changes.
|
||||
#[cfg(windows)]
|
||||
fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> {
|
||||
use craft_platform::owner_only;
|
||||
/// How many creates that were not waited for are still running.
|
||||
static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c));
|
||||
create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0
|
||||
}
|
||||
|
||||
/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names
|
||||
/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that
|
||||
/// folder's permissions; in the default folder, the user's own local app data, which other users
|
||||
/// can't read by default, `path` created with that folder's access list ([`create_new_file`]).
|
||||
#[cfg(any(windows, test))]
|
||||
fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> {
|
||||
match end {
|
||||
IcaclsEnd::Succeeded => Ok(()),
|
||||
IcaclsEnd::TimedOut if !custom_folder => Ok(()),
|
||||
IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))),
|
||||
IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))),
|
||||
fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> {
|
||||
if custom_folder {
|
||||
Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display())))
|
||||
} else {
|
||||
create_new_file(path, contents)
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows: drop inherited entries and grant only the current user full access. An `icacls`
|
||||
/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means.
|
||||
#[cfg(windows)]
|
||||
fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?;
|
||||
let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty());
|
||||
let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}"));
|
||||
let child = std::process::Command::new("icacls")
|
||||
.arg(path)
|
||||
.args(["/inheritance:r", "/grant:r", &format!("{who}:F")])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.creation_flags(0x0800_0000)
|
||||
.spawn()?;
|
||||
let end = match wait_within(child, ICACLS_LIMIT)? {
|
||||
Some(status) if status.success() => IcaclsEnd::Succeeded,
|
||||
Some(_) => IcaclsEnd::Failed,
|
||||
None => IcaclsEnd::TimedOut,
|
||||
/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its
|
||||
/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path`
|
||||
/// (`.<name>.<process id>.<count>.tmp`), and the file takes the name `path` only once `private`
|
||||
/// has finished, so `path` never holds a file that is still being written: with `replace` by a
|
||||
/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`],
|
||||
/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool
|
||||
/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result.
|
||||
/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its
|
||||
/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any
|
||||
/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that
|
||||
/// leaves new processes suspended holds at most the threads that were started together. The
|
||||
/// thread's handle is returned for tests.
|
||||
#[cfg(any(windows, test))]
|
||||
fn create_within(
|
||||
path: &Path,
|
||||
contents: &[u8],
|
||||
custom_folder: bool,
|
||||
replace: bool,
|
||||
limit: std::time::Duration,
|
||||
stuck: &'static std::sync::atomic::AtomicUsize,
|
||||
private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static,
|
||||
) -> (Result<()>, Option<std::thread::JoinHandle<()>>) {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{RecvTimeoutError, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
/// Numbers the thread's files within this process.
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
if stuck.load(Ordering::Acquire) > 0 {
|
||||
return (not_waited_for(path, contents, custom_folder), None);
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
|
||||
let (sender, receiver) = channel();
|
||||
// Set under the lock when the caller stops waiting; the thread reads it under the same lock
|
||||
// before it reports, so its result is either received or its file is removed.
|
||||
let abandoned = Arc::new(Mutex::new(false));
|
||||
let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned));
|
||||
let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || {
|
||||
let made = private(&own_file, &owned_contents);
|
||||
let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if *abandoned {
|
||||
let _ = std::fs::remove_file(&own_file);
|
||||
stuck.fetch_sub(1, Ordering::AcqRel);
|
||||
} else {
|
||||
let _ = sender.send(made);
|
||||
}
|
||||
});
|
||||
let handle = match spawned {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => return (Err(e), None),
|
||||
};
|
||||
restriction_result(end, custom_folder, path)
|
||||
let made = match receiver.recv_timeout(limit) {
|
||||
Ok(made) => made,
|
||||
Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))),
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match receiver.try_recv() {
|
||||
Ok(made) => made,
|
||||
Err(_) => {
|
||||
*abandoned = true;
|
||||
stuck.fetch_add(1, Ordering::AcqRel);
|
||||
drop(abandoned);
|
||||
return (not_waited_for(path, contents, custom_folder), Some(handle));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let placed = match made {
|
||||
// `owner_only` ended a tool that ran out of its own time: the same as not waiting.
|
||||
Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder),
|
||||
made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }),
|
||||
};
|
||||
let _ = std::fs::remove_file(&staged);
|
||||
(placed, Some(handle))
|
||||
}
|
||||
|
||||
/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it
|
||||
/// hasn't finished by then.
|
||||
/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch
|
||||
/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a
|
||||
/// `create_new` there would, instead of replacing the first one's token. The new name is a hard
|
||||
/// link. On a volume without hard links the file is renamed once `path` is found free; there a
|
||||
/// launch that puts its file at `path` between that check and the rename has it replaced, as std
|
||||
/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the
|
||||
/// caller to remove.
|
||||
#[cfg(any(windows, test))]
|
||||
fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result<Option<std::process::ExitStatus>> {
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
fn place_new(staged: &Path, path: &Path) -> Result<()> {
|
||||
match std::fs::hard_link(staged, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => {
|
||||
Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display())))
|
||||
}
|
||||
if start.elapsed() >= limit {
|
||||
// Not waited for afterwards: a suspended process may not end at once.
|
||||
let _ = child.kill();
|
||||
return Ok(None);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
Err(_) => std::fs::rename(staged, path),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,50 +528,127 @@ mod tests {
|
||||
/// An app with no data folder and no environment, whose times read `t<seconds>`.
|
||||
const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 };
|
||||
|
||||
/// #6145: a child that doesn't finish in time is given up on, not waited for forever.
|
||||
#[cfg(unix)]
|
||||
/// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder
|
||||
/// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created
|
||||
/// anyway and holds the token. Either way the file the late create makes is removed when it
|
||||
/// finishes and never takes the token file's name, even when a later write has put a file
|
||||
/// there. While it runs, the next create starts no thread of its own. A create that finishes in
|
||||
/// time puts its file in place unless a file already has the name, and one that fails leaves
|
||||
/// nothing. A create that fails as timed out by itself is taken as one not waited for.
|
||||
#[test]
|
||||
fn a_slow_child_is_waited_for_only_so_long() {
|
||||
use std::time::{Duration, Instant};
|
||||
let start = Instant::now();
|
||||
let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap();
|
||||
assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none());
|
||||
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
let quick = std::process::Command::new("true").spawn().unwrap();
|
||||
assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success()));
|
||||
let failing = std::process::Command::new("false").spawn().unwrap();
|
||||
assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success()));
|
||||
}
|
||||
|
||||
/// #6145's freeze fix stays in the default folder, the user's own; a folder picked with
|
||||
/// the app's `CONTROL_DIR` gets no token unless the file was really restricted.
|
||||
#[test]
|
||||
fn only_the_default_folder_accepts_an_icacls_that_timed_out() {
|
||||
let path = Path::new("control/7878.token");
|
||||
for custom in [false, true] {
|
||||
assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok());
|
||||
assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err());
|
||||
fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::Duration;
|
||||
static STUCK: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let names = || {
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
};
|
||||
for custom in [true, false] {
|
||||
let path = dir.join("7878.port");
|
||||
let (go, wait) = channel::<()>();
|
||||
let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| {
|
||||
wait.recv().map_err(Error::other)?;
|
||||
create_new_file(p, c)
|
||||
});
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 1);
|
||||
if custom {
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
assert!(!path.exists());
|
||||
let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") };
|
||||
let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused);
|
||||
assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
assert!(none.is_none());
|
||||
// A later write of the same contents, as a retry of the same port would make.
|
||||
create_new_file(&path, b"7878\n").unwrap();
|
||||
} else {
|
||||
made.unwrap();
|
||||
}
|
||||
go.send(()).unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 0);
|
||||
assert_eq!(names(), ["7878.port"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("7878"));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok());
|
||||
let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::TimedOut);
|
||||
assert!(e.to_string().contains("7878.token"), "{e}");
|
||||
let path = dir.join("quick.token");
|
||||
let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("quick"));
|
||||
// Another launch's file at the name is kept, as `create_new` keeps it.
|
||||
let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists);
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("quick"));
|
||||
// With `replace` (the discovery file) the later launch's file takes the name.
|
||||
let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("later"));
|
||||
let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) };
|
||||
let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused);
|
||||
assert!(made.is_err());
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
// A create whose tool was ended after its own limit, within this one, is taken as one
|
||||
// that was not waited for.
|
||||
let ended =
|
||||
|_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) };
|
||||
let path = dir.join("ended.token");
|
||||
let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended);
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["ended.token", "quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("ended"));
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A file that couldn't be restricted is removed, empty and with no process file beside it, and
|
||||
/// the error goes to the caller. A restricted one gets its token.
|
||||
/// A file that couldn't be created leaves no process file beside it, and the error goes to the
|
||||
/// caller. A created one gets the token and a newline.
|
||||
#[test]
|
||||
fn a_token_file_that_could_not_be_restricted_is_removed() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id()));
|
||||
fn a_token_file_that_could_not_be_created_leaves_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id()));
|
||||
let path = dir.join("7879.token");
|
||||
let e = write_token_file_with(&path, "secret-token", |p| {
|
||||
assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in");
|
||||
restriction_result(IcaclsEnd::TimedOut, true, p)
|
||||
})
|
||||
.unwrap_err();
|
||||
let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::TimedOut);
|
||||
assert!(!path.exists() && !pid_path(&path).exists());
|
||||
write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap();
|
||||
write_token_file_with(&path, "secret-token", create_new_file).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n");
|
||||
assert!(pid_path(&path).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// On Windows the token file is its user's alone from the moment it exists: in a folder that
|
||||
/// lets Users read what is created in it, the file has no entry for Users and no other
|
||||
/// account's access.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_token_file_is_private_from_the_start_on_windows() {
|
||||
use craft_platform::owner_only;
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
|
||||
let path = dir.join("7880.token");
|
||||
TEST.write_token_file(&path, "secret-token").unwrap();
|
||||
let sddl = owner_only::sddl_of(&path).unwrap();
|
||||
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
|
||||
assert_eq!(read_token(&path).as_deref(), Some("secret-token"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::*;
|
||||
use crate::ControlRequest;
|
||||
use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits};
|
||||
use socket2::{Domain, Socket, Type};
|
||||
use std::ffi::OsString;
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
@@ -78,9 +79,14 @@ fn addr(port: u16) -> String {
|
||||
format!("127.0.0.1:{port}")
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn free_port() -> u16 {
|
||||
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
/// Keep this port bound without listening, so another normal test listener cannot take it.
|
||||
fn reserve_non_listening_port() -> (Socket, u16) {
|
||||
let reserved = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap();
|
||||
let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0));
|
||||
reserved.bind(&address.into()).unwrap();
|
||||
let port = reserved.local_addr().unwrap().as_socket().unwrap().port();
|
||||
assert_ne!(port, 0);
|
||||
(reserved, port)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -115,13 +121,22 @@ fn a_wrong_token_or_none_is_refused() {
|
||||
|
||||
#[test]
|
||||
fn an_app_not_running_says_how_to_start_it() {
|
||||
let port = free_port();
|
||||
let (reserved, port) = reserve_non_listening_port();
|
||||
let mut c = Connection::new(APP, &addr(port), Some(TOKEN));
|
||||
let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err();
|
||||
let CallError::NotRunning(m) = &e else { panic!("{e:?}") };
|
||||
assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}");
|
||||
assert!(m.contains(&format!("`probe --control {port}`")), "{m}");
|
||||
assert_eq!(c.try_connect().unwrap_err().kind(), std::io::ErrorKind::NotConnected);
|
||||
drop(reserved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_not_running_fixture_keeps_its_port_from_another_listener() {
|
||||
let (reserved, port) = reserve_non_listening_port();
|
||||
let rival = TcpListener::bind(("127.0.0.1", port));
|
||||
assert!(rival.is_err(), "another listener acquired the reserved port");
|
||||
drop(reserved);
|
||||
}
|
||||
|
||||
/// An app that goes away during a call is lost, not "not running"; the next call says it is not
|
||||
|
||||
@@ -224,11 +224,13 @@ craft-gpu = { workspace = true, optional = true }
|
||||
craft-gpu-null = { workspace = true, optional = true }
|
||||
craft-gpu-providers = { workspace = true, optional = true }
|
||||
craft-gpu-wgpu = { workspace = true, optional = true }
|
||||
craft-gpu-yuv = { workspace = true, optional = true }
|
||||
craft-ipp = { workspace = true, optional = true }
|
||||
craft-ppt-binary = { workspace = true, optional = true }
|
||||
craft-sqlite = { workspace = true, optional = true }
|
||||
craft-audio-dsp = { workspace = true, optional = true }
|
||||
craft-sbs = { workspace = true, optional = true }
|
||||
craft-shared-vec = { workspace = true, optional = true }
|
||||
craft-ease = { workspace = true, optional = true }
|
||||
craft-i18n-build = { workspace = true, optional = true }
|
||||
craft-pbr = { workspace = true, optional = true }
|
||||
@@ -353,6 +355,7 @@ audio-qoa = ["audio", "craft-audio/qoa"]
|
||||
audio-qoa-decode = ["audio", "craft-audio/qoa-decode"]
|
||||
audio-qoa-encode = ["audio", "craft-audio/qoa-encode"]
|
||||
audio-rayon = ["audio", "craft-audio/rayon"]
|
||||
audio-s302m = ["audio", "craft-audio/s302m"]
|
||||
audio-sbc = ["audio", "craft-audio/sbc"]
|
||||
audio-serde = ["audio", "craft-audio/serde"]
|
||||
audio-symphonia = ["audio", "craft-audio/symphonia"]
|
||||
@@ -541,6 +544,8 @@ gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"]
|
||||
gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"]
|
||||
gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"]
|
||||
|
||||
gpu-yuv = ["dep:craft-gpu-yuv"]
|
||||
|
||||
gridcraft-format = ["dep:craft-gridcraft-format"]
|
||||
|
||||
gzip = ["dep:craft-gzip"]
|
||||
@@ -636,6 +641,7 @@ mcp-server = ["dep:craft-mcp-server"]
|
||||
|
||||
media = ["dep:craft-media"]
|
||||
media-avi = ["media", "craft-media/avi"]
|
||||
media-bink = ["media", "craft-media/bink"]
|
||||
media-bitstream = ["media", "craft-media/bitstream"]
|
||||
media-isobmff = ["media", "craft-media/isobmff"]
|
||||
media-matroska = ["media", "craft-media/matroska"]
|
||||
@@ -817,6 +823,9 @@ settings-testing = ["settings", "craft-settings/testing"]
|
||||
sf2 = ["dep:craft-sf2"]
|
||||
sf2-test-support = ["sf2", "craft-sf2/test-support"]
|
||||
|
||||
shared-vec = ["dep:craft-shared-vec"]
|
||||
shared-vec-serde = ["shared-vec", "craft-shared-vec/serde"]
|
||||
|
||||
sheet = ["dep:craft-sheet"]
|
||||
|
||||
shx = ["dep:craft-shx"]
|
||||
@@ -974,6 +983,8 @@ video-av1 = ["video", "craft-video/av1"]
|
||||
video-av1-decode = ["video", "craft-video/av1-decode"]
|
||||
video-av1-encode = ["video", "craft-video/av1-encode"]
|
||||
video-av1-large-encode = ["video", "craft-video/av1-large-encode"]
|
||||
video-bink = ["video", "craft-video/bink"]
|
||||
video-bink-decode = ["video", "craft-video/bink-decode"]
|
||||
video-dnx = ["video", "craft-video/dnx"]
|
||||
video-ffv1 = ["video", "craft-video/ffv1"]
|
||||
video-h264 = ["video", "craft-video/h264"]
|
||||
@@ -990,7 +1001,11 @@ video-mpeg2-encode = ["video", "craft-video/mpeg2-encode"]
|
||||
video-mpeg4 = ["video", "craft-video/mpeg4"]
|
||||
video-mpeg4-encode = ["video", "craft-video/mpeg4-encode"]
|
||||
video-prores = ["video", "craft-video/prores"]
|
||||
video-rawvideo = ["video", "craft-video/rawvideo"]
|
||||
video-screen-video = ["video", "craft-video/screen-video"]
|
||||
video-theora = ["video", "craft-video/theora"]
|
||||
video-theora-decode = ["video", "craft-video/theora-decode"]
|
||||
video-theora-encode = ["video", "craft-video/theora-encode"]
|
||||
video-threads = ["video", "craft-video/threads"]
|
||||
video-vmd = ["video", "craft-video/vmd"]
|
||||
video-vmd-decode = ["video", "craft-video/vmd-decode"]
|
||||
|
||||
@@ -17,6 +17,7 @@ craft = { workspace = true, features = ["ui", "color-ui", "draw", "imaging", "ke
|
||||
## Features
|
||||
|
||||
- One feature per crate, named after the crate without `craft-`: `color-ui` turns on `craft-color-ui` and re-exports it as `craft::color_ui`.
|
||||
- `gpu-yuv` enables the GPU YUV provider through `craft::gpu_yuv`.
|
||||
- `ui` turns on `craft-ui` (`craft::ui`), re-exports `egui` (`craft::egui`, the egui the library is built with) and forwards `ui` to every enabled crate.
|
||||
- `screen-testing` implies `ui` and forwards to every enabled crate.
|
||||
- Each crate feature is forwarded as `<crate>-<feature>` (`platform-appearance`, `text-hyphen`, `ui-window-frame`).
|
||||
|
||||
@@ -167,6 +167,8 @@ pub use craft_gpu_null as gpu_null;
|
||||
pub use craft_gpu_providers as gpu_providers;
|
||||
#[cfg(feature = "gpu-wgpu")]
|
||||
pub use craft_gpu_wgpu as gpu_wgpu;
|
||||
#[cfg(feature = "gpu-yuv")]
|
||||
pub use craft_gpu_yuv as gpu_yuv;
|
||||
#[cfg(feature = "gridcraft-format")]
|
||||
pub use craft_gridcraft_format as gridcraft_format;
|
||||
#[cfg(feature = "gzip")]
|
||||
@@ -339,6 +341,8 @@ pub use craft_scraft_format as scraft_format;
|
||||
pub use craft_settings as settings;
|
||||
#[cfg(feature = "sf2")]
|
||||
pub use craft_sf2 as sf2;
|
||||
#[cfg(feature = "shared-vec")]
|
||||
pub use craft_shared_vec as shared_vec;
|
||||
#[cfg(feature = "sheet")]
|
||||
pub use craft_sheet as sheet;
|
||||
#[cfg(feature = "shx")]
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
/// Crates the facade leaves out, by directory, with the reason. Everything else under `crates/` is a member.
|
||||
pub const NOT_IN_FACADE: &[(&str, &str)] = &[
|
||||
("appkit", "the `unsafe` AppKit observers behind a safe API, used by craft-window"),
|
||||
("appkit", "the `unsafe` AppKit calls behind a safe API, used by craft-window and craft-dialogs"),
|
||||
("design-lint", "a lint template and checker for apps' clippy.toml, run from xtask"),
|
||||
("feature-root", "a build tool: the dependency set tools/cl resolves every local build's features with; never built"),
|
||||
("fonts-build", "a build-script helper; apps call it from build.rs"),
|
||||
|
||||
@@ -11,7 +11,8 @@ mapping a SYLK sheet onto a document are the caller's work.
|
||||
| Function | What it does |
|
||||
|---|---|
|
||||
| `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 |
|
||||
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
|
||||
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters (empty or whitespace-only quoted records are blank); when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
|
||||
| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma coherently separates every sampled record with text; when no candidate coherently separates every sampled record, falls back to a coherent candidate whose header and at least one later record share a positive delimiter count with strictly more than half of the sampled records having 1 to that many delimiters (preferring comma, then tab over semicolon), or else comma if comma coherently separates the first sampled record with text |
|
||||
| `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text |
|
||||
| `records(text, delim, quote, max_records, max_fields)` | the same, collected |
|
||||
| `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing |
|
||||
|
||||
Loaded 100 of 576 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user