mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-06 12:37:59 -06:00
Compare commits
247
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5bcd710d7 | ||
|
|
be4d197b5f | ||
|
|
efbcb74c3d | ||
|
|
2930c40002 | ||
|
|
15e189b7fb | ||
|
|
ce8cd8f897 | ||
|
|
5e090423b9 | ||
|
|
ce744fb9ab | ||
|
|
e21c406016 | ||
|
|
fb11e9268d | ||
|
|
9f0cc38b02 | ||
|
|
7e5a8d69e3 | ||
|
|
fc09513bc6 | ||
|
|
337f4db5cb | ||
|
|
5584e00693 | ||
|
|
a4193ccba5 | ||
|
|
1a4dbc3b10 | ||
|
|
671a0ceb2a | ||
|
|
46c86c5033 | ||
|
|
dc1cdc6c59 | ||
|
|
6ba76e46ff | ||
|
|
344d732f77 | ||
|
|
7f9e5e71ea | ||
|
|
bf69b6aa25 | ||
|
|
75b87c1394 | ||
|
|
2c187ba304 | ||
|
|
39e09f8b1e | ||
|
|
f9a110751d | ||
|
|
bc7e94a98b | ||
|
|
1010b23770 | ||
|
|
841c4a37c9 | ||
|
|
9c1f7b9fa0 | ||
|
|
7d6cbb1997 | ||
|
|
a67a063280 | ||
|
|
a3e10d89d7 | ||
|
|
15267be73b | ||
|
|
0a37c171e8 | ||
|
|
bb486228cd | ||
|
|
3b06aea7d0 | ||
|
|
7b4905c00e | ||
|
|
40497d7eca | ||
|
|
35dcf1d412 | ||
|
|
f155bba583 | ||
|
|
896de30146 | ||
|
|
681f40f566 | ||
|
|
a3c7f4edc7 | ||
|
|
7fe79e21ed | ||
|
|
d42ade0951 | ||
|
|
025cf1e0ba | ||
|
|
31dfc36766 | ||
|
|
7a563aca6e | ||
|
|
af7c16b570 | ||
|
|
60950ba884 | ||
|
|
c776bbd2b4 | ||
|
|
0f26696507 | ||
|
|
d1694ebfd5 | ||
|
|
66903aa4dc | ||
|
|
f5bcb64199 | ||
|
|
1e7dbcbe54 | ||
|
|
acdc3efbc6 | ||
|
|
eab00b3f01 | ||
|
|
865baa99f1 | ||
|
|
ab682bf54e | ||
|
|
728634732f | ||
|
|
f79cad0f16 | ||
|
|
adda9dab37 | ||
|
|
1dc1aac99a | ||
|
|
3988e34870 | ||
|
|
0c22b29d4a | ||
|
|
213c6aa0e4 | ||
|
|
c1a13d2e3e | ||
|
|
ef3b942d49 | ||
|
|
433c1d5b79 | ||
|
|
6aa38dc14a | ||
|
|
1f35225968 | ||
|
|
c5b3732085 | ||
|
|
474719ed0e | ||
|
|
58b3608bc5 | ||
|
|
7478ee70a7 | ||
|
|
c217d5edf6 | ||
|
|
70071415c9 | ||
|
|
e14357eff7 | ||
|
|
fdfe5aed76 | ||
|
|
91123a1b77 | ||
|
|
e336e68449 | ||
|
|
78dfb59b3b | ||
|
|
8b929d81b1 | ||
|
|
7f8f278b8a | ||
|
|
0fce3e7aba | ||
|
|
0894e882b8 | ||
|
|
4f91806d62 | ||
|
|
8f20500c9d | ||
|
|
81766eebb6 | ||
|
|
f07dc9e221 | ||
|
|
580ba762b0 | ||
|
|
2b21bf0853 | ||
|
|
441a356994 | ||
|
|
dd70599e24 | ||
|
|
c65ae92001 | ||
|
|
a92536f992 | ||
|
|
c876aa0de3 | ||
|
|
c8242560d7 | ||
|
|
417a326b90 | ||
|
|
3dcfa69e35 | ||
|
|
af9f2109ff | ||
|
|
b0562cbce0 | ||
|
|
c5d9c72707 | ||
|
|
97e38ba3c3 | ||
|
|
de4c997d6e | ||
|
|
fcc4b98745 | ||
|
|
481b7e6a68 | ||
|
|
0321122ad4 | ||
|
|
a587aadec5 | ||
|
|
cb0c7395d8 | ||
|
|
6338349f88 | ||
|
|
e652100a53 | ||
|
|
528c245e6f | ||
|
|
84e07209a6 | ||
|
|
5e0b41d291 | ||
|
|
d0c27acc5d | ||
|
|
30afd14075 | ||
|
|
92894ee20a | ||
|
|
c4bb7d12ac | ||
|
|
768c0f972d | ||
|
|
94bbac0711 | ||
|
|
8f513c84c2 | ||
|
|
0c9c1b8ef6 | ||
|
|
66b8e9ad42 | ||
|
|
daf06dfd7e | ||
|
|
d88b9dd19e | ||
|
|
f892550c91 | ||
|
|
005150eb6d | ||
|
|
8ebbad7c32 | ||
|
|
6fbaec65e8 | ||
|
|
404d49e0a9 | ||
|
|
5f0fe9bfb2 | ||
|
|
77c125f564 | ||
|
|
55078b0f23 | ||
|
|
a86949df15 | ||
|
|
4f7bb6796d | ||
|
|
72b061f31e | ||
|
|
fbf3bcd7a4 | ||
|
|
b34b86fd7e | ||
|
|
1111864d20 | ||
|
|
733a17ffa6 | ||
|
|
1b2c087f29 | ||
|
|
a66c29502b | ||
|
|
871f6f9fa7 | ||
|
|
faac329f43 | ||
|
|
308447df97 | ||
|
|
f741e775ef | ||
|
|
a58e54a93c | ||
|
|
2d8931da1d | ||
|
|
aa7c4436c7 | ||
|
|
6b8eeb6f67 | ||
|
|
d516f2c1d1 | ||
|
|
50810053fa | ||
|
|
c582bcb4d2 | ||
|
|
27b0373761 | ||
|
|
51415ca71d | ||
|
|
0f1064a4c0 | ||
|
|
774c07bd85 | ||
|
|
d574a079ff | ||
|
|
87d89ae302 | ||
|
|
7f8a5b39fc | ||
|
|
2c1d83e616 | ||
|
|
32ab49522f | ||
|
|
49af7e3857 | ||
|
|
a852af5495 | ||
|
|
39ff7fd004 | ||
|
|
8bd195f8eb | ||
|
|
7c5d5434b7 | ||
|
|
ec7bd5d0bb | ||
|
|
4eed24d4d0 | ||
|
|
aadf0b4da6 | ||
|
|
01379a61b3 | ||
|
|
8f5d5ec0ec | ||
|
|
70bdc7f046 | ||
|
|
4baaf8af30 | ||
|
|
64ef487e21 | ||
|
|
234990eb2a | ||
|
|
99810a6666 | ||
|
|
48fec6e40d | ||
|
|
cbadb1bcd6 | ||
|
|
cf6ea93d8e | ||
|
|
6bcb14b3bd | ||
|
|
170c329242 | ||
|
|
669a0ebcb6 | ||
|
|
0dd9f8f535 | ||
|
|
07bbb27289 | ||
|
|
2959d8d173 | ||
|
|
bbcb826f38 | ||
|
|
b56703843b | ||
|
|
a5906ce9c7 | ||
|
|
8305f68827 | ||
|
|
cb6fbac081 | ||
|
|
7b7f0ca22b | ||
|
|
751ff25d5f | ||
|
|
30ee5b5b22 | ||
|
|
052d8573bf | ||
|
|
2ef1a73ba6 | ||
|
|
aa1a6d3cbd | ||
|
|
1b99bf0e4f | ||
|
|
7dcb8daa22 | ||
|
|
72d4d9d638 | ||
|
|
a64f8f22e6 | ||
|
|
3d52c606ca | ||
|
|
7810959b59 | ||
|
|
69d336b021 | ||
|
|
55d4a89b98 | ||
|
|
30058888c7 | ||
|
|
245523a866 | ||
|
|
38694924aa | ||
|
|
f554274864 | ||
|
|
1480399413 | ||
|
|
87345598ca | ||
|
|
1125a5f0a1 | ||
|
|
817623090a | ||
|
|
5b604a5884 | ||
|
|
cf4fe7a29b | ||
|
|
6c7491e239 | ||
|
|
b301c7f1d2 | ||
|
|
cb8014ff9c | ||
|
|
5f1335bf8f | ||
|
|
bf62aa6db7 | ||
|
|
92a5ce9a29 | ||
|
|
8cec3da577 | ||
|
|
df1d064e5a | ||
|
|
eaf0634689 | ||
|
|
5787f4dc3b | ||
|
|
9774947acf | ||
|
|
82e3ce059b | ||
|
|
6287acf019 | ||
|
|
a90f96867e | ||
|
|
5c42c6c2f7 | ||
|
|
a9ef108e61 | ||
|
|
afc93c151b | ||
|
|
2f34f0f501 | ||
|
|
0a0b451db0 | ||
|
|
5f56c9f103 | ||
|
|
f2dfd76781 | ||
|
|
9b3b70ba57 | ||
|
|
c4037f27ab | ||
|
|
8b6d9c71fb | ||
|
|
f804014297 | ||
|
|
3d06c6e5b8 | ||
|
|
222f1aef35 |
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/soundcraft",
|
||||
"repository_id": 1408486424,
|
||||
"producer_workflow_id": 429730684,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"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": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
"echelon",
|
||||
"FredApps",
|
||||
"skylartaylor"
|
||||
],
|
||||
"max_age_seconds": 86400,
|
||||
"candidate_policy": {
|
||||
"schema": "craft-nightly-candidate-policy/v3",
|
||||
"epoch": "soundcraft-nightly-20261124",
|
||||
"repository": "storytold/soundcraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 380135771,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_soundcraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_soundcraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": []
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"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",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
name: Nightly build check
|
||||
|
||||
# Builds the isolated Nightly flavor on all three platforms without secrets and checks each
|
||||
# archive as the Launcher unpacks it. The real feed build and its signing live in the shared
|
||||
# producer and release-ref signer (craft-common-actions), which call the same app scripts; this
|
||||
# workflow exists so the three packaging paths are exercised on PRs and by hand.
|
||||
#
|
||||
# macOS runners are shared with release builds: the macOS leg runs only with the `full-ci` label
|
||||
# (as ci.yml's Windows legs), never by changed paths.
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a labelled PR cancels its older run. An event that will not build gets a group of
|
||||
# its own, so it never cancels a real build.
|
||||
concurrency:
|
||||
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Nightly Linux x86_64 (unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install the desktop build dependencies
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
date="$(date -u +%Y-%m-%d)"
|
||||
{
|
||||
echo "SOUNDCRAFT_BUILD_SHA=$sha"
|
||||
echo "SOUNDCRAFT_BUILD_DATE=$date"
|
||||
echo "SOUNDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the GUI-only Nightly tar
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
run: bash packaging/linux/nightly.sh --arch x86_64
|
||||
- name: Check the archive and the isolated launch protocol
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tz="$(mktemp -d)"
|
||||
archive="$RUNNER_TEMP/nightly-dist/soundcraft-$SOUNDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
|
||||
mkdir -p "$tz" && tar -xzf "$archive" -C "$tz"
|
||||
# Flat, allowlisted members only: the launcher, the GUI it starts, the Nightly icon and
|
||||
# the notices.
|
||||
members="$(tar -tzf "$archive" | grep -v '/$' | sort | tr '\n' ' ')"
|
||||
echo "$members"
|
||||
case "$members" in *soundcraft-cli*|*portable.txt*|*.desktop*) echo 'GUI-only tar contains a CLI, marker or desktop entry' >&2; exit 1;; esac
|
||||
test -x "$tz/soundcraft"
|
||||
test -x "$tz/soundcraft-bin"
|
||||
# The entry point is the launcher; the GUI beside it is what a launch starts with the
|
||||
# profile, so an unpacked tar is isolated too.
|
||||
head -n 1 "$tz/soundcraft" | grep -qx '#!/bin/sh' || { echo 'soundcraft is not the launcher' >&2; exit 1; }
|
||||
test -f "$tz/soundcraft-nightly.png"
|
||||
# The version query, plain and in the Launcher's form, with an empty environment (a shell
|
||||
# script needs PATH for dirname/readlink even when everything else is cleared).
|
||||
path=/usr/local/bin:/usr/bin:/bin
|
||||
home="$(mktemp -d)"; profile="$(mktemp -d)"; xdg="$(mktemp -d)"
|
||||
plain="$(env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" XDG_DATA_HOME="$xdg/d" XDG_CACHE_HOME="$xdg/k" XDG_STATE_HOME="$xdg/s" "$tz/soundcraft" --version)"
|
||||
test "$plain" = "SoundCraft $SOUNDCRAFT_VERSION (nightly-v1)" || { echo "plain query: $plain" >&2; exit 1; }
|
||||
launcher="$(env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" "$tz/soundcraft" --launch-profile nightly-v1 --profile-root "$profile" --version)"
|
||||
test "$launcher" = "SoundCraft $SOUNDCRAFT_VERSION (nightly-v1)" || { echo "launcher query: $launcher" >&2; exit 1; }
|
||||
# A native package refuses a Flatpak instance with exit status 2 (the same status whether or
|
||||
# not a display exists), and no stable folder is created.
|
||||
status=0
|
||||
env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" FLATPAK_ID=ai.storyteller.soundcraft "$tz/soundcraft" --launch-profile nightly-v1 --profile-root "$(mktemp -d)/p" -- >/dev/null 2>&1 || status=$?
|
||||
test "$status" -eq 2 || { echo "a Flatpak instance must be refused with exit status 2, got $status" >&2; exit 1; }
|
||||
# Look where the configured XDG folders actually point, not at $xdg/config and $xdg/data.
|
||||
for dir in "$xdg/c" "$xdg/d" "$xdg/k" "$xdg/s"; do test ! -e "$dir/soundcraft" || { echo "stable folder created: $dir/soundcraft" >&2; exit 1; }; done
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: soundcraft-nightly-linux-x86_64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
|
||||
windows:
|
||||
name: Nightly Windows x86_64 (unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$inPkg = $false
|
||||
$base = $null
|
||||
foreach ($line in Get-Content Cargo.toml) {
|
||||
if ($line -match '^\s*\[') { $inPkg = ($line.Trim() -eq '[workspace.package]'); continue }
|
||||
if ($inPkg -and $line -match '^\s*version\s*=\s*"([^"]+)"') { $base = $Matches[1].Split('-')[0]; break }
|
||||
}
|
||||
if (-not $base) { throw 'could not read [workspace.package] version from Cargo.toml' }
|
||||
$sha = (git rev-parse HEAD).Trim()
|
||||
$date = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd')
|
||||
$version = "$base-nightly.$($date.Replace('-','')).$env:GITHUB_RUN_NUMBER.$env:GITHUB_RUN_ATTEMPT.g$($sha.Substring(0,12))"
|
||||
"SOUNDCRAFT_BUILD_SHA=$sha" >> $env:GITHUB_ENV
|
||||
"SOUNDCRAFT_BUILD_DATE=$date" >> $env:GITHUB_ENV
|
||||
"SOUNDCRAFT_VERSION=$version" >> $env:GITHUB_ENV
|
||||
- name: Refuse signing material in the build environment
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/sign.ps1 -CheckBuildEnvironment
|
||||
- name: Build the GUI-only Nightly intermediate
|
||||
shell: pwsh
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly
|
||||
- name: Check the PE, the version and the archive payload
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$exe = Join-Path $env:RUNNER_TEMP 'nightly-targets/x86_64-pc-windows-msvc/release/soundcraft.exe'
|
||||
$bytes = [IO.File]::ReadAllBytes($exe)
|
||||
$pe = [BitConverter]::ToInt32($bytes, 0x3C)
|
||||
if ([BitConverter]::ToUInt16($bytes, $pe + 4) -ne 0x8664) { throw 'not an x86_64 executable' }
|
||||
if ([BitConverter]::ToUInt16($bytes, $pe + 0x5C) -ne 2) { throw 'not a Windows GUI subsystem executable' }
|
||||
$info = (Get-Item -LiteralPath $exe).VersionInfo
|
||||
if ($info.ProductName -ne 'SoundCraft Nightly') { throw "ProductName: $($info.ProductName)" }
|
||||
if ($info.ProductVersion -cne $env:SOUNDCRAFT_VERSION) { throw "ProductVersion: $($info.ProductVersion)" }
|
||||
$version = (& $exe --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $version -cne "SoundCraft $env:SOUNDCRAFT_VERSION (nightly-v1)") { throw "version query: $version" }
|
||||
$profile = Join-Path $env:RUNNER_TEMP 'nightly-profile'
|
||||
New-Item -ItemType Directory -Force -Path $profile | Out-Null
|
||||
$launcher = (& $exe --launch-profile nightly-v1 --profile-root $profile --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $launcher -cne "SoundCraft $env:SOUNDCRAFT_VERSION (nightly-v1)") { throw "launcher query: $launcher" }
|
||||
# A Nightly build without its profile is refused before any window (exit status 2). The
|
||||
# refusal dialog would need a desktop, so that path is covered by the Rust unit tests.
|
||||
$zip = Join-Path $env:RUNNER_TEMP "nightly-dist/soundcraft-$env:SOUNDCRAFT_VERSION-windows-x86_64-nightly.unsigned.zip"
|
||||
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
|
||||
try {
|
||||
$names = @($archive.Entries | ForEach-Object { $_.FullName })
|
||||
if ('soundcraft.exe' -notin $names) { throw 'no soundcraft.exe in the archive' }
|
||||
foreach ($forbidden in @('soundcraft-cli.exe', 'portable.txt', '.desktop')) {
|
||||
if (@($names | Where-Object { $_ -like "*$forbidden*" }).Count -ne 0) { throw "archive holds $forbidden" }
|
||||
}
|
||||
} finally { $archive.Dispose() }
|
||||
- name: Fixture suites
|
||||
shell: pwsh
|
||||
run: |
|
||||
./packaging/windows/nightly-package-tests.ps1 -FixtureRoot (Join-Path $env:RUNNER_TEMP 'nightly-fixtures')
|
||||
./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot (Join-Path $env:RUNNER_TEMP 'nightly-sign-fixtures')
|
||||
- name: Keep the unsigned intermediate
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: soundcraft-nightly-windows-x86_64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
|
||||
macos:
|
||||
name: Nightly macOS aarch64 (unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@main
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
date="$(date -u +%Y-%m-%d)"
|
||||
{
|
||||
echo "SOUNDCRAFT_BUILD_SHA=$sha"
|
||||
echo "SOUNDCRAFT_BUILD_DATE=$date"
|
||||
echo "SOUNDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly bundle
|
||||
env:
|
||||
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
- name: Check the archive and the bundle's version
|
||||
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/soundcraft-$SOUNDCRAFT_VERSION-macos-aarch64-nightly.zip"
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: soundcraft-nightly-macos-aarch64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-macos-aarch64-nightly.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 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.')
|
||||
@@ -0,0 +1,59 @@
|
||||
name: SoundCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
producer_run_id:
|
||||
description: Exact untrusted producer Actions run ID
|
||||
required: true
|
||||
type: string
|
||||
producer_run_attempt:
|
||||
description: Exact untrusted producer Actions run attempt
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: soundcraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/soundcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: main
|
||||
app-name: soundcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -0,0 +1,37 @@
|
||||
name: SoundCraft unsigned nightly
|
||||
|
||||
# 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:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
unsigned:
|
||||
# Actual context guards only; no inherited/platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/soundcraft' &&
|
||||
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
|
||||
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
|
||||
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
|
||||
# no OIDC, attestation write, release environment or platform secrets in compilation.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: main
|
||||
app-name: soundcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# 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"]'
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -49,3 +49,23 @@ jobs:
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
|
||||
nightly-synthetic-suites:
|
||||
# The macOS and Windows Nightly scripts, the flat Linux archive and its launchers, and the
|
||||
# shared caller contracts run as generated fixtures in seconds: no app build, no signing, no
|
||||
# secrets.
|
||||
name: Nightly synthetic suites (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites, the launcher tests and bash -n
|
||||
run: bash packaging/nightly-checks.sh
|
||||
|
||||
@@ -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' }}
|
||||
|
||||
|
||||
@@ -10,3 +10,11 @@ plan/
|
||||
/craft-fonts/
|
||||
plans/
|
||||
.DS_Store
|
||||
|
||||
__pycache__/
|
||||
|
||||
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
/craft-fonts
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
# Accessibility
|
||||
|
||||
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
|
||||
|
||||
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
|
||||
|
||||
## Supported environments and how accessibility works
|
||||
|
||||
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
|
||||
|
||||
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
|
||||
- **macOS:** NSAccessibility (VoiceOver)
|
||||
- **Linux and FreeBSD:** AT-SPI (Orca)
|
||||
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
|
||||
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
|
||||
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
|
||||
|
||||
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
|
||||
|
||||
## Known limitations and workarounds
|
||||
|
||||
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
|
||||
|
||||
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
|
||||
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
|
||||
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
|
||||
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
|
||||
|
||||
See [This application](#this-application) below for repository-specific links and details.
|
||||
|
||||
## Reporting an accessibility barrier
|
||||
|
||||
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
|
||||
|
||||
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
|
||||
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
|
||||
- **Helpful details to share (when convenient):**
|
||||
- What you were trying to do, what happened, and what you expected
|
||||
- Application version (or commit) and operating system or browser
|
||||
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
|
||||
|
||||
## How we respond
|
||||
|
||||
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
|
||||
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
|
||||
|
||||
## Note for contributors and coding agents
|
||||
|
||||
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
|
||||
|
||||
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
|
||||
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
|
||||
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
|
||||
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
|
||||
|
||||
## Ownership
|
||||
|
||||
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
|
||||
|
||||
## This application
|
||||
|
||||
**SoundCraft** (`storytold/soundcraft`) is an open-source digital audio workstation (DAW) written in pure Rust.
|
||||
|
||||
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
|
||||
- **Command-line and automation interface:** `soundcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
|
||||
- **Report an accessibility barrier:** [Open an issue in `storytold/soundcraft`](https://github.com/storytold/soundcraft/issues/new)
|
||||
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/soundcraft`](https://github.com/storytold/soundcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
|
||||
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/soundcraft`](https://github.com/storytold/soundcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
|
||||
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
|
||||
@@ -81,6 +81,7 @@ Layers, checked by `cargo xtask layers`; nothing below L6 depends on egui, efram
|
||||
- Audio formats, codecs and waveform peaks come from `craft-audio` in `storytold/craft-libs`; `soundcraft_model::FileFormat` maps them onto the session model.
|
||||
- Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`), each module with its own `specs()` registered in `crates/engine/src/cmd.rs`; UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Menus, shortcuts, CLI, control channel and MCP dispatch the same ids. Panels act through `engine.execute(id, params)`. Programmatic calls open no dialogs; `ui.menu.invoke` does.
|
||||
- Parity: `crates/engine/catalog/menus.txt` lists the reference menu leaves; `cargo xtask parity` writes `docs/parity-checklist.md`; a test enforces a floor that only rises.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): the parity report marks a leaf `headless: yes` only when the engine registry implements it (what `soundcraft-cli` and the MCP server load); the UI layer's `parity_with` extras never count. Other leaves take their `no`/`partial` value and `reach:` (`window`, `os`, `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or read `unknown`. When a command lands, drop or narrow its mark; `headless_marks_are_current` fails on one that only hides a `yes`.
|
||||
- Progress docs: `ROADMAP.md`, `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md` and the per-area `docs/*-parity.md`. Releases: `docs/releasing.md` (push to `release`; `cargo xtask version [set X.Y.Z]`). Control protocol: `docs/control-protocol.md`.
|
||||
|
||||
### Checks
|
||||
|
||||
+18
-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 |
|
||||
@@ -54,4 +65,8 @@ here. The subset uses default_fonts; the parent face uses monochrome_emoji_fonts
|
||||
| `assets/app-icon/soundcraft.icns` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft.ico` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/hicolor/` | SoundCraft contributors | original, rendered from `icon.svg` (16–512 px PNGs and the scalable SVG) | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly.png` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly-macos-512.png` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly.icns` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `assets/app-icon/soundcraft-nightly.ico` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
|
||||
| `docs/images/` | SoundCraft contributors | screenshots of SoundCraft rendered from the synthesised demo session | MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+1333
-100
File diff suppressed because it is too large
Load Diff
+37
-29
@@ -4,16 +4,16 @@ 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"
|
||||
repository = "https://github.com/storytold/soundcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# internal
|
||||
soundcraft-interchange = { path = "crates/interchange" }
|
||||
soundcraft-time = { path = "crates/time" }
|
||||
@@ -61,27 +61,35 @@ cpal = "0.18"
|
||||
midir = "=0.11.1"
|
||||
|
||||
# Which file paths stored in a session may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
# Video containers and bitstreams, shared with the other craft apps.
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# H.264 and ProRes codecs shared with the other Craft apps.
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
|
||||
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
|
||||
# Audio file formats, codecs and waveform overviews, shared with the other craft apps. It shares
|
||||
# types with craft-media, so both stay on one rev.
|
||||
# Standard MIDI Files and the note/controller model, shared with the other craft apps.
|
||||
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["decode", "lossless-encode", "peaks", "serde"] }
|
||||
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["serde"] }
|
||||
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["decode", "lossless-encode", "peaks", "serde"] }
|
||||
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# AAF property-stream framing, shared with the other craft apps.
|
||||
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# 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 = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["egui"] }
|
||||
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
|
||||
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 = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode
|
||||
# the framework's components draw in (craft-libs).
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
egui = { version = "0.37" }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -124,18 +132,18 @@ debug = 0
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
[patch.crates-io]
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -88,7 +88,7 @@ where things are.
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Automation and markers.</b> Breakpoint automation for volume, pan, mute, sends and every plugin parameter, written live in Write, Touch and Latch, plus memory locations and a big counter.</td>
|
||||
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64, x86, Arm), Linux (AppImage, deb, rpm, Flatpak), FreeBSD, and a WebAssembly build that runs in the browser.</td>
|
||||
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64 and ARM64), Linux (AppImage, deb, rpm, Flatpak, Arch), FreeBSD, and a WebAssembly build that runs in the browser.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img alt="The Video window showing a colour-bar test movie with a timecode burn-in, above a Video track with thumbnails in the Edit window" src="docs/images/video.png"></td>
|
||||
@@ -216,7 +216,9 @@ The realtime audio thread never writes a record itself: the logger keeps the fir
|
||||
Everything you can click is also a command with an id and JSON parameters, and the same commands
|
||||
are reachable from the menus, the keyboard, the command line, a JSON control channel and an
|
||||
[MCP](https://modelcontextprotocol.io) server. Programmatic calls never open dialogs, and
|
||||
`session.inspect` reports exactly what changed, so an agent can check its own work.
|
||||
`session.inspect` returns the session's current state (tracks, clips, mixer, markers) and the
|
||||
last undo and redo step labels, so an agent can check its own work by comparing inspections from
|
||||
before and after.
|
||||
|
||||
```sh
|
||||
# Headless: load the demo, turn the kick down, add an EQ, bounce.
|
||||
@@ -302,7 +304,9 @@ very welcome, in the issues or on Discord.
|
||||
|---|---|---|
|
||||
| x64 (64-bit Intel/AMD) | `soundcraft-<ver>-windows-x64.msi` | `soundcraft-<ver>-windows-x64-portable.zip` |
|
||||
| arm64 (Snapdragon and other ARM PCs) | `soundcraft-<ver>-windows-arm64.msi` | `soundcraft-<ver>-windows-arm64-portable.zip` |
|
||||
| x86 (32-bit) | `soundcraft-<ver>-windows-x86.msi` | `soundcraft-<ver>-windows-x86-portable.zip` |
|
||||
|
||||
For 32-bit Windows, [SoundCraft v0.18.0](https://github.com/storytold/soundcraft/releases/tag/v0.18.0)
|
||||
was the last release with both an x86 MSI and portable ZIP.
|
||||
|
||||
Installers and executables are code-signed.
|
||||
|
||||
@@ -340,15 +344,21 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
|
||||
| Flatpak | `soundcraft-<ver>-linux-x86_64.flatpak` | `soundcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
|
||||
| Debian/Ubuntu | `soundcraft-<ver>-linux-x86_64.deb` | `soundcraft-<ver>-linux-aarch64.deb` | |
|
||||
| Fedora/RHEL/openSUSE | `soundcraft-<ver>-linux-x86_64.rpm` | `soundcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Arch Linux | `soundcraft-<ver>-linux-x86_64.pkg.tar.zst` | `soundcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
|
||||
| Tarball | `soundcraft-<ver>-linux-x86_64.tar.gz` | `soundcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
RISC-V (riscv64): `soundcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (glibc 2.39+, e.g. Ubuntu 24.04).
|
||||
RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
|
||||
`soundcraft-<ver>-linux-riscv64.rpm`, and `soundcraft-<ver>-linux-riscv64.tar.gz`
|
||||
(glibc 2.39+, e.g. Ubuntu 24.04).
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Current prebuilt FreeBSD release packages require FreeBSD 15.1 or later. They are built using the shared FreeBSD 15.1-STABLE release target; older FreeBSD releases are not supported by these binaries.
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `soundcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
| aarch64 (ARM64) | `soundcraft-<ver>-freebsd-aarch64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
@@ -356,6 +366,24 @@ RISC-V (riscv64): `soundcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (glibc
|
||||
|---|---|---|
|
||||
| Static site | `soundcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
|
||||
### Nightly (ArtCraft Launcher only)
|
||||
|
||||
A separate build channel, `nightly-v1`, ships untested previews of main. It is a different app
|
||||
with a different identity, installed and updated by ArtCraft Launcher:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Package, macOS bundle and Linux identity | `ai.storyteller.soundcraft.nightly` |
|
||||
| Window app id and Windows taskbar id | `ai.storyteller.soundcraft.nightly-v1` |
|
||||
| Data (settings, autosaves, presets, logs) | the Launcher's `profiles/soundcraft` folder, never the stable one |
|
||||
| Launch | `soundcraft --launch-profile nightly-v1 --profile-root <dir> -- <files>` |
|
||||
| Version | `soundcraft --version` → `SoundCraft <x.y.z>-nightly.<date>.<run>.<attempt>.g<sha12> (nightly-v1)` |
|
||||
|
||||
It carries no updater, control server or file associations, and it refuses to start without its
|
||||
profile. Build artifacts are `soundcraft-<ver>-{windows-x86_64-nightly.zip,linux-x86_64-nightly.tar.gz,macos-aarch64-nightly.zip}`,
|
||||
made by `packaging/windows/nightly.ps1`, `packaging/linux/nightly.sh` and `packaging/macos/nightly.sh`;
|
||||
see `docs/nightly-release-preparation.md`. Nothing is enabled yet.
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
SoundCraft is one of the **Crafting Apps**: free, open-source creative tools from the
|
||||
|
||||
+15
-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: room tone fill, 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,7 +125,9 @@ 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-12:** Edit › Room Tone fills gaps with recorded silence instead of digital silence, beyond Pro Tools' own menus. Set Room Tone (`edit.room_tone_set`) takes the selected clip, or the selected part of it, as the session's room tone, and the session file keeps it. Fill Gaps with Room Tone (`edit.room_tone_fill`) puts ordinary, editable clips of that tone in every empty stretch of the selection on the selected audio tracks. When a gap is longer than the tone, the clips overlap with equal-power crossfades (10 ms by default) so the background keeps its level, and each gap's edges get a 2 ms fade so it doesn't click. Clear Room Tone forgets the tone and keeps the clips. A synthesised tone that doesn't repeat comes later. 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.
|
||||
- **2026-11-05:** Command-click in an automation lane adds a point at the clicked time and value with the current editing tool (#1394), using the existing Pencil mapping. Command-click preserves the existing selection and also works on the fallback volume lanes of Master, Aux and VCA tracks. Plain clicks and clip contents stay unchanged, and one Undo removes the new point. No readiness percentage change.
|
||||
@@ -133,10 +135,12 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
- **2026-10-27 (plugin editors on Linux):** VST3 editors and embedded CLAP editors open in a SoundCraft X11 host window on Linux and the BSDs (XWayland on Wayland desktops), resized on request and closed from its title bar; the host run loop (VST3 `Linux::IRunLoop`, CLAP `timer-support` and `posix-fd-support`) lets X11 editors read their display connection and repaint. Verified with Graillon 3 and Surge XT Effects (JUCE) in both formats (#527). No readiness percentage change.
|
||||
- **2026-10-25:** Alt+Shift+E (`view.zoom_toggle_cancel`) and an Alt-click on the Zoom Toggle button cancel Zoom Toggle and keep the current view: the zoom, the scroll and the track heights stay as they are, and the button is no longer lit. The next Zoom Toggle zooms in from that view and goes back to it. No readiness percentage change.
|
||||
- **2026-10-25:** Tracks and Groups and the Clip List sit in dock columns that run the Edit window's full height at its left and right edges, with the MIDI Editor under the session view between them; Mix docks Tracks and Groups at its left edge. A panel dragged onto a dock group joins it as a tab, stacks above or below it, or makes a new column; one dragged to an empty window edge makes a dock there. A list with no saved place reopens in its dock, and makes the dock again when it is gone. Preferences and window configurations saved with the earlier split-frame layouts load with the new default layouts and keep their other settings. No readiness percentage change.
|
||||
- **2026-10-25:** A vertical drag on a send's level moves it as finely with Ctrl (Command on a Mac) held as with Shift, as a fader's Ctrl-drag does. The Level and Pan sliders of a send's options menu, the Send window's pan knob and the tracks' pan knobs move a tenth as far for the same drag while Ctrl (Command on a Mac) is held. No readiness percentage change.
|
||||
- **2026-10-25:** Auto Pan moves the balance of a stereo track: the left channel's level falls as the position moves right and the right channel's as it moves left, at constant power, and each channel stays on its own side. At the center the track passes unchanged, so a wide or out-of-phase stereo image keeps its width, and the envelope follower follows the louder channel. No readiness percentage change.
|
||||
- **2026-10-24:** An Alt-click (Option-click on a Mac) on a parameter in the plugin window, the Clip Effects window or an AudioSuite plugin's window returns it to its default value, on a slider or a slider's value box, and in the plugin window on a choice list too, as an Alt-click returns a fader to 0 dB. In the plugin window and the Clip Effects window the reset is one undo step. While Alt is held, a drag on a slider leaves the value where it is. No readiness percentage change.
|
||||
- **2026-10-24:** The parameter sliders of the plugin window, the Clip Effects window and AudioSuite plugins move a tenth as far for the same drag while Ctrl (Command on a Mac) is held, as the Strip Silence sliders do. Logarithmic sliders move a tenth as far along the slider, and whole-number sliders stay on whole numbers. No readiness percentage change.
|
||||
- **2026-10-24:** The Strip Silence window's four sliders move a tenth as far for the same drag while Ctrl (Command on a Mac) is held, on the slider and on its value box. Pressing or releasing the key during a drag leaves the value where it is. The Threshold and Clip Start Pad boxes show one decimal place. No readiness percentage change.
|
||||
- **2026-10-24:** Clip › Unloop… opens the Unloop dialog. Remove deletes the loop iterations and keeps the source clip, and Flatten keeps each loop iteration as its own clip. No readiness percentage change.
|
||||
- **2026-10-24:** Clip List › Auto Rename (`clip.auto_rename`) sets the names that editing gives the clips it separates from the selected clips: a name, a starting number, a number of places (zeros before the number) and a suffix. The piece after each cut takes the next name, the piece before it keeps its name, and all the pieces count up one number sequence. Pieces that Strip Silence names with its own Rename fields, or removes, take no Auto Rename name. Copied clips keep their scheme when they are pasted, saved sessions hold the schemes, and Import Session Data brings them along. No readiness percentage change.
|
||||
- **2026-10-24:** While the Strip Silence window is open, the Edit window draws a rectangle around each range that Strip would keep on the selected tracks, padded by Clip Start Pad and Clip End Pad, and the rectangles follow the sliders as they move. They are removed when the window closes. `edit.strip_silence_preview` returns the same ranges without changing the session. No readiness percentage change.
|
||||
- **2026-10-24:** The Strip Silence window has a Rename button. It opens Rename Selected Clips, where a name, a starting number, a count of zeros and a suffix set the names of the clips that Strip, Extract and Separate leave in the selection (for example SFX023.Reel1, SFX024.Reel1). The app keeps the scheme for later uses of Strip Silence until the app quits, or until Clear and then OK empty it. No readiness percentage change.
|
||||
@@ -189,7 +193,12 @@ 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-12 | trivial | Progress log: room tone fill; 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 |
|
||||
| 2026-11-05 | trivial | Progress log: Command-click adds an undoable automation point (#1394); readiness estimates unchanged |
|
||||
|
||||
@@ -22,9 +22,12 @@ fn is_control_method(method: &str) -> bool {
|
||||
| "ui.move"
|
||||
| "ui.click"
|
||||
| "ui.drag"
|
||||
| "ui.scroll"
|
||||
| "ui.zoom"
|
||||
| "ui.key"
|
||||
| "ui.text"
|
||||
| "ui.screenshot"
|
||||
| "audio.health"
|
||||
| "app.quit"
|
||||
)
|
||||
}
|
||||
@@ -65,8 +68,14 @@ 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 [
|
||||
("ui.scroll", json!({"x": 120, "y": 80, "dx": 5, "dy": -15, "unit": "line"})),
|
||||
("ui.zoom", json!({"x": 120, "y": 80, "factor": 1.5, "steps": 4})),
|
||||
] {
|
||||
assert_eq!(app_request(method, params.clone()), (method.to_string(), params));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ fn write_help() -> &'static str {
|
||||
|
||||
/// soundcraft-cli: SoundCraft without a window
|
||||
#[derive(Parser)]
|
||||
#[command(name = "soundcraft-cli", version = long_version(), arg_required_else_help = true)]
|
||||
#[command(name = "soundcraft-cli", version = long_version(), propagate_version = true, arg_required_else_help = true)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
|
||||
@@ -40,9 +40,12 @@ pub(crate) fn parity(args: &ParityArgs, out: &mut dyn Write) -> Result<(), CliEr
|
||||
for m in p["per_menu"].as_array().cloned().unwrap_or_default() {
|
||||
md.push_str(&format!("| {} | {} | {} |\n", m["menu"].as_str().unwrap_or(""), m["implemented"], m["total"]));
|
||||
}
|
||||
md.push_str(&format!("\n{}\n", soundcraft_engine::catalog::headless_summary_line(&p)));
|
||||
md.push_str("A leaf the engine implements is `headless: yes`: `soundcraft-cli` and the MCP server load that registry. The rest carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n");
|
||||
md.push_str("\n## Not yet implemented\n\n");
|
||||
for m in p["missing"].as_array().cloned().unwrap_or_default() {
|
||||
md.push_str(&format!("- {}\n", m.as_str().unwrap_or("")));
|
||||
for m in p["headless_missing"].as_array().cloned().unwrap_or_default() {
|
||||
let reach = m["reach"].as_str().map(|r| format!(", reach: {r} ({})", m["why"].as_str().unwrap_or(""))).unwrap_or_default();
|
||||
md.push_str(&format!("- {}: headless: {}{reach}\n", m["path"].as_str().unwrap_or(""), m["headless"].as_str().unwrap_or("")));
|
||||
}
|
||||
if let Some(path) = &args.write {
|
||||
std::fs::write(path, &md).map_err(|source| CliError::File { path: path.clone(), source })?;
|
||||
|
||||
@@ -73,10 +73,11 @@ fn at_rate(pos: u64, from: u32, to: u32) -> u64 {
|
||||
fn write_replacing(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
let name = target.file_name().map_or_else(|| "output".into(), |n| n.to_string_lossy().into_owned());
|
||||
let tmp = target.with_file_name(format!(".{name}.{}.part", std::process::id()));
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let written = (|| {
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
std::fs::rename(&tmp, target)
|
||||
})();
|
||||
if written.is_err() {
|
||||
|
||||
@@ -29,6 +29,24 @@ use info::info;
|
||||
use mcp::mcp;
|
||||
use session::{run_cmds, script};
|
||||
|
||||
/// A Launcher-only protocol argument, in either the separate or the `=` form. Everything after
|
||||
/// `--` is a file name, so it is not inspected.
|
||||
fn launcher_protocol_flag(args: &[OsString]) -> Option<&'static str> {
|
||||
for arg in args {
|
||||
if arg == "--" {
|
||||
break;
|
||||
}
|
||||
let text = arg.to_string_lossy();
|
||||
if text == "--launch-profile" || text.starts_with("--launch-profile=") {
|
||||
return Some("--launch-profile");
|
||||
}
|
||||
if text == "--profile-root" || text.starts_with("--profile-root=") {
|
||||
return Some("--profile-root");
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The command line's clap definition.
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
@@ -44,6 +62,12 @@ where
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
// The Launcher's Nightly protocol belongs to the GUI alone. Refuse it here, with a usage error,
|
||||
// before the subcommand is parsed: `soundcraft-cli` never opens a profile root or a window.
|
||||
if let Some(flag) = launcher_protocol_flag(&args) {
|
||||
let _ = writeln!(err, "soundcraft-cli: {flag} belongs to SoundCraft Nightly; this is the command-line tool");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
@@ -81,3 +105,31 @@ fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Resul
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod launcher_protocol_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_launcher_only_protocol_is_a_usage_error_not_a_file() {
|
||||
for args in [
|
||||
vec!["--launch-profile", "nightly-v1", "--profile-root", "/tmp/profile", "--", "song.scraft"],
|
||||
vec!["--launch-profile=nightly-v1"],
|
||||
vec!["--profile-root=/tmp/profile"],
|
||||
vec!["convert", "in.wav", "--launch-profile", "nightly-v1"],
|
||||
] {
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = run(args.iter().map(OsString::from), &mut out, &mut err);
|
||||
assert_eq!(code, 2, "{args:?}");
|
||||
let message = String::from_utf8_lossy(&err);
|
||||
assert!(message.contains("SoundCraft Nightly"), "{args:?}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_after_the_delimiter_is_a_file_name() {
|
||||
let args: Vec<OsString> = ["convert", "--", "--launch-profile", "--profile-root=./x"].map(OsString::from).to_vec();
|
||||
assert_eq!(launcher_protocol_flag(&args), None);
|
||||
assert_eq!(launcher_protocol_flag(&[OsString::from("--profile-root"), OsString::from("/p")]), Some("--profile-root"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ pub(crate) fn run_cmds(args: &RunArgs, out: &mut dyn Write, err: &mut dyn Write)
|
||||
pub(crate) fn script(args: &ScriptArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let path = &args.file;
|
||||
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
|
||||
let mut e = load_engine(&args.engine, err)?;
|
||||
let keep = args.keep_going;
|
||||
let mut failed = false;
|
||||
|
||||
@@ -89,6 +89,19 @@ fn version_flags_print_the_long_version_to_stdout() {
|
||||
}
|
||||
}
|
||||
|
||||
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
|
||||
/// return without running it (`mcp` and `app` would otherwise wait on something).
|
||||
#[test]
|
||||
fn every_subcommand_prints_the_version() {
|
||||
let release = format!("{} ({} {})\n", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
|
||||
for sub in ["info", "convert", "run", "script", "commands", "describe", "app", "mcp", "parity", "plugins"] {
|
||||
for spelling in ["--version", "-V"] {
|
||||
let got = invoke(&[sub, spelling]);
|
||||
assert_eq!((got.code, got.stdout, got.stderr), (0, format!("soundcraft-cli-{sub} {release}"), String::new()), "{sub} {spelling}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_is_not_a_subcommand() {
|
||||
assert_usage_error(&invoke(&["version"]), "unrecognized subcommand 'version'");
|
||||
|
||||
@@ -26,6 +26,15 @@ fn invoke(dir: &Path, args: &[&str]) -> Output {
|
||||
Command::new(crate::common::soundcraft_cli_binary()).current_dir(dir).env("SOUNDCRAFT_NO_PREFS", "1").args(args).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_accepts_a_leading_utf8_bom() {
|
||||
let dir = Scratch::new();
|
||||
std::fs::write(dir.0.join("bom.txt"), "\u{feff}track.new {\"name\":\"BOM\",\"count\":1,\"format\":\"stereo\"}\n").unwrap();
|
||||
let output = invoke(&dir.0, &["script", "bom.txt"]);
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("track.new:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_going_runs_later_commands_and_finishes_but_reports_failure() {
|
||||
let dir = Scratch::new();
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -49,9 +49,10 @@ pub fn start() {
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
log::info!("soundcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
|
||||
}
|
||||
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() }))
|
||||
}),
|
||||
)
|
||||
@@ -224,12 +225,14 @@ impl eframe::App for WebShell {
|
||||
self.app.logic(ctx);
|
||||
// A prompt opened during this frame becomes a picker on the next one.
|
||||
self.take_path_prompt(ctx);
|
||||
self.app.close_path(ctx);
|
||||
}
|
||||
|
||||
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
|
||||
/// shell.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.app.before_input(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
|
||||
@@ -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
|
||||
@@ -48,3 +49,5 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["NSAppl
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# The Nightly flavor's explicit taskbar identity (process_identity.rs); stable sets none.
|
||||
winsafe = { version = "0.0.29", features = ["user", "shell"] }
|
||||
|
||||
@@ -4,24 +4,71 @@
|
||||
//! On every other target this does nothing. A missing resource compiler is a warning, so a
|
||||
//! cross-compile from macOS or Linux still links, unless `SOUNDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! into an error (for release builds).
|
||||
//!
|
||||
//! `SOUNDCRAFT_BUILD_CHANNEL=nightly-v1` compiles the isolated Nightly flavor: `cfg(soundcraft_nightly_v1)`,
|
||||
//! the Nightly icon, `ProductName "SoundCraft Nightly"` and the exact feed version as
|
||||
//! `ProductVersion` (the Launcher checks that field, not FileVersion). An unset, empty or `stable`
|
||||
//! channel is the stable build; anything else is a build error.
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(soundcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("SOUNDCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=soundcraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported SOUNDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/soundcraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/soundcraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_VERSION");
|
||||
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_OVERRIDE_VERSION");
|
||||
let built_version = if nightly {
|
||||
// The feed identity is SOUNDCRAFT_VERSION. The packaging scripts (packaging/env.sh and the
|
||||
// Linux package.sh, inherited from PhotoCraft) set the same value as
|
||||
// SOUNDCRAFT_OVERRIDE_VERSION, which is accepted as the one alias so both agree.
|
||||
let identity = std::env::var("SOUNDCRAFT_VERSION").or_else(|_| std::env::var("SOUNDCRAFT_OVERRIDE_VERSION"));
|
||||
match identity {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit SOUNDCRAFT_VERSION feed identity (SOUNDCRAFT_OVERRIDE_VERSION is accepted)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=SOUNDCRAFT_BUILT_VERSION={built_version}");
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/soundcraft.ico")
|
||||
.set("ProductName", "SoundCraft")
|
||||
.set("FileDescription", "SoundCraft digital audio workstation")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "SoundCraft Nightly" } else { "SoundCraft" })
|
||||
.set("FileDescription", if nightly { "SoundCraft Nightly digital audio workstation" } else { "SoundCraft digital audio workstation" })
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the SoundCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "soundcraft.exe")
|
||||
.set("InternalName", "soundcraft");
|
||||
if nightly {
|
||||
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("SOUNDCRAFT_REQUIRE_WINRES").is_some() {
|
||||
// The workspace denies `clippy::panic`, build scripts included: stop the build with
|
||||
// the reason on stderr.
|
||||
eprintln!("embedding Windows resources failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/soundcraft-nightly.ico" } else { "../../assets/app-icon/soundcraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/soundcraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/soundcraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.20.1-nightly.20261124.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.20.1",
|
||||
"0.20.1-nightly",
|
||||
"0.20.1-nightly.20261124",
|
||||
"0.20.1-nightly.20261124.17.1.gABCDEF012345",
|
||||
"0.20.1-nightly.20261124.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.20.1-nightly.20261124.1.1.gabcdef012345",
|
||||
"0.20.1-nightly.20261124.1.1.gabcdef012345/other",
|
||||
"0.20.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
use std::ffi::OsString;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(soundcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.20.1"), "0.20.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.20.1"), "0.20.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ use soundcraft_ui_egui::docking;
|
||||
|
||||
/// Portable mode (#268): this file beside the executable keeps settings, autosaves, presets and
|
||||
/// logs in [`PORTABLE_DATA_DIR`] next to it instead of the user profile.
|
||||
const PORTABLE_MARKER: &str = "portable.txt";
|
||||
const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Platform {
|
||||
@@ -32,10 +32,17 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<Path
|
||||
Platform::Other
|
||||
};
|
||||
let exe = std::env::current_exe().ok();
|
||||
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent))
|
||||
// The one place a validated Nightly profile replaces every data root: ui.json, Autosave/,
|
||||
// Presets/ and logs/ all hang off this folder, before any of them is first used.
|
||||
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent), crate::launch_profile::current().root())
|
||||
}
|
||||
|
||||
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
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 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());
|
||||
}
|
||||
if let Some(dir) = env(crate::env::CONFIG_DIR) {
|
||||
return (!dir.is_empty()).then(|| PathBuf::from(dir));
|
||||
}
|
||||
@@ -55,12 +62,26 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, e
|
||||
}
|
||||
}
|
||||
|
||||
/// Create `dir` if needed and prove a file can be written in it.
|
||||
fn writable(dir: &Path) -> std::io::Result<()> {
|
||||
/// Create `dir` if needed and prove a file can be written in it. The Nightly profile validator
|
||||
/// injects this same exclusive probe.
|
||||
///
|
||||
/// The probe never replaces an existing entry: `create_new` cannot truncate one, and a name that is
|
||||
/// already taken (an interrupted run, or a file someone else made) is left untouched while the next
|
||||
/// name is tried. Only a file this call created is removed again.
|
||||
pub(crate) fn writable(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let probe = dir.join(format!(".write-test-{}", std::process::id()));
|
||||
std::fs::write(&probe, b"")?;
|
||||
std::fs::remove_file(probe)
|
||||
for attempt in 0..8u32 {
|
||||
let probe = dir.join(format!(".write-test-{}-{attempt}", std::process::id()));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(file) => {
|
||||
drop(file);
|
||||
return std::fs::remove_file(probe);
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name"))
|
||||
}
|
||||
|
||||
/// Read bounded settings, recovering unreadable docking metadata independently of other settings.
|
||||
@@ -156,10 +177,16 @@ mod config_tests {
|
||||
app.ui = load_ui(&path).unwrap().unwrap();
|
||||
assert_eq!(app.ui.theme, soundcraft_ui_egui::theme::ThemeMode::Light);
|
||||
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), edit);
|
||||
assert_eq!(app.ui.mix_docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [140.0, 150.0, 280.0, 420.0]);
|
||||
assert_eq!(
|
||||
app.ui.mix_docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
|
||||
egui::Rect::from_min_size(egui::pos2(140.0, 150.0), egui::vec2(280.0, 420.0))
|
||||
);
|
||||
app.ui.window = MainWindow::Edit;
|
||||
app.run("ui.dock", serde_json::json!({"operation":"open","panel":"tracks"})).unwrap();
|
||||
assert_eq!(app.ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [80.0, 90.0, 260.0, 400.0]);
|
||||
assert_eq!(
|
||||
app.ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
|
||||
egui::Rect::from_min_size(egui::pos2(80.0, 90.0), egui::vec2(260.0, 400.0))
|
||||
);
|
||||
let mut invalid_mix = app.ui.clone();
|
||||
invalid_mix.mix_docking = soundcraft_ui_egui::docking::edit_default();
|
||||
let invalid_bytes = serde_json::to_vec(&invalid_mix).unwrap();
|
||||
@@ -251,7 +278,7 @@ mod config_tests {
|
||||
}
|
||||
|
||||
fn resolve(platform: Platform, vars: &[(&str, &str)]) -> Option<PathBuf> {
|
||||
config_dir_with(platform, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None)
|
||||
config_dir_with(platform, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -264,6 +291,7 @@ mod config_tests {
|
||||
Some(OsString::from("isolated/settings"))
|
||||
},
|
||||
None,
|
||||
None,
|
||||
);
|
||||
assert_eq!(actual, Some(PathBuf::from("isolated/settings")));
|
||||
}
|
||||
@@ -279,6 +307,7 @@ mod config_tests {
|
||||
assert_eq!(name, "SOUNDCRAFT_CONFIG_DIR");
|
||||
Some(OsString::new())
|
||||
},
|
||||
None,
|
||||
None
|
||||
),
|
||||
None
|
||||
@@ -318,7 +347,33 @@ mod config_tests {
|
||||
}
|
||||
|
||||
fn resolve_with_exe(vars: &[(&str, &str)], exe: &Path) -> Option<PathBuf> {
|
||||
config_dir_with(Platform::Windows, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), Some(exe))
|
||||
config_dir_with(Platform::Windows, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), Some(exe), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_validated_nightly_profile_replaces_every_settings_root() {
|
||||
let nightly = PathBuf::from("/launcher/profiles/soundcraft");
|
||||
let vars = [("SOUNDCRAFT_CONFIG_DIR", "/custom"), ("HOME", "/user"), ("APPDATA", "/roaming"), ("XDG_CONFIG_HOME", "/xdg")];
|
||||
for platform in [Platform::Mac, Platform::Windows, Platform::Other] {
|
||||
let dir = config_dir_with(
|
||||
platform,
|
||||
|name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))),
|
||||
None,
|
||||
Some(&nightly),
|
||||
);
|
||||
assert_eq!(dir, Some(nightly.clone()), "the profile wins over the variable and the platform default");
|
||||
}
|
||||
// Even an empty override variable cannot take the Nightly settings folder away.
|
||||
let dir = config_dir_with(Platform::Other, |_| Some(OsString::new()), None, Some(&nightly));
|
||||
assert_eq!(dir, Some(nightly.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stable_channel_keeps_its_own_resolution() {
|
||||
let vars = [("XDG_CONFIG_HOME", "/xdg")];
|
||||
let dir =
|
||||
config_dir_with(Platform::Other, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None, None);
|
||||
assert_eq!(dir, Some(PathBuf::from("/xdg/soundcraft")));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -326,6 +381,6 @@ mod config_tests {
|
||||
fn config_override_preserves_non_unicode_paths() {
|
||||
use std::os::unix::ffi::OsStringExt as _;
|
||||
let value = OsString::from_vec(b"isolated/\xff".to_vec());
|
||||
assert_eq!(config_dir_with(Platform::Mac, |_| Some(value.clone()), None), Some(PathBuf::from(value)));
|
||||
assert_eq!(config_dir_with(Platform::Mac, |_| Some(value.clone()), None, None), Some(PathBuf::from(value)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,14 @@ pub(crate) fn command() -> Command {
|
||||
LaunchArgs::command().mut_args(blank_env_is_unset)
|
||||
}
|
||||
|
||||
/// The command line for the selected channel. A Nightly window never inherits the stable
|
||||
/// `SOUNDCRAFT_CONTROL_PORT` variable: its control server is not started and the Launcher owns
|
||||
/// its lifecycle, so only its file list is meaningful.
|
||||
pub(crate) fn command_for_profile(nightly: bool) -> Command {
|
||||
let cmd = command();
|
||||
if nightly { cmd.mut_arg("control", |arg| arg.env(None)) } else { cmd }
|
||||
}
|
||||
|
||||
/// Parses the launch arguments (without the program name) with `cmd`, from [`command`]. macOS
|
||||
/// passes a process serial number (`-psn_…`) when an app is started from Finder on old versions:
|
||||
/// it is dropped first, unless it comes after `--`. A bad value from a variable is a usage error
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
//! 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::PathBuf;
|
||||
|
||||
use craft_nightly::{AppProfileSpec, Launch, Profile, ProfileError, StartupOptions};
|
||||
|
||||
use crate::build_flavor;
|
||||
|
||||
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"];
|
||||
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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 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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
|
||||
#[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),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with(|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
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 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" }
|
||||
}
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
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 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.
|
||||
@@ -166,7 +166,13 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
|
||||
let message = message.strip_suffix('\n').unwrap_or(message);
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
|
||||
// Control characters are written escaped: a message quoting a session file (a plugin id, a
|
||||
// path) must not start a line of its own in the log or steer the terminal.
|
||||
let mut escaped = String::with_capacity(message.len());
|
||||
for c in message.chars() {
|
||||
if c.is_control() { escaped.extend(c.escape_default()) } else { escaped.push(c) }
|
||||
}
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {escaped}\n")
|
||||
}
|
||||
|
||||
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
|
||||
|
||||
@@ -158,8 +158,15 @@ fn a_line_carries_time_level_thread_target_and_message() {
|
||||
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "soundcraft_mix", "eq_7band: the plugin did not accept its stored state"),
|
||||
"2026-10-08T07:59:17.728Z WARN [main] soundcraft_mix: eq_7band: the plugin did not accept its stored state\n"
|
||||
);
|
||||
// A multi-line message keeps its lines; the record still ends in exactly one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
// A message with breaks of its own stays one record; the record still ends in exactly one newline.
|
||||
assert!(
|
||||
format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\\nb\n"),
|
||||
"a break inside the message is escaped, the final one dropped"
|
||||
);
|
||||
assert!(
|
||||
format_line("t", log::Level::Error, "w", "x", "plugin \u{1b}[2J\r\n2026 INFO forged")
|
||||
.ends_with("x: plugin \\u{1b}[2J\\r\\n2026 INFO forged\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+184
-24
@@ -11,20 +11,26 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod config;
|
||||
mod control_server;
|
||||
mod env;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod graphics;
|
||||
mod launch_args;
|
||||
mod launch_profile;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod process_identity;
|
||||
mod switch;
|
||||
|
||||
use env::Env;
|
||||
use soundcraft_engine::Engine;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs};
|
||||
use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs, os_window};
|
||||
use std::sync::Arc;
|
||||
|
||||
struct App(SoundApp, Option<&'static logging::AppLogger>, Env, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
@@ -64,8 +70,6 @@ impl eframe::App for App {
|
||||
}
|
||||
if self.0.quit_requested {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
} else if ctx.input(|i| i.viewport().close_requested()) && dialogs::ask_to_save(&mut self.0, "app.quit", &serde_json::json!({})) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
soundcraft_ui_egui::fit_window_to_screen(ctx);
|
||||
let (inner, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().maximized.unwrap_or(false)));
|
||||
@@ -80,24 +84,26 @@ impl eframe::App for App {
|
||||
}
|
||||
// With the system menu bar there is no egui bar showing the window and dirty state, so the
|
||||
// title carries them; elsewhere the egui menu bar already does.
|
||||
let app_name = os_window::name_for(os_window::identity());
|
||||
let document = (self.0.engine.session().name.as_str(), self.0.engine.is_dirty());
|
||||
let title = if self.0.native_menu_bar {
|
||||
format!(
|
||||
"{}{} — SoundCraft — {}",
|
||||
self.0.engine.session().name,
|
||||
if self.0.engine.is_dirty() { " *" } else { "" },
|
||||
if self.0.ui.window == soundcraft_ui_egui::MainWindow::Edit { "Edit" } else { "Mix" }
|
||||
)
|
||||
let section = if self.0.ui.window == soundcraft_ui_egui::MainWindow::Edit { "Edit" } else { "Mix" };
|
||||
soundcraft_ui_egui::os_title_with_section(app_name, Some(document), section)
|
||||
} else {
|
||||
format!("{} — SoundCraft", self.0.engine.session().name)
|
||||
soundcraft_ui_egui::os_title(app_name, Some(document.0))
|
||||
};
|
||||
set_title(ctx, title);
|
||||
// Last: the runtime's close path, which asks about unsaved changes before the window closes.
|
||||
self.0.close_path(ctx);
|
||||
}
|
||||
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
|
||||
/// shell.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
soundcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
self.0.guarded(|app| app.ui(ui));
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
@@ -112,6 +118,9 @@ impl eframe::App for App {
|
||||
self.0.player = None;
|
||||
soundcraft_engine::shutdown_plugin_hosts();
|
||||
self.0.start_pending_update();
|
||||
// The binary's last step: on Nightly, finishing the session-health record. macOS ends the
|
||||
// process from inside AppKit's terminate, so this is that channel's only exit path.
|
||||
self.0.services.run_exit_hook();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,30 +183,120 @@ fn services() -> Services {
|
||||
d.save_file()
|
||||
})),
|
||||
pick_folder: Some(Box::new(|start: &std::path::Path| rfd::FileDialog::new().set_directory(start).pick_folder())),
|
||||
..Services::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The window, Dock, taskbar and Alt-Tab icon. macOS gets Apple's icon grid (transparent margin);
|
||||
/// elsewhere the full tile. Regenerate with `packaging/icons.sh`.
|
||||
fn app_icon() -> Option<egui::IconData> {
|
||||
let nightly = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
|
||||
#[cfg(target_os = "macos")]
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/soundcraft-macos-512.png");
|
||||
let png: &[u8] = if nightly {
|
||||
include_bytes!("../../../assets/app-icon/soundcraft-nightly-macos-512.png")
|
||||
} else {
|
||||
include_bytes!("../../../assets/app-icon/soundcraft-macos-512.png")
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft.png");
|
||||
let png: &[u8] = if nightly {
|
||||
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft-nightly.png")
|
||||
} else {
|
||||
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft.png")
|
||||
};
|
||||
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
|
||||
}
|
||||
|
||||
/// Set the immutable Windows AUMID for the Nightly flavor before any window or COM service.
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(
|
||||
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
|
||||
os_window::id_for(os_window::LaunchIdentity::NightlyV1),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// Report a refused launch profile on standard error, and in a dialog on a Windows or X11/Wayland
|
||||
/// desktop session: a Nightly build started from a file manager has no console to read. macOS keeps
|
||||
/// the console line, because a modal before its event loop never appears.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("SoundCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("SoundCraft launch profile: {error}");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("SoundCraft Nightly")
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any start-up service or side effect. `None` means
|
||||
/// this process is done: a version query already answered, or a refused profile (exit status 2).
|
||||
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` / `-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::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) = os_window::select_identity(identity) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.passthrough_args)
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
// The compiled identity, so About and diagnostics report the Nightly feed version verbatim.
|
||||
soundcraft_ui_egui::set_build_version(env!("SOUNDCRAFT_BUILT_VERSION").to_owned());
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
// Nightly has no updater of its own: ArtCraft Launcher carries the next build.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&soundcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if !launch_profile::current().is_nightly()
|
||||
&& let Some(result) = craft_update::self_update::finish(&soundcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// First, so every start-up record (and the engine's panic hook, installed with the first
|
||||
// Engine) is captured; see `logging`.
|
||||
let logger = logging::install(env::rust_log().as_deref());
|
||||
// Help, version and usage errors print and exit here, before a window or a log file exists.
|
||||
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
|
||||
let launch = launch_args::parse(launch_args::command_for_profile(launch_profile::current().is_nightly()), arguments).unwrap_or_else(|e| e.exit());
|
||||
// After the arguments and the logger: reading resolves the settings folder, which creates it,
|
||||
// and a malformed switch is logged.
|
||||
let env = Env::read();
|
||||
@@ -226,12 +325,12 @@ fn main() -> eframe::Result {
|
||||
let prefs = load_prefs(&env).unwrap_or_default();
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("SoundCraft")
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size(sane_window_size(prefs.window_size))
|
||||
.with_maximized(prefs.window_maximized)
|
||||
.with_min_inner_size([960.0, 600.0])
|
||||
.with_drag_and_drop(true)
|
||||
.with_app_id("ai.storyteller.soundcraft"),
|
||||
.with_app_id(os_window::app_id()),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
@@ -240,34 +339,77 @@ fn main() -> eframe::Result {
|
||||
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; SOUNDCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
if env.use_xwayland(std::env::var_os("DISPLAY").as_ref()) {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let forced_x11 = env.use_xwayland(std::env::var_os("DISPLAY").as_ref());
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let forced_x11 = false;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if forced_x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
eframe::run_native(
|
||||
"SoundCraft",
|
||||
// Nightly session health: an owned lease plus a record removed only by a clean exit, so the
|
||||
// next start can say when the previous one did not finish. Stable and a secondary window keep
|
||||
// their existing behaviour and touch nothing. No document names or paths are collected.
|
||||
let (nightly_session, session_health_warning) =
|
||||
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("SOUNDCRAFT_BUILT_VERSION"), None) {
|
||||
Ok(state) => state,
|
||||
Err(error) => {
|
||||
log::warn!("Nightly session health is unavailable: {error}");
|
||||
(None, true)
|
||||
}
|
||||
};
|
||||
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
// Set once a window has posted the interruption notice; until then the record must survive.
|
||||
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let notice_shown_in_callback = unclean_notice_shown.clone();
|
||||
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
|
||||
// The app's exit hook is the controlled return on macOS, where every quit ends the process
|
||||
// inside AppKit's terminate and `run_native` never returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed))
|
||||
};
|
||||
let result = eframe::run_native(
|
||||
os_window::name_for(os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
soundcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11)?;
|
||||
let player =
|
||||
if no_audio { None } else { Some(soundcraft_playback::Player::with_config(Arc::new(engine.session().clone()), &prefs.audio)) };
|
||||
let mut app = SoundApp::new(engine, player, services());
|
||||
app.set_startup_update_check(true);
|
||||
// Nightly is updated by ArtCraft Launcher only, never from inside the app.
|
||||
app.set_startup_update_check(!launch_profile::current().is_nightly());
|
||||
app.set_system_fonts(env.system_fonts());
|
||||
app.autosave_dir = env.config_dir.as_ref().map(|d| d.join("Autosave"));
|
||||
app.leftovers = app.autosave_dir.as_deref().map(soundcraft_engine::autosave::leftovers).unwrap_or_default();
|
||||
app.preset_dir = env.config_dir.as_ref().map(|d| d.join("Presets"));
|
||||
app.extra.ui_scale = prefs.ui_scale;
|
||||
app.ui = prefs;
|
||||
if let Some(port) = control_port {
|
||||
// The Nightly window has no control server: no inherited port, no stable token file.
|
||||
if let Some(port) = control_port.filter(|_| !launch_profile::current().is_nightly()) {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
if previous_nightly_unclean || session_health_warning {
|
||||
app.ui.status = if previous_nightly_unclean {
|
||||
"The previous SoundCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent.".to_owned()
|
||||
} else {
|
||||
"SoundCraft Nightly could not record session health in its private profile; abnormal-exit detection is unavailable.".to_owned()
|
||||
};
|
||||
notice_shown_in_callback.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
app.services.at_exit = Some(Box::new(finish_at_exit));
|
||||
}
|
||||
for f in &files {
|
||||
dialogs::open_path(&mut app, f);
|
||||
}
|
||||
@@ -291,7 +433,11 @@ fn main() -> eframe::Result {
|
||||
menu,
|
||||
)))
|
||||
}),
|
||||
)
|
||||
);
|
||||
// A controlled return, even for a handled start-up error. On macOS a window that was created
|
||||
// has already finished in its exit hook, so this is then a no-op.
|
||||
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
result
|
||||
}
|
||||
|
||||
/// A saved window size, or the default when the prefs file holds nonsense (NaN, negative, tiny).
|
||||
@@ -316,3 +462,17 @@ mod tests {
|
||||
assert_eq!(titles("Song * — SoundCraft"), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refusal_dialog_tests {
|
||||
use super::refusal_dialog;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! App-private Nightly session health, not telemetry or a Launcher protocol.
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
|
||||
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
|
||||
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
|
||||
/// still runs for a start that created no window.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through an exclusively created temporary file in the same directory.
|
||||
/// The temporary name is never reused and is opened with `create_new`, so an existing file or a
|
||||
/// link at either name is replaced rather than followed; a failure leaves `path` untouched.
|
||||
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write as _;
|
||||
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| io::Error::other(error.to_string()))?.as_nanos();
|
||||
let name = path.file_name().ok_or_else(|| io::Error::other("Nightly session state needs a file name"))?;
|
||||
let temporary = path.with_file_name(format!(".{}.{}.{nonce}.tmp", name.to_string_lossy(), std::process::id()));
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
|
||||
let written = (|| -> io::Result<()> {
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&temporary, path)
|
||||
})();
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage,
|
||||
/// while Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version, commit)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is stable or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
// Durable, exclusive creation: a raced destination link is replaced, never followed.
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed
|
||||
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
|
||||
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
|
||||
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
|
||||
/// An unwind, abort, forced exit or killed process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("soundcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unfinished.previous_unclean());
|
||||
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
|
||||
// Renderer initialization failed before the app callback: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The CPU retry (or the next start) still sees the interruption and shows it.
|
||||
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
|
||||
assert!(retry.previous_unclean());
|
||||
retry.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
// Without an earlier interruption, a handled failure still clears normally.
|
||||
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
|
||||
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
|
||||
assert!(data["commit"].is_null(), "missing provenance must not be invented");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IdentityError(String);
|
||||
|
||||
impl std::fmt::Display for IdentityError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentityError {}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
|
||||
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
Binary file not shown.
|
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.
|
||||
@@ -2,8 +2,4 @@ allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -70,6 +70,10 @@ sync_github_name = true
|
||||
real_name = "Kushagra Kumar"
|
||||
sync_github_name = true
|
||||
|
||||
[people.JonRC]
|
||||
real_name = "Jonathan Cardoso"
|
||||
display_name = "Jonathan Cardoso"
|
||||
|
||||
# Display name explicitly chosen by the contributor on 2026-10-19.
|
||||
[people.vhhr7]
|
||||
display_name = "Vic Herrera (@vhhr)"
|
||||
|
||||
@@ -182,6 +182,7 @@ fn writes(dir: &Path) -> Vec<(&'static str, Value)> {
|
||||
("file.print_score", json!({"path": p("k.svg")})),
|
||||
("file.export_clip_groups", json!({"path": p("l.scgrp"), "clips": [clip]})),
|
||||
("track.save_preset", json!({"path": p("m.json"), "tracks": ["Kick"]})),
|
||||
("setup.disk_allocation", json!({"path": p("recordings")})),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -301,6 +302,7 @@ fn links_out_of_the_roots_are_refused() {
|
||||
refused(&mut srv, "file.bounce_mix", json!({"path": s(f.write.join("away/x.wav"))}), "outside the write root");
|
||||
refused(&mut srv, "file.bounce_stems", json!({"dir": s(f.write.join("away/stems"))}), "outside the write root");
|
||||
refused(&mut srv, "session.save_as", json!({"path": s(f.write.join("away/x.scraft"))}), "outside the write root");
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"path": s(f.write.join("away/rec"))}), "outside the write root");
|
||||
refused(&mut srv, "file.bounce_mix", json!({"path": s(f.write.join("dangling.wav"))}), "a link that leads nowhere");
|
||||
assert_eq!(listing(&f.outside), before, "nothing was written through a link");
|
||||
assert!(!f.outside.join("not-yet.wav").exists());
|
||||
@@ -371,6 +373,56 @@ fn media_a_session_names_outside_the_read_root_is_not_loaded() {
|
||||
assert!(inspect(&mut free)["sources"].as_array().unwrap().iter().all(|x| x["loaded"] == true));
|
||||
}
|
||||
|
||||
/// `setup.disk_allocation` stores its path trimmed and cut to 200 characters, so that string is
|
||||
/// what gets checked. With the working folder as the write root, `" /abs/outside"` read as given
|
||||
/// would be `<cwd>/ /abs/outside` and pass, yet `/abs/outside` would be kept. The outside folder
|
||||
/// is the working directory's parent, so this does not depend on `TMPDIR`. A space at character
|
||||
/// 200 would be checked and then trimmed off again: `<pad>/link ` can sit inside the root while
|
||||
/// `<pad>/link` is a symlink out of it. An empty path still clears the setting.
|
||||
#[test]
|
||||
fn the_record_folder_is_checked_as_it_is_stored() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let outside = cwd.parent().expect("the working directory has a parent");
|
||||
let mut srv = demo_server(None, Some(&cwd));
|
||||
let spaced = format!(" {}", s(outside.join("rec")));
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"path": spaced}), "outside the write root");
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"track": "Kick", "path": spaced}), "outside the write root");
|
||||
ok(&mut srv, "setup.disk_allocation", json!({"path": " rec "}));
|
||||
ok(&mut srv, "setup.disk_allocation", json!({"path": ""}));
|
||||
ok(&mut srv, "setup.disk_allocation", json!({"path": " "}));
|
||||
|
||||
// Character 200 is a space, and more follows so the first trim leaves it. The cut used to
|
||||
// keep that space for the check and drop it when the same string was stored.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::symlink;
|
||||
// A folder of our own in the working folder: `create_dir` fails rather than reuse one that
|
||||
// is already there, so only what this run made is removed, and parallel runs don't meet.
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let own = format!("sc-record-{}-{nanos}", std::process::id());
|
||||
std::fs::create_dir(cwd.join(&own)).unwrap();
|
||||
struct RemoveDir(PathBuf);
|
||||
impl Drop for RemoveDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
let _cleanup = RemoveDir(cwd.join(&own));
|
||||
let tail = "/link";
|
||||
let pad = "d".repeat(199 - own.len() - 1 - tail.len());
|
||||
let rel = format!("{own}/{pad}{tail}");
|
||||
assert_eq!(rel.chars().count(), 199, "the stored path is 199 characters");
|
||||
let dir = cwd.join(&own).join(&pad);
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
symlink(outside, dir.join("link")).unwrap();
|
||||
let input = format!("{rel} x");
|
||||
assert_eq!(input.chars().nth(199), Some(' '), "character 200 is a space");
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"path": input}), "outside the write root");
|
||||
let reported = ok(&mut srv, "setup.disk_allocation", json!({}));
|
||||
assert!(!reported.contains(&pad), "a refused record folder was stored: {reported}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_roots_nothing_is_confined() {
|
||||
let f = fixture("free");
|
||||
|
||||
@@ -287,6 +287,11 @@ impl GuiLink {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
self.dispatch(&g);
|
||||
if g.created {
|
||||
// a timer-driven editor's WM_TIMERs and the paints they invalidate are starved while
|
||||
// the transport keeps the queue busy (#1447)
|
||||
if let Some(w) = &g.window {
|
||||
w.service();
|
||||
}
|
||||
let resize = self.host.gui_resize.swap(0, Ordering::Relaxed);
|
||||
if resize != 0
|
||||
&& let Some(win) = &g.window
|
||||
|
||||
@@ -16,6 +16,9 @@ impl HostWindow {
|
||||
clap_window_handle { ptr: std::ptr::null_mut() }
|
||||
}
|
||||
pub fn raise(&self) {}
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@ use clap_sys::ext::gui::clap_window_handle;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::OnceLock;
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
|
||||
use windows_sys::Win32::Graphics::Gdi::{RDW_ALLCHILDREN, RDW_UPDATENOW, RedrawWindow};
|
||||
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, GWL_EXSTYLE, GWL_STYLE,
|
||||
GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, RegisterClassExW, SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE,
|
||||
SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
|
||||
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GWL_EXSTYLE,
|
||||
GWL_STYLE, GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, MSG, PM_REMOVE, PeekMessageW, PostQuitMessage, RegisterClassExW,
|
||||
SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WM_QUIT, WM_TIMER,
|
||||
WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
|
||||
};
|
||||
|
||||
pub const SUPPORTED: bool = true;
|
||||
@@ -148,6 +150,18 @@ impl HostWindow {
|
||||
self.live().is_some_and(|h| unsafe { IsWindowVisible(h) } != 0)
|
||||
}
|
||||
|
||||
/// Per-frame service on the main thread (#1447): while the transport plays eframe always keeps a
|
||||
/// repaint pending, and Win32 only synthesizes `WM_TIMER` and `WM_PAINT` when the queue runs dry —
|
||||
/// so a timer-driven editor is starved until playback pauses. Dispatches the thread's pending
|
||||
/// timers (thread-wide on purpose: nothing else on this thread uses Win32 timers, and a timer
|
||||
/// with a `TIMERPROC` only runs through dispatch) and flushes the paint they invalidate.
|
||||
pub fn service(&self) {
|
||||
let Some(hwnd) = self.live() else { return };
|
||||
pump_timers();
|
||||
// SAFETY: a live window of this thread; ALLCHILDREN reaches the plugin's child windows.
|
||||
unsafe { RedrawWindow(hwnd, std::ptr::null(), std::ptr::null_mut(), RDW_UPDATENOW | RDW_ALLCHILDREN) };
|
||||
}
|
||||
|
||||
pub fn close(self) {
|
||||
if let Some(h) = self.live() {
|
||||
// SAFETY: our own live window; the plugin's GUI was destroyed first.
|
||||
@@ -168,3 +182,94 @@ pub fn resize(window: *mut c_void, w: f64, h: f64) {
|
||||
// SAFETY: as above; only the size changes.
|
||||
unsafe { SetWindowPos(window, std::ptr::null_mut(), 0, 0, ow, oh, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE) };
|
||||
}
|
||||
|
||||
/// Dispatches up to 32 `WM_TIMER`s pending on this thread (main thread only). The cap keeps a timer
|
||||
/// that re-arms on every dispatch from starving the frame; leftovers are served next tick.
|
||||
fn pump_timers() {
|
||||
// SAFETY: `PeekMessageW`/`DispatchMessageW`/`PostQuitMessage` on this thread's own queue;
|
||||
// `msg` outlives them all.
|
||||
unsafe {
|
||||
let mut msg: MSG = std::mem::zeroed();
|
||||
for _ in 0..32 {
|
||||
if PeekMessageW(&mut msg, std::ptr::null_mut(), WM_TIMER, WM_TIMER, PM_REMOVE) == 0 {
|
||||
break;
|
||||
}
|
||||
if msg.message == WM_QUIT {
|
||||
// PeekMessageW returns WM_QUIT regardless of the filter — repost it with its
|
||||
// exit code so the app's own message loop still sees the quit, and stop here.
|
||||
PostQuitMessage(msg.wParam as i32);
|
||||
break;
|
||||
}
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use windows_sys::Win32::Graphics::Gdi::{GetUpdateRect, InvalidateRect};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{KillTimer, SetTimer};
|
||||
|
||||
static FIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
unsafe extern "system" fn on_timer(hwnd: HWND, _msg: u32, _id: usize, _time: u32) {
|
||||
FIRED.fetch_add(1, Ordering::Relaxed);
|
||||
// SAFETY: a live window of this thread.
|
||||
unsafe { InvalidateRect(hwnd, std::ptr::null(), 1) };
|
||||
}
|
||||
|
||||
/// #1447: while the transport plays eframe always has a repaint pending, and Win32 only
|
||||
/// synthesizes `WM_TIMER`/`WM_PAINT` when the queue runs dry — an editor that animates from a
|
||||
/// timer freezes until Pause. `service` must dispatch the timer and its paint without a
|
||||
/// message loop ever waiting.
|
||||
#[test]
|
||||
fn an_editors_timer_and_paint_run_while_the_thread_never_waits_for_messages() {
|
||||
// windows are created and served on the app's UI thread — named "main" here.
|
||||
std::thread::Builder::new()
|
||||
.name("main".into())
|
||||
.spawn(|| {
|
||||
let window = HostWindow::new("timer test", 120.0, 80.0).expect("host window");
|
||||
let h = window.raw() as HWND;
|
||||
FIRED.store(0, Ordering::Relaxed);
|
||||
// SAFETY: live window of this thread; proc outlives the timer (killed below).
|
||||
unsafe { SetTimer(h, 1, 10, Some(on_timer)) };
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
assert_eq!(FIRED.load(Ordering::Relaxed), 0, "the timer fired without anyone pumping");
|
||||
window.service();
|
||||
assert!(FIRED.load(Ordering::Relaxed) > 0, "service() did not dispatch WM_TIMER");
|
||||
// SAFETY: `GetUpdateRect` accepts any window; false means the paint was flushed.
|
||||
assert_eq!(unsafe { GetUpdateRect(h, std::ptr::null_mut(), 0) }, 0, "the timer's paint is still pending");
|
||||
unsafe { KillTimer(h, 1) };
|
||||
window.close();
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("join");
|
||||
}
|
||||
|
||||
/// `PeekMessageW` returns `WM_QUIT` regardless of the filter range, so the pump can swallow
|
||||
/// the quit the app's own loop is waiting for. It must repost it — with its exit code — and
|
||||
/// stop, leaving the signal for the owning loop.
|
||||
#[test]
|
||||
fn the_pump_leaves_a_quit_and_its_exit_code_for_the_owning_loop() {
|
||||
std::thread::Builder::new()
|
||||
.name("main".into())
|
||||
.spawn(|| {
|
||||
// SAFETY: this thread owns the queue it posts to and peeks.
|
||||
unsafe { PostQuitMessage(7) };
|
||||
pump_timers();
|
||||
// SAFETY: `MSG` is a plain Win32 data struct made of integer and pointer fields,
|
||||
// so an all-zero value is valid initialized storage.
|
||||
let mut msg: MSG = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: `msg` is live owned storage, so `&mut msg` remains valid and writable
|
||||
// for the duration of the call.
|
||||
assert_ne!(unsafe { PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) }, 0, "the pump swallowed the quit");
|
||||
assert_eq!((msg.message, msg.wParam), (WM_QUIT, 7), "the quit signal or its exit code changed");
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("join");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,6 +142,9 @@ impl HostWindow {
|
||||
self.shown.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return false };
|
||||
x.pump();
|
||||
|
||||
@@ -153,6 +153,9 @@ impl RunLoop {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
#[test]
|
||||
fn timers_and_descriptors_follow_registration() {
|
||||
@@ -168,25 +171,21 @@ mod tests {
|
||||
assert_eq!(due, vec![a, b], "a late frame fires each timer once");
|
||||
assert!(rl.remove_timer(a) && !rl.remove_timer(a));
|
||||
assert_eq!(rl.due(t0 + Duration::from_secs(2)), vec![b]);
|
||||
let mut fds = [0; 2];
|
||||
// SAFETY: `fds` holds the two descriptors `pipe` writes.
|
||||
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
|
||||
assert!(rl.add_fd(fds[0], CLAP_POSIX_FD_READ));
|
||||
assert!(!rl.add_fd(fds[0], CLAP_POSIX_FD_READ), "registered once");
|
||||
// A connected stream has defined read and write readiness on both Linux and BSD.
|
||||
let (stream, mut peer) = UnixStream::pair().unwrap();
|
||||
let fd = stream.as_raw_fd();
|
||||
assert!(rl.add_fd(fd, CLAP_POSIX_FD_READ));
|
||||
assert!(!rl.add_fd(fd, CLAP_POSIX_FD_READ), "registered once");
|
||||
assert!(!rl.add_fd(-1, CLAP_POSIX_FD_READ));
|
||||
assert!(rl.ready().is_empty(), "nothing to read");
|
||||
// SAFETY: a valid one-byte buffer written to our own pipe.
|
||||
assert_eq!(unsafe { libc::write(fds[1], b"x".as_ptr().cast(), 1) }, 1);
|
||||
assert_eq!(rl.ready(), vec![(fds[0], CLAP_POSIX_FD_READ)]);
|
||||
assert!(rl.modify_fd(fds[0], CLAP_POSIX_FD_WRITE));
|
||||
assert!(rl.ready().is_empty(), "a read end never becomes writable");
|
||||
assert!(rl.remove_fd(fds[0]) && !rl.has_fd(fds[0]));
|
||||
peer.write_all(b"x").unwrap();
|
||||
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_READ)]);
|
||||
// The unread byte is still there, so reporting read as well would be a stale interest.
|
||||
assert!(rl.modify_fd(fd, CLAP_POSIX_FD_WRITE));
|
||||
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_WRITE)]);
|
||||
assert!(rl.remove_fd(fd) && !rl.has_fd(fd));
|
||||
assert!(rl.ready().is_empty(), "no callbacks for an unregistered descriptor");
|
||||
rl.clear();
|
||||
assert!(!rl.has_timer(b));
|
||||
// SAFETY: closing the pipe we opened.
|
||||
unsafe {
|
||||
libc::close(fds[0]);
|
||||
libc::close(fds[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ use std::sync::atomic::Ordering;
|
||||
|
||||
/// Largest block we activate a plugin for.
|
||||
const MAX_BLOCK: usize = 1 << 16;
|
||||
/// Most `on_main_thread` calls one `idle` runs for a plugin that keeps asking for more.
|
||||
const MAX_CALLBACKS_PER_IDLE: usize = 8;
|
||||
/// Most channels a host strip may ask for.
|
||||
const MAX_CHANNELS: usize = 64;
|
||||
/// Queue slots that only releases from `note_off` may take: one per key, so a queue that
|
||||
@@ -43,6 +45,8 @@ pub struct ClapPlugin {
|
||||
channels: usize,
|
||||
max_block: usize,
|
||||
latency: usize,
|
||||
/// What the last `prepare` was asked for, to restart the plugin the same way.
|
||||
prepared: Option<(f32, usize, usize)>,
|
||||
steady: i64,
|
||||
transport: Option<Transport>,
|
||||
}
|
||||
@@ -67,6 +71,7 @@ impl ClapPlugin {
|
||||
channels: 2,
|
||||
max_block: 0,
|
||||
latency: 0,
|
||||
prepared: None,
|
||||
steady: 0,
|
||||
transport: None,
|
||||
}
|
||||
@@ -231,6 +236,7 @@ impl Plugin for ClapPlugin {
|
||||
}
|
||||
|
||||
fn prepare(&mut self, sample_rate: f32, max_block: usize, channels: usize) {
|
||||
self.prepared = Some((sample_rate, max_block, channels));
|
||||
let sr = if sample_rate.is_finite() && sample_rate > 0.0 { f64::from(sample_rate) } else { 48_000.0 };
|
||||
let mb = max_block.clamp(1, MAX_BLOCK);
|
||||
self.channels = channels.clamp(1, MAX_CHANNELS);
|
||||
@@ -358,6 +364,25 @@ impl Plugin for ClapPlugin {
|
||||
self.latency
|
||||
}
|
||||
|
||||
fn idle(&mut self) {
|
||||
// A plugin that finds a new latency while processing asks for `on_main_thread`, and from
|
||||
// there for a restart (maybe after more callbacks): the new value only counts once it is
|
||||
// activated again. Run every callback it asks for here, a bounded number of them.
|
||||
for _ in 0..MAX_CALLBACKS_PER_IDLE {
|
||||
if !self.inst.state().callback.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
self.inst.service_callback();
|
||||
}
|
||||
if self.inst.state().restart.swap(false, Ordering::Relaxed) {
|
||||
if let Some((sr, mb, ch)) = self.prepared {
|
||||
self.prepare(sr, mb, ch);
|
||||
}
|
||||
} else if self.inst.is_active() && self.inst.state().latency_changed.swap(false, Ordering::Relaxed) {
|
||||
self.latency = self.inst.latency() as usize;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_transport(&mut self, transport: &Transport) {
|
||||
self.transport = Some(*transport);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Test-only CLAP plugins for soundcraft-clap-host: a gain effect and a "DC synth".
|
||||
//!
|
||||
//! - `org.soundcraft.test.gain`: stereo in/out, param 7 "Gain" (0..2, default 1), param 3 "Mode"
|
||||
//! (stepped enum A/B/C), hidden param 9, latency 3 samples.
|
||||
//! (stepped enum A/B/C), hidden param 9, latency 3 samples. Mode C needs 16: like LSP, the
|
||||
//! plugin finds that out in `process`, asks for `on_main_thread`, from there for a second
|
||||
//! `on_main_thread`, and from that one for a restart; it reports 16 once activated again.
|
||||
//! - `org.soundcraft.test.synth`: instrument, stereo out, CLAP note port; outputs a constant equal
|
||||
//! to the velocity of the held note (0 when none), switching at the event's sample offset. A
|
||||
//! MIDI CC 7 (volume) sets the constant to its value / 127. `reset` leaves the note sounding.
|
||||
@@ -99,6 +101,11 @@ struct Fx {
|
||||
gain: f64,
|
||||
mode: f64,
|
||||
level: f64,
|
||||
/// The latency the plugin was activated with, and whether it asked for a restart to change it.
|
||||
latency: u32,
|
||||
restart_wanted: bool,
|
||||
/// The first `on_main_thread` after a latency change only asks for another one.
|
||||
second_callback_asked: bool,
|
||||
active: bool,
|
||||
processing: bool,
|
||||
gui_created: bool,
|
||||
@@ -146,9 +153,14 @@ unsafe extern "C" fn activate(p: *const clap_plugin, sr: f64, min: u32, max: u32
|
||||
return false;
|
||||
}
|
||||
f.active = true;
|
||||
f.latency = latency_for(f.mode);
|
||||
true
|
||||
}
|
||||
|
||||
fn latency_for(mode: f64) -> u32 {
|
||||
if mode >= 2.0 { 16 } else { 3 }
|
||||
}
|
||||
|
||||
unsafe extern "C" fn deactivate(p: *const clap_plugin) {
|
||||
let f = unsafe { fx(p) };
|
||||
assert!(!f.processing, "deactivate while processing");
|
||||
@@ -310,6 +322,11 @@ unsafe extern "C" fn process(p: *const clap_plugin, pr: *const clap_process) ->
|
||||
unsafe { *o.add(i) = v };
|
||||
}
|
||||
}
|
||||
if latency_for(f.mode) != f.latency && !f.restart_wanted {
|
||||
f.restart_wanted = true;
|
||||
let host = unsafe { &*f.host };
|
||||
unsafe { (host.request_callback.unwrap())(f.host) };
|
||||
}
|
||||
CLAP_PROCESS_CONTINUE
|
||||
}
|
||||
|
||||
@@ -422,8 +439,8 @@ unsafe extern "C" fn ports_get(p: *const clap_plugin, index: u32, is_input: bool
|
||||
|
||||
static PORTS: clap_plugin_audio_ports = clap_plugin_audio_ports { count: Some(ports_count), get: Some(ports_get) };
|
||||
|
||||
unsafe extern "C" fn latency_get(_p: *const clap_plugin) -> u32 {
|
||||
3
|
||||
unsafe extern "C" fn latency_get(p: *const clap_plugin) -> u32 {
|
||||
unsafe { fx(p) }.latency
|
||||
}
|
||||
|
||||
static LATENCY: clap_plugin_latency = clap_plugin_latency { get: Some(latency_get) };
|
||||
@@ -586,7 +603,20 @@ unsafe extern "C" fn get_extension(p: *const clap_plugin, id: *const c_char) ->
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn on_main_thread(_p: *const clap_plugin) {}
|
||||
unsafe extern "C" fn on_main_thread(p: *const clap_plugin) {
|
||||
let f = unsafe { fx(p) };
|
||||
if !f.restart_wanted {
|
||||
return;
|
||||
}
|
||||
let host = unsafe { &*f.host };
|
||||
if std::mem::replace(&mut f.second_callback_asked, true) {
|
||||
f.restart_wanted = false;
|
||||
f.second_callback_asked = false;
|
||||
unsafe { (host.request_restart.unwrap())(f.host) };
|
||||
} else {
|
||||
unsafe { (host.request_callback.unwrap())(f.host) };
|
||||
}
|
||||
}
|
||||
|
||||
// ---- factory + entry ----
|
||||
|
||||
@@ -641,6 +671,9 @@ unsafe extern "C" fn factory_create(_f: *const clap_plugin_factory, host: *const
|
||||
gain: 1.0,
|
||||
mode: 0.0,
|
||||
level: 0.0,
|
||||
latency: 3,
|
||||
restart_wanted: false,
|
||||
second_callback_asked: false,
|
||||
active: false,
|
||||
processing: false,
|
||||
gui_created: false,
|
||||
|
||||
@@ -80,6 +80,27 @@ fn gain_processes_audio_and_follows_params() {
|
||||
p.process(&mut io, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_latency_counts_after_the_restart_the_plugin_asks_for() {
|
||||
fixture_dir();
|
||||
let mut p = soundcraft_clap_host::create(GAIN).unwrap();
|
||||
p.prepare(48_000.0, 64, 2);
|
||||
assert_eq!(p.latency(), 3);
|
||||
assert!(p.set_param("3", 2.0), "mode C takes 16 samples");
|
||||
let mut io = vec![vec![0.5f32; 64]; 2];
|
||||
p.process(&mut io, 64);
|
||||
assert_eq!(p.latency(), 3, "so far the plugin only asked for on_main_thread");
|
||||
// One idle runs both callbacks the plugin asks for (the second one asks for the restart).
|
||||
p.idle();
|
||||
assert_eq!(p.latency(), 16, "restarted with its new latency");
|
||||
assert_eq!(p.param("3"), Some(2.0));
|
||||
let mut io = vec![vec![0.5f32; 64]; 2];
|
||||
p.process(&mut io, 64);
|
||||
assert!(io[0].iter().all(|&x| (x - 0.5).abs() < 1e-6), "still processing after the restart: {:?}", &io[0][..4]);
|
||||
p.idle();
|
||||
assert_eq!(p.latency(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synth_plays_notes_at_their_offsets() {
|
||||
fixture_dir();
|
||||
|
||||
@@ -210,6 +210,15 @@ pub trait Plugin: Send {
|
||||
fn latency(&self) -> usize {
|
||||
0
|
||||
}
|
||||
/// Main-thread time between blocks, for hosted plugins: runs the callbacks the plugin asked
|
||||
/// for, restarts it when it asked to, and reads its latency again (some plugins only know it
|
||||
/// once they have processed). Offline renders call it after every block; the realtime audio
|
||||
/// thread never does.
|
||||
///
|
||||
/// For implementors: it runs between two `process` calls, on the thread that owns the instance,
|
||||
/// so it may allocate, block and re-activate the plugin, and it may change what `latency()`
|
||||
/// reports; callers read `latency()` again afterwards.
|
||||
fn idle(&mut self) {}
|
||||
/// How long the output keeps ringing after the input stops, in samples.
|
||||
fn tail_samples(&self) -> usize {
|
||||
0
|
||||
|
||||
@@ -33,6 +33,7 @@ winsafe = { version = "0.0.29", features = ["kernel"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cfb.workspace = true
|
||||
craft-aaf.workspace = true
|
||||
proptest.workspace = true
|
||||
zip.workspace = true
|
||||
|
||||
|
||||
@@ -478,6 +478,8 @@ pub fn create_unique_folder(parent: &Path, prefix: &str) -> std::io::Result<Path
|
||||
for _ in 0..16 {
|
||||
let random = |_| std::collections::hash_map::RandomState::new().build_hasher().finish();
|
||||
let dir = parent.join(format!("{prefix}-{:016x}{:016x}", random(0), random(1)));
|
||||
// Only Unix sets a mode on the builder, so elsewhere it is never mutated.
|
||||
#[cfg_attr(not(unix), allow(unused_mut))]
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
|
||||
@@ -96,6 +96,92 @@ pub fn is_placeholder(path: &str) -> bool {
|
||||
PLACEHOLDERS.contains(&path)
|
||||
}
|
||||
|
||||
/// RFC-0052 hand marks for catalog leaves the engine registry doesn't implement:
|
||||
/// `(path, headless, reach, why)`. A path ending in ` > ` marks every leaf under it; the longest
|
||||
/// matching path wins.
|
||||
///
|
||||
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
|
||||
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
|
||||
/// command, isn't one yet). `yes` is never written here: a leaf is `yes` only when the engine registry
|
||||
/// that `soundcraft-cli` and the MCP server load implements it. UI-layer ids (`parity_with`'s
|
||||
/// `extra`) don't count. An unmarked missing leaf is `unknown`. [`headless_errors`] rejects marks
|
||||
/// that match nothing or only hide a `yes`.
|
||||
pub const HEADLESS: &[(&str, &str, &str, &str)] = &[
|
||||
("File > Open > Project...", "no", "os", "online project service"),
|
||||
("File > Open > Sketch...", "no", "engine-gap", "sketch files could be opened by a command"),
|
||||
("File > Dashboard...", "no", "window", "the start dialog"),
|
||||
("File > Start Collaboration...", "no", "os", "online collaboration service"),
|
||||
("File > Import > ", "no", "engine-gap", "the import could be a command"),
|
||||
("File > Export > ", "no", "engine-gap", "the export could be a command"),
|
||||
("File > Sign In", "no", "os", "online account service"),
|
||||
("Edit > Automation > ", "no", "engine-gap", "automation copies could be commands"),
|
||||
("View > ", "no", "window", "shows or hides part of a desktop window"),
|
||||
("Track > Change Track Width > Show / Hide...", "no", "window", "a desktop dialog"),
|
||||
("Track > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
|
||||
("Clip > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
|
||||
("AudioSuite > ", "no", "engine-gap", "offline processing over the crates/dsp plug-ins could be commands"),
|
||||
("Options > Activate HEAT", "no", "engine-gap", "the processor could be an engine option"),
|
||||
("Setup > Machine Track Arming Profiles...", "no", "os", "external machine control hardware"),
|
||||
("Window > ", "no", "window", "opens or arranges a desktop window"),
|
||||
("Window > Collaboration > ", "no", "os", "online collaboration service"),
|
||||
("Window > Splice", "no", "os", "online sample service"),
|
||||
("Window > SoundFlow", "no", "os", "third-party automation service"),
|
||||
];
|
||||
|
||||
/// Whether a `HEADLESS` mark path covers a catalog leaf.
|
||||
fn mark_covers(mark: &str, leaf: &str) -> bool {
|
||||
mark == leaf || (mark.ends_with(" > ") && leaf.starts_with(mark))
|
||||
}
|
||||
|
||||
/// A leaf's RFC-0052 `headless:` value, `reach:` and reason: `yes` when the engine implements it,
|
||||
/// else the longest `marks` path that covers it, else `unknown`.
|
||||
pub fn headless_of<'a>(leaf: &str, in_engine: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) {
|
||||
if in_engine {
|
||||
return ("yes", None, "");
|
||||
}
|
||||
marks.iter().filter(|m| mark_covers(m.0, leaf)).max_by_key(|m| m.0.len()).map_or(("unknown", None, ""), |m| (m.1, Some(m.2), m.3))
|
||||
}
|
||||
|
||||
/// Problems with `marks` against `leaves` (`(path, in_engine)`): bad values, a mark that covers no
|
||||
/// leaf, and a mark whose leaves the engine all implements (it would only hide a `yes`).
|
||||
pub fn headless_errors(marks: &[(&str, &str, &str, &str)], leaves: &[(&str, bool)]) -> Vec<String> {
|
||||
let mut errs = Vec::new();
|
||||
for (i, (path, value, reach, _)) in marks.iter().enumerate() {
|
||||
if !matches!(*value, "no" | "partial") {
|
||||
errs.push(format!("headless mark `{path}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !matches!(*reach, "window" | "os" | "engine-gap") {
|
||||
errs.push(format!("headless mark `{path}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if marks[..i].iter().any(|m| m.0 == *path) {
|
||||
errs.push(format!("headless mark `{path}` is written twice"));
|
||||
}
|
||||
let covered: Vec<bool> = leaves.iter().filter(|l| mark_covers(path, l.0)).map(|l| l.1).collect();
|
||||
if covered.is_empty() {
|
||||
errs.push(format!("headless mark `{path}` matches no catalog leaf"));
|
||||
} else if covered.iter().all(|live| *live) {
|
||||
errs.push(format!("headless mark `{path}` is stale: the engine implements every leaf it covers"));
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
/// The RFC-0052 summary line for a [`parity_with`] report.
|
||||
pub fn headless_summary_line(p: &Value) -> String {
|
||||
let h = &p["headless"];
|
||||
let n = |v: &Value| v.as_u64().unwrap_or(0);
|
||||
format!(
|
||||
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**",
|
||||
n(&h["yes"]),
|
||||
n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]),
|
||||
n(&h["no"]["window"]),
|
||||
n(&h["no"]["os"]),
|
||||
n(&h["no"]["engine-gap"]),
|
||||
n(&h["partial"]),
|
||||
n(&h["unknown"]),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn catalog() -> Vec<&'static str> {
|
||||
MENUS.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
|
||||
}
|
||||
@@ -122,17 +208,27 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
|
||||
let mut done = 0usize;
|
||||
let mut missing = Vec::new();
|
||||
let mut per_menu: std::collections::BTreeMap<String, (usize, usize)> = Default::default();
|
||||
let mut headless: Vec<(&str, Option<&str>)> = Vec::new();
|
||||
let mut headless_missing = Vec::new();
|
||||
for e in &cat {
|
||||
let top = e.split(" > ").next().unwrap_or("").to_string();
|
||||
let slot = per_menu.entry(top).or_default();
|
||||
slot.1 += 1;
|
||||
if implemented_by(e, extra).is_some() {
|
||||
let in_engine = implemented_by(e, &[]).is_some();
|
||||
let (value, reach, why) = headless_of(e, in_engine, HEADLESS);
|
||||
headless.push((value, reach));
|
||||
if value != "yes" {
|
||||
headless_missing.push(json!({"path": e, "headless": value, "reach": reach, "why": why}));
|
||||
}
|
||||
if in_engine || (!extra.is_empty() && implemented_by(e, extra).is_some()) {
|
||||
done += 1;
|
||||
slot.0 += 1;
|
||||
} else {
|
||||
missing.push(*e);
|
||||
}
|
||||
}
|
||||
let count = |v: &str| headless.iter().filter(|h| h.0 == v).count();
|
||||
let no = |r: &str| headless.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count();
|
||||
let pct = if cat.is_empty() { 0.0 } else { done as f64 * 100.0 / cat.len() as f64 };
|
||||
json!({
|
||||
"total": cat.len(),
|
||||
@@ -140,6 +236,13 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
|
||||
"percent": (pct * 10.0).round() / 10.0,
|
||||
"per_menu": per_menu.iter().map(|(k, (d, t))| json!({"menu": k, "implemented": d, "total": t})).collect::<Vec<_>>(),
|
||||
"missing": missing,
|
||||
"headless": {
|
||||
"yes": count("yes"),
|
||||
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
|
||||
"partial": count("partial"),
|
||||
"unknown": count("unknown"),
|
||||
},
|
||||
"headless_missing": headless_missing,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -159,6 +262,51 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_are_current() {
|
||||
let leaves: Vec<(&str, bool)> = catalog().into_iter().map(|e| (e, implemented_by(e, &[]).is_some())).collect();
|
||||
let errs = headless_errors(HEADLESS, &leaves);
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_yes_is_the_engine_only() {
|
||||
let p = parity_json();
|
||||
let h = &p["headless"];
|
||||
assert_eq!(h["yes"], p["implemented"], "engine-only parity: every implemented leaf is yes");
|
||||
// AudioSuite has no engine command: every leaf is marked, none reads as reachable.
|
||||
let audiosuite: Vec<&Value> = p["headless_missing"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| m["path"].as_str().is_some_and(|x| x.starts_with("AudioSuite > ")))
|
||||
.collect();
|
||||
assert!(!audiosuite.is_empty());
|
||||
assert!(audiosuite.iter().all(|m| m["headless"] == "no" && m["reach"] == "engine-gap"));
|
||||
// A UI-layer alias makes a leaf implemented for the desktop report, not headless.
|
||||
let ui = [("Window > Mix", "window.mix")];
|
||||
let with_ui = parity_with(&ui);
|
||||
assert!(with_ui["implemented"].as_u64() > p["implemented"].as_u64());
|
||||
assert_eq!(with_ui["headless"], p["headless"]);
|
||||
assert!(headless_summary_line(&p).contains(&format!("{} yes", h["yes"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_pick_the_longest_path_and_refuse_bad_ones() {
|
||||
let marks = [("W > ", "no", "window", "a"), ("W > C > ", "no", "os", "b"), ("X", "partial", "engine-gap", "c")];
|
||||
assert_eq!(headless_of("W > C > M", false, &marks), ("no", Some("os"), "b"));
|
||||
assert_eq!(headless_of("W > Mix", false, &marks), ("no", Some("window"), "a"));
|
||||
assert_eq!(headless_of("W > Mix", true, &marks).0, "yes");
|
||||
assert_eq!(headless_of("Y", false, &marks).0, "unknown");
|
||||
assert_eq!(headless_of("WX", false, &marks).0, "unknown", "a prefix mark needs the separator");
|
||||
let leaves = [("W > Mix", false), ("X", true)];
|
||||
let bad = [("W > ", "yes", "window", ""), ("W > ", "no", "desk", ""), ("X", "no", "os", ""), ("Z", "no", "os", "")];
|
||||
let errs = headless_errors(&bad, &leaves);
|
||||
for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`X` is stale", "`Z` matches no catalog leaf"] {
|
||||
assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parity_floor() {
|
||||
let p = parity_json();
|
||||
|
||||
@@ -168,7 +168,8 @@ pub fn import(e: &mut Engine, path: &str, first: Option<TrackId>, at: Samples) -
|
||||
.unwrap_or(2);
|
||||
let kind = if audio_lane { soundcraft_model::TrackKind::Audio } else { soundcraft_model::TrackKind::Midi };
|
||||
let fmt = if channels == 1 { soundcraft_model::ChannelFormat::Mono } else { soundcraft_model::ChannelFormat::Stereo };
|
||||
s.add_track(kind, fmt, Some("Clip Group"))
|
||||
let t = s.add_track(kind, fmt, Some("Clip Group"));
|
||||
crate::no_input::assign_first_input(s, t)
|
||||
}
|
||||
};
|
||||
let mut prepared = Vec::new();
|
||||
|
||||
@@ -27,6 +27,7 @@ mod more_util;
|
||||
mod options;
|
||||
mod plugin_state;
|
||||
mod query;
|
||||
mod room_tone;
|
||||
pub(crate) mod sampler;
|
||||
mod setup_more;
|
||||
mod strip_silence;
|
||||
@@ -62,10 +63,12 @@ mod panic_probe {
|
||||
}
|
||||
}
|
||||
|
||||
pub use clip_more::is_looped;
|
||||
pub use file::bounce_job;
|
||||
|
||||
pub(crate) use edit::remember_selection;
|
||||
pub use strip_silence::strip_silence_scan;
|
||||
pub use tab::tab_stop_ahead;
|
||||
|
||||
pub type Run = fn(&mut Engine, &Value) -> Result<Value>;
|
||||
/// `Err(reason)` = disabled.
|
||||
@@ -164,6 +167,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(video::specs());
|
||||
v.extend(zoom_toggle::specs());
|
||||
v.extend(strip_silence::specs());
|
||||
v.extend(room_tone::specs());
|
||||
#[cfg(test)]
|
||||
v.extend(panic_probe::specs());
|
||||
v
|
||||
|
||||
@@ -40,7 +40,9 @@ fn audio_as_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
seq.sort();
|
||||
let count = seq.notes.len();
|
||||
let clip = Clip::midi(ClipId(0), "Audio as MIDI", 0, r.len(), seq);
|
||||
e.clipboard = Clipboard { tracks: vec![vec![clip]], automation: vec![Vec::new()], ..Clipboard::of_range(e.session(), r) };
|
||||
let mut clipboard = Clipboard { automation: vec![Vec::new()], ..Clipboard::of_range(s, r) };
|
||||
clipboard.push_clips(s, r.start, vec![clip]);
|
||||
e.clipboard = clipboard;
|
||||
Ok(json!({"notes": count, "length": r.len()}))
|
||||
}
|
||||
|
||||
|
||||
@@ -21,14 +21,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// How many times longer than its input a process's output can be.
|
||||
fn growth(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> f64 {
|
||||
match name {
|
||||
"time_stretch" => ratio,
|
||||
"pitch_shift" => 2f64.powf(f64::from(semitones) / 12.0),
|
||||
"varispeed" => f64::from(to) / sr,
|
||||
"speed_ramp" if selection == SpeedRampSelection::Extend => 1.5,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The most frames a process can take in: these processes cut their output at MAX_OFFLINE_SAMPLES frames.
|
||||
fn frame_limit(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> usize {
|
||||
let longest = |grows: f64| (soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / grows) as usize;
|
||||
match name {
|
||||
"time_stretch" => longest(ratio),
|
||||
"pitch_shift" => longest(2f64.powf(f64::from(semitones) / 12.0)),
|
||||
"varispeed" => longest(f64::from(to) / sr),
|
||||
"speed_ramp" => longest(if selection == SpeedRampSelection::Extend { 1.5 } else { 1.0 }),
|
||||
"time_stretch" | "pitch_shift" | "varispeed" | "speed_ramp" => {
|
||||
(soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / growth(name, ratio, semitones, sr, to, selection)) as usize
|
||||
}
|
||||
_ => usize::MAX,
|
||||
}
|
||||
}
|
||||
@@ -80,14 +89,33 @@ fn process(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let selection = if get("selection", 0.0) >= 0.5 { SpeedRampSelection::Extend } else { SpeedRampSelection::FitTo };
|
||||
let fades = get("fades", 1.0) >= 0.5;
|
||||
let most = frame_limit(&name, ratio, semitones, sr.as_f64(), to, selection);
|
||||
// Each clip once: a clip listed again would otherwise process the result of its first pass
|
||||
// (an expanding process compounding its length every time).
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let ids: Vec<_> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
// Refuse before processing anything. Every result is kept as a new source for the life of
|
||||
// the command (and undo holds it), so cap the total output across clips, not just each one.
|
||||
// (pitch_shift resamples its stretched result back to the input length)
|
||||
let grows = if name == "pitch_shift" { 1.0 } else { growth(&name, ratio, semitones, sr.as_f64(), to, selection).max(1.0) };
|
||||
let mut budget = soundcraft_mix::MAX_RENDER_SAMPLES;
|
||||
for id in &ids {
|
||||
let Some((track, clip)) = e.session().find_clip(*id) else { continue };
|
||||
if !clip.is_audio() {
|
||||
continue;
|
||||
}
|
||||
let channels = e.session().track(track).map_or(1, |t| t.channels()).max(1);
|
||||
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
|
||||
let frames = (clip.length.max(0) as f64 * grows).ceil() as usize;
|
||||
budget = budget
|
||||
.checked_sub(frames.saturating_mul(channels))
|
||||
.ok_or_else(|| bad("audiosuite.process", "too much audio to process in one command"))?;
|
||||
}
|
||||
let mut done = 0;
|
||||
for id in ids {
|
||||
let Some((track, clip)) = e.session().find_clip(id).map(|(t, c)| (t, c.clone())) else { continue };
|
||||
if !clip.is_audio() {
|
||||
continue;
|
||||
}
|
||||
let channels = e.session().track(track).map_or(1, |t| t.channels());
|
||||
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
|
||||
let mut audio = soundcraft_mix::render_clips(e.session(), track, clip.range());
|
||||
// Render without the clip's own fades: re-render a copy without fades so they stay editable.
|
||||
let mut tmp = e.session().clone();
|
||||
@@ -362,6 +390,40 @@ mod tests {
|
||||
assert_eq!(e.session().tracks[0].clips().len(), 1, "one clip, not one per duplicate listing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_listed_twice_is_processed_once() {
|
||||
let (mut e, id) = gained_clip();
|
||||
let out =
|
||||
e.execute("audiosuite.process", &json!({"process": "time_stretch", "params": {"ratio": 4.0}, "clips": [id.0, id.0, id.0]})).unwrap();
|
||||
assert_eq!(out["processed"], 1);
|
||||
let c = e.session().tracks[0].clips()[0].clone();
|
||||
assert!(c.length <= 64 * 4 + 64, "stretched once, not compounded: {}", c.length);
|
||||
assert_eq!(e.session().sources.len(), 2, "one new source, not one per listing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_refuses_a_total_budget_across_clips() {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Tone"));
|
||||
let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.5; 64]] };
|
||||
let src = crate::io::add_source(&mut s, "tone", buf, None, FileFormat::Wav);
|
||||
// Three clips each within the per-clip limit whose results together exceed the budget.
|
||||
let len = (soundcraft_mix::MAX_RENDER_SAMPLES / 3 + 1) as i64;
|
||||
let ids: Vec<u64> = (0..3)
|
||||
.map(|k| {
|
||||
let id = s.new_clip_id();
|
||||
crate::edit::place_clip(&mut s, t, Clip::audio(id, "tone", src, 0, k * len, len));
|
||||
id.0
|
||||
})
|
||||
.collect();
|
||||
let mut e = crate::Engine::new(s);
|
||||
let before = serde_json::to_value(e.session()).unwrap();
|
||||
let out = e.execute("audiosuite.process", &json!({"process": "reverse", "clips": ids}));
|
||||
let ok = matches!(out, Err(crate::EngineError::BadParams(_, ref m)) if m.contains("too much audio"));
|
||||
assert!(ok, "three clips over budget, but got: {out:?}");
|
||||
assert_eq!(serde_json::to_value(e.session()).unwrap(), before, "refused before processing anything");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_refuses_a_total_budget_across_tracks() {
|
||||
let mut e = Engine::new(Session::default());
|
||||
|
||||
@@ -162,7 +162,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let t = match track {
|
||||
Some(t) if s.track(t).is_some_and(|x| x.kind == soundcraft_model::TrackKind::Audio) => t,
|
||||
Some(_) => return Err(bad("clip.place_source", "audio files go on audio tracks")),
|
||||
None => s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name)),
|
||||
None => {
|
||||
let t =
|
||||
s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name));
|
||||
crate::no_input::assign_first_input(s, t)
|
||||
}
|
||||
};
|
||||
let (sh, len) = (s.edit.edit_mode == soundcraft_model::EditMode::Shuffle, frames.max(1));
|
||||
let at = if sh { crate::edit::shuffle_slot(s, t, at, &[]) } else { at };
|
||||
@@ -301,7 +305,7 @@ const MAX_LOOPS: i64 = 1000;
|
||||
|
||||
fn loop_clips(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let ids = clip_ids_param(e, p);
|
||||
let count = i64_or(p, "count", 4).clamp(1, 512);
|
||||
let count = i64_or(p, "count", 4).clamp(1, MAX_LOOPS);
|
||||
let total = position_param(e, "clip.loop", p, "length")?;
|
||||
let fill = p.get("fill").and_then(Value::as_bool).unwrap_or(false);
|
||||
let s = e.session_mut();
|
||||
|
||||
@@ -55,6 +55,10 @@ fn clear(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
pl.clips.retain(|c| !gone.contains(&c.id));
|
||||
}
|
||||
s.sources.retain(|f| !sources.contains(&f.id));
|
||||
// The room tone plays one of the removed files: nothing is left for it to play.
|
||||
if s.room_tone.is_some_and(|t| sources.contains(&t.source)) {
|
||||
s.room_tone = None;
|
||||
}
|
||||
for f in &sources {
|
||||
s.pool.remove(*f);
|
||||
}
|
||||
@@ -106,6 +110,18 @@ mod tests {
|
||||
assert_eq!(e.session().clips_using(f).count(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_room_tones_file_forgets_the_room_tone() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
let (f, clips) = kick(&e);
|
||||
e.execute("edit.room_tone_set", &json!({"clip": clips[0]})).unwrap();
|
||||
assert_eq!(e.session().room_tone.map(|t| t.source), Some(f));
|
||||
e.execute("clip.clear", &json!({"sources": [f], "with_clips": true})).unwrap();
|
||||
assert_eq!(e.session().room_tone, None);
|
||||
assert!(e.undo());
|
||||
assert_eq!(e.session().room_tone.map(|t| t.source), Some(f), "undo brings it back with the file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_a_files_clips_too_is_enough() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
|
||||
@@ -150,6 +150,11 @@ fn loop_chain(s: &Session, t: TrackId, id: ClipId) -> Vec<ClipId> {
|
||||
chain
|
||||
}
|
||||
|
||||
/// Whether a clip belongs to a loop that `clip.unloop` changes: two or more back-to-back copies.
|
||||
pub fn is_looped(s: &Session, id: ClipId) -> bool {
|
||||
s.find_clip(id).is_some_and(|(t, _)| loop_chain(s, t, id).len() >= 2)
|
||||
}
|
||||
|
||||
fn unloop(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "clip.unloop";
|
||||
let remove = match str_param(p, "mode") {
|
||||
@@ -469,6 +474,13 @@ mod tests {
|
||||
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "length": 100_100})).unwrap()["loops"], 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_count_accepts_up_to_the_documented_thousand() {
|
||||
let (mut e, t, ids) = engine_with(&[(0, 100, 0)]);
|
||||
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "count": 600})).unwrap()["loops"], 599);
|
||||
assert_eq!(e.session().track(t).unwrap().clips().len(), 600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regroup_reuses_group() {
|
||||
let (mut e, _, ids) = engine_with(&[(0, 100, 0), (500, 100, 0), (900, 100, 0)]);
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::more_util::toggle_flag;
|
||||
use crate::edit as ops;
|
||||
use crate::{Clipboard, Engine, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{ClipId, EditMode, Fade, FadeShape, Session, TrackId};
|
||||
use soundcraft_model::{Clip, ClipId, EditMode, Fade, FadeShape, Session, TrackId};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -259,7 +259,9 @@ fn cut_copy(e: &mut Engine, p: &Value, cut: bool, id: &str) -> Result<Value> {
|
||||
let follow = e.session().edit.automation_follows_edit;
|
||||
for t in &tracks {
|
||||
// Cut carries only what it removes; a locked clip stays where it is (see `ops::take_range`).
|
||||
cb.tracks.push(if cut { ops::take_range(e.session(), *t, range) } else { ops::copy_range(e.session(), *t, range) });
|
||||
let s = e.session();
|
||||
let clips = if cut { ops::take_range(s, *t, range) } else { ops::copy_range(s, *t, range) };
|
||||
cb.push_clips(s, range.start, clips);
|
||||
let lanes = e
|
||||
.session()
|
||||
.track(*t)
|
||||
@@ -741,10 +743,9 @@ fn trim_to_file(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
if let Some((frames, lo, hi)) = trim_limits(s, id)
|
||||
&& let Some(c) = s.find_clip_mut(id)
|
||||
{
|
||||
let off = c.source_offset();
|
||||
let new_start = c.start - off;
|
||||
c.trim_start_to(new_start.max(lo));
|
||||
c.trim_end_to((new_start + frames).min(hi));
|
||||
let (file_start, file_end) = file_span(c, frames);
|
||||
c.trim_start_to(file_start.max(lo));
|
||||
c.trim_end_to(file_end.min(hi));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
@@ -760,15 +761,24 @@ fn trim_to_fill(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
if let Some((frames, lo, hi)) = trim_limits(s, id)
|
||||
&& let Some(c) = s.find_clip_mut(id)
|
||||
{
|
||||
let file_start = c.start - c.source_offset();
|
||||
let (file_start, file_end) = file_span(c, frames);
|
||||
c.trim_start_to(r.start.max(file_start).max(lo));
|
||||
c.trim_end_to(r.end.min(file_start + frames).min(hi));
|
||||
c.trim_end_to(r.end.min(file_end).min(hi));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(json!({"trimmed": n}))
|
||||
}
|
||||
|
||||
/// Where a clip's whole source file lies on the timeline. The mixer plays `offset + rel / stretch`,
|
||||
/// so the file starts `offset * stretch` before the clip and spans `frames * stretch` samples.
|
||||
fn file_span(c: &Clip, frames: Samples) -> (Samples, Samples) {
|
||||
let stretch = if c.stretch.is_finite() && c.stretch > 0.0 { c.stretch } else { 1.0 };
|
||||
let scale = |n: Samples| if (stretch - 1.0).abs() >= 1e-9 { (n as f64 * stretch).round() as Samples } else { n };
|
||||
let start = c.start.saturating_sub(scale(c.source_offset()));
|
||||
(start, start.saturating_add(scale(frames)))
|
||||
}
|
||||
|
||||
/// How far a trim may extend an audio clip: its source length in frames, and the earliest
|
||||
/// start and latest end before it would run over the clip before or after it on the playlist
|
||||
/// (an extension never overwrites, like the trim tool). An overlap the clip already has with
|
||||
@@ -1209,9 +1219,9 @@ mod tests {
|
||||
let (mut e, t, at) = keys();
|
||||
let s = e.session_mut();
|
||||
let cc = soundcraft_midi::CtrlEvent { tick: 0, channel: 0, kind: soundcraft_midi::CtrlKind::Cc(1), value: 64 };
|
||||
let a = soundcraft_midi::Sequence { notes: vec![note(0, 1, 60), note(3, 2, 62), note(5, 1, 63)], ctrls: vec![], sysex: vec![] };
|
||||
let b = soundcraft_midi::Sequence { notes: vec![note(0, 1, 64)], ctrls: vec![], sysex: vec![] };
|
||||
let c = soundcraft_midi::Sequence { notes: vec![note(1, 1, 65)], ctrls: vec![cc], sysex: vec![] };
|
||||
let a = soundcraft_midi::Sequence { notes: vec![note(0, 1, 60), note(3, 2, 62), note(5, 1, 63)], ..Default::default() };
|
||||
let b = soundcraft_midi::Sequence { notes: vec![note(0, 1, 64)], ..Default::default() };
|
||||
let c = soundcraft_midi::Sequence { notes: vec![note(1, 1, 65)], ctrls: vec![cc], ..Default::default() };
|
||||
for (start, end, seq, muted) in [(0, 4, a, false), (6, 8, b, true), (8, 12, c, false)] {
|
||||
let id = s.new_clip_id();
|
||||
let mut clip = Clip::midi(id, "Keys", at(start), at(end) - at(start), seq);
|
||||
@@ -1254,6 +1264,33 @@ mod tests {
|
||||
assert_eq!(bounds(&e, t), vec![(0, 10_000, 0), (10_000, 40_000, 10_000), (40_000, 45_000, 0)]);
|
||||
}
|
||||
|
||||
/// A lone stretched clip (start 20,000, length 10,000, source offset 5,000) over the 60,000-frame source.
|
||||
fn stretched_trim_session(stretch: f64) -> (Engine, TrackId, Vec<ClipId>) {
|
||||
let (mut e, t, ids) = trim_session(&[(20_000, 10_000, 5_000)]);
|
||||
if let Some(c) = e.session_mut().find_clip_mut(ids[0]) {
|
||||
c.stretch = stretch;
|
||||
}
|
||||
(e, t, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_to_file_boundaries_covers_the_whole_stretched_file() {
|
||||
let (mut e, t, ids) = stretched_trim_session(2.0);
|
||||
e.execute("edit.trim_to_file_boundaries", &json!({"clips": [ids[0].0]})).unwrap();
|
||||
let (start, end, offset) = bounds(&e, t)[0];
|
||||
assert_eq!(offset, 0, "the clip starts at the file start");
|
||||
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "it plays every file frame: {start}..{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_to_fill_selection_stops_at_the_stretched_file() {
|
||||
let (mut e, t, ids) = stretched_trim_session(2.0);
|
||||
e.execute("edit.trim_to_fill_selection", &json!({"clips": [ids[0].0], "start": 0, "end": 500_000})).unwrap();
|
||||
let (start, end, offset) = bounds(&e, t)[0];
|
||||
assert_eq!(offset, 0);
|
||||
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "a wider selection stops at the file: {start}..{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_to_fill_selection_stops_at_the_neighbours() {
|
||||
let (mut e, t, ids) = trim_session(&[(0, 10_000, 0), (20_000, 10_000, 20_000), (40_000, 5_000, 0)]);
|
||||
|
||||
@@ -448,6 +448,19 @@ fn paste_clip_effects(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"clips": ids.len()}))
|
||||
}
|
||||
|
||||
fn retain_midi_window(sequence: &mut soundcraft_midi::Sequence, end: i64) {
|
||||
let window = 0..end;
|
||||
sequence.notes.retain_mut(|note| {
|
||||
if !window.contains(¬e.start) {
|
||||
return false;
|
||||
}
|
||||
note.length = note.length.min(end - note.start);
|
||||
true
|
||||
});
|
||||
sequence.ctrls.retain(|event| window.contains(&event.tick));
|
||||
sequence.sysex.retain(|event| window.contains(&event.tick));
|
||||
}
|
||||
|
||||
fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "edit.paste_merge_midi";
|
||||
let tracks = tracks_required(e, id, p)?;
|
||||
@@ -460,16 +473,22 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let mut placed = 0;
|
||||
for (i, t) in tracks.iter().enumerate() {
|
||||
let Some(clips) = cb.tracks.get(i % cb.tracks.len().max(1)) else { continue };
|
||||
for c in clips {
|
||||
for source in clips {
|
||||
let mut c = source.clone();
|
||||
let pos = at.saturating_add(c.start);
|
||||
let ClipContent::Midi { sequence } = &c.content else {
|
||||
let mut nc = c.clone();
|
||||
nc.id = s.new_clip_id();
|
||||
nc.start = pos;
|
||||
ops::place_clip(s, *t, nc);
|
||||
let ClipContent::Midi { sequence } = &mut c.content else {
|
||||
c.id = s.new_clip_id();
|
||||
c.start = pos;
|
||||
ops::place_clip(s, *t, c);
|
||||
placed += 1;
|
||||
continue;
|
||||
};
|
||||
let paste_tick = tempo.samples_to_ticks(pos, sr);
|
||||
let sample_end = pos.saturating_add(c.length);
|
||||
let ticks = cb.midi_tick_lengths.get(&c.id).copied().unwrap_or_else(|| tempo.samples_to_ticks(sample_end, sr).saturating_sub(paste_tick));
|
||||
retain_midi_window(sequence, ticks);
|
||||
// At a slower destination tempo the same musical window needs more samples.
|
||||
let want_end = sample_end.max(tempo.tick_to_samples(paste_tick.saturating_add(ticks), sr));
|
||||
let target = s.track(*t).and_then(|tr| {
|
||||
let host = tr.clips().iter().find(|x| matches!(x.content, ClipContent::Midi { .. }) && x.range().contains(pos))?;
|
||||
let next_start = tr.clips().iter().filter(|x| x.start > host.start && x.id != host.id).map(|x| x.start).min();
|
||||
@@ -477,22 +496,23 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
});
|
||||
match target {
|
||||
Some((hid, hstart, next_start)) => {
|
||||
let diff = tempo.samples_to_ticks(pos, sr) - tempo.samples_to_ticks(hstart, sr);
|
||||
let want_end = pos.saturating_add(c.length);
|
||||
let diff = paste_tick - tempo.samples_to_ticks(hstart, sr);
|
||||
let limit = next_start.unwrap_or(Samples::MAX);
|
||||
if let Some(h) = s.find_clip_mut(hid)
|
||||
&& let ClipContent::Midi { sequence: hs } = &mut h.content
|
||||
{
|
||||
for n in &sequence.notes {
|
||||
let mut n = *n;
|
||||
for mut n in sequence.notes.drain(..) {
|
||||
n.start = n.start.saturating_add(diff);
|
||||
hs.notes.push(n);
|
||||
}
|
||||
for cc in &sequence.ctrls {
|
||||
let mut cc = *cc;
|
||||
for mut cc in sequence.ctrls.drain(..) {
|
||||
cc.tick = cc.tick.saturating_add(diff);
|
||||
hs.ctrls.push(cc);
|
||||
}
|
||||
for mut event in sequence.sysex.drain(..) {
|
||||
event.tick = event.tick.saturating_add(diff);
|
||||
hs.sysex.push(event);
|
||||
}
|
||||
hs.sort();
|
||||
if want_end > h.end() {
|
||||
h.trim_end_to(want_end.min(limit));
|
||||
@@ -501,10 +521,17 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut nc = c.clone();
|
||||
nc.id = s.new_clip_id();
|
||||
nc.start = pos;
|
||||
ops::place_clip(s, *t, nc);
|
||||
// Only extend through empty space. Keep the existing placement behavior
|
||||
// inside the original sample range and preserve material beyond it.
|
||||
if want_end > sample_end
|
||||
&& let Some(track) = s.track(*t)
|
||||
{
|
||||
let limit = track.clips().iter().filter(|other| other.end() > sample_end).map(|other| other.start.max(sample_end)).min();
|
||||
c.length = want_end.min(limit.unwrap_or(Samples::MAX)).saturating_sub(pos);
|
||||
}
|
||||
c.id = s.new_clip_id();
|
||||
c.start = pos;
|
||||
ops::place_clip(s, *t, c);
|
||||
placed += 1;
|
||||
}
|
||||
}
|
||||
@@ -1143,7 +1170,7 @@ mod tests {
|
||||
e.execute("edit.select", &json!({"tracks": [keys.0], "start": r.start, "end": r.end})).unwrap();
|
||||
e.execute("edit.copy", &json!({})).unwrap();
|
||||
let copied = match &e.clipboard.tracks[0][0].content {
|
||||
ClipContent::Midi { sequence } => sequence.notes.len(),
|
||||
ClipContent::Midi { sequence } => sequence.notes_in(0, e.clipboard.midi_tick_lengths[&clip.id]).count(),
|
||||
_ => 0,
|
||||
};
|
||||
e.execute("edit.paste_merge_midi", &json!({"at": clip.start + 96_000})).unwrap();
|
||||
|
||||
@@ -313,10 +313,16 @@ fn add_marker(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let at = position_param(e, "markers.add", p, "at")?;
|
||||
let st = position_param(e, "markers.add", p, "start")?;
|
||||
let en = position_param(e, "markers.add", p, "end")?;
|
||||
let kind = match str_param(p, "kind") {
|
||||
Some("selection") => MarkerKind::Selection,
|
||||
Some("none") => MarkerKind::None,
|
||||
_ => MarkerKind::Marker,
|
||||
let kind = match p.get("kind") {
|
||||
None | Some(Value::Null) => MarkerKind::Marker,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("marker") => MarkerKind::Marker,
|
||||
Some("selection") => MarkerKind::Selection,
|
||||
Some("none") => MarkerKind::None,
|
||||
Some(other) => return Err(bad("markers.add", format!("unknown kind `{other}`"))),
|
||||
// A present non-string is neither a documented kind nor an omitted one.
|
||||
None => return Err(bad("markers.add", "kind must be a string")),
|
||||
},
|
||||
};
|
||||
let (a, b) = match (at, st, en) {
|
||||
(Some(a), _, _) => (a, a),
|
||||
@@ -580,6 +586,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `markers.add` rejects an unknown or non-string `kind` instead of silently adding a plain
|
||||
/// marker; an absent or null one still means a plain marker.
|
||||
#[test]
|
||||
fn markers_add_rejects_an_unknown_kind() {
|
||||
let mut e = crate::Engine::default();
|
||||
let err = e.execute("markers.add", &json!({"name": "x", "kind": "garbage"})).unwrap_err();
|
||||
assert!(err.to_string().contains("kind"), "unexpected error: {err}");
|
||||
assert!(e.session().markers.is_empty());
|
||||
for bad in [json!(123), json!(true), json!(["marker"]), json!({"kind": "marker"}), json!(1.5)] {
|
||||
let err = e.execute("markers.add", &json!({"name": "x", "kind": bad})).unwrap_err();
|
||||
assert!(err.to_string().contains("kind"), "{bad}: unexpected error: {err}");
|
||||
assert!(e.session().markers.is_empty(), "{bad}: a marker was added");
|
||||
}
|
||||
let plain = e.execute("markers.add", &json!({"name": "Plain", "kind": null, "at": 500})).unwrap();
|
||||
assert_eq!(e.session().markers.len(), 1, "null is still an omitted kind");
|
||||
let verse = e.execute("markers.add", &json!({"name": "Verse", "kind": "marker", "at": 1000})).unwrap();
|
||||
let pre = e.execute("markers.add", &json!({"name": "Pre", "kind": "none", "at": 2000})).unwrap();
|
||||
let kind_of =
|
||||
|e: &crate::Engine, r: &serde_json::Value| e.session().markers.iter().find(|m| Some(m.id.0) == r["id"].as_u64()).map(|m| m.kind);
|
||||
assert_eq!(kind_of(&e, &plain), Some(soundcraft_model::MarkerKind::Marker));
|
||||
assert_eq!(kind_of(&e, &verse), Some(soundcraft_model::MarkerKind::Marker));
|
||||
assert_eq!(kind_of(&e, &pre), Some(soundcraft_model::MarkerKind::None));
|
||||
}
|
||||
|
||||
/// Constant replaces the tempo over [start, end) only; the tempo at the old end tick carries on after it.
|
||||
#[test]
|
||||
fn tempo_constant_is_bounded_by_its_range() {
|
||||
|
||||
@@ -349,9 +349,9 @@ fn select_split(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut nc = c.clone();
|
||||
nc.id = s.new_clip_id();
|
||||
// Note-split has always copied only the matching notes, not controllers. SysEx is the same
|
||||
// default now that Sequence has that field: packets stay on the source clip. Full SysEx
|
||||
// split/trim/heal is storytold/soundcraft#1618.
|
||||
// Note-split copies only the matching notes, not controllers or SysEx: packets stay on the
|
||||
// source clip. (Split, trim, Merge MIDI and consolidate re-anchor packets to the new clip
|
||||
// start.)
|
||||
nc.content = ClipContent::Midi { sequence: soundcraft_midi::Sequence { notes: hit, ctrls: Vec::new(), sysex: Vec::new() } };
|
||||
crate::edit::place_clip(s, nt, nc);
|
||||
}
|
||||
@@ -965,7 +965,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Note-split copies only the notes in the pitch range. SysEx already on the clip stays there;
|
||||
/// the new clip's sysex list is empty (storytold/soundcraft#1618 owns split/trim of packets).
|
||||
/// the new clip's sysex list is empty.
|
||||
#[test]
|
||||
fn note_split_leaves_sysex_on_the_source_clip() {
|
||||
let (mut e, t) = midi_engine();
|
||||
|
||||
@@ -44,6 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
for t in &mut s.tracks { for pl in &mut t.playlists { pl.clips.clear() } }
|
||||
s.sources.clear();
|
||||
s.videos.clear();
|
||||
s.room_tone = None;
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
// A template too large to open is not saved (#892).
|
||||
crate::io::session_size(file.display(), text.len() as u64, true)?;
|
||||
@@ -73,7 +74,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let at = position_param(e, "file.import_midi", p, "at")?.unwrap_or(0);
|
||||
let bytes = crate::io::read_file(&path)?;
|
||||
let tracks = crate::io::import_midi_bytes(e, &bytes, at, bool_or(p, "tempo_map", true))?;
|
||||
Ok(json!({"tracks": tracks}))
|
||||
let sysex_packets: usize = tracks
|
||||
.iter()
|
||||
.filter_map(|id| e.session().track(*id))
|
||||
.flat_map(|t| t.clips())
|
||||
.map(|c| match &c.content {
|
||||
soundcraft_model::ClipContent::Midi { sequence } => sequence.sysex.len(),
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
let mut result = json!({"tracks": tracks});
|
||||
if sysex_packets > 0 {
|
||||
result["sysex_packets"] = json!(sysex_packets);
|
||||
result["warnings"] = json!(["SysEx packets are retained for session saves and MIDI export; SysEx playback is not supported."]);
|
||||
}
|
||||
Ok(result)
|
||||
}),
|
||||
cmd!(
|
||||
"file.import_video",
|
||||
|
||||
@@ -52,6 +52,23 @@ fn import_audio_places_audio_offered_by_a_worker() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_audio_refuses_a_non_audio_target() {
|
||||
let dir = std::env::temp_dir().join(format!("sc-import-non-audio-target-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let wav = tone_wav(&dir, "tone.wav");
|
||||
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({"kind": "instrument", "name": "Keys"})).unwrap();
|
||||
let err = e.execute("file.import_audio", &json!({"path": wav, "track": "Keys"})).unwrap_err();
|
||||
assert!(err.to_string().contains("audio track"), "{err}");
|
||||
assert_eq!(e.session().tracks.len(), 1);
|
||||
assert!(e.session().sources.is_empty());
|
||||
assert!(e.session().tracks[0].clips().is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_session_text_needs_replace_to_overwrite() {
|
||||
let dir = std::env::temp_dir().join(format!("sc-export-text-replace-{}", std::process::id()));
|
||||
|
||||
@@ -11,7 +11,7 @@ use soundcraft_model::{AutoParam, AutomationMode, INSERT_SLOTS, Insert, SEND_SLO
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("mix.volume", "Set Volume", [], None, "{tracks?, db: -144..12 | delta_db}", has_selection, volume),
|
||||
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1}", has_selection, pan),
|
||||
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1 (stereo: required, 0 = left, 1 = right)}", has_selection, pan),
|
||||
cmd!("mix.mute", "Mute", [], Some("Shift+M"), "{tracks?, value?: bool}", has_selection, |e, p| toggle(
|
||||
e,
|
||||
p,
|
||||
@@ -280,8 +280,25 @@ fn pan(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "mix.pan", p)?;
|
||||
let v = (p.get("pan").and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("mix.pan", "`pan` (number) required"))? as f32)
|
||||
.clamp(-1.0, 1.0);
|
||||
let idx = i64_or(p, "index", 0).clamp(0, 1) as usize;
|
||||
// A stereo track has one panner per channel, so it must say which: moving only the left one
|
||||
// by default folded the left channel into the right. An index the track lacks is an error too.
|
||||
// `null` means no index, as with `slot`. `i64_or` rounds, so the number has to be whole already.
|
||||
let idx = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(i) => {
|
||||
let whole = i.as_f64().is_some_and(|f| f.fract() == 0.0);
|
||||
Some(usize::try_from(i64_or(p, "index", -1)).ok().filter(|n| whole && *n <= 1).ok_or_else(|| bad("mix.pan", "`index` must be 0 or 1"))?)
|
||||
}
|
||||
};
|
||||
let s = e.session_mut();
|
||||
for tr in tracks.iter().filter_map(|t| s.track(*t)) {
|
||||
match (idx, tr.mixer.pan.len()) {
|
||||
(None, 2) => return Err(bad("mix.pan", format!("`{}` is stereo: give `index` 0 (left channel) or 1 (right channel)", tr.name))),
|
||||
(Some(1), 1) => return Err(bad("mix.pan", format!("`{}` is mono: its only panner is `index` 0", tr.name))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let idx = idx.unwrap_or(0);
|
||||
for t in &tracks {
|
||||
if let Some(tr) = s.track_mut(*t)
|
||||
&& let Some(slot) = tr.mixer.pan.get_mut(idx)
|
||||
|
||||
@@ -413,6 +413,38 @@ fn clip_gain_to_volume_with_a_large_envelope_stays_fast() {
|
||||
assert!(lane.points.len() as i64 >= n);
|
||||
}
|
||||
|
||||
/// A stereo track has a panner per channel. `mix.pan` without `index` used to move only the left
|
||||
/// one, which folded the left channel into the right.
|
||||
#[test]
|
||||
fn panning_a_stereo_track_names_the_channel() {
|
||||
let mut e = Engine::default();
|
||||
e.execute("track.new", &json!({"name": "Pad", "format": "stereo"})).unwrap();
|
||||
e.execute("track.new", &json!({"name": "Vox", "format": "mono"})).unwrap();
|
||||
let pans = |e: &Engine, name: &str| e.session().tracks.iter().find(|t| t.name == name).map(|t| t.mixer.pan.clone());
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3})).is_err());
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 1.0]), "a refused pan leaves the track alone");
|
||||
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3, "index": 1})).unwrap();
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
|
||||
// A whole number written as a float counts; a fraction is an error (1.4 used to round to 1).
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.4})).is_err());
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
|
||||
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.0})).unwrap();
|
||||
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 0.9]));
|
||||
// `null` means no index, as with `slot`, so a stereo track still needs one.
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.0, "index": null})).is_err());
|
||||
// A mono track has one panner: no index needed, and any other index is an error, not a no-op.
|
||||
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.25, "index": null})).unwrap();
|
||||
assert_eq!(pans(&e, "Vox"), Some(vec![0.25]));
|
||||
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.5})).unwrap();
|
||||
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
|
||||
for index in [json!(1), json!(2), json!(-1), json!("1"), json!(0.4)] {
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.0, "index": index})).is_err(), "index {index}");
|
||||
}
|
||||
// One stereo track without an index stops the whole command.
|
||||
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox", "Pad"], "pan": 0.2})).is_err());
|
||||
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
|
||||
}
|
||||
|
||||
/// Live input toggles stay outside document history in both enabled and disabled states.
|
||||
#[test]
|
||||
fn live_input_states_are_transient_and_survive_document_history() {
|
||||
|
||||
@@ -36,12 +36,17 @@ pub fn set_flags(e: &mut Engine, ids: &[&str], on: bool) -> Value {
|
||||
json!({"flags": ids, "value": on})
|
||||
}
|
||||
|
||||
/// A string setting as [`set_text`] stores it: trimmed, cut to 200 characters, then trimmed again.
|
||||
/// The second trim drops a space at the cut, so a later call returns the same string. Empty clears it.
|
||||
pub fn text_value(value: &str) -> String {
|
||||
value.trim().chars().take(200).collect::<String>().trim_end().to_string()
|
||||
}
|
||||
|
||||
/// String settings live in `edit.flags` as `key=value` (one per key).
|
||||
pub fn set_text(edit: &mut EditState, key: &str, value: Option<&str>) {
|
||||
let prefix = format!("{key}=");
|
||||
edit.flags.retain(|f| !f.starts_with(&prefix));
|
||||
if let Some(v) = value.map(str::trim).filter(|v| !v.is_empty()) {
|
||||
let v: String = v.chars().take(200).collect();
|
||||
if let Some(v) = value.map(text_value).filter(|v| !v.is_empty()) {
|
||||
edit.flags.insert(format!("{prefix}{v}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
//! Room tone: choose a stretch of recorded silence and fill gaps with it instead of digital silence.
|
||||
//!
|
||||
//! The fill is made of ordinary audio clips that play the chosen window, overlapped and
|
||||
//! crossfaded where the gap is longer than the tone, so it can be edited like any other clip.
|
||||
|
||||
use super::{CommandSpec, always, bad, clip_ids_param, f64_or, has_range, range_param, tracks_required};
|
||||
use crate::{Engine, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{Clip, ClipContent, Fade, FadeShape, RoomTone, Session, TrackId, TrackKind};
|
||||
use soundcraft_time::{Range, Samples};
|
||||
|
||||
const SET: &str = "edit.room_tone_set";
|
||||
const FILL: &str = "edit.room_tone_fill";
|
||||
|
||||
/// The shortest room tone accepted, in seconds: shorter windows tile into a buzz and many clips.
|
||||
const MIN_TONE_SECONDS: f64 = 0.1;
|
||||
/// The most clips one fill makes, so a huge range can't flood the playlist.
|
||||
const MAX_FILL_CLIPS: usize = 20_000;
|
||||
/// The name the fill clips get.
|
||||
const CLIP_NAME: &str = "Room Tone";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"edit.room_tone_set",
|
||||
"Set Room Tone",
|
||||
["Edit", "Room Tone"],
|
||||
None,
|
||||
"{clip?} — the clip (default: the selected clip) becomes the session's room tone; with no `clip`, an edit selection inside the clip picks just that part. At least 0.1 s, not elastic. Returns the window",
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!(
|
||||
"edit.room_tone_fill",
|
||||
"Fill Gaps with Room Tone",
|
||||
["Edit", "Room Tone"],
|
||||
None,
|
||||
"{tracks?, start?, end?, fade_ms?: 10, edge_fade_ms?: 2, min_gap_ms?: 0} — fills every empty stretch of the range on each audio track with clips of the room tone, tiled with crossfades of `fade_ms` where the gap is longer than the tone, and faded in and out over `edge_fade_ms` at the edges of each gap (short, so the background does not dip next to speech); gaps shorter than `min_gap_ms` are left alone. Returns {clips, gaps}",
|
||||
fillable,
|
||||
fill
|
||||
),
|
||||
cmd!(
|
||||
"edit.room_tone_clear",
|
||||
"Clear Room Tone",
|
||||
["Edit", "Room Tone"],
|
||||
None,
|
||||
"{} — forgets the room tone; clips already filled stay",
|
||||
has_tone,
|
||||
|e, _| {
|
||||
let was = e.session_mut().room_tone.take();
|
||||
Ok(json!({"cleared": was.is_some()}))
|
||||
}
|
||||
),
|
||||
cmd!(query "edit.room_tone", "Room Tone", [], None, "{} — the room tone window {source, offset, length, gain_db}, or null", always, |e, _| {
|
||||
Ok(e.session().room_tone.map_or(Value::Null, |t| describe(e.session(), t)))
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
fn has_tone(e: &Engine) -> std::result::Result<(), String> {
|
||||
if e.session().room_tone.is_some() { Ok(()) } else { Err("set a room tone first (Edit › Room Tone › Set Room Tone)".into()) }
|
||||
}
|
||||
|
||||
fn fillable(e: &Engine) -> std::result::Result<(), String> {
|
||||
has_tone(e)?;
|
||||
has_range(e)
|
||||
}
|
||||
|
||||
fn describe(s: &Session, t: RoomTone) -> Value {
|
||||
let name = s.source(t.source).map(|f| f.name.clone());
|
||||
json!({"source": t.source.0, "source_name": name, "offset": t.offset, "length": t.length, "gain_db": t.gain_db})
|
||||
}
|
||||
|
||||
fn set(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let explicit = p.get("clip").is_some() || p.get("clips").is_some();
|
||||
let ids = clip_ids_param(e, p);
|
||||
let s = e.session();
|
||||
let id = match ids.as_slice() {
|
||||
[id] => *id,
|
||||
[] => return Err(bad(SET, "select the clip of room tone, or pass `clip`")),
|
||||
_ => return Err(bad(SET, "select one clip of room tone, not several")),
|
||||
};
|
||||
let (_, clip) = s.find_clip(id).ok_or_else(|| bad(SET, format!("no clip with id {}", id.0)))?;
|
||||
let ClipContent::Audio { source, .. } = clip.content else {
|
||||
return Err(bad(SET, format!("“{}” is not an audio clip", clip.name)));
|
||||
};
|
||||
if (clip.stretch - 1.0).abs() > f64::EPSILON {
|
||||
return Err(bad(SET, format!("“{}” is time-stretched; render it first", clip.name)));
|
||||
}
|
||||
// An edit selection inside the clip picks part of it.
|
||||
let sel = s.edit.selection;
|
||||
let window = if explicit || sel.is_empty() {
|
||||
clip.range()
|
||||
} else {
|
||||
sel.intersect(&clip.range()).ok_or_else(|| bad(SET, "the edit selection is outside the clip"))?
|
||||
};
|
||||
let offset = clip.source_offset().saturating_add(window.start - clip.start);
|
||||
let stored = s.source(source).map(|f| f.frames).ok_or_else(|| bad(SET, format!("the audio file of “{}” is missing", clip.name)))?;
|
||||
// The stored count isn't refreshed when a session reopens; the decoded audio is what plays.
|
||||
let frames = s.pool.get(source).map_or(stored, |a| a.frames() as u64);
|
||||
let tone = RoomTone { source, offset, length: window.len(), gain_db: clip.gain_db }
|
||||
.sanitized(frames)
|
||||
.ok_or_else(|| bad(SET, format!("“{}” plays no audio from its file", clip.name)))?;
|
||||
if tone.length < s.sample_rate.samples(MIN_TONE_SECONDS) {
|
||||
return Err(bad(SET, format!("room tone must be at least {MIN_TONE_SECONDS} s long")));
|
||||
}
|
||||
let s = e.session_mut();
|
||||
// A session reopens with the room tone cut to the stored count, so record the decoded one.
|
||||
if let Some(f) = s.sources.iter_mut().find(|f| f.id == source && f.frames < frames) {
|
||||
f.frames = frames;
|
||||
}
|
||||
s.room_tone = Some(tone);
|
||||
Ok(describe(e.session(), tone))
|
||||
}
|
||||
|
||||
/// The empty stretches of `range` on `track`'s active playlist, at least `min` samples long.
|
||||
fn gaps(s: &Session, track: TrackId, range: Range, min: Samples) -> Vec<Range> {
|
||||
let Some(t) = s.track(track) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut at = range.start;
|
||||
let mut clips: Vec<Range> = t.clips().iter().map(Clip::range).filter(|r| r.end > range.start && r.start < range.end).collect();
|
||||
clips.sort_by_key(|r| r.start);
|
||||
for c in clips {
|
||||
if c.start > at {
|
||||
out.push(Range::new(at, c.start));
|
||||
}
|
||||
at = at.max(c.end);
|
||||
}
|
||||
if at < range.end {
|
||||
out.push(Range::new(at, range.end));
|
||||
}
|
||||
out.retain(|g| g.len() >= min.max(1));
|
||||
out
|
||||
}
|
||||
|
||||
/// The clips that fill `gap` with `tone`: whole tone windows, each overlapping the one before by
|
||||
/// `fade` samples with a crossfade, the last cut to the gap's end; the first fades in and the last
|
||||
/// fades out over `edge` (or less, in a short gap). `None` when that takes more than `budget` clips.
|
||||
fn tiles(tone: RoomTone, gap: Range, fade: Samples, edge: Samples, budget: usize) -> Option<Vec<Clip>> {
|
||||
let edge = edge.max(0);
|
||||
// The overlap must leave each tile moving forward.
|
||||
let fade = fade.clamp(0, tone.length / 2);
|
||||
let step = tone.length - fade;
|
||||
if step <= 0 {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
// Count before allocating: a long gap and a short tone could otherwise make millions.
|
||||
let needed = gap.len().saturating_sub(fade).max(1).saturating_add(step - 1) / step;
|
||||
if usize::try_from(needed).map_or(true, |n| n > budget) {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<Clip> = Vec::new();
|
||||
let mut at = gap.start;
|
||||
while at < gap.end && out.len() <= budget {
|
||||
let length = tone.length.min(gap.end - at);
|
||||
let mut c = Clip::audio(soundcraft_model::ClipId(0), CLIP_NAME, tone.source, tone.offset, at, length);
|
||||
c.gain_db = tone.gain_db;
|
||||
let crossfade = Fade { len: fade.min(length), shape: FadeShape::EqualPower, curvature: 0.0 };
|
||||
if let Some(prev) = out.last_mut() {
|
||||
prev.fade_out = crossfade;
|
||||
c.fade_in = crossfade;
|
||||
} else {
|
||||
c.fade_in = Fade { len: edge.min(length / 2), ..crossfade };
|
||||
}
|
||||
if at + length >= gap.end {
|
||||
// The last tile also fades out to the gap's edge, leaving room for its fade in.
|
||||
c.fade_out = Fade { len: edge.min(length - c.fade_in.len).max(0), ..crossfade };
|
||||
out.push(c);
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
at = at.saturating_add(step);
|
||||
}
|
||||
(out.len() <= budget).then_some(out)
|
||||
}
|
||||
|
||||
fn fill(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tone = e.session().room_tone.ok_or_else(|| bad(FILL, "set a room tone first"))?;
|
||||
let tracks = tracks_required(e, FILL, p)?;
|
||||
let range = range_param(e, FILL, p)?;
|
||||
if range.is_empty() {
|
||||
return Err(bad(FILL, "select a range to fill"));
|
||||
}
|
||||
let s = e.session();
|
||||
let name = s.source(tone.source).map_or_else(|| "the room tone's audio file".to_string(), |f| format!("`{}`", f.name));
|
||||
let Some(audio) = s.pool.get(tone.source) else {
|
||||
return Err(bad(FILL, format!("{name} is not loaded; relink it before filling")));
|
||||
};
|
||||
// The window was checked against the session file's frame count, which can be stale when the
|
||||
// file was replaced by a shorter one: tile only audio that decoded.
|
||||
let tone = tone
|
||||
.sanitized(audio.frames() as u64)
|
||||
.filter(|t| t.length >= s.sample_rate.samples(MIN_TONE_SECONDS))
|
||||
.ok_or_else(|| bad(FILL, format!("{name} is now shorter than the room tone; set the room tone again")))?;
|
||||
let ms = |k: &str, d: f64| s.sample_rate.samples(f64_or(p, k, d).clamp(0.0, 10_000.0) / 1000.0);
|
||||
let (fade, edge, min_gap) = (ms("fade_ms", 10.0), ms("edge_fade_ms", 2.0), ms("min_gap_ms", 0.0));
|
||||
// Plan every track first, so a fill that would be too big changes nothing.
|
||||
let mut plan: Vec<(TrackId, Vec<Clip>)> = Vec::new();
|
||||
let (mut count, mut gap_count) = (0usize, 0usize);
|
||||
for t in tracks {
|
||||
if s.track(t).is_none_or(|tr| tr.kind != TrackKind::Audio) {
|
||||
continue;
|
||||
}
|
||||
let mut clips = Vec::new();
|
||||
for gap in gaps(s, t, range, min_gap) {
|
||||
let budget = MAX_FILL_CLIPS.saturating_sub(count.saturating_add(clips.len()));
|
||||
let made = tiles(tone, gap, fade, edge, budget).ok_or_else(|| {
|
||||
bad(FILL, format!("that would make more than {MAX_FILL_CLIPS} clips; fill a shorter range or use a longer room tone"))
|
||||
})?;
|
||||
clips.extend(made);
|
||||
gap_count += 1;
|
||||
}
|
||||
count += clips.len();
|
||||
plan.push((t, clips));
|
||||
}
|
||||
if gap_count == 0 {
|
||||
return Err(bad(FILL, "no empty space to fill on the audio tracks in that range"));
|
||||
}
|
||||
let s = e.session_mut();
|
||||
for (t, mut clips) in plan {
|
||||
for c in &mut clips {
|
||||
c.id = s.new_clip_id();
|
||||
}
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.extend(clips);
|
||||
pl.sort();
|
||||
}
|
||||
}
|
||||
Ok(json!({"clips": count, "gaps": gap_count}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_model::{ChannelFormat, ClipId, FileFormat, SourceAudio, SourceId};
|
||||
use std::sync::Arc;
|
||||
|
||||
const RATE: Samples = 48_000;
|
||||
|
||||
/// A session with one mono track holding `clips` (start, length) of a 10 s source, the first
|
||||
/// of which plays 1 s of room tone from the start of the file.
|
||||
fn engine(clips: &[(Samples, Samples)]) -> (Engine, TrackId, Vec<ClipId>) {
|
||||
let mut e = Engine::default();
|
||||
let s = e.session_mut();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Narration"));
|
||||
let src = SourceId(s.alloc());
|
||||
let frames = 10 * RATE as usize;
|
||||
s.sources.push(soundcraft_model::Source {
|
||||
id: src,
|
||||
name: "Take".into(),
|
||||
path: "Take.wav".into(),
|
||||
channels: 1,
|
||||
frames: frames as u64,
|
||||
sample_rate: 48_000,
|
||||
format: FileFormat::Wav,
|
||||
time_reference: 0,
|
||||
unsaved: false,
|
||||
});
|
||||
// Quiet white noise, like a room: uncorrelated from one moment to the next.
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let noise: Vec<f32> = (0..frames)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
(seed as f32 / u32::MAX as f32 - 0.5) * 0.02
|
||||
})
|
||||
.collect();
|
||||
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![noise] };
|
||||
s.pool.insert(src, Arc::new(SourceAudio::new(buffer)));
|
||||
let mut ids = Vec::new();
|
||||
for (i, (start, length)) in clips.iter().enumerate() {
|
||||
let id = s.new_clip_id();
|
||||
let offset = if i == 0 { 0 } else { RATE * 2 };
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.push(Clip::audio(id, format!("Clip {i}"), src, offset, *start, *length));
|
||||
pl.sort();
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
s.edit.selected_tracks = vec![t];
|
||||
(e, t, ids)
|
||||
}
|
||||
|
||||
fn clips(e: &Engine, t: TrackId) -> Vec<Clip> {
|
||||
e.session().track(t).map(|tr| tr.clips().to_vec()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_takes_the_selected_clip_or_the_selected_part_of_it() {
|
||||
let (mut e, _, ids) = engine(&[(0, RATE)]);
|
||||
e.session_mut().edit.selected_clips = vec![ids[0]];
|
||||
let r = e.execute(SET, &json!({})).unwrap();
|
||||
assert_eq!((r["offset"].as_i64(), r["length"].as_i64()), (Some(0), Some(RATE)));
|
||||
e.session_mut().edit.selected_clips.clear();
|
||||
e.session_mut().edit.selection = Range::new(RATE / 4, RATE / 2);
|
||||
let r = e.execute(SET, &json!({})).unwrap();
|
||||
assert_eq!((r["offset"].as_i64(), r["length"].as_i64()), (Some(RATE / 4), Some(RATE / 4)));
|
||||
e.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(e.session().room_tone.map(|t| t.length), Some(RATE), "undo restores the previous tone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tone_past_a_stale_stored_length_survives_a_reload() {
|
||||
// The session file says 3 s, but 10 s decoded: the tone at 4..5 s plays.
|
||||
let (mut e, t, _) = engine(&[]);
|
||||
let s = e.session_mut();
|
||||
let src = s.sources.first().map(|f| f.id).unwrap();
|
||||
s.sources.iter_mut().for_each(|f| f.frames = 3 * RATE as u64);
|
||||
let id = s.new_clip_id();
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.push(Clip::audio(id, "Late", src, 4 * RATE, 0, RATE));
|
||||
}
|
||||
e.execute(SET, &json!({"clip": id.0})).unwrap();
|
||||
let tone = e.session().room_tone;
|
||||
assert_eq!(tone.map(|t| (t.offset, t.length)), Some((4 * RATE, RATE)));
|
||||
let loaded = Session::from_json(&e.session().to_json().unwrap()).unwrap();
|
||||
assert_eq!(loaded.room_tone, tone, "reopening keeps the tone that was set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_refuses_what_cannot_be_a_room_tone() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE / 20)]);
|
||||
assert!(e.execute(SET, &json!({"clip": ids[0].0})).is_err(), "50 ms is too short");
|
||||
assert!(e.execute(SET, &json!({"clip": 9999})).is_err(), "unknown clip");
|
||||
e.session_mut().edit.selected_tracks = vec![t];
|
||||
e.session_mut().edit.selection = Range::new(RATE * 5, RATE * 6);
|
||||
assert!(e.execute(SET, &json!({})).is_err(), "nothing selected");
|
||||
assert_eq!(e.session().room_tone, None);
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": RATE})).is_err(), "no tone to fill with");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_puts_crossfaded_tone_clips_in_every_gap_and_nowhere_else() {
|
||||
// Tone 0..1 s, speech 3..4 s; fill 0..6 s: gaps 1..3 s (2 s) and 4..6 s (2 s).
|
||||
let (mut e, t, ids) = engine(&[(0, RATE), (3 * RATE, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
let fade = RATE / 100;
|
||||
let r = e.execute(FILL, &json!({"start": 0, "end": 6 * RATE})).unwrap();
|
||||
assert_eq!(r["gaps"], 2);
|
||||
let fills: Vec<Clip> = clips(&e, t).into_iter().filter(|c| !ids.contains(&c.id)).collect();
|
||||
assert_eq!(r["clips"].as_u64(), Some(fills.len() as u64));
|
||||
for gap in [Range::new(RATE, 3 * RATE), Range::new(4 * RATE, 6 * RATE)] {
|
||||
let mut in_gap: Vec<&Clip> = fills.iter().filter(|c| gap.contains(c.start)).collect();
|
||||
in_gap.sort_by_key(|c| c.start);
|
||||
// 2 s of a 1 s tone with 10 ms overlaps: three tiles, the last cut short.
|
||||
assert_eq!(in_gap.len(), 3, "{gap:?}");
|
||||
assert_eq!(in_gap.first().map(|c| c.start), Some(gap.start));
|
||||
assert_eq!(in_gap.last().map(|c| c.end()), Some(gap.end), "the fill ends at the gap's edge");
|
||||
for pair in in_gap.windows(2) {
|
||||
assert_eq!(pair[0].end() - pair[1].start, fade, "neighbours overlap by the crossfade");
|
||||
assert_eq!((pair[0].fade_out.len, pair[1].fade_in.len), (fade, fade));
|
||||
}
|
||||
let edge = RATE / 500;
|
||||
assert_eq!(in_gap[0].fade_in.len, edge, "a short de-click fade at the gap's edges");
|
||||
assert!(in_gap.last().is_some_and(|c| c.fade_out.len == edge));
|
||||
for c in &in_gap {
|
||||
assert_eq!(c.name, CLIP_NAME);
|
||||
assert_eq!(c.source_offset(), 0);
|
||||
assert!(c.length <= RATE);
|
||||
}
|
||||
}
|
||||
// The original clips are untouched and nothing covers them.
|
||||
let all = clips(&e, t);
|
||||
for id in &ids {
|
||||
let c = all.iter().find(|c| c.id == *id).unwrap();
|
||||
assert!(fills.iter().all(|f| !f.range().overlaps(&c.range())), "fill over {}", c.name);
|
||||
}
|
||||
e.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(clips(&e, t).len(), 2, "undo removes the whole fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_plays_at_the_tones_level_through_every_crossfade() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
e.execute(FILL, &json!({"tracks": [t.0], "start": 0, "end": 5 * RATE, "fade_ms": 50})).unwrap();
|
||||
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 5 * RATE), 512);
|
||||
let left = &out[0];
|
||||
let rms = |a: usize, b: usize| (left[a..b].iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / (b - a) as f64).sqrt();
|
||||
let tone = rms(0, RATE as usize);
|
||||
assert!(tone > 0.0);
|
||||
// 20 ms windows from where the tone clip ends to the end of the fill: the edge fades are
|
||||
// too short to dip a window, and the crossfades keep the power.
|
||||
let win = (RATE / 50) as usize;
|
||||
for w in (RATE as usize..(5 * RATE) as usize - win).step_by(win) {
|
||||
let db = 20.0 * (rms(w, w + win) / tone).log10();
|
||||
assert!(db.abs() < 1.5, "level {db:.2} dB off the tone at {} s", w as f64 / RATE as f64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_skips_short_gaps_and_refuses_when_nothing_is_empty() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE), (RATE + 100, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": 2 * RATE + 100, "min_gap_ms": 5})).is_err(), "the 100-sample gap is under 5 ms");
|
||||
let r = e.execute(FILL, &json!({"start": 0, "end": 2 * RATE + 100})).unwrap();
|
||||
assert_eq!((r["gaps"].as_u64(), r["clips"].as_u64()), (Some(1), Some(1)));
|
||||
let short = clips(&e, t).into_iter().find(|c| !ids.contains(&c.id)).unwrap();
|
||||
assert_eq!((short.start, short.length), (RATE, 100));
|
||||
assert!(short.fade_in.len + short.fade_out.len <= short.length, "fades fit a short gap");
|
||||
assert_eq!((short.fade_in.len, short.fade_out.len), (50, 50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_too_big_changes_nothing() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE / 5)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
// 200 ms tiles over 4 hours is far more than the cap.
|
||||
let r = e.execute(FILL, &json!({"start": 0, "end": RATE * 4 * 3600}));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(clips(&e, t).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_ignores_non_audio_tracks_and_needs_loaded_audio() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
let aux = e.session_mut().add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
|
||||
let r = e.execute(FILL, &json!({"tracks": [t.0, aux.0], "start": 0, "end": 2 * RATE})).unwrap();
|
||||
assert_eq!(r["gaps"], 1);
|
||||
let tone = e.session().room_tone.unwrap();
|
||||
e.session_mut().pool.remove(tone.source);
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": 3 * RATE})).is_err(), "unloaded audio is not filled with");
|
||||
}
|
||||
|
||||
/// Replaces the tone's pooled audio with `frames` frames of silence, as when its file was
|
||||
/// swapped for a shorter one: the stored `Source.frames` keeps the old length.
|
||||
fn shorten_audio(e: &mut Engine, frames: usize) {
|
||||
let src = e.session().sources.first().map(|f| f.id).unwrap();
|
||||
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; frames]] };
|
||||
e.session_mut().pool.insert(src, Arc::new(SourceAudio::new(buffer)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_reads_only_the_audio_that_decoded() {
|
||||
// Tone 0..1 s; the file now decodes to 0.5 s.
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
shorten_audio(&mut e, (RATE / 2) as usize);
|
||||
e.execute(FILL, &json!({"start": 0, "end": 3 * RATE})).unwrap();
|
||||
let fills: Vec<Clip> = clips(&e, t).into_iter().filter(|c| !ids.contains(&c.id)).collect();
|
||||
assert!(!fills.is_empty());
|
||||
for c in &fills {
|
||||
assert!(c.source_offset() + c.length <= RATE / 2, "a fill clip reads past the decoded audio: {c:?}");
|
||||
}
|
||||
// Less than the minimum left: refused, nothing placed.
|
||||
shorten_audio(&mut e, (RATE / 20) as usize);
|
||||
let before = clips(&e, t).len();
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": 6 * RATE})).is_err());
|
||||
assert_eq!(clips(&e, t).len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_measures_the_window_against_the_decoded_audio() {
|
||||
let (mut e, _, ids) = engine(&[(0, RATE)]);
|
||||
shorten_audio(&mut e, (RATE / 2) as usize);
|
||||
let r = e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
assert_eq!(r["length"].as_i64(), Some(RATE / 2));
|
||||
shorten_audio(&mut e, (RATE / 20) as usize);
|
||||
assert!(e.execute(SET, &json!({"clip": ids[0].0})).is_err(), "only 50 ms decoded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_forgets_the_tone_but_keeps_the_fill() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
e.execute(FILL, &json!({"start": 0, "end": 2 * RATE})).unwrap();
|
||||
e.execute("edit.room_tone_clear", &json!({})).unwrap();
|
||||
assert_eq!(e.session().room_tone, None);
|
||||
assert_eq!(e.execute("edit.room_tone", &json!({})).unwrap(), Value::Null);
|
||||
assert_eq!(clips(&e, t).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_never_stall_or_overrun_on_odd_lengths() {
|
||||
let tone = RoomTone { source: SourceId(1), offset: 0, length: 3, gain_db: 0.0 };
|
||||
for (gap, fade) in [(Range::new(0, 1), 10), (Range::new(5, 17), 2), (Range::new(0, 1000), 0), (Range::new(0, 7), 1000)] {
|
||||
let t = tiles(tone, gap, fade, fade, MAX_FILL_CLIPS).unwrap();
|
||||
assert_eq!(t.first().map(|c| c.start), Some(gap.start));
|
||||
assert_eq!(t.last().map(Clip::end), Some(gap.end));
|
||||
assert!(t.iter().all(|c| c.length > 0 && c.fade_in.len + c.fade_out.len <= c.length), "{gap:?} {fade}");
|
||||
}
|
||||
let huge = Range::new(0, soundcraft_time::MAX_POSITION);
|
||||
assert!(tiles(tone, huge, 0, 0, MAX_FILL_CLIPS).is_none(), "refused before allocating");
|
||||
assert_eq!(tiles(tone, Range::new(0, 9), 0, 0, 3).map(|t| t.len()), Some(3), "exactly the budget is fine");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! shortcuts, MIDI setup) and File › Import › Session Data.
|
||||
use super::{CommandSpec, always, bad, command_specs, i64_or, str_param, track_param, tracks_param};
|
||||
|
||||
use super::more_util::{set_text, store_value, text, toggle_flag, values_with_prefix};
|
||||
use super::more_util::{set_text, store_value, text, text_value, toggle_flag, values_with_prefix};
|
||||
use crate::{Engine, EngineError, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{BusId, ChannelFormat, ClipContent, OutputPath, Route, Session, SourceId, TrackId, TrackKind};
|
||||
@@ -242,8 +242,16 @@ fn engine_settings(e: &mut Engine, p: &Value, id: &str) -> Result<Value> {
|
||||
fn disk_allocation(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "setup.disk_allocation";
|
||||
let t = track_param(e, id, p, "track")?;
|
||||
// The path that is checked is the path that is stored. `text_value` trims, cuts to 200
|
||||
// characters, and trims again, which is what `set_text` keeps.
|
||||
// An empty one clears the setting and names no folder, so it isn't checked.
|
||||
let path = str_param(p, "path").map(text_value);
|
||||
// Checked before `session_mut` so a refused path leaves the session untouched.
|
||||
if let Some(path) = path.as_deref().filter(|v| !v.is_empty()) {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Io)?;
|
||||
}
|
||||
let s = e.session_mut();
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
if let Some(path) = path.as_deref() {
|
||||
let key = t.map_or_else(|| "disk.root".to_string(), |t| format!("disk.track.{}", t.0));
|
||||
set_text(&mut s.edit, &key, Some(path));
|
||||
}
|
||||
@@ -476,7 +484,8 @@ fn import_session_data(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "file.import_session_data";
|
||||
let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad(id, "`path` required"))?.to_string();
|
||||
let text_v = crate::io::read_session_text(&path)?;
|
||||
let other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
|
||||
let mut other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
|
||||
crate::no_input::upgrade_legacy_inputs(&mut other);
|
||||
let names: Option<Vec<String>> =
|
||||
p.get("tracks").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
|
||||
let picked: Vec<soundcraft_model::Track> = match &names {
|
||||
|
||||
@@ -58,6 +58,13 @@ fn tab(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"selection": r}))
|
||||
}
|
||||
|
||||
/// Whether Tab has a stop after the insertion point or the selection's start. Every stop of a clip lies at or before
|
||||
/// its end, which is a stop itself.
|
||||
pub fn tab_stop_ahead(s: &Session) -> bool {
|
||||
let from = s.edit.selection.start;
|
||||
s.tracks.iter().filter(|t| s.edit.selected_tracks.contains(&t.id)).flat_map(|t| t.clips()).any(|c| c.start.max(c.end()) > from)
|
||||
}
|
||||
|
||||
/// The nearest stop after `from` (before it when `back`) on the selected tracks.
|
||||
fn stop(s: &Session, from: Samples, back: bool) -> Option<Samples> {
|
||||
let nearer = |x: Samples, best: Option<Samples>| {
|
||||
|
||||
@@ -98,8 +98,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)),
|
||||
cmd!("track.commit", "Commit...", ["Track"], Some("Alt+Shift+C"), "{tracks?}", has_selection, commit),
|
||||
cmd!("track.bounce", "Bounce...", ["Track"], Some("Cmd+Alt+Shift+B"), "{tracks?}", has_selection, commit),
|
||||
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
|
||||
cmd!("track.mute_sends", "All", ["Track", "Mute Sends"], None, "{tracks?, mute?: bool}", has_selection, mute_sends),
|
||||
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], Some("Shift+A"), "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
|
||||
cmd!(
|
||||
"track.mute_sends",
|
||||
"All",
|
||||
["Track", "Mute Sends"],
|
||||
Some("Shift+Q"),
|
||||
"{tracks?, mute?: bool} (toggles when omitted)",
|
||||
has_selection,
|
||||
|e, p| super::track_more::mute_sends_where(e, p, 0, 10)
|
||||
),
|
||||
cmd!(noundo "track.set_record_to_input_only", "Set Record Tracks to Input Only", ["Track"], Some("Alt+K"), "{}", always, |e, _| {
|
||||
let s = e.runtime_session_mut();
|
||||
let mut n = 0;
|
||||
@@ -287,11 +295,28 @@ fn new_track_row(e: &mut Engine, p: &Value) -> Result<Vec<TrackId>> {
|
||||
};
|
||||
let name = str_param(p, "name").map(str::to_string);
|
||||
let ticks = str_param(p, "timebase").map(|t| t == "ticks");
|
||||
let instrument = str_param(p, "instrument").map(str::to_string);
|
||||
// A missing instrument asks for the default; an explicit value must be a string plugin id,
|
||||
// even before a non-instrument row ignores it, so a number is not silently treated as absent.
|
||||
let instrument = match p.get("instrument") {
|
||||
None => None,
|
||||
Some(value) => {
|
||||
let id = value.as_str().ok_or_else(|| bad("track.new", "`instrument` must be a plugin id string"))?;
|
||||
if kind == TrackKind::Instrument {
|
||||
let info = super::clap::plugin_info(id).ok_or_else(|| bad("track.new", format!("unknown plugin `{id}`")))?;
|
||||
if !info.is_instrument {
|
||||
return Err(bad("track.new", format!("`{id}` is not an instrument")));
|
||||
}
|
||||
Some(info.id.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let s = e.session_mut();
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..count {
|
||||
let id = s.add_track(kind, format, name.as_deref());
|
||||
crate::no_input::assign_first_input(s, id);
|
||||
if let Some(t) = s.track_mut(id) {
|
||||
if let Some(tb) = ticks {
|
||||
t.ticks_timebase = tb;
|
||||
@@ -466,6 +491,7 @@ fn split_mono(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
_ => format!("{}", ch + 1),
|
||||
};
|
||||
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{}.{suffix}", src.name)));
|
||||
crate::no_input::assign_first_input(s, id);
|
||||
let mut clips = src.clips().to_vec();
|
||||
for c in &mut clips {
|
||||
c.id = s.new_clip_id();
|
||||
@@ -952,20 +978,6 @@ fn bypass_inserts(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"bypass": target}))
|
||||
}
|
||||
|
||||
fn mute_sends(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "track.mute_sends", p)?;
|
||||
let s = e.session_mut();
|
||||
let target = p.get("mute").and_then(Value::as_bool).unwrap_or(true);
|
||||
for t in &tracks {
|
||||
if let Some(tr) = s.track_mut(*t) {
|
||||
for snd in tr.mixer.sends.iter_mut().flatten() {
|
||||
snd.mute = target;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"mute": target}))
|
||||
}
|
||||
|
||||
fn create_click(e: &mut Engine, _: &Value) -> Result<Value> {
|
||||
let s = e.session_mut();
|
||||
let id = s.add_track(TrackKind::Aux, ChannelFormat::Mono, Some("Click"));
|
||||
@@ -1285,4 +1297,30 @@ mod tests {
|
||||
assert!(e.undo());
|
||||
assert_eq!(vca(&e), Some(master.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instrument_track_validates_the_instrument_id() {
|
||||
let mut e = Engine::default();
|
||||
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": "no.such.plugin"})).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": "eq_7band"})).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
// An explicit non-string is malformed, not a request for the default.
|
||||
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": 42})).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
// In a batch, a malformed second row rolls the first row back too.
|
||||
let batch = json!({"rows": [
|
||||
{"kind": "instrument", "instrument": "drum_synth"},
|
||||
{"kind": "instrument", "instrument": 42},
|
||||
]});
|
||||
assert!(e.execute("track.new", &batch).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
// Omitted still asks for the default instrument.
|
||||
let r = e.execute("track.new", &json!({"kind": "instrument"})).unwrap();
|
||||
let id = TrackId(r["tracks"][0].as_u64().unwrap());
|
||||
assert_eq!(e.session().track(id).unwrap().instrument.as_ref().unwrap().plugin, "subtractive_synth");
|
||||
let r = e.execute("track.new", &json!({"kind": "instrument", "instrument": "drum_synth"})).unwrap();
|
||||
let id = TrackId(r["tracks"][0].as_u64().unwrap());
|
||||
assert_eq!(e.session().track(id).unwrap().instrument.as_ref().unwrap().plugin, "drum_synth");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,38 +68,56 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
load_preset
|
||||
),
|
||||
cmd!("track.bypass_inserts_ae", "Inserts A-E", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |i, _| i < 5)
|
||||
cmd!(
|
||||
"track.bypass_inserts_ae",
|
||||
"Inserts A-E",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+2"),
|
||||
"{tracks?, bypass?: bool}",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |i, _| i < 5)
|
||||
),
|
||||
cmd!(
|
||||
"track.bypass_inserts_fj",
|
||||
"Inserts F-J",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+3"),
|
||||
"{tracks?, bypass?: bool}",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |i, _| (5..10).contains(&i))
|
||||
),
|
||||
cmd!(
|
||||
"track.bypass_eq",
|
||||
"EQ",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+E"),
|
||||
"{tracks?, bypass?: bool} — EQ plug-ins only",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Eq))
|
||||
),
|
||||
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], Some("Shift+C"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Dynamics))
|
||||
}),
|
||||
cmd!("track.bypass_inserts_fj", "Inserts F-J", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |i, _| (5..10).contains(&i))
|
||||
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], Some("Shift+V"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Reverb))
|
||||
}),
|
||||
cmd!("track.bypass_eq", "EQ", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool} — EQ plug-ins only", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Eq))
|
||||
}),
|
||||
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
|
||||
e,
|
||||
p,
|
||||
|_, c| c == Some(Category::Dynamics)
|
||||
)),
|
||||
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
|
||||
e,
|
||||
p,
|
||||
|_, c| c == Some(Category::Reverb)
|
||||
)),
|
||||
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
|
||||
e,
|
||||
p,
|
||||
|_, c| c == Some(Category::Delay)
|
||||
)),
|
||||
cmd!("track.bypass_modulation", "Modulation", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Modulation))
|
||||
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], Some("Shift+D"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
|
||||
bypass_where(e, p, |_, c| c == Some(Category::Delay))
|
||||
}),
|
||||
cmd!(
|
||||
"track.bypass_modulation",
|
||||
"Modulation",
|
||||
["Track", "Bypass Inserts"],
|
||||
Some("Shift+W"),
|
||||
"{tracks?, bypass?: bool}",
|
||||
has_selection,
|
||||
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Modulation))
|
||||
),
|
||||
cmd!(
|
||||
"track.mute_sends_ae",
|
||||
"Sends A-E",
|
||||
["Track", "Mute Sends"],
|
||||
None,
|
||||
Some("Shift+4"),
|
||||
"{tracks?, mute?: bool} (toggles when omitted)",
|
||||
has_selection,
|
||||
|e, p| mute_sends_where(e, p, 0, 5)
|
||||
@@ -108,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"track.mute_sends_fj",
|
||||
"Sends F-J",
|
||||
["Track", "Mute Sends"],
|
||||
None,
|
||||
Some("Shift+5"),
|
||||
"{tracks?, mute?: bool} (toggles when omitted)",
|
||||
has_selection,
|
||||
|e, p| mute_sends_where(e, p, 5, 10)
|
||||
@@ -335,7 +353,7 @@ fn bypass_where(e: &mut Engine, p: &Value, pick: fn(usize, Option<Category>) ->
|
||||
Ok(json!({"bypass": target, "inserts": n}))
|
||||
}
|
||||
|
||||
fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
|
||||
pub(super) fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "track.mute_sends", p)?;
|
||||
let s = e.session_mut();
|
||||
let all_muted = tracks.iter().filter_map(|t| s.track(*t)).all(|tr| tr.mixer.sends.iter().skip(from).take(to - from).flatten().all(|x| x.mute));
|
||||
@@ -502,15 +520,22 @@ fn coalesce_vca(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn designate_target(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tracks = tracks_required(e, "track.designate_target_playlist", p)?;
|
||||
let idx = p.get("index").and_then(Value::as_u64);
|
||||
let id = "track.designate_target_playlist";
|
||||
let tracks = tracks_required(e, id, p)?;
|
||||
let index = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => {
|
||||
let index = value.as_u64().ok_or_else(|| bad(id, "`index` must be a nonnegative integer"))?;
|
||||
Some(usize::try_from(index).map_err(|_| bad(id, "no such playlist"))?)
|
||||
}
|
||||
};
|
||||
let s = e.session_mut();
|
||||
let mut out = Vec::new();
|
||||
for t in &tracks {
|
||||
let Some(tr) = s.track(*t) else { continue };
|
||||
let i = idx.map_or(tr.active_playlist, |x| usize::try_from(x).unwrap_or(usize::MAX));
|
||||
let i = index.unwrap_or(tr.active_playlist);
|
||||
if i >= tr.playlists.len() {
|
||||
return Err(bad("track.designate_target_playlist", "no such playlist"));
|
||||
return Err(bad(id, "no such playlist"));
|
||||
}
|
||||
s.edit.values.insert(format!("playlist.target.{}", t.0), i as f64);
|
||||
out.push(json!({"track": t, "target": i}));
|
||||
@@ -574,6 +599,8 @@ mod tests {
|
||||
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
|
||||
e.execute("track.mute_sends_ae", &json!({})).unwrap();
|
||||
assert!(e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
|
||||
e.execute("track.mute_sends", &json!({})).unwrap();
|
||||
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -726,11 +753,19 @@ mod tests {
|
||||
e.execute("track.playlist_new", &json!({})).unwrap();
|
||||
e.execute("track.designate_target_playlist", &json!({})).unwrap();
|
||||
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
|
||||
let kick = e.session().track_by_name("Kick").unwrap().id;
|
||||
for index in [json!(-1), json!("1"), json!(1.5), json!(u64::MAX)] {
|
||||
assert!(e.execute("track.designate_target_playlist", &json!({"index": index})).is_err(), "{index}");
|
||||
assert_eq!(target_playlist(e.session(), kick), Some(1), "{index} must leave the target unchanged");
|
||||
}
|
||||
e.execute("track.show_target_playlist", &json!({})).unwrap();
|
||||
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
|
||||
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
|
||||
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 0);
|
||||
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
|
||||
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
|
||||
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
|
||||
e.execute("track.designate_target_playlist", &json!({"index": null})).unwrap();
|
||||
assert_eq!(target_playlist(e.session(), kick), Some(0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
offset
|
||||
),
|
||||
cmd!(query "video.list", "Movies", [], None, "{} — movies used by Video tracks (path, size, rate, codec, online file, why it is offline)", always, |e, _| {
|
||||
cmd!(query "video.list", "Movies", [], None, "{} — lists session movies with media details, clip counts, `file_found`, and any recorded `offline` reason. \
|
||||
The top-level `online` flag reports the Video Track Online setting.", always, |e, _| {
|
||||
let s = e.session();
|
||||
let rows: Vec<Value> = s
|
||||
.videos
|
||||
|
||||
@@ -325,6 +325,9 @@ mod tests {
|
||||
doc.pool.remove(SourceId(900));
|
||||
check(&saved, &doc, false, "decoded audio removed");
|
||||
let mut doc = saved.clone();
|
||||
doc.room_tone = Some(soundcraft_model::RoomTone { source: SourceId(900), offset: 0, length: 10, gain_db: 0.0 });
|
||||
check(&saved, &doc, false, "session room tone");
|
||||
let mut doc = saved.clone();
|
||||
doc.folder = Some(std::path::PathBuf::from("session"));
|
||||
check(&saved, &doc, false, "session folder");
|
||||
let mut doc = saved.clone();
|
||||
|
||||
@@ -48,14 +48,19 @@ pub fn split_clip(clip: &Clip, at: Samples, new_id: ClipId, t: TimeCtx<'_>) -> O
|
||||
let boundary = t.ticks(at) - t.ticks(clip.start);
|
||||
ls.notes.retain(|n| n.start < boundary);
|
||||
ls.ctrls.retain(|c| c.tick < boundary);
|
||||
ls.sysex.retain(|e| e.tick < boundary);
|
||||
rs.notes.retain(|n| n.start >= boundary);
|
||||
rs.ctrls.retain(|c| c.tick >= boundary);
|
||||
rs.sysex.retain(|e| e.tick >= boundary);
|
||||
for n in &mut rs.notes {
|
||||
n.start -= boundary;
|
||||
}
|
||||
for c in &mut rs.ctrls {
|
||||
c.tick -= boundary;
|
||||
}
|
||||
for e in &mut rs.sysex {
|
||||
e.tick -= boundary;
|
||||
}
|
||||
}
|
||||
Some((left, right))
|
||||
}
|
||||
@@ -69,12 +74,16 @@ fn rebase_midi_start(clip: &mut Clip, old_start: Samples, t: TimeCtx<'_>) {
|
||||
}
|
||||
sequence.notes.retain(|n| n.start >= delta);
|
||||
sequence.ctrls.retain(|c| c.tick >= delta);
|
||||
sequence.sysex.retain(|e| e.tick >= delta);
|
||||
for n in &mut sequence.notes {
|
||||
n.start -= delta;
|
||||
}
|
||||
for c in &mut sequence.ctrls {
|
||||
c.tick -= delta;
|
||||
}
|
||||
for e in &mut sequence.sysex {
|
||||
e.tick -= delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,6 +332,10 @@ pub fn consolidate_midi(s: &mut Session, track: TrackId, range: Range) -> bool {
|
||||
c.tick += at;
|
||||
merged.ctrls.push(c);
|
||||
}
|
||||
for mut e in sequence.sysex.into_iter().filter(|e| (0..len).contains(&e.tick)) {
|
||||
e.tick += at;
|
||||
merged.sysex.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
merged.sort();
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside one of the roots of its kind, compared by whole components
|
||||
//! (`/work2` isn't inside `/work`), without regard to case on Windows.
|
||||
//! (`/work2` isn't inside `/work`), by the case the disk stores (links are resolved first, so a
|
||||
//! differently cased spelling of a root still lands inside it).
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
//! Roots are in force on a thread inside [`confine`], and in the whole process after
|
||||
@@ -266,24 +267,12 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
/// Is `path` (resolved) `root` or inside it, component by component? Both come from
|
||||
/// `canonicalize`, which gives the name's case as the disk stores it, so equal means the same
|
||||
/// folder; folding case would equate two folders on a case-sensitive Windows directory.
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return false;
|
||||
}
|
||||
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => false,
|
||||
}
|
||||
root.components().all(|r| path.next().is_some_and(|p| p == r))
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
@@ -476,7 +465,7 @@ mod tests {
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
fn windows_resolves_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/a.scraft"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
@@ -488,6 +477,50 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On a case-sensitive Windows directory `Work` and `work` are two folders: a root on one
|
||||
/// doesn't grant the other, while a differently cased spelling of a name that is the same
|
||||
/// folder (the ordinary, case-insensitive directories) is still accepted. Skipped, with a
|
||||
/// note, where `fsutil` can't switch a directory to case-sensitive (it needs rights and the
|
||||
/// NTFS volume's support).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_case_sensitive_directory_keeps_case_equal_folders_apart() {
|
||||
let (base, _) = folders("case-sensitive");
|
||||
let cs = base.join("cs");
|
||||
std::fs::create_dir_all(&cs).unwrap();
|
||||
let switched = std::process::Command::new("fsutil")
|
||||
.args(["file", "setCaseSensitiveInfo"])
|
||||
.arg(&cs)
|
||||
.arg("enable")
|
||||
.output()
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !switched {
|
||||
eprintln!("skipped: cannot make {} case-sensitive", cs.display());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
for d in ["Work/sub", "work"] {
|
||||
std::fs::create_dir_all(cs.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(cs.join("Work/a.scraft"), "x").unwrap();
|
||||
std::fs::write(cs.join("work/secret.scraft"), "x").unwrap();
|
||||
let roots = AutomationRoots::new(&[&cs.join("Work")], &[&cs.join("Work")]).unwrap().unwrap();
|
||||
for access in [Access::Read, Access::Write] {
|
||||
assert_eq!(roots.check(s(cs.join("Work/a.scraft")), access), Ok(()));
|
||||
assert_eq!(roots.check(s(cs.join("Work/sub/New.scraft")), access), Ok(()));
|
||||
// The other folder exists, and so does a name no folder has: both are outside.
|
||||
for outside in ["work/secret.scraft", "work/new.scraft", "WORK/new.scraft"] {
|
||||
let e = roots.check(s(cs.join(outside)), access).unwrap_err();
|
||||
assert!(e.contains("outside the"), "{outside}: {e}");
|
||||
}
|
||||
}
|
||||
// A root on the lower-case folder grants that one only.
|
||||
let lower = AutomationRoots::new(&[&cs.join("work")], &[]).unwrap().unwrap();
|
||||
assert_eq!(lower.check(s(cs.join("work/secret.scraft")), Access::Read), Ok(()));
|
||||
assert!(lower.check(s(cs.join("Work/a.scraft")), Access::Read).is_err());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
|
||||
+26
-2
@@ -335,6 +335,8 @@ pub struct Bounce {
|
||||
gain: f32,
|
||||
peak: f32,
|
||||
meter: soundcraft_dsp::meter::LoudnessMeter,
|
||||
/// The file has an integer bit depth, so the encoder clips to full scale (a float file keeps its headroom).
|
||||
integer: bool,
|
||||
enc: Option<craft_audio::FileEncoder<Out>>,
|
||||
}
|
||||
|
||||
@@ -409,6 +411,7 @@ impl Bounce {
|
||||
peak: 0.0,
|
||||
meter,
|
||||
enc: Some(enc),
|
||||
integer: opts.bit_depth != craft_audio::BitDepth::Float32,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -438,6 +441,19 @@ impl Bounce {
|
||||
Some((chunk, n)) => {
|
||||
fill(&mut self.block, chunk, n, self.fold, self.gain);
|
||||
self.done += n;
|
||||
if !self.measuring {
|
||||
// The encoder clips an integer file to full scale and maps a float file's NaN to 0 and
|
||||
// infinities to +-1, so the report must describe what it writes.
|
||||
for v in self.block.iter_mut().flatten() {
|
||||
*v = if v.is_nan() {
|
||||
0.0
|
||||
} else if self.integer || v.is_infinite() {
|
||||
v.clamp(-1.0, 1.0)
|
||||
} else {
|
||||
*v
|
||||
};
|
||||
}
|
||||
}
|
||||
self.peak = self.peak.max(soundcraft_dsp::offline::peak(&self.block));
|
||||
if !self.measuring {
|
||||
self.meter.process(&self.block, n);
|
||||
@@ -1097,7 +1113,8 @@ fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::colle
|
||||
}
|
||||
|
||||
/// The record-enabled audio tracks, each with the input channels it records (those its input
|
||||
/// route names, "In 3" → 2, wrapped to the device's `input_channels`) and a new take file
|
||||
/// route names, "In 3" → 2, wrapped to the device's `input_channels`; with no input,
|
||||
/// [`NO_INPUT_CHANNEL`](crate::no_input::NO_INPUT_CHANNEL), which records silence) and a new take file
|
||||
/// `<track>_<NN>.wav` in the `Audio Files` of the session's folder (`unsaved_dir` until it is saved).
|
||||
pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<(TrackId, Vec<usize>, PathBuf)> {
|
||||
let dir = e.path.as_deref().and_then(|p| Path::new(p).parent()).unwrap_or(unsaved_dir);
|
||||
@@ -1113,7 +1130,11 @@ pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let inputs = (0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect();
|
||||
let inputs = if t.mixer.input == soundcraft_model::Route::None {
|
||||
vec![crate::no_input::NO_INPUT_CHANNEL; t.channels()]
|
||||
} else {
|
||||
(0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect()
|
||||
};
|
||||
let file = |n: usize| dir.join("Audio Files").join(format!("{}_{n:02}.wav", sanitize_name(&t.name)));
|
||||
let path = (take_no..take_no + 1_000).map(file).find(|p| !p.exists()).unwrap_or_else(|| file(take_no));
|
||||
(t.id, inputs, path)
|
||||
@@ -1241,7 +1262,10 @@ pub(crate) fn read_aaf_plan(_: &str, _: &str, _: Option<&str>) -> Result<Value>
|
||||
Err(EngineError::Io("AAF import needs the desktop app: its media files are read from a local folder".into()))
|
||||
}
|
||||
|
||||
// Every test here plants a link, so the module and its helper are Unix-only. `cfg(test)` stays an
|
||||
// attribute of its own: clippy allows `unwrap` in tests only under a plain `#[cfg(test)]`.
|
||||
#[cfg(test)]
|
||||
#[cfg(unix)]
|
||||
mod exclusive_tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -176,6 +176,13 @@ fn place_import(
|
||||
let file_rate = info.sample_rate;
|
||||
let s = e.session_mut();
|
||||
let session_rate = s.sample_rate.hz();
|
||||
// An explicit non-audio target cannot play the clip: refuse it before registering
|
||||
// the source, like `clip.place_source` does.
|
||||
if let Some(t) = target
|
||||
&& !s.track(t).is_some_and(|tr| tr.kind == TrackKind::Audio)
|
||||
{
|
||||
return Err(EngineError::BadParams("file.import_audio".into(), "audio files go on audio tracks".into()));
|
||||
}
|
||||
let src = add_source_audio(s, name, audio, path, FileFormat::of(info));
|
||||
if let (Some(bwf), Some(sx)) = (info.bwf.as_ref(), s.sources.last_mut()) {
|
||||
sx.time_reference = stamp_at_rate(bwf.time_reference, file_rate, session_rate);
|
||||
@@ -185,7 +192,8 @@ fn place_import(
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let stem = Path::new(name).file_stem().and_then(OsStr::to_str).unwrap_or("Audio").to_string();
|
||||
s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem))
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem));
|
||||
crate::no_input::assign_first_input(s, t)
|
||||
}
|
||||
};
|
||||
let cid = s.new_clip_id();
|
||||
|
||||
@@ -22,7 +22,11 @@ pub(super) const MAX_MIDI_TRACKS: usize = 512;
|
||||
pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: bool) -> Result<Vec<TrackId>> {
|
||||
let smf = match soundcraft_midi::read_smf(bytes) {
|
||||
Ok(smf) => smf,
|
||||
Err(err @ (soundcraft_midi::MidiError::TooManyEvents(_) | soundcraft_midi::MidiError::TooManyTracks(_))) => {
|
||||
Err(
|
||||
err @ (soundcraft_midi::MidiError::TooManyEvents(_)
|
||||
| soundcraft_midi::MidiError::TooManyTracks(_)
|
||||
| soundcraft_midi::MidiError::SysExTooLarge(_)),
|
||||
) => {
|
||||
return Err(EngineError::Io(err.to_string()));
|
||||
}
|
||||
Err(_) => {
|
||||
@@ -30,9 +34,10 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
|
||||
// The strict reader stops at the first damage, so a limit further on shows only here.
|
||||
if read.over_limit {
|
||||
return Err(EngineError::Io(format!(
|
||||
"MIDI file: more than {} events or {} tracks",
|
||||
"MIDI file exceeds a limit of {} events, {} tracks, or {} bytes of SysEx payload",
|
||||
soundcraft_midi::MAX_EVENTS,
|
||||
soundcraft_midi::MAX_TRACKS
|
||||
soundcraft_midi::MAX_TRACKS,
|
||||
soundcraft_midi::MAX_SYSEX_BYTES
|
||||
)));
|
||||
}
|
||||
for warning in &read.warnings {
|
||||
@@ -50,7 +55,8 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
|
||||
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TEMPOS} tempo changes")));
|
||||
}
|
||||
}
|
||||
let tracks_to_import = smf.tracks.iter().filter(|tr| !tr.sequence.notes.is_empty() || !tr.sequence.ctrls.is_empty()).count();
|
||||
let tracks_to_import =
|
||||
smf.tracks.iter().filter(|tr| !tr.sequence.notes.is_empty() || !tr.sequence.ctrls.is_empty() || !tr.sequence.sysex.is_empty()).count();
|
||||
if tracks_to_import > MAX_MIDI_TRACKS {
|
||||
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TRACKS} tracks")));
|
||||
}
|
||||
@@ -72,12 +78,13 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
|
||||
let base_tick = tempo.samples_to_ticks(at, s.sample_rate);
|
||||
let mut clips = Vec::new();
|
||||
for (i, tr) in smf.tracks.iter().enumerate() {
|
||||
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.is_empty() {
|
||||
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.is_empty() && tr.sequence.sysex.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// A controller on the clip's last tick would not play, so the clip runs one tick past the last one.
|
||||
let past_ctrls = tr.sequence.ctrls.iter().map(|c| c.tick.saturating_add(1)).max().unwrap_or(0);
|
||||
let end_tick = base_tick.saturating_add(tr.sequence.end_tick().max(past_ctrls).max(1));
|
||||
let past_sysex = tr.sequence.sysex.iter().map(|e| e.tick.saturating_add(1)).max().unwrap_or(0);
|
||||
let end_tick = base_tick.saturating_add(tr.sequence.end_tick().max(past_ctrls).max(past_sysex).max(1));
|
||||
let len = tempo.tick_to_samples(end_tick, s.sample_rate).saturating_sub(at);
|
||||
if len > s.sample_rate.samples(86_400.0) {
|
||||
return Err(EngineError::Io(format!("MIDI track {}: longer than 24 hours", i + 1)));
|
||||
@@ -125,8 +132,14 @@ pub fn export_midi(e: &Engine, only: Option<&[TrackId]>) -> Result<Vec<u8>> {
|
||||
for c in t.clips() {
|
||||
if let ClipContent::Midi { sequence } = &c.content {
|
||||
let base = s.tempo.samples_to_ticks(c.start, s.sample_rate);
|
||||
// Only what plays: notes starting inside the clip, cut at its end.
|
||||
// Only what plays: notes starting inside the clip (cut at its end), and the
|
||||
// controllers and SysEx inside it.
|
||||
let clip_end = s.tempo.samples_to_ticks(c.end(), s.sample_rate);
|
||||
for event in sequence.sysex.iter().filter(|event| event.tick.saturating_add(base) < clip_end) {
|
||||
let mut event = event.clone();
|
||||
event.tick = event.tick.saturating_add(base);
|
||||
seq.sysex.push(event);
|
||||
}
|
||||
for n in sequence.notes.iter().filter(|n| n.start.saturating_add(base) < clip_end) {
|
||||
let mut n = *n;
|
||||
n.start = n.start.saturating_add(base);
|
||||
|
||||
@@ -87,7 +87,7 @@ fn lost_covers(lost: u8, device: u8) -> bool {
|
||||
}
|
||||
|
||||
/// What `track` recorded of `events` over `range`, in ticks from the start of the range. A key
|
||||
/// already down when the range starts is left out; one still down at its end ends there, and one
|
||||
/// already down when the range starts sounds from its start, as long as it is held; one still down at its end ends there, and one
|
||||
/// whose device lost input ends where that happened. Keys are told apart by device, channel and
|
||||
/// pitch: the same pitch held on two devices gives two notes. A key held while loop recording
|
||||
/// goes round ([`MidiTakeEvent::WRAP`]) is two notes: to the end of the loop, and from its start;
|
||||
@@ -108,9 +108,10 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
// The round of the loop being played: it goes up at every `WRAP`.
|
||||
let mut round = 0u32;
|
||||
// Keys down: (device, channel, pitch) -> (start tick, velocity, round, the sample the key was
|
||||
// pressed at). Whether the loop went round between a press and its release is judged by
|
||||
// their samples: two positions a few samples apart may share a tick, and a press in the
|
||||
// last samples of the range starts its note a tick earlier so that it plays.
|
||||
// pressed at, which is before the range only for a key held into it). Whether the loop went
|
||||
// round between a press and its release is judged by their samples: two positions a few
|
||||
// samples apart may share a tick, and a press in the last samples of the range starts its
|
||||
// note a tick earlier so that it plays.
|
||||
let mut down: HashMap<(u8, u8, u8), (i64, u8, u32, Samples)> = HashMap::new();
|
||||
let close = |seq: &mut Sequence,
|
||||
(_, channel, pitch): (u8, u8, u8),
|
||||
@@ -152,7 +153,16 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
round = round.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
if e.at < range.start || e.at >= range.end {
|
||||
if e.at < range.start {
|
||||
// Before the range (the pre-roll, or before the punch-in): a key pressed there and
|
||||
// still down when the range starts is recorded from the start of the range, "the
|
||||
// start of the note is quantized to the punch-in point" (Reference Guide p.822).
|
||||
// An entry there that ends a note pressed in the range is a late callback, as below.
|
||||
if round > 0 || held_into_range(s, input, devices, e, &mut down, range.start) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if e.at >= range.end {
|
||||
continue;
|
||||
}
|
||||
let at = tick(e.at);
|
||||
@@ -175,7 +185,7 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
match e.status & 0xF0 {
|
||||
0x90 if d2 > 0 => {
|
||||
// The same key again without a release: the first note ends here.
|
||||
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at)) {
|
||||
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at.max(range.start))) {
|
||||
close(&mut seq, key, open, at, 64, round, e.at);
|
||||
}
|
||||
}
|
||||
@@ -209,6 +219,45 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
|
||||
seq
|
||||
}
|
||||
|
||||
/// Follow the keys pressed and released before a record range starts, in `down` (as the take
|
||||
/// builder keeps them: start tick, velocity, round, the sample the key was pressed at, which for
|
||||
/// these keys alone is before `start`). A key still down when the range starts goes on from its
|
||||
/// first tick; one released before it, or whose device lost input, leaves nothing. Returns
|
||||
/// false when `e` is left to the range: a lost-input entry (for the keys pressed in the range),
|
||||
/// or an entry for a key pressed in the range, stamped early by a late audio callback.
|
||||
fn held_into_range(
|
||||
s: &Session,
|
||||
input: &MidiInput<'_>,
|
||||
devices: &[String],
|
||||
e: &MidiTakeEvent,
|
||||
down: &mut HashMap<(u8, u8, u8), (i64, u8, u32, Samples)>,
|
||||
start: Samples,
|
||||
) -> bool {
|
||||
if e.status == MidiTakeEvent::LOST {
|
||||
down.retain(|k, open| open.3 >= start || !lost_covers(e.device, k.0));
|
||||
return false;
|
||||
}
|
||||
let channel = e.status & 0x0F;
|
||||
if midi_filtered(s, e.status) || !input.accepts(devices.get(usize::from(e.device)).map(String::as_str), channel) {
|
||||
return true;
|
||||
}
|
||||
let key = (e.device, channel, e.data1 & 0x7F);
|
||||
let note = matches!(e.status & 0xF0, 0x80 | 0x90);
|
||||
if note && down.get(&key).is_some_and(|open| open.3 >= start) {
|
||||
return false;
|
||||
}
|
||||
match e.status & 0xF0 {
|
||||
0x90 if e.data2 & 0x7F > 0 => {
|
||||
down.insert(key, (0, e.data2 & 0x7F, 0, e.at));
|
||||
}
|
||||
0x80 | 0x90 => {
|
||||
down.remove(&key);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Most events of one MIDI record pass that are kept.
|
||||
pub const MAX_MIDI_TAKE_EVENTS: usize = 1 << 20;
|
||||
|
||||
@@ -310,7 +359,7 @@ mod tests {
|
||||
assert_eq!(e.session().busses.len(), 0, "a MIDI input is not a bus name");
|
||||
assert!(records_midi(&e));
|
||||
let events = [
|
||||
ev(40_000, 0, 0x90, 59, 80), // before the pass: left out, and so is its release
|
||||
ev(40_000, 0, 0x90, 59, 80), // before the pass, released inside it: from the pass start
|
||||
ev(48_000, 0, 0x90, 60, 100), // one beat at 120 bpm, 48 kHz: 24 000 samples = 960 ticks
|
||||
ev(50_000, 0, 0x80, 59, 0),
|
||||
ev(60_000, 1, 0x99, 36, 127),
|
||||
@@ -328,7 +377,7 @@ mod tests {
|
||||
assert_eq!((before, take.clips.len(), take.gaps), (0, 2, 0), "the track whose device was silent gets no clip");
|
||||
let keys = sequence(&e, all, range);
|
||||
let notes: Vec<(u8, u8, i64, i64, u8)> = keys.notes.iter().map(|n| (n.channel, n.pitch, n.start, n.length, n.release_velocity)).collect();
|
||||
assert_eq!(notes, [(0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
|
||||
assert_eq!(notes, [(0, 59, 0, 80, 0), (0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
|
||||
assert_eq!(
|
||||
keys.ctrls.iter().map(|c| (c.tick, c.kind, c.value)).collect::<Vec<_>>(),
|
||||
[(960, CtrlKind::PitchBend, 4096), (1680, CtrlKind::Cc(64), 127)]
|
||||
@@ -345,6 +394,28 @@ mod tests {
|
||||
assert!(add_midi_recording(&mut e, Range::new(5, 5), &events, &devices, false).clips.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_held_into_the_punch_in_is_recorded_from_the_punch_in() {
|
||||
// Reference Guide p.822: played before the punch-in point, released after it.
|
||||
let s = Session::default();
|
||||
let range = Range::new(48_000, 144_000);
|
||||
let events = [
|
||||
ev(24_000, 0, 0x90, 60, 100), // held into the range
|
||||
ev(30_000, 0, 0x90, 62, 100), // pressed and released before it: nothing
|
||||
ev(36_000, 0, 0x80, 62, 0),
|
||||
ev(40_000, 0, 0x90, 64, 90), // another one released before it
|
||||
ev(44_000, 0, 0x80, 64, 0),
|
||||
ev(72_000, 0, 0x80, 60, 30), // the held key, released one quarter into the range
|
||||
ev(96_000, 0, 0x90, 67, 100),
|
||||
ev(120_000, 0, 0x80, 67, 0),
|
||||
];
|
||||
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events, &[]));
|
||||
assert_eq!(got, [(0, 60, 0, 960, 100, 30), (0, 67, 1920, 960, 100, 0)]);
|
||||
// A key still down at the end of the range covers all of it.
|
||||
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events[..1], &[]));
|
||||
assert_eq!(got, [(0, 60, 0, 3840, 100, 64)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_pitch_on_two_devices_is_two_notes_and_lost_input_ends_only_its_device() {
|
||||
let mut e = Engine::default();
|
||||
@@ -550,6 +621,21 @@ mod tests {
|
||||
let marked = [ev(24_000, 0, 0x90, 60, 100), ev(96_000, u8::MAX, MidiTakeEvent::WRAP, 0, 0), ev(48_000, 0, 0x80, 60, 0)];
|
||||
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &marked, &[]));
|
||||
assert_eq!(got.iter().map(|n| (n.2, n.3)).collect::<Vec<_>>(), [(960, 960)]);
|
||||
// A punch range: a key pressed in it whose release is stamped before its start is one
|
||||
// short note at the press too, and a key pressed and released before it stays out.
|
||||
let punch = Range::new(48_000, 144_000);
|
||||
let events = [
|
||||
ev(30_000, 0, 0x90, 62, 100),
|
||||
ev(36_000, 0, 0x80, 62, 0),
|
||||
ev(49_000, 0, 0x90, 60, 100),
|
||||
ev(47_000, 0, 0x80, 60, 40),
|
||||
ev(72_000, 0, 0x90, 64, 100),
|
||||
ev(47_400, 0, 0xB0, 64, 127), // a controller stamped there is still left out
|
||||
ev(47_500, u8::MAX, MidiTakeEvent::LOST, 0, 0),
|
||||
];
|
||||
let seq = midi_take_sequence(&s, &MidiInput::default(), punch, MidiPass::Linear, &events, &[]);
|
||||
assert_eq!(notes_of(&seq), [(0, 60, 40, 1, 100, 40), (0, 64, 960, 1, 100, 64)]);
|
||||
assert!(seq.ctrls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -562,7 +562,9 @@ mod open_tests {
|
||||
let at = |f: &str| dir.join(f).to_string_lossy().into_owned();
|
||||
assert_eq!(got[0], (stored_path("Movies/here.mov", &session).unwrap().to_string_lossy().into_owned(), None));
|
||||
assert_eq!(got[1], (at("near.mov"), None));
|
||||
assert_eq!(got[2], (at("Video Files/filed.mov"), None));
|
||||
// Joined part by part, as `relink_videos` does: `join("Video Files/filed.mov")` keeps the `/`,
|
||||
// which differs from the relinked path on Windows.
|
||||
assert_eq!(got[2], (dir.join("Video Files").join("filed.mov").to_string_lossy().into_owned(), None));
|
||||
assert_eq!(got[3], ("Old/gone.mov".into(), Some("file not found".into())));
|
||||
assert_eq!(got[4].0, stored[4]);
|
||||
assert!(got[4].1.as_deref().is_some_and(|why| why.starts_with("not opened:")), "{:?}", got[4]);
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod feature_names;
|
||||
pub mod file_access;
|
||||
pub mod inspect;
|
||||
pub mod io;
|
||||
pub mod no_input;
|
||||
pub mod score;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -112,6 +113,9 @@ pub struct TransportStatus {
|
||||
pub struct Clipboard {
|
||||
pub length: Samples,
|
||||
pub tracks: Vec<Vec<Clip>>,
|
||||
/// Visible duration at copy time. An ordinary paste keeps the underlying clip's trim handles,
|
||||
/// whereas merging materializes only its selected MIDI events, even after a tempo change.
|
||||
pub midi_tick_lengths: std::collections::BTreeMap<soundcraft_model::ClipId, i64>,
|
||||
pub automation: Vec<Vec<soundcraft_model::AutomationLane>>,
|
||||
/// Copy Special › Clip Gain: per track, (offset from the copied range start, dB) breakpoints.
|
||||
pub clip_gain: Vec<Vec<(Samples, f32)>>,
|
||||
@@ -130,6 +134,19 @@ pub struct Clipboard {
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
/// Store one track of range-relative clips and capture the source tempo before a paste.
|
||||
pub(crate) fn push_clips(&mut self, session: &Session, range_start: Samples, clips: Vec<Clip>) {
|
||||
for clip in &clips {
|
||||
if matches!(clip.content, soundcraft_model::ClipContent::Midi { .. }) {
|
||||
let start = range_start.saturating_add(clip.start);
|
||||
let end = start.saturating_add(clip.length);
|
||||
let ticks = |at| session.tempo.samples_to_ticks(at, session.sample_rate);
|
||||
self.midi_tick_lengths.insert(clip.id, ticks(end).saturating_sub(ticks(start)));
|
||||
}
|
||||
}
|
||||
self.tracks.push(clips);
|
||||
}
|
||||
|
||||
/// An empty clipboard for material copied from `range`.
|
||||
pub fn of_range(s: &Session, range: soundcraft_time::Range) -> Clipboard {
|
||||
let line = s.grid_line_at_or_before(range.start);
|
||||
@@ -220,8 +237,9 @@ impl Default for Engine {
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(session: Session) -> Self {
|
||||
pub fn new(mut session: Session) -> Self {
|
||||
install_panic_hook();
|
||||
no_input::upgrade_legacy_inputs(&mut session);
|
||||
let doc = Arc::new(session);
|
||||
Engine {
|
||||
saved: Arc::clone(&doc),
|
||||
@@ -296,8 +314,10 @@ impl Engine {
|
||||
&mut Arc::make_mut(&mut self.doc).edit.zoom
|
||||
}
|
||||
|
||||
/// Replace the whole document (open / new); clears history.
|
||||
pub fn replace_session(&mut self, s: Session) {
|
||||
/// Replace the whole document (open / new); clears history. A session saved before "no
|
||||
/// input" existed is upgraded ([`no_input::upgrade_legacy_inputs`]).
|
||||
pub fn replace_session(&mut self, mut s: Session) {
|
||||
no_input::upgrade_legacy_inputs(&mut s);
|
||||
self.transport = TransportStatus { position: s.edit.selection.start.max(0), ..TransportStatus::default() };
|
||||
self.transport_requests.clear();
|
||||
self.transport_requests.push(TransportRequest::ResetSession);
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! "no input" on an audio track (`Route::None`): the track records and monitors nothing, as
|
||||
//! Pro Tools' No Input does. A new audio track gets its first input path explicitly instead.
|
||||
//!
|
||||
//! Sessions saved before this rule used `Route::None` for an audio track that recorded and
|
||||
//! monitored hardware input 1 (the selector showed "In 1"). [`upgrade_legacy_inputs`] turns
|
||||
//! those into the explicit first input when such a session is opened, so it keeps sounding and
|
||||
//! recording as before. Sessions held by the engine carry [`NO_INPUT_MARKER`], so a "no input"
|
||||
//! saved by this build stays "no input" when it is opened again.
|
||||
|
||||
use soundcraft_model::{ChannelFormat, Route, Session, TrackKind};
|
||||
|
||||
/// Set in `edit.flags` of every session the engine holds: its `Route::None` audio inputs mean
|
||||
/// "no input". A session without it was saved before that, when they meant hardware input 1.
|
||||
pub const NO_INPUT_MARKER: &str = "io.none_is_no_input";
|
||||
|
||||
/// The input channel an audio track with no input records: no device has it, so the take is
|
||||
/// digital silence.
|
||||
pub const NO_INPUT_CHANNEL: usize = usize::MAX;
|
||||
|
||||
/// The first hardware input path of a track of `format`: "In 1", "In 1-2", "In 1-6"…
|
||||
pub fn first_input(format: ChannelFormat) -> Route {
|
||||
match format.channels() {
|
||||
0 | 1 => Route::Hardware("In 1".into()),
|
||||
n => Route::Hardware(format!("In 1-{n}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the new track `id`, if it is an audio track, its first input path (Pro Tools assigns
|
||||
/// new tracks an input path), and return `id`.
|
||||
pub(crate) fn assign_first_input(s: &mut Session, id: soundcraft_model::TrackId) -> soundcraft_model::TrackId {
|
||||
if let Some(t) = s.track_mut(id)
|
||||
&& t.kind == TrackKind::Audio
|
||||
&& t.mixer.input == Route::None
|
||||
{
|
||||
t.mixer.input = first_input(t.format);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// A session saved before [`NO_INPUT_MARKER`]: each audio track whose input is `Route::None`
|
||||
/// recorded and monitored hardware input 1, so it gets that input explicitly. Then the session
|
||||
/// is marked, and running this again changes nothing.
|
||||
pub fn upgrade_legacy_inputs(s: &mut Session) {
|
||||
if s.edit.flag(NO_INPUT_MARKER) {
|
||||
return;
|
||||
}
|
||||
for t in &mut s.tracks {
|
||||
if t.kind == TrackKind::Audio && t.mixer.input == Route::None {
|
||||
t.mixer.input = first_input(t.format);
|
||||
}
|
||||
}
|
||||
s.edit.set_flag(NO_INPUT_MARKER, true);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Engine;
|
||||
use serde_json::json;
|
||||
use soundcraft_model::TrackId;
|
||||
|
||||
fn new_track(e: &mut Engine, format: &str) -> TrackId {
|
||||
TrackId(e.execute("track.new", &json!({"format": format})).unwrap()["tracks"][0].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn input(e: &Engine, t: TrackId) -> Route {
|
||||
e.session().track(t).unwrap().mixer.input.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_audio_track_gets_its_first_input_path() {
|
||||
let mut e = Engine::default();
|
||||
let mono = new_track(&mut e, "mono");
|
||||
let stereo = new_track(&mut e, "stereo");
|
||||
assert_eq!(input(&e, mono), Route::Hardware("In 1".into()));
|
||||
assert_eq!(input(&e, stereo), Route::Hardware("In 1-2".into()));
|
||||
let aux = TrackId(e.execute("track.new", &json!({"kind": "aux"})).unwrap()["tracks"][0].as_u64().unwrap());
|
||||
assert_eq!(input(&e, aux), Route::None, "only audio tracks take a hardware input by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_track_with_no_input_records_no_device_channel() {
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-no-input-{}", std::process::id()));
|
||||
let mut e = Engine::default();
|
||||
let vox = new_track(&mut e, "mono");
|
||||
let gtr = new_track(&mut e, "stereo");
|
||||
e.execute("track.input", &json!({"tracks": [vox.0, gtr.0], "input": "none"})).unwrap();
|
||||
e.execute("mix.record_arm", &json!({"tracks": [vox.0, gtr.0], "value": true})).unwrap();
|
||||
let plan = crate::io::plan_takes(&e, &dir, 30);
|
||||
assert_eq!(
|
||||
plan.iter().map(|(t, inputs, _)| (*t, inputs.clone())).collect::<Vec<_>>(),
|
||||
vec![(vox, vec![NO_INPUT_CHANNEL]), (gtr, vec![NO_INPUT_CHANNEL; 2])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_saved_before_no_input_existed_keeps_recording_input_1() {
|
||||
let mut old = Session::default();
|
||||
let vox = old.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Vox"));
|
||||
let gtr = old.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Gtr"));
|
||||
let keys = old.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys"));
|
||||
let text = old.to_json().unwrap();
|
||||
assert!(!text.contains(NO_INPUT_MARKER));
|
||||
let mut e = Engine::default();
|
||||
e.replace_session(Session::from_json(&text).unwrap());
|
||||
assert_eq!(input(&e, vox), Route::Hardware("In 1".into()));
|
||||
assert_eq!(input(&e, gtr), Route::Hardware("In 1-2".into()));
|
||||
assert_eq!(input(&e, keys), Route::None, "a MIDI input is left alone");
|
||||
assert!(!e.is_dirty(), "opening an old session does not modify it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_input_survives_save_and_reopen() {
|
||||
let mut e = Engine::default();
|
||||
let vox = new_track(&mut e, "mono");
|
||||
e.execute("track.input", &json!({"tracks": [vox.0], "input": "no input"})).unwrap();
|
||||
let text = e.session().to_json().unwrap();
|
||||
let mut reopened = Engine::default();
|
||||
reopened.replace_session(Session::from_json(&text).unwrap());
|
||||
assert_eq!(input(&reopened, vox), Route::None);
|
||||
}
|
||||
}
|
||||
@@ -437,3 +437,105 @@ fn repeated_local_mob_references_fail_before_property_expansion() {
|
||||
let err = f.preview().unwrap_err().to_string();
|
||||
assert!(err.contains("duplicate local reference in mobs"), "{err}");
|
||||
}
|
||||
|
||||
/// A FilmCraft-style AAF that references one external mono PCM WAV per channel, written by the
|
||||
/// shared `craft-aaf` writer around WAVs generated here.
|
||||
struct MonoWavAaf {
|
||||
dir: PathBuf,
|
||||
}
|
||||
impl MonoWavAaf {
|
||||
fn new(wav_channels: usize) -> Self {
|
||||
use craft_aaf::model::{CClip, CItem, CKind, CTrack, Composition, Document, Source};
|
||||
use craft_aaf::time::{FrameRate, Tick};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-aaf-mono-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let frames = 96_000;
|
||||
let options = EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(BitDepth::Int16);
|
||||
let mut sources = Vec::new();
|
||||
let mut tracks = Vec::new();
|
||||
for (i, name) in ["Dialogue.A1.wav", "Dialogue.A2.wav"].into_iter().enumerate() {
|
||||
let audio = AudioBuffer { sample_rate: 48000, channels: vec![vec![0.25; frames]; wav_channels] };
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, craft_audio::encode(&audio, &options).unwrap()).unwrap();
|
||||
sources.push(Source {
|
||||
key: "item:1".into(),
|
||||
name: name.into(),
|
||||
kind: CKind::Sound,
|
||||
path: Some(path.display().to_string()),
|
||||
channel: None,
|
||||
channels: 1,
|
||||
file_channels: 1,
|
||||
width: 0,
|
||||
height: 0,
|
||||
frame_rate: FrameRate::FPS_25,
|
||||
sample_rate: 48000,
|
||||
bits: 16,
|
||||
length: Tick::from_units(frames as i64, 48000),
|
||||
offset: Tick::ZERO,
|
||||
start_tc: None,
|
||||
tc_rate: FrameRate::FPS_25,
|
||||
embedded: None,
|
||||
markers: Vec::new(),
|
||||
nested: None,
|
||||
});
|
||||
let clip = CClip { len: Tick::from_units(25, 25), source: i, start: Tick::ZERO, gain: None, name: format!("Cut {}", i + 1) };
|
||||
tracks.push(CTrack {
|
||||
kind: CKind::Sound,
|
||||
name: format!("A{}", i + 1),
|
||||
number: i as u32 + 1,
|
||||
channels: 1,
|
||||
items: vec![CItem::Clip(clip)],
|
||||
});
|
||||
}
|
||||
let composition = Composition {
|
||||
name: "Separate mono".into(),
|
||||
aaf_mob_id: None,
|
||||
rate: FrameRate::FPS_25,
|
||||
sample_rate: 48000,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
start_tc: 0,
|
||||
drop: false,
|
||||
tracks,
|
||||
markers: Vec::new(),
|
||||
};
|
||||
let doc = Document { compositions: vec![composition], sources, ..Document::default() };
|
||||
let identity =
|
||||
craft_aaf::Identity { company: "Craft", product: "soundcraft tests", version: "1", platform: "test", product_id: *b"soundcraft-test." };
|
||||
let bytes =
|
||||
craft_aaf::aaf::write(&doc, &craft_aaf::aaf::WriteOptions { identity, small_sectors: false }, &mut craft_aaf::Report::default()).unwrap();
|
||||
std::fs::write(dir.join("Separate mono.aaf"), bytes).unwrap();
|
||||
Self { dir }
|
||||
}
|
||||
fn preview(&self) -> soundcraft_engine::Result<Value> {
|
||||
Engine::default().execute("file.preview_aaf", &json!({"path": self.dir.join("Separate mono.aaf"), "media_dir": self.dir}))
|
||||
}
|
||||
}
|
||||
impl Drop for MonoWavAaf {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_mono_pcm_wav_aaf_imports_one_mono_track_per_file() {
|
||||
let f = MonoWavAaf::new(1);
|
||||
let preview = f.preview().unwrap();
|
||||
let plan = &preview["plan"];
|
||||
let channels: Vec<_> = plan["sources"].as_array().unwrap().iter().map(|s| s["channels"].as_u64().unwrap()).collect();
|
||||
assert_eq!(channels, [1, 1]);
|
||||
let mut e = Engine::default();
|
||||
e.execute("file.import_aaf", &json!({"plan": plan, "media_dir": f.dir, "selected": [0, 1]})).unwrap();
|
||||
assert_eq!(e.session().tracks.len(), 2);
|
||||
assert!(e.session().tracks.iter().all(|t| t.channels() == 1 && t.clips().len() == 1));
|
||||
let sources: Vec<_> = e.session().tracks.iter().map(|t| t.clips()[0].source()).collect();
|
||||
assert_ne!(sources[0], sources[1], "each channel file is its own source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pcm_descriptor_whose_channel_count_differs_from_its_wav_is_refused() {
|
||||
let f = MonoWavAaf::new(2);
|
||||
let err = f.preview().unwrap_err().to_string();
|
||||
assert!(err.contains("channel counts differ"), "{err}");
|
||||
}
|
||||
|
||||
@@ -66,6 +66,39 @@ fn scratch(name: &str) -> PathBuf {
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_bounce_reports_the_levels_of_the_clipped_file() {
|
||||
let mut e = soundcraft_engine::Engine::default();
|
||||
let sr = e.session().sample_rate.hz();
|
||||
let frames = sr as usize;
|
||||
let samples: Vec<f32> = (0..frames).map(|i| 1.5 * (std::f32::consts::TAU * 440.0 * i as f32 / sr as f32).sin()).collect();
|
||||
let audio = craft_audio::AudioBuffer { sample_rate: sr, channels: vec![samples.clone(), samples] };
|
||||
let s = e.session_mut();
|
||||
let track = s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::Stereo, Some("Hot"));
|
||||
let source = soundcraft_engine::io::add_source(s, "hot", audio, None, FileFormat::Wav);
|
||||
let clip = soundcraft_model::Clip::audio(s.new_clip_id(), "hot", source, 0, 0, frames as i64);
|
||||
soundcraft_engine::edit::place_clip(s, track, clip);
|
||||
let mix = soundcraft_mix::render_range(e.session(), Range::new(0, frames as i64), 1024);
|
||||
assert!(soundcraft_dsp::offline::peak(&mix) > 1.0);
|
||||
let dir = scratch("bounce-int-clipped");
|
||||
let path = dir.join("Mix.wav");
|
||||
let r = e.execute("file.bounce_mix", &serde_json::json!({"path": path, "bit_depth": 16, "dither": false, "start": 0, "end": frames})).unwrap();
|
||||
let (_, file) = craft_audio::decode(&std::fs::read(&path).unwrap(), None).unwrap();
|
||||
assert!(file.peak() <= 1.0);
|
||||
let mut meter = soundcraft_dsp::meter::LoudnessMeter::new(sr as f32, file.channels.len());
|
||||
meter.process(&file.channels, file.frames());
|
||||
for (key, value, tolerance) in [
|
||||
("peak_db", soundcraft_dsp::offline::peak_db(&file.channels), 0.01),
|
||||
("lufs", meter.integrated_lufs(), 0.05),
|
||||
("true_peak_db", meter.true_peak_db(), 0.05),
|
||||
] {
|
||||
let reported = r[key].as_f64().unwrap();
|
||||
assert!((reported - f64::from(value)).abs() < tolerance, "{key}: reported {reported}, file {value}");
|
||||
}
|
||||
assert!(r["peak_db"].as_f64().unwrap() <= 0.0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounces_write_exactly_the_mix_and_report_its_levels() {
|
||||
let e = soundcraft_engine::demo::demo_engine();
|
||||
|
||||
@@ -17,8 +17,10 @@ mod new_track_rows;
|
||||
mod processing_keeps_crossfades;
|
||||
mod random_edits;
|
||||
mod recording;
|
||||
mod session_inspect;
|
||||
mod session_transport;
|
||||
mod split_into_mono;
|
||||
mod sysex_import;
|
||||
mod time_key_signatures;
|
||||
mod track_name_collisions;
|
||||
mod trim_to_selection;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user