mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-02 10:37:29 -06:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a67a063280 | ||
|
|
a3e10d89d7 | ||
|
|
bb486228cd | ||
|
|
3b06aea7d0 | ||
|
|
7b4905c00e | ||
|
|
40497d7eca | ||
|
|
35dcf1d412 | ||
|
|
f155bba583 | ||
|
|
896de30146 | ||
|
|
681f40f566 | ||
|
|
a3c7f4edc7 | ||
|
|
7fe79e21ed | ||
|
|
d42ade0951 | ||
|
|
025cf1e0ba | ||
|
|
31dfc36766 | ||
|
|
7a563aca6e | ||
|
|
af7c16b570 | ||
|
|
60950ba884 | ||
|
|
c776bbd2b4 | ||
|
|
0f26696507 | ||
|
|
d1694ebfd5 | ||
|
|
66903aa4dc | ||
|
|
f5bcb64199 | ||
|
|
1e7dbcbe54 | ||
|
|
acdc3efbc6 | ||
|
|
eab00b3f01 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408486424,
|
||||
"producer_workflow_id": 429730684,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -83,7 +83,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -95,7 +97,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -214,7 +214,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@main
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [SoundCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
if: >-
|
||||
github.repository == 'storytold/soundcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/soundcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/soundcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/soundcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/soundcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'soundcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: main
|
||||
app-name: soundcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
name: SoundCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and a reviewed dispatcher with it).
|
||||
# Runs automatically on the reviewed nightly schedule and for supervised manual runs
|
||||
# by the reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 5 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,9 +24,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: main
|
||||
app-name: soundcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
@@ -32,3 +34,4 @@ jobs:
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
|
||||
@@ -37,6 +37,7 @@ jobs:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: soundcraft
|
||||
app-title: SoundCraft
|
||||
macos-runner: macos-15
|
||||
version: ${{ inputs.version }}
|
||||
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
|
||||
secrets:
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
+14
-3
@@ -21,9 +21,18 @@ are bundled.
|
||||
|
||||
## Fonts
|
||||
|
||||
SoundCraft bundles no font files. It uses the default fonts shipped inside the `egui` crate
|
||||
(Ubuntu-Light: Ubuntu Font Licence 1.0; Hack: MIT; Noto Emoji: OFL-1.1; emoji-icon-font: MIT)
|
||||
and, at runtime, the operating system's own UI fonts when available (never redistributed).
|
||||
SoundCraft ships one font file, for the web build only. Everything else is the default fonts
|
||||
shipped inside the `egui` crate (Ubuntu-Light: Ubuntu Font Licence 1.0; Hack: MIT; Noto Emoji:
|
||||
OFL-1.1; emoji-icon-font: MIT) and, at runtime, the operating system's own UI fonts when available
|
||||
(never redistributed).
|
||||
|
||||
The browser cannot reach the operating system's fonts, and egui's bundled faces carry no Han
|
||||
glyphs, so a Simplified Chinese interface would draw boxes. `assets/fonts/NotoSansSC-SoundCraftSubset.ttf`
|
||||
is therefore compiled into the web build alone (`crates/ui-egui/src/fonts.rs`): a subset of the
|
||||
Noto Sans SC variable font, pinned at weight 400 and reduced with fontTools to the UI glyph set
|
||||
(the zh-Hans catalog, GB 2312 level-1 common characters, ASCII, Latin-1 letters and the UI's
|
||||
punctuation, arrows and triangles; about 1.1 MiB). It is SIL Open Font License 1.1 — see
|
||||
`assets/fonts/OFL.txt`. Native builds never embed it and keep drawing with system fonts.
|
||||
|
||||
## Bundled egui font icons
|
||||
|
||||
@@ -47,6 +56,8 @@ here. The subset uses default_fonts; the parent face uses monochrome_emoji_fonts
|
||||
| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand assets | ArtCraft brand terms |
|
||||
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand assets | ArtCraft brand terms |
|
||||
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand assets | ArtCraft brand terms |
|
||||
| `assets/fonts/NotoSansSC-SoundCraftSubset.ttf` | Google LLC / Noto Project Authors | Noto Sans SC variable font, subset to the UI glyph set and pinned at weight 400 (generated with fontTools by `docs/i18n/tools/subset_web_font.py`) | SIL Open Font License 1.1 (`assets/fonts/OFL.txt`) |
|
||||
| `assets/fonts/OFL.txt` | Noto Project Authors / SIL | SIL Open Font License 1.1 text | OFL-1.1 |
|
||||
| `assets/app-icon/icon.svg` | SoundCraft contributors | original (hand-placed SVG paths; placeholder app icon) | MIT OR Apache-2.0 |
|
||||
| `packaging/macos/dmg/` (all files) | @XusBadia | original (macOS DMG window background and layout, from the app icon; see `packaging/macos/dmg/README.md`) | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-1024.png` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+39
-18
@@ -1478,6 +1478,14 @@ dependencies = [
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -1822,6 +1830,17 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2bfc45c49378effb801c6433758fb5aaa5d7808e#2bfc45c49378effb801c6433758fb5aaa5d7808e"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
@@ -5960,11 +5979,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
"craft-audio",
|
||||
"craft-nightly",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5985,7 +6005,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-au-host"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
@@ -5995,7 +6015,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-automation"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"craft-audio",
|
||||
@@ -6009,7 +6029,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-clap-host"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"libc",
|
||||
@@ -6024,7 +6044,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-cli"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
@@ -6042,7 +6062,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-dsp"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -6053,7 +6073,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-engine"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"craft-aaf",
|
||||
@@ -6083,7 +6103,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-interchange"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"craft-aaf",
|
||||
@@ -6096,7 +6116,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-midi"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-midi",
|
||||
"proptest",
|
||||
@@ -6104,7 +6124,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-mix"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"log",
|
||||
@@ -6120,14 +6140,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-model"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-scraft-format",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-playback"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cpal",
|
||||
"craft-audio",
|
||||
@@ -6143,14 +6163,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-time"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-ui-egui"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-behavior",
|
||||
@@ -6186,7 +6206,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-video"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-media",
|
||||
"craft-video",
|
||||
@@ -6197,7 +6217,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-vst3-host"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"libloading 0.9.0",
|
||||
@@ -6215,9 +6235,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "soundcraft-web"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-web-api",
|
||||
"eframe",
|
||||
"egui",
|
||||
"js-sys",
|
||||
@@ -8138,7 +8159,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+2
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -79,6 +79,7 @@ craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/c
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
+11
-6
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (Languages table: Spanish full; previously trivial: French and Spanish partial; previously minor: long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
|
||||
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
|
||||
@@ -52,7 +52,7 @@ measures readiness and adds hardware, localization and field bug reports.
|
||||
| UI/UX fidelity | ~55 % | 60–100 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| File formats | ~40 % | 70–120 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Hardware (interfaces, MIDI, surfaces, sync) | ~12 % | 110–180 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization | ~12 % (1 of Pro Tools' 8 languages; English and pt-BR fixed UI strings, no CJK/RTL font fallback or native review) | 70–110 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Localization | ~19 % (2 of Pro Tools' 8 languages; English, pt-BR and zh-Hans fixed UI strings, with a CJK fallback and a web Han font; no RTL or complex-script shaping, no native review) | 55–90 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | ~35 % (unmeasured) | 40–70 | [hardware-parity.md](docs/hardware-parity.md#performance) |
|
||||
| Stability | ~45 % | 50–80 | [gaps.md](docs/gaps.md) |
|
||||
| Platforms | ~65 % (5 platforms built, macOS exercised) | 20–40 | [gaps.md](docs/gaps.md) |
|
||||
@@ -86,11 +86,11 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
|
||||
| Language | Code | Status | Translated |
|
||||
|---|---|---|---:|
|
||||
| English | en | full | 100 % |
|
||||
| Simplified Chinese | zh-Hans | none | 0 % |
|
||||
| Spanish | es | none (PR #143 open) | 0 % |
|
||||
| Simplified Chinese | zh-Hans | full — 100 % of fixed UI strings; CJK fallback, web Han font, tests pass | 100 % (native-speaker review pending) |
|
||||
| Spanish | es | full — 100 % of fixed UI strings and engine errors; tests pass | 100 % (native-speaker review done) |
|
||||
| Hindi | hi | none | 0 % |
|
||||
| Arabic | ar | none | 0 % |
|
||||
| French | fr | none (PR #143 open) | 0 % |
|
||||
| French | fr | partial — catalog of 1,368 strings, the rest in English | ≈ 62 % |
|
||||
| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
|
||||
| Indonesian | id | none | 0 % |
|
||||
| Japanese | ja | none | 0 % |
|
||||
@@ -98,7 +98,7 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
|
||||
| Korean | ko | none | 0 % |
|
||||
| Vietnamese | vi | none | 0 % |
|
||||
|
||||
Other languages shipped: 0 complete. Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
Other languages shipped: Spanish complete (fixed UI strings and engine errors, native-speaker review). French is partial (≈ 62 %). Brazilian Portuguese and Simplified Chinese cover the fixed UI strings (100 %); both still need native-speaker review. CJK fallbacks ship for Chinese, while RTL and complex-script shaping are still missing. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -125,6 +125,7 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
## Progress log
|
||||
|
||||
- **2026-11-18 (MIDI input):** MIDI input devices: keyboards play record-enabled and input-monitored MIDI and instrument tracks live and are recorded into MIDI clips, with a device and channel choice per track. The device switches are in the MIDI inputs section of Setup › Playback Engine (Setup › MIDI › MIDI Input Devices opens the same window) and are kept in the app preferences, per computer, not in the session. Controllers, pitch bend and aftertouch reach the instrument live; a pitch held on two devices or channels sounds until both release it; a full input queue releases the notes of its device and marks the take incomplete. On Linux, live play was checked with a hardware keyboard (Akai MPK mini 3) and recording with a virtual one; macOS and Windows are type-checked only, and there is no MIDI input on FreeBSD or the web. Guide: `docs/midi-input.md`. No readiness percentage change until that is measured.
|
||||
- **2026-11-15 (27 October–15 November recap):** Releases v0.14.0 through v0.20.1; clips draw as a small name pill with shared cut seams, alternate playlist lanes draw on screen and rating stars follow their own switch; the Edit window's I/O column sets volume and pan; edit modes, playback and record colours; Grid and Nudge time scales; a new-tracks workflow; Smart Tool/Pencil shortcuts, held zoom keys, track-colour Color Palette, Sub-counter format menu, searchable I/O menus, scrolling menus, distinct link icons and Insertion Follows Playback; folder-track indentation, stereo input pairs, sends that open their Send window, Alt-click marker deletion and selection-aware Clip menus; the playback engine applies the chosen device and buffer (#1077) and volume automation is read at every sample (#1355); a 256 MiB session cap with a tree-free parser (#892), overflow and bounds hardening across H.264, FLAC, WAV, CAF, tempo, grid, automation and timecode, MIDI tempo/track-flood limits (#890), bounded command journal and score output (#995, #993), clip-FX gain and send-level clamps (#884), clip-group path-traversal rejection and VST3 multi-out instruments with up to 64 buses; MIDI export keeps only the notes a trimmed clip plays, key signatures follow Insert/Cut Time, score export keeps short-bar notes and strips XML-forbidden characters, and WAV bounces carry BWF timecode; Enter presses the default button only without button focus (#1243), the 1/4t quantize grid (#1453), VST3 scan paths (#1450) and portable.txt (#1341) are fixed, CLAP resets keep note-offs (#1464, #1470) and hosted plugins learn when they render offline; the #1144 demo benchmark recorded about a 20 % faster mix bounce on its stated setup; shared craft-update with Flatpak self-update and Linux signing fixes, and a nightly release dry run (#1508); session format and H.264/ProRes codecs move to craft-libs, and audio formats to craft-audio; commands --json (#744), malformed control requests close the connection and Import Audio Browse selects several files (#1089). This is a historical summary, not a new measurement of readiness.
|
||||
- **2026-11-14:** AAF import supports a strict CompositionMob SourceClip/Filler subset with external mono/stereo PCM WAV media, editable clips and handles, relink and absolute or relative timecode mapping. The reader shares cached object properties, caps retained property data at 128 MiB and rejects duplicate local references before expansion. AAF export, OMF and `.ptx` remain missing. No readiness percentage change.
|
||||
- **2026-11-09:** A built-in Frequency Shifter (`freq_shifter`) moves every frequency in the signal by the same number of hertz, from 0.01 Hz to 5 kHz: up, down, both ways at once, or down on the left and up on the right of a stereo track. The unwanted sideband stays at least 100 dB down from 20 Hz to 20 Hz below Nyquist at 44.1 to 96 kHz. Feedback sends the output round again for a trail of further shifts, Mix blends in the dry signal, and every change glides without a click. No readiness percentage change.
|
||||
- **2026-11-08:** Command-click near an existing automation breakpoint keeps that point as the click target with every active tool, and existing fade and clip-gain controls retain their normal priority. Empty automation space shows a crosshair and an insertion hint while Command is held. The active tool's drag gestures stay unchanged. No readiness percentage change.
|
||||
@@ -189,6 +190,10 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | trivial | Languages table: Spanish catalog complete with native-speaker review. Estimates unchanged |
|
||||
| 2026-11-24 | trivial | Languages table: French and Spanish catalogs, partial (≈ 62 %), PR #143. Estimates unchanged |
|
||||
| 2026-11-22 | minor | Languages table: Simplified Chinese (zh-Hans) covers the fixed UI strings through the `locales/zh-Hans` catalog, with a Han system-font fallback and an OFL web subset; needs native review. Localization estimate 70–110 → 55–90 h |
|
||||
| 2026-11-15 | minor | Historical 27 October–15 November progress recap through v0.20.1; menu breadth, readiness and effort were not re-measured |
|
||||
| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged |
|
||||
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
|
||||
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
|
||||
|
||||
@@ -27,6 +27,7 @@ fn is_control_method(method: &str) -> bool {
|
||||
| "ui.key"
|
||||
| "ui.text"
|
||||
| "ui.screenshot"
|
||||
| "audio.health"
|
||||
| "app.quit"
|
||||
)
|
||||
}
|
||||
@@ -67,7 +68,7 @@ mod tests {
|
||||
assert_eq!(m, "engine.execute");
|
||||
let (m, _) = app_request("track.new", json!({}));
|
||||
assert_eq!(m, "engine.execute");
|
||||
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
|
||||
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "audio.health", "app.quit"] {
|
||||
assert_eq!(app_request(method, json!({})).0, method);
|
||||
}
|
||||
for (method, params) in [
|
||||
|
||||
@@ -17,6 +17,8 @@ path = "src/main.rs"
|
||||
soundcraft-engine = { workspace = true }
|
||||
craft-audio.workspace = true
|
||||
soundcraft-ui-egui.workspace = true
|
||||
# The page command API (storytold/craft-libs#413): window.soundcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2bfc45c49378effb801c6433758fb5aaa5d7808e", version = "0.1.0" }
|
||||
soundcraft-playback = { workspace = true }
|
||||
soundcraft-model = { workspace = true }
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! `window.soundcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
|
||||
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
|
||||
//!
|
||||
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
|
||||
//! `screenshot`, as promises with a timeout). This module is SoundCraft's part: a [`Request`] that
|
||||
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
|
||||
//! reply. SoundCraft's control request has no abandon state, so a call the page gave up on still runs
|
||||
//! when the app reaches it, as it does for a desktop client that timed out.
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, TrySendError, sync_channel};
|
||||
|
||||
use craft_web_api::methods::Methods;
|
||||
use craft_web_api::page::{PageApi, Request};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_ui_egui::ControlRequest;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
/// The app id in `window.<app>`.
|
||||
const APP: &str = "soundcraft";
|
||||
|
||||
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
|
||||
const POLL_MS: i32 = 16;
|
||||
|
||||
/// How many control requests may wait for the app at once. `craft-web-api` already refuses calls past its own
|
||||
/// in-flight limit; this bounds the app's queue too, so a flood of calls can't grow it without limit.
|
||||
const QUEUE: usize = 64;
|
||||
|
||||
/// Put `window.soundcraft` on the page and return the queue the app drains each frame (hand it to
|
||||
/// `SoundApp::with_control`). An existing `window.soundcraft` keeps the functions it already has.
|
||||
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (queue, requests) = sync_channel::<ControlRequest>(QUEUE);
|
||||
let request: Request = Rc::new(move |method, params| {
|
||||
let (control, reply) = ControlRequest::new(method, params);
|
||||
if let Err(refused) = queue.try_send(control) {
|
||||
let error = match refused {
|
||||
TrySendError::Full(_) => format!("soundcraft is busy: {QUEUE} requests are already waiting for the app"),
|
||||
TrySendError::Disconnected(_) => "the app is not running".to_string(),
|
||||
};
|
||||
return Box::pin(async move { json!({"ok": false, "error": error}) });
|
||||
}
|
||||
ctx.request_repaint();
|
||||
Box::pin(wait(reply))
|
||||
});
|
||||
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
|
||||
log::warn!("couldn't install window.{APP}: {e:?}");
|
||||
}
|
||||
requests
|
||||
}
|
||||
|
||||
/// The app's reply, polled about once a frame.
|
||||
async fn wait(reply: Receiver<Value>) -> Value {
|
||||
loop {
|
||||
match reply.try_recv() {
|
||||
Ok(reply) => return reply,
|
||||
Err(TryRecvError::Empty) => {
|
||||
if !sleep(POLL_MS).await {
|
||||
return json!({"ok": false, "error": "this page has no timer to wait for the app with"});
|
||||
}
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn sleep(ms: i32) -> bool {
|
||||
// `false` when this page has no timer to wait with (no window, or the timer is refused): the caller ends the
|
||||
// call with an error instead of going round again at once.
|
||||
let timer = std::cell::Cell::new(false);
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
let set = web_sys::window().is_some_and(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms).is_ok());
|
||||
timer.set(set);
|
||||
if !set {
|
||||
let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED);
|
||||
}
|
||||
});
|
||||
let _ = JsFuture::from(promise).await;
|
||||
timer.get()
|
||||
}
|
||||
@@ -6,7 +6,8 @@
|
||||
//! from this directory (output in `dist/web`).
|
||||
//!
|
||||
//! Differences from the desktop app:
|
||||
//! - no TCP control channel (browsers can't listen on sockets);
|
||||
//! - no TCP control channel (browsers can't listen on sockets); `window.soundcraft` (`api`) drives the
|
||||
//! same control channel from the page instead;
|
||||
//! - no file system: File > Open Session…, Import > Audio…/MIDI… and files dropped on the page are
|
||||
//! read as bytes through the browser's file picker; a session is saved as ONE bundle file
|
||||
//! (`<name>.scraftz`: the `.scraft` and its `Audio Files/`), and every save or export arrives as a
|
||||
@@ -18,6 +19,8 @@
|
||||
//! empty session instead of the demo.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn start() {
|
||||
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
|
||||
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
|
||||
let app = SoundApp::new(engine, Some(player), Services::default());
|
||||
let app = SoundApp::new(engine, Some(player), Services::default()).with_control(crate::api::install(cc.egui_ctx.clone()));
|
||||
Ok(Box::new(WebShell { app, inbox: Rc::default(), samples: Rc::default() }))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// Real-browser check of window.soundcraft (the page command API from craft-web-api): serve a built
|
||||
// copy of the web app, load it in headless Chromium and drive every function the crate installs.
|
||||
//
|
||||
// Usage, from a folder where Playwright is installed (`npm i playwright`, then `npx playwright install chromium`):
|
||||
// node <repo>/apps/soundcraft-web/tests/page-api.mjs <site folder>
|
||||
// The site folder is a built copy of the web app: `trunk build --release` in apps/soundcraft-web
|
||||
// (dist/web), or the unpacked `packaging/web/package.sh` zip. Exits non-zero on the first failed check.
|
||||
//
|
||||
// Not repeated here: the 30 s request timeout belongs to craft-web-api and is covered by that crate's own
|
||||
// tests. The limit on calls waiting for the app (64) is exercised below: it needs a craft-web-api that has it
|
||||
// (craft-libs#733) and the app's own bounded queue.
|
||||
import { createRequire } from 'node:module'
|
||||
import http from 'node:http'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
const dir = process.argv[2]
|
||||
if (!dir) { console.error('usage: node page-api.mjs <site folder>'); process.exit(2) }
|
||||
const cwd = path.resolve(process.cwd())
|
||||
const tmp = path.resolve(os.tmpdir())
|
||||
const rootDir = path.resolve(cwd, dir)
|
||||
const inAllowedRoot =
|
||||
rootDir === cwd ||
|
||||
rootDir.startsWith(cwd + path.sep) ||
|
||||
rootDir === tmp ||
|
||||
rootDir.startsWith(tmp + path.sep)
|
||||
if (!inAllowedRoot) {
|
||||
console.error('site folder must be inside the current working directory or system temp directory')
|
||||
process.exit(2)
|
||||
}
|
||||
const rootPrefix = rootDir.endsWith(path.sep) ? rootDir : rootDir + path.sep
|
||||
const require = createRequire(path.join(process.cwd(), 'noop.js'))
|
||||
const { chromium } = (() => { try { return require('playwright') } catch { return require('@playwright/test') } })()
|
||||
|
||||
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png' }
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const route = decodeURIComponent(req.url.split('?')[0])
|
||||
const relPath = (route === '/' ? 'index.html' : route).replace(/^\/+/, '')
|
||||
const file = path.resolve(rootDir, relPath)
|
||||
if (!file.startsWith(rootPrefix)) {
|
||||
res.writeHead(403)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
try {
|
||||
const body = await readFile(file)
|
||||
res.writeHead(200, { 'content-type': types[path.extname(file)] || 'application/octet-stream' })
|
||||
res.end(body)
|
||||
} catch { res.writeHead(404); res.end() }
|
||||
})
|
||||
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
|
||||
const origin = `http://127.0.0.1:${server.address().port}`
|
||||
const browser = await chromium.launch({ headless: true, args: ['--disable-gpu'] })
|
||||
try {
|
||||
const page = await (await browser.newContext({ viewport: { width: 1280, height: 900 } })).newPage()
|
||||
const errors = []
|
||||
page.on('pageerror', (e) => errors.push(e.message))
|
||||
// ?webgl forces the WebGL2 backend: headless Chromium has no WebGPU adapter.
|
||||
await page.goto(`${origin}/?webgl`)
|
||||
await page.locator('canvas').first().waitFor({ timeout: 180_000 })
|
||||
await page.waitForFunction(() => window.soundcraft && typeof window.soundcraft.request === 'function', null, { timeout: 180_000 })
|
||||
|
||||
const names = await page.evaluate(() => Object.keys(window.soundcraft).sort((a, b) => a.localeCompare(b)))
|
||||
for (const f of ['request', 'execute', 'commands', 'docInspect', 'uiInspect', 'screenshot']) {
|
||||
assert(names.includes(f), `window.soundcraft.${f} is installed (found: ${names.join(' ')})`)
|
||||
}
|
||||
|
||||
// A call that rejects is reported, not thrown, so each check can look at the error.
|
||||
const call = (fn, ...args) => page.evaluate(async ([fn, args]) => {
|
||||
try { return { ok: true, value: await window.soundcraft[fn](...args) } }
|
||||
catch (e) { return { ok: false, error: String((e && e.message) || e), isError: e instanceof Error } }
|
||||
}, [fn, args])
|
||||
|
||||
const commands = await call('commands')
|
||||
assert(commands.ok && Array.isArray(commands.value) && commands.value.length > 0, `commands() lists the commands: ${JSON.stringify(commands).slice(0, 200)}`)
|
||||
assert(commands.value.some((c) => c.id === 'track.new'), 'commands() includes track.new')
|
||||
|
||||
const doc = await call('docInspect')
|
||||
assert(doc.ok && typeof doc.value === 'object', `docInspect() resolves with an object: ${JSON.stringify(doc).slice(0, 200)}`)
|
||||
const ui = await call('uiInspect')
|
||||
assert(ui.ok && typeof ui.value === 'object', `uiInspect() resolves with an object: ${JSON.stringify(ui).slice(0, 200)}`)
|
||||
|
||||
// execute changes the session, and docInspect shows it.
|
||||
const docBefore = await call('docInspect')
|
||||
assert(docBefore.ok, `docInspect() resolves before execute: ${JSON.stringify(docBefore).slice(0, 200)}`)
|
||||
const ran = await call('execute', 'track.new', {})
|
||||
assert(ran.ok, `execute('track.new') resolves: ${JSON.stringify(ran).slice(0, 300)}`)
|
||||
const docAfter = await call('docInspect')
|
||||
assert(docAfter.ok, `docInspect() resolves after execute: ${JSON.stringify(docAfter).slice(0, 200)}`)
|
||||
assert.notEqual(JSON.stringify(docBefore.value), JSON.stringify(docAfter.value), 'docInspect() changes after execute(track.new)')
|
||||
|
||||
// Failures reject with an Error that names what went wrong.
|
||||
const unknownCommand = await call('execute', 'no.such.command', {})
|
||||
assert(!unknownCommand.ok && unknownCommand.isError && unknownCommand.error.includes('no.such.command'), `execute of an unknown command rejects with an Error naming it: ${JSON.stringify(unknownCommand)}`)
|
||||
const unknownMethod = await call('request', 'no.such.method', {})
|
||||
assert(!unknownMethod.ok && unknownMethod.isError && unknownMethod.error.includes('no.such.method'), `an unknown method rejects with an Error naming it: ${JSON.stringify(unknownMethod)}`)
|
||||
|
||||
const shot = await call('screenshot')
|
||||
assert(shot.ok, `screenshot() resolves: ${JSON.stringify(shot).slice(0, 200)}`)
|
||||
const data = shot.value && shot.value.data
|
||||
assert(typeof data === 'string' && data.length > 1000, 'screenshot() carries base64 data')
|
||||
assert.equal(Buffer.from(data, 'base64').subarray(1, 4).toString(), 'PNG', 'the screenshot is a PNG')
|
||||
|
||||
// Several calls at once all settle.
|
||||
const settled = await page.evaluate(() => Promise.all([1, 2, 3, 4, 5].map(() => window.soundcraft.uiInspect())).then((r) => r.length))
|
||||
assert.equal(settled, 5, 'five concurrent calls all settle')
|
||||
|
||||
// Overload: far more calls than may wait at once. The ones over the limit are refused at once as busy, the
|
||||
// ones within it are answered, and the page can call again afterwards (the slots came back).
|
||||
const burst = await page.evaluate(() => Promise.all(
|
||||
Array.from({ length: 300 }, () => window.soundcraft.uiInspect().then(() => 'ok', (e) => String((e && e.message) || e))),
|
||||
))
|
||||
const refused = burst.filter((r) => r !== 'ok')
|
||||
console.log(`burst of ${burst.length}: ${burst.length - refused.length} answered, ${refused.length} refused (${refused[0]})`)
|
||||
assert(refused.length > 0, 'calls beyond the limit are refused')
|
||||
assert(refused.every((r) => /busy/i.test(r)), `every refusal says busy: ${refused.find((r) => !/busy/i.test(r))}`)
|
||||
assert(burst.includes('ok'), 'the calls within the limit are answered')
|
||||
assert.equal(burst.length, 300, 'every call settled, none was left waiting')
|
||||
const afterBurst = await call('uiInspect')
|
||||
assert(afterBurst.ok, `a call after the burst is accepted again: ${JSON.stringify(afterBurst).slice(0, 200)}`)
|
||||
|
||||
assert.deepEqual(errors, [], 'no uncaught page errors')
|
||||
console.log('PASS window.soundcraft: all six functions, the failure paths and concurrent calls work against the real app')
|
||||
} finally {
|
||||
await browser.close()
|
||||
server.close()
|
||||
}
|
||||
@@ -17,6 +17,7 @@ asio = ["soundcraft-playback/asio"]
|
||||
[dependencies]
|
||||
soundcraft-engine.workspace = true
|
||||
craft-audio.workspace = true
|
||||
craft-nightly.workspace = true
|
||||
soundcraft-ui-egui.workspace = true
|
||||
soundcraft-playback.workspace = true
|
||||
soundcraft-automation.workspace = true
|
||||
|
||||
@@ -1,23 +1,10 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(soundcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open SoundCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable SoundCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
@@ -36,6 +23,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -44,20 +32,6 @@ mod tests {
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.20.1"), "0.20.1");
|
||||
|
||||
@@ -10,12 +10,6 @@ use soundcraft_ui_egui::docking;
|
||||
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
|
||||
/// The portable marker in `dir`, if it is a regular file (never a link or a directory).
|
||||
pub(crate) fn portable_marker(dir: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
let marker = dir.join(PORTABLE_MARKER);
|
||||
std::fs::symlink_metadata(&marker).ok().filter(|m| m.file_type().is_file()).map(|_| marker)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Platform {
|
||||
Mac,
|
||||
@@ -44,7 +38,7 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<Path
|
||||
}
|
||||
|
||||
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option<PathBuf> {
|
||||
// The compiled Nightly flavor cannot run without a profile (`build_flavor::require_profile`),
|
||||
// The compiled Nightly flavor always selects an isolated profile (`launch_profile::prepare`),
|
||||
// so this is the complete settings folder and never falls back to Stable data.
|
||||
if let Some(root) = nightly {
|
||||
return Some(root.to_path_buf());
|
||||
|
||||
@@ -1,214 +1,289 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
//! Nightly-v1 bootstrap and profile fencing via `craft-nightly`.
|
||||
//!
|
||||
//! Selected before logging, updates, fonts or saved state. Direct launches of a nightly build
|
||||
//! self-isolate into `craft_nightly::canonical_profile_root("soundcraft")`; launcher launches
|
||||
//! pass `--launch-profile nightly-v1 --profile-root <dir> -- <args...>`. Stable builds keep
|
||||
//! their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
use craft_nightly::{AppProfileSpec, Launch, Profile, ProfileError, StartupOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
use crate::build_flavor;
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
const APP_ID: &str = "soundcraft";
|
||||
const DISPLAY_NAME: &str = "SoundCraft";
|
||||
const STABLE_DIR_NAMES: &[&str] = &["soundcraft", "SoundCraft"];
|
||||
const STABLE_PACKAGE_ID: &str = "ai.storyteller.soundcraft";
|
||||
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.soundcraft.nightly";
|
||||
const FORBIDDEN_ENV_VARS: &[&str] = &[crate::env::CONFIG_DIR];
|
||||
const PORTABLE_MARKERS: &[&str] = &[crate::config::PORTABLE_MARKER];
|
||||
const FOLDER_ONLY_ENTRIES: &[&str] = &["Autosave", "Presets", "logs"];
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
fn non_empty_abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi).
|
||||
if let Some(local) = non_empty_abs_env(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
if let Some(profile) = non_empty_abs_env(&env, "USERPROFILE") {
|
||||
roots.push(profile.join("AppData").join("Local").join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs_env(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
if let Some(home) = non_empty_abs_env(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.soundcraft"));
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
roots.push(PathBuf::from("/Applications/SoundCraft.app"));
|
||||
if let Some(home) = non_empty_abs_env(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.soundcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.soundcraft.savedState"));
|
||||
roots.push(home.join("Applications/SoundCraft.app"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
let _ = env;
|
||||
|
||||
roots
|
||||
}
|
||||
|
||||
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: DISPLAY_NAME,
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: STABLE_PACKAGE_ID,
|
||||
nightly_package_id: NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: FORBIDDEN_ENV_VARS,
|
||||
portable_markers: PORTABLE_MARKERS,
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots_with(env),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with(|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old portable/config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
// SoundCraft keeps no Documents agent folder and has no craft-settings data/cache roots: one
|
||||
// settings folder holds ui.json, Autosave/, Presets/ and logs/, and `config::writable` is the
|
||||
// app's existing exclusive write probe.
|
||||
crate::profile_root::validate(root, env, exe, crate::config::writable)
|
||||
pub fn prepare(args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
craft_nightly::prepare_launch(build_flavor::COMPILED, &spec(), args, &StartupOptions::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, canonical_profile_root, launch_arguments, parse_startup, validate_and_prepare_root};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\soundcraft" } else { "/nightly-data/profiles/soundcraft" }
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "image with spaces.psd"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
impl TempDir {
|
||||
fn new(prefix: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
|
||||
loop {
|
||||
let candidate = base.join(format!("{prefix}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => return Self(candidate),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create temp dir: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
fn soundcraft_spec_preserves_stable_fences_and_folder_entries() {
|
||||
let spec = spec();
|
||||
assert_eq!(spec.app_id, "soundcraft");
|
||||
assert_eq!(spec.display_name, "SoundCraft");
|
||||
assert_eq!(spec.stable_dir_names, &["soundcraft", "SoundCraft"]);
|
||||
assert_eq!(spec.stable_package_id, "ai.storyteller.soundcraft");
|
||||
assert_eq!(spec.nightly_package_id, "ai.storyteller.soundcraft.nightly");
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert_eq!(spec.forbidden_env_vars, &["SOUNDCRAFT_CONFIG_DIR"]);
|
||||
assert_eq!(spec.portable_markers, &["portable.txt"]);
|
||||
assert_eq!(spec.folder_only_entries, &["Autosave", "Presets", "logs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = spec();
|
||||
let expected_root = canonical_profile_root("soundcraft").unwrap();
|
||||
let argv = args(&["--demo", "song.scraft"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
assert!(launch.leading_flags.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_launcher_invocation_round_trips_and_preserves_file_arguments() {
|
||||
let spec = spec();
|
||||
let root = PathBuf::from(absolute());
|
||||
let user_args = args(&["--profile-root", "session with spaces.scraft"]);
|
||||
let argv = launch_arguments(&root, &user_args);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(root));
|
||||
assert_eq!(launch.passthrough_args, user_args);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_build_keeps_arguments_and_refuses_nightly_flags() {
|
||||
let spec = spec();
|
||||
for argv in [args(&[]), args(&["--demo", "a.scraft"]), args(&["--", "--launch-profile", "file.scraft"])] {
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
}
|
||||
let nightly = launch_arguments(Path::new(absolute()), &[]);
|
||||
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec, nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_queries_are_recognized_for_plain_and_launcher_invocations() {
|
||||
let spec = spec();
|
||||
for flag in ["--version", "-V"] {
|
||||
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
|
||||
assert!(plain.is_version_query());
|
||||
|
||||
for header in [
|
||||
["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()],
|
||||
["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT],
|
||||
] {
|
||||
let mut query = args(&header);
|
||||
query.push(flag.into());
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, query.clone(), &StartupOptions::new()).unwrap().is_version_query());
|
||||
query.push("recording with spaces.wav".into());
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, query, &StartupOptions::new()).unwrap();
|
||||
assert!(!launch.is_version_query());
|
||||
assert_eq!(launch.passthrough_args, args(&[flag, "recording with spaces.wav"]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
|
||||
let dir = TempDir::new("soundcraft-nightly-reopen");
|
||||
let root = dir.path().join("profile");
|
||||
let spec = spec();
|
||||
|
||||
let prepared = validate_and_prepare_root(&root, &spec).unwrap();
|
||||
assert_eq!(prepared, root);
|
||||
|
||||
for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(prepared.join(file), b"saved profile data").unwrap();
|
||||
}
|
||||
for folder in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(prepared.join(folder)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&root, &spec).unwrap(), prepared);
|
||||
|
||||
for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(prepared.join(file)).unwrap(), b"saved profile data", "{file} remains intact after reopen");
|
||||
}
|
||||
for folder in FOLDER_ONLY_ENTRIES {
|
||||
let path = prepared.join(folder);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(
|
||||
matches!(validate_and_prepare_root(&root, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
|
||||
"{folder} must remain a directory"
|
||||
);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_roots_fence_soundcraft_install_locations() {
|
||||
let dir = TempDir::new("soundcraft-extra-fence");
|
||||
let custom_forbidden = dir.path().join("forbidden-install");
|
||||
let mut spec = spec();
|
||||
spec.extra_forbidden_roots.push(custom_forbidden.clone());
|
||||
assert!(matches!(validate_and_prepare_root(&custom_forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_extra_forbidden_roots_include_expected_paths() {
|
||||
let home = if cfg!(windows) { r"C:\Users\tester" } else { "/Users/tester" };
|
||||
let local = if cfg!(windows) { r"C:\Users\tester\AppData\Local" } else { "/unused" };
|
||||
let program_files = if cfg!(windows) { r"C:\Program Files" } else { "/unused" };
|
||||
let spec = spec_with(|key| match key {
|
||||
"HOME" | "USERPROFILE" => Some(OsString::from(home)),
|
||||
"LOCALAPPDATA" => Some(OsString::from(local)),
|
||||
"ProgramFiles" => Some(OsString::from(program_files)),
|
||||
_ => None,
|
||||
});
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(local).join("Programs").join("ArtCraft").join("SoundCraft")));
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(program_files).join("ArtCraft").join("SoundCraft")));
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/soundcraft")));
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join(".var/app/ai.storyteller.soundcraft")));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/Applications/SoundCraft.app")));
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join("Library/Preferences/ai.storyteller.soundcraft.plist")));
|
||||
}
|
||||
let _ = (home, local, program_files, &spec);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
//! callback must never do. Code that runs on the audio thread logs anyway (the cpal error callback,
|
||||
//! the synth's full event queue, a hosted plugin's failed `process`, a CLAP plugin calling the
|
||||
//! host's `log` from its audio thread, the panic hook). So the cpal callbacks mark their thread
|
||||
//! (`soundcraft_playback::mark_audio_thread`; the mix engine carries the mark into the worker
|
||||
//! threads that render strips for it), and a record from a marked thread is not written
|
||||
//! (`soundcraft_playback::mark_audio_thread`; the mix engine renders every strip on the marked
|
||||
//! thread itself), and a record from a marked thread is not written
|
||||
//! there: the first one is kept in a fixed buffer (`try_lock`, no allocation, never waits) and the
|
||||
//! rest are only counted (an atomic). Another thread writes them out: the UI thread every frame
|
||||
//! ([`AppLogger::report_audio_thread`]) and any other thread before its own next record.
|
||||
|
||||
+20
-23
@@ -26,7 +26,6 @@ mod logging;
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod switch;
|
||||
|
||||
use env::Env;
|
||||
@@ -251,36 +250,34 @@ fn report_launch_profile_error(error: &str) {
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before the logger, updates, fonts or saved state.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window, as
|
||||
// `SoundCraft <version> (nightly-v1)` on standard output with nothing on standard error.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
// Plain `--version` / `-V` on Nightly: answered before canonical root resolution, validation,
|
||||
// process identity, IPC or any window, even in environments without HOME/LOCALAPPDATA.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let early = launch_profile::prepare(argv).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
|
||||
// `craft_nightly::prepare_launch` skips root validation and profile installation for version queries.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable };
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
|
||||
if let Err(error) = os_window::select_identity(identity) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(early.passthrough_args)
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
|
||||
@@ -1,705 +0,0 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::config::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The Nightly Flatpak's own app id (packaging/linux/flatpak-bundle.sh). Inside that instance the
|
||||
/// sandbox is the isolation, so it is the one Flatpak whose environment a Nightly launch accepts.
|
||||
const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.soundcraft.nightly";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("SoundCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
|
||||
// install folder is not known here; the executable's own folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("soundcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.soundcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/SoundCraft"),
|
||||
library.join("Caches/SoundCraft"),
|
||||
library.join("Caches/ai.storyteller.soundcraft"),
|
||||
library.join("Preferences/SoundCraft"),
|
||||
library.join("Preferences/ai.storyteller.soundcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.soundcraft.savedState"),
|
||||
home.join("Applications/SoundCraft.app"),
|
||||
PathBuf::from("/Applications/SoundCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
match std::fs::symlink_metadata(&child) {
|
||||
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve
|
||||
/// inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
|
||||
// marker only counts beside a SoundCraft executable, so an unrelated portable.txt higher up
|
||||
// (in a user folder or at a drive root) does not refuse the profile.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
portable_marker(ancestor).is_some() && (depth == 0 || ["soundcraft.exe", "soundcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
|
||||
/// boundary tests exercise the real policy without starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if env("SOUNDCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
// The Launcher protocol is the one root the app validates. A wrapper that isolates with
|
||||
// the stable override variable instead passes the profile explicitly; the message names
|
||||
// that, because this is what a Linux nightly launcher hits when it exports the variable.
|
||||
return Err(
|
||||
"nightly-v1 cannot be combined with SOUNDCRAFT_CONFIG_DIR; pass --launch-profile nightly-v1 --profile-root <dir> -- instead".into()
|
||||
);
|
||||
}
|
||||
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its
|
||||
// runtime socket namespace could point another profile at the stable app's socket. The
|
||||
// Nightly Flatpak is the exception: its own app id is the sandbox, so $HOME and the XDG
|
||||
// folders in there are already this package's own.
|
||||
if platform != Platform::Windows
|
||||
&& let Some(instance) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
&& instance.to_string_lossy() != NIGHTLY_FLATPAK_ID
|
||||
{
|
||||
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable SoundCraft installation or its SoundCraftData settings folder".into());
|
||||
}
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Autosave is swept and rewritten on start and Presets are written in place: never let either
|
||||
// alias leave this private profile, including toward a Stable portable directory we cannot know.
|
||||
private_subdirectory(&chosen, "Autosave", "autosave folder")?;
|
||||
private_subdirectory(&chosen, "Presets", "presets folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "Autosave", "autosave folder")?;
|
||||
private_subdirectory(&confirmed, "Presets", "presets folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 3] = ["Autosave", "Presets", "logs"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("soundcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/soundcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
|
||||
assert!(!probed.get(), "reject portable data before a writable probe");
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
|
||||
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("SoundCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn autosave_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/state/soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("Autosave")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "Autosave must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-self");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&private, private.join("Autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "Autosave cannot treat all profile settings as autosaves");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn autosave_alias_to_a_private_subfolder_keeps_the_profile_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let autosave = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&autosave).unwrap();
|
||||
std::os::unix::fs::symlink(&autosave, private.join("Autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("Autosave")).unwrap(), autosave);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/soundcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Autosave"), platform));
|
||||
assert!(overlaps(&root.join("Autosave"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("soundcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/soundcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/SoundCraft Nightly.app/Contents/MacOS/SoundCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/SoundCraft",
|
||||
"Caches/SoundCraft",
|
||||
"Caches/ai.storyteller.soundcraft",
|
||||
"Preferences/SoundCraft",
|
||||
"Saved Application State/ai.storyteller.soundcraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/soundcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/soundcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_msi_install_folders_are_fenced() {
|
||||
let mut fixture = Fixture::new();
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("soundcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not SoundCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let portable = fixture.root.join("D/PC");
|
||||
std::fs::create_dir_all(&portable).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
|
||||
std::fs::write(portable.join("soundcraft.exe"), b"stable portable executable, never run").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("portable"));
|
||||
assert!(!probed.get());
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
}
|
||||
// A portable.txt that no SoundCraft executable sits beside is someone else's file.
|
||||
let unrelated = fixture.root.join("user folder");
|
||||
std::fs::create_dir_all(&unrelated).unwrap();
|
||||
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
|
||||
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/soundcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.soundcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn any_profile_entry_alias_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/soundcraft/Presets");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap();
|
||||
for name in ["Presets", "logs", "settings.json"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-presets")).unwrap();
|
||||
std::fs::write(private.join("settings.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/soundcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("SOUNDCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("SOUNDCRAFT_CONFIG_DIR"));
|
||||
fixture.env.remove("SOUNDCRAFT_CONFIG_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
// The Nightly Flatpak is its own instance: the profile inside it is a sandbox-local folder.
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft.nightly".into());
|
||||
let sandboxed = fixture.home().join(".var/app/ai.storyteller.soundcraft.nightly/config/soundcraft-nightly");
|
||||
assert_eq!(fixture.check(Platform::Linux, &sandboxed).unwrap(), sandboxed);
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"do not replace me").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file).is_err());
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
|
||||
let candidate = fixture.home().join("nightly");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert!(!fixture.home().join(".config/soundcraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
|
||||
let alias = fixture.home().join("alias");
|
||||
symlink(&stable, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
|
||||
let missing = fixture.home().join("missing-target");
|
||||
let dangling = fixture.home().join("dangling");
|
||||
symlink(&missing, &dangling).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
|
||||
assert!(!missing.exists());
|
||||
assert!(!stable.join("nightly").exists());
|
||||
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 46 KiB |
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright © 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Existing commands/history and saved session PCM for bounded send automation.
|
||||
use craft_audio::AudioBuffer;
|
||||
use serde_json::json;
|
||||
use soundcraft_engine::{Engine, io};
|
||||
use soundcraft_model::{AutoParam, ChannelFormat, Clip, FileFormat, Route, Session, TrackKind};
|
||||
use soundcraft_time::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn fixture() -> Engine {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Original"));
|
||||
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 512]] };
|
||||
let src = io::add_source(&mut s, "Original synthetic", buffer, None, FileFormat::Wav);
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original", src, 0, 0, 512));
|
||||
s.track_mut(t).unwrap().mixer.output = Route::None;
|
||||
let mut e = Engine::new(s);
|
||||
e.execute("mix.new_bus", &json!({"name":"Send","format":"stereo"})).unwrap();
|
||||
e.execute("mix.send", &json!({"track":"Original","bus":"Send","slot":"A","level_db":0})).unwrap();
|
||||
e.execute("track.new", &json!({"name":"Return","kind":"aux","format":"stereo"})).unwrap();
|
||||
let bus = e.session().busses.iter().find(|b| b.name == "Send").unwrap().id;
|
||||
let aux = e.session().tracks.iter().find(|t| t.kind == TrackKind::Aux).unwrap().id;
|
||||
e.session_mut().track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
|
||||
e.mark_clean();
|
||||
e
|
||||
}
|
||||
fn render(e: &Engine) -> Vec<Vec<f32>> {
|
||||
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 512), 37);
|
||||
assert_eq!(out.len(), 2);
|
||||
assert!(out.iter().all(|c| c.len() == 512));
|
||||
out
|
||||
}
|
||||
fn point(e: &mut Engine, param: &str, at: i64, value: f32) {
|
||||
e.execute("automation.set_point", &json!({"track":"Original","param":param,"at":at,"value":value})).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn commands_undo_redo_reuse_renderer_and_preserve_render_state() {
|
||||
let mut e = fixture();
|
||||
let baseline = render(&e);
|
||||
point(&mut e, "send_a_pan", 0, -1.0);
|
||||
point(&mut e, "send_a_pan", 173, 1.0);
|
||||
point(&mut e, "send_a_mute", 0, 0.0);
|
||||
let before = render(&e);
|
||||
point(&mut e, "send_a_mute", 97, 1.0);
|
||||
let after = render(&e);
|
||||
assert_ne!(before, after);
|
||||
assert_ne!(baseline, before);
|
||||
let arc = e.session_arc();
|
||||
let serialized = e.session().to_json().unwrap();
|
||||
let revision = e.revision;
|
||||
let history = e.undo_history();
|
||||
let dirty = e.is_dirty();
|
||||
let mut mix = soundcraft_mix::MixEngine::new(48_000.0, 512);
|
||||
let mut out = vec![vec![0.0; 512]; 2];
|
||||
mix.render(e.session(), 0, 512, &mut out);
|
||||
assert_eq!(out, after);
|
||||
mix.render(e.session(), 97, 13, &mut out);
|
||||
assert!(Arc::ptr_eq(&arc, &e.session_arc()));
|
||||
assert_eq!(serialized, e.session().to_json().unwrap());
|
||||
assert_eq!(revision, e.revision);
|
||||
assert_eq!(history, e.undo_history());
|
||||
assert_eq!(dirty, e.is_dirty());
|
||||
assert!(e.undo());
|
||||
assert_eq!(render(&e), before);
|
||||
mix.render(e.session(), 0, 512, &mut out);
|
||||
assert_eq!(out, before);
|
||||
assert!(e.redo());
|
||||
assert_eq!(render(&e), after);
|
||||
mix.render(e.session(), 0, 512, &mut out);
|
||||
assert_eq!(out, after);
|
||||
e.execute("mix.automation_mode", &json!({"track":"Original","mode":"off"})).unwrap();
|
||||
assert_eq!(render(&e), baseline);
|
||||
}
|
||||
#[test]
|
||||
fn lane_commands_survive_folder_and_bundle_save_reopen_with_exact_pcm() {
|
||||
let mut e = fixture();
|
||||
e.execute("mix.send_level", &json!({"track":"Original","slot":"A","pan":0.5,"mute":true})).unwrap();
|
||||
point(&mut e, "send_a_pan", 37, -1.0);
|
||||
point(&mut e, "send_a_pan", 401, 1.0);
|
||||
point(&mut e, "send_a_mute", 0, 0.0);
|
||||
e.execute("automation.write_range", &json!({"track":"Original","param":"send_a_mute","start":97,"end":173,"value":1.0})).unwrap();
|
||||
let expected = render(&e);
|
||||
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-send-automation-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = dir.join("Original/Send.scraft").to_string_lossy().into_owned();
|
||||
io::save_session(&mut e, &path).unwrap();
|
||||
let mut reopened = Engine::default();
|
||||
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
|
||||
assert_eq!(render(&reopened), expected);
|
||||
let tr = reopened.session().tracks.iter().find(|t| t.name == "Original").unwrap();
|
||||
assert_eq!(tr.lane(&AutoParam::SendPan(0)).unwrap().points.len(), 2);
|
||||
assert!(!reopened.is_dirty());
|
||||
assert!(!reopened.can_undo());
|
||||
let (bundle, _) = io::session_bundle(e.session()).unwrap();
|
||||
let mut bundled = Engine::default();
|
||||
io::open_session_bytes(&mut bundled, "Send.scraftz", &bundle).unwrap();
|
||||
assert_eq!(render(&bundled), expected);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn absent_enabled_field_keeps_legacy_reader_behavior() {
|
||||
let mut e = fixture();
|
||||
point(&mut e, "send_a_pan", 0, -1.0);
|
||||
point(&mut e, "send_a_mute", 0, 0.0);
|
||||
let expected = render(&e);
|
||||
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
let mut json = serde_json::to_value(e.session()).unwrap();
|
||||
for track in json["tracks"].as_array_mut().unwrap() {
|
||||
for lane in track["automation"].as_array_mut().unwrap() {
|
||||
lane.as_object_mut().unwrap().remove("enabled");
|
||||
}
|
||||
}
|
||||
let mut old: Session = serde_json::from_value(json).unwrap();
|
||||
old.pool = e.session().pool.clone();
|
||||
let tr = old.tracks.iter().find(|t| t.name == "Original").unwrap();
|
||||
assert!(tr.automation.iter().all(|l| !l.enabled));
|
||||
assert_eq!(soundcraft_mix::render_range(&old, Range::new(0, 512), 100), expected);
|
||||
}
|
||||
+38
-8
@@ -70,6 +70,7 @@ mod midi;
|
||||
mod offline;
|
||||
mod pan;
|
||||
mod routing;
|
||||
mod send_automation;
|
||||
mod strip;
|
||||
mod threads;
|
||||
|
||||
@@ -362,7 +363,7 @@ impl MixEngine {
|
||||
}
|
||||
for b in &s.busses {
|
||||
let n = b.format.channels().clamp(1, MAX_CHANNELS);
|
||||
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new() });
|
||||
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new(), age: send_automation::SignalAge::Empty });
|
||||
bus.fmt = b.format;
|
||||
if bus.buf.len() != n {
|
||||
bus.buf = vec![vec![0.0; mb]; n];
|
||||
@@ -389,7 +390,7 @@ impl MixEngine {
|
||||
self.begin_block(s, pos, frames);
|
||||
let blk = Block { pos, frames, any_solo: any_solo(s) };
|
||||
let order = std::mem::take(&mut self.order);
|
||||
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
|
||||
// Phase 1: independent strips (audio, instrument, MIDI), in parallel except on the audio thread.
|
||||
let mut work = std::mem::take(&mut self.work);
|
||||
work.clear();
|
||||
for &i in &order {
|
||||
@@ -454,6 +455,7 @@ impl MixEngine {
|
||||
}
|
||||
self.ensure_synced(s);
|
||||
for b in self.busses.values_mut() {
|
||||
b.age = send_automation::SignalAge::Empty;
|
||||
for c in b.buf.iter_mut() {
|
||||
c.iter_mut().take(frames).for_each(|x| *x = 0.0);
|
||||
}
|
||||
@@ -508,9 +510,11 @@ impl MixEngine {
|
||||
let ch = st.buf.len();
|
||||
st.align.set(lmax_t.saturating_sub(st.latency), ch);
|
||||
st.align.process(&mut st.buf, frames);
|
||||
st.send_post_age = st.send_post_age.delayed(st.align.len);
|
||||
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
|
||||
st.align_pre.set(lmax_t.saturating_sub(st.latency), ch);
|
||||
st.align_pre.process(&mut st.pre, frames);
|
||||
st.send_pre_age = st.send_pre_age.delayed(st.align_pre.len);
|
||||
}
|
||||
let waits = match &t.mixer.output {
|
||||
Route::Main => true,
|
||||
@@ -546,6 +550,7 @@ impl MixEngine {
|
||||
let ch = st.buf.len();
|
||||
st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch);
|
||||
st.align.process(&mut st.buf, frames);
|
||||
st.send_post_age = st.send_post_age.delayed(st.align.len);
|
||||
st.out_extra.set(0, ch);
|
||||
self.route_strip(t, &mut st, pos, frames);
|
||||
self.strips.insert(t.id, st);
|
||||
@@ -643,22 +648,41 @@ impl MixEngine {
|
||||
let law = self.pan_law;
|
||||
for (i, snd) in t.mixer.sends.iter().enumerate() {
|
||||
let Some(snd) = snd else { continue };
|
||||
if snd.mute || strip.muted {
|
||||
if strip.muted {
|
||||
continue;
|
||||
}
|
||||
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
|
||||
let age = if snd.pre_fader { strip.send_pre_age } else { strip.send_post_age };
|
||||
let clock = age.clock(pos);
|
||||
let Route::Bus(b) = &snd.target else { continue };
|
||||
let Some(dst) = self.busses.get_mut(b) else { continue };
|
||||
let ordinary = !src_fmt.is_ambisonic() && !dst.fmt.is_ambisonic();
|
||||
let mute = ordinary.then(|| send_automation::Reader::for_send(t, AutoParam::SendMute, i, clock.at(0))).flatten();
|
||||
if mute.is_none() && snd.mute {
|
||||
continue;
|
||||
}
|
||||
let lvl = send_level(t, i, snd.level_db, pos);
|
||||
let gain = db_to_gain(lvl);
|
||||
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
|
||||
let Route::Bus(b) = &snd.target else { continue };
|
||||
let Some(dst) = self.busses.get_mut(b) else { continue };
|
||||
if gain <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
dst.age.include(age);
|
||||
let pan = (ordinary && src.len() == 1 && dst.fmt == ChannelFormat::Stereo)
|
||||
.then(|| send_automation::Reader::for_send(t, AutoParam::SendPan, i, clock.at(0)))
|
||||
.flatten();
|
||||
if let Some(pan) = pan {
|
||||
send_automation::apply_mono_stereo(src, frames, &mut dst.buf, gain, law, clock, pan, mute);
|
||||
continue;
|
||||
}
|
||||
// Mono sends use the send's own pan; stereo sends go straight to L/R.
|
||||
let stereo = if src.len() == 1 { [snd.pan, 0.0] } else { [-1.0, 1.0] };
|
||||
let surround = snd.surround.as_ref().or(if snd.follow_main_pan { t.mixer.surround.as_ref() } else { None });
|
||||
let m = build_matrix(src_fmt, src.len(), dst.fmt, dst.buf.len(), &PanSpec { stereo, surround }, law);
|
||||
apply_matrix(src, frames, &mut dst.buf, &m, gain);
|
||||
if let Some(mute) = mute {
|
||||
send_automation::apply_gated(src, frames, &mut dst.buf, &m, gain, clock, mute);
|
||||
} else {
|
||||
apply_matrix(src, frames, &mut dst.buf, &m, gain);
|
||||
}
|
||||
}
|
||||
let src: &[Vec<f32>] = match &t.mixer.output {
|
||||
Route::Main | Route::Bus(_) if strip.out_extra.len > 0 => {
|
||||
@@ -677,7 +701,10 @@ impl MixEngine {
|
||||
let (dst, dst_fmt) = match &t.mixer.output {
|
||||
Route::Main => (&mut self.main, self.main_fmt),
|
||||
Route::Bus(b) => match self.busses.get_mut(b) {
|
||||
Some(d) => (&mut d.buf, d.fmt),
|
||||
Some(d) => {
|
||||
d.age.include(strip.send_post_age.delayed(strip.out_extra.len));
|
||||
(&mut d.buf, d.fmt)
|
||||
}
|
||||
None => return,
|
||||
},
|
||||
_ => return,
|
||||
@@ -711,3 +738,6 @@ mod click;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod send_age_tests;
|
||||
|
||||
+20
-4
@@ -18,13 +18,27 @@ fn midi_offset(s: &Session, t: &Track) -> i64 {
|
||||
.map_or(0, |v| v as i64)
|
||||
}
|
||||
|
||||
/// Send note on/offs and controllers for MIDI clips overlapping the block.
|
||||
/// Send note on/offs and controllers for MIDI clips overlapping the block. With `chase` (the
|
||||
/// first block after a start or seek), notes already sounding at `pos` are struck at the block
|
||||
/// start too, so a chord that began before a seek is heard rather than skipped until the next one.
|
||||
///
|
||||
/// `live` holds the notes played live on the same instrument. Instruments end notes by pitch, so
|
||||
/// a clip note-off is not sent while a live key holds that pitch: the key's own release ends it.
|
||||
/// A note-off held back that way is told to `live`: when the key goes up earlier in the same
|
||||
/// block, the note still lasts until the clip's note-off.
|
||||
pub(crate) fn schedule_notes(s: &Session, t: &Track, pos: Samples, frames: usize, inst: &mut PluginSlot, held: &mut Vec<u8>, live: &mut LiveNotes) {
|
||||
// The block, the instrument, its held and live notes, and whether this block chases: one call per
|
||||
// block from `render_instrument`, so a struct would only repack these.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn schedule_notes(
|
||||
s: &Session,
|
||||
t: &Track,
|
||||
pos: Samples,
|
||||
frames: usize,
|
||||
inst: &mut PluginSlot,
|
||||
held: &mut Vec<u8>,
|
||||
live: &mut LiveNotes,
|
||||
chase: bool,
|
||||
) {
|
||||
let sr = s.sample_rate;
|
||||
// MIDI Track Offsets: the track's notes sound `offset` samples later (earlier if negative), so
|
||||
// the block looks that far back into the clips.
|
||||
@@ -36,7 +50,9 @@ pub(crate) fn schedule_notes(s: &Session, t: &Track, pos: Samples, frames: usize
|
||||
continue;
|
||||
}
|
||||
let ClipContent::Midi { sequence } = &clip.content else { continue };
|
||||
if !clip.range().overlaps(&Range { start: pos, end }) {
|
||||
// A note-off clamped to the clip end falls on the first sample after the
|
||||
// clip, so a block starting exactly there still releases its notes.
|
||||
if !clip.range().overlaps(&Range { start: pos, end }) && clip.end() != pos {
|
||||
continue;
|
||||
}
|
||||
let base = s.tempo.samples_to_ticks(clip.start, sr);
|
||||
@@ -71,7 +87,7 @@ pub(crate) fn schedule_notes(s: &Session, t: &Track, pos: Samples, frames: usize
|
||||
if on >= clip.end() {
|
||||
continue;
|
||||
}
|
||||
if on >= pos && on < end {
|
||||
if (on >= pos && on < end) || (chase && on < pos && off > pos) {
|
||||
inst.plugin.note_on(usize::try_from(on - pos).unwrap_or(0), n.pitch, n.velocity);
|
||||
if !held.contains(&n.pitch) && held.len() < 128 {
|
||||
held.push(n.pitch);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains};
|
||||
|
||||
/// Per-block routing gains: `m[src][dst]`.
|
||||
type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
pub(crate) type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
|
||||
/// How a source is panned: the stereo pan pair (mono uses `[0]`) and the optional surround pan.
|
||||
pub(crate) struct PanSpec<'a> {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_dsp::Plugin;
|
||||
|
||||
use super::send_automation::SignalAge;
|
||||
use super::strip::{Block, BusBuf, LiveInput, MAX_LATENCY, PluginSlot, Strip, process_strip};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_bus_ages_accumulate_and_mixed_ages_keep_the_legacy_clock() {
|
||||
let mut bus = SignalAge::Empty;
|
||||
assert_eq!(bus.input(), SignalAge::Known(0));
|
||||
bus.include(SignalAge::Known(71));
|
||||
bus.include(SignalAge::Known(71));
|
||||
assert_eq!(bus, SignalAge::Known(71));
|
||||
let aux_pre = bus.delayed(23);
|
||||
let aux_post = aux_pre.delayed(48);
|
||||
assert_eq!(aux_pre, SignalAge::Known(94));
|
||||
assert_eq!(aux_post, SignalAge::Known(142));
|
||||
assert_eq!(aux_pre.clock(300).at(0), 206);
|
||||
assert_eq!(aux_post.clock(300).at(0), 158);
|
||||
let nested = aux_post.delayed(71);
|
||||
assert_eq!(nested, SignalAge::Known(213));
|
||||
bus.include(SignalAge::Known(142));
|
||||
assert_eq!(bus, SignalAge::Mixed);
|
||||
assert_eq!(bus.delayed(71).clock(300).at(0), 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_overflow_preserves_audio_with_the_legacy_clock_fallback() {
|
||||
let age = SignalAge::Known(u64::MAX).delayed(1);
|
||||
assert_eq!(age, SignalAge::Mixed);
|
||||
assert_eq!(age.clock(-7).at(3), -4);
|
||||
let mut bus = SignalAge::Known(71);
|
||||
bus.include(SignalAge::Empty);
|
||||
assert_eq!(bus, SignalAge::Known(71));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processed_insert_age_is_uncapped_while_pdc_stays_capped_and_overflow_falls_back() {
|
||||
struct DeclaredDelay {
|
||||
inner: Box<dyn Plugin>,
|
||||
latency: usize,
|
||||
}
|
||||
impl Plugin for DeclaredDelay {
|
||||
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
|
||||
self.inner.info()
|
||||
}
|
||||
fn prepare(&mut self, rate: f32, block: usize, channels: usize) {
|
||||
self.inner.prepare(rate, block, channels);
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
fn set_param(&mut self, id: &str, value: f32) -> bool {
|
||||
self.inner.set_param(id, value)
|
||||
}
|
||||
fn param(&self, id: &str) -> Option<f32> {
|
||||
self.inner.param(id)
|
||||
}
|
||||
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
|
||||
self.inner.process(io, frames);
|
||||
}
|
||||
fn latency(&self) -> usize {
|
||||
self.latency
|
||||
}
|
||||
}
|
||||
fn slot(latency: usize) -> PluginSlot {
|
||||
let mut inner = soundcraft_dsp::create("gain").unwrap();
|
||||
inner.prepare(48_000.0, 16, 1);
|
||||
PluginSlot::test_instance("gain".into(), 1, Box::new(DeclaredDelay { inner, latency }))
|
||||
}
|
||||
let mut source = Session::default();
|
||||
source.edit.delay_compensation = false;
|
||||
let audio = source.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
let source_id = soundcraft_model::SourceId(900);
|
||||
source.pool.insert(source_id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 16]] })));
|
||||
let clip = source.new_clip_id();
|
||||
let track = source.track_mut(audio).unwrap();
|
||||
track.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared-age reference", source_id, 0, 0, 16));
|
||||
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
|
||||
track.mixer.inserts[1] = Some(soundcraft_model::Insert::new("gain"));
|
||||
let mut pre = soundcraft_model::SendSlot::new(Route::None);
|
||||
pre.pre_fader = true;
|
||||
track.mixer.sends[0] = Some(pre);
|
||||
let mut strip = Strip::new();
|
||||
strip.buf = vec![vec![0.0; 16]];
|
||||
strip.scratch = vec![0.0; 16];
|
||||
strip.plugins = vec![Some(slot(MAX_LATENCY + 5)), Some(slot(MAX_LATENCY + 9))];
|
||||
let busses = HashMap::new();
|
||||
let live = LiveInput { input: &[], midi: &[], ports: None, midi_lost: 0, monitor_only: false, recording: false };
|
||||
let blk = Block { pos: 0, frames: 16, any_solo: false };
|
||||
process_strip(&source, source.track(audio).unwrap(), &mut strip, &busses, &live, blk);
|
||||
let declared_sum = 2 * MAX_LATENCY as u64 + 14;
|
||||
assert_eq!(strip.latency, MAX_LATENCY, "the existing PDC cap remains unchanged");
|
||||
assert_eq!(strip.send_pre_age, SignalAge::Known(declared_sum));
|
||||
assert_eq!(strip.send_post_age, SignalAge::Known(declared_sum));
|
||||
assert_eq!(strip.align.len, 0);
|
||||
assert_eq!(strip.align_pre.len, 0);
|
||||
assert_eq!(strip.pre, vec![vec![0.25; 16]]);
|
||||
assert_eq!(strip.buf, strip.pre, "declared age metadata never changes the processed PCM");
|
||||
|
||||
let bus = source.add_bus("Overflowing known input", ChannelFormat::Mono);
|
||||
let aux = source.add_track(TrackKind::Aux, ChannelFormat::Mono, None);
|
||||
let track = source.track_mut(aux).unwrap();
|
||||
track.mixer.input = Route::Bus(bus);
|
||||
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
|
||||
let busses = HashMap::from([(bus, BusBuf { fmt: ChannelFormat::Mono, buf: vec![vec![0.25; 16]], age: SignalAge::Known(u64::MAX) })]);
|
||||
let mut aux_strip = Strip::new();
|
||||
aux_strip.buf = vec![vec![0.0; 16]];
|
||||
aux_strip.plugins = vec![Some(slot(1))];
|
||||
process_strip(&source, source.track(aux).unwrap(), &mut aux_strip, &busses, &live, blk);
|
||||
assert_eq!(aux_strip.latency, 1);
|
||||
assert_eq!(aux_strip.send_pre_age, SignalAge::Mixed);
|
||||
assert_eq!(aux_strip.send_post_age, SignalAge::Mixed);
|
||||
assert_eq!(aux_strip.send_post_age.clock(300).at(0), 300);
|
||||
assert_eq!(aux_strip.buf, vec![vec![0.25; 16]], "overflow preserves the output instead of silencing it");
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Local send playback: sample-exact mono-to-stereo pan and stepped ordinary-bus mute.
|
||||
//! No document mutation, allocation, locks or persistent cursor survive a callback/seek.
|
||||
|
||||
use super::MAX_CHANNELS;
|
||||
use super::pan::Matrix;
|
||||
use soundcraft_dsp::pan::{PanLaw, gains};
|
||||
use soundcraft_model::{AutoParam, AutomationPoint, Track};
|
||||
use soundcraft_time::Samples;
|
||||
|
||||
/// Source-sample age metadata only; it never changes routing or audio delay compensation.
|
||||
/// A mixed-age sum has no single source clock, so new send readers retain their legacy clock.
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum SignalAge {
|
||||
#[default]
|
||||
Empty,
|
||||
Known(u64),
|
||||
Mixed,
|
||||
}
|
||||
|
||||
impl SignalAge {
|
||||
pub(crate) fn input(self) -> Self {
|
||||
match self {
|
||||
Self::Empty => Self::Known(0),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn delayed(self, frames: usize) -> Self {
|
||||
match self {
|
||||
Self::Known(age) => u64::try_from(frames).ok().and_then(|frames| age.checked_add(frames)).map_or(Self::Mixed, Self::Known),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn include(&mut self, contribution: Self) {
|
||||
*self = match (*self, contribution) {
|
||||
(Self::Empty, age) | (age, Self::Empty) => age,
|
||||
(Self::Known(a), Self::Known(b)) if a == b => Self::Known(a),
|
||||
_ => Self::Mixed,
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn clock(self, position: Samples) -> Clock {
|
||||
let age = match self {
|
||||
Self::Known(age) => age,
|
||||
Self::Empty | Self::Mixed => 0,
|
||||
};
|
||||
Clock::new(position, age)
|
||||
}
|
||||
}
|
||||
|
||||
/// A forward cursor rebuilt at each callback's absolute position. Like the existing mixer
|
||||
/// readers, this deliberately ignores lane.enabled; global suspension/migration is separate.
|
||||
/// Nonfinite or decreasing-time lanes fall back to the static control for the whole callback.
|
||||
/// Finite values clamp to the control range; duplicate times deterministically use the last knot.
|
||||
pub(super) struct Reader<'a> {
|
||||
points: &'a [AutomationPoint],
|
||||
next: usize,
|
||||
mute: bool,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn for_send(t: &'a Track, param: fn(u8) -> AutoParam, slot: usize, pos: Samples) -> Option<Self> {
|
||||
if !t.mixer.automation_mode.reads() {
|
||||
return None;
|
||||
}
|
||||
let param = param(u8::try_from(slot).ok()?);
|
||||
let lane = t.lane(¶m)?;
|
||||
let points = &lane.points;
|
||||
if points.is_empty() || points.iter().any(|p| !p.value.is_finite()) || points.windows(2).any(|p| p[0].at > p[1].at) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { points, next: points.partition_point(|p| p.at <= pos), mute: matches!(param, AutoParam::SendMute(_)) })
|
||||
}
|
||||
|
||||
pub(super) fn value(&mut self, pos: Samples) -> f32 {
|
||||
while self.points.get(self.next).is_some_and(|p| p.at <= pos) {
|
||||
self.next = self.next.saturating_add(1);
|
||||
}
|
||||
let Some(a) = self.points.get(self.next.saturating_sub(1)) else { return 0.0 };
|
||||
let lo = if self.mute { 0.0 } else { -1.0 };
|
||||
let av = a.value.clamp(lo, 1.0);
|
||||
if self.next == 0 || self.mute {
|
||||
return av;
|
||||
}
|
||||
let Some(b) = self.points.get(self.next) else { return av };
|
||||
// Valid timestamps may span i64::MIN..MAX. Widen before subtraction, and interpolate
|
||||
// bounded values in f64 so neither timestamp nor value arithmetic can overflow.
|
||||
let width = i128::from(b.at) - i128::from(a.at);
|
||||
if width <= 0 {
|
||||
return av;
|
||||
}
|
||||
let fraction = ((i128::from(pos) - i128::from(a.at)) as f64 / width as f64).clamp(0.0, 1.0);
|
||||
(f64::from(av) + (f64::from(b.value.clamp(lo, 1.0)) - f64::from(av)) * fraction) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeline position represented by a delayed source tap. Widen the entire expression before
|
||||
/// clamping, so advancing a frame near MIN/MAX does not lose an earlier delay subtraction.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Clock {
|
||||
position: Samples,
|
||||
age: u64,
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
pub(super) fn new(position: Samples, age: u64) -> Self {
|
||||
Self { position, age }
|
||||
}
|
||||
|
||||
pub(super) fn at(self, frame: usize) -> Samples {
|
||||
let frame = i128::try_from(frame).unwrap_or(i128::MAX);
|
||||
let at = i128::from(self.position).saturating_add(frame).saturating_sub(i128::from(self.age));
|
||||
at.clamp(i128::from(Samples::MIN), i128::from(Samples::MAX)) as Samples
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Samples> for Clock {
|
||||
fn from(position: Samples) -> Self {
|
||||
Self::new(position, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn frame_position(pos: Samples, frame: usize) -> Samples {
|
||||
Clock::from(pos).at(frame)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn apply_mono_stereo(
|
||||
src: &[Vec<f32>],
|
||||
frames: usize,
|
||||
dst: &mut [Vec<f32>],
|
||||
gain: f32,
|
||||
law: PanLaw,
|
||||
pos: impl Into<Clock>,
|
||||
mut pan: Reader<'_>,
|
||||
mut mute: Option<Reader<'_>>,
|
||||
) {
|
||||
let clock = pos.into();
|
||||
let Some(src) = src.first() else { return };
|
||||
for (i, sample) in src.iter().enumerate().take(frames) {
|
||||
let at = clock.at(i);
|
||||
if mute.as_mut().is_some_and(|m| m.value(at) >= 0.5) {
|
||||
continue;
|
||||
}
|
||||
let (left, right) = gains(pan.value(at), law);
|
||||
for (channel, factor) in [(0, left), (1, right)] {
|
||||
if let Some(out) = dst.get_mut(channel).and_then(|c| c.get_mut(i)) {
|
||||
*out += sample * gain * factor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the existing static routing matrix (including mono folds and surround positions),
|
||||
/// applying only the exact mute gate. Sparse taps are prepared on the stack once per block.
|
||||
pub(super) fn apply_gated(
|
||||
src: &[Vec<f32>],
|
||||
frames: usize,
|
||||
dst: &mut [Vec<f32>],
|
||||
matrix: &Matrix,
|
||||
gain: f32,
|
||||
pos: impl Into<Clock>,
|
||||
mut mute: Reader<'_>,
|
||||
) {
|
||||
let clock = pos.into();
|
||||
let mut taps = [[(0usize, 0.0f32); MAX_CHANNELS]; MAX_CHANNELS];
|
||||
let mut counts = [0usize; MAX_CHANNELS];
|
||||
for (d, (taps, count)) in taps.iter_mut().zip(counts.iter_mut()).enumerate().take(dst.len()) {
|
||||
for (s, row) in matrix.iter().enumerate().take(src.len().min(MAX_CHANNELS)) {
|
||||
let g = row.get(d).copied().unwrap_or(0.0);
|
||||
if g != 0.0
|
||||
&& let Some(tap) = taps.get_mut(*count)
|
||||
{
|
||||
*tap = (s, g);
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..frames {
|
||||
if mute.value(clock.at(i)) >= 0.5 {
|
||||
continue;
|
||||
}
|
||||
for (d, channel) in dst.iter_mut().enumerate().take(MAX_CHANNELS) {
|
||||
let Some(out) = channel.get_mut(i) else { continue };
|
||||
let mut acc = 0.0;
|
||||
for &(s, g) in taps.get(d).and_then(|t| counts.get(d).and_then(|n| t.get(..*n))).unwrap_or(&[]) {
|
||||
acc += src.get(s).and_then(|c| c.get(i)).copied().unwrap_or(0.0) * gain * g;
|
||||
}
|
||||
*out += acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use soundcraft_model::{AutomationLane, ChannelFormat, Session, TrackKind};
|
||||
|
||||
fn track(points: &[(i64, f32)], mute: bool) -> Track {
|
||||
let mut s = Session::default();
|
||||
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
let t = s.track_mut(id).unwrap();
|
||||
let mut lane = AutomationLane::new(if mute { AutoParam::SendMute(0) } else { AutoParam::SendPan(0) });
|
||||
lane.points = points.iter().map(|&(at, value)| AutomationPoint { at, value }).collect();
|
||||
t.automation.push(lane);
|
||||
t.clone()
|
||||
}
|
||||
#[test]
|
||||
fn wide_interpolation_does_not_overflow() {
|
||||
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
|
||||
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MIN).unwrap();
|
||||
assert_eq!(r.value(i64::MIN), -1.0);
|
||||
assert!(r.value(0).abs() < 1e-7);
|
||||
assert_eq!(r.value(i64::MAX), 1.0);
|
||||
assert_eq!(frame_position(i64::MAX - 1, 3), i64::MAX);
|
||||
}
|
||||
#[test]
|
||||
fn endpoints_duplicates_and_finite_extremes_are_deterministic() {
|
||||
let t = track(&[(3, -f32::MAX), (3, 0.25), (7, f32::MAX)], false);
|
||||
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, 0).unwrap();
|
||||
assert_eq!(r.value(0), -1.0);
|
||||
assert_eq!(r.value(3), 0.25);
|
||||
assert_eq!(r.value(5), 0.625);
|
||||
assert_eq!(r.value(9), 1.0);
|
||||
let t = track(&[(i64::MIN, -f32::MAX), (i64::MAX, f32::MAX)], true);
|
||||
let mut r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MIN).unwrap();
|
||||
assert_eq!(r.value(0), 0.0);
|
||||
assert_eq!(r.value(i64::MAX), 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn short_buffers_and_saturating_positions_do_not_panic() {
|
||||
let t = track(&[(i64::MIN, 0.0), (i64::MAX, 1.0)], true);
|
||||
let r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MAX - 1).unwrap();
|
||||
let mut dst = vec![vec![0.0; 1]];
|
||||
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
matrix[0][0] = 1.0;
|
||||
apply_gated(&[vec![0.25; 2]], 4, &mut dst, &matrix, 1.0, i64::MAX - 1, r);
|
||||
assert_eq!(dst, vec![vec![0.25]]);
|
||||
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
|
||||
let r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MAX - 1).unwrap();
|
||||
apply_mono_stereo(&[vec![0.25; 2]], 4, &mut [], 1.0, PanLaw::Minus3, i64::MAX - 1, r, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_clock_clamps_after_the_composite_delay_expression() {
|
||||
assert_eq!(Clock::new(i64::MIN + 5, 10).at(8), i64::MIN + 3);
|
||||
assert_eq!(Clock::new(i64::MAX, 10).at(3), i64::MAX - 7);
|
||||
assert_eq!(Clock::new(i64::MAX, 10).at(20), i64::MAX);
|
||||
assert_eq!(Clock::new(-5, 10).at(3), -12);
|
||||
assert_eq!(Clock::new(i64::MAX, u64::MAX).at(0), i64::MIN);
|
||||
assert_eq!(Clock::new(i64::MIN, u64::MAX).at(0), i64::MIN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_reader_seed_and_gate_advancement_use_the_same_clock() {
|
||||
let t = track(&[(0, 0.0), (30, 1.0), (40, 0.0)], true);
|
||||
let clock = Clock::new(45, 25);
|
||||
let reader = Reader::for_send(&t, AutoParam::SendMute, 0, clock.at(0)).unwrap();
|
||||
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
matrix[0][0] = 1.0;
|
||||
let mut destination = vec![vec![0.0; 25]];
|
||||
apply_gated(&[vec![0.25; 25]], 25, &mut destination, &matrix, 1.0, clock, reader);
|
||||
assert_eq!(destination[0], (0..25).map(|frame| if (10..20).contains(&frame) { 0.0 } else { 0.25 }).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
+43
-9
@@ -5,6 +5,7 @@ use super::live_midi::{LiveMidi, LiveNotes, MidiPorts, midi_thru};
|
||||
use super::midi::{chase_controllers, schedule_notes};
|
||||
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
|
||||
use super::routing::solo_muted;
|
||||
use super::send_automation::SignalAge;
|
||||
use super::{
|
||||
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
|
||||
db_to_gain,
|
||||
@@ -16,6 +17,8 @@ use std::sync::Arc;
|
||||
pub(crate) struct BusBuf {
|
||||
pub(crate) fmt: ChannelFormat,
|
||||
pub(crate) buf: Vec<Vec<f32>>,
|
||||
/// Age shared by the routed contributions in this block, or Mixed when they differ.
|
||||
pub(crate) age: SignalAge,
|
||||
}
|
||||
|
||||
pub(crate) struct PluginSlot {
|
||||
@@ -35,6 +38,13 @@ pub(crate) struct PluginSlot {
|
||||
pub(crate) retried: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl PluginSlot {
|
||||
pub(crate) fn test_instance(id: String, ch: usize, plugin: Box<dyn Plugin>) -> Self {
|
||||
Self { id, ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Strip {
|
||||
pub(crate) buf: Vec<Vec<f32>>,
|
||||
/// Pre-fader copy for pre-fader sends.
|
||||
@@ -50,6 +60,9 @@ pub(crate) struct Strip {
|
||||
pub(crate) live: LiveNotes,
|
||||
/// The instrument's next block starts somewhere new: send it the controllers in effect there.
|
||||
pub(crate) chase: bool,
|
||||
/// Live controllers moved the instrument and were let go: the next block sends it the clips'
|
||||
/// controllers again, without striking the notes already sounding (that is `chase`).
|
||||
pub(crate) restore_controllers: bool,
|
||||
/// The last block played the clips: stopped monitoring has their sustain pedal to let go of.
|
||||
pub(crate) clips_played: bool,
|
||||
pub(crate) muted: bool,
|
||||
@@ -59,6 +72,9 @@ pub(crate) struct Strip {
|
||||
clipbuf: Vec<Vec<f32>>,
|
||||
/// Total latency of the active inserts (samples).
|
||||
pub(crate) latency: usize,
|
||||
/// Sample ages of the selected send taps after their actual applied alignment.
|
||||
pub(crate) send_pre_age: SignalAge,
|
||||
pub(crate) send_post_age: SignalAge,
|
||||
/// Delay compensation: align this strip with the slowest one (post- and pre-fader paths),
|
||||
/// plus extra delay for direct-to-main outputs so they line up with aux returns.
|
||||
pub(crate) align: DelayLine,
|
||||
@@ -151,12 +167,15 @@ impl Strip {
|
||||
held: Vec::new(),
|
||||
live: LiveNotes::default(),
|
||||
chase: true,
|
||||
restore_controllers: false,
|
||||
clips_played: false,
|
||||
muted: false,
|
||||
gr: 0.0,
|
||||
clip_fx: HashMap::new(),
|
||||
clipbuf: Vec::new(),
|
||||
latency: 0,
|
||||
send_pre_age: SignalAge::Known(0),
|
||||
send_post_age: SignalAge::Known(0),
|
||||
align: DelayLine::default(),
|
||||
align_pre: DelayLine::default(),
|
||||
out_extra: DelayLine::default(),
|
||||
@@ -289,10 +308,11 @@ fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) {
|
||||
}
|
||||
|
||||
/// An aux or folder reads the bus its input is routed from.
|
||||
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) {
|
||||
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) -> SignalAge {
|
||||
if let Route::Bus(b) = &t.mixer.input
|
||||
&& let Some(src) = busses.get(b)
|
||||
{
|
||||
let input_age = src.age.input();
|
||||
let (ns, nd) = (src.buf.len(), strip.buf.len());
|
||||
let dst_fmt = strip_format(t, nd);
|
||||
let m = if src.fmt == dst_fmt && ns == nd {
|
||||
@@ -308,7 +328,9 @@ fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, f
|
||||
build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3)
|
||||
};
|
||||
apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0);
|
||||
return input_age;
|
||||
}
|
||||
SignalAge::Known(0)
|
||||
}
|
||||
|
||||
/// Render the track's instrument into the strip.
|
||||
@@ -325,7 +347,10 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
|
||||
}
|
||||
inst.plugin.set_transport(transport);
|
||||
// Whether the clips' controller values were sent to the instrument for this block.
|
||||
let mut chased = std::mem::take(&mut strip.chase);
|
||||
// A start or seek: notes already sounding are struck again too (not when only a live
|
||||
// source went away, below; those notes are still held).
|
||||
let chase = std::mem::take(&mut strip.chase);
|
||||
let mut chased = chase | std::mem::take(&mut strip.restore_controllers);
|
||||
if chased {
|
||||
let from_clips = chase_controllers(s, t, pos, inst);
|
||||
strip.live.restore_defaults(from_clips, inst.plugin.as_mut());
|
||||
@@ -346,7 +371,7 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
|
||||
chased = true;
|
||||
}
|
||||
if !live.monitor_only {
|
||||
schedule_notes(s, t, pos, frames, inst, &mut strip.held, &mut strip.live);
|
||||
schedule_notes(s, t, pos, frames, inst, &mut strip.held, &mut strip.live, chase);
|
||||
strip.clips_played = true;
|
||||
} else {
|
||||
// Stopped: the clips are silent, only live MIDI input plays. Playback that ran to its
|
||||
@@ -371,7 +396,7 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
|
||||
strip.live.play(t, inst.plugin.as_mut(), live.midi, live.ports, frames);
|
||||
} else if strip.live.touched() && strip.live.release(inst.plugin.as_mut()) {
|
||||
// Live controllers moved the instrument: the next block sets them from the clips.
|
||||
strip.chase = true;
|
||||
strip.restore_controllers = true;
|
||||
}
|
||||
if strip.buf.len() >= 2 {
|
||||
inst.plugin.process(&mut strip.buf, frames);
|
||||
@@ -393,10 +418,12 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
|
||||
}
|
||||
|
||||
/// Run the active inserts in order; records their latency and the first gain reduction.
|
||||
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) {
|
||||
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport, input_age: SignalAge) {
|
||||
let Block { pos, frames, .. } = blk;
|
||||
let mut gr = 0.0f32;
|
||||
let mut latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
|
||||
let inst_latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
|
||||
let mut latency = inst_latency;
|
||||
let mut send_age = input_age.delayed(inst_latency);
|
||||
for (i, ins) in t.mixer.inserts.iter().enumerate() {
|
||||
let (Some(ins), Some(Some(slot))) = (ins, strip.plugins.get_mut(i)) else { continue };
|
||||
if !ins.active || ins.bypass || slot.failed {
|
||||
@@ -409,13 +436,17 @@ fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport)
|
||||
strip.failures.record(i);
|
||||
continue;
|
||||
}
|
||||
latency = latency.saturating_add(slot.plugin.latency());
|
||||
let declared_latency = slot.plugin.latency();
|
||||
latency = latency.saturating_add(declared_latency);
|
||||
send_age = send_age.delayed(declared_latency);
|
||||
if gr == 0.0 {
|
||||
gr = slot.plugin.gain_reduction_db();
|
||||
}
|
||||
}
|
||||
strip.gr = gr;
|
||||
strip.latency = latency.min(MAX_LATENCY);
|
||||
strip.send_pre_age = send_age;
|
||||
strip.send_post_age = send_age;
|
||||
}
|
||||
|
||||
/// Fader gain (volume, trim and VCA automation), read at every sample of the block.
|
||||
@@ -466,6 +497,7 @@ fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) {
|
||||
pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, live: &LiveInput<'_>, blk: Block) {
|
||||
let Block { pos, frames, any_solo } = blk;
|
||||
zero_buf(&mut strip.buf, frames);
|
||||
let mut input_age = SignalAge::Known(0);
|
||||
let transport = transport_at(s, pos, !live.monitor_only, live.recording);
|
||||
match t.kind {
|
||||
TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => {
|
||||
@@ -476,7 +508,9 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
|
||||
// doing so, to release its notes).
|
||||
TrackKind::Instrument | TrackKind::Midi if live.monitor_only && !midi_thru(t) && !strip.live.touched() => {}
|
||||
TrackKind::Audio => render_audio_clips(s, t, strip, blk),
|
||||
TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames),
|
||||
TrackKind::Aux | TrackKind::Folder => {
|
||||
input_age = read_aux_bus(t, strip, busses, frames);
|
||||
}
|
||||
TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, live, blk, &transport),
|
||||
_ => {}
|
||||
}
|
||||
@@ -486,7 +520,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
|
||||
c.iter_mut().take(frames).for_each(|x| *x *= trim);
|
||||
}
|
||||
}
|
||||
run_inserts(t, strip, blk, &transport);
|
||||
run_inserts(t, strip, blk, &transport, input_age);
|
||||
let soloed_out = solo_muted(s, t, any_solo);
|
||||
strip.muted = t.mixer.mute || soloed_out;
|
||||
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
|
||||
|
||||
@@ -47,6 +47,20 @@ fn delay_line_change_keeps_buffers_and_history() {
|
||||
assert_eq!(ptrs, after, "delay line reallocated going back to its size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_off_at_the_clip_end_on_a_block_boundary_releases_the_note() {
|
||||
// The note ends with its 24,000-sample clip; 480-frame blocks put that
|
||||
// note-off at the first sample of the block after the clip.
|
||||
let mut s = synth_session(-6.0);
|
||||
if let Some(ins) = s.tracks[0].instrument.as_mut() {
|
||||
ins.params.insert("amp_release".into(), 20.0);
|
||||
}
|
||||
let out = render_range(&s, Range::new(0, 48_000), 480);
|
||||
let peak = |r: std::ops::Range<usize>| out[0].get(r).unwrap_or_default().iter().fold(0.0_f32, |p, x| p.max(x.abs()));
|
||||
assert!(peak(12_000..24_000) > 0.01, "the synth should sound");
|
||||
assert!(peak(30_000..48_000) < 1e-4, "the note must be released at the clip end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_instrument_params_reach_the_plugin() {
|
||||
// #152: a saved instrument level of -12 dB must render quieter than -6 dB.
|
||||
@@ -529,6 +543,36 @@ impl Plugin for Ears {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_held_across_a_seek_are_struck_again() {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, None);
|
||||
s.track_mut(t).unwrap().instrument = Some(Insert::new("clap:test.keys"));
|
||||
let mut seq = soundcraft_midi::Sequence::default();
|
||||
// A two-note chord over the first two beats at 120 BPM (0..48_000), then a note from beat 3.
|
||||
for pitch in [60, 64] {
|
||||
seq.notes.push(soundcraft_midi::Note { pitch, velocity: 90, release_velocity: 64, channel: 0, start: 0, length: 1920 });
|
||||
}
|
||||
seq.notes.push(soundcraft_midi::Note { pitch: 67, velocity: 90, release_velocity: 64, channel: 0, start: 1920, length: 960 });
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::midi(cid, "m", 0, 96_000, seq));
|
||||
let heard = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let keys = Keys { inner: soundcraft_dsp::create("gain").unwrap(), heard: Arc::clone(&heard) };
|
||||
let mut eng = MixEngine::new(48_000.0, 512);
|
||||
eng.set_external_instances(true);
|
||||
eng.adopt(vec![PreparedInstance { track: t, slot: INSTRUMENT_SLOT, id: "clap:test.keys".into(), ch: 2, plugin: Box::new(keys) }]);
|
||||
render_block(&mut eng, &s, 0);
|
||||
assert_eq!(std::mem::take(&mut *heard.lock().unwrap()), vec![(60, 90), (64, 90)]);
|
||||
render_block(&mut eng, &s, 512);
|
||||
assert!(heard.lock().unwrap().is_empty(), "continuing playback does not strike held notes again");
|
||||
// Seek into the middle of the chord: both notes sound again from the block start.
|
||||
render_block(&mut eng, &s, 24_000);
|
||||
assert_eq!(std::mem::take(&mut *heard.lock().unwrap()), vec![(60, 90), (64, 90)]);
|
||||
// Seek past the chord into the later note: only that one is chased.
|
||||
render_block(&mut eng, &s, 60_000);
|
||||
assert_eq!(std::mem::take(&mut *heard.lock().unwrap()), vec![(67, 90)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controllers_play_at_their_offsets_and_are_chased_after_a_seek() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
use super::AUDIO_THREAD;
|
||||
|
||||
/// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks
|
||||
/// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads
|
||||
/// count as the audio thread while they render for it. Code that might run there asks
|
||||
/// do, every call: one thread-local store). [`MixEngine::render`] renders every strip on that
|
||||
/// thread itself instead of handing strips to worker threads. Code that might run there asks
|
||||
/// [`on_audio_thread`] before doing anything that blocks; the desktop app's logger does, so a
|
||||
/// `log::` record from the audio thread never takes a lock or touches a file.
|
||||
pub fn mark_audio_thread() {
|
||||
AUDIO_THREAD.set(true);
|
||||
}
|
||||
|
||||
/// True on the thread [`mark_audio_thread`] marked, and on a worker while it renders strips for
|
||||
/// it. Lock-free and allocation-free.
|
||||
/// True on the thread [`mark_audio_thread`] marked. Lock-free and allocation-free.
|
||||
pub fn on_audio_thread() -> bool {
|
||||
AUDIO_THREAD.get()
|
||||
}
|
||||
@@ -29,7 +28,11 @@ fn as_audio_thread(audio: bool, f: impl FnOnce()) {
|
||||
f();
|
||||
}
|
||||
|
||||
/// Process strips, in parallel on native targets when there are enough of them.
|
||||
/// Process strips: in parallel on native targets when there are enough of them, except on the
|
||||
/// realtime audio thread. There they render one after the other on the thread itself: the pool's
|
||||
/// workers run at normal priority, so under load the callback would wait for starved workers
|
||||
/// (priority inversion) and miss its deadline, and waiting on them blocks, which the callback
|
||||
/// never may. Offline renders (bounces) keep the parallelism.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn run_strips<T: Send>(work: &mut [T], f: impl Fn(&mut T) + Sync + Send) {
|
||||
use rayon::prelude::*;
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
//! Independent PCM references for the bounded send consumers, with no hosted plugins/devices.
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_dsp::pan::PanLaw;
|
||||
use soundcraft_mix::{MixEngine, render_bus, render_range};
|
||||
use soundcraft_model::{
|
||||
AutoParam, AutomationLane, AutomationMode, AutomationPoint, BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId,
|
||||
TrackKind,
|
||||
};
|
||||
use soundcraft_time::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
const LEN: usize = 640;
|
||||
const PAN: [(i64, f32); 3] = [(37, -1.0), (173, 0.75), (401, 1.0)];
|
||||
const MUTE: [(i64, f32); 5] = [(37, 0.0), (97, 1.0), (173, 0.0), (257, 1.0), (349, 0.0)];
|
||||
|
||||
fn fixture(format: ChannelFormat) -> (Session, TrackId, BusId) {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, format, None);
|
||||
let src = SourceId(900);
|
||||
let channels = (0..format.channels()).map(|ch| (0..LEN).map(|n| signal(ch, n)).collect()).collect();
|
||||
s.pool.insert(src, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels })));
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original synthetic", src, 0, 0, LEN as i64));
|
||||
let bus = s.add_bus("Send", ChannelFormat::Stereo);
|
||||
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
|
||||
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.output = Route::None;
|
||||
let mut send = SendSlot::new(Route::Bus(bus));
|
||||
send.level_db = 0.0;
|
||||
tr.mixer.sends[0] = Some(send);
|
||||
(s, t, bus)
|
||||
}
|
||||
fn signal(ch: usize, n: usize) -> f32 {
|
||||
if n % 17 < 9 { 0.25 + ch as f32 / 100.0 } else { -0.125 - ch as f32 / 200.0 }
|
||||
}
|
||||
fn lane(s: &mut Session, t: TrackId, param: AutoParam, points: &[(i64, f32)]) {
|
||||
let mut lane = AutomationLane::new(param);
|
||||
for &(at, value) in points {
|
||||
lane.set_point(at, value);
|
||||
}
|
||||
s.track_mut(t).unwrap().automation.push(lane);
|
||||
}
|
||||
fn automated() -> (Session, TrackId, BusId) {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
(s, t, bus)
|
||||
}
|
||||
// The expectation never calls AutomationLane::value_at, pan::gains or any mixer helper.
|
||||
fn expected_pan(at: i64) -> f64 {
|
||||
if at <= PAN[0].0 {
|
||||
return f64::from(PAN[0].1);
|
||||
}
|
||||
for pair in PAN.windows(2) {
|
||||
if at < pair[1].0 {
|
||||
let f = (at - pair[0].0) as f64 / (pair[1].0 - pair[0].0) as f64;
|
||||
return f64::from(pair[0].1) + f64::from(pair[1].1 - pair[0].1) * f;
|
||||
}
|
||||
}
|
||||
f64::from(PAN[2].1)
|
||||
}
|
||||
fn muted(at: i64) -> bool {
|
||||
MUTE.iter().rev().find(|p| p.0 <= at).unwrap_or(&MUTE[0]).1 >= 0.5
|
||||
}
|
||||
fn pan_factors(p: f64, law: PanLaw) -> [f64; 2] {
|
||||
if law == PanLaw::Zero {
|
||||
return [(1.0 - p).min(1.0), (1.0 + p).min(1.0)];
|
||||
}
|
||||
let depth = match law {
|
||||
PanLaw::Minus3 => -3.0,
|
||||
PanLaw::Minus4_5 => -4.5,
|
||||
PanLaw::Minus6 => -6.0,
|
||||
PanLaw::Zero => 0.0,
|
||||
};
|
||||
let angle = (p + 1.0) * std::f64::consts::PI / 4.0;
|
||||
[angle.cos().max(0.0).powf(depth / -3.0103), angle.sin().max(0.0).powf(depth / -3.0103)]
|
||||
}
|
||||
fn assert_shape(out: &[Vec<f32>], channels: usize, frames: usize) {
|
||||
assert_eq!(out.len(), channels);
|
||||
for channel in out {
|
||||
assert_eq!(channel.len(), frames);
|
||||
}
|
||||
}
|
||||
fn check(out: &[Vec<f32>], start: i64, frames: usize, law: PanLaw, scale: f64) {
|
||||
assert_shape(out, 2, frames);
|
||||
for (ch, values) in out.iter().enumerate() {
|
||||
for (n, &actual) in values.iter().enumerate() {
|
||||
let at = start + n as i64;
|
||||
let reference = if muted(at) { 0.0 } else { f64::from(signal(0, at as usize)) * scale * pan_factors(expected_pan(at), law)[ch] };
|
||||
assert!((f64::from(actual) - reference).abs() < 2e-7, "channel {ch}, at {at}: {actual} vs {reference}");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn chunks(eng: &mut MixEngine, s: &Session, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
|
||||
let mut out = vec![Vec::new(), Vec::new()];
|
||||
let mut offset = 0;
|
||||
let mut k = 0;
|
||||
while offset < length {
|
||||
let n = sizes[k % sizes.len()].min(length - offset);
|
||||
let mut block = vec![vec![0.0; n]; 2];
|
||||
eng.render(s, start + offset as i64, n, &mut block);
|
||||
for (out, block) in out.iter_mut().zip(block) {
|
||||
out.extend(block);
|
||||
}
|
||||
offset += n;
|
||||
k += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_and_mute_match_independent_pcm_across_chunks() {
|
||||
let (s, _, bus) = automated();
|
||||
for block in [1, 37, 64, 100, 512, 1024] {
|
||||
let mut e = MixEngine::new(48_000.0, block.max(16));
|
||||
let out = chunks(&mut e, &s, 0, LEN, &[block]);
|
||||
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
check(&chunks(&mut e, &s, 0, LEN, &[1, 37, 64, 3, 100, 19]), 0, LEN, PanLaw::Minus3, 1.0);
|
||||
check(&render_bus(&s, bus, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn all_pan_laws_match_numeric_reference_and_static_calibration() {
|
||||
let (s, _, _) = automated();
|
||||
for law in [PanLaw::Minus3, PanLaw::Minus4_5, PanLaw::Minus6, PanLaw::Zero] {
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
e.pan_law = law;
|
||||
check(&chunks(&mut e, &s, 0, LEN, &[100]), 0, LEN, law, 1.0);
|
||||
for at in [0, 77, 173, 349, 401] {
|
||||
let (mut reference, t, _) = fixture(ChannelFormat::Mono);
|
||||
reference.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pan = expected_pan(at) as f32;
|
||||
let mut static_engine = MixEngine::new(48_000.0, 16);
|
||||
static_engine.pan_law = law;
|
||||
let static_pcm = chunks(&mut static_engine, &reference, at, 1, &[1]);
|
||||
let automated_pcm = chunks(&mut e, &s, at, 1, &[1]);
|
||||
assert_shape(&automated_pcm, 2, 1);
|
||||
assert_shape(&static_pcm, 2, 1);
|
||||
assert_eq!(automated_pcm, static_pcm);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn seeking_used_engine_has_no_cursor_history() {
|
||||
let (s, _, _) = automated();
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
let _ = chunks(&mut e, &s, 0, 520, &[100]);
|
||||
for at in [31, 77, 97, 98, 173, 256, 257, 301] {
|
||||
let out = chunks(&mut e, &s, at, 31, &[17, 1, 13]);
|
||||
check(&out, at, 31, PanLaw::Minus3, 1.0);
|
||||
let mut fresh = MixEngine::new(48_000.0, 1024);
|
||||
assert_eq!(out, chunks(&mut fresh, &s, at, 31, &[17, 1, 13]));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn loop_wrap_and_tiny_final_chunks_use_absolute_knots() {
|
||||
let (s, _, _) = automated();
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
// Same loop splitting as playback: do not render past the loop end before wrapping.
|
||||
for _ in 0..3 {
|
||||
check(&chunks(&mut e, &s, 37, 264, &[100, 63]), 37, 264, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
check(&chunks(&mut e, &s, 97, 76, &[37]), 97, 76, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn modes_and_lane_enabled_preserve_existing_reader_policy() {
|
||||
for mode in AutomationMode::ALL {
|
||||
let (mut s, t, _) = automated();
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.automation_mode = mode;
|
||||
tr.mixer.sends[0].as_mut().unwrap().mute = true;
|
||||
for lane in &mut tr.automation {
|
||||
lane.enabled = false;
|
||||
}
|
||||
let out = render_range(&s, Range::new(0, LEN as i64), 37);
|
||||
assert_shape(&out, 2, LEN);
|
||||
if mode == AutomationMode::Off {
|
||||
assert!(out.iter().flatten().all(|v| *v == 0.0));
|
||||
} else {
|
||||
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn missing_and_empty_lanes_keep_static_pan_and_mute() {
|
||||
let (mut s, t, _) = fixture(ChannelFormat::Mono);
|
||||
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &[]);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &[]);
|
||||
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
|
||||
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().mute = true;
|
||||
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
|
||||
}
|
||||
#[test]
|
||||
fn static_matrix_mute_steps_and_threshold_match_reference() {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &[(0, 0.49), (97, 0.5), (173, 0.0)]);
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
|
||||
assert_shape(&out, 2, LEN);
|
||||
assert_shape(&reference, 2, LEN);
|
||||
assert_eq!(out.len(), reference.len());
|
||||
for (actual, reference) in out.iter().zip(reference) {
|
||||
assert_eq!(actual.len(), reference.len());
|
||||
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
|
||||
assert_eq!(a, if (97..173).contains(&i) { 0.0 } else { r });
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn mute_preserves_routing_for_mono_surround_and_sixteen_channels() {
|
||||
for fmt in [ChannelFormat::Mono, ChannelFormat::Stereo, ChannelFormat::Surround51, ChannelFormat::Atmos714, ChannelFormat::Atmos916] {
|
||||
let (mut s, t, bus) = fixture(fmt);
|
||||
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = fmt;
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
|
||||
assert_shape(&out, fmt.channels(), LEN);
|
||||
assert_shape(&reference, fmt.channels(), LEN);
|
||||
assert_eq!(out.len(), reference.len());
|
||||
for (actual, reference) in out.iter().zip(reference) {
|
||||
assert_eq!(actual.len(), reference.len());
|
||||
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
|
||||
assert_eq!(a, if muted(i as i64) { 0.0 } else { r });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn wider_source_and_destination_send_pan_keep_static_routing() {
|
||||
for (src_fmt, dst_fmt) in [
|
||||
(ChannelFormat::Stereo, ChannelFormat::Stereo),
|
||||
(ChannelFormat::Mono, ChannelFormat::Surround51),
|
||||
(ChannelFormat::Surround51, ChannelFormat::Stereo),
|
||||
] {
|
||||
let (mut s, t, bus) = fixture(src_fmt);
|
||||
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = dst_fmt;
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
assert_shape(&reference, dst_fmt.channels(), LEN);
|
||||
let actual = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert_shape(&actual, dst_fmt.channels(), LEN);
|
||||
assert_eq!(actual, reference);
|
||||
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn pre_post_fader_send_level_and_direct_output_are_preserved() {
|
||||
for pre in [false, true] {
|
||||
let (mut s, t, bus) = automated();
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.volume_db = -6.0;
|
||||
let snd = tr.mixer.sends[0].as_mut().unwrap();
|
||||
snd.pre_fader = pre;
|
||||
snd.level_db = -3.0;
|
||||
let factor = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
|
||||
check(&render_range(&s, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, factor);
|
||||
// Keep the direct path isolated from the Aux while comparing source-main PCM.
|
||||
let aux = s.tracks.iter().find(|tr| tr.kind == TrackKind::Aux).unwrap().id;
|
||||
s.track_mut(aux).unwrap().inactive = true;
|
||||
s.track_mut(t).unwrap().mixer.output = Route::Main;
|
||||
let direct = render_range(&s, Range::new(0, LEN as i64), 37);
|
||||
s.track_mut(t).unwrap().automation.clear();
|
||||
s.track_mut(t).unwrap().mixer.sends[0] = None;
|
||||
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 37), direct);
|
||||
assert_eq!(s.bus(bus).unwrap().format, ChannelFormat::Stereo);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn track_solo_and_vca_suppression_cannot_be_unmuted_by_send_lane() {
|
||||
for suppression in [0, 1, 2] {
|
||||
let (mut s, t, _) = automated();
|
||||
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pre_fader = true;
|
||||
match suppression {
|
||||
0 => s.track_mut(t).unwrap().mixer.mute = true,
|
||||
1 => {
|
||||
let other = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
s.track_mut(other).unwrap().mixer.solo = true;
|
||||
}
|
||||
_ => {
|
||||
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, None);
|
||||
s.track_mut(vca).unwrap().mixer.mute = true;
|
||||
s.track_mut(t).unwrap().mixer.vca = Some(vca.0);
|
||||
}
|
||||
}
|
||||
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn slots_a_and_j_and_absent_slots_do_not_drive_each_other() {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
|
||||
let other = s.add_bus("J", ChannelFormat::Stereo);
|
||||
let mut send = SendSlot::new(Route::Bus(other));
|
||||
send.level_db = 0.0;
|
||||
s.track_mut(t).unwrap().mixer.sends[9] = Some(send);
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
lane(&mut s, t, AutoParam::SendPan(9), &PAN);
|
||||
lane(&mut s, t, AutoParam::SendMute(9), &MUTE);
|
||||
lane(&mut s, t, AutoParam::SendMute(8), &[(0, 1.0)]);
|
||||
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
|
||||
check(&render_bus(&s, other, Range::new(0, LEN as i64), 100), 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn malformed_lanes_fall_back_without_changing_document() {
|
||||
for points in [
|
||||
vec![AutomationPoint { at: 3, value: -1.0 }, AutomationPoint { at: 1, value: 1.0 }],
|
||||
vec![AutomationPoint { at: 0, value: f32::NAN }],
|
||||
vec![AutomationPoint { at: 0, value: f32::INFINITY }],
|
||||
] {
|
||||
let (mut s, t, _) = fixture(ChannelFormat::Mono);
|
||||
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
|
||||
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
|
||||
let mut lane = AutomationLane::new(param);
|
||||
lane.points = points.clone();
|
||||
s.track_mut(t).unwrap().automation.push(lane);
|
||||
}
|
||||
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
|
||||
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
assert_eq!(before, after);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_sends_keep_legacy_left_right_routing_for_every_static_pan() {
|
||||
for static_pan in [-1.0, -0.75, 0.0, 0.75, 1.0, f32::NAN, f32::INFINITY] {
|
||||
for state in ["absent", "empty", "off", "malformed", "active"] {
|
||||
for pre in [false, true] {
|
||||
for gated in [false, true] {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.volume_db = -6.0;
|
||||
let send = tr.mixer.sends[0].as_mut().unwrap();
|
||||
send.pan = static_pan;
|
||||
send.pre_fader = pre;
|
||||
send.level_db = -3.0;
|
||||
match state {
|
||||
"absent" => {}
|
||||
"empty" => lane(&mut s, t, AutoParam::SendPan(0), &[]),
|
||||
"off" => {
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
|
||||
}
|
||||
"malformed" => {
|
||||
let mut pan = AutomationLane::new(AutoParam::SendPan(0));
|
||||
pan.points = vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: -1.0 }];
|
||||
s.track_mut(t).unwrap().automation.push(pan);
|
||||
}
|
||||
"active" => lane(&mut s, t, AutoParam::SendPan(0), &PAN),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
if gated {
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
}
|
||||
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
|
||||
for block in [1, 37, 100] {
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
|
||||
assert_shape(&out, 2, LEN);
|
||||
for (ch, channel) in out.iter().enumerate() {
|
||||
for (n, &actual) in channel.iter().enumerate() {
|
||||
// Existing stereo sends route channels directly to L/R. This reference
|
||||
// does not call either routing matrices or a pan helper.
|
||||
let expected = if gated && state != "off" && muted(n as i64) { 0.0 } else { f64::from(signal(ch, n)) * scale };
|
||||
assert!(
|
||||
(f64::from(actual) - expected).abs() < 2e-7,
|
||||
"{state} pre={pre} gated={gated} ch={ch} at={n}: {actual} != {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(s.track(t).unwrap().mixer.sends[0].as_ref().unwrap().pan.to_bits(), static_pan.to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_mono_send_lanes_match_independent_static_controls() {
|
||||
for state in ["absent", "empty", "off", "unordered", "nan", "infinite"] {
|
||||
for pre in [false, true] {
|
||||
for static_mute in [false, true] {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.volume_db = -6.0;
|
||||
let send = tr.mixer.sends[0].as_mut().unwrap();
|
||||
send.pan = -0.625;
|
||||
send.mute = static_mute;
|
||||
send.pre_fader = pre;
|
||||
send.level_db = -3.0;
|
||||
if state == "off" {
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
|
||||
} else if state != "absent" {
|
||||
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
|
||||
let mut control = AutomationLane::new(param);
|
||||
control.points = match state {
|
||||
"empty" => vec![],
|
||||
"unordered" => vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: 0.0 }],
|
||||
"nan" => vec![AutomationPoint { at: 0, value: f32::NAN }],
|
||||
"infinite" => vec![AutomationPoint { at: 0, value: f32::INFINITY }],
|
||||
_ => unreachable!(),
|
||||
};
|
||||
s.track_mut(t).unwrap().automation.push(control);
|
||||
}
|
||||
}
|
||||
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
|
||||
let factors = pan_factors(-0.625, PanLaw::Minus3);
|
||||
for block in [1, 37, 100] {
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
|
||||
assert_shape(&out, 2, LEN);
|
||||
for (ch, channel) in out.iter().enumerate() {
|
||||
for (n, &actual) in channel.iter().enumerate() {
|
||||
let expected = if static_mute { 0.0 } else { f64::from(signal(0, n)) * scale * factors[ch] };
|
||||
assert!(
|
||||
(f64::from(actual) - expected).abs() < 2e-7,
|
||||
"{state} pre={pre} muted={static_mute} ch={ch} at={n}: {actual} != {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
assert_eq!(before, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Send automation follows the delayed audio at its tap, without changing existing PDC routing.
|
||||
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_dsp::pan::PanLaw;
|
||||
use soundcraft_mix::{MixEngine, render_bus};
|
||||
use soundcraft_model::{
|
||||
AutoParam, AutomationLane, BusId, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind,
|
||||
};
|
||||
use soundcraft_time::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
// The built-in Maximizer uses 1.5 ms of lookahead: 72 samples at 48 kHz, with a declared
|
||||
// and physical delay of 72 - 1 = 71. Its untouched threshold 0 dB gives unity drive;
|
||||
// every synthetic level stays below the default -0.3 dB ceiling, so there is no limiting.
|
||||
// Expected timelines use these declared values, not mixer latency fields or the clock helper.
|
||||
const LOOKAHEAD: usize = 71;
|
||||
const SOURCE_FRAMES: usize = 2048;
|
||||
const MUTE_AT: i64 = 300;
|
||||
const AMPLITUDE: f32 = 0.25;
|
||||
|
||||
struct Graph {
|
||||
session: Session,
|
||||
capture: BusId,
|
||||
receiver: TrackId,
|
||||
clip_start: i64,
|
||||
pan_start: i64,
|
||||
pan_end: i64,
|
||||
}
|
||||
|
||||
fn maximizers(session: &mut Session, track: TrackId, count: usize) {
|
||||
for slot in session.track_mut(track).unwrap().mixer.inserts.iter_mut().take(count) {
|
||||
*slot = Some(Insert::new("maximizer"));
|
||||
}
|
||||
}
|
||||
|
||||
fn source(session: &mut Session, insert_count: usize, clip_start: i64) -> TrackId {
|
||||
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Declared DC"));
|
||||
let id = SourceId(901);
|
||||
session.pool.insert(id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![AMPLITUDE; SOURCE_FRAMES]] })));
|
||||
let clip = session.new_clip_id();
|
||||
let t = session.track_mut(track).unwrap();
|
||||
t.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared DC", id, 0, clip_start, SOURCE_FRAMES as i64));
|
||||
t.mixer.pan = vec![0.0];
|
||||
t.mixer.output = Route::None;
|
||||
maximizers(session, track, insert_count);
|
||||
track
|
||||
}
|
||||
|
||||
fn silent_audio(session: &mut Session, insert_count: usize) {
|
||||
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Unrelated silent lookahead"));
|
||||
session.track_mut(track).unwrap().mixer.output = Route::None;
|
||||
maximizers(session, track, insert_count);
|
||||
}
|
||||
|
||||
fn aux(session: &mut Session, input: BusId, format: ChannelFormat, insert_count: usize) -> TrackId {
|
||||
let track = session.add_track(TrackKind::Aux, format, None);
|
||||
let t = session.track_mut(track).unwrap();
|
||||
t.mixer.input = Route::Bus(input);
|
||||
t.mixer.output = Route::None;
|
||||
t.mixer.pan = if format == ChannelFormat::Mono { vec![0.0] } else { vec![-1.0, 1.0] };
|
||||
maximizers(session, track, insert_count);
|
||||
track
|
||||
}
|
||||
|
||||
fn silent_aux(session: &mut Session, insert_count: usize) {
|
||||
let input = session.add_bus("Unrelated empty input", ChannelFormat::Mono);
|
||||
aux(session, input, ChannelFormat::Mono, insert_count);
|
||||
}
|
||||
|
||||
fn return_to_main(session: &mut Session, input: BusId) -> TrackId {
|
||||
let track = aux(session, input, ChannelFormat::Stereo, 0);
|
||||
session.track_mut(track).unwrap().mixer.output = Route::Main;
|
||||
track
|
||||
}
|
||||
|
||||
fn automation(session: &mut Session, track: TrackId, param: AutoParam, points: &[(i64, f32)]) {
|
||||
let mut lane = AutomationLane::new(param);
|
||||
for &(at, value) in points {
|
||||
lane.set_point(at, value);
|
||||
}
|
||||
session.track_mut(track).unwrap().automation.push(lane);
|
||||
}
|
||||
|
||||
fn send(session: &mut Session, sender: TrackId, capture: BusId, pre: bool, pan_start: i64, pan_end: i64, automated_pan: bool) {
|
||||
let mut send = SendSlot::new(Route::Bus(capture));
|
||||
send.level_db = 0.0;
|
||||
send.pre_fader = pre;
|
||||
send.pan = -1.0;
|
||||
session.track_mut(sender).unwrap().mixer.sends[0] = Some(send);
|
||||
automation(session, sender, AutoParam::SendMute(0), &[(-512, 0.0), (MUTE_AT, 1.0)]);
|
||||
if automated_pan {
|
||||
automation(session, sender, AutoParam::SendPan(0), &[(pan_start, -1.0), (pan_end, 1.0)]);
|
||||
}
|
||||
}
|
||||
|
||||
fn ordinary(pre: bool, own_inserts: usize, silent_inserts: usize, pdc: bool, clip_start: i64, pan_start: i64, pan_end: i64) -> Graph {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = pdc;
|
||||
let sender = source(&mut session, own_inserts, clip_start);
|
||||
if silent_inserts > 0 {
|
||||
silent_audio(&mut session, silent_inserts);
|
||||
}
|
||||
let capture = session.add_bus("Automation capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, pre, pan_start, pan_end, true);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
Graph { session, capture, receiver, clip_start, pan_start, pan_end }
|
||||
}
|
||||
|
||||
fn make_mix() -> MixEngine {
|
||||
let mut mix = MixEngine::new(48_000.0, 1024);
|
||||
mix.pan_law = PanLaw::Zero;
|
||||
mix
|
||||
}
|
||||
|
||||
fn capture_pcm(mix: &mut MixEngine, graph: &Graph, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
|
||||
let mut main = vec![Vec::new(), Vec::new()];
|
||||
let mut offset = 0;
|
||||
let mut block = 0;
|
||||
while offset < length {
|
||||
let n = sizes[block % sizes.len()].min(length - offset);
|
||||
let mut main_block = vec![vec![0.0; n]; 2];
|
||||
mix.render(&graph.session, start + offset as i64, n, &mut main_block);
|
||||
for (output, samples) in main.iter_mut().zip(main_block) {
|
||||
assert_eq!(samples.len(), n);
|
||||
output.extend(samples);
|
||||
}
|
||||
offset += n;
|
||||
block += 1;
|
||||
}
|
||||
main
|
||||
}
|
||||
|
||||
fn numeric_pan(at: i64, first: i64, last: i64) -> [f32; 2] {
|
||||
let pan = if at <= first {
|
||||
-1.0
|
||||
} else if at >= last {
|
||||
1.0
|
||||
} else {
|
||||
(-1.0 + 2.0 * (at - first) as f64 / (last - first) as f64) as f32
|
||||
};
|
||||
// Independent declared zero-depth pan law; no routing or automation helper is called.
|
||||
[(1.0 - pan).min(1.0), (1.0 + pan).min(1.0)]
|
||||
}
|
||||
|
||||
fn check_known(output: &[Vec<f32>], graph: &Graph, start: i64, delay: usize, length: usize) {
|
||||
assert_eq!(output.len(), 2);
|
||||
for (channel, samples) in output.iter().enumerate() {
|
||||
assert_eq!(samples.len(), length);
|
||||
for (offset, &sample) in samples.iter().enumerate() {
|
||||
let source_time = start + offset as i64 - delay as i64;
|
||||
let audible =
|
||||
offset >= delay && source_time >= graph.clip_start && source_time < graph.clip_start + SOURCE_FRAMES as i64 && source_time < MUTE_AT;
|
||||
let expected = if audible { AMPLITUDE * numeric_pan(source_time, graph.pan_start, graph.pan_end)[channel] } else { 0.0 };
|
||||
assert!(sample.is_finite());
|
||||
assert!(
|
||||
(sample - expected).abs() < 2e-7,
|
||||
"channel {channel}, emit {}, source {source_time}, delay {delay}: {sample} != {expected}",
|
||||
start + offset as i64
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(output.iter().flatten().any(|sample| sample.abs() > 0.02), "declared capture must be audible");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_silent_lookahead_keeps_audio_pre_post_pan_and_last_source_sample_299() {
|
||||
for pre in [false, true] {
|
||||
let graph = ordinary(pre, 0, 1, true, 0, 0, 600);
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 800, &[1, 7, 37, 100, 3, 64]);
|
||||
assert_eq!(mix.latency, LOOKAHEAD, "the unrelated real Maximizer actually contributes latency");
|
||||
check_known(&output, &graph, 0, LOOKAHEAD, 800);
|
||||
let last = output[0].iter().rposition(|sample| sample.abs() > 1e-6).unwrap();
|
||||
assert_eq!(last, MUTE_AT as usize - 1 + LOOKAHEAD);
|
||||
// Public render_bus uses its default -3 dB law. This separate mute-only fixture
|
||||
// holds the static send at its left endpoint, whose factors are exactly1/0.
|
||||
let mut offline_session = graph.session.clone();
|
||||
offline_session.tracks[0].automation.retain(|lane| lane.param != AutoParam::SendPan(0));
|
||||
let offline = render_bus(&offline_session, graph.capture, Range::new(0, 640), 37);
|
||||
assert_eq!(offline[0].len(), 640);
|
||||
assert_eq!(offline[0].iter().rposition(|sample| sample.abs() > 1e-6), Some(299));
|
||||
for (channel, samples) in offline.iter().enumerate() {
|
||||
for (at, &sample) in samples.iter().enumerate() {
|
||||
let expected = if at < MUTE_AT as usize && channel == 0 { AMPLITUDE } else { 0.0 };
|
||||
assert!((sample - expected).abs() < 2e-7);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aux_pre_tap_omits_post_alignment_while_both_taps_include_upstream_and_own_delay() {
|
||||
for pdc in [false, true] {
|
||||
for pre in [false, true] {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = pdc;
|
||||
let source = source(&mut session, 1, 0);
|
||||
let input = session.add_bus("Own upstream", ChannelFormat::Mono);
|
||||
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
|
||||
let sender = aux(&mut session, input, ChannelFormat::Mono, 1);
|
||||
silent_aux(&mut session, 2);
|
||||
let capture = session.add_bus("Aux capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, pre, 0, 600, true);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
|
||||
let tap_delay = if pdc && !pre { 3 * LOOKAHEAD } else { 2 * LOOKAHEAD };
|
||||
let observation_delay = if pdc { 2 * LOOKAHEAD } else { 0 };
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 900, &[100, 17, 1, 37, 64]);
|
||||
assert_eq!(mix.latency, if pdc { 3 * LOOKAHEAD } else { 0 });
|
||||
check_known(&output, &graph, 0, tap_delay + observation_delay, 900);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_aux_taps_accumulate_the_actual_upstream_path_instead_of_global_latency() {
|
||||
for pre in [false, true] {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = true;
|
||||
let source = source(&mut session, 1, 0);
|
||||
silent_audio(&mut session, 2);
|
||||
let first_bus = session.add_bus("Nested first", ChannelFormat::Mono);
|
||||
session.track_mut(source).unwrap().mixer.output = Route::Bus(first_bus);
|
||||
let first_aux = aux(&mut session, first_bus, ChannelFormat::Mono, 1);
|
||||
let second_bus = session.add_bus("Nested second", ChannelFormat::Mono);
|
||||
session.track_mut(first_aux).unwrap().mixer.output = Route::Bus(second_bus);
|
||||
let sender = aux(&mut session, second_bus, ChannelFormat::Mono, 1);
|
||||
silent_aux(&mut session, 2);
|
||||
let capture = session.add_bus("Nested capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, pre, 0, 600, true);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
|
||||
// Upstream audio2*71; first Aux own+alignment2*71; target pre adds1*71,
|
||||
// target post adds2*71. The scalar global mix delay is only4*71.
|
||||
let tap_delay = if pre { 5 * LOOKAHEAD } else { 6 * LOOKAHEAD };
|
||||
let observation_delay = 2 * LOOKAHEAD;
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 1100, &[37, 3, 100, 64, 1]);
|
||||
assert_eq!(mix.latency, 4 * LOOKAHEAD);
|
||||
check_known(&output, &graph, 0, tap_delay + observation_delay, 1100);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_extra_downstream_aux_and_master_delay_do_not_shift_the_send_clock() {
|
||||
for pre in [false, true] {
|
||||
let mut graph = ordinary(pre, 0, 1, true, 0, 0, 600);
|
||||
let source = graph.session.tracks[0].id;
|
||||
graph.session.track_mut(source).unwrap().mixer.output = Route::Main;
|
||||
maximizers(&mut graph.session, graph.receiver, 1);
|
||||
silent_aux(&mut graph.session, 2);
|
||||
let master = graph.session.add_track(TrackKind::Master, ChannelFormat::Stereo, None);
|
||||
maximizers(&mut graph.session, master, 1);
|
||||
let mut mix = make_mix();
|
||||
let main = capture_pcm(&mut mix, &graph, 0, 900, &[100, 37, 1, 64]);
|
||||
assert_eq!(mix.latency, 4 * LOOKAHEAD);
|
||||
assert!(main.iter().all(|channel| channel[..4 * LOOKAHEAD].iter().all(|sample| *sample == 0.0)));
|
||||
assert!(main[0][4 * LOOKAHEAD] > 0.4, "main really traverses the excluded output/Aux/Master delays");
|
||||
for (channel, samples) in main.iter().enumerate() {
|
||||
for (at, &sample) in samples.iter().enumerate() {
|
||||
let source_time = at as i64 - (4 * LOOKAHEAD) as i64;
|
||||
let expected = if source_time < 0 {
|
||||
0.0
|
||||
} else {
|
||||
let sent = if source_time < MUTE_AT { AMPLITUDE * numeric_pan(source_time, 0, 600)[channel] } else { 0.0 };
|
||||
AMPLITUDE + sent
|
||||
};
|
||||
assert!((sample - expected).abs() < 2e-7, "exclusion channel {channel}, emit {at}: {sample} != {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_aux_pre_and_direct_bus_ages_keep_the_documented_raw_clock_fallback() {
|
||||
for target_pre in [false, true] {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = true;
|
||||
let source = source(&mut session, 1, 0);
|
||||
let input = session.add_bus("Mixed upstream", ChannelFormat::Mono);
|
||||
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
|
||||
let contributor = aux(&mut session, input, ChannelFormat::Mono, 1);
|
||||
silent_aux(&mut session, 2);
|
||||
let mixed_bus = session.add_bus("Unequal actual ages", ChannelFormat::Mono);
|
||||
session.track_mut(contributor).unwrap().mixer.output = Route::Bus(mixed_bus);
|
||||
let mut pre_send = SendSlot::new(Route::Bus(mixed_bus));
|
||||
pre_send.level_db = 0.0;
|
||||
pre_send.pre_fader = true;
|
||||
session.track_mut(contributor).unwrap().mixer.sends[0] = Some(pre_send);
|
||||
let sender = aux(&mut session, mixed_bus, ChannelFormat::Mono, 0);
|
||||
let capture = session.add_bus("Mixed capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, target_pre, 0, 600, false);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 900, &[37, 100, 1, 3, 64]);
|
||||
let extra = if target_pre { 0 } else { 2 * LOOKAHEAD };
|
||||
let observation_delay = 2 * LOOKAHEAD;
|
||||
let delays = [2 * LOOKAHEAD + extra + observation_delay, 3 * LOOKAHEAD + extra + observation_delay];
|
||||
for (at, (&left, &right)) in output[0].iter().zip(&output[1]).enumerate() {
|
||||
let contributions = delays.iter().filter(|&&delay| at >= delay).count();
|
||||
let expected = if at < MUTE_AT as usize + observation_delay { AMPLITUDE * contributions as f32 } else { 0.0 };
|
||||
assert!((left - expected).abs() < 2e-7, "mixed tap pre={target_pre} emit{at}: {left} != {expected}");
|
||||
assert_eq!(right, 0.0);
|
||||
}
|
||||
assert!(output[0].iter().any(|sample| *sample > 0.02));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_positions_and_reset_seek_use_the_delayed_source_clock_with_pdc_off() {
|
||||
let graph = ordinary(false, 1, 0, false, -512, -300, 300);
|
||||
let mut mix = make_mix();
|
||||
let negative = capture_pcm(&mut mix, &graph, -128, 256, &[1, 37, 3, 64, 17]);
|
||||
assert_eq!(mix.latency, 0, "PDC is off while the insert still physically delays its source");
|
||||
check_known(&negative, &graph, -128, LOOKAHEAD, 256);
|
||||
mix.reset();
|
||||
let seek = capture_pcm(&mut mix, &graph, 240, 400, &[100, 1, 37, 3]);
|
||||
check_known(&seek, &graph, 240, LOOKAHEAD, 400);
|
||||
assert_eq!(seek[1].iter().rposition(|sample| sample.abs() > 1e-6), Some(130));
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin,
|
||||
PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId,
|
||||
itu_stereo_fold, main_channels, midi, record, sync_channel,
|
||||
Arc, AtomicBool, AtomicU32, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering,
|
||||
OutputTrouble, Plugin, PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared,
|
||||
SyncSender, TrackId, devices, itu_stereo_fold, main_channels, midi, record, sync_channel,
|
||||
};
|
||||
use soundcraft_mix::{LiveMidi, midi_port_bit, midi_thru};
|
||||
use soundcraft_model::TrackKind;
|
||||
@@ -17,6 +17,29 @@ pub(crate) struct Fault {
|
||||
pub(crate) beats: std::sync::atomic::AtomicU64,
|
||||
/// The UI has been told.
|
||||
reported: AtomicBool,
|
||||
/// Underruns the device reported, callbacks that overran their buffer period, and the worst
|
||||
/// callback's share of its buffer time (‰), since the stream opened or the last
|
||||
/// [`Player::take_health`], and the device callbacks in that time.
|
||||
xruns: std::sync::atomic::AtomicU64,
|
||||
late_callbacks: std::sync::atomic::AtomicU64,
|
||||
worst_load: AtomicU32,
|
||||
callbacks: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
/// How the realtime audio path keeps up, for the UI and for stress tests: since the output
|
||||
/// opened, or since the last [`Player::take_health`].
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
|
||||
pub struct AudioHealth {
|
||||
/// Device callbacks (none for the silent clock).
|
||||
pub callbacks: u64,
|
||||
/// Underruns (dropouts) the device reported.
|
||||
pub xruns: u64,
|
||||
/// Callbacks that overran their buffer period. Not every one is an audible gap, and the
|
||||
/// device may report the same overrun as an xrun too (CoreAudio does).
|
||||
pub late_callbacks: u64,
|
||||
/// The slowest callback's render time as a share of its buffer period, to 0.001 (1.0 = it
|
||||
/// overran).
|
||||
pub worst_load: f64,
|
||||
}
|
||||
|
||||
impl Fault {
|
||||
@@ -33,6 +56,50 @@ impl Fault {
|
||||
};
|
||||
(!self.reported.swap(true, Ordering::Relaxed)).then_some(trouble)
|
||||
}
|
||||
|
||||
/// A device callback rendered `frames` at `rate` in `took`. Lock-free and allocation-free.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn note_callback(&self, took: std::time::Duration, frames: usize, rate: f64) {
|
||||
self.callbacks.fetch_add(1, Ordering::Relaxed);
|
||||
if frames == 0 || rate <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let load = took.as_secs_f64() * rate / frames as f64;
|
||||
if load > 1.0 {
|
||||
self.late_callbacks.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
self.worst_load.fetch_max((load * 1000.0).min(f64::from(u32::MAX)) as u32, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The stream reported an error (on the audio thread or another). A lost stream is recorded
|
||||
/// as gone; a transient xrun is counted and the stream keeps playing.
|
||||
pub(crate) fn note_stream_error(&self, e: &cpal::Error) {
|
||||
if devices::stream_lost(e) {
|
||||
self.gone.store(true, Ordering::Relaxed);
|
||||
} else if e.kind() == cpal::ErrorKind::Xrun {
|
||||
self.xruns.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn health(&self) -> AudioHealth {
|
||||
AudioHealth {
|
||||
callbacks: self.callbacks.load(Ordering::Relaxed),
|
||||
xruns: self.xruns.load(Ordering::Relaxed),
|
||||
late_callbacks: self.late_callbacks.load(Ordering::Relaxed),
|
||||
worst_load: f64::from(self.worst_load.load(Ordering::Relaxed)) / 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The health so far, counting afresh from here: each counter is swapped for zero, so an
|
||||
/// event the callback records meanwhile lands in this reading or the next, never in neither.
|
||||
pub(crate) fn take_health(&self) -> AudioHealth {
|
||||
AudioHealth {
|
||||
callbacks: self.callbacks.swap(0, Ordering::Relaxed),
|
||||
xruns: self.xruns.swap(0, Ordering::Relaxed),
|
||||
late_callbacks: self.late_callbacks.swap(0, Ordering::Relaxed),
|
||||
worst_load: f64::from(self.worst_load.swap(0, Ordering::Relaxed)) / 1000.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a playing output may go without a block before it counts as stalled.
|
||||
|
||||
@@ -48,8 +48,9 @@ const BLOCK: usize = 512;
|
||||
/// Room for replaced snapshots on their way back; `update_session` empties it before each send.
|
||||
const OLD_SESSIONS: usize = 16;
|
||||
|
||||
/// The realtime audio thread marker lives in the mix engine, which carries it into the strips it
|
||||
/// renders on worker threads; the cpal callbacks here set it.
|
||||
pub use callback::AudioHealth;
|
||||
/// The realtime audio thread marker lives in the mix engine, which renders every strip on the
|
||||
/// marked thread itself; the cpal callbacks here set it.
|
||||
pub use soundcraft_mix::{mark_audio_thread, on_audio_thread};
|
||||
|
||||
mod callback;
|
||||
@@ -221,6 +222,19 @@ impl Player {
|
||||
self.fault.trouble(stalled)
|
||||
}
|
||||
|
||||
/// How the realtime path has kept up since the output opened or the last
|
||||
/// [`Player::take_health`]: callbacks, device-reported underruns, late callbacks and the
|
||||
/// worst callback load.
|
||||
pub fn health(&self) -> AudioHealth {
|
||||
self.fault.health()
|
||||
}
|
||||
|
||||
/// [`Player::health`] so far, then count afresh (a stress run measures from a take). No
|
||||
/// event is lost between the reading and the restart.
|
||||
pub fn take_health(&self) -> AudioHealth {
|
||||
self.fault.take_health()
|
||||
}
|
||||
|
||||
fn side(&self) -> std::sync::MutexGuard<'_, Side> {
|
||||
self.side.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::callback::{AudioState, Fault, guarded_block};
|
||||
use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
|
||||
use super::{Arc, AudioConfig, Cmd, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
|
||||
|
||||
/// Start a freshly built output stream. `false` when the device refuses to start it, so the caller
|
||||
/// treats it like a stream that failed to build and tries the next configuration.
|
||||
@@ -63,10 +63,14 @@ where
|
||||
let mut scratch = vec![0.0f32; 8192 * frame];
|
||||
let chunk = scratch.len();
|
||||
let (failed, guard, gone) = (Arc::clone(fault), Arc::clone(shared), Arc::clone(fault));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let rate = f64::from(config.sample_rate);
|
||||
device.build_output_stream(
|
||||
config,
|
||||
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
|
||||
mark_audio_thread();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let started = std::time::Instant::now();
|
||||
for out in data.chunks_mut(chunk) {
|
||||
let Some(s) = scratch.get_mut(..out.len()) else { return };
|
||||
guarded_block(&failed, &guard, s, |d| state.fill(d, channels));
|
||||
@@ -74,6 +78,8 @@ where
|
||||
*o = T::from_sample(*x);
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
failed.note_callback(started.elapsed(), data.len() / frame, rate);
|
||||
},
|
||||
// cpal may call this on the audio thread (on ALSA in a loop while the device stays
|
||||
// broken): marked, so the logger hands the record off instead of writing it.
|
||||
@@ -83,9 +89,7 @@ where
|
||||
// stream that must be rebuilt (`StreamInvalidated`), stops playback until the user
|
||||
// reconnects; a rerouted default device (`DeviceChanged`) keeps playing on the new
|
||||
// route, and an xrun is transient, so neither counts as losing the stream.
|
||||
if devices::stream_lost(&e) {
|
||||
gone.gone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
gone.note_stream_error(&e);
|
||||
log::warn!("audio stream error: {e}");
|
||||
},
|
||||
None,
|
||||
|
||||
@@ -289,6 +289,28 @@ fn a_lost_or_stalled_device_is_reported_once() {
|
||||
assert_eq!((fault.trouble(false), fault.trouble(true)), (Some(OutputTrouble::Gone), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underruns_and_late_callbacks_are_counted_until_taken() {
|
||||
use std::time::Duration;
|
||||
let f = Fault::default();
|
||||
let error = |kind| cpal::Error::with_message(kind, "test");
|
||||
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
|
||||
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
|
||||
// 512 frames at 48 kHz last 10.67 ms.
|
||||
f.note_callback(Duration::from_millis(4), 512, 48_000.0);
|
||||
f.note_callback(Duration::from_millis(16), 512, 48_000.0);
|
||||
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
|
||||
let h = f.health();
|
||||
assert_eq!(h, AudioHealth { callbacks: 3, xruns: 2, late_callbacks: 1, worst_load: 1.5 });
|
||||
assert!(!f.gone.load(Ordering::Relaxed), "an underrun is not a lost device");
|
||||
assert_eq!(f.take_health(), h);
|
||||
assert_eq!(f.health(), AudioHealth::default());
|
||||
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
|
||||
assert_eq!(f.health().callbacks, 1);
|
||||
f.note_stream_error(&error(cpal::ErrorKind::DeviceNotAvailable));
|
||||
assert!(f.gone.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_state_plays_and_stops_at_end() {
|
||||
let s = Arc::new(soundcraft_model::Session::default());
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -154,6 +154,8 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"new" => "novo",
|
||||
"New Bus" => "Novo bus",
|
||||
"new bus..." => "novo bus...",
|
||||
"new mono bus" => "novo bus mono",
|
||||
"new stereo bus" => "novo bus estéreo",
|
||||
"New Configuration…" => "Nova configuração…",
|
||||
"New Group…" => "Novo grupo…",
|
||||
"New..." => "Novo...",
|
||||
@@ -1782,6 +1784,9 @@ fn menu_translate(source: &str) -> Option<&'static str> {
|
||||
"Enable Track Notes Dialog" => "Ativar o diálogo de notas da pista",
|
||||
"English" => "Inglês",
|
||||
"Portuguese (Brazil)" => "Português (Brasil)",
|
||||
"French" => "Francês",
|
||||
"Spanish" => "Espanhol",
|
||||
"Simplified Chinese" => "Chinês simplificado",
|
||||
"key:Space" => "Espaço",
|
||||
"key:Up" => "Cima",
|
||||
"key:Down" => "Baixo",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -488,6 +488,19 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
|
||||
"session.inspect" | "document.inspect" => {
|
||||
ok(soundcraft_engine::inspect::session(&app.engine, p.get("detail").and_then(Value::as_str) == Some("full")))
|
||||
}
|
||||
"audio.health" => match &app.player {
|
||||
Some(player) => {
|
||||
let h = if p.get("reset").and_then(Value::as_bool) == Some(true) { player.take_health() } else { player.health() };
|
||||
ok(json!({
|
||||
"device": player.device_name,
|
||||
"silent": player.silent,
|
||||
"sample_rate": player.device_rate,
|
||||
"buffer_frames": player.device_buffer,
|
||||
"health": h,
|
||||
}))
|
||||
}
|
||||
None => err("no audio output"),
|
||||
},
|
||||
"ui.inspect" => {
|
||||
let mut v = app.inspect(ctx);
|
||||
v["edit_layout"] = json!(app.edit_layout);
|
||||
|
||||
+196
-20
@@ -1,10 +1,13 @@
|
||||
//! Fonts: egui's bundled defaults, plus the operating system's own UI fonts loaded at runtime when
|
||||
//! present (never redistributed). A "bold" family is always defined so the UI can use it.
|
||||
//! present (never redistributed). The web build, which reaches no operating-system fonts, bundles a
|
||||
//! small Open Font License subset of Noto Sans SC instead (see `assets/fonts/` and
|
||||
//! `ATTRIBUTION.md`). A "bold" family is always defined so the UI can use it.
|
||||
|
||||
use egui::{FontData, FontDefinitions, FontFamily};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// (path, ttc index) candidates for regular and bold UI text, by platform.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const REGULAR: &[(&str, u32)] = &[
|
||||
("/System/Library/Fonts/HelveticaNeue.ttc", 0),
|
||||
("/System/Library/Fonts/Helvetica.ttc", 0),
|
||||
@@ -17,6 +20,7 @@ const REGULAR: &[(&str, u32)] = &[
|
||||
("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", 0),
|
||||
("/usr/share/fonts/liberation-sans-fonts/LiberationSans-Regular.ttf", 0),
|
||||
];
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const BOLD: &[(&str, u32)] = &[
|
||||
("/System/Library/Fonts/HelveticaNeue.ttc", 1),
|
||||
("/System/Library/Fonts/Helvetica.ttc", 1),
|
||||
@@ -31,6 +35,7 @@ const BOLD: &[(&str, u32)] = &[
|
||||
];
|
||||
/// Hangul fallback, appended after every family so Korean session, track and clip names draw
|
||||
/// whatever the interface language. The Noto Sans CJK collection's face 1 is its Korean face.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HANGUL: &[(&str, u32)] = &[
|
||||
("/System/Library/Fonts/AppleSDGothicNeo.ttc", 0),
|
||||
("/System/Library/Fonts/Supplemental/AppleGothic.ttf", 0),
|
||||
@@ -42,9 +47,40 @@ const HANGUL: &[(&str, u32)] = &[
|
||||
("/usr/share/fonts/truetype/nanum/NanumGothic.ttf", 0),
|
||||
("/usr/share/fonts/naver-nanum/NanumGothic.ttf", 0),
|
||||
];
|
||||
/// Han fallback (Simplified Chinese first), placed before [`HANGUL`] for every interface language
|
||||
/// except Korean, so a Chinese interface and Chinese session, track and clip names draw in Chinese
|
||||
/// shapes instead of boxes. On Linux the first resolvable CJK face is often Noto Sans CJK's Korean
|
||||
/// face, whose Han glyphs are Korean-styled; the first face with a glyph wins, so Han must come
|
||||
/// first. Face 2 of the Noto Sans CJK collection is its Simplified Chinese face (face 0 is
|
||||
/// Japanese, 1 Korean), and `Source Han Sans SC` / `Noto Sans CJK SC` ship as single-face files.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HAN: &[(&str, u32)] = &[
|
||||
("/System/Library/Fonts/PingFang.ttc", 0),
|
||||
("/System/Library/Fonts/Supplemental/Songti.ttc", 0),
|
||||
("/System/Library/Fonts/STHeiti Light.ttc", 0),
|
||||
("C:\\Windows\\Fonts\\msyh.ttc", 0),
|
||||
("C:\\Windows\\Fonts\\msyh.ttf", 0),
|
||||
("C:\\Windows\\Fonts\\simhei.ttf", 0),
|
||||
("/usr/share/fonts/opentype/source-han-cjk/SourceHanSansSC-Regular.otf", 0),
|
||||
("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", 0),
|
||||
("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0),
|
||||
("/usr/share/fonts/wqy-microhei/wqy-microhei.ttc", 0),
|
||||
("/usr/share/fonts/truetype/arphic/uming.ttc", 0),
|
||||
];
|
||||
/// Font files larger than this are skipped: egui keeps the whole file in memory.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FONT_BYTES: u64 = 64 << 20;
|
||||
/// The Han-capable TrueType font bundled for the web build only: egui's default fonts carry no Han
|
||||
/// glyphs and a browser cannot reach the operating system's fonts, so a Chinese interface would
|
||||
/// draw boxes. It is a Noto Sans SC (OFL-1.1) subset at weight 400 covering a superset of the UI
|
||||
/// glyph set; regenerate it with `docs/i18n/tools/subset_web_font.py`. See `assets/fonts/OFL.txt`
|
||||
/// and `ATTRIBUTION.md`. Native builds never embed it: the include is compiled out of them
|
||||
/// (`test` keeps it available to the glyph-coverage tests).
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
const BUNDLED_HAN: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/NotoSansSC-SoundCraftSubset.ttf"));
|
||||
|
||||
/// Asks fontconfig for the desktop's font matching `pattern`. Only TrueType/OpenType results are
|
||||
/// used: egui cannot read Type 1 or bitmap fonts, which `fc-match` may return on minimal systems.
|
||||
@@ -103,34 +139,79 @@ fn load(cands: &[(&str, u32)], pattern: &str, lang: Option<&str>, system_fonts:
|
||||
None
|
||||
}
|
||||
|
||||
/// The web build has no operating-system fonts: the bundled subset is the CJK fallback.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn load(_: &[(&str, u32)], _: &str, _: Option<&str>, _: bool) -> Option<FontData> {
|
||||
None
|
||||
fn bundled_han() -> FontData {
|
||||
FontData::from_static(BUNDLED_HAN)
|
||||
}
|
||||
|
||||
/// The font set: the bundled faces, plus the system ones when `system_fonts` is true.
|
||||
/// Appends `name` as the lowest-priority fallback of every family. Only appends, so the order the
|
||||
/// faces are added in is the order glyphs are looked up in.
|
||||
fn add_fallback(fonts: &mut FontDefinitions, name: &'static str, font: FontData) {
|
||||
fonts.font_data.insert(name.into(), Arc::new(font));
|
||||
for family in fonts.families.values_mut() {
|
||||
family.push(name.into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Should a Chinese-shaped Han face claim the Han glyphs before the Korean face? The first face
|
||||
/// with a glyph wins, so a Chinese interface must come first (on Linux fontconfig often resolves
|
||||
/// Noto Sans CJK's Korean face, whose Han glyphs are Korean-styled). Every interface language
|
||||
/// except Korean orders Han first; Korean reverses the two, so Hangul and Hanja draw from the
|
||||
/// Korean face. A future `zh-Hant` (Traditional Chinese) or `ja` (Japanese) is expected to keep
|
||||
/// Han first as well; only a language-suitable Han face would change (the [`HAN`] list is
|
||||
/// Simplified-first today).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn han_before_hangul(language: &str) -> bool {
|
||||
language.split(['-', '_']).next() != Some("ko")
|
||||
}
|
||||
|
||||
/// The font set: egui's bundled defaults, the operating system's faces where present and when
|
||||
/// `system_fonts` is true, and (web only) the bundled Han face as the last fallback of every
|
||||
/// family. The interface language decides the order of the two CJK fallbacks.
|
||||
pub fn definitions(system_fonts: bool) -> FontDefinitions {
|
||||
let mut fonts = FontDefinitions::default();
|
||||
let base: Vec<String> = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let mut bold_family = base.clone();
|
||||
if let Some(reg) = load(REGULAR, "sans-serif", None, system_fonts) {
|
||||
fonts.font_data.insert("system-regular".into(), Arc::new(reg));
|
||||
if let Some(f) = fonts.families.get_mut(&FontFamily::Proportional) {
|
||||
f.insert(0, "system-regular".into());
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if let Some(reg) = load(REGULAR, "sans-serif", None, system_fonts) {
|
||||
fonts.font_data.insert("system-regular".into(), Arc::new(reg));
|
||||
if let Some(f) = fonts.families.get_mut(&FontFamily::Proportional) {
|
||||
f.insert(0, "system-regular".into());
|
||||
}
|
||||
}
|
||||
if let Some(b) = load(BOLD, "sans-serif:style=Bold", None, system_fonts) {
|
||||
fonts.font_data.insert("system-bold".into(), Arc::new(b));
|
||||
bold_family.insert(0, "system-bold".into());
|
||||
} else if fonts.font_data.contains_key("system-regular") {
|
||||
bold_family.insert(0, "system-regular".into());
|
||||
}
|
||||
fonts.families.insert(FontFamily::Name("bold".into()), bold_family);
|
||||
// The first face with a glyph wins, so the interface language decides whether a Han or a
|
||||
// Korean face claims the Han glyphs a Chinese interface draws (see `han_before_hangul`).
|
||||
let language = crate::localization::current_language().id();
|
||||
let hangul = load(HANGUL, "sans-serif:lang=ko", Some("ko"), system_fonts);
|
||||
let han = load(HAN, "sans-serif:lang=zh-cn", Some("zh-cn"), system_fonts);
|
||||
let ordered = if han_before_hangul(language) {
|
||||
[("system-han", han), ("system-hangul", hangul)]
|
||||
} else {
|
||||
[("system-hangul", hangul), ("system-han", han)]
|
||||
};
|
||||
for (name, font) in ordered {
|
||||
if let Some(font) = font {
|
||||
add_fallback(&mut fonts, name, font);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(b) = load(BOLD, "sans-serif:style=Bold", None, system_fonts) {
|
||||
fonts.font_data.insert("system-bold".into(), Arc::new(b));
|
||||
bold_family.insert(0, "system-bold".into());
|
||||
} else if fonts.font_data.contains_key("system-regular") {
|
||||
bold_family.insert(0, "system-regular".into());
|
||||
}
|
||||
fonts.families.insert(FontFamily::Name("bold".into()), bold_family);
|
||||
if let Some(h) = load(HANGUL, "sans-serif:lang=ko", Some("ko"), system_fonts) {
|
||||
fonts.font_data.insert("system-hangul".into(), Arc::new(h));
|
||||
for family in fonts.families.values_mut() {
|
||||
family.push("system-hangul".into());
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// No system fonts in the browser: the bundled Han face keeps a Chinese interface, and
|
||||
// Chinese session, track and clip names, readable instead of drawing boxes.
|
||||
let _ = system_fonts;
|
||||
fonts.families.insert(FontFamily::Name("bold".into()), base);
|
||||
add_fallback(&mut fonts, "web-han", bundled_han());
|
||||
}
|
||||
fonts
|
||||
}
|
||||
@@ -226,4 +307,99 @@ mod tests {
|
||||
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "가한국어세션")), "{family:?} has no Hangul");
|
||||
}
|
||||
}
|
||||
|
||||
/// The interface language orders the two CJK fallbacks: a Chinese interface draws Han glyphs
|
||||
/// from the Han face first, Korean draws them from the Korean face.
|
||||
#[test]
|
||||
fn cjk_fallback_order_follows_the_interface_language() {
|
||||
assert!(han_before_hangul("zh-Hans"));
|
||||
assert!(han_before_hangul("en"));
|
||||
// A future Traditional Chinese or Japanese catalog keeps Han first; only the Han face
|
||||
// itself would become Traditional Chinese or Japanese.
|
||||
assert!(han_before_hangul("zh-Hant"));
|
||||
assert!(han_before_hangul("ja"));
|
||||
assert!(!han_before_hangul("ko"));
|
||||
assert!(!han_before_hangul("ko-kr"));
|
||||
}
|
||||
|
||||
/// Chinese names draw in every family, not as boxes; skipped when the system has no Han font.
|
||||
#[test]
|
||||
fn every_family_draws_han_with_a_system_han_font() {
|
||||
let defs = definitions(true);
|
||||
if !defs.font_data.contains_key("system-han") {
|
||||
eprintln!("skipping: no Han system font");
|
||||
return;
|
||||
}
|
||||
let families: Vec<FontFamily> = defs.families.keys().cloned().collect();
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(defs);
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
output.textures_delta.clear();
|
||||
for family in families {
|
||||
let font = egui::FontId::new(13.0, family.clone());
|
||||
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "轨道片段混音")), "{family:?} has no Han");
|
||||
}
|
||||
}
|
||||
|
||||
/// Under a Chinese interface every family that resolved both faces puts Han before Hangul, so
|
||||
/// Chinese text never draws in Korean-styled shapes.
|
||||
#[test]
|
||||
fn chinese_interface_puts_han_before_hangul_in_every_family() {
|
||||
let _language = crate::localization::enter(crate::localization::Language::SimplifiedChinese);
|
||||
let defs = definitions(true);
|
||||
let mut compared = 0;
|
||||
for (family, family_fonts) in &defs.families {
|
||||
let han = family_fonts.iter().position(|font| font == "system-han");
|
||||
let hangul = family_fonts.iter().position(|font| font == "system-hangul");
|
||||
if let (Some(han), Some(hangul)) = (han, hangul) {
|
||||
assert!(han < hangul, "{family:?} puts Hangul before Han: {family_fonts:?}");
|
||||
compared += 1;
|
||||
}
|
||||
}
|
||||
if compared == 0 {
|
||||
eprintln!("skipping: no system Han and Hangul fonts resolved");
|
||||
}
|
||||
}
|
||||
|
||||
/// The web fallback chain (egui defaults + the bundled face) draws the entire zh-Hans catalog in
|
||||
/// every family: the property that keeps the browser build free of boxes.
|
||||
#[test]
|
||||
fn bundled_web_font_draws_the_zh_hans_catalog_in_every_family() {
|
||||
let Some(catalog) = zh_hans_catalog() else { return };
|
||||
let mut defs = definitions(false);
|
||||
add_fallback(&mut defs, "web-han", FontData::from_static(BUNDLED_HAN));
|
||||
let mut sample: Vec<char> = catalog.chars().filter(|c| !['\t', '\r', '\n'].contains(c)).collect();
|
||||
sample.sort_unstable();
|
||||
sample.dedup();
|
||||
let sample: String = sample.into_iter().collect();
|
||||
let families: Vec<FontFamily> = defs.families.keys().cloned().collect();
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(defs);
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
output.textures_delta.clear();
|
||||
for family in families {
|
||||
let font = egui::FontId::new(13.0, family.clone());
|
||||
let missing: Vec<char> = sample.chars().filter(|c| !ctx.fonts_mut(|fonts| fonts.has_glyphs(&font, &c.to_string()))).collect();
|
||||
assert!(missing.is_empty(), "{family:?} cannot draw {missing:?} of the zh-Hans catalog even with the bundled web font");
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset must not silently grow into a full CJK font, which would bloat the web download.
|
||||
#[test]
|
||||
fn bundled_web_font_stays_within_its_size_budget() {
|
||||
const BUDGET: usize = 2 << 20; // 2 MiB
|
||||
assert!(BUNDLED_HAN.len() <= BUDGET, "the bundled web font is {} bytes; its budget is {BUDGET}", BUNDLED_HAN.len());
|
||||
}
|
||||
|
||||
/// The source of the zh-Hans catalog, or `None` (skip) when it is not checked out.
|
||||
fn zh_hans_catalog() -> Option<String> {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/i18n/zh-hans.tsv");
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(catalog) => Some(catalog),
|
||||
Err(err) => {
|
||||
eprintln!("skipping: cannot read {path}: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
SoundCraft UI translations — license and provenance
|
||||
====================================================
|
||||
|
||||
`crates/ui-egui/src/i18n/zh-hans.tsv` holds SoundCraft's own Simplified Chinese translation of the
|
||||
English source strings in the code. `crates/ui-egui/locales/zh-Hans/mod.rs` is generated from it by
|
||||
`docs/i18n/tools/gen_zh_hans_locale.py`; edit the TSV, never the module.
|
||||
|
||||
License: MIT OR Apache-2.0, the same terms as the SoundCraft code (see LICENSE-MIT and
|
||||
LICENSE-APACHE in the repository root). The translations are bundled only in the SoundCraft UI; the
|
||||
English source strings in the code remain the canonical text.
|
||||
|
||||
Provenance: the rows are original wording written for SoundCraft. No translated string, glossary or
|
||||
translation memory from another product was copied. Wording decisions and their reasoning are
|
||||
recorded in `docs/i18n/glossary.md`, so a reviewer can challenge a term without leaving the
|
||||
repository.
|
||||
|
||||
Review status: AI-authored, not yet read by a native-speaking audio engineer.
|
||||
|
||||
Rules when editing: keep the format documented at the top of the TSV, keep every `{name}` and `{}`
|
||||
placeholder (and its format spec) exactly, keep a trailing `…` in menu items, and run
|
||||
`python3 docs/i18n/tools/gen_zh_hans_locale.py` followed by
|
||||
`cargo test -p soundcraft-ui-egui --lib`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,13 @@
|
||||
//! Language selection and source-language fallback for UI strings.
|
||||
|
||||
#[path = "../locales/es/mod.rs"]
|
||||
mod es;
|
||||
#[path = "../locales/fr/mod.rs"]
|
||||
mod fr;
|
||||
#[path = "../locales/pt-BR/mod.rs"]
|
||||
mod pt_br;
|
||||
#[path = "../locales/zh-Hans/mod.rs"]
|
||||
mod zh_hans;
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
@@ -17,17 +23,26 @@ pub enum Language {
|
||||
English,
|
||||
#[serde(rename = "pt-BR")]
|
||||
PortugueseBrazil,
|
||||
#[serde(rename = "fr")]
|
||||
French,
|
||||
#[serde(rename = "es")]
|
||||
Spanish,
|
||||
#[serde(rename = "zh-Hans")]
|
||||
SimplifiedChinese,
|
||||
}
|
||||
|
||||
impl Language {
|
||||
/// All supported languages, in the order they are shown in the language menu.
|
||||
pub const ALL: [Self; 2] = [Self::English, Self::PortugueseBrazil];
|
||||
pub const ALL: [Self; 5] = [Self::English, Self::PortugueseBrazil, Self::French, Self::Spanish, Self::SimplifiedChinese];
|
||||
|
||||
/// Stable language tag used in preferences and control commands.
|
||||
pub const fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::English => "en",
|
||||
Self::PortugueseBrazil => "pt-BR",
|
||||
Self::French => "fr",
|
||||
Self::Spanish => "es",
|
||||
Self::SimplifiedChinese => "zh-Hans",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +51,9 @@ impl Language {
|
||||
match self {
|
||||
Self::English => "English",
|
||||
Self::PortugueseBrazil => "Portuguese (Brazil)",
|
||||
Self::French => "French",
|
||||
Self::Spanish => "Spanish",
|
||||
Self::SimplifiedChinese => "Simplified Chinese",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +65,8 @@ impl Language {
|
||||
pub fn localize_decimal(self, number: &str) -> String {
|
||||
match self {
|
||||
Self::English => number.to_owned(),
|
||||
Self::PortugueseBrazil => number.replace('.', ","),
|
||||
Self::PortugueseBrazil | Self::French | Self::Spanish => number.replace('.', ","),
|
||||
Self::SimplifiedChinese => number.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +75,9 @@ impl Language {
|
||||
match self {
|
||||
Self::English => source,
|
||||
Self::PortugueseBrazil => pt_br::translate(source).unwrap_or(source),
|
||||
Self::French => fr::translate(source).unwrap_or(source),
|
||||
Self::Spanish => es::translate(source).unwrap_or(source),
|
||||
Self::SimplifiedChinese => zh_hans::translate(source).unwrap_or(source),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,6 +111,9 @@ fn error_text_in(language: Language, message: &str, depth: usize) -> String {
|
||||
let templates: &[(&str, &str)] = match language {
|
||||
Language::English => &[],
|
||||
Language::PortugueseBrazil => pt_br::ERROR_TEMPLATES,
|
||||
Language::French => fr::ERROR_TEMPLATES,
|
||||
Language::Spanish => es::ERROR_TEMPLATES,
|
||||
Language::SimplifiedChinese => zh_hans::ERROR_TEMPLATES,
|
||||
};
|
||||
let mut best: Option<(usize, &str, Vec<(String, String)>)> = None;
|
||||
for (template, translation) in templates {
|
||||
@@ -354,14 +379,40 @@ mod tests {
|
||||
assert_eq!(decoded, language);
|
||||
}
|
||||
assert_eq!(Language::parse(" PT-br "), Some(Language::PortugueseBrazil));
|
||||
assert_eq!(Language::parse("fr"), None);
|
||||
assert_eq!(Language::parse(" FR "), Some(Language::French));
|
||||
assert_eq!(Language::parse("de"), None);
|
||||
assert_eq!(Language::parse(" ZH-hans "), Some(Language::SimplifiedChinese));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_translations_fall_back_to_the_english_source() {
|
||||
assert_ne!(Language::PortugueseBrazil.text("Appearance"), "Appearance");
|
||||
assert_eq!(Language::PortugueseBrazil.text("A source string with no catalog entry"), "A source string with no catalog entry");
|
||||
assert_ne!(Language::SimplifiedChinese.text("Appearance"), "Appearance");
|
||||
assert_eq!(Language::English.text("Appearance"), "Appearance");
|
||||
for language in [Language::French, Language::Spanish] {
|
||||
assert_ne!(language.text("Appearance"), "Appearance", "{language:?}");
|
||||
assert_eq!(language.text("A source string with no catalog entry"), "A source string with no catalog entry");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplified_chinese_translates_the_language_menu() {
|
||||
// `Language::native_name` is English source text; the menu draws it through the catalog, so
|
||||
// a Chinese interface must name every language it offers in Chinese.
|
||||
for language in Language::ALL {
|
||||
assert_ne!(Language::SimplifiedChinese.text(language.native_name()), language.native_name(), "{language:?}");
|
||||
}
|
||||
assert_eq!(Language::SimplifiedChinese.text("Simplified Chinese"), "简体中文");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplified_chinese_catalog_covers_every_menu_label() {
|
||||
for path in include_str!("../../engine/catalog/menus.txt").lines() {
|
||||
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
|
||||
assert!(super::zh_hans::translate(label).is_some(), "missing zh-Hans menu label: {label}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,6 +439,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanish_catalog_covers_every_menu_label() {
|
||||
for path in include_str!("../../engine/catalog/menus.txt").lines() {
|
||||
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
|
||||
assert!(super::es::translate(label).is_some(), "missing es menu label: {label}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_errors_are_translated_with_their_values() {
|
||||
assert_eq!(error_text("select a clip"), "select a clip");
|
||||
@@ -460,9 +520,17 @@ mod tests {
|
||||
None
|
||||
}
|
||||
|
||||
/// Every `"source" => "translation"` pair of the catalog, read from its source file.
|
||||
fn catalog_entries() -> Vec<(String, String)> {
|
||||
let text = include_str!("../locales/pt-BR/mod.rs");
|
||||
type Lookup = fn(&str) -> Option<&'static str>;
|
||||
|
||||
/// Every catalog: its tag, source file and lookup.
|
||||
const CATALOGS: [(&str, &str, Lookup); 3] = [
|
||||
("pt-BR", include_str!("../locales/pt-BR/mod.rs"), super::pt_br::translate),
|
||||
("fr", include_str!("../locales/fr/mod.rs"), super::fr::translate),
|
||||
("es", include_str!("../locales/es/mod.rs"), super::es::translate),
|
||||
];
|
||||
|
||||
/// Every `"source" => "translation"` pair of a catalog, read from its source file.
|
||||
fn catalog_entries(text: &str) -> Vec<(String, String)> {
|
||||
let mut lines = text.lines().map(str::trim);
|
||||
let mut entries = Vec::new();
|
||||
while let Some(line) = lines.next() {
|
||||
@@ -495,20 +563,24 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn catalog_entries_are_parsed_and_unique() {
|
||||
let entries = catalog_entries();
|
||||
assert!(entries.len() > 1000, "parsed only {} catalog entries", entries.len());
|
||||
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
|
||||
keys.sort_unstable();
|
||||
let before = keys.len();
|
||||
keys.dedup();
|
||||
assert_eq!(before, keys.len(), "duplicate catalog keys");
|
||||
for (tag, text, _) in CATALOGS {
|
||||
let entries = catalog_entries(text);
|
||||
assert!(entries.len() > 1000, "{tag}: parsed only {} catalog entries", entries.len());
|
||||
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
|
||||
keys.sort_unstable();
|
||||
let before = keys.len();
|
||||
keys.dedup();
|
||||
assert_eq!(before, keys.len(), "{tag}: duplicate catalog keys");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_translations_keep_the_english_placeholders() {
|
||||
for (source, translation) in catalog_entries() {
|
||||
assert_eq!(placeholders(&source), placeholders(&translation), "placeholders differ for {source:?}");
|
||||
assert_eq!(super::pt_br::translate(&source), Some(translation.as_str()), "lookup differs for {source:?}");
|
||||
for (tag, text, translate) in CATALOGS {
|
||||
for (source, translation) in catalog_entries(text) {
|
||||
assert_eq!(placeholders(&source), placeholders(&translation), "{tag}: placeholders differ for {source:?}");
|
||||
assert_eq!(translate(&source), Some(translation.as_str()), "{tag}: lookup differs for {source:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,21 +594,22 @@ mod tests {
|
||||
assert_eq!(pt.text("Strip"), "Canal", "the Channel Strip plug-in's short name keeps its own key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_localized_source_string_has_a_catalog_entry() {
|
||||
fn visit(dir: &std::path::Path, missing: &mut Vec<String>) {
|
||||
/// Every string passed to `text` / `localized_format!` in this crate must have an entry in
|
||||
/// `catalog`; `locale` names it in the failure.
|
||||
fn assert_catalog_covers_the_source(catalog: fn(&str) -> Option<&'static str>, locale: &str) {
|
||||
fn visit(dir: &std::path::Path, missing: &mut Vec<String>, catalog: fn(&str) -> Option<&'static str>) {
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return };
|
||||
for entry in read.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
visit(&path, missing);
|
||||
visit(&path, missing, catalog);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("localization.rs") {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
for marker in ["localization::text(\"", "localized_format!(\""] {
|
||||
for (at, _) in text.match_indices(marker) {
|
||||
let start = at + marker.len() - 1;
|
||||
if let Some((source, _)) = literal(&text[start..])
|
||||
&& super::pt_br::translate(&source).is_none()
|
||||
&& catalog(&source).is_none()
|
||||
{
|
||||
missing.push(format!("{}: {source:?}", path.display()));
|
||||
}
|
||||
@@ -546,7 +619,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
let mut missing = Vec::new();
|
||||
visit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut missing);
|
||||
assert!(missing.is_empty(), "strings without a pt-BR entry:\n{}", missing.join("\n"));
|
||||
visit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut missing, catalog);
|
||||
assert!(missing.is_empty(), "strings without a {locale} entry:\n{}", missing.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_localized_source_string_has_a_catalog_entry() {
|
||||
assert_catalog_covers_the_source(super::pt_br::translate, "pt-BR");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_localized_source_string_has_a_zh_hans_entry() {
|
||||
assert_catalog_covers_the_source(super::zh_hans::translate, "zh-Hans");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,12 +394,13 @@ fn header_footer_menu<H, R, F>(
|
||||
|
||||
/// What the send menu's footer was used for.
|
||||
enum SendFooter {
|
||||
NewBus,
|
||||
/// A new bus in this format (`mono` or `stereo`), with the send going to it.
|
||||
NewBus(&'static str),
|
||||
RemoveSend,
|
||||
}
|
||||
|
||||
/// The send's destination menu: a title and the bus search on top, the matching buses in a list
|
||||
/// that scrolls, "new bus..." (and "Remove send" for an existing send) fixed under it.
|
||||
/// that scrolls, "new mono bus" / "new stereo bus" (and "Remove send" for an existing send) fixed under it.
|
||||
/// `current` is the send's destination and its name, if the slot has a send.
|
||||
fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: TrackId, slot: usize, current: Option<(Route, String)>) {
|
||||
let which = (b'A' + slot as u8) as char;
|
||||
@@ -445,9 +446,11 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
})
|
||||
},
|
||||
|ui| {
|
||||
if ui.button(crate::localization::text("new bus...")).clicked() {
|
||||
ui.close();
|
||||
return Some(SendFooter::NewBus);
|
||||
for (label, format) in [(crate::localization::text("new mono bus"), "mono"), (crate::localization::text("new stereo bus"), "stereo")] {
|
||||
if ui.button(label).clicked() {
|
||||
ui.close();
|
||||
return Some(SendFooter::NewBus(format));
|
||||
}
|
||||
}
|
||||
if has_send && ui.button(crate::localization::text("Remove send")).clicked() {
|
||||
ui.close();
|
||||
@@ -478,7 +481,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
show_new_send(app);
|
||||
}
|
||||
match footer {
|
||||
Some(SendFooter::NewBus) => {
|
||||
Some(SendFooter::NewBus(format)) => {
|
||||
let busses = &app.engine.session().busses;
|
||||
let mut n = busses.len() + 1;
|
||||
while busses.iter().any(|bus| bus.name.eq_ignore_ascii_case(&format!("Bus {n}")))
|
||||
@@ -486,7 +489,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
{
|
||||
n += 1;
|
||||
}
|
||||
if app.run("mix.new_bus", json!({"name": format!("Bus {n}")})).is_ok()
|
||||
if app.run("mix.new_bus", json!({"name": format!("Bus {n}"), "format": format})).is_ok()
|
||||
&& app.run("mix.send", send_params(app, &format!("Bus {n}"))).is_ok()
|
||||
{
|
||||
show_new_send(app);
|
||||
@@ -505,6 +508,7 @@ mod tests {
|
||||
use crate::Services;
|
||||
use crate::preferences::SendsDefault;
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use soundcraft_model::ChannelFormat;
|
||||
|
||||
/// Filtering the destination list to nothing shrinks the menu; clearing the filter grows it
|
||||
/// back, with the search field in the same place and the footer under the list.
|
||||
@@ -538,7 +542,7 @@ mod tests {
|
||||
let field = |h: &Harness<'_, (SoundApp, TrackId)>| h.get_by_role(egui::accesskit::Role::TextInput).rect();
|
||||
let footer = |h: &Harness<'_, (SoundApp, TrackId)>| h.get_by_label("Remove send").rect();
|
||||
let (search, full) = (field(&h), footer(&h));
|
||||
assert!(h.query_by_label("new bus...").is_some(), "the footer lists new bus...");
|
||||
assert!(h.query_by_label("new stereo bus").is_some(), "the footer offers a new stereo bus");
|
||||
assert!(full.top() > search.bottom() + 150.0, "the list sits between the search and the footer: {search:?} {full:?}");
|
||||
|
||||
h.get_by_role(egui::accesskit::Role::TextInput).type_text("zzzz");
|
||||
@@ -599,7 +603,7 @@ mod tests {
|
||||
assert_eq!(app.ui.send_window, Some((kick, 0)), "the new send's window is open");
|
||||
}
|
||||
|
||||
/// So does a send made with "new bus...".
|
||||
/// So does a send made with "new stereo bus".
|
||||
#[test]
|
||||
fn a_send_to_a_new_bus_opens_its_send_window() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
@@ -607,13 +611,32 @@ mod tests {
|
||||
h.run();
|
||||
h.get_by_label("Send A for Kick").click();
|
||||
h.run();
|
||||
h.get_by_label("new bus...").click();
|
||||
h.get_by_label("new stereo bus").click();
|
||||
h.run();
|
||||
let (app, _) = h.state();
|
||||
assert!(app.engine.session().track(kick).and_then(|t| t.mixer.sends.first().cloned().flatten()).is_some(), "the send was created");
|
||||
assert_eq!(app.ui.send_window, Some((kick, 0)), "the new send's window is open");
|
||||
}
|
||||
|
||||
/// #1388: the send menu asks for mono or stereo, and the new bus has the format picked.
|
||||
#[test]
|
||||
fn a_new_bus_from_the_send_menu_is_mono_or_stereo_as_picked() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
for (label, format) in [("new mono bus", ChannelFormat::Mono), ("new stereo bus", ChannelFormat::Stereo)] {
|
||||
let (mut h, kick) = kick_send_harness(false);
|
||||
h.run();
|
||||
h.get_by_label("Send A for Kick").click();
|
||||
h.run();
|
||||
h.get_by_label(label).click();
|
||||
h.run();
|
||||
let (app, _) = h.state();
|
||||
let s = app.engine.session();
|
||||
let send = s.track(kick).and_then(|t| t.mixer.sends.first().cloned().flatten()).unwrap();
|
||||
let bus = s.busses.iter().find(|b| Route::Bus(b.id) == send.target).unwrap();
|
||||
assert_eq!(bus.format, format, "{label} makes a bus in that format");
|
||||
}
|
||||
}
|
||||
|
||||
/// Moving an existing send to another bus keeps the Send window as it was.
|
||||
#[test]
|
||||
fn changing_a_sends_destination_leaves_the_send_window_alone() {
|
||||
@@ -653,7 +676,7 @@ mod tests {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
assert_eq!(level_after_picking(false, SendsDefault::NegativeInfinity, "Aux"), Some(-144.0));
|
||||
assert_eq!(level_after_picking(false, SendsDefault::Unity, "Aux"), Some(0.0));
|
||||
assert_eq!(level_after_picking(false, SendsDefault::Unity, "new bus..."), Some(0.0));
|
||||
assert_eq!(level_after_picking(false, SendsDefault::Unity, "new stereo bus"), Some(0.0));
|
||||
}
|
||||
|
||||
/// Moving an existing send to another bus keeps its level, whatever the preference says.
|
||||
|
||||
@@ -591,9 +591,11 @@ mod tests {
|
||||
assert_eq!(app.run("ui.language", json!({})), Ok(json!({"language": "en"})));
|
||||
assert_eq!(app.run("ui.language", json!({"language": "pt-BR"})), Ok(json!({"language": "pt-BR"})));
|
||||
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
|
||||
assert!(app.run("ui.language", json!({"language": "fr"})).is_err());
|
||||
assert!(app.run("ui.language", json!({"language": "xx"})).is_err());
|
||||
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
|
||||
assert!(crate::menus::UI_COMMANDS.iter().any(|command| command.0 == "ui.language"));
|
||||
assert_eq!(app.run("ui.language", json!({"language": "zh-Hans"})), Ok(json!({"language": "zh-Hans"})));
|
||||
assert_eq!(app.ui.language, crate::localization::Language::SimplifiedChinese);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -44,6 +44,7 @@ Errors: `{"id": 1, "ok": false, "error": "bad parameters for `mix.volume`: no tr
|
||||
| `engine.parity` | `{}` | Parity report against the incumbent's menu catalog. |
|
||||
| `session.inspect` | `{detail?: "summary"|"full"}` | The document: tracks, clips (with times), inserts (+params when full), sends, routing, automation, markers, groups, busses, sources (`loaded` true when decoded audio is in the pool), selection, zoom (`samples_per_px`, `scroll`), transport, undo label. |
|
||||
| `ui.inspect` | `{}` | UI state (`window`, panels, dialogs), window size, playing/position, audio device, MIDI inputs (`midi_inputs`: name, enabled, open; `midi_events`: messages received so far; `midi_events_dropped`: messages a full input queue dropped), and `edit_layout` (timeline rect and every track row's rect, for clicking). |
|
||||
| `audio.health` | `{reset?: bool}` | How the realtime audio path keeps up since the output opened (or the last reset): `health` holds `callbacks`, `xruns` (underruns the device reported), `late_callbacks` (callbacks that overran their buffer period; not every one is audible, and the device may report the same overrun as an xrun) and `worst_load` (slowest callback as a share of its buffer period, to 0.001; 1.0 = it overran). Also `device`, `silent`, `sample_rate` and `buffer_frames` (`null`: the device default). The first blocks create plugins and may read late, so a stress run resets once playback is under way. `reset: true` returns the reading and counts afresh from it; no event falls between the two. |
|
||||
| `ui.set` | any `UiState` fields | e.g. `{"window": "Mix", "narrow_mix": true}`. |
|
||||
| `ui.menu.list` | `{}` | Every catalog menu path and the command that implements it (or null). |
|
||||
| `ui.menu.invoke` | `{path}` or `{id}` | Like clicking the menu item: may open its dialog (e.g. `"Track > New..."`). |
|
||||
|
||||
+20
-14
@@ -1,6 +1,6 @@
|
||||
# Where SoundCraft falls short of Pro Tools
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-25 · **Change:** minor (G-01: the Playback Engine shows the current device choice after a command changes it, and a buffer size the driver does not take is reported; previously trivial: G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-28 · **Change:** minor (G-09: the zh-Hans catalog now covers the fixed UI strings, with a Han fallback and a web subset; previously minor: G-05: the signed macOS app and CLI carry the plugin-loading entitlements; previously minor: G-01: the Playback Engine shows the current device choice after a command changes it, and a buffer size the driver does not take is reported; previously trivial: G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing
|
||||
real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker**
|
||||
@@ -23,7 +23,7 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t
|
||||
| G-06 | Sources decoded whole into RAM (recording to disk is done: #84, #888) | Performance | [hardware-parity.md](hardware-parity.md) | 15–25 |
|
||||
| G-07 | Nothing is compared against Pro Tools' output (no fidelity harness) | Features | this file | 20–30 |
|
||||
| G-08 | Built-in plugin catalogue thin and unverified | Features | [plugin-parity.md](plugin-parity.md) | 80–120 |
|
||||
| G-09 | English-first UI with a pt-BR catalog (not native-reviewed); all fixed UI strings covered, no CJK/RTL rendering | Localization | [localization-parity.md](localization-parity.md) | 20–40 |
|
||||
| G-09 | English-first UI with pt-BR and zh-Hans catalogs (neither native-reviewed); all fixed UI strings covered, CJK fallback ships, no other Pro Tools languages and no RTL/complex-script shaping | Localization | [localization-parity.md](localization-parity.md) | 55–90 |
|
||||
| G-10 | No control surfaces (HUI/MCU, EUCON) | Hardware | [hardware-parity.md](hardware-parity.md) | 40–70 |
|
||||
| G-11 | No external sync (MTC, LTC, MIDI clock, video reference) | Hardware | [hardware-parity.md](hardware-parity.md) | 15–25 |
|
||||
| G-12 | Immersive delivery: no Dolby Atmos/ADM BWF, MPEG-H, binaural | Features | [file-format-parity.md](file-format-parity.md) | 50–80 |
|
||||
@@ -150,11 +150,14 @@ launch #142; Linux #45, #107.
|
||||
|
||||
### G-05. Plugin hosting on macOS
|
||||
|
||||
- **Missing:** the `com.apple.security.cs.disable-library-validation` entitlement in the signed
|
||||
build, so hardened runtime refuses third-party VST3 bundles (#153, #149). AU editor views
|
||||
- **Fixed (pending release):** the `com.apple.security.cs.disable-library-validation` and
|
||||
`com.apple.security.cs.allow-unsigned-executable-memory` entitlements are now in
|
||||
`entitlements.plist` and applied to the app and the CLI (#153, #149); verify on a signed build
|
||||
with `codesign -d --entitlements - SoundCraft.app` and a third-party VST3.
|
||||
- **Missing:** AU editor views
|
||||
(`crates/au-host/src/lib.rs` header: "Not hosted yet: Audio Unit editor views"). Embedded CLAP
|
||||
GUIs on macOS (#485). VST3 and embedded CLAP editors are hosted on Windows and Linux/X11.
|
||||
- **Estimate:** ≈ 10–15 h (entitlement ≈ 1 h; AU Cocoa views and embedded CLAP on macOS most of it).
|
||||
- **Estimate:** ≈ 9–14 h (AU Cocoa views and embedded CLAP on macOS).
|
||||
|
||||
### G-06. Memory-bound media
|
||||
|
||||
@@ -182,15 +185,17 @@ parametric request #139. ≈ 80–120 h.
|
||||
|
||||
### G-09. Localization
|
||||
|
||||
See [`localization-parity.md`](localization-parity.md): a pt-BR catalog covers the menu labels and
|
||||
every fixed UI string passed to `text` / `localized_format!` or localized inside a button, toggle or
|
||||
close button (test-checked), including the Edit-window status bar, the remove-session question and
|
||||
the send help text; engine errors are matched against catalog templates at display time by
|
||||
`error_text`. What remains is independent native-speaker review plus egui's lack of complex-script
|
||||
shaping and RTL, and the missing other Pro Tools languages; values built at run time (file, track
|
||||
and device names) and engine command parameter documentation stay untranslated. egui has no
|
||||
complex-script shaping or RTL; no CJK font fallback (PR #141 open). ≈ 70–110 h plus
|
||||
native-speaker review.
|
||||
See [`localization-parity.md`](localization-parity.md): pt-BR and zh-Hans catalogs cover the menu
|
||||
labels and every fixed UI string passed to `text` / `localized_format!` or localized inside a button,
|
||||
toggle or close button (test-checked), including the Edit-window status bar, the remove-session
|
||||
question and the send help text; pt-BR also matches engine errors against catalog templates through
|
||||
`error_text`, while zh-Hans keeps diagnostics English. Chinese has a Han font fallback on the desktop
|
||||
(a system face, never redistributed) and an OFL subset in the web build, ordered ahead of the Hangul
|
||||
fallback except under a Korean interface. What remains is independent native-speaker review of both
|
||||
catalogs, the other Pro Tools languages (Spanish, French, German, Japanese, Korean, Traditional
|
||||
Chinese, Hindi/Arabic for the non-target languages), and egui's lack of complex-script shaping and
|
||||
RTL; values built at run time (file, track and device names) and engine command parameter
|
||||
documentation stay untranslated. ≈ 55–90 h plus native-speaker review.
|
||||
|
||||
### G-10. Control surfaces
|
||||
|
||||
@@ -266,6 +271,7 @@ missing. Out of scope unless the owner decides otherwise.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-28 | minor | G-05: library-validation and unsigned-executable-memory entitlements for the macOS app and CLI, so signed builds load third-party plugins (#153, #149); G-05 estimate ≈ 9–14 h |
|
||||
| 2026-11-25 | minor | G-01: the Playback Engine shows the current device choice after a command changes it, and Apply keeps it; a buffer size the driver does not take is reported, with the driver's range (#1757); estimates unchanged |
|
||||
| 2026-11-23 | trivial | G-04: Clip Looping Number of Loops accepts up to 1,000; crossfade remains open; estimates unchanged |
|
||||
| 2026-11-14 | minor | G-03: strict external-WAV AAF import with bounded property caching; AAF/OMF export, OMF import and `.ptx` remain; estimates unchanged |
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# i18n tools and notes
|
||||
|
||||
Working files for SoundCraft's own catalog (`zh-Hans`). The runtime mechanism and the language list
|
||||
are described in [`../localization.md`](../localization.md); the translator workflow in
|
||||
[`../localization-zh-hans.md`](../localization-zh-hans.md); wording decisions in
|
||||
[`glossary.md`](glossary.md).
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `tools/gen_zh_hans_locale.py` | turns `crates/ui-egui/src/i18n/zh-hans.tsv` into `crates/ui-egui/locales/zh-Hans/mod.rs`; `--check` is the CI/`xtask`-style staleness gate |
|
||||
| `tools/subset_web_font.py` | rebuilds `assets/fonts/NotoSansSC-SoundCraftSubset.ttf` from the catalog's glyph set and the pinned Noto Sans SC source |
|
||||
|
||||
## Why the catalog lives here
|
||||
|
||||
The org keeps shared translations in `storytold/craft-i18n`, read through an optional
|
||||
`CRAFT_I18N_DIR` build input. SoundCraft has not cut over (roadmap stage 3d), so — like the pt-BR
|
||||
catalog — this one ships in the repository, and the TSV is the pre-cutover file that
|
||||
`craft-i18n`'s `tools/sync_app.py` consumes when the app does migrate. Nothing here depends on the
|
||||
other repository being present.
|
||||
|
||||
## Clean room, restated
|
||||
|
||||
Write every row from the plain meaning of the English source. Do not read, copy or "check against"
|
||||
another product's translated interface or translation files, and do not download copyleft or
|
||||
proprietary string tables for reference. If a term needs a decision, write the reasoning in
|
||||
[`glossary.md`](glossary.md) instead of citing a source we must not use.
|
||||
|
||||
The translations are original work by SoundCraft contributors (AI-assisted), licensed like the rest
|
||||
of the repository (MIT OR Apache-2.0); see `crates/ui-egui/src/i18n/LICENSE-translations.txt`.
|
||||
@@ -0,0 +1,69 @@
|
||||
# i18n glossary
|
||||
|
||||
The decisions behind SoundCraft's Simplified Chinese wording. The strings themselves live in
|
||||
`crates/ui-egui/src/i18n/zh-hans.tsv`; the mechanism is in
|
||||
[`../localization.md`](../localization.md) and the translator workflow in
|
||||
[`../localization-zh-hans.md`](../localization-zh-hans.md).
|
||||
|
||||
**Clean room.** Every entry is written from the plain meaning of the English source text. Do not
|
||||
consult another product's translation files, string tables or localized interface — not proprietary
|
||||
ones and not copyleft ones. Where a term is hard, argue it here with the reasoning, not with a
|
||||
source we are not allowed to read.
|
||||
|
||||
## 1. Terms we keep
|
||||
|
||||
| English | Ours | Why |
|
||||
|---|---|---|
|
||||
| Session | 会话 | the ordinary word for a DAW project in Chinese; 工程 reads as engineering |
|
||||
| Track | 轨道 | covers audio and MIDI tracks; 音轨 reads as audio-only |
|
||||
| Clip | 片段 | a piece of audio or MIDI on the timeline |
|
||||
| Region | 区域 | kept distinct from clip |
|
||||
| Bus | 总线 | signal-routing bus |
|
||||
| Solo / Mute | 独奏 / 静音 | |
|
||||
| Automation | 自动化 | |
|
||||
| Export / Import | 导出 / 导入 | |
|
||||
| Snap to Grid | 吸附到网格 | |
|
||||
| Normalize | 标准化 | not 归一化, which is the loudness-community word |
|
||||
| Sample rate | 采样率 | |
|
||||
| Mono / Stereo | 单声道 / 立体声 | |
|
||||
| Quantize | 量化 | |
|
||||
| Undo / Redo | 撤销 / 重做 | 撤销 (not 撤消) is the standard spelling |
|
||||
| Preferences | 首选项 | the majority DAW wording in Chinese |
|
||||
| Meter (level) | 电平表 | the level meter |
|
||||
| Meter (time signature) | 拍号 | same English word, different sense: the catalog carries both |
|
||||
| Tempo | 速度 | |
|
||||
| Velocity | 力度 | MIDI note velocity |
|
||||
| Pan | 声像 | the 规范 acoustics term (sound image) |
|
||||
|
||||
## 2. Deliberate choices that differ from the obvious translation
|
||||
|
||||
| English | Ours | Why |
|
||||
|---|---|---|
|
||||
| Transport | 走带 | the standard Chinese audio-engineering word for the transport section |
|
||||
| Bypass | 旁通 | the community word for bypassing a plug-in |
|
||||
| Record / Record Enable | 录音 / 启用录音 | the action, not the medium |
|
||||
| Latch / Touch (automation) | 锁存 / 触碰 | |
|
||||
| Start / End (clip boundary) | 开头 / 结尾 | positions keep 起点 / 终点 |
|
||||
| Key (signature) | 调号 | musical sense |
|
||||
| Trim (edit) / Trim (automation) | 修剪 / 微调 | two senses, kept apart |
|
||||
| Slip / Spot | 滑动 / 定位 | |
|
||||
| Bounce | 导出 | Bounce Mix = 导出混音 |
|
||||
| Big Counter | 大计数器 | the transport readout |
|
||||
|
||||
## 3. Shape of a translated string
|
||||
|
||||
- Chinese punctuation: use full-width `:`、`,`、`(`、`)`、`。`、`?` inside sentences; keep ASCII
|
||||
`·`、`·`、`—`、`/` and the `>` `›` path separators as they are.
|
||||
- Keep a leading space when the English has one: such fragments are appended to a label at run time
|
||||
(`" It is used by {users}"`).
|
||||
- Preserve every `{placeholder}`, including format specs (`{ms:.1}`, `{seconds:.2}`) and positional
|
||||
`{}`; a test compares placeholder sets.
|
||||
- Keep trailing `…` in menu items (`首选项…`), and keep UI symbols (`+`, `−`, `−∞`, `⬆`) as they are.
|
||||
- No spaces around Chinese text; one space between Chinese and Latin words is fine where it helps
|
||||
(`24 位`, `MIDI 轨道`).
|
||||
|
||||
## 4. Review status
|
||||
|
||||
The catalog is AI-authored from the English source and has not been reviewed by a native-speaking
|
||||
audio engineer. Treat wording as provisional until it is; changes go in the TSV, and the module is
|
||||
regenerated.
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate `crates/ui-egui/locales/zh-Hans/mod.rs` from the translator-facing TSV.
|
||||
|
||||
The TSV (`crates/ui-egui/src/i18n/zh-hans.tsv`) is the source translators edit: one row per
|
||||
string, `context<TAB>English source<TAB>Simplified Chinese`. The UI reads the Rust module, because
|
||||
that is how every locale in this repository ships (see `locales/pt-BR/mod.rs`); this script is the
|
||||
only thing that turns one into the other, so the two never drift.
|
||||
|
||||
Usage (from the repository root):
|
||||
|
||||
python3 docs/i18n/tools/gen_zh_hans_locale.py # write the module
|
||||
python3 docs/i18n/tools/gen_zh_hans_locale.py --check # fail if it is out of date
|
||||
|
||||
`@plural` rows carry `singular|plural` in the source column, because English inflects where
|
||||
Simplified Chinese does not; both English keys map to the same Chinese row. The columns use the
|
||||
catalog's escapes (`\n`, `\t`, `\\`), which this script decodes before writing the Rust literal.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
TSV = ROOT / "crates/ui-egui/src/i18n/zh-hans.tsv"
|
||||
OUT = ROOT / "crates/ui-egui/locales/zh-Hans/mod.rs"
|
||||
|
||||
HEADER = """\
|
||||
//! Simplified Chinese (`zh-Hans`) catalog, keyed by the English source string.
|
||||
//!
|
||||
//! Generated by `docs/i18n/tools/gen_zh_hans_locale.py` from
|
||||
//! `crates/ui-egui/src/i18n/zh-hans.tsv`; edit the TSV, then rerun the script. Engine diagnostics
|
||||
//! stay English by design, so this catalog has no error templates.
|
||||
|
||||
/// Returns the Simplified Chinese translation for a source-language UI string.
|
||||
#[rustfmt::skip]
|
||||
pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
Some(match source {
|
||||
"""
|
||||
|
||||
FOOTER = """\
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Engine error messages with `{name}` placeholders standing for the values they embed. Simplified
|
||||
/// Chinese keeps engine diagnostics in English by design (see `docs/localization-zh-hans.md`).
|
||||
pub(super) const ERROR_TEMPLATES: &[(&str, &str)] = &[];
|
||||
"""
|
||||
|
||||
|
||||
def unescape(text: str) -> str:
|
||||
"""Decode the catalog's `\\n`, `\\t` and `\\\\` escapes (the TSV is one row per string)."""
|
||||
out = []
|
||||
index = 0
|
||||
while index < len(text):
|
||||
ch = text[index]
|
||||
if ch == "\\" and index + 1 < len(text):
|
||||
nxt = text[index + 1]
|
||||
if nxt == "n":
|
||||
out.append("\n")
|
||||
elif nxt == "t":
|
||||
out.append("\t")
|
||||
elif nxt == "\\":
|
||||
out.append("\\")
|
||||
else:
|
||||
out.append(ch)
|
||||
out.append(nxt)
|
||||
index += 2
|
||||
continue
|
||||
out.append(ch)
|
||||
index += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def rust_literal(text: str) -> str:
|
||||
"""A Rust string literal for `text`; the catalogs contain quotes, braces and newlines."""
|
||||
out = []
|
||||
for ch in text:
|
||||
if ch == "\\":
|
||||
out.append("\\\\")
|
||||
elif ch == '"':
|
||||
out.append('\\"')
|
||||
elif ch == "\n":
|
||||
out.append("\\n")
|
||||
elif ch == "\t":
|
||||
out.append("\\t")
|
||||
elif ch == "\r":
|
||||
out.append("\\r")
|
||||
elif ord(ch) < 0x20:
|
||||
out.append(f"\\u{{{ord(ch):x}}}")
|
||||
else:
|
||||
out.append(ch)
|
||||
return '"' + "".join(out) + '"'
|
||||
|
||||
|
||||
def rows() -> dict[str, str]:
|
||||
"""Every English source string mapped to its Chinese translation."""
|
||||
pairs: dict[str, str] = {}
|
||||
for number, line in enumerate(TSV.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
columns = line.split("\t", 2)
|
||||
if len(columns) != 3:
|
||||
raise SystemExit(f"{TSV}:{number}: expected three tab-separated columns")
|
||||
context, source, translation = (unescape(column) for column in columns)
|
||||
if not source or not translation:
|
||||
raise SystemExit(f"{TSV}:{number}: empty source or translation")
|
||||
# A `@plural` row names both English forms; Chinese has one form for both.
|
||||
sources = source.split("|") if context.startswith("@") else [source]
|
||||
for key in sources:
|
||||
previous = pairs.get(key)
|
||||
if previous is not None and previous != translation:
|
||||
raise SystemExit(f"{TSV}:{number}: {key!r} translated twice, differently")
|
||||
pairs[key] = translation
|
||||
return pairs
|
||||
|
||||
|
||||
def render(pairs: dict[str, str]) -> str:
|
||||
arms = "".join(f" {rust_literal(source)} => {rust_literal(pairs[source])},\n" for source in sorted(pairs))
|
||||
return HEADER + arms + FOOTER
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
rendered = render(rows())
|
||||
if "--check" in argv:
|
||||
if not OUT.exists() or OUT.read_text(encoding="utf-8") != rendered:
|
||||
print(f"{OUT} is out of date; run python3 docs/i18n/tools/gen_zh_hans_locale.py", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{OUT}: up to date")
|
||||
return 0
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text(rendered, encoding="utf-8")
|
||||
print(f"wrote {OUT.relative_to(ROOT)} ({len(rows())} strings)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate `assets/fonts/NotoSansSC-SoundCraftSubset.ttf`.
|
||||
|
||||
Usage (run from the repo root):
|
||||
python3 docs/i18n/tools/subset_web_font.py NotoSansSC-VariableFont_wght.ttf
|
||||
python3 docs/i18n/tools/subset_web_font.py --check
|
||||
|
||||
The web build has no operating-system fonts, so it bundles a small subset of
|
||||
Noto Sans SC (SIL OFL-1.1, see `assets/fonts/OFL.txt` and `ATTRIBUTION.md`),
|
||||
pinned at weight 400. The full variable font is a noto-cjk release:
|
||||
https://github.com/notofonts/noto-cjk (Sans/Variable/OTF or the "Subset"
|
||||
OTC — any file whose family is Noto Sans SC with a wght axis).
|
||||
|
||||
The codepoint set is a superset of the UI glyph set:
|
||||
|
||||
- printable ASCII (U+0020-007E) and Latin-1 (U+00A0-00FF);
|
||||
- the GB 2312 level-1 common Han characters (3,755, rows 16-55), so the
|
||||
catalog can grow new everyday words without touching this script;
|
||||
- every BMP, non-control character used in `crates/ui-egui/src/i18n/*.tsv`
|
||||
(sources, translations and comments — emoji outside the BMP come from
|
||||
egui's bundled emoji fonts, see `fonts.rs`);
|
||||
- `EXTRA_SYMBOLS` below: the punctuation, arrows and symbols the UI draws
|
||||
outside the catalogs (meters, transport, musical notation).
|
||||
|
||||
`--check` compares that set against the shipped subset and exits non-zero on
|
||||
any difference; the catalog-side guarantee (every catalog glyph present) is
|
||||
enforced by the `bundled_web_font_*` tests in `crates/ui-egui/src/fonts.rs`.
|
||||
|
||||
Requires fontTools (`pip install fonttools`). Steps: pin weight 400 with
|
||||
`fontTools.varLib.instancer`, then subset with `fontTools.subset`, keeping the
|
||||
name table (the OFL copyright notice rides along) and all layout features.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
CATALOG_DIR = REPO / "crates/ui-egui/src/i18n"
|
||||
SHIPPED = REPO / "assets/fonts/NotoSansSC-SoundCraftSubset.ttf"
|
||||
|
||||
# Punctuation, arrows and symbols the UI draws outside the catalogs. Comment
|
||||
# each addition; the `--check` run against the shipped font catches drift.
|
||||
EXTRA_SYMBOLS = (
|
||||
"ΔΣπ" # Greek letters used in math/technical readouts
|
||||
"–‘’′″›※" # dashes, quotes, primes and reference marks
|
||||
"←↑→↓↔⬆" # arrows (transport, nudge, navigation)
|
||||
"∈√∞≈≤≥" # math symbols
|
||||
"⌘" # command-key hint glyphs
|
||||
"─★" # box drawing and rating star
|
||||
"♩♯" # musical notation
|
||||
"〈〉《》「」『』【】〔〕" # CJK brackets
|
||||
"!¥" # fullwidth exclamation mark, yen sign
|
||||
)
|
||||
|
||||
|
||||
def collect_codepoints() -> set[int]:
|
||||
"""The full codepoint set the subset must carry."""
|
||||
points = set(range(0x20, 0x7F)) | set(range(0xA0, 0x100))
|
||||
# GB 2312 level-1 Han: rows 16-55, decoded straight from the encoding so
|
||||
# no external table is needed (row 55 stops at column 89).
|
||||
for row in range(16, 56):
|
||||
for col in range(1, 95):
|
||||
try:
|
||||
points.add(ord(bytes([0xA0 + row, 0xA0 + col]).decode("gb2312")))
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
for path in sorted(CATALOG_DIR.glob("*.tsv")):
|
||||
for ch in path.read_text(encoding="utf-8"):
|
||||
cp = ord(ch)
|
||||
if cp <= 0xFFFF and not ch.isspace() and not unicodedata_category_cc(ch):
|
||||
points.add(cp)
|
||||
points |= {ord(ch) for ch in EXTRA_SYMBOLS}
|
||||
return points
|
||||
|
||||
|
||||
def unicodedata_category_cc(ch: str) -> bool:
|
||||
import unicodedata
|
||||
|
||||
return unicodedata.category(ch) == "Cc"
|
||||
|
||||
|
||||
def shipped_codepoints() -> set[int]:
|
||||
from fontTools.ttLib import TTFont
|
||||
|
||||
return set(TTFont(SHIPPED).getBestCmap())
|
||||
|
||||
|
||||
def check(points: set[int]) -> int:
|
||||
shipped = shipped_codepoints()
|
||||
missing = sorted(points - shipped)
|
||||
stale = sorted(shipped - points)
|
||||
for label, diff in (("missing from the shipped subset", missing), ("no longer needed", stale)):
|
||||
if diff:
|
||||
print(f"{label}: {len(diff)}")
|
||||
for cp in diff[:40]:
|
||||
print(f" U+{cp:04X} {chr(cp)}")
|
||||
if missing:
|
||||
print("regenerate: python3 docs/i18n/tools/subset_web_font.py <NotoSansSC variable font>")
|
||||
return 1
|
||||
if stale:
|
||||
print("the recipe and the shipped subset drifted — regenerate or update EXTRA_SYMBOLS")
|
||||
return 1
|
||||
print(f"ok: the shipped subset matches the recipe exactly ({len(points)} codepoints)")
|
||||
return 0
|
||||
|
||||
|
||||
def regenerate(font: Path, points: set[int], out: Path) -> int:
|
||||
from fontTools import subset
|
||||
from fontTools.varLib import instancer
|
||||
|
||||
font_path = font.resolve()
|
||||
out_path = out.resolve()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
instanced = Path(tmp) / "NotoSansSC-400.ttf"
|
||||
instancer.main([str(font_path), "wght=400", "-o", str(instanced)])
|
||||
unicodes = ",".join(f"U+{cp:04X}" for cp in sorted(points))
|
||||
subset.main([
|
||||
str(instanced),
|
||||
f"--output-file={out_path}",
|
||||
f"--unicodes={unicodes}",
|
||||
"--layout-features=*",
|
||||
"--glyph-names",
|
||||
"--name-IDs=*",
|
||||
"--name-legacy",
|
||||
"--name-languages=*",
|
||||
"--notdef-glyph",
|
||||
"--notdef-outline",
|
||||
"--recommended-glyphs",
|
||||
])
|
||||
size = out_path.stat().st_size
|
||||
print(f"wrote {out_path} ({size} bytes, {len(points)} codepoints)")
|
||||
if size > 2 * 1024 * 1024:
|
||||
print("warning: over the 2 MiB web budget enforced by the fonts.rs tests")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("font", type=Path, nargs="?", help="Noto Sans SC variable font (a noto-cjk release)")
|
||||
ap.add_argument("--out", type=Path, default=SHIPPED)
|
||||
ap.add_argument("--check", action="store_true", help="compare the recipe against the shipped subset and exit")
|
||||
args = ap.parse_args()
|
||||
|
||||
points = collect_codepoints()
|
||||
if args.check:
|
||||
return check(points)
|
||||
if args.font is None:
|
||||
ap.error("a Noto Sans SC variable font is required (or use --check)")
|
||||
return 2
|
||||
if not args.font.is_file():
|
||||
print(f"error: {args.font} is not a file", file=sys.stderr)
|
||||
return 1
|
||||
return regenerate(args.font, points, args.out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+40
-29
@@ -1,62 +1,73 @@
|
||||
# Localization parity
|
||||
|
||||
> **Last reviewed:** 2026-11-13 · **Last updated:** 2026-11-13 · **Change:** minor (pt-BR catalog completed: all fixed UI strings translated and covered by tests; native-speaker review, CJK/RTL font fallbacks and RTL script shaping still pending) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-13 · **Last updated:** 2026-11-28 · **Change:** minor (zh-Hans catalog covers the fixed UI strings, with a Han system-font fallback and an OFL web subset; previously minor: Spanish catalog completed, with native-speaker terminology review; previously minor: French and Spanish catalogs, partial; previously minor: pt-BR catalog completed: all fixed UI strings translated and covered by tests; native-speaker review, CJK/RTL font fallbacks and RTL script shaping still pending) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
SoundCraft defaults to English and supports selecting Brazilian Portuguese. The pt-BR catalog
|
||||
covers all fixed UI strings found in the current source: command labels, menus, Appearance,
|
||||
SoundCraft defaults to English and supports selecting Brazilian Portuguese, French, Spanish and
|
||||
Simplified Chinese. The Spanish catalog covers the same fixed UI strings and engine errors as pt-BR;
|
||||
the French catalog is partial (missing strings show in English). The pt-BR and zh-Hans catalogs
|
||||
cover all fixed UI strings found in the current source: command labels, menus, Appearance,
|
||||
About/Credits, Audio Health, Playback Engine, System Usage, Workspace, plugin parameter and display
|
||||
names, dialogs and buttons, tooltips (including those localized inside buttons and toggles),
|
||||
accessibility names, the Edit-window status bar, the remove-session question and formatted
|
||||
messages. Engine errors are matched against catalog templates at display time by
|
||||
`localization::error_text`. Values built at run time (file, track and device names), engine command
|
||||
parameter documentation and third-party plugin names stay as they are, and the catalog has not been
|
||||
independently or native-speaker reviewed. Pro Tools ships its UI in **8 languages** (bundle
|
||||
`.lproj` folders: English, German, Spanish, French, Japanese, Korean, Simplified Chinese,
|
||||
Traditional Chinese).
|
||||
`localization::error_text`; zh-Hans keeps engine diagnostics in English. Values built at run time
|
||||
(file, track and device names), engine command parameter documentation and third-party plugin names
|
||||
stay as they are, and neither the pt-BR nor the zh-Hans catalog has been independently or
|
||||
native-speaker reviewed. Pro Tools ships its UI in **8 languages** (bundle `.lproj` folders:
|
||||
English, German, Spanish, French, Japanese, Korean, Simplified Chinese, Traditional Chinese).
|
||||
|
||||
**Localization: ~12 %** (measured: 1 of the target's 8 UI languages, and English is the only one
|
||||
complete). Remaining ≈ 70–110 h: a catalog and extraction pass (≈ 15–25 h), a font fallback for
|
||||
CJK/Devanagari/Arabic (PR #141 open), RTL layout and complex-script shaping (egui has neither:
|
||||
≈ 25–40 h, or ship Arabic/Hindi menus-only), then ≈ 3–5 h of agent translation per language, plus
|
||||
native-speaker review (human).
|
||||
**Localization: ~19 %** (measured: 2 of the target's 8 UI languages, and neither translation has had
|
||||
a native-speaker pass). Remaining ≈ 55–90 h: RTL layout and complex-script shaping (egui has
|
||||
neither: ≈ 25–40 h, or ship Arabic/Hindi menus-only), the remaining catalogs (≈ 3–5 h of agent
|
||||
translation each), the Japanese/Korean font faces, and native-speaker review (human).
|
||||
|
||||
Open work: PR #143 (French and Spanish, a
|
||||
Language setting), PR #141 (bundled multilingual font fallbacks), issue #67 (Ukrainian).
|
||||
Open work: completing the French catalog (rows also kept in storytold/craft-i18n for
|
||||
when SoundCraft reads it), PR #141 (bundled multilingual font fallbacks), issue #67 (Ukrainian).
|
||||
|
||||
| Language | Code | UI strings translated | Dialogs / tooltips / help | Script support | Native review | Status | Est. to full (h) | In Pro Tools |
|
||||
|---|---|---|---|---|---|---|---:|---|
|
||||
| English | en | all (source) | ✅ | Latin ✅ | — | **full** | 0 | ✅ |
|
||||
| Simplified Chinese | zh-Hans | 0 (0 %) | ❌ | ❌ no CJK font fallback, no IME testing | no | none | 6–10 | ✅ |
|
||||
| Spanish | es | 0 (0 %) — PR #143 pending | ❌ | Latin ✅ | no | none | 3–5 | ✅ |
|
||||
| Simplified Chinese | zh-Hans | ✅ 100 % of fixed UI strings: menus, dialogs, buttons, tooltips, accessibility names, status bar, formatted messages | ✅ | Han ✅ (system font on the desktop, OFL subset on the web) | no | **full** | 0–4 (native review) | ✅ |
|
||||
| Spanish | es | ✅ 100 % of fixed UI strings (1,960) and engine errors (254), as pt-BR; catalog and menu-coverage tests pass | 🟡 partial | Latin ✅ | yes (es-ES, sound engineer; terminology reviewed) | full | 0–2 | ✅ |
|
||||
| Hindi | hi | 0 (0 %) | ❌ | ❌ no Devanagari font or shaping | no | none | 8–15 | ❌ |
|
||||
| Arabic | ar | 0 (0 %) | ❌ | ❌ no RTL layout, no shaping | no | none | 15–25 | ❌ |
|
||||
| French | fr | 0 (0 %) — PR #143 pending | ❌ | Latin ✅ | no | none | 3–5 | ✅ |
|
||||
|| Portuguese (Brazil) | pt-BR | ✅ 100 % of fixed UI strings: menus, dialogs, buttons, tooltips, accessibility names, status bar, formatted messages and engine errors; catalog tests pass | 🟡 partial | Latin ✅ | no (native review pending) | full | 0–4 | ❌ |
|
||||
| French | fr | 🟡 1,368 of ~2,210 catalog strings (≈ 62 %); engine errors not yet translated | 🟡 partial | Latin ✅ | no | partial | 1–3 | ✅ |
|
||||
| Portuguese (Brazil) | pt-BR | ✅ 100 % of fixed UI strings: menus, dialogs, buttons, tooltips, accessibility names, status bar, formatted messages and engine errors; catalog tests pass | 🟡 partial | Latin ✅ | no (native review pending) | full | 0–4 | ❌ |
|
||||
| Indonesian | id | 0 (0 %) | ❌ | Latin ✅ | no | none | 3–5 | ❌ |
|
||||
| Japanese | ja | 0 (0 %) | ❌ | ❌ no CJK font fallback, no IME testing | no | none | 6–10 | ✅ |
|
||||
| Japanese | ja | 0 (0 %) | ❌ | 🟡 Han fallback draws Japanese kanji, no kana face and no IME testing | no | none | 6–10 | ✅ |
|
||||
| German | de | 0 (0 %) | ❌ | Latin ✅ | no | none | 3–5 | ✅ |
|
||||
| Korean | ko | 0 (0 %) | ❌ | ❌ no Hangul font fallback | no | none | 6–10 | ✅ |
|
||||
| Korean | ko | 0 (0 %) | ❌ | 🟡 Hangul system-font fallback, no IME testing | no | none | 6–10 | ✅ |
|
||||
| Vietnamese | vi | 0 (0 %) | ❌ | 🟡 Latin with stacked diacritics, untested | no | none | 3–5 | ❌ |
|
||||
|
||||
Other languages shipped: **0**. (Pro Tools also ships Traditional Chinese, zh-Hant.)
|
||||
Other languages shipped: **2**. (Pro Tools also ships Traditional Chinese, zh-Hant.)
|
||||
|
||||
Per-language hours exclude the shared catalog and script work above.
|
||||
Per-language hours exclude the shared catalog and script work above. A Han face now ships for the
|
||||
desktop (system font, never redistributed) and the web (an OFL subset); Traditional Chinese and
|
||||
Japanese would need their own Han faces, since the fallback list is Simplified-first.
|
||||
|
||||
## Usage
|
||||
|
||||
- Pick the language in Appearance ▸ Language, or run the `ui.language` command with
|
||||
`{"language": "pt-BR"}` (or `"en"`); with no parameter it reports the current language.
|
||||
Example: `soundcraft-cli run --demo --cmd 'ui.language={"language":"pt-BR"}'`.
|
||||
`{"language": "pt-BR"}` (or `"en"`, `"fr"`, `"es"`, `"zh-Hans"`); with no parameter it reports the
|
||||
current language. Example: `soundcraft-cli run --demo --cmd 'ui.language={"language":"zh-Hans"}'`.
|
||||
- The choice is a global preference saved with the UI state (like the theme); recalling a saved
|
||||
window configuration does not change it.
|
||||
- Strings missing from the catalog fall back to English. Add one with a `"English text" => "translated text"`
|
||||
arm in `crates/ui-egui/locales/pt-BR/mod.rs`; tests check placeholder parity, duplicates and that every
|
||||
string passed to `text` / `localized_format!` has an entry.
|
||||
- Strings missing from the catalog fall back to English, and the tests check placeholder parity,
|
||||
duplicate keys and that every string passed to `text` / `localized_format!` has a pt-BR and a
|
||||
zh-Hans entry.
|
||||
- How a catalog is edited depends on how it is kept. pt-BR, fr and es are hand-written: add a
|
||||
`"English text" => "translated text"` arm to `crates/ui-egui/locales/<tag>/mod.rs`. zh-Hans is
|
||||
generated: add the row to `crates/ui-egui/src/i18n/zh-hans.tsv` and run
|
||||
`python3 docs/i18n/tools/gen_zh_hans_locale.py` — never edit the generated module by hand. See
|
||||
[localization.md](localization.md).
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | minor | Completed the Spanish catalog (all fixed UI strings and engine errors) with a native-speaker terminology review; Spanish menu-coverage test; the path prompt's `File path` and `Folder path` fields are translated apart from the Auto Pan `Path` parameter |
|
||||
| 2026-11-24 | minor | French and Spanish catalogs (`locales/fr`, `locales/es`, 1,368 strings each) from PR #143, on the `localization` layer; Appearance ▸ Language lists them; estimates unchanged |
|
||||
| 2026-11-22 | minor | Added the Simplified Chinese catalog on the shared `localization` module (1,383 strings, all menu labels and every `text`/`localized_format!` source covered), a Han system-font fallback ordered ahead of Hangul except for Korean, and a 1.1 MiB OFL Noto Sans SC subset for the web build; catalog and font tests added; localization estimate ~12 % → ~19 % |
|
||||
| 2026-11-13 | minor | Completed the pt-BR catalog: tooltips passed to buttons and toggles, `Not available yet.`, the send hover help, `no instrument`, the search placeholders, the Edit-window status bar (bit depth, track count, undo, ms/frame), the remove-session question and the transport/sample-rate readouts; engine errors now reach the status line through `error_text` |
|
||||
| 2026-11-05 | minor | Added persisted language selection, the `ui.language` command, English fallback and a pt-BR catalog (menus, dialogs, tooltips, accessibility text, formatted messages); added a Usage section and catalog tests |
|
||||
| 2026-10-10 | major | Created: English only, no catalog; the twelve key languages at 0 %; Pro Tools' 8 languages listed from its bundle |
|
||||
| 2026-10-10 | major | Created: English only, no catalog; the twelve key languages at 0 %; Pro Tools' 8 languages listed from its bundle |
|
||||
@@ -0,0 +1,121 @@
|
||||
# Simplified Chinese UI
|
||||
|
||||
SoundCraft's interface can be shown in **简体中文**. The catalog is compiled into the binary
|
||||
(`crates/ui-egui/locales/zh-Hans/mod.rs`), so there is nothing to install and no locale files to
|
||||
find at run time. It covers **every string the UI looks up literally** — menu items and path
|
||||
segments, command labels, dialogs, window titles, tooltips, status-bar and accessibility text and
|
||||
the formatted messages — and every reference menu label in `crates/engine/catalog/menus.txt`.
|
||||
Engine diagnostics and machine-facing surfaces stay English (see
|
||||
[What is translated](#what-is-translated)).
|
||||
|
||||
The mechanism is described in [`localization.md`](localization.md); wording decisions are in
|
||||
[`i18n/glossary.md`](i18n/glossary.md).
|
||||
|
||||
## Selecting the language
|
||||
|
||||
**Setup ▸ Appearance ▸ Language** lists **English** and **简体中文**. Choosing a language applies
|
||||
immediately — menus, panels, dialogs and window titles switch on the next frame, no restart.
|
||||
|
||||
Without the window, use the command:
|
||||
|
||||
```sh
|
||||
soundcraft-cli run --demo --cmd 'ui.language={"language":"zh-Hans"}'
|
||||
```
|
||||
|
||||
`ui.language` with no parameter reports the current language (`{"language":"en"}`), and an unknown
|
||||
tag is an error. The choice is a global preference saved with the UI state (like the theme), so it
|
||||
survives a restart; recalling a saved window configuration never changes it. In the browser the
|
||||
interface starts from `navigator.language`, and the saved preference wins once one exists.
|
||||
|
||||
## What is translated
|
||||
|
||||
English source strings stay in the code and are the lookup keys; the catalog maps them at draw
|
||||
time. Command ids, menu paths used for lookup, preference keys and values, file formats, the
|
||||
control protocol, the CLI and MCP never see translated text, and neither do values built at run
|
||||
time (file, track and device names) or third-party plugin names.
|
||||
|
||||
Engine error messages stay English: a half-translated diagnostic is worse than a whole one, and the
|
||||
`error_text` templates pt-BR carries are deliberately omitted here.
|
||||
|
||||
## Files
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `crates/ui-egui/src/i18n/zh-hans.tsv` | the translator-facing catalog: `context<TAB>English<TAB>translation`, escapes `\n`, `\t`, `\\` |
|
||||
| `crates/ui-egui/locales/zh-Hans/mod.rs` | generated from the TSV; the UI reads this |
|
||||
| `docs/i18n/tools/gen_zh_hans_locale.py` | regenerates the module (`--check` fails when stale) |
|
||||
| `assets/fonts/NotoSansSC-SoundCraftSubset.ttf` | web-only Han font subset, OFL-1.1 |
|
||||
| `docs/i18n/tools/subset_web_font.py` | regenerates the subset from the catalog's glyphs |
|
||||
|
||||
## Editing translations
|
||||
|
||||
```sh
|
||||
# 1. edit crates/ui-egui/src/i18n/zh-hans.tsv (one row per string)
|
||||
python3 docs/i18n/tools/gen_zh_hans_locale.py # 2. regenerate the module
|
||||
cargo test -p soundcraft-ui-egui --lib # 3. catalog and font tests
|
||||
```
|
||||
|
||||
Keep the English placeholders (`{name}`, `{}`, `{ms:.1}`) exactly as they are: a test compares them.
|
||||
Rows are keyed by the English source, so rewording English text requires updating the row with it.
|
||||
`@plural` rows pair `singular|plural` on one row because Chinese has no plural inflection.
|
||||
|
||||
Look the result up, don't guess: `cargo run -p soundcraft-ui-egui --example ui_shot -- out.png` with a
|
||||
script that sets the language, then read the PNG (and the accessibility tree) before claiming a
|
||||
screen is right.
|
||||
|
||||
## Terminology
|
||||
|
||||
The short table; the reasoning is in [`i18n/glossary.md`](i18n/glossary.md).
|
||||
|
||||
| English | 中文 | Note |
|
||||
|---|---|---|
|
||||
| Session | 会话 | |
|
||||
| Track | 轨道 | audio and MIDI alike; 音轨 reads as audio only |
|
||||
| Clip | 片段 | |
|
||||
| Bus | 总线 | |
|
||||
| Transport | 走带 | standard audio-engineering word |
|
||||
| Pan | 声像 | 规范 acoustics term |
|
||||
| Bypass | 旁通 | |
|
||||
| Record | 录音 | Record Enable = 启用录音 |
|
||||
| Preferences | 首选项 | |
|
||||
| Bounce | 导出 | |
|
||||
| Slip / Spot | 滑动 / 定位 | |
|
||||
| Meter (level) / Meter (time signature) | 电平表 / 拍号 | two senses, two words |
|
||||
| Undo / Redo | 撤销 / 重做 | |
|
||||
|
||||
## Fonts
|
||||
|
||||
egui's bundled faces carry no Han glyphs, so `crates/ui-egui/src/fonts.rs` appends a Han fallback in
|
||||
every family: the operating system's own face on the desktop (fontconfig `lang=zh-cn`, plus
|
||||
per-platform candidates), and the bundled Noto Sans SC subset in the browser, which has no system
|
||||
fonts. Han is ordered before the Hangul fallback for every language except Korean, so Chinese text
|
||||
never draws Korean-styled shapes on Linux where fontconfig resolves Noto Sans CJK's Korean face
|
||||
first.
|
||||
|
||||
The web subset is 1.1 MiB and must stay under 2 MiB (test-enforced). After a catalog change,
|
||||
rebuild it from a Noto Sans SC variable font (a `noto-cjk` release, Sans/Variable/OTF) and check the
|
||||
result:
|
||||
|
||||
```sh
|
||||
# <font>: a Noto Sans SC variable font (family "Noto Sans SC", wght axis) from a noto-cjk release
|
||||
python3 docs/i18n/tools/subset_web_font.py <font> # writes assets/fonts/…
|
||||
python3 docs/i18n/tools/subset_web_font.py --check # fails on drift
|
||||
```
|
||||
|
||||
The test that draws the whole catalog in every family fails until the subset covers the new
|
||||
characters.
|
||||
|
||||
## Validation
|
||||
|
||||
- every localized source string has a zh-Hans entry (test lists what is missing);
|
||||
- placeholders match the English source, keys are unique, every menu label is covered;
|
||||
- the bundled web face draws the whole catalog in every family and fits its budget;
|
||||
- with a system Han font installed, every family draws 轨道片段混音.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- Engine diagnostics stay English.
|
||||
- No native-speaker review yet; the catalog is AI-authored and should be read by a Chinese-speaking
|
||||
audio engineer before it is called finished.
|
||||
- Traditional Chinese (`zh-Hant`) is not shipped; the Han face list is Simplified-first.
|
||||
- No IME testing beyond what the platform provides, and no complex-script shaping (egui has none).
|
||||
@@ -0,0 +1,121 @@
|
||||
# Localization
|
||||
|
||||
SoundCraft's interface ships in English and 简体中文 (Simplified Chinese), and English source text
|
||||
is the key: the strings in the code are what the catalogs translate, so a missing translation falls
|
||||
back to readable English instead of an empty label. Catalogs are compiled into the binary; a
|
||||
release has no catalog files to install or find, and the web build carries them too.
|
||||
|
||||
This page describes the mechanism. For the Chinese catalog itself see
|
||||
[`localization-zh-hans.md`](localization-zh-hans.md); for terminology see
|
||||
[`i18n/glossary.md`](i18n/glossary.md); for coverage against the incumbent see
|
||||
[`localization-parity.md`](localization-parity.md).
|
||||
|
||||
## Supported languages
|
||||
|
||||
| Language | Code | Catalog | Notes |
|
||||
|---|---|---|---|
|
||||
| English (source) | `en` | — (the strings live in the code) | fallback for every catalog |
|
||||
| 简体中文 — Simplified Chinese | `zh-Hans` | [`crates/ui-egui/locales/zh-Hans/mod.rs`](../crates/ui-egui/locales/zh-Hans/mod.rs) | generated from [`zh-hans.tsv`](../crates/ui-egui/src/i18n/zh-hans.tsv) |
|
||||
| Português (Brasil) — Portuguese (Brazil) | `pt-BR` | [`crates/ui-egui/locales/pt-BR/mod.rs`](../crates/ui-egui/locales/pt-BR/mod.rs) | hand-written |
|
||||
|
||||
The registry is the `Language` enum in
|
||||
[`crates/ui-egui/src/localization.rs`](../crates/ui-egui/src/localization.rs): `ALL` is the order
|
||||
the Appearance window offers, `id()` is the tag stored in preferences, and `native_name()` is the
|
||||
English source name the menu draws through the catalog.
|
||||
|
||||
## How a string is localized
|
||||
|
||||
- `localization::text("English source")` returns the translation for the language entered for the
|
||||
current frame, or the source when the catalog has no entry.
|
||||
- `localized_format!("{name} send level", name = …)` translates the template and then fills it; the
|
||||
translation keeps the same placeholders (a test enforces that).
|
||||
- `localization::error_text(message)` matches an engine error against the catalog's error templates
|
||||
and carries the embedded values over, so a low-level library error stays in English rather than
|
||||
turning into a half-translated sentence.
|
||||
- A catalog module exposes `pub(super) fn translate(source: &str) -> Option<&'static str>` and, if
|
||||
it translates engine errors, `pub(super) const ERROR_TEMPLATES`.
|
||||
|
||||
Values built at run time (file, track and device names), command ids, menu paths used for lookup,
|
||||
preference keys and values, file formats, the control protocol and third-party plugin names are
|
||||
never translated. Engine diagnostics are English in the zh-Hans catalog by design; pt-BR carries
|
||||
error templates.
|
||||
|
||||
The zh-Hans module is generated: edit
|
||||
[`crates/ui-egui/src/i18n/zh-hans.tsv`](../crates/ui-egui/src/i18n/zh-hans.tsv) (one row per
|
||||
string, `context<TAB>English<TAB>translation`) and rerun
|
||||
|
||||
```sh
|
||||
python3 docs/i18n/tools/gen_zh_hans_locale.py # rewrite the locale module
|
||||
python3 docs/i18n/tools/gen_zh_hans_locale.py --check # fail when it is out of date
|
||||
```
|
||||
|
||||
The TSV is also the file `storytold/craft-i18n`'s `tools/sync_app.py` reads, so the catalog can move
|
||||
to the shared repository when SoundCraft takes that step.
|
||||
|
||||
## Choosing the language
|
||||
|
||||
`Setup ▸ Appearance ▸ Language` (or the `ui.language` command) selects it while the app runs, and
|
||||
the choice is a global preference saved with the UI state:
|
||||
|
||||
```sh
|
||||
soundcraft-cli run --demo --cmd 'ui.language={"language":"zh-Hans"}'
|
||||
```
|
||||
|
||||
With no parameter, `ui.language` reports the current language; an unknown tag is an error. In the
|
||||
browser the language starts from `navigator.language` and follows the saved preference once one
|
||||
exists.
|
||||
|
||||
## Fonts
|
||||
|
||||
egui's bundled faces carry no Han glyphs, so the interface needs a CJK fallback
|
||||
([`crates/ui-egui/src/fonts.rs`](../crates/ui-egui/src/fonts.rs)):
|
||||
|
||||
- Native builds append the operating system's own Han face after every family, resolved through
|
||||
fontconfig (`lang=zh-cn`) with a list of per-platform candidates; nothing is redistributed.
|
||||
- The web build cannot reach system fonts, so it embeds `assets/fonts/NotoSansSC-SoundCraftSubset.ttf`,
|
||||
a Noto Sans SC (OFL-1.1) subset at weight 400 covering the UI glyph set. Regenerate it after a
|
||||
catalog change with
|
||||
|
||||
```sh
|
||||
# <font>: a Noto Sans SC variable font from a noto-cjk release — any file whose family is
|
||||
# "Noto Sans SC" and that carries a wght axis
|
||||
python3 docs/i18n/tools/subset_web_font.py <font>
|
||||
python3 docs/i18n/tools/subset_web_font.py --check
|
||||
```
|
||||
|
||||
and keep [`ATTRIBUTION.md`](../ATTRIBUTION.md) in step; `cargo xtask assets` enforces that.
|
||||
- Han comes before the Hangul fallback for every interface language except Korean, so a Chinese
|
||||
interface and Chinese names draw Chinese shapes even where fontconfig would resolve the Korean
|
||||
face of Noto Sans CJK first.
|
||||
|
||||
## Tests and gates
|
||||
|
||||
`cargo test -p soundcraft-ui-egui` covers the catalog and the fonts:
|
||||
|
||||
- every catalog entry parses, keys are unique and translations keep the English placeholders;
|
||||
- every string passed to `localization::text` / `localized_format!` in `crates/ui-egui/src` has an
|
||||
entry in every shipped catalog, and every reference menu label is translated;
|
||||
- the bundled web face draws the whole zh-Hans catalog in every family and stays inside its 2 MiB
|
||||
budget;
|
||||
- with a system Han font installed, every family draws Chinese text.
|
||||
|
||||
`cargo xtask ci` runs those with the rest of the gates (fmt, clippy, assets, layers, wasm).
|
||||
|
||||
## Adding another language
|
||||
|
||||
1. Add a `locales/<tag>/mod.rs` with `translate` (and `ERROR_TEMPLATES` when engine errors should be
|
||||
translated), plus the `#[path]` module declaration in `localization.rs`.
|
||||
2. Add the `Language` variant: `ALL`, `id()`, `native_name()`, `text()`, and the `error_text`
|
||||
template arm.
|
||||
3. Translate `every_localized_source_string_has_a_catalog_entry`'s set (the test lists what is
|
||||
missing by file and string) and the menu labels.
|
||||
4. Add a font fallback for the script, and for the web build either bundle a subset or document the
|
||||
gap; extend `ATTRIBUTION.md` when a file is added.
|
||||
5. Update [`localization-parity.md`](localization-parity.md), `ROADMAP.md` and `docs/gaps.md`.
|
||||
|
||||
## Relation to `storytold/craft-i18n`
|
||||
|
||||
The org keeps shared translations in `craft-i18n` and reads them through an optional `CRAFT_I18N_DIR`
|
||||
build input. SoundCraft has not cut over (roadmap stage 3d): like pt-BR, this catalog lives in the
|
||||
repository, and its TSV is the pre-cutover file the sync script consumes, so a later migration only
|
||||
moves data.
|
||||
+6
-2
@@ -90,8 +90,12 @@ plugins), and WebAudio in the browser.
|
||||
the default player. `NSMicrophoneUsageDescription` explains the recording prompt.
|
||||
- **Signing** goes inside-out with the hardened runtime and a secure timestamp. The executable is
|
||||
signed first, then the bundle. There's no `--deep` on the final signature. `entitlements.plist`
|
||||
holds a single exception, `com.apple.security.device.audio-input`, without which the hardened
|
||||
runtime blocks recording.
|
||||
holds three exceptions: `com.apple.security.device.audio-input`, without which the hardened
|
||||
runtime blocks recording; `com.apple.security.cs.disable-library-validation`, without which
|
||||
`dlopen` refuses every third-party VST3/CLAP/AU bundle (signed by another Team ID); and
|
||||
`com.apple.security.cs.allow-unsigned-executable-memory`, without which plugin runtimes that
|
||||
create executable memory without `MAP_JIT` (UADx/PACE) are killed at load. The CLI is signed
|
||||
with the same entitlements because it hosts plugins too.
|
||||
- **Notarization:** the app is zipped and sent with `xcrun notarytool submit --wait`, then the
|
||||
ticket is stapled to the app. The app goes on a DMG (`hdiutil`, with an `Applications` link).
|
||||
The DMG is signed, notarized and stapled too.
|
||||
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
# SoundCraft roadmap: milestones and what's next
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (M6: long takes continue in a new file (#888); previously minor: MIDI input landed, the gate row needs checking on macOS and Windows; strict external-WAV AAF import; previously trivial: 28 built-in processors with the Frequency Shifter; G-05 estimate after Linux/X11 plugin editors; M15: partial pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (M15: Spanish catalog complete; previously trivial: M15: French and Spanish catalogs, partial; previously minor: M6: long takes continue in a new file (#888); previously minor: MIDI input landed, the gate row needs checking on macOS and Windows; strict external-WAV AAF import; previously trivial: 28 built-in processors with the Frequency Shifter; G-05 estimate after Linux/X11 plugin editors; M15: partial pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
Forward-looking plan. Status and numbers: [`../ROADMAP.md`](../ROADMAP.md) and
|
||||
[`target-app-parity.md`](target-app-parity.md); the ranked work list: [`gaps.md`](gaps.md).
|
||||
@@ -49,7 +49,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started.
|
||||
| M12 | **Hardware**: audio interfaces, MIDI devices, sync, control surfaces | ⬜ | 110–180 |
|
||||
| M13 | **Interchange**: AAF/OMF import/export, disk streaming | 🟡 strict external-WAV AAF import; export, OMF and disk streaming missing | 65–115 |
|
||||
| M14 | **Fidelity harness** against Pro Tools (null tests, plugin responses) | ⬜ | 20–30 |
|
||||
| M15 | **Localization**: catalog, fonts/RTL, the 8 Pro Tools languages first | 🟡 partial (pt-BR catalog; needs native review; PRs #141, #143 open) | 45–80 |
|
||||
| M15 | **Localization**: catalog, fonts/RTL, the 8 Pro Tools languages first | 🟡 partial (pt-BR and zh-Hans catalogs, zh-Hans with a CJK fallback; Spanish complete; French partial; pt-BR and zh-Hans need native review; PR #141 open) | 45–80 |
|
||||
| M16 | Built-in plugin depth, sidechain, ARA | ⬜ | 110–170 |
|
||||
| M17 | Immersive delivery (ADM BWF, object renderer, binaural) and video depth | ⬜ | 80–130 |
|
||||
|
||||
@@ -88,6 +88,9 @@ There is no `cargo xtask scorecard` in this repo; the measured number is `cargo
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | trivial | M15: Spanish catalog complete (UI strings and engine errors, native-speaker review). Estimates unchanged |
|
||||
| 2026-11-24 | trivial | M15: French and Spanish catalogs (partial, ≈ 62 %) on the `localization` layer (#143). Estimates unchanged |
|
||||
| 2026-11-22 | trivial | M15: the zh-Hans catalog covers the fixed UI strings, with a Han font fallback on the desktop and an OFL web subset; native review still pending |
|
||||
| 2026-11-18 | minor | MIDI input devices landed (G-02 shrunk); the MIDI gate row is unverified until checked on macOS and Windows |
|
||||
| 2026-11-14 | minor | M13 is in progress with strict external-WAV AAF import; the exchange gate still fails without AAF export, OMF or `.ptx`; estimates unchanged |
|
||||
| 2026-11-09 | trivial | 28 built-in processors with the Frequency Shifter |
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Send pan and mute automation
|
||||
|
||||
Last reviewed: 2026-10-14. Last updated: 2026-10-14.
|
||||
|
||||
Bus sends read supported `SendPan` and `SendMute` automation during mixing. Pan automation
|
||||
covers mono sources sent to ordinary stereo buses. Mute automation gates ordinary bus routes
|
||||
using the existing channel-routing matrix.
|
||||
|
||||
## Reading and fallback
|
||||
|
||||
A valid nonempty lane in an automation mode that reads overrides the corresponding static send
|
||||
control. A pan lane interpolates between knots and clamps finite values to -1 through 1. A mute
|
||||
lane holds each knot's value, clamps to 0 through 1 and gates the send at values of at least 0.5.
|
||||
Before the first knot, the reader holds its first value; at duplicate timestamps it uses the last
|
||||
knot at that position.
|
||||
|
||||
Off mode, an absent or empty lane, nonfinite point values or decreasing timestamps use the
|
||||
static control for the entire callback. This reader follows the existing mixer convention:
|
||||
`lane.enabled` does not independently gate reading. Global lane-enable and suspension semantics
|
||||
remain the existing mixer policy.
|
||||
|
||||
Each callback builds local forward cursors at the source-sample time represented by its send
|
||||
buffer. Seeking, looping or rendering irregular chunks does not reuse a cursor from an earlier
|
||||
callback. Reader initialization and per-frame lookup share that clock. Position, frame offset
|
||||
and sample age are combined in widened arithmetic before clamping once to the supported bounds.
|
||||
|
||||
## Delay accounting
|
||||
|
||||
Audio send clocks account for processor-declared active insert latency and alignment already
|
||||
applied to the selected buffer. Insert ages accumulate separately from the bounded delay-
|
||||
compensation field; its safety cap does not shorten a send's clock. This assumes processors
|
||||
report their delay accurately. Aux and folder sends also carry the upstream input bus's sample age, including
|
||||
known ages propagated through nested Aux paths. Post-fader Aux buffers include their applied
|
||||
alignment; the existing pre-fader Aux copy does not receive that alignment and uses its own age.
|
||||
Pre-fader audio-track buffers do receive their existing pre-fader alignment.
|
||||
|
||||
Direct bus outputs contribute the age after any additional output delay. A send tap excludes
|
||||
that later output delay, receiving processors and Master processing. Audio processing, routing,
|
||||
delay-line placement and offline latency removal retain their existing behavior.
|
||||
|
||||
Bus age metadata is rebuilt with each block and introduces no new dynamic collection. Equal
|
||||
known contribution ages retain a shared source clock. A sum of differently delayed contributors
|
||||
has no single source age; mixed or overflowing age metadata retains the earlier render-position
|
||||
clock for these send readers. This preserves the existing mixed-routing policy and does not
|
||||
claim complete graph delay compensation. Empty bus inputs use zero upstream age. When delay
|
||||
compensation is off, a known path still accounts for its actual processor delay.
|
||||
|
||||
## Routing compatibility
|
||||
|
||||
Without a qualifying pan lane, routing uses the current static matrix. Mono sends retain their
|
||||
static send pan; stereo sends retain their left/right routing even when a stored static send pan
|
||||
is nonzero. Automated stereo-send pan is outside this contribution.
|
||||
|
||||
A supported mute lane can override the static send mute, including unmuting it. Track mute and
|
||||
the existing solo/VCA suppression still take precedence. Pre-fader sends use the existing
|
||||
pre-fader buffer, post-fader sends use the existing processed buffer, and send level keeps its
|
||||
current reader and timing policy.
|
||||
|
||||
Mute gating preserves the ordinary matrix for mono folds, stereo and supported surround widths.
|
||||
Ambisonic routes and non-bus sends keep their existing handling. Main outputs, master processing,
|
||||
audio delay compensation, hosted-plugin parameter delivery and routing-error policies are unchanged.
|
||||
|
||||
## Callback work and verification
|
||||
|
||||
Pan gains are computed per sample only for supported automated mono-to-stereo sends. Mute uses
|
||||
a stepped gate at each sample. Static routing matrices and gated-path sparse taps are prepared outside the
|
||||
sample loop; automated mono-pan routing needs no matrix. The new helpers use local cursors and fixed
|
||||
stack storage without introducing heap allocation.
|
||||
|
||||
Lane validity is scanned once per callback over its stored points. Worst-case callback CPU and
|
||||
the allocation behavior of the complete mixer remain unmeasured.
|
||||
|
||||
Synthetic regressions exercise independent PCM expectations, all pan laws, mute knots, static
|
||||
fallback, pre/post-fader routing, send level, irregular chunks, seek/loop behavior, hostile
|
||||
timestamps and short buffers. Engine cases cover command history and native save/reopen.
|
||||
Static stereo compatibility checks use nonzero stored send-pan values and unchanged routing
|
||||
references.
|
||||
|
||||
Latency regressions cover the unrelated silent Maximizer case, pan and mute source clocks,
|
||||
Aux pre/post taps, nested upstream paths, subsequent output/processor delay, mixed-age fallback,
|
||||
negative positions and reset/seek behavior with synthetic audio.
|
||||
Unit regressions also check insert-age accounting beyond the delay-compensation cap and age overflow.
|
||||
|
||||
This contribution is limited to these send readers and bus-routing branches.
|
||||
|
||||
## Revision history
|
||||
|
||||
- 2026-10-14: Document supported bus-send automation, fallback, stereo compatibility and callback-work limits.
|
||||
- 2026-10-14: Account for the actual delayed send tap and known upstream bus ages; retain mixed-age timing limits.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Target-app parity: SoundCraft vs Avid Pro Tools
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-14 · **Change:** minor (Performance row: recording is to disk (#84, #888); scores unchanged; previously minor: strict external-WAV AAF import; previously trivial: Frequency Shifter: 28 built-in processors; G-09/localization: pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 (bundle 26.4.1.179, macOS)
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-23 · **Change:** minor (archived the 27 October–15 November progress recap; Performance row: recording is to disk (#84, #888); scores unchanged; previously minor: strict external-WAV AAF import; previously trivial: Frequency Shifter: 28 built-in processors; G-09/localization: pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 (bundle 26.4.1.179, macOS)
|
||||
|
||||
The authoritative assessment of how close SoundCraft is to Pro Tools. [`ROADMAP.md`](../ROADMAP.md)
|
||||
summarizes it, [`gaps.md`](gaps.md) itemizes every shortfall, and the per-dimension docs go deeper:
|
||||
@@ -87,7 +87,7 @@ post-production, tracking) can switch. "Ready" is depth, correctness and fidelit
|
||||
| Performance | 5 % | **~35 %** | estimated (unmeasured) | 40–70 | [hardware-parity.md](hardware-parity.md) | Parallel strip rendering and PDC exist; whole files decoded into RAM, recording to disk (#84; long takes #888), no track-count or latency benchmarks |
|
||||
| Ecosystem / plugins | 4 % | **~30 %** | estimated | in Features + Hardware | [plugin-parity.md](plugin-parity.md) | CLAP/VST3/AU hosting; no AAX (Pro Tools' only format), no ARA, no sidechain, no control-surface ecosystem, no content library |
|
||||
| Platforms | 3 % | **~65 %** | estimated | 20–40 | [ROADMAP.md](../ROADMAP.md) | Builds for macOS, Windows x64/x86/arm64, Linux, FreeBSD, Web (Pro Tools: macOS, Windows), but only macOS is exercised at runtime; Web lacks file pickers (#63, #64) |
|
||||
| Localization | 2 % | **~12 %** | measured (catalog count) | 70–110 | [localization-parity.md](localization-parity.md) | English plus a pt-BR catalog (not native-reviewed); Pro Tools ships 8 UI languages; FR/ES PR #143 open |
|
||||
| Localization | 2 % | **~19 %** | measured (catalog count) | 55–90 | [localization-parity.md](localization-parity.md) | English, pt-BR, es, fr (partial) and zh-Hans catalogs (es native-reviewed); Han fallback on the desktop and an OFL subset on the web; Pro Tools ships 8 UI languages |
|
||||
| AI features | 1 % | **~5 %** | estimated | 30–50 | [gaps.md](gaps.md) | Pro Tools has speech-to-text transcription (upgraded in 2026.4); we have only an audio-to-MIDI pitch tracker |
|
||||
| **Weighted** | 100 % | **~40 %** | | **~950–1,450** (overlaps removed) | | |
|
||||
|
||||
@@ -245,6 +245,7 @@ serializes more, because it needs hands-on testing.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Historical ROADMAP sync over 27 October–15 November: releases v0.14.0–v0.20.1, clip drawing and edit-mode colours, Edit-window I/O volume and pan, Grid/Nudge time scales, a new-tracks workflow, device/buffer application (#1077), sample-accurate volume automation (#1355), session and format hardening (#892, #890, #995, #993), VST3 multi-out and offline-render support, BWF timecode, about a 20 % faster mix bounce in the #1144 demo benchmark and craft-libs cutovers; no new measurement of menu breadth, readiness or effort |
|
||||
| 2026-11-14 | minor | Strict external-WAV AAF import added to format, interchange and alpha-gate evidence; readiness estimates unchanged |
|
||||
| 2026-11-09 | trivial | Built-in plugin counts: 28 processors + 3 instruments with the Frequency Shifter. Percentages unchanged |
|
||||
| 2026-11-05 | trivial | Localization row: English plus a near-complete pt-BR catalog for fixed UI strings (PR #1346), not native-reviewed. Percentages and hours unchanged |
|
||||
|
||||
@@ -57,7 +57,7 @@ echo "==> SoundCraft $VERSION Flatpak bundle for $ARCH from $(basename "$TARBALL
|
||||
# host's disk before anything here could check it.
|
||||
MAX_UNPACKED_BYTES=$((2 * 1024 * 1024 * 1024))
|
||||
UNPACKED="$(tar --numeric-owner -tzvf "$TARBALL" | awk '{ s += $3 } END { print s + 0 }')"
|
||||
[ "$UNPACKED" -le "$MAX_UNPACKED_BYTES" ] || { echo "error: $TARBALL unpacks to $UNPACKED bytes, more than $MAX_UNPACKED_BYTES" >&2; exit 1; }
|
||||
[[ "$UNPACKED" -le "$MAX_UNPACKED_BYTES" ]] || { echo "error: $TARBALL unpacks to $UNPACKED bytes, more than $MAX_UNPACKED_BYTES" >&2; exit 1; }
|
||||
|
||||
WORK="$CARGO_TARGET_DIR/flatpak-bundle"
|
||||
rm -rf "$WORK"
|
||||
|
||||
@@ -100,6 +100,9 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$SOUNDCRAFT_BUILD_DATE/g" \
|
||||
"$HERE/$APP_ID.metainfo.xml.in" >"$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
|
||||
mkdir -p "$STAGE/usr/share/icons"
|
||||
cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/usr/share/icons/"
|
||||
# The compile-time embedded nightly icon lives in assets/app-icon/hicolor for include_bytes!;
|
||||
# exclude it from staged FHS icons so stable and nightly packages never collide on it.
|
||||
rm -f "$STAGE/usr/share/icons/hicolor/256x256/apps/$APP_ID-nightly.png"
|
||||
mkdir -p "$STAGE/usr/share/doc/soundcraft"
|
||||
copy_docs "$STAGE/usr/share/doc/soundcraft"
|
||||
# soundcraft-cli's man pages and shell completions, from its clap definition, written by the
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<!-- Hardened-runtime entitlements for SoundCraft. The app is pure Rust, loads no unsigned code,
|
||||
needs no JIT, and is not sandboxed (it opens files by path, from the command line and
|
||||
<!-- Hardened-runtime entitlements for SoundCraft. The host is Rust, loads third-party plugins,
|
||||
and is not sandboxed (it opens files by path, from the command line and
|
||||
drag-and-drop). Add exceptions here only with a reason in a comment. -->
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- VST3/CLAP/AU plugins are signed by their own developers (or ad hoc for local builds).
|
||||
Library validation otherwise rejects these modules in the signed host, even when
|
||||
discovery succeeds in an unpackaged build. -->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
<!-- Third-party plugin runtimes can create executable memory without MAP_JIT. UADx/PACE
|
||||
initialisation is killed with CODESIGNING/Invalid Page without this exception; allow-jit
|
||||
alone does not suffice. Keep executable-page protection and the hardened runtime enabled. -->
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<!-- Recording: the hardened runtime blocks audio input (CoreAudio via cpal) without this,
|
||||
even after the user grants microphone access (NSMicrophoneUsageDescription). -->
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
|
||||
@@ -212,7 +212,9 @@ CLI_DIR="$WORK/soundcraft-cli-$VERSION-macos-$ARCH"
|
||||
mkdir -p "$CLI_DIR"
|
||||
cp "$WORK/bin/soundcraft-cli" "$CLI_DIR/"
|
||||
copy_docs "$CLI_DIR"
|
||||
sign --options runtime "$CLI_DIR/soundcraft-cli"
|
||||
# The CLI runs the same engine and hosts plugins too, so it needs the same entitlements (the
|
||||
# plugin exceptions) or third-party plugins fail to load there as well.
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$CLI_DIR/soundcraft-cli"
|
||||
codesign --verify --strict --verbose=2 "$CLI_DIR/soundcraft-cli"
|
||||
rm -f "$CLI_ZIP"
|
||||
ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP"
|
||||
|
||||
@@ -148,7 +148,7 @@ def reviewed_manual_actors(caller_source, policy):
|
||||
|
||||
|
||||
def caller_pin(name):
|
||||
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$",
|
||||
return re.findall(r"(?m)^ tooling-revision: (\S+)$",
|
||||
(ROOT / ".github/workflows" / name).read_text())[0]
|
||||
|
||||
|
||||
@@ -182,8 +182,8 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
producer_platforms(source.replace(" " + current + "\n", ""))
|
||||
|
||||
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
|
||||
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
|
||||
source = (ROOT / ".github/workflows" / workflow).read_text()
|
||||
for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
expected = NightlyEnabledCallers.GUARDS[name]
|
||||
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
|
||||
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
|
||||
@@ -192,15 +192,22 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
(indicator, expression), = job_conditions(jobs)
|
||||
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
|
||||
|
||||
def test_no_nightly_schedule_is_registered(self):
|
||||
for name, event in (("nightly.yml", "workflow_dispatch"),
|
||||
("nightly-sign.yml", "workflow_dispatch")):
|
||||
def test_nightly_triggers_and_schedule_match_review(self):
|
||||
expected_triggers = (
|
||||
("nightly.yml", [" schedule:", " workflow_dispatch:"]),
|
||||
("nightly-sign.yml", [" workflow_dispatch:"]),
|
||||
("nightly-dispatch.yml", [" workflow_run:"]),
|
||||
)
|
||||
for name, expected in expected_triggers:
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
|
||||
triggers = [line for line in events.splitlines() if line.startswith(" ")
|
||||
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
|
||||
self.assertEqual(triggers, expected, "schedule/activation needs explicit review")
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
crons = re.findall(r"(?m)^ - cron: '([^']+)'$", producer)
|
||||
self.assertEqual(crons, ["30 5 * * *"], "nightly schedule must match the reviewed cadence")
|
||||
|
||||
def test_signer_serialization_contract_is_enforced(self):
|
||||
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
|
||||
@@ -221,7 +228,7 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
assert_nightly_serialization(source.replace(old, new))
|
||||
|
||||
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml"):
|
||||
for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
executable = "\n".join(line for line in source.splitlines()
|
||||
if not line.lstrip().startswith("#"))
|
||||
@@ -307,7 +314,7 @@ class NightlyTrustAnchors(unittest.TestCase):
|
||||
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
|
||||
pins.update(uses)
|
||||
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
|
||||
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
|
||||
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
|
||||
|
||||
|
||||
class NightlyEnabledCallers(unittest.TestCase):
|
||||
@@ -319,6 +326,7 @@ class NightlyEnabledCallers(unittest.TestCase):
|
||||
"github.event_name == 'workflow_dispatch')",
|
||||
"nightly-sign.yml": "github.repository == 'storytold/soundcraft' && github.event_name == 'workflow_dispatch' && "
|
||||
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
|
||||
"nightly-dispatch.yml": "github.repository == 'storytold/soundcraft' && github.event_name == 'workflow_run'",
|
||||
}
|
||||
|
||||
def test_enabled_jobs_keep_exact_context_guards(self):
|
||||
@@ -335,7 +343,8 @@ class NightlyEnabledCallers(unittest.TestCase):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
|
||||
"automatic signer actor must match the scheduled dispatcher")
|
||||
|
||||
def test_an_actor_outside_the_release_managers_is_refused(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
@@ -719,7 +728,7 @@ def trust_closure_problems(workflows):
|
||||
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
|
||||
if name == "nightly-sign.yml":
|
||||
signer_calls += 1
|
||||
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
|
||||
if name != "nightly-sign.yml" or ref != "main":
|
||||
problems.append(name + " calls nightly-release.yml@" + ref)
|
||||
if workflow.lower() in ("release.yml", "release.yaml"):
|
||||
stable_callers.add(name)
|
||||
@@ -769,7 +778,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
|
||||
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
|
||||
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
|
||||
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
|
||||
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
|
||||
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
|
||||
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
|
||||
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
|
||||
}
|
||||
@@ -794,11 +803,22 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
|
||||
"the signer guard is exactly the reviewed repository, dispatch and signer-branch expression")
|
||||
self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), ["soundcraft"],
|
||||
"the shared signer needs the reviewed registry app")
|
||||
self.assertFalse((ROOT / ".github/workflows/nightly-dispatch.yml").exists(),
|
||||
"this app has no automatic transport; adding one needs its own reviewed PR")
|
||||
dispatch_path = ROOT / ".github/workflows/nightly-dispatch.yml"
|
||||
self.assertTrue(dispatch_path.exists(), "scheduled nightly requires the reviewed automatic transport")
|
||||
dispatch = dispatch_path.read_text()
|
||||
producer_name = re.findall(r"(?m)^name: (.+)$", (ROOT / ".github/workflows/nightly.yml").read_text())
|
||||
self.assertEqual(producer_name, ["SoundCraft unsigned nightly"])
|
||||
self.assertIn(f"workflows: [{producer_name[0]}]", dispatch)
|
||||
self.assertIn("branches: [main]", dispatch)
|
||||
self.assertIn("\npermissions: {}\n", dispatch)
|
||||
self.assertIn("'ref': 'refs/heads/" + SIGNER_BRANCH + "'", dispatch)
|
||||
self.assertIn("https://api.github.com/repos/storytold/soundcraft/actions/workflows/nightly-sign.yml/dispatches",
|
||||
dispatch)
|
||||
assert_caller_secrets(dispatch, "dispatch", set())
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(policy["release_branch"], SIGNER_BRANCH)
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
|
||||
"automatic signer actor must match the scheduled dispatcher")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+16
-2
@@ -87,5 +87,19 @@ A browser with neither WebGPU nor WebGL2 gets a message in place of the app.
|
||||
|
||||
Playback goes through WebAudio. Browsers only start an `AudioContext` after a user gesture, so
|
||||
the first click or key press in the page may be needed before sound is heard. In an iframe,
|
||||
`allow="autoplay"` lets the embedding page grant that up front. The web build has no recording,
|
||||
no native file dialogs and no control channel; it opens the synthesised demo session.
|
||||
`allow="autoplay"` lets the embedding page grant that up front. The web build has no recording
|
||||
and no native file dialogs; it opens the synthesised demo session. There is no TCP control channel, but the page can drive the same one through `window.soundcraft` (below).
|
||||
|
||||
## Driving it from the page (`window.soundcraft`)
|
||||
|
||||
Every SoundCraft web build puts `window.soundcraft` on the page, from [`craft-web-api`](https://github.com/storytold/craft-libs/tree/main/crates/web-api) (storytold/craft-libs#413), the same shape in every Craft app. `soundcraft.request(method, params)` calls any method of the control channel the desktop app serves (`docs/control-protocol.md`), and `execute(command, params)`, `commands()`, `docInspect(params)`, `uiInspect(params)` and `screenshot(params)` are shortcuts for the common ones. Each returns a Promise that resolves with the method's result and rejects with an `Error`; a call the app does not answer within 30 seconds rejects. At most 64 calls wait for the app at once: a call made while that many wait rejects at once, as busy. SoundCraft's control requests cannot be withdrawn, so a call that times out in the page still runs when the app reaches it, as it does for a desktop client that timed out.
|
||||
|
||||
```js
|
||||
const session = await soundcraft.docInspect(); // tracks, clips, routing
|
||||
await soundcraft.execute("track.new", { count: 2, format: "Stereo" });
|
||||
const { data } = await soundcraft.screenshot(); // the window as PNG (base64)
|
||||
```
|
||||
|
||||
The API is installed in every session. Playback still needs a user gesture before the browser starts audio.
|
||||
|
||||
The repository holds a real-browser check of this API, `apps/soundcraft-web/tests/page-api.mjs`. It serves a built copy of the site (`trunk build --release` in `apps/soundcraft-web`, or the unpacked zip), loads it in headless Chromium with Playwright, and drives all six functions, a command that changes the session, the rejection of an unknown method and of an unknown command, the screenshot, several calls at once, and a burst of calls beyond the limit (the ones over it are refused as busy, and a call afterwards is accepted). Run it with `node apps/soundcraft-web/tests/page-api.mjs <site folder>` from a folder where `playwright` is installed. It is not part of `cargo xtask ci`.
|
||||
|
||||
@@ -7,3 +7,5 @@ sonar.organization=storytold
|
||||
sonar.cpd.exclusions=crates/ui-egui/locales/**
|
||||
# Packaging verification scripts are standalone test suites, not covered by Rust coverage reports.
|
||||
sonar.coverage.exclusions=packaging/**
|
||||
# Browser test harness under apps/soundcraft-web/tests is test code, not production source.
|
||||
sonar.test.inclusions=apps/soundcraft-web/tests/**
|
||||
|
||||
Reference in New Issue
Block a user