Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor 0a166a5d00 ci: verify the actions lockfile in CI
Fails the build when .github/workflows/actions.lock stops matching the
workflows, or when a locked pin no longer verifies upstream, so a stale or
tampered lockfile cannot go unnoticed between dependency updates.
2026-11-12 07:23:19 -05:00
Dylan M. Taylor 220b42773d ci: lock workflow actions through an actions.lock lockfile
Mutable action tags are a supply-chain risk: a moved tag runs different code
without a diff. Every workflow action is now pinned through
.github/workflows/actions.lock, and CI verifies the lockfile so an out-of-sync
or tampered one fails instead of running.
2026-11-12 07:18:10 -05:00
167 changed files with 18901 additions and 8271 deletions
+32
View File
@@ -0,0 +1,32 @@
# This file is machine-generated by `gh actions-lock`.
# Do not edit by hand; run `gh actions-lock` to update.
# Docs: https://gh.io/actions-lockfile
version: 'v0.0.3'
workflows:
'.github/workflows/ast-grep.yml': []
'.github/workflows/ci.yml': []
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nix.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
dependencies:
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
+34
View File
@@ -0,0 +1,34 @@
name: Lockfile
# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin
# no longer verifies upstream, so a moved tag cannot slip a different commit into a run.
# Docs: https://gh.io/actions-lockfile
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
env:
GH_TOKEN: ${{ github.token }}
jobs:
lockfile:
name: Lockfile is in sync
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install gh-actions-lock
run: gh extension install github/gh-actions-lock --pin v0.4.1
- name: Verify the lockfile
run: gh actions-lock --verify
+40 -2
View File
@@ -23,5 +23,43 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
git-sources:
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
name: Git dependencies come from storytold
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
+2 -2
View File
@@ -28,10 +28,10 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
+2 -9
View File
@@ -109,16 +109,9 @@ Parity is measured, not guessed: `crates/engine/catalog/menus.txt` lists the inc
- Drive it: JSON lines over TCP, e.g. `{"id":1,"method":"engine.execute","params":{"command":"track.new","params":{"count":2,"format":"stereo"}}}`, then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`.
- Offscreen UI render (no window, no focus stealing): `cargo run -p soundcraft-ui-egui --example ui_shot -- out.png [script.jsonl]`.
- Headless: `soundcraft-cli run --demo --cmd 'mix.volume={"track":"Kick","db":-6}' --bounce out.wav`; MCP: `soundcraft-cli mcp [--connect PORT]`.
- **Language / localization:** the interface is English by default; Brazilian Portuguese
(`pt-BR`) is selected under `Setup › Appearance › Language` (or the `ui.language` command with
`{"language":"pt-BR"}`). The pt-BR catalog is complete for every fixed UI string — tests cover
placeholder parity, unique keys and source coverage, and the `cargo test` suite passes.
- Commands: build `cargo build -p soundcraft --bin soundcraft`; test
`cargo test -p soundcraft --bin soundcraft`; run `DISPLAY=:0 ./target/debug/soundcraft`. The
`cargo xtask ci` gate runs formatting, clippy, tests, assets, layering and the WebAssembly build.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write
manifests atomically; delete your target dir when done (disk).
- **For UI work, look at the result** (render, read the PNG) and compare with `plan/protools/screenshots/`.
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically; delete your target dir when done (disk).
## Quality gates (before every commit)
`cargo xtask ci` = fmt check, `clippy --workspace --all-targets -D warnings`, tests, assets, layers, wasm check. Commit after each arc of work that builds; one topic per commit.
Generated
+20 -101
View File
@@ -1064,7 +1064,7 @@ dependencies = [
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
source = "git+https://github.com/storytold/craft-libs?rev=7db4645d1f1673df3b064de32faa3335bcdd7aed#7db4645d1f1673df3b064de32faa3335bcdd7aed"
dependencies = [
"craft-media",
"log",
@@ -1073,25 +1073,20 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1114,7 +1109,7 @@ dependencies = [
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
source = "git+https://github.com/storytold/craft-libs?rev=7db4645d1f1673df3b064de32faa3335bcdd7aed#7db4645d1f1673df3b064de32faa3335bcdd7aed"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1123,40 +1118,7 @@ dependencies = [
[[package]]
name = "craft-midi"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
dependencies = [
"chrono",
"craft-codepage",
"encoding_rs",
]
[[package]]
name = "craft-scraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"craft-audio",
"craft-midi",
"craft-time",
"craft-zip",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
source = "git+https://github.com/storytold/craft-libs?rev=7db4645d1f1673df3b064de32faa3335bcdd7aed#7db4645d1f1673df3b064de32faa3335bcdd7aed"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1165,7 +1127,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1186,7 +1148,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"chrono",
"dunce",
@@ -1210,35 +1172,6 @@ dependencies = [
"zip",
]
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"craft-media",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -1572,20 +1505,6 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "encoding_rs"
version = "0.8.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "endi"
version = "1.1.1"
@@ -2789,12 +2708,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "naga"
version = "30.0.1"
@@ -4533,8 +4446,6 @@ version = "0.20.1"
dependencies = [
"craft-audio",
"craft-docpath",
"craft-scraft-format",
"craft-xml",
"log",
"proptest",
"serde",
@@ -4581,7 +4492,13 @@ dependencies = [
name = "soundcraft-model"
version = "0.20.1"
dependencies = [
"craft-scraft-format",
"craft-audio",
"proptest",
"serde",
"serde_json",
"soundcraft-midi",
"soundcraft-time",
"thiserror 2.0.21",
]
[[package]]
@@ -4603,7 +4520,10 @@ dependencies = [
name = "soundcraft-time"
version = "0.20.1"
dependencies = [
"craft-time",
"proptest",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
@@ -4611,7 +4531,6 @@ name = "soundcraft-ui-egui"
version = "0.20.1"
dependencies = [
"craft-audio",
"craft-mime",
"craft-ui",
"craft-update",
"egui",
@@ -4642,9 +4561,9 @@ name = "soundcraft-video"
version = "0.20.1"
dependencies = [
"craft-media",
"craft-video",
"image",
"proptest",
"rayon",
"serde",
"thiserror 2.0.21",
]
+6 -12
View File
@@ -11,8 +11,6 @@ rust-version = "1.95"
repository = "https://github.com/storytold/soundcraft"
[workspace.dependencies]
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
# internal
soundcraft-time = { path = "crates/time" }
soundcraft-midi = { path = "crates/midi" }
@@ -50,24 +48,20 @@ zip = { version = "9", default-features = false }
cpal = "0.18"
# Which file paths stored in a session may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
# Video containers and bitstreams, shared with the other craft apps.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c" }
# 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 = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c", default-features = false, features = ["h264-decode", "prores"] }
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7db4645d1f1673df3b064de32faa3335bcdd7aed" }
# 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 = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c" }
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7db4645d1f1673df3b064de32faa3335bcdd7aed", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7db4645d1f1673df3b064de32faa3335bcdd7aed", features = ["decode", "lossless-encode", "peaks", "serde"] }
# 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 = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", features = ["egui"] }
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", features = ["serde"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] }
egui = { version = "0.37" }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
+4 -14
View File
@@ -243,10 +243,10 @@ about egui, so the interface could be swapped for another one.
| Crate | What it does |
|---|---|
| `soundcraft-time` | Compatibility re-export of `craft-time`'s SoundCraft sample-index API |
| `soundcraft-time` | Timebases, tempo and meter maps, timecode, grid |
| `soundcraft-midi` | Standard MIDI Files and MIDI operations |
| `soundcraft-dsp` | Plugins, offline processing, meters, loudness, FFT |
| `soundcraft-model` | Compatibility re-export of `craft-scraft-format`'s schema, validation and JSON API |
| `soundcraft-model` | The session document |
| `soundcraft-mix` | The mix engine (realtime and offline share it) |
| `soundcraft-engine` | Commands, undo, editing, import/export, bounce |
| `soundcraft-playback` | Audio devices (CoreAudio, WASAPI, ALSA, WebAudio) and recording |
@@ -263,18 +263,8 @@ SoundCraft is **pre-alpha**: it covers 94 % of the incumbent's menu items (measu
its features by presence, and is roughly 40 % of the way to replacing it for real work: record,
edit, mix and bounce work end to end, but choosing an audio interface and buffer size,
recording MIDI from a controller and session interchange (AAF/OMF) are still missing, and those
are the alpha checklist.
**Translations:** the Brazilian Portuguese (`pt-BR`) catalog is **100 % complete** for every fixed
UI string found in the current source — menus, dialogs and buttons, tooltips (including those
localized inside buttons and toggles), accessibility names, the Edit-window status bar, the
remove-session question, formatted messages, engine error templates and engine error text at display
time. All these entries are covered by a test, placeholders match, keys are unique, and the
`pt-BR` catalog is chosen automatically when `ui.language` is `pt-BR` (or "Portuguese (Brazil)")
under `Setup › Appearance`. Engine errors keep their run-time values and a decimal comma in
`pt-BR`. The remaining localization work is a native-speaker (human) review of wording plus CJK /
Devanagari / Arabic font fallbacks and RTL layout — not new UI translation. The status, the stage
and our effort estimates are in [`ROADMAP.md`](ROADMAP.md); the full assessment is in
are the alpha checklist. Translations are missing too. The status, the stage and our effort
estimates are in [`ROADMAP.md`](ROADMAP.md); the full assessment is in
[`docs/target-app-parity.md`](docs/target-app-parity.md), the ranked list of what's missing in
[`docs/gaps.md`](docs/gaps.md), and the menu-by-menu comparison in
[`docs/parity-checklist.md`](docs/parity-checklist.md). Bug reports and wish lists are
+4 -11
View File
@@ -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-10-24 · **Last updated:** 2026-10-27 · **Change:** trivial (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-10-24 · **Last updated:** 2026-10-25 · **Change:** trivial (Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, 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
@@ -50,7 +50,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 | ~12 % (1 of Pro Tools' 8 languages) | 70–110 | [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) |
@@ -89,14 +89,14 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
| Hindi | hi | none | 0 % |
| Arabic | ar | none | 0 % |
| French | fr | none (PR #143 open) | 0 % |
| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
| Portuguese | pt | none | 0 % |
| Indonesian | id | none | 0 % |
| Japanese | ja | none | 0 % |
| German | de | none | 0 % |
| 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: 0. Detail: [localization-parity.md](docs/localization-parity.md).
## Upcoming
@@ -125,9 +125,6 @@ mutated and truncated movies. Field reports from the first public week are track
- **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:** 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 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.
@@ -180,13 +177,9 @@ mutated and truncated movies. Field reports from the first public week are track
| Date | Change | Summary |
|---|---|---|
| 2026-11-05 | trivial | Languages table: Brazilian Portuguese (pt-BR) near complete for fixed UI strings via PR #1346; needs native review. Estimates unchanged |
| 2026-10-25 | trivial | Progress log: Cancel Zoom Toggle; readiness estimates unchanged |
| 2026-10-25 | trivial | Progress log: side panels in dock columns; readiness estimates unchanged |
| 2026-10-25 | trivial | Progress log: Auto Pan stereo balance; readiness estimates unchanged |
| 2026-10-24 | trivial | Progress log: Alt-click returns a plugin parameter to its default; readiness estimates unchanged |
| 2026-10-24 | trivial | Progress log: fine adjustment on plugin parameter sliders; readiness estimates unchanged |
| 2026-10-24 | trivial | Progress log: Strip Silence fine adjustment; readiness estimates unchanged |
| 2026-10-24 | trivial | Progress log: Clip List Auto Rename; readiness estimates unchanged |
| 2026-10-24 | trivial | Progress log: Strip Silence rectangles; readiness estimates unchanged |
| 2026-10-24 | trivial | Progress log: Strip Silence Rename; readiness estimates unchanged |
-10
View File
@@ -1,10 +0,0 @@
//! Test helpers shared by the `soundcraft-cli` integration test binaries.
use std::ffi::OsString;
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
pub fn soundcraft_cli_binary() -> OsString {
std::env::var_os("NEXTEST_BIN_EXE_soundcraft_cli")
.or_else(|| std::env::var_os("NEXTEST_BIN_EXE_soundcraft-cli"))
.unwrap_or_else(|| env!("CARGO_BIN_EXE_soundcraft-cli").into())
}
+2 -4
View File
@@ -7,8 +7,6 @@ use std::process::Command;
use craft_audio::{AudioBuffer, BitDepth, BwfInfo, EncodeOptions};
mod common;
fn tmpdir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("sc-cli-convert-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -27,7 +25,7 @@ fn write_wav16(path: &Path, samples: &[i16]) {
}
fn convert(input: &Path, output: &Path, extra: &[&str]) {
let o = Command::new(common::soundcraft_cli_binary())
let o = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli"))
.env("SOUNDCRAFT_NO_PREFS", "1")
.arg("convert")
.arg(input)
@@ -137,7 +135,7 @@ fn convert_warns_about_damaged_packets_and_never_replaces_the_source_with_them()
let bytes = mp1_with_a_damaged_frame();
std::fs::write(&src, &bytes).unwrap();
let run = |args: &[&std::ffi::OsStr]| {
Command::new(common::soundcraft_cli_binary()).env("SOUNDCRAFT_NO_PREFS", "1").arg("convert").args(args).output().unwrap()
Command::new(env!("CARGO_BIN_EXE_soundcraft-cli")).env("SOUNDCRAFT_NO_PREFS", "1").arg("convert").args(args).output().unwrap()
};
// To another file: written, with a warning that says how much was lost.
let out = dir.join("take.wav");
+3 -7
View File
@@ -19,7 +19,7 @@ fn invoke(dir: &Path, args: &[&str]) -> Invoke {
}
fn invoke_env(dir: &Path, args: &[&str], control_port: Option<&str>) -> Invoke {
let mut cmd = Command::new(crate::common::soundcraft_cli_binary());
let mut cmd = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli"));
cmd.env("SOUNDCRAFT_NO_PREFS", "1").env_remove("SOUNDCRAFT_CONTROL_PORT");
if let Some(port) = control_port {
cmd.env("SOUNDCRAFT_CONTROL_PORT", port);
@@ -80,16 +80,12 @@ fn not_found() -> std::io::Error {
std::io::Error::from_raw_os_error(2)
}
/// Exit 1 with the unreachable message for `port`. The reason is either the OS's refusal, whose text
/// differs by platform, or the client's connect timeout, which on Windows can expire before a
/// closed loopback port is refused.
/// Exit 1 with the refused-connection message for `port`; the OS's text for the refusal differs by platform.
#[track_caller]
fn assert_refused(got: &Invoke, port: u16) {
assert_eq!((got.code, got.stdout.as_str()), (1, ""));
let prefix = format!("error: cannot reach SoundCraft at 127.0.0.1:{port}: ");
let reason = got.stderr.strip_prefix(&prefix).unwrap_or_else(|| panic!("{}", got.stderr));
let refused = reason.contains(" (os error ") && reason.ends_with(")\n");
assert!(refused || reason == "connection timed out\n", "{}", got.stderr);
assert!(got.stderr.starts_with(&prefix) && got.stderr.contains(" (os error ") && got.stderr.ends_with(")\n"), "{}", got.stderr);
}
// ---- logging ----
+1 -1
View File
@@ -8,7 +8,7 @@ use std::process::{Command, Output, Stdio};
use serde_json::Value;
fn bin() -> Command {
let mut cmd = Command::new(crate::common::soundcraft_cli_binary());
let mut cmd = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli"));
cmd.env("SOUNDCRAFT_NO_PREFS", "1");
cmd
}
@@ -3,7 +3,7 @@
use std::process::{Command, Stdio};
fn bin() -> Command {
let mut cmd = Command::new(crate::common::soundcraft_cli_binary());
let mut cmd = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli"));
cmd.env("SOUNDCRAFT_NO_PREFS", "1");
cmd
}
-3
View File
@@ -1,8 +1,5 @@
//! Integration tests, built as one test binary: each file is a module.
#[path = "../common.rs"]
mod common;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod behaviour;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+2 -6
View File
@@ -53,16 +53,12 @@ fn not_found() -> std::io::Error {
std::io::Error::from_raw_os_error(2)
}
/// Exit 1 with the unreachable message for `port`. The reason is either the OS's refusal, whose text
/// differs by platform, or the client's connect timeout, which on Windows can expire before a
/// closed loopback port is refused.
/// Exit 1 with the refused-connection message for `port`; the OS's text for the refusal differs by platform.
#[track_caller]
fn assert_refused(got: &Invoke, port: u16) {
assert_eq!((got.code, got.stdout.as_str()), (1, ""));
let prefix = format!("error: cannot reach SoundCraft at 127.0.0.1:{port}: ");
let reason = got.stderr.strip_prefix(&prefix).unwrap_or_else(|| panic!("{}", got.stderr));
let refused = reason.contains(" (os error ") && reason.ends_with(")\n");
assert!(refused || reason == "connection timed out\n", "{}", got.stderr);
assert!(got.stderr.starts_with(&prefix) && got.stderr.contains(" (os error ") && got.stderr.ends_with(")\n"), "{}", got.stderr);
}
#[test]
@@ -23,7 +23,7 @@ impl Drop for Scratch {
}
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()
Command::new(env!("CARGO_BIN_EXE_soundcraft-cli")).current_dir(dir).env("SOUNDCRAFT_NO_PREFS", "1").args(args).output().unwrap()
}
#[test]
+1 -3
View File
@@ -5,10 +5,8 @@
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
mod common;
fn bin() -> Command {
let mut cmd = Command::new(common::soundcraft_cli_binary());
let mut cmd = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli"));
cmd.env("SOUNDCRAFT_NO_PREFS", "1");
cmd
}
+12 -32
View File
@@ -2,8 +2,6 @@
use soundcraft_engine::{Engine, io};
use soundcraft_ui_egui::dialogs::Dialog;
use soundcraft_ui_egui::localization::{self, Language};
use soundcraft_ui_egui::localized_format;
use soundcraft_ui_egui::sampler_window::SampleRead;
use soundcraft_ui_egui::{Services, SoundApp};
use std::cell::RefCell;
@@ -14,19 +12,10 @@ use wasm_bindgen::JsCast as _;
const CANVAS_ID: &str = "soundcraft_canvas";
const LOADING_ID: &str = "soundcraft_loading";
/// The language the browser asks for, for text shown before or outside a running app.
fn browser_language() -> Language {
web_sys::window().and_then(|w| w.navigator().language()).and_then(|tag| Language::parse(&tag)).unwrap_or_default()
}
pub fn start() {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
io::set_deliver(download);
wasm_bindgen_futures::spawn_local(async {
let _language = localization::enter(browser_language());
if let Some(el) = web_sys::window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id(LOADING_ID)) {
el.set_text_content(Some(localization::text("Loading SoundCraft…")));
}
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
log::error!("no document");
return;
@@ -59,11 +48,7 @@ pub fn start() {
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
Err(e) => el.set_text_content(Some(&format!(
"{} {}",
localized_format!("SoundCraft failed to start: {}", format!("{e:?}")),
localization::text("A browser with WebGPU or WebGL2 is required.")
))),
Err(e) => el.set_inner_html(&format!("<p>SoundCraft failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>")),
}
}
});
@@ -107,11 +92,11 @@ impl Purpose {
}
}
fn filter(self) -> (String, Vec<&'static str>) {
fn filter(self) -> (&'static str, Vec<&'static str>) {
match self {
Self::Session => (localization::text("SoundCraft Session").to_owned(), SESSION_EXTS.to_vec()),
Self::Audio => (localization::text("Audio").to_owned(), craft_audio::DECODE_EXTENSIONS.to_vec()),
Self::Midi => (localization::text("MIDI").to_owned(), MIDI_EXTS.to_vec()),
Self::Session => ("SoundCraft Session", SESSION_EXTS.to_vec()),
Self::Audio => ("Audio", craft_audio::DECODE_EXTENSIONS.to_vec()),
Self::Midi => ("MIDI", MIDI_EXTS.to_vec()),
}
}
}
@@ -141,12 +126,9 @@ impl WebShell {
let Some(purpose) = purpose else { return };
self.app.dialogs.open = None;
let (inbox, ctx) = (self.inbox.clone(), ctx.clone());
let (label, exts) = {
let _language = localization::enter(self.app.ui.language);
purpose.filter()
};
wasm_bindgen_futures::spawn_local(async move {
let Some(file) = rfd::AsyncFileDialog::new().add_filter(&label, &exts).pick_file().await else { return };
let (label, exts) = purpose.filter();
let Some(file) = rfd::AsyncFileDialog::new().add_filter(label, &exts).pick_file().await else { return };
let bytes = file.read().await;
inbox.borrow_mut().push((purpose, file.file_name(), bytes));
ctx.request_repaint();
@@ -183,7 +165,6 @@ impl WebShell {
}
fn handle(&mut self, purpose: Purpose, name: String, bytes: Vec<u8>) {
let _language = localization::enter(self.app.ui.language);
let e = &mut self.app.engine;
let at = e.session().edit.selection.start.max(0);
let result = match purpose {
@@ -193,15 +174,15 @@ impl WebShell {
Purpose::Audio => {
let before = e.session_arc();
io::import_audio_bytes(e, &name, &bytes, None, None, at).map(|_| {
e.push_undo(localization::text("Import Audio"), before);
localized_format!("Imported {name}", name = name)
e.push_undo("Import Audio", before);
format!("Imported {name}")
})
}
Purpose::Midi => {
let before = e.session_arc();
io::import_midi_bytes(e, &bytes, at, true).map(|_| {
e.push_undo(localization::text("Import MIDI"), before);
localized_format!("Imported {name}", name = name)
e.push_undo("Import MIDI", before);
format!("Imported {name}")
})
}
};
@@ -240,8 +221,7 @@ impl eframe::App for WebShell {
/// Hand a saved or exported file to the person as a download named `name` (the engine's delivery
/// hook on the web).
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
let _language = localization::enter(browser_language());
let js = |e: wasm_bindgen::JsValue| localized_format!("Download failed: {}", format!("{e:?}"));
let js = |e: wasm_bindgen::JsValue| format!("download failed: {e:?}");
let window = web_sys::window().ok_or("no window")?;
let document = window.document().ok_or("no document")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
+7 -43
View File
@@ -1,7 +1,5 @@
//! Loopback JSON-lines control server: one request per line, one reply per line.
//! This is the transport the MCP server (`soundcraft-cli mcp --connect PORT`) wraps.
//! A line that is not a JSON object with a string `method` gets one error reply, and the
//! connection is closed.
//!
//! Lines are bounded ([`MAX_LINE`]): a longer one is refused and the connection closed, without
//! buffering the rest. So is the number of connections served at once ([`MAX_CONNECTIONS`]).
@@ -105,8 +103,7 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -
}
/// Answer newline-delimited JSON requests for one connection: bound each line, forward it to the UI thread with a 90
/// s reply deadline, and stop at EOF, invalid UTF-8, a closed request queue or a line that isn't a request (see
/// [`parse_request`]). That line gets one error reply first.
/// s reply deadline, and stop at EOF, invalid UTF-8 or a closed request queue. Bad JSON still gets an error reply.
fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
@@ -126,8 +123,11 @@ fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context)
if line.trim().is_empty() {
continue;
}
let reply = match parse_request(line) {
Ok((id, method, params)) => {
let reply = match serde_json::from_str::<Value>(line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let (req, rrx) = ControlRequest::new(method, params);
match tx.try_send(req) {
Ok(()) => {
@@ -143,12 +143,7 @@ fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context)
Err(TrySendError::Disconnected(_)) => break,
}
}
// Control clients send one request object per line. A peer that sends anything else isn't
// one: answer once and close, so nothing it sends after that line runs.
Err(e) => {
let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("{e}; closing the connection")}));
break;
}
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
};
if writeln!(out, "{reply}").is_err() {
break;
@@ -156,15 +151,6 @@ fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context)
}
}
/// A request line's `(id, method, params)`. The line must be a JSON object with a string `method`;
/// otherwise the error says what it is instead.
fn parse_request(line: &str) -> Result<(Value, String, Value), String> {
let msg = serde_json::from_str::<Value>(line).map_err(|e| format!("bad JSON: {e}"))?;
let Some(msg) = msg.as_object() else { return Err("not a request: expected a JSON object".into()) };
let Some(method) = msg.get("method").and_then(Value::as_str) else { return Err("not a request: no string `method`".into()) };
Ok((msg.get("id").cloned().unwrap_or(Value::Null), method.to_string(), msg.get("params").cloned().unwrap_or(json!({}))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -240,26 +226,4 @@ mod tests {
assert!(line.contains("too many control connections"), "{line}");
drop(held);
}
#[test]
fn a_line_that_is_not_a_request_ends_the_connection() {
let addr = serve_echo();
for junk in ["not json", "[1, 2]", "\"ping\"", r#"{"id": 5}"#, r#"{"id": 5, "method": 7}"#] {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
// One write, so both lines arrive together and the request after the junk is waiting.
c.write_all(format!("{junk}\n{{\"id\":6,\"method\":\"ping\"}}\n").as_bytes()).unwrap();
let mut r = BufReader::new(c);
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"].as_bool(), Some(false), "{junk}: {line}");
line.clear();
let closed = match r.read_line(&mut line) {
Ok(n) => n == 0,
Err(e) => e.kind() == std::io::ErrorKind::ConnectionReset,
};
assert!(closed, "{junk}: the connection stays open and the next request is answered: {line}");
}
}
}
-3
View File
@@ -156,9 +156,6 @@ fn services() -> Services {
};
d.pick_file()
})),
pick_open_many: Some(Box::new(|_purpose: &str| {
rfd::FileDialog::new().add_filter("Audio", craft_audio::DECODE_EXTENSIONS).pick_files().unwrap_or_default()
})),
pick_save: Some(Box::new(|purpose: &str, path: &std::path::Path| {
let mut d = match purpose {
"file.bounce_mix" => rfd::FileDialog::new().add_filter("Audio", craft_audio::ENCODE_EXTENSIONS),
+1 -6
View File
@@ -2,13 +2,8 @@
use std::process::{Command, Output};
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
fn soundcraft_binary() -> std::ffi::OsString {
std::env::var_os("NEXTEST_BIN_EXE_soundcraft").unwrap_or_else(|| env!("CARGO_BIN_EXE_soundcraft").into())
}
fn soundcraft(args: &[&str], control_port: &str) -> Output {
Command::new(soundcraft_binary())
Command::new(env!("CARGO_BIN_EXE_soundcraft"))
.args(args)
.env("SOUNDCRAFT_NO_PREFS", "1")
.env("SOUNDCRAFT_CONTROL_PORT", control_port)
+1 -3
View File
@@ -8,10 +8,8 @@ rust-version.workspace = true
repository.workspace = true
[dependencies]
craft-xml.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
craft-scraft-format.workspace = true
soundcraft-midi.workspace = true
soundcraft-dsp.workspace = true
soundcraft-clap-host.workspace = true
@@ -24,6 +22,7 @@ serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
log.workspace = true
zip.workspace = true
craft-docpath.workspace = true
[target.'cfg(windows)'.dependencies]
@@ -31,7 +30,6 @@ winsafe = { version = "0.0.29", features = ["kernel"] }
[dev-dependencies]
proptest.workspace = true
zip.workspace = true
[lints]
workspace = true
-7
View File
@@ -240,7 +240,6 @@ fn grid_ticks(p: &Value) -> i64 {
"1/1" | "1" | "bar" => TICKS_PER_QUARTER * 4,
"1/2" => TICKS_PER_QUARTER * 2,
"1/4" => TICKS_PER_QUARTER,
"1/4t" => TICKS_PER_QUARTER * 2 / 3,
"1/8" => TICKS_PER_QUARTER / 2,
"1/8t" => TICKS_PER_QUARTER / 3,
"1/16t" => TICKS_PER_QUARTER / 6,
@@ -433,12 +432,6 @@ mod tests {
use crate::demo::demo_engine;
use serde_json::json;
#[test]
fn grid_ticks_accepts_the_quarter_triplet() {
use super::{TICKS_PER_QUARTER, grid_ticks};
assert_eq!(grid_ticks(&json!({"grid": "1/4t"})), TICKS_PER_QUARTER * 2 / 3);
}
#[test]
fn tempo_constant_with_an_empty_range_sets_the_tempo_at_its_start() {
use soundcraft_time::Range;
+4 -16
View File
@@ -114,7 +114,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Assign Send",
[],
None,
"{track?, slot?: 0..9|a..j, bus: name, level_db?: -144..12, default -144 (silent; kept when re-targeting), pre_fader?: false}",
"{track?, slot?: 0..9|a..j, bus: name, level_db?: 0 (kept when re-targeting), pre_fader?: false}",
has_selection,
send
),
@@ -244,15 +244,6 @@ fn volume(e: &mut Engine, p: &Value) -> Result<Value> {
return Err(bad("mix.volume", "`db` or `delta_db` required"));
}
let s = e.session_mut();
// The fader stops at -144 and +12 dB. The reply says when a value was held there: +15 dB used
// to play at +12 with nothing to show it.
let clamped = std::cell::Cell::new(false);
let fader = |db: f32| {
if !(-144.0..=12.0).contains(&db) {
clamped.set(true);
}
db.clamp(-144.0, 12.0)
};
// Tracks already moved as a group sibling of an earlier target must not move again.
let mut done: Vec<TrackId> = Vec::new();
for t in &tracks {
@@ -266,14 +257,11 @@ fn volume(e: &mut Engine, p: &Value) -> Result<Value> {
(None, Some(d)) => cur + d as f32,
_ => cur,
};
let new = if new.is_finite() { fader(new) } else { cur };
let new = if new.is_finite() { new.clamp(-144.0, 12.0) } else { cur };
let d = new - cur;
set_grouped(s, *t, "volume", |tr| tr.mixer.volume_db = if tr.id == *t { new } else { fader(tr.mixer.volume_db + d) });
set_grouped(s, *t, "volume", |tr| tr.mixer.volume_db = if tr.id == *t { new } else { (tr.mixer.volume_db + d).clamp(-144.0, 12.0) });
}
// Every requested track at its final volume, also one that moved as a group sibling of an
// earlier target and was skipped above.
let volumes: Vec<Value> = tracks.iter().filter_map(|t| s.track(*t)).map(|tr| json!({"track": tr.id.0, "db": tr.mixer.volume_db})).collect();
Ok(json!({"tracks": tracks.len(), "volumes": volumes, "clamped": clamped.get()}))
Ok(json!({"tracks": tracks.len()}))
}
fn pan(e: &mut Engine, p: &Value) -> Result<Value> {
-34
View File
@@ -263,18 +263,6 @@ fn retargeting_a_send_keeps_its_settings() {
assert_eq!((sl.level_db, sl.pan, sl.mute, sl.pre_fader), (-9.0, 0.5, true, true));
}
#[test]
fn a_new_send_starts_at_the_documented_level() {
let mut e = Engine::default();
e.execute("track.new", &json!({"count": 1, "name": "Vox", "format": "mono"})).unwrap();
e.execute("mix.new_bus", &json!({"name": "Rev"})).unwrap();
e.execute("mix.send", &json!({"track": "Vox", "bus": "Rev"})).unwrap();
let level = e.session().tracks[0].mixer.sends[0].as_ref().unwrap().level_db;
assert_eq!(level, -144.0);
let doc = crate::cmd::command_specs().iter().find(|c| c.id == "mix.send").unwrap().params;
assert!(doc.contains("level_db?: -144..12, default -144 (silent;"), "{doc}");
}
fn grouped_demo() -> Engine {
let mut e = crate::demo::demo_engine();
e.execute("mix.volume", &json!({"tracks": [3], "db": 0.0})).unwrap();
@@ -306,28 +294,6 @@ fn volume_absolute_on_a_whole_group_keeps_offsets() {
assert_eq!(volumes(&e), [-10.0, -12.0]);
}
/// The fader stops at +12 dB; the reply says what each track got, and when a value was held at a stop.
#[test]
fn volume_held_at_the_fader_stop_is_reported() {
let mut e = grouped_demo();
let r = e.execute("mix.volume", &json!({"tracks": [3], "db": -6.0})).unwrap();
assert_eq!((r["volumes"].clone(), r["clamped"].clone()), (json!([{"track": 3, "db": -6.0}]), json!(false)));
let r = e.execute("mix.volume", &json!({"tracks": [3], "db": 15.0})).unwrap();
assert_eq!((r["volumes"].clone(), r["clamped"].clone()), (json!([{"track": 3, "db": 12.0}]), json!(true)));
assert_eq!(volumes(&e), [12.0, 12.0]);
// A group member held at the stop counts too.
let mut e = grouped_demo();
e.session_mut().track_mut(TrackId(6)).unwrap().mixer.volume_db = 6.0;
let r = e.execute("mix.volume", &json!({"tracks": [3], "db": 10.0})).unwrap();
assert_eq!(r["clamped"], json!(true));
assert_eq!(volumes(&e), [10.0, 12.0]);
// Both grouped targets are listed, each at the value it ended with.
let mut e = grouped_demo();
e.session_mut().track_mut(TrackId(6)).unwrap().mixer.volume_db = -2.0;
let r = e.execute("mix.volume", &json!({"tracks": [3, 6], "db": -10.0})).unwrap();
assert_eq!(r["volumes"], json!([{"track": 3, "db": -10.0}, {"track": 6, "db": -12.0}]));
}
#[test]
fn clear_with_unknown_param_keeps_lanes() {
let (mut e, t) = tone_session(&[(0, -6.0), (100, -3.0)]);
+73 -17
View File
@@ -182,20 +182,46 @@ impl Drop for SessionLimit {
/// Refuses the session `name` of `len` bytes when it is larger than [`session_limit`]: too large
/// to open, or, when `saving`, to save.
pub(crate) fn session_size(name: impl std::fmt::Display, len: u64, saving: bool) -> Result<()> {
craft_scraft_format::check_session_size(&name.to_string(), len, session_limit(), saving).map_err(|error| EngineError::Io(error.to_string()))
let limit = session_limit();
if len <= limit {
return Ok(());
}
let most = if limit >= 1 << 20 { format!("{} MiB", limit >> 20) } else { format!("{limit} bytes") };
Err(EngineError::Io(if saving {
format!("{name} is too large to save: over {most}, more than SoundCraft opens")
} else {
format!("{name} is too large to open (over {most})")
}))
}
/// [`read_text`] for a session file: refused, unread, past [`session_limit`].
pub(crate) fn read_session_text(path: impl AsRef<Path>) -> Result<String> {
let path = path.as_ref();
craft_scraft_format::read_session_data(&path.display().to_string(), read_file_within(path, true)?, session_limit())
.map_err(|error| EngineError::Io(error.to_string()))
utf8(path, read_file_within(path, true)?)
}
/// A bare `.scraft` handed over as bytes (the browser) as text: refused, uncopied, past
/// [`session_limit`].
pub(crate) fn session_bytes_text(name: &str, bytes: &[u8]) -> Result<String> {
craft_scraft_format::read_session_bytes(name, bytes, session_limit()).map_err(|error| EngineError::Io(error.to_string()))
session_size(name, bytes.len() as u64, false)?;
String::from_utf8(bytes.to_vec()).map_err(|_| EngineError::Io(format!("{name}: not a SoundCraft session")))
}
/// How many bytes [`Session::to_json`] makes of `s`, counted without keeping them.
fn json_len(s: &Session) -> u64 {
struct Count(u64);
impl std::io::Write for Count {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0 = self.0.saturating_add(buf.len() as u64);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut n = Count(0);
// A session that cannot be written counts as nothing here: `to_json` reports that error.
serde_json::to_writer_pretty(&mut n, s).map_or(0, |()| n.0)
}
/// Is there a file at `path` the automation read root lets us see? A path outside the root is
@@ -769,12 +795,11 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
// Before any audio is written: a session too large to open again is not saved (#892). With no
// audio to write, the text checked is the text saved.
let checked = if pending.is_empty() {
let label = p.display().to_string();
let text = craft_scraft_format::write_session_named(&s, &label, session_limit()).map_err(|error| EngineError::Io(error.to_string()))?;
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
session_size(p.display(), text.len() as u64, true)?;
Some(text)
} else {
let size = craft_scraft_format::session_json_len(&s).map_err(|error| EngineError::Io(error.to_string()))?;
session_size(p.display(), size, true)?;
session_size(p.display(), json_len(&s), true)?;
None
};
let mut written = 0;
@@ -795,10 +820,7 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
}
let text = match checked {
Some(text) => text,
None => {
let label = p.display().to_string();
craft_scraft_format::write_session_named(&s, &label, session_limit()).map_err(|error| EngineError::Io(error.to_string()))?
}
None => s.to_json().map_err(|err| EngineError::Io(err.to_string()))?,
};
make_dir(&dir)?;
// Atomic-ish write: temp file then rename.
@@ -1085,11 +1107,45 @@ fn write_export_checked(path: &Path, mut bytes: &[u8]) -> std::io::Result<()> {
/// Unpack a bundle: the one `.scraft` at its top level and the files beside it, by relative path.
fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::collections::HashMap<String, Vec<u8>>)> {
craft_scraft_format::read_bundle(
bytes,
craft_scraft_format::BundleLimits { entries: limits.entries, bytes: limits.bytes, session_bytes: session_limit() },
)
.map_err(|error| EngineError::Io(error.to_string()))
use std::io::Read as _;
let zerr = |err: zip::result::ZipError| EngineError::Io(format!("bundle: {err}"));
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(zerr)?;
if z.len() > limits.entries {
return Err(EngineError::Io("bundle: too many files".into()));
}
// Entries are stored, so the files we keep can only outgrow the bundle when several entries
// point at the same bytes: a small bundle naming one payload thousands of times would be
// copied out once per name.
if z.has_overlapping_files().map_err(zerr)? {
return Err(EngineError::Io("bundle: files share data".into()));
}
let (mut text, mut files, mut total) = (None, std::collections::HashMap::new(), 0u64);
for i in 0..z.len() {
let mut f = z.by_index(i).map_err(zerr)?;
if f.is_dir() {
continue;
}
let rel = f.name().map_err(zerr)?.to_string();
let size = f.size();
total = total.saturating_add(size);
if total > limits.bytes {
return Err(EngineError::Io("bundle: too large".into()));
}
let is_session = !rel.contains('/') && Path::new(&rel).extension().and_then(OsStr::to_str) == Some(soundcraft_model::SESSION_EXTENSION);
if is_session && text.is_none() {
session_size(format_args!("bundle: {rel}"), size, false)?;
}
let mut data = Vec::new();
// The declared size is hostile too: never read past it.
f.by_ref().take(size).read_to_end(&mut data).map_err(|err| EngineError::Io(format!("bundle: {rel}: {err}")))?;
if is_session && text.is_none() {
text = Some(String::from_utf8(data).map_err(|_| EngineError::Io(format!("bundle: {rel} is not text")))?);
} else {
files.insert(rel, data);
}
}
let text = text.ok_or_else(|| EngineError::Io("bundle: no .scraft session inside".into()))?;
Ok((text, files))
}
/// The record-enabled audio tracks, each with the input channels it records (those its input
+50 -46
View File
@@ -1,13 +1,13 @@
use super::render::sanitize_name;
use super::session::decode_source;
use super::{Arc, Engine, EngineError, OsStr, Path, Result, Session, SourceAudio, read_bundle, session_limit, write_file};
use super::{Arc, EncodeOptions, Engine, EngineError, FileFormat, OsStr, Path, Result, Session, SourceAudio, read_bundle, write_file};
// ─── Hosts without a filesystem (the browser) ─────────────────────────────────────────────────
/// Extension of a session bundle: one zip file holding the `.scraft` session and its
/// `Audio Files/`, the same layout as a saved session folder. The browser has no folders, so it
/// saves and opens sessions as bundles.
pub const BUNDLE_EXTENSION: &str = craft_scraft_format::BUNDLE_EXTENSION;
pub const BUNDLE_EXTENSION: &str = "scraftz";
/// Most entries and bytes a bundle may unpack to (bundles are hostile input). The writer keeps to
/// them too, so a bundle it saves always opens again (#433).
@@ -28,8 +28,54 @@ pub fn session_bundle(session: &Session) -> Result<(Vec<u8>, Session)> {
/// [`session_bundle`], refused when it would hold more than `limits` allows.
fn session_bundle_within(session: &Session, limits: BundleLimits) -> Result<(Vec<u8>, Session)> {
let shared = craft_scraft_format::BundleLimits { entries: limits.entries, bytes: limits.bytes, session_bytes: session_limit() };
craft_scraft_format::write_bundle(session, shared).map_err(|error| EngineError::Io(error.to_string()))
use std::io::Write as _;
let zerr = |err: zip::result::ZipError| EngineError::Io(format!("bundle: {err}"));
let ioerr = |err: std::io::Error| EngineError::Io(format!("bundle: {err}"));
let mut s = session.clone();
let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).large_file(true);
let mut taken = std::collections::HashSet::new();
let (mut entries, mut total) = (0usize, 0u64);
// Counted as the reader counts them: files, and the bytes they unpack to.
let mut fits = |len: usize| {
entries += 1;
total = total.saturating_add(len as u64);
if entries > limits.entries || total > limits.bytes {
return Err(EngineError::Io(format!(
"bundle: too large to save (a bundle holds at most {} files and {} MiB, or it can't be opened again)",
limits.entries,
limits.bytes >> 20
)));
}
Ok(())
};
for src in &mut s.sources {
let Some(audio) = s.pool.get(src.id) else { continue };
let base = sanitize_name(&src.name);
let mut target = format!("Audio Files/{base}.wav");
let mut k = 1;
while taken.contains(&target) && k <= 9_999 {
target = format!("Audio Files/{base}_{k:02}.wav");
k += 1;
}
let opts_wav = EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(craft_audio::BitDepth::Float32);
let bytes = craft_audio::encode(&audio.buffer, &opts_wav).map_err(|err| EngineError::Io(err.to_string()))?;
fits(bytes.len())?;
w.start_file(target.as_str(), opts).map_err(zerr)?;
w.write_all(&bytes).map_err(ioerr)?;
taken.insert(target.clone());
src.path = target;
src.unsaved = false;
src.format = FileFormat::Wav;
}
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
// Its session too: one the reader would refuse is not saved (#892).
super::session_size("the session", text.len() as u64, true)?;
fits(text.len())?;
w.start_file(format!("{}.{}", sanitize_name(&s.name), soundcraft_model::SESSION_EXTENSION), opts).map_err(zerr)?;
w.write_all(text.as_bytes()).map_err(ioerr)?;
let bytes = w.finish().map_err(zerr)?.into_inner();
Ok((bytes, s))
}
/// Save as a bundle named after `path`'s file name, delivered through the host ([`write_file`]).
@@ -154,48 +200,6 @@ mod bundle_tests {
assert_eq!(r.path.as_deref(), Some("Midnight Groove.scraftz"));
}
#[test]
fn legacy_zip64_bundle_opens_with_shared_reader() {
use craft_audio::{AudioBuffer, EncodeFormat, EncodeOptions, encode};
use soundcraft_model::{FileFormat, Source, SourceId};
use std::io::Write as _;
let id = SourceId(7);
let samples = [0.125, -0.75, 1.25, -1.5];
let mut audio = AudioBuffer::new(48_000, 1, samples.len());
audio.channels[0].copy_from_slice(&samples);
let mut session = Session::default();
session.sources.push(Source {
id,
name: "Legacy Lead".into(),
path: "Audio Files/Legacy Lead.wav".into(),
channels: 1,
frames: samples.len() as u64,
sample_rate: 48_000,
format: FileFormat::Wav,
time_reference: 0,
unsaved: false,
});
session.pool.insert(id, Arc::new(SourceAudio::new(audio)));
let wav =
encode(&session.pool.get(id).unwrap().buffer, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(craft_audio::BitDepth::Float32))
.unwrap();
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).large_file(true);
zip.start_file("Audio Files/Legacy Lead.wav", opts).unwrap();
zip.write_all(&wav).unwrap();
zip.start_file("Legacy.scraft", opts).unwrap();
zip.write_all(session.to_json().unwrap().as_bytes()).unwrap();
let legacy = zip.finish().unwrap().into_inner();
let mut opened = Engine::default();
let missing = open_session_bytes(&mut opened, "Legacy.scraftz", &legacy).unwrap();
assert!(missing.is_empty(), "{missing:?}");
assert_eq!(opened.session().pool.get(id).unwrap().buffer.channels[0], samples);
}
#[test]
fn sources_sharing_one_file_all_load_from_a_bundle() {
use std::io::Write as _;
+3 -9
View File
@@ -206,8 +206,8 @@ pub fn load_sampler_bytes(e: &mut Engine, track: TrackId, name: &str, bytes: &[u
/// Resolve each movie referenced by the session file `session` ([`stored_path`]): keep the
/// resolved path when its file exists, else look for a file of the same name next to the session
/// (moved projects) and relink. A movie whose stored path is refused, or resolves to a file that
/// is not there, and has no such copy is marked offline. Returns the movies still missing.
/// (moved projects) and relink. A movie whose stored path is refused and has no such copy is
/// marked offline. Returns the movies still missing.
pub fn relink_videos(s: &mut Session, session: &Path) -> Vec<String> {
let session_dir = session.parent().unwrap_or(Path::new(""));
let mut missing = Vec::new();
@@ -228,13 +228,7 @@ pub fn relink_videos(s: &mut Session, session: &Path) -> Vec<String> {
.find(|c| !name.as_os_str().is_empty() && file_found(c));
match (near, p) {
(Some(c), _) => v.path = c.to_string_lossy().into_owned(),
// The movie is gone: mark it offline, so the Video track never opens the stored
// string (which the working directory would resolve). The string itself is kept as
// stored, so saving does not swap a path relative to the session for this folder's.
(None, Ok(p)) => {
missing.push(format!("{} (video)", p.display()));
v.offline = Some("file not found".into());
}
(None, Ok(p)) => missing.push(format!("{} (video)", p.display())),
(None, Err(why)) => {
missing.push(format!("{} (video): {why}", v.path));
v.offline = Some(why);
+14 -57
View File
@@ -8,39 +8,8 @@ pub(super) const MAX_MIDI_TEMPOS: usize = 10_000;
pub(super) const MAX_MIDI_TRACKS: usize = 512;
/// Import a Standard MIDI File as MIDI tracks (one per SMF track).
///
/// The file is checked in full before the session changes, so a refused file (too many tempo or
/// meter changes or tracks, a track longer than a day) leaves the session as it was: callers that
/// keep their own undo step, like the web shell, never see a half-applied import.
///
/// A sound file is read strictly. A damaged one is read leniently, as other MIDI readers do: with
/// stray bytes after the last track (#1528), a track length its End of Track contradicts or a
/// track cut short, what can be read is imported and what could not is logged. A file past the
/// reader's event or track limit is still refused, also when other damage comes first: read
/// leniently it would lose the rest without saying so. Something that is not a Standard MIDI File
/// is refused.
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(_))) => {
return Err(EngineError::Io(err.to_string()));
}
Err(_) => {
let read = soundcraft_midi::read_smf_lenient(bytes).map_err(|err| EngineError::Io(err.to_string()))?;
// 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",
soundcraft_midi::MAX_EVENTS,
soundcraft_midi::MAX_TRACKS
)));
}
for warning in &read.warnings {
log::warn!("MIDI import: {warning}");
}
read.smf
}
};
let smf = soundcraft_midi::read_smf(bytes).map_err(|err| EngineError::Io(err.to_string()))?;
if tempo_map {
// Each meter is placed by walking the ones before it.
if smf.meters.len() > MAX_MIDI_METERS {
@@ -54,43 +23,24 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
if tracks_to_import > MAX_MIDI_TRACKS {
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TRACKS} tracks")));
}
// Phase 1, read only: the tempo map the clips will be placed with, built apart from the
// session. `session_mut` would already count as an edit (revision, unsaved mark).
let s = e.session();
let mut tempo = s.tempo.clone();
let s = e.session_mut();
if tempo_map {
for (tick, bpm) in &smf.tempos {
if tempo.tempo_at_tick(*tick) == *bpm {
if s.tempo.tempo_at_tick(*tick) == *bpm {
continue;
}
let _ = tempo.set_tempo(*tick, *bpm);
let _ = s.tempo.set_tempo(*tick, *bpm);
}
for (tick, n, d) in &smf.meters {
let _ = tempo.set_meter(*tick, u32::from(*n), u32::from(*d));
let _ = s.tempo.set_meter(*tick, u32::from(*n), u32::from(*d));
}
}
let base_tick = tempo.samples_to_ticks(at, s.sample_rate);
let mut clips = Vec::new();
let base_tick = s.tempo.samples_to_ticks(at, s.sample_rate);
let mut out = Vec::new();
for (i, tr) in smf.tracks.iter().enumerate() {
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.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 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)));
}
clips.push((i, tr, len));
}
// Phase 2: nothing can fail from here on.
let s = e.session_mut();
if tempo_map {
s.tempo = tempo;
}
let mut out = Vec::new();
for (i, tr, len) in clips {
let mut name = if tr.name.trim().is_empty() { format!("MIDI {}", i + 1) } else { tr.name.clone() };
soundcraft_model::truncate_chars(&mut name, soundcraft_model::MAX_NAME_CHARS);
let id = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some(&name));
@@ -98,6 +48,13 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
if let Some(t) = s.track_mut(id) {
t.instrument = Some(soundcraft_model::Insert::new(if drums { "drum_synth" } else { "subtractive_synth" }));
}
// 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 len = s.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)));
}
let cid = s.new_clip_id();
crate::edit::place_clip(s, id, Clip::midi(cid, name, at, len.max(1), tr.sequence.clone()));
out.push(id);
-92
View File
@@ -177,71 +177,6 @@ mod name_tests {
}
}
#[test]
fn a_midi_file_with_stray_bytes_after_its_last_track_is_imported() {
// #1528: a complete format-0 file followed by two line feeds, too short to be a chunk.
let note = soundcraft_midi::Note { pitch: 60, velocity: 100, release_velocity: 64, channel: 0, start: 0, length: 960 };
let sequence = soundcraft_midi::Sequence { notes: vec![note], ..Default::default() };
let smf = soundcraft_midi::Smf { format: 0, tracks: vec![soundcraft_midi::SmfTrack { name: String::new(), sequence }], ..Default::default() };
let mut bytes = soundcraft_midi::write_smf(&smf).unwrap();
bytes.extend_from_slice(b"\n\n");
let mut e = Engine::default();
let ids = import_midi_bytes(&mut e, &bytes, 0, true).unwrap();
assert_eq!(ids.len(), 1);
match &e.session().track(ids[0]).unwrap().clips()[0].content {
ClipContent::Midi { sequence } => assert_eq!(sequence.notes, vec![note]),
_ => panic!("expected a MIDI clip"),
}
// Something that is no MIDI file is still refused, and leaves the session as it was.
let mut e = Engine::default();
assert!(import_midi_bytes(&mut e, b"RIFF\0\0\0\0WAVE", 0, true).is_err());
assert!(e.session().tracks.is_empty());
}
#[test]
fn a_midi_file_past_the_track_limit_is_refused_even_with_stray_bytes() {
// Read leniently, the tracks past the limit would be left out without a word: the note in
// the last one would be lost. The file stays refused, and the session as it was.
let tracks = soundcraft_midi::MAX_TRACKS + 1;
let mut bytes = b"MThd\0\0\0\x06\0\x01".to_vec();
bytes.extend_from_slice(&u16::try_from(tracks).unwrap().to_be_bytes());
bytes.extend_from_slice(&960u16.to_be_bytes());
for _ in 1..tracks {
bytes.extend_from_slice(b"MTrk\0\0\0\x04\0\xFF\x2F\0");
}
// A note on, a quarter note later its note off, then End of Track.
bytes.extend_from_slice(b"MTrk\0\0\0\x0D\0\x90\x3C\x64\x87\x40\x80\x3C\x40\0\xFF\x2F\0");
bytes.extend_from_slice(b"\n\n");
let mut e = Engine::default();
let err = import_midi_bytes(&mut e, &bytes, 0, true).unwrap_err();
assert!(err.to_string().contains("too many tracks"), "{err}");
assert!(e.session().tracks.is_empty());
}
#[test]
fn a_midi_file_past_the_event_limit_is_refused_after_a_damaged_track() {
// The strict reader stops at track 1's damage, before track 2 reaches the event limit; read
// leniently, track 2's note after the limit (pitch 72) would be lost without a word.
let mut damaged = b"\0\x3C\x40".to_vec(); // a data byte with no status before it
damaged.extend_from_slice(b"\0\xFF\x2F\0");
let mut long = b"\0\x90\x3C\x64".to_vec();
for _ in 0..soundcraft_midi::MAX_EVENTS {
long.extend_from_slice(b"\0\x3C\0"); // running status: note off
}
long.extend_from_slice(b"\0\x90\x48\x64\x87\x40\x80\x48\x40\0\xFF\x2F\0");
let mut bytes = b"MThd\0\0\0\x06\0\x01\0\x02\x03\xC0".to_vec();
for body in [&damaged, &long] {
bytes.extend_from_slice(b"MTrk");
bytes.extend_from_slice(&u32::try_from(body.len()).unwrap().to_be_bytes());
bytes.extend_from_slice(body);
}
assert!(!matches!(soundcraft_midi::read_smf(&bytes), Err(soundcraft_midi::MidiError::TooManyEvents(_)) | Ok(_)));
let mut e = Engine::default();
let err = import_midi_bytes(&mut e, &bytes, 0, true).unwrap_err();
assert!(err.to_string().contains("events"), "{err}");
assert!(e.session().tracks.is_empty());
}
#[test]
fn midi_longer_than_a_day_is_refused() {
let held = soundcraft_midi::Note { pitch: 60, velocity: 100, release_velocity: 64, channel: 0, start: 0, length: (1 << 28) - 1 };
@@ -251,33 +186,6 @@ mod name_tests {
assert!(err.to_string().contains("longer than 24 hours"), "{err}");
}
#[test]
fn a_refused_midi_file_leaves_the_session_untouched() {
// Track 1 fits; track 2 is longer than a day. Before the import is refused, nothing of
// track 1, nor the file's tempo and meter changes, may have reached the session.
let note = |length| soundcraft_midi::Note { pitch: 60, velocity: 100, release_velocity: 64, channel: 0, start: 0, length };
let short = soundcraft_midi::Sequence { notes: vec![note(960)], ..Default::default() };
let held = soundcraft_midi::Sequence { notes: vec![note((1 << 28) - 1)], ..Default::default() };
let smf = soundcraft_midi::Smf {
tracks: vec![
soundcraft_midi::SmfTrack { name: "fits".into(), sequence: short },
soundcraft_midi::SmfTrack { name: "too long".into(), sequence: held },
],
tempos: vec![(0, 91.0)],
meters: vec![(0, 7, 8)],
..Default::default()
};
let mut e = Engine::default();
let before = e.session().clone();
let (revision, dirty) = (e.revision, e.is_dirty());
let err = import_midi_bytes(&mut e, &soundcraft_midi::write_smf(&smf).unwrap(), 0, true).unwrap_err();
assert!(err.to_string().contains("MIDI track 2: longer than 24 hours"), "{err}");
assert_eq!(e.session().tracks.len(), before.tracks.len());
assert_eq!(e.session().tempo, before.tempo);
assert_eq!(*e.session(), before);
assert_eq!((e.revision, e.is_dirty()), (revision, dirty), "a refused file is not an edit");
}
#[test]
fn midi_with_more_meter_changes_than_scores_have_is_refused() {
let note = soundcraft_midi::Note { pitch: 60, velocity: 100, release_velocity: 64, channel: 0, start: 0, length: 960 };
-93
View File
@@ -520,99 +520,6 @@ mod open_tests {
assert!(r.session().pool.get(r.session().sources[0].id).is_some());
let _ = std::fs::remove_dir_all(&dir);
}
/// Every outcome of [`relink_videos`] for a movie: its file is there; it is gone but a file of
/// the same name is next to the session or in its `Video Files` (relinked); it is gone with
/// no copy (offline, path kept); its stored path is refused, with or without such a copy.
#[test]
fn each_movie_is_kept_relinked_or_offline() {
let dir = std::env::temp_dir().join(format!("soundcraft-relink-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("Movies")).unwrap();
std::fs::create_dir_all(dir.join("Video Files")).unwrap();
for f in ["Movies/here.mov", "near.mov", "Video Files/filed.mov", "remote_copy.mov"] {
std::fs::write(dir.join(f), b"movie").unwrap();
}
let session = dir.join("Song.scraft");
let mut s = Session::default();
let stored = [
"Movies/here.mov",
"Old/near.mov",
"Old/filed.mov",
"Old/gone.mov",
"file://192.0.2.1/s/remote.mov",
"file://192.0.2.1/s/remote_copy.mov",
];
for path in stored {
let id = SourceId(s.alloc());
s.videos.push(soundcraft_model::VideoSource {
id,
name: path.into(),
path: path.into(),
width: 0,
height: 0,
frame_rate: 0.0,
duration: 0.0,
codec: String::new(),
offline: None,
});
}
let missing = relink_videos(&mut s, &session);
let got: Vec<(String, Option<String>)> = s.videos.iter().map(|v| (v.path.clone(), v.offline.clone())).collect();
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));
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]);
assert_eq!(got[5], (at("remote_copy.mov"), None));
assert_eq!(missing.len(), 2, "{missing:?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_missing_movie_is_offline_and_keeps_its_stored_path() {
// The stored path is relative to the session and names no file. The movie is offline, so
// the Video track never opens the stored string (the working directory would resolve
// it), and the string is kept: saved into another folder, the session finds the movie
// once it is back there under the same relative path.
let dir = std::env::temp_dir().join(format!("soundcraft-missing-movie-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (first, moved) = (dir.join("a"), dir.join("b"));
std::fs::create_dir_all(&first).unwrap();
std::fs::create_dir_all(moved.join("Movies")).unwrap();
let mut s = Session::default();
let id = SourceId(s.alloc());
s.videos.push(soundcraft_model::VideoSource {
id,
name: "gone".into(),
path: "Movies/gone.mov".into(),
width: 0,
height: 0,
frame_rate: 0.0,
duration: 0.0,
codec: String::new(),
offline: None,
});
let session = first.join("Song.scraft");
std::fs::write(&session, s.to_json().unwrap()).unwrap();
let mut e = Engine::default();
let missing = open_session(&mut e, &session).unwrap();
assert_eq!(missing, vec![format!("{} (video)", stored_path("Movies/gone.mov", &session).unwrap().display())]);
let v = &e.session().videos[0];
assert_eq!((v.path.as_str(), v.offline.as_deref()), ("Movies/gone.mov", Some("file not found")));
// Saved next to the movie's new home, the session opens it.
let session = moved.join("Song.scraft");
save_session(&mut e, session.to_str().unwrap()).unwrap();
std::fs::write(moved.join("Movies").join("gone.mov"), b"movie").unwrap();
let mut r = Engine::default();
assert!(open_session(&mut r, &session).unwrap().is_empty());
let v = &r.session().videos[0];
assert_eq!(v.path, stored_path("Movies/gone.mov", &session).unwrap().to_string_lossy());
assert!(v.offline.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(all(test, unix))]
+7 -12
View File
@@ -273,10 +273,13 @@ fn spell(pitch: u8) -> (char, i32, i32) {
}
fn xml_escape(s: &str) -> String {
// Keep the score export's existing literal whitespace and quote spelling. The
// shared attribute writer owns XML legality/escaping; only its generated
// whitespace references are restored (input ampersands were escaped first).
craft_xml::esc_attr(s).replace("&#9;", "\t").replace("&#10;", "\n").replace("&#13;", "\r")
s.chars()
.filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}'))
.collect::<String>()
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}
fn note_type(units: u32) -> (&'static str, bool) {
@@ -607,14 +610,6 @@ fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) {
mod tests {
use super::*;
#[test]
fn shared_xml_escaping_preserves_score_bytes() {
let input = "<&>\"'\t\n\r\0\u{1f}\u{fffe}\u{ffff}é𝄞&#9;&#10;&#13;";
assert_eq!(xml_escape(input), "&lt;&amp;&gt;&quot;'\t\n\ré𝄞&amp;#9;&amp;#10;&amp;#13;");
assert_eq!(xml_escape(""), "");
assert_eq!(xml_escape("Already &amp; escaped"), "Already &amp;amp; escaped");
}
#[test]
fn split_units_uses_representable_values() {
assert_eq!(split_units(16), vec![16]);
+3 -6
View File
@@ -2,9 +2,8 @@
//!
//! - [`Note`], [`CtrlEvent`] and [`Sequence`]: the MIDI content of a region / track, in ticks at
//! [`PPQ`] (960) ticks per quarter note; [`read_smf`] / [`write_smf`]: Standard MIDI File import
//! and export, and [`read_smf_lenient`] for files that are slightly damaged. These come from
//! `craft-midi` in craft-libs, shared with the other Craft apps, and are re-exported so the rest
//! of SoundCraft names them from here.
//! and export. These come from `craft-midi` in craft-libs, shared with the other Craft apps, and
//! are re-exported so the rest of SoundCraft names them from here.
//! - [`ops`]: MIDI editing operations (quantize, transpose, velocity, duration, split).
//! - [`note_name`], [`gm_drum_name`], [`gm_program_name`]: display names.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -13,8 +12,6 @@ mod names;
pub mod ops;
mod rng;
pub use craft_midi::{
CtrlEvent, CtrlKind, LenientRead, MAX_EVENTS, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, read_smf, read_smf_lenient, write_smf,
};
pub use craft_midi::{CtrlEvent, CtrlKind, MAX_EVENTS, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, read_smf, write_smf};
pub use names::{gm_drum_name, gm_program_name, note_name};
pub use rng::XorShift;
+10 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "soundcraft-model"
description = "Compatibility facade for SoundCraft's shared native session format"
description = "SoundCraft session document: tracks, playlists, clips, mixer, routing, automation, markers"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,7 +8,15 @@ rust-version.workspace = true
repository.workspace = true
[dependencies]
craft-scraft-format.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
soundcraft-midi.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[dev-dependencies]
proptest.workspace = true
[lints]
workspace = true
+394
View File
@@ -0,0 +1,394 @@
//! Automation lanes and modes.
use soundcraft_time::Samples;
/// Automation modes (per track).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum AutomationMode {
Off,
#[default]
Read,
Touch,
Latch,
TouchLatch,
Write,
Trim,
}
impl AutomationMode {
pub const ALL: [AutomationMode; 7] = [
AutomationMode::Off,
AutomationMode::Read,
AutomationMode::Touch,
AutomationMode::Latch,
AutomationMode::TouchLatch,
AutomationMode::Write,
AutomationMode::Trim,
];
pub fn label(self) -> &'static str {
match self {
AutomationMode::Off => "off",
AutomationMode::Read => "read",
AutomationMode::Touch => "touch",
AutomationMode::Latch => "latch",
AutomationMode::TouchLatch => "touch/latch",
AutomationMode::Write => "write",
AutomationMode::Trim => "trim",
}
}
pub fn from_id(s: &str) -> Option<AutomationMode> {
let s = s.to_ascii_lowercase();
AutomationMode::ALL.into_iter().find(|m| m.label() == s || m.label().replace('/', "_") == s || format!("{m:?}").to_ascii_lowercase() == s)
}
pub fn reads(self) -> bool {
!matches!(self, AutomationMode::Off)
}
}
/// Which parameter an automation lane controls.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub enum AutoParam {
/// Fader level, dB.
Volume,
/// Pan, -1..1 (index = which panner of a stereo track: 0 left, 1 right).
Pan(u8),
/// Mute (0/1).
Mute,
/// Send level, dB.
SendLevel(u8),
SendPan(u8),
SendMute(u8),
/// Insert slot + parameter id.
Plugin {
slot: u8,
param: String,
},
}
impl AutoParam {
pub fn label(&self) -> String {
match self {
AutoParam::Volume => "volume".into(),
AutoParam::Pan(0) => "pan".into(),
AutoParam::Pan(i) => format!("pan {}", u16::from(*i) + 1),
AutoParam::Mute => "mute".into(),
AutoParam::SendLevel(i) => format!("send {} level", slot_letter(*i)),
AutoParam::SendPan(i) => format!("send {} pan", slot_letter(*i)),
AutoParam::SendMute(i) => format!("send {} mute", slot_letter(*i)),
AutoParam::Plugin { slot, param } => format!("insert {} {param}", slot_letter(*slot)),
}
}
/// Parse ids like `volume`, `pan`, `pan2`, `mute`, `send_a_level`, `plugin:a:threshold`.
pub fn parse(s: &str) -> Option<AutoParam> {
let orig = s.trim();
let s = orig.to_ascii_lowercase();
match s.as_str() {
"volume" | "vol" => return Some(AutoParam::Volume),
"pan" | "pan1" => return Some(AutoParam::Pan(0)),
"pan2" => return Some(AutoParam::Pan(1)),
"mute" => return Some(AutoParam::Mute),
_ => {}
}
if let Some(rest) = s.strip_prefix("send_") {
let mut it = rest.splitn(2, '_');
let slot = letter_slot(it.next()?)?;
return match it.next()? {
"level" => Some(AutoParam::SendLevel(slot)),
"pan" => Some(AutoParam::SendPan(slot)),
"mute" => Some(AutoParam::SendMute(slot)),
_ => None,
};
}
if let Some(rest) = s.strip_prefix("plugin:") {
let (slot, param) = rest.split_once(':')?;
// ASCII lowercasing keeps byte offsets, so take the param from the original.
let param = orig.get(orig.len() - param.len()..)?;
return Some(AutoParam::Plugin { slot: letter_slot(slot)?, param: param.to_string() });
}
None
}
/// Value range and default.
pub fn range(&self) -> (f32, f32, f32) {
match self {
AutoParam::Volume | AutoParam::SendLevel(_) => (-144.0, 12.0, 0.0),
AutoParam::Pan(_) | AutoParam::SendPan(_) => (-1.0, 1.0, 0.0),
AutoParam::Mute | AutoParam::SendMute(_) => (0.0, 1.0, 0.0),
AutoParam::Plugin { .. } => (f32::MIN, f32::MAX, 0.0),
}
}
}
pub fn slot_letter(i: u8) -> char {
char::from(b'A'.saturating_add(i.min(25)))
}
fn letter_slot(s: &str) -> Option<u8> {
let c = s.chars().next()?.to_ascii_uppercase();
if s.len() == 1 && c.is_ascii_uppercase() { Some(c as u8 - b'A') } else { s.parse().ok() }
}
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AutomationPoint {
pub at: Samples,
pub value: f32,
}
/// A breakpoint automation lane. Points are kept sorted by time.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AutomationLane {
pub param: AutoParam,
pub points: Vec<AutomationPoint>,
#[serde(default)]
pub enabled: bool,
}
impl AutomationLane {
pub fn new(param: AutoParam) -> Self {
AutomationLane { param, points: Vec::new(), enabled: true }
}
/// Value at `at` (linear interpolation; `default` when empty).
pub fn value_at(&self, at: Samples, default: f32) -> f32 {
let pts = &self.points;
let Some(first) = pts.first() else { return default };
if at <= first.at {
return first.value;
}
let idx = pts.partition_point(|p| p.at <= at);
match (pts.get(idx.wrapping_sub(1)), pts.get(idx)) {
(Some(a), Some(b)) if b.at > a.at => {
// Mute-like lanes step instead of ramping.
if matches!(self.param, AutoParam::Mute | AutoParam::SendMute(_)) {
return a.value;
}
// Widen so far-apart breakpoints cannot overflow i64.
let span = i128::from(b.at) - i128::from(a.at);
let off = i128::from(at) - i128::from(a.at);
// Interpolate in f64: the f32 difference overflows for
// opposite-sign values near f32::MAX.
let (av, bv) = (f64::from(a.value), f64::from(b.value));
(av + (bv - av) * (off as f64 / span as f64)) as f32
}
(Some(a), _) => a.value,
_ => default,
}
}
/// Insert or replace a breakpoint.
pub fn set_point(&mut self, at: Samples, value: f32) {
let (lo, hi, _) = self.param.range();
let value = if value.is_nan() { 0.0 } else { value.clamp(lo, hi) };
match self.points.binary_search_by(|p| p.at.cmp(&at)) {
Ok(i) => {
if let Some(p) = self.points.get_mut(i) {
p.value = value;
}
}
Err(i) => self.points.insert(i, AutomationPoint { at, value }),
}
}
/// Remove points in `[start, end)`.
pub fn clear_range(&mut self, start: Samples, end: Samples) -> usize {
let before = self.points.len();
self.points.retain(|p| p.at < start || p.at >= end);
before - self.points.len()
}
/// Write a constant value over a range, keeping the surrounding curve intact with anchor points.
pub fn write_range(&mut self, start: Samples, end: Samples, value: f32, default: f32) {
if end <= start {
return;
}
let before = self.value_at(start.saturating_sub(1), default);
let after = self.value_at(end, default);
self.clear_range(start, end.saturating_add(1));
if start > 0 {
self.set_point(start - 1, before);
}
self.set_point(start, value);
self.set_point(end, value);
let anchor = end.saturating_add(1);
// A real breakpoint already at `end + 1` keeps its own value.
if self.points.binary_search_by(|p| p.at.cmp(&anchor)).is_err() {
self.set_point(anchor, after);
}
}
/// Thin: remove points whose removal changes the curve by less than `tolerance`.
pub fn thin(&mut self, tolerance: f32) -> usize {
// Linear thinning would move the transitions of step lanes.
if matches!(self.param, AutoParam::Mute | AutoParam::SendMute(_)) || self.points.len() < 3 || tolerance.is_nan() {
return 0;
}
let tolerance = f64::from(tolerance);
let mut keep = vec![true; self.points.len()];
let mut last = 0usize;
// Slopes from the last kept point that keep every point removed since then within `tolerance`.
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
for i in 1..self.points.len() - 1 {
let (Some(a), Some(b), Some(c)) = (self.points.get(last), self.points.get(i), self.points.get(i + 1)) else { continue };
let dt = b.at.saturating_sub(a.at) as f64;
let rise = f64::from(b.value) - f64::from(a.value);
lo = lo.max((rise - tolerance) / dt);
hi = hi.min((rise + tolerance) / dt);
let slope = (f64::from(c.value) - f64::from(a.value)) / c.at.saturating_sub(a.at) as f64;
if (lo..=hi).contains(&slope) {
if let Some(k) = keep.get_mut(i) {
*k = false;
}
} else {
last = i;
(lo, hi) = (f64::NEG_INFINITY, f64::INFINITY);
}
}
let before = self.points.len();
let mut it = keep.iter();
self.points.retain(|_| it.next().copied().unwrap_or(true));
before - self.points.len()
}
/// Shift points at or after `from` by `delta` (Shuffle edits, Insert Time).
pub fn shift_from(&mut self, from: Samples, delta: Samples) {
for p in &mut self.points {
if p.at >= from {
p.at = p.at.saturating_add(delta).max(0);
}
}
self.points.sort_by_key(|p| p.at);
self.points.dedup_by_key(|p| p.at);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_keeps_plugin_param_case() {
let p = AutoParam::Plugin { slot: 0, param: "Cutoff".into() };
assert_eq!(AutoParam::parse("plugin:a:Cutoff"), Some(p));
assert_eq!(AutoParam::parse("Plugin:B:Mix"), Some(AutoParam::Plugin { slot: 1, param: "Mix".into() }));
assert_eq!(AutoParam::parse("Volume"), Some(AutoParam::Volume));
assert_eq!(AutoParam::parse("SEND_B_LEVEL"), Some(AutoParam::SendLevel(1)));
}
#[test]
fn value_at_far_apart_points_does_not_overflow() {
let mut l = AutomationLane::new(AutoParam::Volume);
l.set_point(-1, 0.0);
l.set_point(i64::MAX, -10.0);
let v = l.value_at(5, 0.0);
assert!(v.is_finite() && (-10.0..=0.0).contains(&v));
let w = l.value_at(i64::MAX - 1, 0.0);
assert!(w.is_finite() && (-10.0..=0.0).contains(&w));
}
#[test]
fn value_at_opposite_sign_extremes_stays_finite() {
let mut l = AutomationLane::new(AutoParam::Plugin { slot: 0, param: "Cutoff".into() });
l.set_point(0, -3.0e38);
l.set_point(1000, 3.0e38);
let v = l.value_at(500, 0.0);
assert!(v.is_finite() && v.abs() < 1.0e32, "mid value {v}");
let w = l.value_at(1, 0.0);
assert!(w.is_finite() && w < -2.9e38, "early value {w}");
}
#[test]
fn pan_label_max_does_not_overflow() {
assert_eq!(AutoParam::Pan(255).label(), "pan 256");
}
#[test]
fn interpolation_and_steps() {
let mut l = AutomationLane::new(AutoParam::Volume);
assert_eq!(l.value_at(10, -3.0), -3.0);
l.set_point(0, 0.0);
l.set_point(100, -10.0);
assert!((l.value_at(50, 0.0) + 5.0).abs() < 1e-6);
assert_eq!(l.value_at(1000, 0.0), -10.0);
let mut m = AutomationLane::new(AutoParam::Mute);
m.set_point(0, 0.0);
m.set_point(100, 1.0);
assert_eq!(m.value_at(99, 0.0), 0.0);
assert_eq!(m.value_at(100, 0.0), 1.0);
}
#[test]
fn write_range_keeps_point_right_after_end() {
let mut l = AutomationLane::new(AutoParam::Volume);
l.set_point(0, 0.0);
l.set_point(11, -100.0);
l.write_range(2, 10, -20.0, 0.0);
assert_eq!(l.value_at(11, 0.0), -100.0);
}
#[test]
fn write_range_preserves_outside() {
let mut l = AutomationLane::new(AutoParam::Volume);
l.set_point(0, 0.0);
l.set_point(1000, 0.0);
l.write_range(200, 400, -20.0, 0.0);
assert_eq!(l.value_at(100, 0.0), 0.0);
assert_eq!(l.value_at(300, 0.0), -20.0);
assert_eq!(l.value_at(600, 0.0), 0.0);
}
#[test]
fn thin_removes_collinear() {
let mut l = AutomationLane::new(AutoParam::Volume);
for i in 0..=10 {
l.set_point(i * 10, -(i as f32));
}
assert_eq!(l.thin(0.01), 9);
assert_eq!(l.points.len(), 2);
}
#[test]
fn thin_keeps_removed_points_within_tolerance() {
for direction in [1.0, -1.0] {
let mut lane = AutomationLane::new(AutoParam::Volume);
for (at, value) in [(0, 0.0), (100, 0.0), (200, 0.0), (300, 0.12), (400, 0.26)] {
lane.set_point(at, value * direction);
}
let original = lane.points.clone();
let tolerance = 0.1;
assert!(lane.thin(tolerance) > 0);
for point in original {
let error = (lane.value_at(point.at, 0.0) - point.value).abs();
assert!(error <= tolerance, "at {}: error {error} exceeds {tolerance}", point.at);
}
}
}
#[test]
fn thin_keeps_mute_changes_in_place() {
for param in [AutoParam::Mute, AutoParam::SendMute(0)] {
let mut lane = AutomationLane::new(param);
for (at, value) in [(0, 0.0), (9000, 1.0), (10000, 1.0)] {
lane.set_point(at, value);
}
lane.thin(0.1);
assert_eq!(lane.value_at(8999, 0.0), 0.0);
assert_eq!(lane.value_at(9000, 0.0), 1.0);
}
}
#[test]
fn param_ids() {
assert_eq!(AutoParam::parse("send_b_level"), Some(AutoParam::SendLevel(1)));
assert_eq!(AutoParam::parse("plugin:a:threshold"), Some(AutoParam::Plugin { slot: 0, param: "threshold".into() }));
assert_eq!(AutoParam::parse("nope"), None);
assert_eq!(AutomationMode::from_id("touch/latch"), Some(AutomationMode::TouchLatch));
}
#[test]
fn set_point_clamps_nan() {
let mut l = AutomationLane::new(AutoParam::Pan(0));
l.set_point(0, f32::NAN);
l.set_point(1, 5.0);
assert_eq!(l.points[0].value, 0.0);
assert_eq!(l.points[1].value, 1.0);
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Standard base64 (RFC 4648, `+/` alphabet, `=` padding), used to keep opaque plugin state
//! blobs in the JSON session file. Decoding treats its input as hostile: it rejects bad
//! characters and bad padding, ignores ASCII whitespace, and caps the output size.
/// Largest blob [`decode`] will produce (64 MiB): bigger session fields are rejected.
pub const MAX_DECODED_BYTES: usize = 64 << 20;
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// Encodes bytes as padded standard base64.
pub fn encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3).saturating_mul(4));
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
let sym = |shift: u32| char::from(ALPHABET.get(((n >> shift) & 63) as usize).copied().unwrap_or(b'A'));
out.push(sym(18));
out.push(sym(12));
out.push(if chunk.len() > 1 { sym(6) } else { '=' });
out.push(if chunk.len() > 2 { sym(0) } else { '=' });
}
out
}
fn value(c: u8) -> Option<u32> {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
_ => return None,
};
Some(u32::from(v))
}
/// Decodes padded (or unpadded) standard base64. `None` for malformed input or a result larger
/// than [`MAX_DECODED_BYTES`].
pub fn decode(text: &str) -> Option<Vec<u8>> {
if text.bytes().filter(|c| !c.is_ascii_whitespace()).count() > MAX_DECODED_BYTES.div_ceil(3).saturating_mul(4) {
return None;
}
let syms: Vec<u8> = text.bytes().filter(|c| !c.is_ascii_whitespace()).collect();
let body = syms.strip_suffix(b"==").or_else(|| syms.strip_suffix(b"=")).unwrap_or(&syms);
if body.contains(&b'=') || (syms.len() != body.len() && !syms.len().is_multiple_of(4)) || body.len() % 4 == 1 {
return None;
}
let decoded_len = body.len() / 4 * 3 + body.len() % 4 * 3 / 4;
if decoded_len > MAX_DECODED_BYTES {
return None;
}
let mut out = Vec::with_capacity(decoded_len);
for chunk in body.chunks(4) {
let mut n = 0u32;
for (i, &c) in chunk.iter().enumerate() {
n |= value(c)? << (18 - 6 * i as u32);
}
let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8];
out.extend_from_slice(bytes.get(..chunk.len() - 1)?);
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc4648_vectors_round_trip() {
for (plain, enc) in
[("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")]
{
assert_eq!(encode(plain.as_bytes()), enc);
assert_eq!(decode(enc).unwrap(), plain.as_bytes());
}
let all: Vec<u8> = (0..=255).collect();
assert_eq!(decode(&encode(&all)).unwrap(), all);
assert_eq!(decode("Zm9v\nYmE=").unwrap(), b"fooba", "whitespace is ignored");
assert_eq!(decode("Zm9vYmE").unwrap(), b"fooba", "padding is optional");
}
#[test]
fn hostile_input_is_rejected() {
for bad in ["Z", "Zm9=v", "Zm9v!", "====", "Zg=", "é", "Zg===", "Z==="] {
assert!(decode(bad).is_none(), "{bad}");
}
}
#[test]
fn size_cap_counts_the_partial_quartet() {
for (extra, ok) in [(-1, true), (0, true), (1, false), (2, false)] {
let data = vec![7u8; MAX_DECODED_BYTES.saturating_add_signed(extra)];
let padded = encode(&data);
let unpadded = padded.trim_end_matches('=');
assert_eq!(decode(&padded).is_some(), ok, "padded, {extra}");
assert_eq!(decode(unpadded).is_some(), ok, "unpadded, {extra}");
let spaced = format!("{}\n {}", &padded[..8], &padded[8..]);
assert_eq!(decode(&spaced).is_some(), ok, "whitespace, {extra}");
}
}
}
+544
View File
@@ -0,0 +1,544 @@
//! Clips: windows onto audio sources or MIDI sequences, placed on a playlist.
use crate::{ClipId, MAX_NAME_CHARS, SourceId, truncate_chars};
use soundcraft_midi::Sequence;
use soundcraft_time::{MAX_POSITION, Range, Samples};
/// Fade curve shapes (Pro Tools offers standard, equal-power, S-curve and custom presets).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum FadeShape {
Linear,
#[default]
EqualPower,
SCurve,
Exponential,
Logarithmic,
}
impl FadeShape {
pub const ALL: [FadeShape; 5] = [FadeShape::Linear, FadeShape::EqualPower, FadeShape::SCurve, FadeShape::Exponential, FadeShape::Logarithmic];
/// Fade-in gain at `t` ∈ [0,1] (fade-outs use `gain(1 - t)`).
pub fn gain(self, t: f32) -> f32 {
let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
match self {
FadeShape::Linear => t,
FadeShape::EqualPower => (t * std::f32::consts::FRAC_PI_2).sin(),
FadeShape::SCurve => 0.5 - 0.5 * (t * std::f32::consts::PI).cos(),
FadeShape::Exponential => t * t * t,
FadeShape::Logarithmic => 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t),
}
}
pub fn label(self) -> &'static str {
match self {
FadeShape::Linear => "Linear",
FadeShape::EqualPower => "Equal Power",
FadeShape::SCurve => "S-Curve",
FadeShape::Exponential => "Exponential",
FadeShape::Logarithmic => "Logarithmic",
}
}
pub fn from_id(s: &str) -> Option<FadeShape> {
let s = s.to_ascii_lowercase().replace(['-', '_', ' '], "");
FadeShape::ALL.into_iter().find(|f| f.label().to_ascii_lowercase().replace(['-', ' '], "") == s)
}
}
/// A fade at a clip boundary, `len` samples long.
#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct Fade {
pub len: Samples,
pub shape: FadeShape,
/// Continuous bend (-1..1); zero preserves the original shape exactly.
#[serde(default)]
pub curvature: f32,
}
impl Fade {
/// The envelope used by both rendering and audio, with fixed zero/unity endpoints.
pub fn gain(self, t: f32) -> f32 {
let base = self.shape.gain(t);
let curvature = if self.curvature.is_finite() { self.curvature.clamp(-1.0, 1.0) } else { 0.0 };
if curvature == 0.0 || base <= 0.0 || base >= 1.0 {
return base;
}
let weighted = base * (curvature * 4.0).exp2();
weighted / (weighted + 1.0 - base)
}
/// Invert the bend at the midpoint so a vertical drag follows the pointer.
pub fn curvature_for_midpoint_gain(self, gain: f32) -> f32 {
let gain = if gain.is_finite() { gain.clamp(0.001, 0.999) } else { self.gain(0.5) };
let base = self.shape.gain(0.5);
(((gain / (1.0 - gain)).log2() - (base / (1.0 - base)).log2()) / 4.0).clamp(-1.0, 1.0)
}
pub fn sanitize(&mut self) {
self.curvature = if self.curvature.is_finite() { self.curvature.clamp(-1.0, 1.0) } else { 0.0 };
}
}
/// What a clip plays.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ClipContent {
/// Audio from `source`, starting `offset` samples into the file.
Audio { source: SourceId, offset: Samples },
/// MIDI notes, with ticks relative to the clip start.
Midi { sequence: Sequence },
/// Picture from the movie `source` ([`crate::VideoSource`], `Session::videos`), starting
/// `offset` samples into the movie. Video clips carry no audio.
Video { source: SourceId, offset: Samples },
}
/// A clip on a playlist.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Clip {
pub id: ClipId,
pub name: String,
/// Timeline start (samples).
pub start: Samples,
/// Length (samples, > 0).
pub length: Samples,
pub content: ClipContent,
/// Static clip gain in dB.
#[serde(default)]
pub gain_db: f32,
/// Clip gain envelope breakpoints: (offset from clip start, dB). Empty = flat `gain_db`.
#[serde(default)]
pub gain_env: Vec<(Samples, f32)>,
#[serde(default)]
pub fade_in: Fade,
#[serde(default)]
pub fade_out: Fade,
#[serde(default)]
pub muted: bool,
#[serde(default)]
pub edit_locked: bool,
#[serde(default)]
pub time_locked: bool,
#[serde(default)]
pub rating: u8,
/// Sync point offset from clip start.
#[serde(default)]
pub sync_point: Samples,
/// Optional colour override (RGB).
#[serde(default)]
pub color: Option<[u8; 3]>,
/// The key in [`crate::Session::auto_names`] of the names that editing gives the clips it
/// separates from this one (Clip List › Auto Rename). `None` keeps the clip's name.
#[serde(default)]
pub auto_name: Option<u64>,
/// Elastic / Vari-speed ratio (1.0 = none) — applied by rendered processing.
#[serde(default = "one")]
pub stretch: f64,
/// Reversed playback (AudioSuite Reverse renders into a new source; this is for previews).
#[serde(default)]
pub group: Option<u64>,
/// Marks the clips made by `clip.loop` (the origin and its copies share one id), so
/// `clip.unloop` still recognises the loop after the source's content is edited.
#[serde(default)]
pub loop_id: Option<u64>,
}
fn one() -> f64 {
1.0
}
impl Clip {
pub fn audio(id: ClipId, name: impl Into<String>, source: SourceId, offset: Samples, start: Samples, length: Samples) -> Clip {
Clip {
id,
name: name.into(),
start,
length: length.max(1),
content: ClipContent::Audio { source, offset },
gain_db: 0.0,
gain_env: Vec::new(),
fade_in: Fade::default(),
fade_out: Fade::default(),
muted: false,
edit_locked: false,
time_locked: false,
rating: 0,
sync_point: 0,
color: None,
auto_name: None,
stretch: 1.0,
group: None,
loop_id: None,
}
}
pub fn midi(id: ClipId, name: impl Into<String>, start: Samples, length: Samples, sequence: Sequence) -> Clip {
let mut c = Clip::audio(id, name, SourceId(0), 0, start, length);
c.content = ClipContent::Midi { sequence };
c
}
/// A clip showing the movie `source` from `offset` samples into it.
pub fn video(id: ClipId, name: impl Into<String>, source: SourceId, offset: Samples, start: Samples, length: Samples) -> Clip {
let mut c = Clip::audio(id, name, SourceId(0), 0, start, length);
c.content = ClipContent::Video { source, offset };
c
}
pub fn end(&self) -> Samples {
self.start.saturating_add(self.length)
}
pub fn range(&self) -> Range {
Range { start: self.start, end: self.end() }
}
pub fn is_audio(&self) -> bool {
matches!(self.content, ClipContent::Audio { .. })
}
pub fn is_video(&self) -> bool {
matches!(self.content, ClipContent::Video { .. })
}
/// The audio source this clip plays (None for MIDI and video clips).
pub fn source(&self) -> Option<SourceId> {
match self.content {
ClipContent::Audio { source, .. } => Some(source),
ClipContent::Midi { .. } | ClipContent::Video { .. } => None,
}
}
/// The movie this clip shows (video clips only).
pub fn video_source(&self) -> Option<SourceId> {
match self.content {
ClipContent::Video { source, .. } => Some(source),
ClipContent::Audio { .. } | ClipContent::Midi { .. } => None,
}
}
/// Offset into the audio file or movie (0 for MIDI).
pub fn source_offset(&self) -> Samples {
match self.content {
ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } => offset,
ClipContent::Midi { .. } => 0,
}
}
/// Gain (linear) at `rel` samples from the clip start: clip gain × envelope × fades.
pub fn gain_at(&self, rel: Samples) -> f32 {
self.gain_at_with_fades(rel, self.fade_in, self.fade_out)
}
/// Evaluate temporary fades while retaining clip gain and its envelope.
/// UI previews can use this without modifying the clip or rebuilding media.
pub fn gain_at_with_fades(&self, rel: Samples, fade_in: Fade, fade_out: Fade) -> f32 {
let mut db = self.gain_db;
if !self.gain_env.is_empty() {
db += env_value(&self.gain_env, rel);
}
let mut g = db_to_gain(db);
if fade_in.len > 0 && rel < fade_in.len {
g *= fade_in.gain(rel as f32 / fade_in.len as f32);
}
let from_end = self.length.saturating_sub(rel);
if fade_out.len > 0 && from_end <= fade_out.len {
g *= fade_out.gain(from_end as f32 / fade_out.len as f32);
}
g
}
/// Gain envelope value in dB at `rel` samples from the clip start (0 without an envelope).
pub fn env_db_at(&self, rel: Samples) -> f32 {
env_value(&self.gain_env, rel)
}
/// Move the start edge to `new_start` keeping material anchored (trim start).
pub fn trim_start_to(&mut self, new_start: Samples) {
// #907: these are public APIs, so they have to survive arguments a command would never
// pass (commands clamp to `MAX_POSITION` first). `Samples` is `i64`, so an extreme
// `new_start` against an extreme `start` wrapped in release and panicked in debug.
// Never so far back that the length would pass `MAX_POSITION`: trimming the start keeps the end.
let end = self.end();
let new_start = new_start.max(end.saturating_sub(MAX_POSITION)).clamp(-MAX_POSITION, MAX_POSITION).min(end.saturating_sub(1));
let delta = new_start.saturating_sub(self.start);
// The mixer plays a stretched audio clip from `offset + rel / stretch`.
let stretch = if self.stretch.is_finite() && self.stretch > 0.0 { self.stretch } else { 1.0 };
match &mut self.content {
ClipContent::Audio { offset, .. } if (stretch - 1.0).abs() >= 1e-9 => {
*offset = offset.saturating_add((delta as f64 / stretch).round() as Samples);
}
ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } => {
*offset = offset.saturating_add(delta);
}
ClipContent::Midi { .. } => {}
}
// MIDI note ticks are re-anchored by the engine, which knows the tempo map.
self.length = self.length.saturating_sub(delta).clamp(1, MAX_POSITION);
self.start = new_start;
if self.sync_point != 0 {
self.sync_point = self.sync_point.saturating_sub(delta);
}
self.drop_stray_sync();
self.clamp_fades();
// Keep the gain at the cut when earlier breakpoints are dropped.
if self.gain_env.iter().any(|&(t, _)| t < delta) && self.gain_env.iter().all(|&(t, _)| t != delta) {
self.gain_env.insert(0, (delta, env_value(&self.gain_env, delta)));
}
self.gain_env.retain(|&(t, _)| t >= delta);
self.gain_env.iter_mut().for_each(|(t, _)| *t = t.saturating_sub(delta));
}
/// Move the end edge to `new_end`.
pub fn trim_end_to(&mut self, new_end: Samples) {
// #907: saturating, like `trim_start_to`.
let new_end = new_end.clamp(-MAX_POSITION, MAX_POSITION).max(self.start.saturating_add(1));
self.length = new_end.saturating_sub(self.start).clamp(1, MAX_POSITION);
self.drop_stray_sync();
self.clamp_fades();
}
/// Keep both fades within the clip.
pub fn clamp_fades(&mut self) {
self.fade_in.len = self.fade_in.len.clamp(0, self.length);
self.fade_out.len = self.fade_out.len.clamp(0, self.length);
}
/// A sync point (0 means none) that a trim left outside the clip no longer marks anything.
fn drop_stray_sync(&mut self) {
if !(0..self.length).contains(&self.sync_point) {
self.sync_point = 0;
}
}
/// Repair a clip read from a file: positions and lengths within ±[`MAX_POSITION`], as commands
/// keep theirs, fades within the clip, a name that can be drawn, and a usable gain and stretch.
pub fn sanitize(&mut self) {
bound(&mut self.start);
self.length = self.length.clamp(1, MAX_POSITION);
bound(&mut self.sync_point);
self.gain_env.iter_mut().for_each(|(at, _)| bound(at));
match &mut self.content {
ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } => bound(offset),
ClipContent::Midi { sequence } => bound_sequence(sequence),
}
self.clamp_fades();
self.fade_in.sanitize();
self.fade_out.sanitize();
truncate_chars(&mut self.name, MAX_NAME_CHARS);
if !self.gain_db.is_finite() {
self.gain_db = 0.0;
}
if !self.stretch.is_finite() || self.stretch <= 0.0 {
self.stretch = 1.0;
}
}
}
pub(crate) fn bound(at: &mut Samples) {
*at = (*at).clamp(-MAX_POSITION, MAX_POSITION);
}
pub(crate) fn bound_sequence(s: &mut Sequence) {
for n in &mut s.notes {
bound(&mut n.start);
n.length = n.length.clamp(1, MAX_POSITION);
}
s.ctrls.iter_mut().for_each(|c| bound(&mut c.tick));
}
fn env_value(env: &[(Samples, f32)], at: Samples) -> f32 {
let mut prev: Option<(Samples, f32)> = None;
for &(t, v) in env {
if t >= at {
return match prev {
Some((pt, pv)) if t > pt => {
let elapsed = i128::from(at).saturating_sub(i128::from(pt));
let span = i128::from(t).saturating_sub(i128::from(pt));
pv + (v - pv) * (elapsed as f32 / span as f32)
}
_ => v,
};
}
prev = Some((t, v));
}
prev.map_or(0.0, |(_, v)| v)
}
pub(crate) fn db_to_gain(db: f32) -> f32 {
if db.is_nan() || db <= -144.0 { 0.0 } else { 10f32.powf(db.min(48.0) / 20.0) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fade_shapes_hit_endpoints() {
for s in FadeShape::ALL {
assert!(s.gain(0.0).abs() < 1e-6, "{s:?}");
assert!((s.gain(1.0) - 1.0).abs() < 1e-6, "{s:?}");
assert_eq!(s.gain(f32::NAN), 0.0);
assert_eq!(FadeShape::from_id(s.label()), Some(s));
}
}
#[test]
fn fade_curvature_is_bounded_monotonic_and_inverts_at_the_midpoint() {
for shape in FadeShape::ALL {
let original = Fade { len: 1000, shape, curvature: 0.0 };
for i in 0..=128 {
let t = i as f32 / 128.0;
assert_eq!(original.gain(t), shape.gain(t), "legacy curves must be unchanged");
}
for curvature in [-1.0, -0.5, 0.0, 0.5, 1.0] {
let fade = Fade { curvature, ..original };
assert_eq!(fade.gain(0.0), 0.0);
assert_eq!(fade.gain(1.0), 1.0);
let mut previous = 0.0;
for i in 0..=128 {
let gain = fade.gain(i as f32 / 128.0);
assert!(gain.is_finite() && (0.0..=1.0).contains(&gain));
assert!(gain >= previous, "{shape:?}, {curvature}");
previous = gain;
}
assert!((fade.curvature_for_midpoint_gain(fade.gain(0.5)) - curvature).abs() < 1e-5);
}
assert!((Fade { curvature: 0.5, ..original }).gain(0.5) > original.gain(0.5));
assert!((Fade { curvature: -0.5, ..original }).gain(0.5) < original.gain(0.5));
}
}
#[test]
fn fade_curvature_loads_legacy_data_and_sanitizes_hostile_values() {
let fade: Fade = serde_json::from_str(r#"{"len":100,"shape":"SCurve"}"#).unwrap();
assert_eq!(fade.curvature, 0.0);
for curvature in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -10.0, 10.0] {
let mut fade = Fade { curvature, ..fade };
assert!(fade.gain(0.5).is_finite());
fade.sanitize();
assert!(fade.curvature.is_finite() && (-1.0..=1.0).contains(&fade.curvature));
let roundtrip: Fade = serde_json::from_str(&serde_json::to_string(&fade).unwrap()).unwrap();
assert_eq!(roundtrip, fade);
}
}
#[test]
fn temporary_fades_keep_clip_gain_and_envelope_without_mutating_the_clip() {
let mut clip = Clip::audio(ClipId(1), "preview", SourceId(1), 0, 0, 1000);
clip.gain_db = -6.0;
clip.gain_env = vec![(0, 0.0), (1000, 6.0)];
clip.fade_in = Fade { len: 100, shape: FadeShape::SCurve, curvature: 0.25 };
clip.fade_out = Fade { len: 100, shape: FadeShape::Logarithmic, curvature: -0.1 };
let before = clip.clone();
let fade_in = Fade { len: 1000, shape: FadeShape::Linear, curvature: 0.5 };
let fade_out = Fade { len: 1000, shape: FadeShape::Linear, curvature: -0.5 };
assert!((clip.gain_at_with_fades(500, fade_in, fade_out) - db_to_gain(-3.0) * 0.16).abs() < 1e-6);
let mut committed = clip.clone();
committed.fade_in = fade_in;
committed.fade_out = fade_out;
for rel in [0, 50, 500, 999, 1000] {
assert_eq!(clip.gain_at_with_fades(rel, fade_in, fade_out), committed.gain_at(rel));
}
for rel in [i64::MIN, i64::MAX] {
assert!(clip.gain_at(rel).is_finite());
assert!(clip.gain_at_with_fades(rel, fade_in, fade_out).is_finite());
}
assert_eq!(clip, before);
clip.gain_env = vec![(i64::MIN, 0.0), (i64::MAX, 6.0)];
assert!((clip.gain_at(500) - db_to_gain(-3.0)).abs() < 1e-6);
assert!((clip.gain_at_with_fades(500, fade_in, fade_out) - db_to_gain(-3.0) * 0.16).abs() < 1e-6);
}
#[test]
fn gain_with_fades() {
let mut c = Clip::audio(ClipId(1), "a", SourceId(1), 0, 100, 1000);
c.fade_in = Fade { len: 100, shape: FadeShape::Linear, curvature: 0.0 };
c.fade_out = Fade { len: 100, shape: FadeShape::Linear, curvature: 0.0 };
assert!(c.gain_at(0).abs() < 1e-6);
assert!((c.gain_at(50) - 0.5).abs() < 1e-6);
assert!((c.gain_at(500) - 1.0).abs() < 1e-6);
assert!((c.gain_at(950) - 0.5).abs() < 1e-6);
}
#[test]
fn gain_envelope_interpolates() {
let mut c = Clip::audio(ClipId(1), "a", SourceId(1), 0, 0, 1000);
c.gain_env = vec![(0, 0.0), (1000, -20.0)];
assert!((c.gain_at(500) - db_to_gain(-10.0)).abs() < 1e-4);
}
#[test]
fn trim_start_keeps_gain_envelope_at_cut() {
for (env, cut, expected) in [
(vec![(0, 0.0), (1000, -20.0)], 500, vec![(0, -10.0), (500, -20.0)]),
(vec![(0, 0.0), (100, -20.0)], 500, vec![(0, -20.0)]),
(vec![(0, 0.0), (500, -10.0), (1000, -20.0)], 500, vec![(0, -10.0), (500, -20.0)]),
(vec![], 500, vec![]),
(vec![(100, -3.0)], 0, vec![(100, -3.0)]),
(vec![(100, -3.0)], -100, vec![(200, -3.0)]),
] {
let mut clip = Clip::audio(ClipId(1), "a", SourceId(1), 100, 0, 1000);
clip.gain_env = env;
let gain_at_cut = clip.gain_at(cut);
clip.trim_start_to(cut);
assert_eq!(clip.gain_env, expected);
if cut > 0 {
assert!((clip.gain_at(0) - gain_at_cut).abs() < 1e-6);
}
}
}
#[test]
fn trims_keep_material_anchored() {
let mut c = Clip::audio(ClipId(1), "a", SourceId(1), 1000, 100, 1000);
c.trim_start_to(300);
assert_eq!((c.start, c.length, c.source_offset()), (300, 800, 1200));
c.trim_end_to(500);
assert_eq!(c.length, 200);
c.trim_end_to(-50);
assert_eq!(c.length, 1);
// Regression: trimming the start must not leave a fade-out longer than the clip.
let mut c = Clip::audio(ClipId(2), "b", SourceId(1), 0, 0, 1000);
c.fade_out = Fade { len: 800, shape: FadeShape::Linear, curvature: 0.0 };
c.trim_start_to(900);
assert!(c.fade_out.len <= c.length);
}
/// #907: `trim_start_to` / `trim_end_to` are public APIs, so they have to survive arguments a
/// command would never pass. `Samples` is `i64`, so an extreme `new_start` against an extreme
/// `start` wrapped in release and panicked in debug. Every position stays within
/// `±MAX_POSITION` and every length within `1..=MAX_POSITION`.
#[test]
fn trims_saturate_on_extreme_arguments() {
for &new_start in &[Samples::MIN, -(MAX_POSITION * 2), -1, 0, MAX_POSITION, MAX_POSITION * 2, Samples::MAX] {
let mut c = Clip::audio(ClipId(1), "a", SourceId(1), 1000, MAX_POSITION / 2, 1000);
c.trim_start_to(new_start);
assert!((-(MAX_POSITION as i128)..=(MAX_POSITION as i128)).contains(&(c.start as i128)), "start {new_start}: {}", c.start);
assert!((1..=MAX_POSITION).contains(&c.length), "start {new_start}: length {}", c.length);
assert_eq!(c.end(), MAX_POSITION / 2 + 1000, "start {new_start} moved the end");
}
for &new_end in &[Samples::MIN, -(MAX_POSITION * 2), -1, 0, MAX_POSITION, MAX_POSITION * 2, Samples::MAX] {
let mut c = Clip::audio(ClipId(2), "b", SourceId(1), 1000, -(MAX_POSITION / 2), 1000);
c.trim_end_to(new_end);
assert!((1..=MAX_POSITION).contains(&c.length), "end {new_end}: length {}", c.length);
assert!(c.end() - c.start == c.length, "end {new_end}: start {} end {}", c.start, c.end());
}
}
#[test]
fn trim_start_of_stretched_audio_advances_offset_by_source_time() {
// The mixer plays source `offset + rel / stretch`, so a split at timeline 1000 of a 2x clip
// must start the right half at source sample 500.
let mut c = Clip::audio(ClipId(1), "a", SourceId(1), 0, 0, 2000);
c.stretch = 2.0;
c.trim_start_to(1000);
assert_eq!(c.source_offset(), 500);
let mut c = Clip::audio(ClipId(2), "b", SourceId(1), 0, 0, 2000);
c.stretch = 0.5;
c.trim_start_to(1000);
assert_eq!(c.source_offset(), 2000);
let mut c = Clip::audio(ClipId(3), "c", SourceId(1), 0, 0, 2000);
c.trim_start_to(1000);
assert_eq!(c.source_offset(), 1000);
}
}
+21
View File
@@ -0,0 +1,21 @@
//! Typed ids. All ids come from one session-wide counter so they never collide across kinds.
macro_rules! id_type {
($name:ident) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct $name(pub u64);
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
};
}
id_type!(TrackId);
id_type!(ClipId);
id_type!(SourceId);
id_type!(BusId);
id_type!(GroupId);
id_type!(MarkerId);
+29 -4
View File
@@ -1,7 +1,32 @@
//! Compatibility facade for SoundCraft's shared session document crate.
//! The SoundCraft session document.
//!
//! Engine and UI adapters depend on this name, while the wire schema, JSON reader/writer,
//! validation, and bundle format live in `craft-scraft-format`.
//! A [`Session`] is pure data: tracks with playlists of clips, the mixer (inserts, sends, routing,
//! automation), tempo/meter, memory locations and groups. Audio sample data lives in
//! [`SourcePool`] behind `Arc`s, so cloning a session for undo is cheap.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub use craft_scraft_format::*;
mod automation;
pub mod b64;
mod clip;
mod ids;
mod markers;
mod mixer;
mod session;
mod source;
mod track;
pub use automation::{AutoParam, AutomationLane, AutomationMode, AutomationPoint};
pub use clip::{Clip, ClipContent, Fade, FadeShape};
pub use ids::{BusId, ClipId, GroupId, MarkerId, SourceId, TrackId};
pub use markers::{Group, MarkerKind, MemoryLocation};
pub use mixer::{
Bus, ChannelFormat, INSERT_SLOTS, Insert, Mixer, OutputPath, Route, SEND_SLOTS, SendSlot, Speaker, SurroundPan, fader_db_to_pos, fader_pos_to_db,
};
pub use session::{
AutoName, BitDepthSetting, EditMode, EditState, FEET_FRAMES_START, MAX_COMMENT_CHARS, MAX_NAME_CHARS, SESSION_EXTENSION, Session, SessionError,
Tool, TrackView, ZoomState, ZoomToggle, truncate_chars,
};
pub use source::{FileFormat, Source, SourceAudio, SourcePool, VideoSource};
pub use track::{Playlist, TRACK_COLORS, Track, TrackHeight, TrackKind};
pub use soundcraft_time as time;
+58
View File
@@ -0,0 +1,58 @@
//! Memory locations (markers and stored selections) and mix/edit groups.
use crate::{GroupId, MarkerId, TrackId};
use soundcraft_time::Samples;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum MarkerKind {
/// A point marker on a ruler.
#[default]
Marker,
/// A stored selection range.
Selection,
/// A location that only recalls view settings.
None,
}
/// A memory location (Window › Memory Locations).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MemoryLocation {
pub id: MarkerId,
/// User-visible number (1-based, unique).
pub number: u32,
pub name: String,
pub kind: MarkerKind,
pub start: Samples,
pub end: Samples,
#[serde(default)]
pub comments: String,
#[serde(default)]
pub color: Option<[u8; 3]>,
/// Marker ruler lane 1..5.
#[serde(default = "one")]
pub ruler: u8,
/// Track-lane marker on this track, if any.
#[serde(default)]
pub track: Option<TrackId>,
}
fn one() -> u8 {
1
}
/// A track group (Track › Group…).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Group {
pub id: GroupId,
pub name: String,
/// Group letter id shown in the Groups list ("a", "b", …).
pub letter: char,
pub members: Vec<TrackId>,
pub edit: bool,
pub mix: bool,
pub active: bool,
pub color: [u8; 3],
/// Shared attributes linked by the group (volume, mute, solo, rec, etc.).
#[serde(default)]
pub attributes: Vec<String>,
}
+714
View File
@@ -0,0 +1,714 @@
//! Per-track mixer state: inserts, sends, routing, fader, pan, mute/solo.
use crate::{AutomationMode, BusId, SourceId};
use std::collections::BTreeMap;
pub const INSERT_SLOTS: usize = 10;
pub const SEND_SLOTS: usize = 10;
/// Channel formats (track widths).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum ChannelFormat {
#[default]
Mono,
Stereo,
Lcr,
Quad,
Lcrs,
Surround50,
Surround51,
Surround60,
Surround61,
Sdds70,
Sdds71,
Surround70,
Surround71,
Atmos702,
Atmos712,
Atmos502,
Atmos512,
Atmos504,
Atmos514,
Atmos704,
Atmos714,
Atmos706,
Atmos716,
Atmos904,
Atmos914,
Atmos906,
Atmos916,
/// Ambisonics of order 1..=7 ((n+1)² channels).
Ambisonics(u8),
}
impl ChannelFormat {
pub const ALL: [ChannelFormat; 34] = [
ChannelFormat::Mono,
ChannelFormat::Stereo,
ChannelFormat::Lcr,
ChannelFormat::Quad,
ChannelFormat::Lcrs,
ChannelFormat::Surround50,
ChannelFormat::Surround51,
ChannelFormat::Surround60,
ChannelFormat::Surround61,
ChannelFormat::Sdds70,
ChannelFormat::Sdds71,
ChannelFormat::Surround70,
ChannelFormat::Surround71,
ChannelFormat::Atmos702,
ChannelFormat::Atmos712,
ChannelFormat::Ambisonics(1),
ChannelFormat::Ambisonics(2),
ChannelFormat::Ambisonics(3),
ChannelFormat::Ambisonics(4),
ChannelFormat::Ambisonics(5),
ChannelFormat::Ambisonics(6),
ChannelFormat::Ambisonics(7),
ChannelFormat::Atmos502,
ChannelFormat::Atmos512,
ChannelFormat::Atmos504,
ChannelFormat::Atmos514,
ChannelFormat::Atmos704,
ChannelFormat::Atmos714,
ChannelFormat::Atmos706,
ChannelFormat::Atmos716,
ChannelFormat::Atmos904,
ChannelFormat::Atmos914,
ChannelFormat::Atmos906,
ChannelFormat::Atmos916,
];
pub fn channels(self) -> usize {
match self {
ChannelFormat::Mono => 1,
ChannelFormat::Stereo => 2,
ChannelFormat::Lcr => 3,
ChannelFormat::Quad | ChannelFormat::Lcrs => 4,
ChannelFormat::Surround50 => 5,
ChannelFormat::Surround51 | ChannelFormat::Surround60 => 6,
ChannelFormat::Surround61 | ChannelFormat::Sdds70 | ChannelFormat::Surround70 | ChannelFormat::Atmos502 => 7,
ChannelFormat::Sdds71 | ChannelFormat::Surround71 | ChannelFormat::Atmos512 => 8,
ChannelFormat::Atmos702 | ChannelFormat::Atmos504 => 9,
ChannelFormat::Atmos712 | ChannelFormat::Atmos514 => 10,
ChannelFormat::Atmos704 => 11,
ChannelFormat::Atmos714 => 12,
ChannelFormat::Atmos706 | ChannelFormat::Atmos904 => 13,
ChannelFormat::Atmos716 | ChannelFormat::Atmos914 => 14,
ChannelFormat::Atmos906 => 15,
ChannelFormat::Atmos916 => 16,
ChannelFormat::Ambisonics(n) => {
let n = usize::from(n.clamp(1, 7)) + 1;
n * n
}
}
}
pub fn label(self) -> &'static str {
match self {
ChannelFormat::Mono => "Mono",
ChannelFormat::Stereo => "Stereo",
ChannelFormat::Lcr => "LCR",
ChannelFormat::Quad => "Quad",
ChannelFormat::Lcrs => "LCRS",
ChannelFormat::Surround50 => "5.0",
ChannelFormat::Surround51 => "5.1",
ChannelFormat::Surround60 => "6.0",
ChannelFormat::Surround61 => "6.1",
ChannelFormat::Sdds70 => "7.0 SDDS",
ChannelFormat::Sdds71 => "7.1 SDDS",
ChannelFormat::Surround70 => "7.0",
ChannelFormat::Surround71 => "7.1",
ChannelFormat::Atmos702 => "7.0.2",
ChannelFormat::Atmos712 => "7.1.2",
ChannelFormat::Atmos502 => "5.0.2",
ChannelFormat::Atmos512 => "5.1.2",
ChannelFormat::Atmos504 => "5.0.4",
ChannelFormat::Atmos514 => "5.1.4",
ChannelFormat::Atmos704 => "7.0.4",
ChannelFormat::Atmos714 => "7.1.4",
ChannelFormat::Atmos706 => "7.0.6",
ChannelFormat::Atmos716 => "7.1.6",
ChannelFormat::Atmos904 => "9.0.4",
ChannelFormat::Atmos914 => "9.1.4",
ChannelFormat::Atmos906 => "9.0.6",
ChannelFormat::Atmos916 => "9.1.6",
ChannelFormat::Ambisonics(1) => "1st Order Ambisonics",
ChannelFormat::Ambisonics(2) => "2nd Order Ambisonics",
ChannelFormat::Ambisonics(3) => "3rd Order Ambisonics",
ChannelFormat::Ambisonics(4) => "4th Order Ambisonics",
ChannelFormat::Ambisonics(5) => "5th Order Ambisonics",
ChannelFormat::Ambisonics(6) => "6th Order Ambisonics",
ChannelFormat::Ambisonics(_) => "7th Order Ambisonics",
}
}
pub fn from_id(s: &str) -> Option<ChannelFormat> {
ChannelFormat::ALL.into_iter().find(|f| f.label().eq_ignore_ascii_case(s.trim()))
}
/// Speakers in channel order, or empty for Ambisonics (ACN order, SN3D).
///
/// Channel order is SMPTE / WAV order: speakers with a WAVE_FORMAT_EXTENSIBLE mask bit come in
/// ascending bit order (L R C LFE Ls Rs Lc Rc Cs Lss Rss Ltf Rtf Ltr Rtr; 7.x puts the rear
/// surrounds Lrs/Rrs on the "back" bits before the sides Lss/Rss), followed by speakers WAV
/// cannot name (the top-middle pair of .6 layouts). E.g. 5.1 = L R C LFE Ls Rs,
/// 7.1 = L R C LFE Lrs Rrs Lss Rss, 7.1.4 = L R C LFE Lrs Rrs Lss Rss Ltf Rtf Ltr Rtr.
pub fn speakers(self) -> &'static [Speaker] {
use Speaker::*;
match self {
ChannelFormat::Mono => &[C],
ChannelFormat::Stereo => &[L, R],
ChannelFormat::Lcr => &[L, R, C],
ChannelFormat::Quad => &[L, R, Ls, Rs],
ChannelFormat::Lcrs => &[L, R, C, Cs],
ChannelFormat::Surround50 => &[L, R, C, Ls, Rs],
ChannelFormat::Surround51 => &[L, R, C, Lfe, Ls, Rs],
ChannelFormat::Surround60 => &[L, R, C, Ls, Rs, Cs],
ChannelFormat::Surround61 => &[L, R, C, Lfe, Ls, Rs, Cs],
ChannelFormat::Sdds70 => &[L, R, C, Ls, Rs, Lc, Rc],
ChannelFormat::Sdds71 => &[L, R, C, Lfe, Ls, Rs, Lc, Rc],
ChannelFormat::Surround70 => &[L, R, C, Lrs, Rrs, Lss, Rss],
ChannelFormat::Surround71 => &[L, R, C, Lfe, Lrs, Rrs, Lss, Rss],
ChannelFormat::Atmos702 => &[L, R, C, Lrs, Rrs, Lss, Rss, Ltm, Rtm],
ChannelFormat::Atmos712 => &[L, R, C, Lfe, Lrs, Rrs, Lss, Rss, Ltm, Rtm],
ChannelFormat::Atmos502 => &[L, R, C, Ls, Rs, Ltm, Rtm],
ChannelFormat::Atmos512 => &[L, R, C, Lfe, Ls, Rs, Ltm, Rtm],
ChannelFormat::Atmos504 => &[L, R, C, Ls, Rs, Ltf, Rtf, Ltr, Rtr],
ChannelFormat::Atmos514 => &[L, R, C, Lfe, Ls, Rs, Ltf, Rtf, Ltr, Rtr],
ChannelFormat::Atmos704 => &[L, R, C, Lrs, Rrs, Lss, Rss, Ltf, Rtf, Ltr, Rtr],
ChannelFormat::Atmos714 => &[L, R, C, Lfe, Lrs, Rrs, Lss, Rss, Ltf, Rtf, Ltr, Rtr],
ChannelFormat::Atmos706 => &[L, R, C, Lrs, Rrs, Lss, Rss, Ltf, Rtf, Ltr, Rtr, Ltm, Rtm],
ChannelFormat::Atmos716 => &[L, R, C, Lfe, Lrs, Rrs, Lss, Rss, Ltf, Rtf, Ltr, Rtr, Ltm, Rtm],
ChannelFormat::Atmos904 => &[L, R, C, Lrs, Rrs, Lw, Rw, Lss, Rss, Ltf, Rtf, Ltr, Rtr],
ChannelFormat::Atmos914 => &[L, R, C, Lfe, Lrs, Rrs, Lw, Rw, Lss, Rss, Ltf, Rtf, Ltr, Rtr],
ChannelFormat::Atmos906 => &[L, R, C, Lrs, Rrs, Lw, Rw, Lss, Rss, Ltf, Rtf, Ltr, Rtr, Ltm, Rtm],
ChannelFormat::Atmos916 => &[L, R, C, Lfe, Lrs, Rrs, Lw, Rw, Lss, Rss, Ltf, Rtf, Ltr, Rtr, Ltm, Rtm],
ChannelFormat::Ambisonics(_) => &[],
}
}
pub fn is_ambisonic(self) -> bool {
matches!(self, ChannelFormat::Ambisonics(_))
}
pub fn has_lfe(self) -> bool {
self.speakers().contains(&Speaker::Lfe)
}
pub fn has_height(self) -> bool {
self.speakers().iter().any(|s| s.is_height())
}
/// Short per-channel labels for meters (`W Y Z X 5…` for Ambisonics).
pub fn channel_label(self, ch: usize) -> String {
match self.speakers().get(ch) {
Some(s) => s.label().to_string(),
None if self.is_ambisonic() => ["W", "Y", "Z", "X"].get(ch).map_or_else(|| format!("{}", ch + 1), ToString::to_string),
None => format!("{}", ch + 1),
}
}
/// WAVE_FORMAT_EXTENSIBLE channel mask (0 = no positions, e.g. Ambisonics). Speakers that WAV
/// cannot name (top middle) borrow the top-front bits when the layout has no top fronts.
pub fn channel_mask(self) -> u32 {
let sp = self.speakers();
let has_tf = sp.contains(&Speaker::Ltf);
sp.iter().fold(0u32, |m, s| match s {
Speaker::Ltm if !has_tf => m | 0x1000,
Speaker::Rtm if !has_tf => m | 0x4000,
s => m | s.wave_bit(),
})
}
/// Best format for a channel count.
pub fn for_channels(n: usize) -> ChannelFormat {
[
ChannelFormat::Mono,
ChannelFormat::Stereo,
ChannelFormat::Lcr,
ChannelFormat::Quad,
ChannelFormat::Surround50,
ChannelFormat::Surround51,
ChannelFormat::Surround70,
ChannelFormat::Surround71,
]
.into_iter()
.find(|f| f.channels() == n)
.unwrap_or(if n <= 1 { ChannelFormat::Mono } else { ChannelFormat::Stereo })
}
}
/// A loudspeaker position in a channel format.
///
/// Angles follow ITU-R BS.775 / Dolby conventions: azimuth in degrees, 0 = front centre, positive
/// = to the right; elevation in degrees above the listener plane.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Speaker {
L,
R,
C,
Lfe,
/// 5.x surrounds (±110°).
Ls,
Rs,
/// SDDS inner fronts (±15°).
Lc,
Rc,
/// Centre surround (180°).
Cs,
/// 7.x side surrounds (±90°).
Lss,
Rss,
/// 7.x rear surrounds (±150°).
Lrs,
Rrs,
/// 9.x front wides (±60°).
Lw,
Rw,
/// Top front (±45°, elevation 45°).
Ltf,
Rtf,
/// Top middle (±90°, elevation 45°).
Ltm,
Rtm,
/// Top rear (±135°, elevation 45°).
Ltr,
Rtr,
}
impl Speaker {
pub fn azimuth(self) -> f32 {
match self {
Speaker::L => -30.0,
Speaker::R => 30.0,
Speaker::C | Speaker::Lfe => 0.0,
Speaker::Ls => -110.0,
Speaker::Rs => 110.0,
Speaker::Lc => -15.0,
Speaker::Rc => 15.0,
Speaker::Cs => 180.0,
Speaker::Lss => -90.0,
Speaker::Rss => 90.0,
Speaker::Lrs => -150.0,
Speaker::Rrs => 150.0,
Speaker::Lw => -60.0,
Speaker::Rw => 60.0,
Speaker::Ltf => -45.0,
Speaker::Rtf => 45.0,
Speaker::Ltm => -90.0,
Speaker::Rtm => 90.0,
Speaker::Ltr => -135.0,
Speaker::Rtr => 135.0,
}
}
pub fn elevation(self) -> f32 {
if self.is_height() { 45.0 } else { 0.0 }
}
pub fn is_height(self) -> bool {
matches!(self, Speaker::Ltf | Speaker::Rtf | Speaker::Ltm | Speaker::Rtm | Speaker::Ltr | Speaker::Rtr)
}
pub fn is_lfe(self) -> bool {
self == Speaker::Lfe
}
pub fn label(self) -> &'static str {
match self {
Speaker::L => "L",
Speaker::R => "R",
Speaker::C => "C",
Speaker::Lfe => "LFE",
Speaker::Ls => "Ls",
Speaker::Rs => "Rs",
Speaker::Lc => "Lc",
Speaker::Rc => "Rc",
Speaker::Cs => "Cs",
Speaker::Lss => "Lss",
Speaker::Rss => "Rss",
Speaker::Lrs => "Lrs",
Speaker::Rrs => "Rrs",
Speaker::Lw => "Lw",
Speaker::Rw => "Rw",
Speaker::Ltf => "Ltf",
Speaker::Rtf => "Rtf",
Speaker::Ltm => "Ltm",
Speaker::Rtm => "Rtm",
Speaker::Ltr => "Ltr",
Speaker::Rtr => "Rtr",
}
}
/// WAVE_FORMAT_EXTENSIBLE `dwChannelMask` bit (0 for speakers WAV cannot name).
pub fn wave_bit(self) -> u32 {
match self {
Speaker::L => 0x1,
Speaker::R => 0x2,
Speaker::C => 0x4,
Speaker::Lfe => 0x8,
Speaker::Ls | Speaker::Lrs => 0x10,
Speaker::Rs | Speaker::Rrs => 0x20,
Speaker::Lc | Speaker::Lw => 0x40,
Speaker::Rc | Speaker::Rw => 0x80,
Speaker::Cs => 0x100,
Speaker::Lss => 0x200,
Speaker::Rss => 0x400,
Speaker::Ltf => 0x1000,
Speaker::Rtf => 0x4000,
Speaker::Ltr => 0x8000,
Speaker::Rtr => 0x2_0000,
Speaker::Ltm | Speaker::Rtm => 0,
}
}
}
/// Surround panner position (Pro Tools-style X/Y puck). `None` on a mixer means "use the stereo
/// pan", which keeps sessions made before surround mixing sounding exactly as they did.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct SurroundPan {
/// -1 (left) ..= 1 (right).
pub x: f32,
/// -1 (back) ..= 1 (front).
pub y: f32,
/// Elevation 0 (ear level) ..= 1 (overhead), used by height formats.
pub z: f32,
/// 0 = point source ..= 1 = spread over every speaker.
pub divergence: f32,
/// Centre speaker share of front-centre images, 0..=100 % (0 = phantom centre on L/R).
pub center: f32,
/// LFE send level, dB (-144 = off).
pub lfe_db: f32,
}
impl Default for SurroundPan {
fn default() -> Self {
SurroundPan { x: 0.0, y: 1.0, z: 0.0, divergence: 0.0, center: 100.0, lfe_db: -144.0 }
}
}
impl SurroundPan {
/// Puck at the stereo pan position (front edge).
pub fn from_stereo(pan: f32) -> Self {
SurroundPan { x: finite_or(pan, 0.0).clamp(-1.0, 1.0), ..SurroundPan::default() }
}
/// Clamp into range (NaN → defaults).
pub fn sanitize(&mut self) {
let d = SurroundPan::default();
self.x = finite_or(self.x, d.x).clamp(-1.0, 1.0);
self.y = finite_or(self.y, d.y).clamp(-1.0, 1.0);
self.z = finite_or(self.z, d.z).clamp(0.0, 1.0);
self.divergence = finite_or(self.divergence, d.divergence).clamp(0.0, 1.0);
self.center = finite_or(self.center, d.center).clamp(0.0, 100.0);
self.lfe_db = finite_or(self.lfe_db, d.lfe_db).clamp(-144.0, 12.0);
}
}
/// An internal mix bus (Pro Tools "bus" paths).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Bus {
pub id: BusId,
pub name: String,
pub format: ChannelFormat,
}
/// Physical output paths (from the I/O setup).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct OutputPath {
pub name: String,
/// First hardware channel (0-based).
pub first_channel: u16,
pub format: ChannelFormat,
}
/// Where a signal goes or comes from.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum Route {
#[default]
None,
/// The main output (hardware outputs 1-2, or the bounce source).
Main,
Bus(BusId),
/// Hardware input/output by path name.
Hardware(String),
}
/// A plugin instance on an insert slot.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Insert {
/// Registry id from `soundcraft-dsp` (e.g. `eq7`, `comp`).
pub plugin: String,
#[serde(default, deserialize_with = "finite_params")]
pub params: BTreeMap<String, f32>,
#[serde(default)]
pub bypass: bool,
#[serde(default = "yes")]
pub active: bool,
/// Preset name shown in the plugin window header.
#[serde(default)]
pub preset: String,
/// Opaque plugin state (third-party plugins: CLAP state / VST3 component + controller
/// state), standard base64. Restored into a new instance before it first processes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
/// The session audio source a sample-playing instrument (the built-in Sampler) plays.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sample: Option<SourceId>,
}
fn yes() -> bool {
true
}
impl Insert {
pub fn new(plugin: impl Into<String>) -> Self {
Insert {
plugin: plugin.into(),
params: BTreeMap::new(),
bypass: false,
active: true,
preset: String::from("<factory default>"),
state: None,
sample: None,
}
}
/// The decoded plugin state (`None` when absent or malformed).
pub fn state_bytes(&self) -> Option<Vec<u8>> {
self.state.as_deref().and_then(crate::b64::decode)
}
/// Stores a plugin state blob (base64-encoded); an empty blob clears it.
pub fn set_state_bytes(&mut self, data: &[u8]) {
self.state = (!data.is_empty()).then(|| crate::b64::encode(data));
}
}
/// A send to a bus.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SendSlot {
pub target: Route,
pub level_db: f32,
pub pan: f32,
pub mute: bool,
pub pre_fader: bool,
#[serde(default = "yes")]
pub follow_main_pan: bool,
/// Surround position into a multichannel bus (None = follow the track / stereo pan).
#[serde(default)]
pub surround: Option<SurroundPan>,
}
impl SendSlot {
pub fn new(target: Route) -> Self {
SendSlot { target, level_db: -144.0, pan: 0.0, mute: false, pre_fader: false, follow_main_pan: true, surround: None }
}
}
/// The channel strip.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Mixer {
pub volume_db: f32,
/// One panner per source channel for mono/stereo (stereo tracks: two panners, default hard L/R).
pub pan: Vec<f32>,
pub mute: bool,
pub solo: bool,
#[serde(default)]
pub solo_safe: bool,
/// Live record-enable state. Runtime-only: opening a session must never arm an input.
#[serde(skip)]
pub record_arm: bool,
/// Live input-monitor state. Runtime-only: opening a session must never enable monitoring.
#[serde(skip)]
pub input_monitor: bool,
#[serde(default)]
pub phase_invert: bool,
pub input: Route,
pub output: Route,
pub inserts: Vec<Option<Insert>>,
pub sends: Vec<Option<SendSlot>>,
pub automation_mode: AutomationMode,
/// Input gain / trim, dB.
#[serde(default)]
pub trim_db: f32,
/// VCA master that controls this track, if any (track id of the VCA).
#[serde(default)]
pub vca: Option<u64>,
/// Surround panner, used when the output is multichannel (None = the stereo pan to L/R).
#[serde(default)]
pub surround: Option<SurroundPan>,
}
impl Mixer {
pub fn new(format: ChannelFormat) -> Self {
let pan = match format {
ChannelFormat::Mono => vec![0.0],
ChannelFormat::Stereo => vec![-1.0, 1.0],
_ => Vec::new(),
};
Mixer {
volume_db: 0.0,
pan,
mute: false,
solo: false,
solo_safe: false,
record_arm: false,
input_monitor: false,
phase_invert: false,
input: Route::None,
output: Route::Main,
inserts: vec![None; INSERT_SLOTS],
sends: vec![None; SEND_SLOTS],
automation_mode: AutomationMode::Read,
trim_db: 0.0,
vca: None,
surround: None,
}
}
/// Clamp everything into range (after deserialising untrusted files).
pub fn sanitize(&mut self) {
self.volume_db = finite_or(self.volume_db, 0.0).clamp(-144.0, 12.0);
for p in &mut self.pan {
*p = finite_or(*p, 0.0).clamp(-1.0, 1.0);
}
self.inserts.resize(INSERT_SLOTS, None);
self.sends.resize(SEND_SLOTS, None);
for s in self.sends.iter_mut().flatten() {
s.level_db = finite_or(s.level_db, -144.0).clamp(-144.0, 12.0);
s.pan = finite_or(s.pan, 0.0).clamp(-1.0, 1.0);
if let Some(sp) = &mut s.surround {
sp.sanitize();
}
}
if let Some(sp) = &mut self.surround {
sp.sanitize();
}
self.trim_db = finite_or(self.trim_db, 0.0).clamp(-144.0, 24.0);
}
}
impl crate::Session {
/// The main mix format: the format of the first (main) output path, at least stereo and at
/// most 16 channels (wider formats fall back to stereo).
pub fn main_format(&self) -> ChannelFormat {
match self.outputs.first().map(|o| o.format) {
Some(f) if (2..=16).contains(&f.channels()) => f,
_ => ChannelFormat::Stereo,
}
}
}
pub(crate) fn finite_or(v: f32, d: f32) -> f32 {
if v.is_finite() { v } else { d }
}
/// Parameters saved as `null` (how JSON writes NaN and infinity) or beyond `f32` are dropped, so
/// they keep their defaults instead of failing the whole session.
fn finite_params<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, f32>, D::Error> {
let params: BTreeMap<String, Option<f64>> = serde::Deserialize::deserialize(d)?;
Ok(params.into_iter().filter_map(|(k, v)| Some((k, v.map(|v| v as f32).filter(|v| v.is_finite())?))).collect())
}
/// Fader taper used by Pro Tools-style faders: position 0..1 ↔ dB (-inf..+12).
pub fn fader_pos_to_db(pos: f32) -> f32 {
let p = finite_or(pos, 0.0).clamp(0.0, 1.0);
if p <= 0.0 {
return -144.0;
}
// Piecewise: top 75 % covers -24..+12 linearly-ish, the bottom compresses to -inf.
if p >= 0.25 { -24.0 + (p - 0.25) / 0.75 * 36.0 } else { -24.0 - (1.0 - p / 0.25).powf(1.5) * 120.0 }
}
pub fn fader_db_to_pos(db: f32) -> f32 {
let db = finite_or(db, -144.0);
if db <= -144.0 {
return 0.0;
}
if db >= -24.0 {
(0.25 + (db.min(12.0) + 24.0) / 36.0 * 0.75).min(1.0)
} else {
let x = ((-24.0 - db) / 120.0).clamp(0.0, 1.0).powf(1.0 / 1.5);
((1.0 - x) * 0.25).max(0.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_state_round_trips_through_json() {
let mut i = Insert::new("vst3:00");
assert_eq!(i.state_bytes(), None);
let blob: Vec<u8> = (0..=255u8).cycle().take(1000).collect();
i.set_state_bytes(&blob);
let json = serde_json::to_string(&i).unwrap();
let back: Insert = serde_json::from_str(&json).unwrap();
assert_eq!(back.state_bytes().unwrap(), blob);
i.set_state_bytes(&[]);
assert_eq!(i.state, None);
// Old sessions have no `state`; stateless inserts don't write one.
let old: Insert = serde_json::from_str(r#"{"plugin":"eq_7band"}"#).unwrap();
assert_eq!(old.state, None);
assert!(!serde_json::to_string(&old).unwrap().contains("state"));
// A hostile state string decodes to nothing rather than failing the load.
let bad: Insert = serde_json::from_str(r#"{"plugin":"x","state":"!!!"}"#).unwrap();
assert_eq!(bad.state_bytes(), None);
}
#[test]
fn params_saved_as_null_or_out_of_range_are_dropped() {
let mut i = Insert::new("eq_7band");
i.params.extend([("gain".to_string(), f32::NAN), ("q".to_string(), 0.7)]);
let back: Insert = serde_json::from_str(&serde_json::to_string(&i).unwrap()).unwrap();
assert_eq!(back.params, BTreeMap::from([("q".to_string(), 0.7)]));
let big: Insert = serde_json::from_str(r#"{"plugin":"x","params":{"gain":1e39,"q":0.5}}"#).unwrap();
assert_eq!(big.params, BTreeMap::from([("q".to_string(), 0.5)]));
}
#[test]
fn fader_taper_round_trips() {
for db in [-100.0f32, -60.0, -24.0, -10.0, 0.0, 6.0, 12.0] {
let p = fader_db_to_pos(db);
assert!((fader_pos_to_db(p) - db).abs() < 0.05, "{db} → {p}");
}
assert_eq!(fader_pos_to_db(0.0), -144.0);
assert_eq!(fader_db_to_pos(f32::NAN), 0.0);
}
#[test]
fn mixer_defaults_and_sanitize() {
let mut m = Mixer::new(ChannelFormat::Stereo);
assert_eq!(m.pan, vec![-1.0, 1.0]);
m.volume_db = f32::INFINITY;
m.inserts.truncate(2);
m.sanitize();
assert_eq!(m.volume_db, 0.0);
assert_eq!(m.inserts.len(), INSERT_SLOTS);
}
#[test]
fn speaker_layouts_match_channel_counts_and_masks() {
for f in ChannelFormat::ALL {
if !f.is_ambisonic() {
assert_eq!(f.speakers().len(), f.channels(), "{f:?}");
// Mask bits are unique and in ascending channel order.
let bits: Vec<u32> = f.speakers().iter().map(|s| s.wave_bit()).filter(|b| *b != 0).collect();
assert!(bits.windows(2).all(|w| w[0] < w[1]), "{f:?} not in WAV order");
}
}
assert_eq!(ChannelFormat::Surround51.channel_mask(), 0x3F);
assert_eq!(ChannelFormat::Surround71.channel_mask(), 0x63F);
assert_eq!(ChannelFormat::Atmos714.channel_mask(), 0x2_D63F);
assert_eq!(ChannelFormat::Ambisonics(1).channel_mask(), 0);
}
#[test]
fn surround_pan_defaults_and_old_sessions() {
let m = Mixer::new(ChannelFormat::Mono);
assert_eq!(m.surround, None);
// A mixer saved before surround existed still loads.
let mut v = serde_json::to_value(&m).unwrap();
v.as_object_mut().unwrap().remove("surround");
let back: Mixer = serde_json::from_value(v).unwrap();
assert_eq!(back.surround, None);
let mut sp: SurroundPan = serde_json::from_str(r#"{"x": 5.0}"#).unwrap();
sp.sanitize();
assert_eq!(sp.x, 1.0);
assert_eq!(sp.center, 100.0);
}
#[test]
fn formats() {
assert_eq!(ChannelFormat::for_channels(6), ChannelFormat::Surround51);
assert_eq!(ChannelFormat::from_id("stereo"), Some(ChannelFormat::Stereo));
}
}
File diff suppressed because it is too large Load Diff
+204
View File
@@ -0,0 +1,204 @@
//! Audio sources (files in the session's Audio Files folder) and their decoded data, and the
//! movies video clips reference.
use crate::SourceId;
use craft_audio::{AudioBuffer, AudioInfo, CodecId, Container, peaks::Peaks};
use std::collections::BTreeMap;
use std::sync::Arc;
/// The kind of file a source came from, as session files store it in [`Source::format`]. The
/// variant names are part of the session format: craft-audio's `Container` and `CodecId` name
/// more formats under other names, so this stays here and maps from them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum FileFormat {
Wav,
Aiff,
Flac,
Mp3,
Ogg,
Aac,
Alac,
Caf,
/// Anything else that decodes: Matroska, WebM, raw AC-3.
Other,
}
impl FileFormat {
/// The kind of the file `info` describes.
pub fn of(info: &AudioInfo) -> FileFormat {
match info.container {
Container::Wav => FileFormat::Wav,
Container::Aiff => FileFormat::Aiff,
Container::Flac => FileFormat::Flac,
Container::MpegAudio => FileFormat::Mp3,
Container::Ogg => FileFormat::Ogg,
Container::Caf => FileFormat::Caf,
Container::Adts => FileFormat::Aac,
// MP4 and QuickTime hold many codecs: the codec names the kind.
Container::Mp4 | Container::QuickTime => match info.codec {
CodecId::Alac => FileFormat::Alac,
CodecId::Aac | CodecId::HeAac => FileFormat::Aac,
_ => FileFormat::Other,
},
_ => FileFormat::Other,
}
}
}
/// Metadata for an audio file used by the session (serialised).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Source {
pub id: SourceId,
pub name: String,
/// Path relative to the session folder (or absolute for referenced media).
pub path: String,
pub channels: u16,
pub frames: u64,
pub sample_rate: u32,
pub format: FileFormat,
/// Original BWF time stamp (samples), if any.
#[serde(default)]
pub time_reference: u64,
/// True when the file has not been written to disk yet (recorded/rendered this session).
#[serde(default)]
pub unsaved: bool,
}
/// A movie used by Video track clips (serialised). The pictures themselves are never stored in
/// the session: the UI opens the movie from `path` and decodes frames on demand.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct VideoSource {
pub id: SourceId,
pub name: String,
/// Absolute path of the movie (referenced, never copied into the session folder).
pub path: String,
#[serde(default)]
pub width: u32,
#[serde(default)]
pub height: u32,
/// Frames per second (0 = unknown).
#[serde(default)]
pub frame_rate: f64,
/// Picture length in seconds.
#[serde(default)]
pub duration: f64,
/// Codec id (`h264`, `prores`, `mjpeg`, `hevc`, …).
#[serde(default)]
pub codec: String,
/// Why the movie is not opened, when its stored path was refused on opening the session.
#[serde(skip)]
pub offline: Option<String>,
}
impl VideoSource {
/// Display aspect ratio (width / height), 16:9 when unknown.
pub fn aspect(&self) -> f64 {
if self.width == 0 || self.height == 0 { 16.0 / 9.0 } else { f64::from(self.width) / f64::from(self.height) }
}
}
/// Decoded audio plus waveform overviews (not serialised).
#[derive(Debug)]
pub struct SourceAudio {
pub buffer: AudioBuffer,
pub peaks: Vec<Peaks>,
}
impl SourceAudio {
pub fn new(buffer: AudioBuffer) -> Self {
let peaks = buffer.channels.iter().map(|c| Peaks::build(c)).collect();
SourceAudio { buffer, peaks }
}
pub fn frames(&self) -> usize {
self.buffer.frames()
}
pub fn channel(&self, ch: usize) -> Option<&[f32]> {
self.buffer.channels.get(ch).map(Vec::as_slice)
}
}
/// Shared decoded audio, keyed by source id.
#[derive(Debug, Clone, Default)]
pub struct SourcePool {
map: BTreeMap<SourceId, Arc<SourceAudio>>,
}
impl SourcePool {
pub fn insert(&mut self, id: SourceId, audio: Arc<SourceAudio>) {
self.map.insert(id, audio);
}
pub fn get(&self, id: SourceId) -> Option<&Arc<SourceAudio>> {
self.map.get(&id)
}
pub fn remove(&mut self, id: SourceId) -> Option<Arc<SourceAudio>> {
self.map.remove(&id)
}
pub fn contains(&self, id: SourceId) -> bool {
self.map.contains_key(&id)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn ids(&self) -> impl Iterator<Item = SourceId> + '_ {
self.map.keys().copied()
}
}
impl PartialEq for SourcePool {
fn eq(&self, other: &Self) -> bool {
self.map.len() == other.map.len() && self.map.iter().zip(other.map.iter()).all(|((a, x), (b, y))| a == b && Arc::ptr_eq(x, y))
}
}
#[cfg(test)]
mod tests {
use super::FileFormat;
use craft_audio::{AudioBuffer, EncodeFormat, EncodeOptions, encode, probe};
/// Sessions written before the format code moved to craft-audio name a source's format with
/// these words; they must keep reading, and new sessions must keep writing them.
#[test]
fn the_format_names_in_session_files_do_not_change() {
use FileFormat::{Aac, Aiff, Alac, Caf, Flac, Mp3, Ogg, Other, Wav};
let names = ["Wav", "Aiff", "Flac", "Mp3", "Ogg", "Aac", "Alac", "Caf", "Other"];
for (format, name) in [Wav, Aiff, Flac, Mp3, Ogg, Aac, Alac, Caf, Other].into_iter().zip(names) {
assert_eq!(serde_json::to_string(&format).unwrap(), format!("\"{name}\""));
assert_eq!(serde_json::from_str::<FileFormat>(&format!("\"{name}\"")).unwrap(), format);
}
}
/// An MP4 is AAC only when its audio is: Opus, AC-3 or PCM in MP4 is not.
#[test]
fn an_mp4_is_named_by_its_codec() {
let wav = encode(&AudioBuffer::new(48_000, 1, 480), &EncodeOptions::default()).unwrap();
let mut info = serde_json::to_value(probe(&wav, None).unwrap()).unwrap();
for (container, codec, format) in [
("Mp4", "Aac", FileFormat::Aac),
("Mp4", "HeAac", FileFormat::Aac),
("QuickTime", "Alac", FileFormat::Alac),
("Mp4", "Opus", FileFormat::Other),
("Mp4", "Ac3", FileFormat::Other),
("QuickTime", "Pcm", FileFormat::Other),
("Adts", "Aac", FileFormat::Aac),
] {
info["container"] = container.into();
info["codec"] = codec.into();
let info: craft_audio::AudioInfo = serde_json::from_value(info.clone()).unwrap();
assert_eq!(FileFormat::of(&info), format, "{codec} in {container}");
}
}
#[test]
fn a_probed_file_maps_to_its_format() {
let buf = AudioBuffer::new(48_000, 1, 480);
for (written, format) in
[(EncodeFormat::Wav, FileFormat::Wav), (EncodeFormat::Aiff, FileFormat::Aiff), (EncodeFormat::Flac, FileFormat::Flac)]
{
let info = probe(&encode(&buf, &EncodeOptions::new(written)).unwrap(), None).unwrap();
assert_eq!(FileFormat::of(&info), format);
}
}
}
+477
View File
@@ -0,0 +1,477 @@
//! Tracks and playlists.
use crate::{AutoParam, AutomationLane, ChannelFormat, Clip, ClipId, Mixer, TrackId};
use soundcraft_time::{Range, Samples};
/// Track types (Track › New).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum TrackKind {
#[default]
Audio,
Aux,
Master,
Midi,
Instrument,
Vca,
Folder,
/// Picture: clips reference a movie ([`crate::VideoSource`]); no audio path.
Video,
}
impl TrackKind {
pub const ALL: [TrackKind; 8] = [
TrackKind::Audio,
TrackKind::Aux,
TrackKind::Master,
TrackKind::Midi,
TrackKind::Instrument,
TrackKind::Vca,
TrackKind::Folder,
TrackKind::Video,
];
pub fn label(self) -> &'static str {
match self {
TrackKind::Audio => "Audio Track",
TrackKind::Aux => "Aux Input",
TrackKind::Master => "Master Fader",
TrackKind::Midi => "MIDI Track",
TrackKind::Instrument => "Instrument Track",
TrackKind::Vca => "VCA Master",
TrackKind::Folder => "Routing Folder Track",
TrackKind::Video => "Video Track",
}
}
pub fn default_name(self) -> &'static str {
match self {
TrackKind::Audio => "Audio",
TrackKind::Aux => "Aux",
TrackKind::Master => "Master",
TrackKind::Midi => "MIDI",
TrackKind::Instrument => "Inst",
TrackKind::Vca => "VCA",
TrackKind::Folder => "Folder",
TrackKind::Video => "Video",
}
}
pub fn id(self) -> &'static str {
match self {
TrackKind::Audio => "audio",
TrackKind::Aux => "aux",
TrackKind::Master => "master",
TrackKind::Midi => "midi",
TrackKind::Instrument => "instrument",
TrackKind::Vca => "vca",
TrackKind::Folder => "folder",
TrackKind::Video => "video",
}
}
pub fn from_id(s: &str) -> Option<TrackKind> {
let s = s.to_ascii_lowercase();
TrackKind::ALL.into_iter().find(|k| k.id() == s || k.label().eq_ignore_ascii_case(&s))
}
/// Track kinds that hold clips on a timeline.
pub fn has_playlist(self) -> bool {
matches!(self, TrackKind::Audio | TrackKind::Midi | TrackKind::Instrument | TrackKind::Video)
}
pub fn is_midi(self) -> bool {
matches!(self, TrackKind::Midi | TrackKind::Instrument)
}
/// Kinds that pass audio through the mixer.
pub fn is_audio_path(self) -> bool {
matches!(self, TrackKind::Audio | TrackKind::Aux | TrackKind::Master | TrackKind::Instrument | TrackKind::Folder)
}
}
/// Track heights (View › Track Height presets).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize)]
pub enum TrackHeight {
/// Any height from Micro to Extreme, in points.
Custom(u16),
Micro,
Mini,
Small,
#[default]
Medium,
Large,
Jumbo,
Extreme,
/// Fit To Window: this many points.
Fit(u16),
}
/// A saved track height: `"Micro"` … `"Extreme"` (or `{"Micro": null}` …), `{"Custom": points}`,
/// `{"Fit": points}`, or the bare `"Fit"` older sessions used. Read as it comes, never buffered (as an
/// untagged enum would), so anything else in a session file is refused at its first token.
impl<'de> serde::Deserialize<'de> for TrackHeight {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
d.deserialize_any(HeightVisitor)
}
}
const HEIGHT_VARIANTS: &[&str] = &["Custom", "Micro", "Mini", "Small", "Medium", "Large", "Jumbo", "Extreme", "Fit"];
struct HeightVisitor;
impl HeightVisitor {
/// The height a variant without a size names.
fn preset(name: &str) -> Option<TrackHeight> {
Some(match name {
"Micro" => TrackHeight::Micro,
"Mini" => TrackHeight::Mini,
"Small" => TrackHeight::Small,
"Medium" => TrackHeight::Medium,
"Large" => TrackHeight::Large,
"Jumbo" => TrackHeight::Jumbo,
"Extreme" => TrackHeight::Extreme,
_ => return None,
})
}
}
impl<'de> serde::de::Visitor<'de> for HeightVisitor {
type Value = TrackHeight;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a track height")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<TrackHeight, E> {
match v {
// Older sessions stored Fit with no size, drawn 88 points tall: the default Medium height.
"Fit" => Ok(TrackHeight::Medium),
"Custom" => Err(E::invalid_type(serde::de::Unexpected::UnitVariant, &"a height in points")),
other => Self::preset(other).ok_or_else(|| E::unknown_variant(other, HEIGHT_VARIANTS)),
}
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<TrackHeight, A::Error> {
use serde::de::Error as _;
let Some(key) = map.next_key::<String>()? else { return Err(A::Error::invalid_length(0, &"one variant")) };
let h = match key.as_str() {
"Custom" => TrackHeight::Custom(map.next_value()?),
// `{"Fit": null}` is the old size-less Fit too, as above.
"Fit" => map.next_value::<Option<u16>>()?.map_or(TrackHeight::Medium, TrackHeight::Fit),
other => {
let h = Self::preset(other).ok_or_else(|| A::Error::unknown_variant(other, HEIGHT_VARIANTS))?;
map.next_value::<()>()?;
h
}
};
if map.next_key::<serde::de::IgnoredAny>()?.is_some() {
return Err(A::Error::invalid_length(2, &"one variant"));
}
Ok(h)
}
}
impl TrackHeight {
pub const ALL: [TrackHeight; 7] = [
TrackHeight::Micro,
TrackHeight::Mini,
TrackHeight::Small,
TrackHeight::Medium,
TrackHeight::Large,
TrackHeight::Jumbo,
TrackHeight::Extreme,
];
pub fn points(self) -> f32 {
match self {
TrackHeight::Custom(points) => f32::from(points).clamp(TrackHeight::Micro.points(), TrackHeight::Extreme.points()),
TrackHeight::Micro => 16.0,
TrackHeight::Mini => 24.0,
TrackHeight::Small => 46.0,
TrackHeight::Medium => 88.0,
TrackHeight::Large => 132.0,
TrackHeight::Jumbo => 220.0,
TrackHeight::Extreme => 440.0,
TrackHeight::Fit(points) => f32::from(points.max(16)),
}
}
pub fn label(self) -> &'static str {
match self {
TrackHeight::Custom(_) => "custom",
TrackHeight::Micro => "micro",
TrackHeight::Mini => "mini",
TrackHeight::Small => "small",
TrackHeight::Medium => "medium",
TrackHeight::Large => "large",
TrackHeight::Jumbo => "jumbo",
TrackHeight::Extreme => "extreme",
TrackHeight::Fit(_) => "fit to window",
}
}
pub fn from_id(s: &str) -> Option<TrackHeight> {
TrackHeight::ALL.into_iter().find(|h| h.label().eq_ignore_ascii_case(s))
}
/// The preset this many points tall, else a custom height clamped to Micro..Extreme.
pub fn from_points(points: f32) -> TrackHeight {
let p = points.max(TrackHeight::Micro.points()).min(TrackHeight::Extreme.points()).round() as u16;
TrackHeight::ALL.into_iter().find(|h| h.points() == f32::from(p)).unwrap_or(TrackHeight::Custom(p))
}
/// The next preset taller (or shorter) than this height; Extreme (or Micro) stays.
pub fn step(self, taller: bool) -> TrackHeight {
let p = self.points();
let next =
if taller { TrackHeight::ALL.into_iter().find(|h| h.points() > p) } else { TrackHeight::ALL.into_iter().rev().find(|h| h.points() < p) };
next.unwrap_or(self)
}
}
/// The default track colour palette (original, chosen for SoundCraft).
pub const TRACK_COLORS: [[u8; 3]; 16] = [
[86, 132, 214],
[94, 170, 214],
[80, 190, 168],
[104, 186, 98],
[168, 196, 76],
[222, 196, 72],
[230, 152, 62],
[222, 104, 72],
[214, 82, 110],
[196, 86, 168],
[150, 98, 206],
[110, 104, 214],
[130, 150, 170],
[178, 140, 110],
[120, 170, 140],
[190, 120, 150],
];
/// A playlist: an alternative take of a track's clips.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct Playlist {
pub name: String,
/// Clips sorted by start; non-overlapping except at crossfades.
pub clips: Vec<Clip>,
}
impl Playlist {
pub fn new(name: impl Into<String>) -> Self {
Playlist { name: name.into(), clips: Vec::new() }
}
pub fn sort(&mut self) {
self.clips.sort_by_key(|c| (c.start, c.id.0));
}
pub fn clip(&self, id: ClipId) -> Option<&Clip> {
self.clips.iter().find(|c| c.id == id)
}
pub fn clip_mut(&mut self, id: ClipId) -> Option<&mut Clip> {
self.clips.iter_mut().find(|c| c.id == id)
}
pub fn clips_in(&self, r: Range) -> impl Iterator<Item = &Clip> {
self.clips.iter().filter(move |c| c.range().overlaps(&r))
}
pub fn clip_at(&self, at: Samples) -> Option<&Clip> {
self.clips.iter().rev().find(|c| c.range().contains(at))
}
pub fn end(&self) -> Samples {
self.clips.iter().map(Clip::end).max().unwrap_or(0)
}
}
/// A track.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Track {
pub id: TrackId,
pub name: String,
pub kind: TrackKind,
pub format: ChannelFormat,
pub color: [u8; 3],
pub height: TrackHeight,
pub playlists: Vec<Playlist>,
pub active_playlist: usize,
pub mixer: Mixer,
pub automation: Vec<AutomationLane>,
/// Which lane the track shows: `waveform`/`blocks`/`notes`/`regions` or an automation param id.
pub view: String,
#[serde(default)]
pub hidden: bool,
#[serde(default)]
pub inactive: bool,
#[serde(default)]
pub frozen: bool,
#[serde(default)]
pub comments: String,
/// Folder that contains this track.
#[serde(default)]
pub folder: Option<TrackId>,
#[serde(default = "yes")]
pub folder_open: bool,
/// Instrument plugin (instrument tracks) — registry id.
#[serde(default)]
pub instrument: Option<crate::Insert>,
/// Ticks (musical) or samples timebase for clips.
#[serde(default)]
pub ticks_timebase: bool,
/// Elastic Audio algorithm, if enabled.
#[serde(default)]
pub elastic: Option<String>,
/// Pinned to top in the Edit window.
#[serde(default)]
pub pinned: bool,
}
fn yes() -> bool {
true
}
impl Track {
pub fn new(id: TrackId, name: impl Into<String>, kind: TrackKind, format: ChannelFormat, color: [u8; 3]) -> Self {
let name = name.into();
let format = if kind.is_midi() && kind == TrackKind::Midi { ChannelFormat::Mono } else { format };
let view = if kind.is_midi() {
"notes"
} else if kind.has_playlist() {
"waveform"
} else {
"volume"
};
Track {
id,
playlists: vec![Playlist::new(name.clone())],
name,
kind,
format,
color,
height: TrackHeight::Medium,
active_playlist: 0,
mixer: Mixer::new(format),
automation: Vec::new(),
view: view.into(),
hidden: false,
inactive: false,
frozen: false,
comments: String::new(),
folder: None,
folder_open: true,
instrument: None,
ticks_timebase: kind.is_midi(),
elastic: None,
pinned: false,
}
}
pub fn channels(&self) -> usize {
self.format.channels()
}
pub fn playlist(&self) -> Option<&Playlist> {
self.playlists.get(self.active_playlist)
}
pub fn playlist_mut(&mut self) -> Option<&mut Playlist> {
self.playlists.get_mut(self.active_playlist)
}
pub fn clips(&self) -> &[Clip] {
self.playlist().map_or(&[], |p| p.clips.as_slice())
}
pub fn lane(&self, p: &AutoParam) -> Option<&AutomationLane> {
self.automation.iter().find(|l| &l.param == p)
}
pub fn lane_mut(&mut self, p: &AutoParam) -> &mut AutomationLane {
let idx = match self.automation.iter().position(|l| &l.param == p) {
Some(i) => i,
None => {
self.automation.push(AutomationLane::new(p.clone()));
self.automation.len() - 1
}
};
let len = self.automation.len();
// `idx` is in range: it came from `position` or is the index of the element just pushed.
&mut self.automation[idx.min(len - 1)]
}
pub fn is_folder(&self) -> bool {
self.kind == TrackKind::Folder
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_fit_string_loads_as_default_height() {
assert_eq!(serde_json::from_str::<TrackHeight>("\"Fit\"").unwrap(), TrackHeight::Medium);
assert_eq!(serde_json::from_str::<TrackHeight>("{\"Fit\":120}").unwrap(), TrackHeight::Fit(120));
assert_eq!(serde_json::to_string(&TrackHeight::Fit(120)).unwrap(), "{\"Fit\":120}");
assert_eq!(serde_json::from_str::<TrackHeight>("\"Large\"").unwrap(), TrackHeight::Large);
assert_eq!(serde_json::from_str::<TrackHeight>("{\"Custom\":50}").unwrap(), TrackHeight::Custom(50));
}
#[test]
fn every_saved_height_form_loads_and_nothing_else() {
for h in TrackHeight::ALL.into_iter().chain([TrackHeight::Custom(50), TrackHeight::Fit(120)]) {
assert_eq!(serde_json::from_str::<TrackHeight>(&serde_json::to_string(&h).unwrap()).unwrap(), h);
assert_eq!(serde_json::from_value::<TrackHeight>(serde_json::to_value(h).unwrap()).unwrap(), h);
}
for h in TrackHeight::ALL {
let null = format!("{{{}:null}}", serde_json::to_string(&h).unwrap());
assert_eq!(serde_json::from_str::<TrackHeight>(&null).unwrap(), h, "{null}");
}
assert_eq!(serde_json::from_str::<TrackHeight>(r#"{"Fit":null}"#).unwrap(), TrackHeight::Medium);
assert!(serde_json::from_str::<TrackHeight>(r#"{"Custom":null}"#).is_err());
for bad in
[r#""Custom""#, r#""Huge""#, "7", "[]", "null", "{}", r#"{"Fit":"x"}"#, r#"{"Fit":70000}"#, r#"{"Large":1}"#, r#"{"Fit":1,"Fit":2}"#]
{
assert!(serde_json::from_str::<TrackHeight>(bad).is_err(), "{bad}");
}
}
#[test]
fn a_huge_height_is_refused_at_its_first_token() {
// #892: the height was read through an untagged enum, which buffers the whole value
// first; a session could hold a huge array there. It is refused where it starts.
for (open, rest) in [("[", "0,".repeat(100_000) + "0]"), (r#"{"Fit":["#, "0,".repeat(100_000) + "0]}")] {
let text = format!("{open}{rest}");
let err = serde_json::from_str::<TrackHeight>(&text).unwrap_err();
assert!(err.is_data() && err.line() == 1 && err.column() <= open.len() + 1, "{open}: {err}");
}
}
#[test]
fn new_track_defaults() {
let t = Track::new(TrackId(1), "Gtr", TrackKind::Audio, ChannelFormat::Stereo, TRACK_COLORS[0]);
assert_eq!(t.channels(), 2);
assert_eq!(t.view, "waveform");
assert_eq!(t.playlists.len(), 1);
let m = Track::new(TrackId(2), "Keys", TrackKind::Midi, ChannelFormat::Stereo, TRACK_COLORS[0]);
assert_eq!(m.format, ChannelFormat::Mono);
assert_eq!(m.view, "notes");
}
#[test]
fn lane_mut_creates_once() {
let mut t = Track::new(TrackId(1), "Gtr", TrackKind::Audio, ChannelFormat::Mono, TRACK_COLORS[0]);
t.lane_mut(&AutoParam::Volume).set_point(0, -3.0);
t.lane_mut(&AutoParam::Volume).set_point(10, -6.0);
assert_eq!(t.automation.len(), 1);
assert_eq!(t.lane(&AutoParam::Volume).map(|l| l.points.len()), Some(2));
}
#[test]
fn kind_ids() {
for k in TrackKind::ALL {
assert_eq!(TrackKind::from_id(k.id()), Some(k));
}
}
#[test]
fn custom_heights_round_to_presets_and_step_through_them() {
assert_eq!(TrackHeight::from_points(88.0), TrackHeight::Medium);
assert_eq!(TrackHeight::from_points(57.4), TrackHeight::Custom(57));
assert_eq!(TrackHeight::from_points(9999.0), TrackHeight::Extreme);
assert_eq!(TrackHeight::from_points(f32::NAN), TrackHeight::Micro);
assert_eq!(TrackHeight::Custom(u16::MAX).points(), 440.0);
assert_eq!(TrackHeight::Custom(57).step(true), TrackHeight::Medium);
assert_eq!(TrackHeight::Custom(57).step(false), TrackHeight::Small);
assert_eq!(TrackHeight::Extreme.step(true), TrackHeight::Extreme);
assert_eq!(TrackHeight::Micro.step(false), TrackHeight::Micro);
let json = serde_json::to_string(&TrackHeight::Custom(57)).unwrap();
assert_eq!(serde_json::from_str::<TrackHeight>(&json).unwrap(), TrackHeight::Custom(57));
assert_eq!(serde_json::from_str::<TrackHeight>("\"Large\"").unwrap(), TrackHeight::Large);
}
}
+7 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "soundcraft-time"
description = "Compatibility facade for SoundCraft's shared sample-index time API"
description = "SoundCraft timebases: samples, Bars|Beats, Min:Secs, Timecode, Feet+Frames, tempo and meter maps, grid"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,7 +8,12 @@ rust-version.workspace = true
repository.workspace = true
[dependencies]
craft-time.workspace = true
serde.workspace = true
thiserror.workspace = true
[dev-dependencies]
proptest.workspace = true
serde_json.workspace = true
[lints]
workspace = true
+241
View File
@@ -0,0 +1,241 @@
//! Formatting and parsing positions in the five timebases.
use crate::{BarBeat, FrameRate, SampleRate, Samples, TempoMap, TimeError, Timecode, timecode::feet_frames};
/// The counters' and rulers' timebases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum TimeFormat {
BarsBeats,
#[default]
MinSecs,
Timecode,
FeetFrames,
Samples,
}
impl TimeFormat {
pub const ALL: [TimeFormat; 5] = [TimeFormat::BarsBeats, TimeFormat::MinSecs, TimeFormat::Timecode, TimeFormat::FeetFrames, TimeFormat::Samples];
pub fn label(self) -> &'static str {
match self {
TimeFormat::BarsBeats => "Bars|Beats",
TimeFormat::MinSecs => "Min:Secs",
TimeFormat::Timecode => "Timecode",
TimeFormat::FeetFrames => "Feet+Frames",
TimeFormat::Samples => "Samples",
}
}
pub fn id(self) -> &'static str {
match self {
TimeFormat::BarsBeats => "bars_beats",
TimeFormat::MinSecs => "min_secs",
TimeFormat::Timecode => "timecode",
TimeFormat::FeetFrames => "feet_frames",
TimeFormat::Samples => "samples",
}
}
pub fn from_id(id: &str) -> Option<TimeFormat> {
TimeFormat::ALL.into_iter().find(|f| f.id() == id || f.label().eq_ignore_ascii_case(id))
}
}
fn min_secs(s: Samples, sr: SampleRate) -> String {
let neg = s < 0;
// Integer maths: a float `seconds * 1000` lands just below exact millisecond positions.
let ms_total = i64::try_from(i128::from(s).abs() * 1000 / i128::from(sr.hz().max(1))).unwrap_or(i64::MAX);
let mins = ms_total / 60_000;
let secs = (ms_total / 1000) % 60;
let ms = ms_total % 1000;
format!("{}{mins}:{secs:02}.{ms:03}", if neg { "-" } else { "" })
}
/// Format an absolute position. `tc_start` is the timecode of sample 0 in samples, `ff_start` the
/// feet+frames reading of sample 0 in frames.
pub fn format_position(s: Samples, fmt: TimeFormat, sr: SampleRate, map: &TempoMap, rate: FrameRate, tc_start: Samples, ff_start: i64) -> String {
match fmt {
TimeFormat::Samples => s.to_string(),
TimeFormat::MinSecs => min_secs(s, sr),
TimeFormat::Timecode => Timecode::from_samples(s.saturating_add(tc_start), rate, sr).format(rate),
TimeFormat::FeetFrames => {
let (ft, fr) = feet_frames(s, rate, sr, ff_start);
format!("{ft}+{fr:02}")
}
TimeFormat::BarsBeats => {
let bb = map.bar_beat_at(s, sr);
format!("{}| {}| {:03}", bb.bar, bb.beat, bb.tick)
}
}
}
/// Format a length starting at `start` (Bars|Beats lengths count from 0|0|000).
pub fn format_length(start: Samples, len: Samples, fmt: TimeFormat, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> String {
match fmt {
TimeFormat::BarsBeats => {
let t0 = map.samples_to_ticks(start, sr);
let t1 = map.samples_to_ticks(start.saturating_add(len), sr);
let m = map.meter_at_tick(t0);
let d = (t1 - t0).max(0);
let bars = d / m.ticks_per_bar().max(1);
let rem = d % m.ticks_per_bar().max(1);
format!("{bars}| {}| {:03}", rem / m.ticks_per_beat().max(1), rem % m.ticks_per_beat().max(1))
}
TimeFormat::Timecode => Timecode::from_samples(len, rate, sr).format(rate),
other => format_position(len, other, sr, map, rate, 0, 0),
}
}
/// Parse a position typed into a counter or dialog.
pub fn parse_position(
text: &str,
fmt: TimeFormat,
sr: SampleRate,
map: &TempoMap,
rate: FrameRate,
tc_start: Samples,
ff_start: i64,
) -> Result<Samples, TimeError> {
let t = text.trim();
let err = || TimeError::Parse(t.to_string(), fmt.label());
match fmt {
TimeFormat::Samples => t.replace([',', '_'], "").parse::<i64>().map_err(|_| err()),
TimeFormat::MinSecs => {
let (neg, body) = match t.strip_prefix('-') {
Some(r) => (true, r),
None => (false, t),
};
let (m, s) = match body.split_once(':') {
Some((m, s)) => (m.trim().parse::<f64>().map_err(|_| err())?, s.trim().parse::<f64>().map_err(|_| err())?),
None => (0.0, body.parse::<f64>().map_err(|_| err())?),
};
if !m.is_finite() || !s.is_finite() || m < 0.0 || s < 0.0 {
return Err(err());
}
let v = sr.samples(m * 60.0 + s);
Ok(if neg { -v } else { v })
}
TimeFormat::Timecode => {
let tc = Timecode::parse(t)?;
if tc.minutes >= 60 || tc.seconds >= 60 || tc.frames >= rate.nominal().max(1) {
return Err(err());
}
if rate.is_drop() && tc.seconds == 0 && tc.minutes % 10 != 0 {
let dropped = if rate.nominal() >= 60 { 4 } else { 2 };
if tc.frames < dropped {
return Err(err());
}
}
Ok(tc.to_samples(rate, sr).saturating_sub(tc_start))
}
TimeFormat::FeetFrames => {
let (ft, fr) = t.split_once('+').ok_or_else(err)?;
let ft: i64 = ft.trim().parse().map_err(|_| err())?;
let fr: i64 = fr.trim().parse().map_err(|_| err())?;
Ok(rate.samples_at_frame(ft.saturating_mul(16).saturating_add(fr).saturating_sub(ff_start), sr))
}
TimeFormat::BarsBeats => {
let parts: Vec<i64> =
t.split(['|', '.', ' ']).filter(|p| !p.is_empty()).map(str::parse::<i64>).collect::<Result<_, _>>().map_err(|_| err())?;
let bb = BarBeat {
bar: *parts.first().ok_or_else(err)?,
beat: parts.get(1).copied().unwrap_or(1).max(1),
tick: parts.get(2).copied().unwrap_or(0).max(0),
};
Ok(map.samples_at_bar_beat(bb, sr))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ctx() -> (SampleRate, TempoMap, FrameRate) {
(SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps30)
}
#[test]
fn huge_typed_positions_parse_without_overflowing() {
let (sr, map, rate) = ctx();
for (text, fmt) in [
("999999999999999999:0", TimeFormat::Timecode),
("100000000000000:00:00:00", TimeFormat::Timecode),
("-9223372036854775808", TimeFormat::BarsBeats),
] {
let _ = parse_position(text, fmt, sr, &map, rate, 0, 0);
}
}
#[test]
fn formats_like_pro_tools_counters() {
let (sr, map, rate) = ctx();
assert_eq!(format_position(0, TimeFormat::MinSecs, sr, &map, rate, 0, 0), "0:00.000");
assert_eq!(format_position(48_000 * 75 + 24_000, TimeFormat::MinSecs, sr, &map, rate, 0, 0), "1:15.500");
assert_eq!(format_position(0, TimeFormat::BarsBeats, sr, &map, rate, 0, 0), "1| 1| 000");
assert_eq!(format_position(48_000, TimeFormat::Timecode, sr, &map, rate, 0, 0), "00:00:01:00");
assert_eq!(format_position(12345, TimeFormat::Samples, sr, &map, rate, 0, 0), "12345");
}
#[test]
fn minimum_bar_parses_without_overflow() {
let (sr, map, rate) = ctx();
let p = |t: &str| parse_position(t, TimeFormat::BarsBeats, sr, &map, rate, 0, 0);
assert!(p("-9223372036854775808|01|000").is_ok_and(|s| s < 0));
assert_eq!(p("2|3|000").ok(), Some(144_000));
assert_eq!(p("0|1|000").ok(), Some(-96_000));
}
#[test]
fn parse_round_trips() {
let (sr, map, rate) = ctx();
for fmt in TimeFormat::ALL {
for s in [0i64, 48_000, 96_000 * 3, 1_440_000] {
let text = format_position(s, fmt, sr, &map, rate, 0, 0);
let back = parse_position(&text, fmt, sr, &map, rate, 0, 0).unwrap();
assert!((back - s).abs() <= 48, "{fmt:?} {s} → {text} → {back}");
}
}
}
#[test]
fn parse_round_trips_timecode_negative() {
let (sr, map, _) = ctx();
let rate = FrameRate::Fps25;
for fmt in [TimeFormat::Timecode, TimeFormat::FeetFrames] {
for s in [-48_000i64, -96_000 * 3, -1_440_000] {
let text = format_position(s, fmt, sr, &map, rate, 0, 0);
let back = parse_position(&text, fmt, sr, &map, rate, 0, 0).unwrap();
assert_eq!(back, s, "{fmt:?} {s} → {text} → {back}");
}
}
}
#[test]
fn parse_rejects_garbage() {
let (sr, map, rate) = ctx();
assert!(parse_position("abc", TimeFormat::Samples, sr, &map, rate, 0, 0).is_err());
assert!(parse_position("1:x", TimeFormat::MinSecs, sr, &map, rate, 0, 0).is_err());
assert!(parse_position("", TimeFormat::BarsBeats, sr, &map, rate, 0, 0).is_err());
}
#[test]
fn drop_frame_skipped_labels_are_rejected() {
let (sr, map, _) = ctx();
for (rate, skipped) in [
(FrameRate::Fps29_97Drop, &["00:01:00;00", "00:01:00;01"][..]),
(FrameRate::Fps59_94Drop, &["00:01:00;00", "00:01:00;01", "00:01:00;02", "00:01:00;03"][..]),
] {
for text in skipped {
assert!(parse_position(text, TimeFormat::Timecode, sr, &map, rate, 0, 0).is_err(), "accepted skipped label {text} at {rate:?}");
}
assert!(parse_position("00:10:00;00", TimeFormat::Timecode, sr, &map, rate, 0, 0).is_ok());
}
}
#[test]
fn bar_lengths() {
let (sr, map, rate) = ctx();
assert_eq!(format_length(0, 96_000 + 24_000, TimeFormat::BarsBeats, sr, &map, rate), "1| 1| 000");
}
}
+809
View File
@@ -0,0 +1,809 @@
//! Grid and Nudge values: musical or absolute step sizes, grid lines and snapping.
use crate::{FrameRate, SampleRate, Samples, TICKS_PER_QUARTER, TempoMap, Timecode, to_samples};
/// Note values for Bars|Beats grids.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum NoteValue {
Bar,
Whole,
Half,
Quarter,
Eighth,
Sixteenth,
ThirtySecond,
SixtyFourth,
}
impl NoteValue {
/// Every musical increment in menu order, from largest to smallest.
pub const ALL: [NoteValue; 8] = [
NoteValue::Bar,
NoteValue::Whole,
NoteValue::Half,
NoteValue::Quarter,
NoteValue::Eighth,
NoteValue::Sixteenth,
NoteValue::ThirtySecond,
NoteValue::SixtyFourth,
];
/// Returns the nominal tick length; bars are adjusted for the active meter when used.
pub fn ticks(self) -> i64 {
match self {
NoteValue::Bar => TICKS_PER_QUARTER * 4,
NoteValue::Whole => TICKS_PER_QUARTER * 4,
NoteValue::Half => TICKS_PER_QUARTER * 2,
NoteValue::Quarter => TICKS_PER_QUARTER,
NoteValue::Eighth => TICKS_PER_QUARTER / 2,
NoteValue::Sixteenth => TICKS_PER_QUARTER / 4,
NoteValue::ThirtySecond => TICKS_PER_QUARTER / 8,
NoteValue::SixtyFourth => TICKS_PER_QUARTER / 16,
}
}
/// Returns the menu label for this musical increment.
pub fn label(self) -> &'static str {
match self {
NoteValue::Bar => "1 bar",
NoteValue::Whole => "Whole note",
NoteValue::Half => "1/2 note",
NoteValue::Quarter => "1/4 note",
NoteValue::Eighth => "1/8 note",
NoteValue::Sixteenth => "1/16 note",
NoteValue::ThirtySecond => "1/32 note",
NoteValue::SixtyFourth => "1/64 note",
}
}
}
/// The time scale used by a Grid or Nudge value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum GridScale {
BarsBeats,
MinSecs,
Timecode,
FeetFrames,
Samples,
ClipsMarkers,
}
impl GridScale {
/// Numeric time scales shared by Grid and Nudge.
pub const TIME: [GridScale; 5] = [GridScale::BarsBeats, GridScale::MinSecs, GridScale::Timecode, GridScale::FeetFrames, GridScale::Samples];
/// Returns the user-facing scale label.
pub fn label(self) -> &'static str {
match self {
GridScale::BarsBeats => "Bars|Beats",
GridScale::MinSecs => "Min:Secs",
GridScale::Timecode => "Timecode",
GridScale::FeetFrames => "Feet+Frames",
GridScale::Samples => "Samples",
GridScale::ClipsMarkers => "Clips/Markers",
}
}
/// Returns the stable command and session identifier.
pub fn id(self) -> &'static str {
match self {
GridScale::BarsBeats => "bars_beats",
GridScale::MinSecs => "min_secs",
GridScale::Timecode => "timecode",
GridScale::FeetFrames => "feet_frames",
GridScale::Samples => "samples",
GridScale::ClipsMarkers => "clips_markers",
}
}
/// Parses a stable identifier or user-facing label.
pub fn from_id(id: &str) -> Option<GridScale> {
Self::TIME.into_iter().chain([GridScale::ClipsMarkers]).find(|scale| scale.id() == id || scale.label().eq_ignore_ascii_case(id))
}
}
/// Timecode Grid/Nudge increments, ordered independently of the session frame rate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum TimecodeValue {
Second,
/// Five physical frames, independent of skipped drop-frame labels.
FiveFrames,
Frame,
HalfFrame,
QuarterFrame,
SubFrame,
}
impl TimecodeValue {
/// Every Timecode increment in menu order, from largest to smallest.
pub const ALL: [TimecodeValue; 6] = [
TimecodeValue::Second,
TimecodeValue::FiveFrames,
TimecodeValue::Frame,
TimecodeValue::HalfFrame,
TimecodeValue::QuarterFrame,
TimecodeValue::SubFrame,
];
/// Returns the user-facing increment label.
pub fn label(self) -> &'static str {
match self {
TimecodeValue::Second => "1 second",
TimecodeValue::FiveFrames => "5 frames",
TimecodeValue::Frame => "1 frame",
TimecodeValue::HalfFrame => "1/2 frame",
TimecodeValue::QuarterFrame => "1/4 frame",
TimecodeValue::SubFrame => "1 subframe",
}
}
/// Returns the stable command and session identifier.
pub fn id(self) -> &'static str {
match self {
TimecodeValue::Second => "second",
TimecodeValue::FiveFrames => "5_frames",
TimecodeValue::Frame => "frame",
TimecodeValue::HalfFrame => "half_frame",
TimecodeValue::QuarterFrame => "quarter_frame",
TimecodeValue::SubFrame => "subframe",
}
}
/// Parses a stable identifier or user-facing label.
pub fn from_id(id: &str) -> Option<TimecodeValue> {
Self::ALL.into_iter().find(|value| value.id() == id || value.label().eq_ignore_ascii_case(id))
}
/// Returns the increment length in frames at the session rate.
fn frames(self, rate: FrameRate) -> f64 {
match self {
TimecodeValue::Second => rate.nominal() as f64,
TimecodeValue::FiveFrames => 5.0,
TimecodeValue::Frame => 1.0,
TimecodeValue::HalfFrame => 0.5,
TimecodeValue::QuarterFrame => 0.25,
TimecodeValue::SubFrame => 0.01,
}
}
}
/// Feet+Frames Grid/Nudge increments in physical frames, independent of drop-frame label skips.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum FeetFramesValue {
Foot,
Frame,
QuarterFrame,
SubFrame,
}
impl FeetFramesValue {
/// Every Feet+Frames increment in menu order, from largest to smallest.
pub const ALL: [FeetFramesValue; 4] = [FeetFramesValue::Foot, FeetFramesValue::Frame, FeetFramesValue::QuarterFrame, FeetFramesValue::SubFrame];
/// Returns the user-facing increment label.
pub fn label(self) -> &'static str {
match self {
FeetFramesValue::Foot => "1 foot",
FeetFramesValue::Frame => "1 frame",
FeetFramesValue::QuarterFrame => "1/4 frame",
FeetFramesValue::SubFrame => "1 subframe",
}
}
/// Returns the stable command and session identifier.
pub fn id(self) -> &'static str {
match self {
FeetFramesValue::Foot => "foot",
FeetFramesValue::Frame => "frame",
FeetFramesValue::QuarterFrame => "quarter_frame",
FeetFramesValue::SubFrame => "subframe",
}
}
/// Parses a stable identifier or user-facing label.
pub fn from_id(id: &str) -> Option<FeetFramesValue> {
Self::ALL.into_iter().find(|value| value.id() == id || value.label().eq_ignore_ascii_case(id))
}
/// Returns the increment length in frames.
fn frames(self) -> f64 {
let (num, den) = self.frame_ratio();
num as f64 / den as f64
}
/// Exact numerator and denominator of the increment in physical frames.
fn frame_ratio(self) -> (i128, i128) {
match self {
Self::Foot => (16, 1),
Self::Frame => (1, 1),
Self::QuarterFrame => (1, 4),
Self::SubFrame => (1, 100),
}
}
/// Apply the counter origin in frames before rounding once to the nearest sample.
fn sample_line(self, index: i128, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
let (num, den) = self.frame_ratio();
let (rate_num, rate_den) = rate.rational();
let frames = index * num - i128::from(origin) * den;
let samples = frames * i128::from(sr.hz().max(1)) * i128::from(rate_den);
let divisor = den * i128::from(rate_num);
let magnitude = (samples.abs() + divisor / 2) / divisor;
let rounded = if samples < 0 { -magnitude } else { magnitude };
i64::try_from(rounded).unwrap_or(if rounded < 0 { i64::MIN } else { i64::MAX })
}
/// Find a line index using exact frame arithmetic, allowing for whole-sample rounding.
fn line_index(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> i128 {
let (num, den) = self.frame_ratio();
let (rate_num, rate_den) = rate.rational();
let scale = i128::from(sr.hz().max(1)) * i128::from(rate_den);
let frames = i128::from(position) * i128::from(rate_num) + i128::from(origin) * scale;
let mut index = (frames * den).div_euclid(scale * num);
if self.sample_line(index + 1, sr, rate, origin) <= position {
index += 1;
}
index
}
/// The Feet+Frames line at or before a sample, relative to the counter's frame origin.
pub fn line_at_or_before(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
self.sample_line(self.line_index(position, sr, rate, origin), sr, rate, origin)
}
/// The next distinct sample line; subframe increments may share a sample at low sample rates.
fn next_line(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
self.sample_line(self.line_index(position, sr, rate, origin) + 1, sr, rate, origin).max(position.saturating_add(1))
}
/// Snap against frame-origin lines, choosing the earlier line when distances are equal.
pub fn snap(self, position: Samples, sr: SampleRate, rate: FrameRate, origin: i64) -> Samples {
let lo = self.line_at_or_before(position, sr, rate, origin);
let hi = self.next_line(lo, sr, rate, origin);
if i128::from(position) - i128::from(lo) <= i128::from(hi) - i128::from(position) { lo } else { hi }
}
/// Distinct Feet+Frames sample lines within `[start, end)`, capped at `max`.
pub fn lines(self, start: Samples, end: Samples, sr: SampleRate, rate: FrameRate, origin: i64, max: usize) -> Vec<Samples> {
let mut out = Vec::new();
let mut line = self.line_at_or_before(start, sr, rate, origin);
while line < end && out.len() < max {
if line >= start {
out.push(line);
}
let next = self.next_line(line, sr, rate, origin);
if next <= line {
break;
}
line = next;
}
out
}
}
/// A grid or nudge step.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GridValue {
/// Musical: note value, optionally dotted or triplet.
Note { value: NoteValue, dotted: bool, triplet: bool },
/// Absolute seconds (Min:Secs grids: 0.001 … 1 s).
Seconds(f64),
/// Frames at the session timecode rate.
/// Kept for sessions and commands written before named timecode increments were added.
Frames(i64),
/// A named Timecode increment, including fractional frames and one second.
Timecode(TimecodeValue),
/// A Feet+Frames increment (one foot is 16 frames).
FeetFrames(FeetFramesValue),
/// Raw samples.
Samples(i64),
}
impl Default for GridValue {
/// Starts on a straight sixteenth-note Bars|Beats grid.
fn default() -> Self {
GridValue::Note { value: NoteValue::Sixteenth, dotted: false, triplet: false }
}
}
impl GridValue {
/// Returns the user-facing label for this increment.
pub fn label(&self) -> String {
match self {
GridValue::Note { value, dotted, triplet } => {
let mut s = value.label().to_string();
if *dotted {
s.push_str(" dotted");
}
if *triplet {
s.push_str(" triplet");
}
s
}
GridValue::Seconds(s) => {
if *s >= 1.0 {
format!("{s} second{}", if *s == 1.0 { "" } else { "s" })
} else {
format!("{} ms", (s * 1000.0).round() as i64)
}
}
GridValue::Frames(f) => format!("{f} frame{}", if *f == 1 { "" } else { "s" }),
GridValue::Timecode(value) => value.label().to_string(),
GridValue::FeetFrames(value) => value.label().to_string(),
GridValue::Samples(n) => format!("{n} sample{}", if *n == 1 { "" } else { "s" }),
}
}
/// Returns the time scale to which this increment belongs.
pub fn scale(self) -> GridScale {
match self {
GridValue::Note { .. } => GridScale::BarsBeats,
GridValue::Seconds(_) => GridScale::MinSecs,
GridValue::Frames(_) | GridValue::Timecode(_) => GridScale::Timecode,
GridValue::FeetFrames(_) => GridScale::FeetFrames,
GridValue::Samples(_) => GridScale::Samples,
}
}
/// Returns the default increment for a newly selected time scale.
pub fn for_scale(scale: GridScale) -> GridValue {
match scale {
GridScale::BarsBeats => GridValue::default(),
GridScale::MinSecs => GridValue::Seconds(1.0),
GridScale::Timecode => GridValue::Timecode(TimecodeValue::Frame),
GridScale::FeetFrames => GridValue::FeetFrames(FeetFramesValue::Frame),
GridScale::Samples => GridValue::Samples(100),
GridScale::ClipsMarkers => GridValue::default(),
}
}
/// The next larger or smaller menu value of the same kind, or `self` at either end. Note values keep
/// their dot or triplet modifier.
pub fn stepped(self, larger: bool) -> GridValue {
/// Finds the next value in a numeric increment ladder without wrapping.
fn next<T: PartialOrd + Copy>(ladder: &[T], v: T, larger: bool) -> Option<T> {
if larger { ladder.iter().copied().find(|x| *x > v) } else { ladder.iter().rev().copied().find(|x| *x < v) }
}
match self {
GridValue::Note { value, dotted, triplet } => {
let i = NoteValue::ALL.iter().position(|v| *v == value).unwrap_or(0);
let j = if larger { i.checked_sub(1) } else { i.checked_add(1) };
j.and_then(|j| NoteValue::ALL.get(j)).map_or(self, |&value| GridValue::Note { value, dotted, triplet })
}
GridValue::Seconds(s) => next(&[0.001, 0.01, 0.1, 0.5, 1.0], s, larger).map_or(self, GridValue::Seconds),
GridValue::Frames(f) => next(&[1, 10, 100], f, larger).map_or(self, GridValue::Frames),
GridValue::Timecode(value) => step_enum(&TimecodeValue::ALL, value, larger).map_or(self, GridValue::Timecode),
GridValue::FeetFrames(value) => step_enum(&FeetFramesValue::ALL, value, larger).map_or(self, GridValue::FeetFrames),
GridValue::Samples(n) => next(&[1, 2, 10, 100, 1_000, 10_000], n, larger).map_or(self, GridValue::Samples),
}
}
fn note_ticks(value: NoteValue, dotted: bool, triplet: bool, map: &TempoMap, at_tick: i64) -> i64 {
let base = if value == NoteValue::Bar { map.meter_at_tick(at_tick).ticks_per_bar() } else { value.ticks() };
let mut t = base;
if dotted {
t = t * 3 / 2;
}
if triplet {
t = t * 2 / 3;
}
t.max(1)
}
/// The step in samples at position `at` (musical steps depend on tempo).
pub fn step_samples(&self, at: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
match *self {
GridValue::Note { value, dotted, triplet } => {
let t0 = map.samples_to_ticks(at, sr);
let dt = Self::note_ticks(value, dotted, triplet, map, t0);
(map.tick_to_samples(t0.saturating_add(dt), sr).saturating_sub(map.tick_to_samples(t0, sr))).max(1)
}
GridValue::Seconds(s) => sr.samples(s.clamp(0.000_01, 3600.0)).max(1),
GridValue::Frames(f) => to_samples(rate.samples_per_frame(sr) * f.clamp(1, 1_000_000) as f64).max(1),
GridValue::Timecode(value) => to_samples(rate.samples_per_frame(sr) * value.frames(rate)).max(1),
GridValue::FeetFrames(value) => to_samples(rate.samples_per_frame(sr) * value.frames()).max(1),
GridValue::Samples(n) => n.max(1),
}
}
/// Nearest grid line to `pos`.
pub fn snap(&self, pos: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
if let Self::FeetFrames(value) = *self {
return value.snap(pos, sr, rate, 0);
}
let lo = self.line_at_or_before(pos, sr, map, rate);
let hi = self.next_line(lo, sr, map, rate);
if (pos - lo) <= (hi - pos) { lo } else { hi }
}
/// The grid line at or before `pos`.
pub fn line_at_or_before(&self, pos: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
match *self {
Self::FeetFrames(value) => value.line_at_or_before(pos, sr, rate, 0),
GridValue::Note { value, dotted, triplet } => {
// Float ticks can land a hair either side of a line's own tick.
let mut t = map.samples_to_ticks_f(pos, sr).floor() as i64;
if map.tick_to_samples(t, sr) > pos {
t = t.saturating_sub(1);
} else if map.tick_to_samples(t.saturating_add(1), sr) <= pos {
t = t.saturating_add(1);
}
// Sub-bar values restart at each bar so odd meters stay aligned. A whole note is
// always four quarter notes and therefore keeps a continuous tick origin.
let bb = map.bar_beat_at_tick(t);
let bar_tick = map.bar_start_tick(bb.bar);
let origin = if value == NoteValue::Whole { 0 } else { bar_tick };
let step = Self::note_ticks(value, dotted, triplet, map, origin);
let k = (t - origin).div_euclid(step);
map.tick_to_samples(origin + k * step, sr)
}
_ => self.abs_line(self.abs_index_at_or_before(pos, sr, rate), sr, rate),
}
}
/// Position of absolute grid line `k` (Seconds, Frames, Samples), at an exact multiple of the step
/// rounded once, so rounding never accumulates from line to line.
fn abs_line(&self, k: i64, sr: SampleRate, rate: FrameRate) -> Samples {
if let Self::FeetFrames(value) = *self {
return value.sample_line(i128::from(k), sr, rate, 0);
}
if matches!(self, GridValue::Timecode(TimecodeValue::Second)) && rate.is_drop() {
return rate.samples_at_frame(Self::drop_second_frame(k, rate), sr);
}
if let Some(frames) = self.frame_step(rate) {
let whole = frames.round();
if frames == whole {
return rate.samples_at_frame(k.saturating_mul(whole as i64), sr);
}
let step = (rate.samples_per_frame(sr) * frames).max(1.0);
return to_samples(k as f64 * step);
}
match *self {
GridValue::Seconds(s) => to_samples(k as f64 * Self::seconds_step(s, sr)),
GridValue::Samples(n) => k.saturating_mul(n.max(1)),
GridValue::Note { .. } => 0,
GridValue::Frames(_) | GridValue::Timecode(_) | GridValue::FeetFrames(_) => 0,
}
}
/// Index of the absolute grid line at or before `pos`.
fn abs_index_at_or_before(&self, pos: Samples, sr: SampleRate, rate: FrameRate) -> i64 {
if matches!(self, GridValue::Timecode(TimecodeValue::Second)) && rate.is_drop() {
let tc = Timecode::from_frames(rate.frames_at(pos, sr), rate);
let magnitude = tc.hours.saturating_mul(3600).saturating_add(tc.minutes.saturating_mul(60)).saturating_add(tc.seconds);
let mut k = if tc.negative { magnitude.saturating_neg() } else { magnitude };
while self.abs_line(k, sr, rate) > pos {
let previous = k.saturating_sub(1);
if previous == k {
break;
}
k = previous;
}
while self.abs_line(k.saturating_add(1), sr, rate) <= pos {
let next = k.saturating_add(1);
if next == k {
break;
}
k = next;
}
return k;
}
let mut k = if let Some(frames) = self.frame_step(rate) {
let step = (rate.samples_per_frame(sr) * frames).max(1.0);
(pos as f64 / step).floor() as i64
} else {
match *self {
GridValue::Seconds(s) => (pos as f64 / Self::seconds_step(s, sr)).floor() as i64,
GridValue::Samples(n) => return pos.div_euclid(n.max(1)),
GridValue::Note { .. } => return 0,
GridValue::Frames(_) | GridValue::Timecode(_) | GridValue::FeetFrames(_) => return 0,
}
};
// Lines are rounded to whole samples, so the floored index can be one off either way.
if self.abs_line(k, sr, rate) > pos {
k = k.saturating_sub(1);
} else if self.abs_line(k.saturating_add(1), sr, rate) <= pos {
k = k.saturating_add(1);
}
k
}
/// The exact (fractional) Seconds step in samples, at least one sample.
fn seconds_step(s: f64, sr: SampleRate) -> f64 {
(s.clamp(0.000_01, 3600.0) * sr.as_f64()).max(1.0)
}
/// Maps a signed whole-second timecode label to its physical frame at a drop-frame rate.
fn drop_second_frame(index: i64, rate: FrameRate) -> i64 {
let seconds = index.unsigned_abs();
let total_minutes = seconds / 60;
let frames = if seconds.is_multiple_of(60) && !total_minutes.is_multiple_of(10) { if rate.nominal() >= 60 { 4 } else { 2 } } else { 0 };
Timecode {
negative: index < 0,
hours: i64::try_from(seconds / 3600).unwrap_or(i64::MAX),
minutes: i64::try_from((seconds / 60) % 60).unwrap_or(0),
seconds: i64::try_from(seconds % 60).unwrap_or(0),
frames,
}
.to_frames(rate)
}
/// A frame-based increment as a possibly fractional number of frames.
fn frame_step(&self, rate: FrameRate) -> Option<f64> {
match *self {
GridValue::Frames(frames) => Some(frames.clamp(1, 1_000_000) as f64),
GridValue::Timecode(value) => Some(value.frames(rate)),
GridValue::FeetFrames(value) => Some(value.frames()),
_ => None,
}
}
/// The first grid line strictly after `line`.
pub fn next_line(&self, line: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate) -> Samples {
if let Self::FeetFrames(value) = *self {
return value.next_line(line, sr, rate, 0);
}
if !matches!(self, GridValue::Note { .. }) {
let next = self.abs_line(self.abs_index_at_or_before(line, sr, rate).saturating_add(1), sr, rate);
return if next > line { next } else { line.saturating_add(1) };
}
let step = self.step_samples(line, sr, map, rate);
let candidate = self.line_at_or_before(line.saturating_add(step), sr, map, rate);
if candidate > line { candidate } else { line.saturating_add(step) }
}
/// All grid lines within `[start, end)`, capped at `max` lines.
pub fn lines(&self, start: Samples, end: Samples, sr: SampleRate, map: &TempoMap, rate: FrameRate, max: usize) -> Vec<Samples> {
if let Self::FeetFrames(value) = *self {
return value.lines(start, end, sr, rate, 0, max);
}
let mut out = Vec::new();
let mut p = self.line_at_or_before(start, sr, map, rate);
while p < end && out.len() < max {
if p >= start {
out.push(p);
}
let n = self.next_line(p, sr, map, rate);
if n <= p {
break;
}
p = n;
}
out
}
}
/// Moves one position through an ordered increment menu without wrapping.
fn step_enum<T: Copy + PartialEq>(values: &[T], value: T, larger: bool) -> Option<T> {
let index = values.iter().position(|candidate| *candidate == value)?;
let next = if larger { index.checked_sub(1) } else { index.checked_add(1) }?;
values.get(next).copied()
}
#[cfg(test)]
mod tests {
use super::*;
/// Frame origins are subtracted before rounding whole frames, quarter frames and subframes.
#[test]
fn feet_frames_origins_round_only_after_applying_the_frame_offset() {
let (sr, rate) = (SampleRate::HZ_48000, FrameRate::Fps29_97);
for at in [49_650, 100_901, 177_778] {
assert_eq!(FeetFramesValue::Foot.line_at_or_before(at, sr, rate, 1), at);
assert_eq!(FeetFramesValue::Foot.snap(at - 1, sr, rate, 1), at);
}
assert_eq!(FeetFramesValue::QuarterFrame.snap(50_049, sr, rate, 1), 50_050);
assert_eq!(FeetFramesValue::SubFrame.lines(49_665, 49_667, sr, rate, 1, 4), [49_666]);
}
/// Dense subframes retain distinct sample lines and remain bounded with extreme signed origins.
#[test]
fn feet_frames_subframes_handle_dense_steps_and_extreme_origins() {
let sr = SampleRate::new(8_000).unwrap();
let rate = FrameRate::Fps120;
for origin in [i64::MIN, -1, 0, 1, i64::MAX] {
assert_eq!(FeetFramesValue::SubFrame.lines(-3, 4, sr, rate, origin, 20), [-3, -2, -1, 0, 1, 2, 3]);
for at in [i64::MIN, -1, 0, 1, i64::MAX] {
assert_eq!(FeetFramesValue::SubFrame.line_at_or_before(at, sr, rate, origin), at);
assert_eq!(FeetFramesValue::SubFrame.snap(at, sr, rate, origin), at);
}
}
}
#[test]
fn grid_lines_are_their_own_line_at_odd_tempos() {
let (g, sr, rate) = (GridValue::default(), SampleRate::HZ_48000, FrameRate::Fps30);
for bpm in [90.0, 95.0, 110.0, 130.0, 140.0] {
let map = TempoMap::new(bpm, 4, 4).unwrap();
let mut line = 0;
for _ in 0..64 {
assert_eq!(g.line_at_or_before(line, sr, &map, rate), line, "{bpm} bpm");
line = g.next_line(line, sr, &map, rate);
}
}
}
/// Musical boundaries stay exact across a tempo change while absolute scales remain
/// independent of the tempo map.
#[test]
fn grids_stay_aligned_across_a_tempo_change() {
let (sr, rate) = (SampleRate::HZ_48000, FrameRate::Fps29_97Drop);
let mut map = TempoMap::default();
map.set_tempo(TICKS_PER_QUARTER * 4, 90.0).unwrap();
let musical = GridValue::Note { value: NoteValue::Quarter, dotted: false, triplet: false };
for tick in [0, TICKS_PER_QUARTER * 3, TICKS_PER_QUARTER * 4, TICKS_PER_QUARTER * 5] {
let line = map.tick_to_samples(tick, sr);
assert_eq!(musical.line_at_or_before(line, sr, &map, rate), line);
}
for absolute in [
GridValue::Seconds(0.5),
GridValue::Timecode(TimecodeValue::Second),
GridValue::FeetFrames(FeetFramesValue::Foot),
GridValue::Samples(1_000),
] {
let line = absolute.next_line(absolute.line_at_or_before(100_000, sr, &map, rate), sr, &map, rate);
assert_eq!(absolute.line_at_or_before(line, sr, &map, rate), line, "{absolute:?}");
}
}
#[test]
fn sixteenth_grid_at_120() {
let g = GridValue::default();
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps30);
assert_eq!(g.step_samples(0, sr, &map, rate), 6000);
assert_eq!(g.snap(2900, sr, &map, rate), 0);
assert_eq!(g.snap(3100, sr, &map, rate), 6000);
assert_eq!(g.lines(0, 24_000, sr, &map, rate, 100), vec![0, 6000, 12000, 18000]);
}
/// Absolute increments report their expected sample lengths at a fixed rate.
#[test]
fn absolute_grids() {
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps25);
assert_eq!(GridValue::Seconds(1.0).snap(70_000, sr, &map, rate), 48_000);
assert_eq!(GridValue::Frames(1).step_samples(0, sr, &map, rate), 1920);
assert_eq!(GridValue::Timecode(TimecodeValue::Second).step_samples(0, sr, &map, rate), 48_000);
assert_eq!(GridValue::Timecode(TimecodeValue::FiveFrames).step_samples(0, sr, &map, rate), 9_600);
assert_eq!(GridValue::Timecode(TimecodeValue::HalfFrame).step_samples(0, sr, &map, rate), 960);
assert_eq!(GridValue::Timecode(TimecodeValue::QuarterFrame).step_samples(0, sr, &map, rate), 480);
assert_eq!(GridValue::Timecode(TimecodeValue::SubFrame).step_samples(0, sr, &map, rate), 19);
assert_eq!(GridValue::FeetFrames(FeetFramesValue::Foot).step_samples(0, sr, &map, rate), 30_720);
assert_eq!(GridValue::Samples(0).step_samples(0, sr, &map, rate), 1);
}
/// Bar length follows the meter while a whole note always spans four quarter notes.
#[test]
fn a_bar_and_a_whole_note_differ_in_three_four() {
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::new(120.0, 3, 4).unwrap(), FrameRate::Fps25);
let note = |value| GridValue::Note { value, dotted: false, triplet: false };
assert_eq!(note(NoteValue::Bar).step_samples(0, sr, &map, rate), 72_000);
assert_eq!(note(NoteValue::Whole).step_samples(0, sr, &map, rate), 96_000);
assert_eq!(note(NoteValue::Bar).line_at_or_before(96_000, sr, &map, rate), 72_000);
assert_eq!(note(NoteValue::Whole).line_at_or_before(96_000, sr, &map, rate), 96_000);
assert_eq!(note(NoteValue::Half).lines(0, 150_000, sr, &map, rate, 10), [0, 48_000, 72_000, 120_000, 144_000]);
}
#[test]
fn seconds_grid_lines_land_on_whole_seconds() {
let (sr, map, rate) = (SampleRate::HZ_44100, TempoMap::default(), FrameRate::Fps30);
for g in [GridValue::Seconds(0.001), GridValue::Seconds(0.01)] {
for n in 0..20 {
let s = n * 44_100;
assert_eq!(g.snap(s, sr, &map, rate), s, "{g:?} at {n} s");
assert_eq!(g.line_at_or_before(s, sr, &map, rate), s, "{g:?} at {n} s");
}
}
}
/// Legacy frame grids stay aligned to exact frame starts at fractional rates.
#[test]
fn frame_grid_lines_land_on_frame_starts() {
let sr = SampleRate::HZ_48000;
let map = TempoMap::default();
for rate in [FrameRate::Fps29_97, FrameRate::Fps23_976] {
for f in [1, 10] {
let g = GridValue::Frames(f);
for k in (0..5000).step_by(37) {
let s = rate.samples_at_frame(k, sr);
let line = rate.samples_at_frame(k.div_euclid(f) * f, sr);
assert_eq!(g.line_at_or_before(s, sr, &map, rate), line, "{rate:?} {f} frames at frame {k}");
if k % f == 0 {
assert_eq!(g.snap(s, sr, &map, rate), s, "{rate:?} {f} frames at frame {k}");
}
}
let start = rate.samples_at_frame(4000, sr);
let end = rate.samples_at_frame(4000 + 20 * f, sr);
let want: Vec<_> = (0..20).map(|i| rate.samples_at_frame(4000 + i * f, sr)).collect();
assert_eq!(g.lines(start, end, sr, &map, rate, 100), want, "{rate:?} {f} frames");
}
}
}
/// Named whole- and sub-frame grids retain the exact-multiple calculation used by legacy frame grids.
#[test]
fn named_frame_grids_land_on_exact_subdivisions() {
let sr = SampleRate::HZ_48000;
let map = TempoMap::default();
let grids = TimecodeValue::ALL.into_iter().map(GridValue::Timecode).chain(FeetFramesValue::ALL.into_iter().map(GridValue::FeetFrames));
for rate in [FrameRate::Fps29_97, FrameRate::Fps23_976] {
for grid in grids.clone() {
for index in 0..200 {
let line = grid.abs_line(index, sr, rate);
assert_eq!(grid.line_at_or_before(line, sr, &map, rate), line, "{grid:?} {rate:?} line {index}");
assert_eq!(grid.next_line(line, sr, &map, rate), grid.abs_line(index + 1, sr, rate), "{grid:?} {rate:?} line {index}");
}
}
}
}
/// Drop-frame second grids follow labelled second boundaries in both timeline directions.
#[test]
fn drop_frame_second_grids_follow_timecode_labels() {
let sr = SampleRate::HZ_48000;
let map = TempoMap::default();
let grid = GridValue::Timecode(TimecodeValue::Second);
for rate in [FrameRate::Fps29_97Drop, FrameRate::Fps59_94Drop] {
for seconds in [0, 59, 60, 61, 600, 601, 3600] {
let frame = GridValue::drop_second_frame(seconds, rate);
let line = rate.samples_at_frame(frame, sr);
assert_eq!(grid.line_at_or_before(line, sr, &map, rate), line, "{rate:?} second {seconds}");
assert_eq!(grid.line_at_or_before(-line, sr, &map, rate), -line, "{rate:?} second -{seconds}");
for offset in -2..=rate.nominal() + 2 {
let position = rate.samples_at_frame(frame.saturating_add(offset), sr);
let before = grid.line_at_or_before(position, sr, &map, rate);
assert!(before <= position, "{rate:?} second {seconds}, frame offset {offset}");
assert!(grid.next_line(before, sr, &map, rate) > position, "{rate:?} second {seconds}, frame offset {offset}");
}
}
let labelled = Timecode { negative: false, hours: 0, minutes: 1, seconds: 1, frames: 0 }.to_samples(rate, sr);
assert_eq!(grid.snap(labelled, sr, &map, rate), labelled);
}
for (rate, minute_frame) in [(FrameRate::Fps29_97Drop, 1800), (FrameRate::Fps59_94Drop, 3600)] {
let boundary = rate.samples_at_frame(minute_frame, sr);
assert_eq!(grid.line_at_or_before(boundary, sr, &map, rate), boundary, "{rate:?} positive minute boundary");
assert_eq!(grid.snap(boundary, sr, &map, rate), boundary, "{rate:?} positive minute snap");
assert_eq!(grid.line_at_or_before(-boundary, sr, &map, rate), -boundary, "{rate:?} negative minute boundary");
assert_eq!(grid.snap(-boundary, sr, &map, rate), -boundary, "{rate:?} negative minute snap");
}
}
#[test]
fn lines_are_capped() {
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps25);
assert_eq!(GridValue::Samples(1).lines(0, 1_000_000, sr, &map, rate, 50).len(), 50);
}
#[test]
fn triplets_and_dots() {
let (sr, map, rate) = (SampleRate::HZ_48000, TempoMap::default(), FrameRate::Fps25);
let t = GridValue::Note { value: NoteValue::Quarter, dotted: false, triplet: true };
assert_eq!(t.step_samples(0, sr, &map, rate), 16_000);
let d = GridValue::Note { value: NoteValue::Quarter, dotted: true, triplet: false };
assert_eq!(d.step_samples(0, sr, &map, rate), 36_000);
}
/// Stepping follows each menu ladder and stops at its endpoints.
#[test]
fn values_step_to_the_next_larger_or_smaller() {
let note = |value, triplet| GridValue::Note { value, dotted: false, triplet };
assert_eq!(note(NoteValue::Sixteenth, false).stepped(true), note(NoteValue::Eighth, false));
assert_eq!(note(NoteValue::Eighth, true).stepped(false), note(NoteValue::Sixteenth, true));
assert_eq!(note(NoteValue::Bar, false).stepped(true), note(NoteValue::Bar, false));
assert_eq!(note(NoteValue::SixtyFourth, false).stepped(false), note(NoteValue::SixtyFourth, false));
assert_eq!(GridValue::Seconds(0.01).stepped(true), GridValue::Seconds(0.1));
assert_eq!(GridValue::Seconds(0.5).stepped(false), GridValue::Seconds(0.1));
assert_eq!(GridValue::Seconds(1.0).stepped(true), GridValue::Seconds(1.0));
assert_eq!(GridValue::Frames(1).stepped(true), GridValue::Frames(10));
assert_eq!(GridValue::Timecode(TimecodeValue::Frame).stepped(false), GridValue::Timecode(TimecodeValue::HalfFrame));
assert_eq!(GridValue::FeetFrames(FeetFramesValue::Frame).stepped(true), GridValue::FeetFrames(FeetFramesValue::Foot));
assert_eq!(GridValue::Samples(100).stepped(false), GridValue::Samples(10));
assert_eq!(GridValue::Samples(1).stepped(true), GridValue::Samples(2));
assert_eq!(GridValue::Samples(1).stepped(false), GridValue::Samples(1));
}
#[test]
fn snap_at_extreme_position_does_not_overflow() {
let sr = SampleRate::new(8000).unwrap();
let map = TempoMap::new(1000.0, 4, 4).unwrap();
let _ = GridValue::default().snap(i64::MAX, sr, &map, FrameRate::Fps30);
}
}
+153 -2
View File
@@ -1,4 +1,155 @@
//! Compatibility facade for SoundCraft's sample-index time API in shared `craft-time`.
//! SoundCraft timebases.
//!
//! Every position in a session is an absolute sample index (`i64`) at the session sample rate.
//! This crate converts those positions to and from the five Pro Tools-style timebases
//! (Bars|Beats, Min:Secs, Timecode, Feet+Frames, Samples) through a [`TempoMap`], and computes
//! grid lines and snapping for the Grid / Nudge values.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub use craft_time::soundcraft::*;
mod format;
mod grid;
mod tempo;
mod timecode;
pub use format::{TimeFormat, format_length, format_position, parse_position};
pub use grid::{FeetFramesValue, GridScale, GridValue, NoteValue, TimecodeValue};
pub use tempo::{BarBeat, MeterEvent, TICKS_PER_QUARTER, TempoEvent, TempoMap};
pub use timecode::{FrameRate, Timecode};
/// A position or length in samples.
pub type Samples = i64;
/// Largest position accepted from parameters and files: 2^40 samples (about 265 days at 48 kHz).
/// Clamping there keeps every later addition and subtraction on positions far away from overflow.
pub const MAX_POSITION: Samples = 1 << 40;
/// Errors from parsing or converting time values.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum TimeError {
#[error("cannot parse `{0}` as a {1} value")]
Parse(String, &'static str),
#[error("invalid sample rate {0}")]
SampleRate(u32),
#[error("invalid tempo {0}")]
Tempo(f64),
#[error("invalid meter {0}/{1}")]
Meter(u32, u32),
}
/// Sample rates supported by sessions (Pro Tools offers 44.1 k – 192 k; we accept 8 k – 768 k).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SampleRate(u32);
impl SampleRate {
pub const HZ_44100: SampleRate = SampleRate(44_100);
pub const HZ_48000: SampleRate = SampleRate(48_000);
pub const COMMON: [u32; 8] = [44_100, 48_000, 88_200, 96_000, 176_400, 192_000, 352_800, 384_000];
pub fn new(hz: u32) -> Result<Self, TimeError> {
if (8_000..=768_000).contains(&hz) { Ok(SampleRate(hz)) } else { Err(TimeError::SampleRate(hz)) }
}
pub fn hz(self) -> u32 {
self.0
}
pub fn as_f64(self) -> f64 {
f64::from(self.0)
}
/// Samples → seconds.
pub fn seconds(self, s: Samples) -> f64 {
s as f64 / self.as_f64()
}
/// Seconds → samples, rounded to nearest and saturated.
pub fn samples(self, seconds: f64) -> Samples {
to_samples(seconds * self.as_f64())
}
}
impl Default for SampleRate {
fn default() -> Self {
SampleRate::HZ_48000
}
}
/// Round a float sample count to `i64`, mapping NaN to 0 and saturating infinities.
pub fn to_samples(v: f64) -> Samples {
if v.is_nan() {
0
} else if v >= i64::MAX as f64 {
i64::MAX
} else if v <= i64::MIN as f64 {
i64::MIN
} else {
v.round() as i64
}
}
/// A half-open sample range `[start, end)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub struct Range {
pub start: Samples,
pub end: Samples,
}
impl Range {
pub fn new(a: Samples, b: Samples) -> Self {
if a <= b { Range { start: a, end: b } } else { Range { start: b, end: a } }
}
pub fn point(at: Samples) -> Self {
Range { start: at, end: at }
}
pub fn len(&self) -> Samples {
self.end.saturating_sub(self.start)
}
pub fn is_empty(&self) -> bool {
self.end <= self.start
}
pub fn contains(&self, s: Samples) -> bool {
s >= self.start && s < self.end
}
pub fn overlaps(&self, o: &Range) -> bool {
self.start < o.end && o.start < self.end
}
pub fn intersect(&self, o: &Range) -> Option<Range> {
let s = self.start.max(o.start);
let e = self.end.min(o.end);
(s < e).then_some(Range { start: s, end: e })
}
pub fn shifted(&self, by: Samples) -> Range {
Range { start: self.start.saturating_add(by), end: self.end.saturating_add(by) }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_rate_bounds() {
assert!(SampleRate::new(48_000).is_ok());
assert!(SampleRate::new(0).is_err());
assert!(SampleRate::new(10_000_000).is_err());
}
#[test]
fn seconds_round_trip() {
let sr = SampleRate::HZ_44100;
assert_eq!(sr.samples(1.0), 44_100);
assert!((sr.seconds(22_050) - 0.5).abs() < 1e-12);
}
#[test]
fn to_samples_is_total() {
assert_eq!(to_samples(f64::NAN), 0);
assert_eq!(to_samples(f64::INFINITY), i64::MAX);
assert_eq!(to_samples(f64::NEG_INFINITY), i64::MIN);
}
#[test]
fn range_ops() {
let a = Range::new(10, 0);
assert_eq!(a, Range { start: 0, end: 10 });
assert_eq!(a.intersect(&Range::new(5, 20)), Some(Range::new(5, 10)));
assert_eq!(a.intersect(&Range::new(10, 20)), None);
assert!(a.contains(9) && !a.contains(10));
}
}
+622
View File
@@ -0,0 +1,622 @@
//! Tempo and meter maps: the conversion between musical time (ticks) and samples.
use crate::{MAX_POSITION, SampleRate, Samples, TimeError, to_samples};
/// Ticks per quarter note (Pro Tools' resolution).
pub const TICKS_PER_QUARTER: i64 = 960;
/// A tempo change at a tick position. `bpm` is quarter notes per minute.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TempoEvent {
pub tick: i64,
pub bpm: f64,
}
/// A meter (time signature) change at a tick position, which must fall on a bar line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MeterEvent {
pub tick: i64,
pub numerator: u32,
pub denominator: u32,
}
impl MeterEvent {
pub fn ticks_per_beat(&self) -> i64 {
let d = i64::from(self.denominator.max(1));
(TICKS_PER_QUARTER * 4 / d).max(1)
}
pub fn ticks_per_bar(&self) -> i64 {
self.ticks_per_beat().saturating_mul(i64::from(self.numerator.max(1)))
}
}
/// A musical position: 1-based bar and beat plus ticks within the beat.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct BarBeat {
pub bar: i64,
pub beat: i64,
pub tick: i64,
}
/// Tempo and meter changes for a session. Always has at least one of each, at tick 0.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(from = "TempoMapData")]
pub struct TempoMap {
tempos: Vec<TempoEvent>,
meters: Vec<MeterEvent>,
/// For each tempo event, the elapsed time at its tick in quarter-note minutes (ticks / bpm,
/// summed over the earlier segments). Lets tick/sample conversions binary-search the segment
/// instead of walking every earlier tempo change, so converting many positions against a large
/// tempo map stays O(log n) each. Rebuilt whenever `tempos` changes.
#[serde(skip)]
elapsed: Vec<f64>,
}
/// The serialized form of [`TempoMap`], without the derived lookup table.
#[derive(serde::Deserialize)]
struct TempoMapData {
tempos: Vec<TempoEvent>,
meters: Vec<MeterEvent>,
}
impl From<TempoMapData> for TempoMap {
fn from(d: TempoMapData) -> Self {
TempoMap::from_parts(d.tempos, d.meters)
}
}
impl Default for TempoMap {
fn default() -> Self {
TempoMap::from_parts(vec![TempoEvent { tick: 0, bpm: 120.0 }], vec![MeterEvent { tick: 0, numerator: 4, denominator: 4 }])
}
}
fn valid_bpm(bpm: f64) -> Result<f64, TimeError> {
if bpm.is_finite() && (5.0..=1000.0).contains(&bpm) { Ok(bpm) } else { Err(TimeError::Tempo(bpm)) }
}
fn valid_meter(numerator: u32, denominator: u32) -> bool {
(1..=64).contains(&numerator) && [1, 2, 4, 8, 16, 32, 64].contains(&denominator)
}
impl TempoMap {
fn from_parts(tempos: Vec<TempoEvent>, meters: Vec<MeterEvent>) -> Self {
let mut m = TempoMap { tempos, meters, elapsed: Vec::new() };
m.reindex();
m
}
/// Rebuild `elapsed` from `tempos`. The first segment runs from tick 0 at the first tempo.
fn reindex(&mut self) {
let mut elapsed = Vec::with_capacity(self.tempos.len());
let mut acc = 0.0;
let mut seg_tick = 0i64;
let mut bpm = self.tempos.first().map_or(120.0, |e| e.bpm);
for (i, e) in self.tempos.iter().enumerate() {
if i > 0 {
// Saturating: a file's ticks are indexed before `sanitize` orders them.
acc += e.tick.saturating_sub(seg_tick) as f64 / bpm;
seg_tick = e.tick;
bpm = e.bpm;
}
elapsed.push(acc);
}
self.elapsed = elapsed;
}
/// Samples per quarter-note minute (the unit of `elapsed`) at `sr`.
fn samples_per_elapsed(sr: SampleRate) -> f64 {
sr.as_f64() * 60.0 / TICKS_PER_QUARTER as f64
}
/// The tempo segment `i` (an index into `tempos`, 0 when it is empty): its start tick (0 for
/// the first), bpm and elapsed time at its start.
fn segment(&self, i: usize) -> (i64, f64, f64) {
let bpm = self.tempos.get(i).or(self.tempos.first()).map_or(120.0, |e| e.bpm);
let tick = if i == 0 { 0 } else { self.tempos.get(i).map_or(0, |e| e.tick) };
(tick, bpm, self.elapsed.get(i).copied().unwrap_or(0.0))
}
pub fn new(bpm: f64, numerator: u32, denominator: u32) -> Result<Self, TimeError> {
let mut m = TempoMap::default();
m.set_tempo(0, bpm)?;
m.set_meter(0, numerator, denominator)?;
Ok(m)
}
pub fn tempos(&self) -> &[TempoEvent] {
&self.tempos
}
pub fn meters(&self) -> &[MeterEvent] {
&self.meters
}
/// Repair a map read from a file: only valid tempos and meters within `0..=MAX_POSITION` ticks, in
/// tick order, with one of each at tick 0.
pub fn sanitize(&mut self) {
self.tempos.retain(|e| (0..=MAX_POSITION).contains(&e.tick) && valid_bpm(e.bpm).is_ok());
self.tempos.sort_by_key(|e| e.tick);
self.tempos.dedup_by_key(|e| e.tick);
if self.tempos.first().is_none_or(|e| e.tick > 0) {
let bpm = self.tempos.first().map_or(120.0, |e| e.bpm);
self.tempos.insert(0, TempoEvent { tick: 0, bpm });
}
self.meters.retain(|m| (0..=MAX_POSITION).contains(&m.tick) && valid_meter(m.numerator, m.denominator));
self.meters.sort_by_key(|m| m.tick);
self.meters.dedup_by_key(|m| m.tick);
if self.meters.first().is_none_or(|m| m.tick > 0) {
let (numerator, denominator) = self.meters.first().map_or((4, 4), |m| (m.numerator, m.denominator));
self.meters.insert(0, MeterEvent { tick: 0, numerator, denominator });
}
self.reindex();
}
/// Insert or replace the tempo at `tick`.
pub fn set_tempo(&mut self, tick: i64, bpm: f64) -> Result<(), TimeError> {
let bpm = valid_bpm(bpm)?;
let tick = tick.max(0);
match self.tempos.binary_search_by(|e| e.tick.cmp(&tick)) {
Ok(i) => {
if let Some(e) = self.tempos.get_mut(i) {
e.bpm = bpm;
}
}
Err(i) => self.tempos.insert(i, TempoEvent { tick, bpm }),
}
self.reindex();
Ok(())
}
/// Remove a tempo event (the one at tick 0 is kept).
pub fn remove_tempo(&mut self, tick: i64) -> bool {
if tick == 0 {
return false;
}
let before = self.tempos.len();
self.tempos.retain(|e| e.tick != tick);
self.reindex();
before != self.tempos.len()
}
/// Insert or replace the meter at `tick` (snapped to the bar line at or before it).
/// Later meter changes keep their bar numbers, so they stay on bar lines.
pub fn set_meter(&mut self, tick: i64, numerator: u32, denominator: u32) -> Result<(), TimeError> {
if !valid_meter(numerator, denominator) {
return Err(TimeError::Meter(numerator, denominator));
}
let tick = if tick <= 0 { 0 } else { self.bar_start_tick(self.bar_beat_at_tick(tick).bar) };
let later = self.take_meters_after(tick);
self.put_meter(MeterEvent { tick, numerator, denominator });
self.restore_meters_at_bars(later);
Ok(())
}
/// Remove a meter event (the one at tick 0 is kept). Later meter changes keep their bar numbers.
pub fn remove_meter(&mut self, tick: i64) -> bool {
if tick == 0 || !self.meters.iter().any(|e| e.tick == tick) {
return false;
}
let later = self.take_meters_after(tick);
self.meters.retain(|e| e.tick != tick);
self.restore_meters_at_bars(later);
true
}
fn put_meter(&mut self, ev: MeterEvent) {
match self.meters.binary_search_by(|e| e.tick.cmp(&ev.tick)) {
Ok(i) => {
if let Some(e) = self.meters.get_mut(i) {
*e = ev;
}
}
Err(i) => self.meters.insert(i, ev),
}
}
/// Remove the meters after `tick`, returning each with the bar it starts: the bar
/// [`Self::bar_beat_at_tick`] gives its tick, counted in one pass over the map rather than one
/// walk per meter, so a session with many meter changes edits in linear time.
fn take_meters_after(&mut self, tick: i64) -> Vec<(i64, MeterEvent)> {
let mut later = Vec::new();
let (mut bar, mut seg_tick) = (1i64, 0i64);
for (i, m) in self.meters.iter().enumerate() {
let tpb = m.ticks_per_bar();
if m.tick > tick {
later.push((bar.saturating_add(m.tick.saturating_sub(seg_tick) / tpb), *m));
}
if let Some(n) = self.meters.get(i + 1) {
bar = bar.saturating_add(ceil_div(n.tick.saturating_sub(seg_tick), tpb));
seg_tick = n.tick;
}
}
self.meters.retain(|e| e.tick <= tick);
later
}
/// The bar and tick of the last meter's segment, where [`Self::bar_start_tick`]'s walk ends.
fn last_segment(&self) -> (i64, i64) {
let (mut cur_bar, mut cur_tick) = (1i64, 0i64);
for (i, m) in self.meters.iter().enumerate() {
if let Some(n) = self.meters.get(i + 1) {
cur_bar = cur_bar.saturating_add(ceil_div(n.tick.saturating_sub(cur_tick), m.ticks_per_bar()));
cur_tick = n.tick;
}
}
(cur_bar, cur_tick)
}
/// Put meters back at the start of their bars under the current earlier meters, in bar order.
/// Each lands at or past the last meter, so the walk to its bar resumes from there; a bar
/// before it (meters off their bar lines) takes the full walk.
fn restore_meters_at_bars(&mut self, later: Vec<(i64, MeterEvent)>) {
let (mut cur_bar, mut cur_tick) = self.last_segment();
for (bar, ev) in later {
let tick = if bar >= cur_bar {
let tpb = self.meters.last().map_or(MeterEvent { tick: 0, numerator: 4, denominator: 4 }, |m| *m).ticks_per_bar();
cur_tick.saturating_add(bar.saturating_sub(cur_bar).saturating_mul(tpb))
} else {
self.bar_start_tick(bar)
};
self.put_meter(MeterEvent { tick, ..ev });
(cur_bar, cur_tick) = if bar >= cur_bar { (bar, tick) } else { self.last_segment() };
}
}
/// Tempo in effect at `tick`.
pub fn tempo_at_tick(&self, tick: i64) -> f64 {
let mut bpm = self.tempos.first().map_or(120.0, |e| e.bpm);
for e in &self.tempos {
if e.tick <= tick {
bpm = e.bpm;
} else {
break;
}
}
bpm
}
/// Meter in effect at `tick`.
pub fn meter_at_tick(&self, tick: i64) -> MeterEvent {
let mut m = self.meters.first().copied().unwrap_or(MeterEvent { tick: 0, numerator: 4, denominator: 4 });
for e in &self.meters {
if e.tick <= tick {
m = *e;
} else {
break;
}
}
m
}
fn samples_per_tick(bpm: f64, sr: SampleRate) -> f64 {
sr.as_f64() * 60.0 / (bpm * TICKS_PER_QUARTER as f64)
}
/// Ticks → samples (exact for constant-tempo segments).
pub fn tick_to_samples(&self, tick: i64, sr: SampleRate) -> Samples {
to_samples(self.tick_to_samples_f(tick, sr))
}
fn tick_to_samples_f(&self, tick: i64, sr: SampleRate) -> f64 {
// Tempo events after the first that start before `tick` (the segments it has passed).
let passed = self.tempos.get(1..).map_or(0, |rest| rest.partition_point(|e| e.tick < tick));
let (seg_tick, bpm, elapsed) = self.segment(passed);
elapsed * Self::samples_per_elapsed(sr) + (tick - seg_tick) as f64 * Self::samples_per_tick(bpm, sr)
}
/// Samples → ticks (fractional).
pub fn samples_to_ticks_f(&self, s: Samples, sr: SampleRate) -> f64 {
let s = s as f64;
let scale = Self::samples_per_elapsed(sr);
// Tempo events after the first that start at or before `s`.
let passed = self.elapsed.get(1..).map_or(0, |rest| rest.partition_point(|e| e * scale <= s));
let (seg_tick, bpm, elapsed) = self.segment(passed);
seg_tick as f64 + (s - elapsed * scale) / Self::samples_per_tick(bpm, sr)
}
pub fn samples_to_ticks(&self, s: Samples, sr: SampleRate) -> i64 {
to_samples(self.samples_to_ticks_f(s, sr))
}
/// Tick of the first beat of `bar` (1-based; bars before 1 extend the first meter backwards).
pub fn bar_start_tick(&self, bar: i64) -> i64 {
let mut cur_bar = 1i64;
let mut cur_tick = 0i64;
let first = self.meter_at_tick(0);
if bar < 1 {
return bar.saturating_sub(1).saturating_mul(first.ticks_per_bar());
}
for (i, m) in self.meters.iter().enumerate() {
let next_tick = self.meters.get(i + 1).map(|n| n.tick);
let tpb = m.ticks_per_bar();
let bars_in_seg = next_tick.map(|nt| ceil_div(nt.saturating_sub(cur_tick), tpb));
match bars_in_seg {
Some(n) if bar >= cur_bar.saturating_add(n) => {
cur_bar = cur_bar.saturating_add(n);
cur_tick = next_tick.unwrap_or(cur_tick);
}
_ => return cur_tick.saturating_add((bar - cur_bar).saturating_mul(tpb)),
}
}
cur_tick
}
/// Bar|beat|tick at `tick`.
pub fn bar_beat_at_tick(&self, tick: i64) -> BarBeat {
let first = self.meter_at_tick(0);
if tick < 0 {
let tpb = first.ticks_per_bar();
let abs = tick.unsigned_abs();
let tpb_u = tpb.unsigned_abs();
let bars_back_u = abs / tpb_u + u64::from(!abs.is_multiple_of(tpb_u));
let bars_back = i64::try_from(bars_back_u).unwrap_or(i64::MAX);
// Offset of `tick` inside its bar, without negating `i64::MIN`.
let within = ((tpb_u - abs % tpb_u) % tpb_u) as i64;
let beat_t = first.ticks_per_beat();
return BarBeat { bar: 1 - bars_back, beat: within / beat_t + 1, tick: within % beat_t };
}
let mut bar = 1i64;
let mut seg_tick = 0i64;
for (i, m) in self.meters.iter().enumerate() {
let tpb = m.ticks_per_bar();
if let Some(n) = self.meters.get(i + 1)
&& tick >= n.tick
{
bar = bar.saturating_add(ceil_div(n.tick.saturating_sub(seg_tick), tpb));
seg_tick = n.tick;
continue;
}
let rel = tick - seg_tick;
let bars = rel / tpb;
let within = rel % tpb;
let beat_t = m.ticks_per_beat();
return BarBeat { bar: bar + bars, beat: within / beat_t + 1, tick: within % beat_t };
}
BarBeat { bar, beat: 1, tick: 0 }
}
/// Bar|beat|tick → tick.
pub fn tick_at_bar_beat(&self, bb: BarBeat) -> i64 {
let start = self.bar_start_tick(bb.bar);
let m = self.meter_at_tick(start);
start.saturating_add(bb.beat.saturating_sub(1).max(0).saturating_mul(m.ticks_per_beat())).saturating_add(bb.tick)
}
pub fn bar_beat_at(&self, s: Samples, sr: SampleRate) -> BarBeat {
self.bar_beat_at_tick(self.samples_to_ticks(s, sr))
}
pub fn samples_at_bar_beat(&self, bb: BarBeat, sr: SampleRate) -> Samples {
self.tick_to_samples(self.tick_at_bar_beat(bb), sr)
}
/// Scale every tempo by `factor` (Tempo Operations › Scale).
pub fn scale_tempos(&mut self, factor: f64) -> Result<(), TimeError> {
let mut out = self.tempos.clone();
for e in &mut out {
e.bpm = valid_bpm(e.bpm * factor)?;
}
self.tempos = out;
self.reindex();
Ok(())
}
}
/// Ceiling division for a non-negative `num` and positive `den`, without overflow.
fn ceil_div(num: i64, den: i64) -> i64 {
num / den + i64::from(num % den != 0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_map_is_120_4_4() {
let m = TempoMap::default();
let sr = SampleRate::HZ_48000;
// One bar of 4/4 at 120 bpm = 2 seconds.
assert_eq!(m.samples_at_bar_beat(BarBeat { bar: 2, beat: 1, tick: 0 }, sr), 96_000);
assert_eq!(m.bar_beat_at(96_000, sr), BarBeat { bar: 2, beat: 1, tick: 0 });
assert_eq!(m.bar_beat_at(24_000, sr), BarBeat { bar: 1, beat: 2, tick: 0 });
}
#[test]
fn meter_near_max_tick_does_not_overflow() {
let mut m = TempoMap::default();
m.set_meter(i64::MAX, 7, 8).unwrap();
let bb = m.bar_beat_at_tick(i64::MAX);
assert!(bb.bar > 1);
assert!(m.bar_start_tick(bb.bar) > 0);
assert!(m.bar_start_tick(i64::MAX) > 0);
}
#[test]
fn minimum_bar_saturates_instead_of_overflowing() {
let m = TempoMap::default();
assert_eq!(m.bar_start_tick(i64::MIN), i64::MIN);
assert_eq!(m.bar_start_tick(0), -TICKS_PER_QUARTER * 4);
}
#[test]
fn minimum_beat_is_clamped_without_overflow() {
let m = TempoMap::default();
assert_eq!(m.tick_at_bar_beat(BarBeat { bar: 1, beat: i64::MIN, tick: 0 }), 0);
}
#[test]
fn bar_beat_at_min_tick_does_not_overflow() {
let m = TempoMap::default();
let bb = m.bar_beat_at_tick(i64::MIN);
assert!(bb.bar < 1);
assert!(bb.beat >= 1 && bb.tick >= 0);
assert_eq!(m.bar_beat_at_tick(-1).bar, 0);
}
#[test]
fn tempo_change_is_integrated() {
let mut m = TempoMap::default();
let sr = SampleRate::HZ_48000;
m.set_tempo(TICKS_PER_QUARTER * 4, 60.0).unwrap();
// Bar 1 at 120 = 96000 samples; bar 2 at 60 = 192000 samples.
assert_eq!(m.tick_to_samples(TICKS_PER_QUARTER * 8, sr), 96_000 + 192_000);
assert_eq!(m.samples_to_ticks(96_000 + 192_000, sr), TICKS_PER_QUARTER * 8);
}
#[test]
fn meter_change_counts_bars() {
let mut m = TempoMap::default();
// 2 bars of 4/4 then 3/4.
m.set_meter(TICKS_PER_QUARTER * 8, 3, 4).unwrap();
assert_eq!(m.bar_beat_at_tick(TICKS_PER_QUARTER * 8), BarBeat { bar: 3, beat: 1, tick: 0 });
assert_eq!(m.bar_beat_at_tick(TICKS_PER_QUARTER * 11), BarBeat { bar: 4, beat: 1, tick: 0 });
assert_eq!(m.bar_start_tick(4), TICKS_PER_QUARTER * 11);
let bb = BarBeat { bar: 4, beat: 2, tick: 10 };
assert_eq!(m.bar_beat_at_tick(m.tick_at_bar_beat(bb)), bb);
}
#[test]
fn editing_an_early_meter_keeps_later_bars_and_scales_linearly() {
// 200 000 meter changes, one per bar, built directly: a walk per meter would take
// minutes to edit here, and even to build through `set_meter`.
let mut m = TempoMap::new(120.0, 4, 4).unwrap();
let mut tick = 0;
for bar in 1..200_000i64 {
let numerator = 3 + (bar % 2) as u32;
tick += m.meters.last().map_or(0, MeterEvent::ticks_per_bar);
m.meters.push(MeterEvent { tick, numerator, denominator: 4 });
}
let sample = [1usize, 1_000, 199_998];
let bars = |m: &TempoMap| sample.map(|i| m.bar_beat_at_tick(m.meters[i].tick).bar);
assert_eq!(bars(&m), [2, 1_001, 199_999]);
m.set_meter(0, 7, 8).unwrap();
assert_eq!(bars(&m), [2, 1_001, 199_999], "later meters keep their bar numbers");
assert_eq!(m.meters.len(), 200_000);
assert!(m.meters.windows(2).all(|w| w[0].tick < w[1].tick));
assert!(m.remove_meter(m.meters[1].tick));
assert_eq!([1usize, 999, 199_997].map(|i| m.bar_beat_at_tick(m.meters[i].tick).bar), [3, 1_001, 199_999]);
// Meters off their bar lines (counted as bars 2 and 4) land where they always did: on
// bar 2 of the new meter, then two bars of their own later.
let mut off = TempoMap::new(120.0, 4, 4).unwrap();
off.meters.push(MeterEvent { tick: 100, numerator: 3, denominator: 4 });
off.meters.push(MeterEvent { tick: 5_000, numerator: 5, denominator: 4 });
off.set_meter(0, 2, 4).unwrap();
let placed: Vec<(i64, u32)> = off.meters.iter().map(|e| (e.tick, e.numerator)).collect();
assert_eq!(placed, vec![(0, 2), (2 * TICKS_PER_QUARTER, 3), (8 * TICKS_PER_QUARTER, 5)]);
}
#[test]
fn eighth_note_meters() {
let m = TempoMap::new(120.0, 6, 8).unwrap();
assert_eq!(m.bar_beat_at_tick(TICKS_PER_QUARTER * 3), BarBeat { bar: 2, beat: 1, tick: 0 });
assert_eq!(m.bar_beat_at_tick(TICKS_PER_QUARTER / 2), BarBeat { bar: 1, beat: 2, tick: 0 });
}
#[test]
fn sanitize_keeps_what_the_setters_accept() {
let tempo = |tick, bpm| TempoEvent { tick, bpm };
let meter = |tick, numerator, denominator| MeterEvent { tick, numerator, denominator };
let mut m = TempoMap::from_parts(
vec![tempo(960, 4e9), tempo(3840, 90.0), tempo(-5, 100.0), tempo(1920, 60.0), tempo(1920, 70.0)],
vec![meter(0, 0, 4), meter(3840, 3, 4)],
);
m.sanitize();
assert_eq!(m.tempos(), [tempo(0, 60.0), tempo(1920, 60.0), tempo(3840, 90.0)]);
assert_eq!(m.meters(), [meter(0, 3, 4), meter(3840, 3, 4)]);
let mut empty = TempoMap::from_parts(Vec::new(), Vec::new());
empty.sanitize();
assert_eq!(empty, TempoMap::default());
}
#[test]
fn sanitize_drops_events_beyond_the_position_range() {
let mut m = TempoMap::from_parts(
vec![TempoEvent { tick: 0, bpm: 120.0 }, TempoEvent { tick: i64::MAX, bpm: 90.0 }],
vec![MeterEvent { tick: 0, numerator: 4, denominator: 4 }, MeterEvent { tick: i64::MAX, numerator: 3, denominator: 4 }],
);
m.sanitize();
assert_eq!(m, TempoMap::default());
assert_eq!(m.bar_start_tick(2), TICKS_PER_QUARTER * 4);
}
#[test]
fn rejects_bad_values() {
let mut m = TempoMap::default();
assert!(m.set_tempo(0, f64::NAN).is_err());
assert!(m.set_tempo(0, 0.0).is_err());
assert!(m.set_meter(0, 0, 4).is_err());
assert!(m.set_meter(0, 4, 3).is_err());
assert!(!m.remove_tempo(0));
}
#[test]
fn negative_positions() {
let m = TempoMap::default();
assert_eq!(m.bar_beat_at_tick(-TICKS_PER_QUARTER * 4), BarBeat { bar: 0, beat: 1, tick: 0 });
assert_eq!(m.bar_beat_at_tick(-TICKS_PER_QUARTER), BarBeat { bar: 0, beat: 4, tick: 0 });
}
/// The segment walk the indexed conversions replaced, kept as the reference they must match.
fn linear_tick_to_samples(m: &TempoMap, tick: i64, sr: SampleRate) -> i64 {
let mut acc = 0.0;
let mut seg_tick = 0i64;
let mut bpm = m.tempos[0].bpm;
for e in m.tempos.iter().skip(1) {
if e.tick >= tick {
break;
}
acc += (e.tick - seg_tick) as f64 * TempoMap::samples_per_tick(bpm, sr);
seg_tick = e.tick;
bpm = e.bpm;
}
to_samples(acc + (tick - seg_tick) as f64 * TempoMap::samples_per_tick(bpm, sr))
}
#[test]
fn indexed_conversions_match_the_segment_walk() {
let sr = SampleRate::HZ_48000;
let mut m = TempoMap::default();
for i in 1..200i64 {
m.set_tempo(i * 487, 40.0 + ((i * 37) % 300) as f64).unwrap();
}
assert!(m.remove_tempo(487 * 50));
for tick in (-1000..200 * 487 + 5000).step_by(113) {
let s = m.tick_to_samples(tick, sr);
assert_eq!(s, linear_tick_to_samples(&m, tick, sr), "tick {tick}");
assert!((m.samples_to_ticks(s, sr) - tick).abs() <= 1, "tick {tick}");
}
let json = serde_json::to_string(&m).unwrap();
assert!(!json.contains("elapsed"));
let back: TempoMap = serde_json::from_str(&json).unwrap();
assert_eq!(back, m);
assert_eq!(back.tick_to_samples(150 * 487 + 3, sr), m.tick_to_samples(150 * 487 + 3, sr));
}
#[test]
fn a_file_with_wild_ticks_is_indexed_without_overflow() {
let json = r#"{"tempos":[{"tick":0,"bpm":120.0},{"tick":-9223372036854775808,"bpm":100.0},{"tick":9223372036854775807,"bpm":90.0}],"meters":[{"tick":0,"numerator":4,"denominator":4}]}"#;
let mut m: TempoMap = serde_json::from_str(json).unwrap();
m.sanitize();
assert_eq!(m.tempos().first().map(|e| e.tick), Some(0));
assert_eq!(m.elapsed.len(), m.tempos().len());
}
#[test]
fn conversions_against_a_large_tempo_map_stay_fast() {
// 200k tempo changes, then 200k conversions each way: quadratic if every conversion walks
// the earlier segments, well under a second when it binary-searches them.
let sr = SampleRate::HZ_48000;
let n = 200_000i64;
let tempos = (0..n).map(|i| TempoEvent { tick: i * 10, bpm: 60.0 + (i % 7) as f64 }).collect();
let mut m = TempoMap::from_parts(tempos, vec![MeterEvent { tick: 0, numerator: 4, denominator: 4 }]);
m.sanitize();
let start = std::time::Instant::now();
let mut sum = 0i64;
for i in 0..n {
let s = m.tick_to_samples(i * 10 + 5, sr);
sum = sum.wrapping_add(s).wrapping_add(m.samples_to_ticks(s, sr));
}
assert!(sum != 0);
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
}
}
+309
View File
@@ -0,0 +1,309 @@
//! SMPTE timecode and Feet+Frames.
use crate::{SampleRate, Samples, TimeError};
/// Session timecode rates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum FrameRate {
Fps23_976,
#[default]
Fps24,
Fps25,
Fps29_97,
Fps29_97Drop,
Fps30,
Fps47_952,
Fps48,
Fps50,
Fps59_94,
Fps59_94Drop,
Fps60,
Fps100,
Fps119_88,
Fps120,
}
impl FrameRate {
pub const ALL: [FrameRate; 15] = [
FrameRate::Fps23_976,
FrameRate::Fps24,
FrameRate::Fps25,
FrameRate::Fps29_97,
FrameRate::Fps29_97Drop,
FrameRate::Fps30,
FrameRate::Fps47_952,
FrameRate::Fps48,
FrameRate::Fps50,
FrameRate::Fps59_94,
FrameRate::Fps59_94Drop,
FrameRate::Fps60,
FrameRate::Fps100,
FrameRate::Fps119_88,
FrameRate::Fps120,
];
/// Real frames per second as a rational (num, den).
pub fn rational(self) -> (i64, i64) {
match self {
FrameRate::Fps23_976 => (24_000, 1001),
FrameRate::Fps24 => (24, 1),
FrameRate::Fps25 => (25, 1),
FrameRate::Fps29_97 | FrameRate::Fps29_97Drop => (30_000, 1001),
FrameRate::Fps30 => (30, 1),
FrameRate::Fps47_952 => (48_000, 1001),
FrameRate::Fps48 => (48, 1),
FrameRate::Fps50 => (50, 1),
FrameRate::Fps59_94 | FrameRate::Fps59_94Drop => (60_000, 1001),
FrameRate::Fps60 => (60, 1),
FrameRate::Fps100 => (100, 1),
FrameRate::Fps119_88 => (120_000, 1001),
FrameRate::Fps120 => (120, 1),
}
}
/// Frames per labelled second (the counting base).
pub fn nominal(self) -> i64 {
let (n, d) = self.rational();
(n + d / 2) / d
}
pub fn is_drop(self) -> bool {
matches!(self, FrameRate::Fps29_97Drop | FrameRate::Fps59_94Drop)
}
pub fn label(self) -> &'static str {
match self {
FrameRate::Fps23_976 => "23.976",
FrameRate::Fps24 => "24",
FrameRate::Fps25 => "25",
FrameRate::Fps29_97 => "29.97",
FrameRate::Fps29_97Drop => "29.97 Drop",
FrameRate::Fps30 => "30",
FrameRate::Fps47_952 => "47.952",
FrameRate::Fps48 => "48",
FrameRate::Fps50 => "50",
FrameRate::Fps59_94 => "59.94",
FrameRate::Fps59_94Drop => "59.94 Drop",
FrameRate::Fps60 => "60",
FrameRate::Fps100 => "100",
FrameRate::Fps119_88 => "119.88",
FrameRate::Fps120 => "120",
}
}
/// Whole frame index at a sample position (floored).
pub fn frames_at(self, s: Samples, sr: SampleRate) -> i64 {
let (n, d) = self.rational();
let num = i128::from(s) * i128::from(n);
let den = i128::from(sr.hz()) * i128::from(d);
if den == 0 {
return 0;
}
i64::try_from(num.div_euclid(den)).unwrap_or(0)
}
/// Sample position of the start of frame `f`.
pub fn samples_at_frame(self, f: i64, sr: SampleRate) -> Samples {
let (n, d) = self.rational();
if n == 0 {
return 0;
}
// Round half away from zero so negative frames mirror positive ones.
let mag = (i128::from(f.unsigned_abs()) * i128::from(sr.hz()) * i128::from(d) + i128::from(n) / 2) / i128::from(n);
let v = if f < 0 { -mag } else { mag };
i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX })
}
/// Samples per frame (fractional).
pub fn samples_per_frame(self, sr: SampleRate) -> f64 {
let (n, d) = self.rational();
sr.as_f64() * d as f64 / n as f64
}
}
/// A timecode label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Timecode {
pub negative: bool,
pub hours: i64,
pub minutes: i64,
pub seconds: i64,
pub frames: i64,
}
impl Timecode {
/// Label for an absolute frame count.
pub fn from_frames(frames: i64, rate: FrameRate) -> Timecode {
let negative = frames < 0;
// Drop-frame labels can exceed i64::MAX even when the frame count fits. Widen before
// taking the magnitude so i64::MIN is represented exactly too.
let mut f = i128::from(frames).abs();
let base = i128::from(rate.nominal().max(1));
if rate.is_drop() {
// Drop 2 (or 4) labels each minute except every tenth.
let drop = if base >= 60 { 4 } else { 2 };
let per_10min = base * 600 - drop * 9;
let per_min = base * 60 - drop;
let tens = f / per_10min;
let rem = f % per_10min;
let extra = if rem > drop { drop * 9 * tens + drop * ((rem - drop) / per_min) } else { drop * 9 * tens };
f += extra;
}
let frames_l = f % base;
let total_secs = f / base;
Timecode {
negative,
hours: i64::try_from(total_secs / 3600).unwrap_or(i64::MAX),
minutes: i64::try_from((total_secs / 60) % 60).unwrap_or(0),
seconds: i64::try_from(total_secs % 60).unwrap_or(0),
frames: i64::try_from(frames_l).unwrap_or(0),
}
}
/// Absolute frame count of this label.
pub fn to_frames(&self, rate: FrameRate) -> i64 {
let base = rate.nominal().max(1);
let total_min = i128::from(self.hours) * 60 + i128::from(self.minutes);
let mut f = (total_min * 60 + i128::from(self.seconds)) * i128::from(base) + i128::from(self.frames);
if rate.is_drop() {
let drop = if base >= 60 { 4 } else { 2 };
f -= drop * (total_min - total_min / 10);
}
let f = if self.negative { -f } else { f };
i64::try_from(f).unwrap_or(if f < 0 { i64::MIN } else { i64::MAX })
}
pub fn from_samples(s: Samples, rate: FrameRate, sr: SampleRate) -> Timecode {
Timecode::from_frames(rate.frames_at(s, sr), rate)
}
pub fn to_samples(&self, rate: FrameRate, sr: SampleRate) -> Samples {
rate.samples_at_frame(self.to_frames(rate), sr)
}
pub fn format(&self, rate: FrameRate) -> String {
let sep = if rate.is_drop() { ';' } else { ':' };
let sign = if self.negative { "-" } else { "" };
format!("{sign}{:02}:{:02}:{:02}{sep}{:02}", self.hours, self.minutes, self.seconds, self.frames)
}
/// Parse `HH:MM:SS:FF` (also `;` / `.` separators and fewer fields, right-aligned).
pub fn parse(text: &str) -> Result<Timecode, TimeError> {
let t = text.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(r) => (true, r),
None => (false, t),
};
let parts: Vec<&str> = t.split([':', ';', '.']).collect();
if parts.is_empty() || parts.len() > 4 {
return Err(TimeError::Parse(text.to_string(), "timecode"));
}
let mut nums = [0i64; 4];
let offset = 4 - parts.len();
for (i, p) in parts.iter().enumerate() {
let v: i64 = p.trim().parse().map_err(|_| TimeError::Parse(text.to_string(), "timecode"))?;
if v < 0 {
return Err(TimeError::Parse(text.to_string(), "timecode"));
}
if let Some(slot) = nums.get_mut(offset + i) {
*slot = v;
}
}
Ok(Timecode { negative, hours: nums[0], minutes: nums[1], seconds: nums[2], frames: nums[3] })
}
}
/// Feet+Frames for 35 mm film (16 frames per foot), `start` frames in at sample 0.
pub fn feet_frames(s: Samples, rate: FrameRate, sr: SampleRate, start: i64) -> (i64, i64) {
let f = rate.frames_at(s, sr).saturating_add(start);
(f.div_euclid(16), f.rem_euclid(16))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn non_drop_round_trip() {
let sr = SampleRate::HZ_48000;
let tc = Timecode::from_samples(48_000 * 3661, FrameRate::Fps25, sr);
assert_eq!(tc.format(FrameRate::Fps25), "01:01:01:00");
assert_eq!(tc.to_samples(FrameRate::Fps25, sr), 48_000 * 3661);
}
#[test]
fn negative_timecode_rounds_symmetrically() {
let sr = SampleRate::HZ_48000;
let tc = Timecode::parse("-00:00:01:00").unwrap();
assert_eq!(tc.to_samples(FrameRate::Fps25, sr), -48_000);
for r in [FrameRate::Fps25, FrameRate::Fps29_97, FrameRate::Fps29_97Drop, FrameRate::Fps23_976] {
for f in [1i64, 7, 25, 1799, 107_892] {
assert_eq!(r.samples_at_frame(-f, sr), -r.samples_at_frame(f, sr), "{r:?} frame {f}");
}
}
}
#[test]
fn drop_frame_labels() {
let r = FrameRate::Fps29_97Drop;
// Frame 1800 is the first frame of minute 1 → labelled 00:01:00;02.
assert_eq!(Timecode::from_frames(1800, r).format(r), "00:01:00;02");
assert_eq!(Timecode::from_frames(1799, r).format(r), "00:00:59;29");
// Minute 10 keeps its labels.
assert_eq!(Timecode::from_frames(17_982, r).format(r), "00:10:00;00");
for f in [0, 1, 1799, 1800, 1801, 17_981, 17_982, 107_892, 500_000] {
assert_eq!(Timecode::from_frames(f, r).to_frames(r), f, "frame {f}");
}
}
#[test]
fn huge_timecode_saturates_instead_of_overflowing() {
let sr = SampleRate::HZ_48000;
for r in [FrameRate::Fps30, FrameRate::Fps29_97Drop] {
let tc = Timecode::parse("9223372036854775807:00:00:00").unwrap();
assert_eq!(tc.to_samples(r, sr), i64::MAX);
let tc = Timecode::parse("-9223372036854775807:00:00:00").unwrap();
assert_eq!(tc.to_samples(r, sr), i64::MIN);
}
let tc = Timecode::parse("01:02:03:04").unwrap();
assert_eq!(tc.to_samples(FrameRate::Fps30, sr), 178_710_400);
}
#[test]
fn extreme_frame_counts_round_trip_at_every_rate() {
for rate in FrameRate::ALL {
for frames in [i64::MIN, i64::MIN + 1, -1, 0, 1, i64::MAX - 1, i64::MAX] {
let tc = Timecode::from_frames(frames, rate);
assert_eq!(tc.to_frames(rate), frames, "{rate:?}: {frames}");
assert_eq!(tc.negative, frames < 0);
assert!((0..60).contains(&tc.minutes));
assert!((0..60).contains(&tc.seconds));
assert!((0..rate.nominal()).contains(&tc.frames));
assert_eq!(Timecode::parse(&tc.format(rate)).unwrap(), tc);
}
}
}
#[test]
fn extreme_drop_frame_labels_do_not_overflow() {
for rate in [FrameRate::Fps29_97Drop, FrameRate::Fps59_94Drop] {
assert_eq!(Timecode::from_frames(i64::MAX, rate).to_frames(rate), i64::MAX);
}
}
#[test]
fn parse_variants() {
let tc = Timecode::parse("01:02:03:04").unwrap();
assert_eq!((tc.hours, tc.minutes, tc.seconds, tc.frames), (1, 2, 3, 4));
let tc = Timecode::parse("3:04").unwrap();
assert_eq!((tc.seconds, tc.frames), (3, 4));
assert!(Timecode::parse("a:b").is_err());
assert!(Timecode::parse("1:2:3:4:5").is_err());
}
#[test]
fn feet_and_frames() {
let sr = SampleRate::HZ_48000;
assert_eq!(feet_frames(48_000, FrameRate::Fps24, sr, 0), (1, 8));
}
}
-1
View File
@@ -8,7 +8,6 @@ rust-version = "1.95"
repository.workspace = true
[dependencies]
craft-mime.workspace = true
craft-ui.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
File diff suppressed because it is too large Load Diff
-2
View File
@@ -139,7 +139,6 @@ impl SoundApp {
/// Each host iteration starts with `raw_input_hook`; its editor-poll admission prevents an
/// empty queue on a discarded pass from ending a still-active plugin gesture.
pub fn logic(&mut self, ctx: &egui::Context) {
let _language = crate::localization::enter(self.ui.language);
self.ui.undo_levels = self.ui.undo_levels.clamp(1, 64);
self.engine.set_history_limit(self.ui.undo_levels);
// Fonts set now take effect next frame, so draw only from the frame after.
@@ -245,7 +244,6 @@ impl SoundApp {
/// Lay out the whole window.
pub fn ui(&mut self, ui: &mut egui::Ui) {
let _language = crate::localization::enter(self.ui.language);
let ctx = ui.ctx().clone();
// egui just processed the scripted key events. A scripted release while the host still
// physically holds the key would report it up; put the host-only state back before any
+16 -20
View File
@@ -13,7 +13,7 @@ impl SoundApp {
/// then stays the configuration of the open device.
pub fn apply_audio_config(&mut self, cfg: soundcraft_playback::AudioConfig) -> Result<(), String> {
if self.engine.transport.recording {
return Err(crate::localization::text("stop recording before changing the audio device").into());
return Err("stop recording before changing the audio device".into());
}
self.ui.audio = cfg;
let at = self.position();
@@ -46,7 +46,7 @@ impl SoundApp {
}
Err(e) => {
self.recorder_failed = true;
self.ui.status = crate::localized_format!("No audio input: {e}", e = e);
self.ui.status = format!("No audio input: {e}");
}
}
}
@@ -58,28 +58,24 @@ impl SoundApp {
let name = p.device_name.clone();
let (cause, then) = match trouble {
OutputTrouble::Bug => (
crate::localization::text("the audio engine hit an internal error (see the log)").to_string(),
crate::localization::text("Use Reconnect audio device in Setup › Playback Engine, or restart SoundCraft."),
),
OutputTrouble::Gone => (
format!("“{}” {}", name, crate::localization::text("is unavailable")),
crate::localization::text("Check the audio device, then use Reconnect audio device in Setup › Playback Engine."),
),
OutputTrouble::Stalled => (
format!("“{}” {}", name, crate::localization::text("stopped asking for audio")),
crate::localization::text("Use Reconnect audio device in Setup › Playback Engine."),
"the audio engine hit an internal error (see the log)".to_string(),
"Use Reconnect audio device in Setup › Playback Engine, or restart SoundCraft.",
),
OutputTrouble::Gone => {
(format!("“{name}” is unavailable"), "Check the audio device, then use Reconnect audio device in Setup › Playback Engine.")
}
OutputTrouble::Stalled => (format!("“{name}” stopped asking for audio"), "Use Reconnect audio device in Setup › Playback Engine."),
};
let (recording, playing) = (self.engine.transport.recording, self.engine.transport.playing);
if recording || playing {
self.stop_play();
}
self.ui.status = if recording {
crate::localized_format!("Recording stopped: {cause} The take is kept up to there. {then}", cause = cause, then = then)
format!("Recording stopped: {cause}. The take is kept up to there. {then}")
} else if playing {
crate::localized_format!("Playback stopped: {cause} {then}", cause = cause, then = then)
format!("Playback stopped: {cause}. {then}")
} else {
crate::localized_format!("Audio output: {cause} {then}", cause = cause, then = then)
format!("Audio output: {cause}. {then}")
};
}
@@ -92,7 +88,7 @@ impl SoundApp {
let lost = r.lost_ms();
if recording && lost > self.lost_shown {
self.lost_shown = lost;
self.ui.status = crate::localized_format!("The disk is too slow: this take has lost {lost} ms of input so far.", lost = lost);
self.ui.status = format!("The disk is too slow: this take has lost {lost} ms of input so far.");
}
return;
};
@@ -103,14 +99,14 @@ impl SoundApp {
Trouble::Device(what) => {
self.recorder = None;
self.recorder_failed = true;
(what, crate::localization::text("Reconnect it, then use Reconnect audio device in Setup › Playback Engine."))
(what, "Reconnect it, then use Reconnect audio device in Setup › Playback Engine.")
}
Trouble::Disk(what) => (what, crate::localization::text("Check the disk, then record again.")),
Trouble::Disk(what) => (what, "Check the disk, then record again."),
};
self.ui.status = if recording {
crate::localized_format!("Recording stopped: {what} The take is kept up to there. {then}", what = what, then = then)
format!("Recording stopped: {what}. The take is kept up to there. {then}")
} else {
crate::localized_format!("Audio input: {what} {then}", what = what, then = then)
format!("Audio input: {what}. {then}")
};
}
+1 -2
View File
@@ -3,7 +3,6 @@ use super::{SoundApp, Value, bounce, menus};
impl SoundApp {
/// Run a command; errors go to the status line. Returns the result.
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
let _language = crate::localization::enter(self.ui.language);
if matches!(id, "session.new" | "session.open" | "session.close" | "session.revert") && bounce::refuses_session_switch(self) {
return Err(self.ui.status.clone());
}
@@ -40,7 +39,7 @@ impl SoundApp {
Ok(v)
}
Err(e) => {
self.ui.status = crate::localization::error_text(&e.to_string());
self.ui.status = e.to_string();
log::warn!("{id}: {e}");
Err(e.to_string())
}
+8 -15
View File
@@ -34,7 +34,7 @@ impl SoundApp {
/// plugins' own state reaches the session every two minutes (`autosave`).
pub(super) fn autosave_changes(&mut self) {
if let Some(e) = self.autosaver.as_ref().and_then(soundcraft_engine::autosave::Autosaver::failure) {
self.ui.status = crate::localized_format!("Autosave failed: {e}", e = e);
self.ui.status = format!("Autosave failed: {e}");
}
if self.autosave_dir.is_none() || self.engine.revision == self.autosaved_rev {
return;
@@ -60,7 +60,7 @@ impl SoundApp {
let Some(w) = &self.autosaver else { return false };
let written = w.flush();
if let Err(e) = &written {
self.ui.status = crate::localized_format!("Autosave failed: {e}", e = e);
self.ui.status = format!("Autosave failed: {e}");
}
written.is_ok()
}
@@ -105,19 +105,16 @@ impl SoundApp {
self.panic_rev = self.engine.revision;
let saved = self.engine.is_dirty() && self.write_autosave();
self.ui.status = if saved {
crate::localization::text(
"SoundCraft hit an internal error (see the log). Your changes were autosaved: save them, then restart SoundCraft.",
)
.into()
"SoundCraft hit an internal error (see the log). Your changes were autosaved: save them, then restart SoundCraft.".into()
} else {
crate::localization::text("SoundCraft hit an internal error (see the log). Restart SoundCraft to be safe.").into()
"SoundCraft hit an internal error (see the log). Restart SoundCraft to be safe.".into()
};
}
/// Replace the open session with unsaved work an earlier run left behind.
pub fn recover(&mut self, left: &soundcraft_engine::autosave::Leftover) {
if self.engine.transport.recording {
self.ui.status = crate::localization::text("Stop recording before recovering other work.").into();
self.ui.status = "Stop recording before recovering other work.".into();
return;
}
self.close_autosave();
@@ -128,15 +125,11 @@ impl SoundApp {
soundcraft_engine::autosave::discard(left);
}
self.ui.status = match missing.len() {
0 => crate::localized_format!("Recovered “{name}”. Save it to keep the changes.", name = left.name),
n => crate::localized_format!(
"Recovered “{name}”, but {n} audio file(s) are missing. Save it to keep the changes.",
name = left.name,
n = n
),
0 => format!("Recovered “{}”. Save it to keep the changes.", left.name),
n => format!("Recovered “{}”, but {n} audio file(s) are missing. Save it to keep the changes.", left.name),
};
}
Err(e) => self.ui.status = crate::localized_format!("Couldn't recover “{name}”: {e}", name = left.name, e = e),
Err(e) => self.ui.status = format!("Couldn't recover “{}”: {e}", left.name),
}
}
+1 -1
View File
@@ -153,7 +153,7 @@ impl SoundApp {
let r = self.run("mix.sampler_load", json!({"track": track.0, "path": path}));
self.sample_loaded(track, path, r);
}
Err(e) => self.ui.status = crate::localization::error_text(&e.to_string()),
Err(e) => self.ui.status = e.to_string(),
}
} else {
self.sample_reads.push(sampler_window::SampleRead { track, file });
+7 -10
View File
@@ -92,9 +92,9 @@ impl SoundApp {
let armed = self.engine.session().tracks.iter().any(|t| t.mixer.record_arm);
if !armed {
let why = if self.engine.session().tracks.is_empty() {
crate::localization::text("Nothing to record on yet: add a track with Track › New…, then click its R button.")
"Nothing to record on yet: add a track with Track › New…, then click its R button."
} else {
crate::localization::text("No track is record-enabled: click the R button on the track to record.")
"No track is record-enabled: click the R button on the track to record."
};
self.ui.status = why.into();
self.record_hint = Some((self.last_frame.unwrap_or_default(), why));
@@ -104,7 +104,7 @@ impl SoundApp {
let takes = match self.arm_recorder() {
Ok(takes) => takes,
Err(err) => {
self.ui.status = crate::localized_format!("Cannot record: {err}", err = err);
self.ui.status = format!("Cannot record: {err}");
return;
}
};
@@ -163,10 +163,10 @@ impl SoundApp {
None if self.engine.path.is_some() => std::path::PathBuf::new(),
None => self.fallback_take_dir()?,
};
let Some(r) = &mut self.recorder else { return Err(crate::localization::text("no audio input device").into()) };
let Some(r) = &mut self.recorder else { return Err("no audio input device".into()) };
let plan = soundcraft_engine::io::plan_takes(&self.engine, &unsaved_dir, r.channels);
if plan.is_empty() {
return Err(crate::localization::text("no audio track is record-enabled").into());
return Err("no audio track is record-enabled".into());
}
// The takes are unsaved work: on Unix the folder they go into is owner-only, like the
// autosaves, before the recorder makes anything in it (other systems get the folder's
@@ -216,11 +216,8 @@ impl SoundApp {
self.punch = None;
self.autosaved_rev = 0;
let ids = soundcraft_engine::io::place_recording(&mut self.engine, &plan, takes);
self.ui.status = if plan.pass.is_some() {
crate::localized_format!("Loop-recorded {} take(s)", ids.len() / tracks)
} else {
crate::localized_format!("Recorded {} clip(s)", ids.len())
};
self.ui.status =
if plan.pass.is_some() { format!("Loop-recorded {} take(s)", ids.len() / tracks) } else { format!("Recorded {} clip(s)", ids.len()) };
if let Some(p) = problem {
log::warn!("recording: {p}");
self.ui.status = format!("{} ({p})", self.ui.status);
+2 -10
View File
@@ -75,11 +75,7 @@ impl SoundApp {
{
match p.open_editor(track, slot) {
Ok(()) => return,
Err(e) => {
let name = mix_window::plugin_info(&plugin).map_or(plugin.as_str(), |i| i.name);
let reason = crate::localization::error_text(&e.to_string());
self.ui.status = format!("{name}: {reason}");
}
Err(e) => self.ui.status = format!("{}: {e}", mix_window::plugin_info(&plugin).map_or(plugin.as_str(), |i| i.name)),
}
}
if !self.ui.plugin_windows.contains(&(track, slot)) {
@@ -134,9 +130,5 @@ pub(crate) fn failed_plugin_status(s: &soundcraft_model::Session, track: TrackId
let t = s.track(track)?;
let ins = if slot == soundcraft_mix::INSTRUMENT_SLOT { t.instrument.as_ref() } else { t.mixer.inserts.get(slot)?.as_ref() }?;
let name = crate::mix_window::plugin_info(&ins.plugin).map_or(ins.plugin.as_str(), |p| p.name);
Some(crate::localized_format!(
"{name} on {track} put out invalid audio, so it is bypassed until playback stops or starts again.",
name = name,
track = t.name
))
Some(format!("{name} on {} put out invalid audio, so it is bypassed until playback stops or starts again.", t.name))
}
+8 -13
View File
@@ -8,14 +8,14 @@ use serde_json::Value;
/// Starts the bounce `file.bounce_mix` runs for `params`; [`step`] renders it.
pub fn start(app: &mut SoundApp, params: &Value) {
if app.bounce.is_some() {
app.ui.status = crate::localization::text("A bounce is already running").into();
app.ui.status = "A bounce is already running".into();
return;
}
// Third-party plugins keep state the session can't see: store it first.
app.capture_plugin_states();
match soundcraft_engine::cmd::bounce_job(&app.engine, params) {
Ok(job) => app.bounce = Some(job),
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
Err(e) => app.ui.status = e.to_string(),
}
}
@@ -29,14 +29,9 @@ pub fn step(app: &mut SoundApp, ctx: &egui::Context) {
return;
}
Ok(Some(done)) => {
crate::localized_format!(
"Bounced {} (peak {:.1} dBFS, {:.1} LUFS)",
job.path().file_name().unwrap_or_default().to_string_lossy(),
done.peak_db,
done.lufs
)
format!("Bounced {} (peak {:.1} dBFS, {:.1} LUFS)", job.path().file_name().unwrap_or_default().to_string_lossy(), done.peak_db, done.lufs)
}
Err(e) => crate::localization::error_text(&e.to_string()),
Err(e) => e.to_string(),
};
app.bounce = None;
}
@@ -45,7 +40,7 @@ pub fn step(app: &mut SoundApp, ctx: &egui::Context) {
/// out of memory. True when refused; the status line says why.
pub fn refuses_session_switch(app: &mut SoundApp) -> bool {
if app.bounce.is_some() {
app.ui.status = crate::localization::text("Finish or cancel the bounce first").into();
app.ui.status = "Finish or cancel the bounce first".into();
}
app.bounce.is_some()
}
@@ -75,15 +70,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);
ui.set_width(320.0);
let name = job.path().file_name().unwrap_or_default().to_string_lossy();
ui.label(egui::RichText::new(crate::localized_format!("Bouncing {name}", name = name)).font(bold(13.0)));
ui.label(egui::RichText::new(format!("Bouncing {name}")).font(bold(13.0)));
ui.add(egui::ProgressBar::new(job.progress()));
ui.horizontal(|ui| {
cancel |= ui.button(crate::localization::text("Cancel")).clicked();
cancel |= ui.button("Cancel").clicked();
ui.label(egui::RichText::new(format!("{:.0}%", job.progress() * 100.0)).color(Tokens::current().text_dim));
});
});
if cancel {
app.bounce = None;
app.ui.status = crate::localization::text("Bounce cancelled").into();
app.ui.status = "Bounce cancelled".into();
}
}
+18 -2
View File
@@ -824,8 +824,24 @@ fn encode(img: &egui::ColorImage, path: Option<&str>, token: u64) -> Value {
}
}
/// Standard padded Base64 without line wrapping, shared across Craft apps.
pub use craft_mime::transfer::base64;
/// Minimal base64 (standard alphabet) to avoid another dependency.
pub fn base64(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for i in 0..4 {
if i <= chunk.len() {
let idx = ((n >> (18 - 6 * i)) & 63) as usize;
out.push(char::from(T.get(idx).copied().unwrap_or(b'A')));
} else {
out.push('=');
}
}
}
out
}
#[cfg(test)]
mod tests;
-16
View File
@@ -899,19 +899,3 @@ fn scroll_reports_the_wheel_and_trackpad_sources_after_delivery() {
let v = reply.try_recv().expect("trackpad scroll replies after its events were applied");
assert_eq!(v["result"]["source"], "trackpad");
}
#[test]
fn shared_base64_retains_control_wire_bytes() {
assert_eq!(super::base64(b""), "");
assert_eq!(super::base64(b"f"), "Zg==");
assert_eq!(super::base64(b"fo"), "Zm8=");
assert_eq!(super::base64(b"foo"), "Zm9v");
assert_eq!(super::base64(&[251, 255, 255]), "+///");
let bytes: Vec<u8> = (0..=255).cycle().take(513).collect();
for len in 0..=bytes.len() {
let encoded = super::base64(&bytes[..len]);
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
assert!(!encoded.contains(['\r', '\n']));
assert_eq!(craft_mime::base64::STANDARD.decode(&encoded).unwrap(), bytes[..len]);
}
}
+17 -18
View File
@@ -123,7 +123,7 @@ impl Contributor {
/// One line with everything we know, for tooltips.
pub fn summary(&self) -> String {
crate::localized_format!(
format!(
"@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}",
self.login,
self.prs,
@@ -213,31 +213,31 @@ impl Default for View {
/// Controls for name style, sort key and sort direction above the contributor table.
fn contributors_toolbar(ui: &mut egui::Ui, v: &mut View) {
ui.horizontal_wrapped(|ui| {
ui.label(crate::localization::text("Show"));
ui.label("Show");
for m in NameMode::ALL {
if ui.selectable_label(v.names == m, crate::localization::text(m.label())).clicked() {
if ui.selectable_label(v.names == m, m.label()).clicked() {
v.names = m;
}
}
ui.separator();
let sort = ui.label(crate::localization::text("Sort"));
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::localization::text(v.key.label().0)).show_ui(ui, |ui| {
let sort = ui.label("Sort");
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, crate::localization::text(k.label().0)).clicked() {
if ui.selectable_label(v.key == k, k.label().0).clicked() {
v.key = k;
v.ascending = k.default_ascending();
}
}
});
combo.response.labelled_by(sort.id);
if ui.button(if v.ascending { "⏶" } else { "⏷" }).on_hover_text(crate::localization::text("Reverse the order")).clicked() {
if ui.button(if v.ascending { "⏶" } else { "⏷" }).on_hover_text("Reverse the order").clicked() {
v.ascending = !v.ascending;
}
ui.separator();
if ui.selectable_label(!v.table, crate::localization::text("Grab bag")).clicked() {
if ui.selectable_label(!v.table, "Grab bag").clicked() {
v.table = false;
}
if ui.selectable_label(v.table, crate::localization::text("Table")).clicked() {
if ui.selectable_label(v.table, "Table").clicked() {
v.table = true;
}
});
@@ -247,7 +247,7 @@ fn contributors_grab_bag(ui: &mut egui::Ui, list: &[&Contributor], names: NameMo
ui.horizontal_wrapped(|ui| {
for (i, c) in list.iter().enumerate() {
if i > 0 {
ui.label(RichText::new(crate::localization::text("·")).weak());
ui.label(RichText::new("·").weak());
}
ui.hyperlink_to(c.name(names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary());
}
@@ -260,10 +260,10 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
let mut v = ui.data_mut(|d| d.get_temp::<View>(id)).unwrap_or_default();
contributors_toolbar(ui, &mut v);
let list = sorted(CONTRIBUTORS, v.names, v.key, v.ascending);
ui.label(RichText::new(crate::localized_format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().weak());
ui.label(RichText::new(format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().weak());
ui.separator();
if list.is_empty() {
ui.label(crate::localization::text("No contributor data was built into this copy."));
ui.label("No contributor data was built into this copy.");
} else if v.table {
// The table scrolls vertically itself, under a fixed header; it only scrolls sideways
// once its columns are dragged wider than the dialog.
@@ -372,7 +372,7 @@ fn cells(c: &Contributor) -> [String; 9] {
/// A contributor-table header. The sorted column is highlighted; its direction shows on the
/// toolbar's sort-order button, so no arrow widens the column.
fn header_text(k: SortKey) -> RichText {
RichText::new(crate::localization::text(k.label().1)).strong()
RichText::new(k.label().1).strong()
}
fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
@@ -390,8 +390,7 @@ fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
.header(h + 4.0, |mut header| {
for k in SortKey::ALL {
header.col(|ui| {
let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k)))
.on_hover_text(crate::localization::text(k.label().0));
let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))).on_hover_text(k.label().0);
if r.clicked() {
if v.key == k {
@@ -424,7 +423,7 @@ fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
/// About ▸ Models: AI models credited in Co-Authored-By trailers.
pub fn models_ui(ui: &mut egui::Ui) {
if MODELS.is_empty() {
ui.label(crate::localization::text("No model credits were built into this copy."));
ui.label("No model credits were built into this copy.");
return;
}
let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1);
@@ -448,14 +447,14 @@ pub fn models_ui(ui: &mut egui::Ui) {
let widths: Vec<f32> = titles
.iter()
.enumerate()
.map(|(i, title)| natural(ui, RichText::new(crate::localization::text(title)).strong(), rows.iter().filter_map(|r| r.get(i).cloned())))
.map(|(i, title)| natural(ui, RichText::new(*title).strong(), rows.iter().filter_map(|r| r.get(i).cloned())))
.collect();
egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| {
fitted_table(ui, "credits_models", &widths, &MODEL_GROW)
.header(h + 4.0, |mut header| {
for (title, r) in titles.into_iter().zip(right) {
header.col(|ui| {
aligned(ui, r, |ui| ui.label(RichText::new(crate::localization::text(title)).strong()));
aligned(ui, r, |ui| ui.label(RichText::new(title).strong()));
});
}
})
+92 -169
View File
@@ -82,8 +82,6 @@ pub struct Dialogs {
strip_values: StripValues,
/// The Strip Silence rectangles the Edit window draws while Strip Silence is open.
strip_rectangles: StripRectangles,
/// True while a dialog was drawn on the previous frame.
shown: bool,
}
impl Dialogs {
@@ -117,25 +115,22 @@ impl Dialogs {
/// Whether a worker thread is finding Strip Silence rectangles.
pub fn strip_scan_running(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
self.strip_rectangles.running.is_some()
}
#[cfg(target_arch = "wasm32")]
{
false
if self.strip_rectangles.running.is_some() {
return true;
}
false
}
pub fn open_rename_track(&mut self, id: TrackId, name: &str) {
self.set(Dialog::RenameTrack { id, name: name.to_string() });
self.open = Some(Dialog::RenameTrack { id, name: name.to_string() });
}
pub fn open_rename_clip(&mut self, id: ClipId, name: &str) {
self.set(Dialog::RenameClip { id, name: name.to_string() });
self.open = Some(Dialog::RenameClip { id, name: name.to_string() });
}
pub fn open_rename_marker(&mut self, id: soundcraft_model::MarkerId, name: &str) {
self.set(Dialog::RenameMarker { id, name: name.to_string() });
self.open = Some(Dialog::RenameMarker { id, name: name.to_string() });
}
/// Groups list › Modify Group…: the creation dialog, pre-filled from an existing group. False
@@ -144,31 +139,24 @@ impl Dialogs {
let s = e.session();
let Some(g) = s.group(id) else { return false };
let members = s.tracks.iter().map(|t| (t.id.0, t.name.clone(), g.members.contains(&t.id))).collect();
self.set(Dialog::Group { id: Some(id), name: g.name.clone(), edit: g.edit, mix: g.mix, members });
self.open = Some(Dialog::Group { id: Some(id), name: g.name.clone(), edit: g.edit, mix: g.mix, members });
true
}
/// Clip List › Clear: confirm before clips and files leave the session. False when there is nothing to clear.
pub fn open_clear(&mut self, e: &Engine, clips: Vec<ClipId>, sources: Vec<SourceId>) -> bool {
let Some(message) = clear_message(e.session(), &clips, &sources) else { return false };
self.set(Dialog::ClearClips { clips, sources, message });
self.open = Some(Dialog::ClearClips { clips, sources, message });
true
}
/// Opens `d` in place of any open dialog. Its first frame clears the keyboard focus and ignores Enter, as for a
/// dialog opened when none was open.
pub(crate) fn set(&mut self, d: Dialog) {
self.open = Some(d);
self.shown = false;
}
/// Clip List › Auto Rename: the clips' naming scheme, filled in from the first clip's. False
/// when none of the clips is in the session.
pub fn open_auto_rename(&mut self, e: &Engine, clips: Vec<ClipId>) -> bool {
let s = e.session();
let Some((_, first)) = clips.iter().find_map(|id| s.find_clip(*id)) else { return false };
let names = first.auto_name.and_then(|k| s.auto_names.get(&k)).map_or_else(StripNames::default, StripNames::from);
self.set(Dialog::AutoRename { clips, names });
self.open = Some(Dialog::AutoRename { clips, names });
true
}
@@ -177,7 +165,7 @@ impl Dialogs {
self.after_save = None;
let home = default_dir();
let name = e.session().name.clone();
let d = match id {
self.open = Some(match id {
"clip.clear" => {
let ed = &e.session().edit;
return self.open_clear(e, ed.selected_clips.clone(), ed.selected_sources.clone());
@@ -258,8 +246,7 @@ impl Dialogs {
Some(d) => d,
None => return false,
},
};
self.set(d);
});
true
}
}
@@ -268,43 +255,33 @@ fn clear_message(s: &Session, clips: &[ClipId], sources: &[SourceId]) -> Option<
let listed: std::collections::BTreeSet<ClipId> = clips.iter().copied().collect();
let names: Vec<&str> = s.tracks.iter().flat_map(|t| t.clips()).filter(|c| listed.contains(&c.id)).map(|c| c.name.as_str()).collect();
let files: Vec<_> = sources.iter().filter_map(|id| s.source(*id)).collect();
let count = |n: usize, what: &str| {
if n == 1 { crate::localized_format!("1 {what}", what = what) } else { crate::localized_format!("{n} {what}s", n = n, what = what) }
};
let count = |n: usize, what: &str| if n == 1 { format!("1 {what}") } else { format!("{n} {what}s") };
let what = match (names.as_slice(), files.as_slice()) {
([], []) => return None,
([name], []) => crate::localized_format!("the clip \"{name}\"", name = name),
([], [f]) => crate::localized_format!("the file \"{name}\"", name = f.name),
(c, []) => count(c.len(), crate::localization::text("clip")),
([], f) => count(f.len(), crate::localization::text("file")),
(c, f) => crate::localized_format!(
"{clips} and {files}",
clips = count(c.len(), crate::localization::text("clip")),
files = count(f.len(), crate::localization::text("file"))
),
([name], []) => format!("the clip \"{name}\""),
([], [f]) => format!("the file \"{}\"", f.name),
(c, []) => count(c.len(), "clip"),
([], f) => count(f.len(), "file"),
(c, f) => format!("{} and {}", count(c.len(), "clip"), count(f.len(), "file")),
};
let mut text = crate::localized_format!("Remove {what} from the session?", what = what);
let mut text = format!("Remove {what} from the session?");
let used: Vec<(&str, usize)> =
files.iter().map(|f| (f.name.as_str(), s.clips_using(f.id).filter(|c| !listed.contains(&c.id)).count())).filter(|(_, n)| *n > 0).collect();
let n: usize = used.iter().map(|u| u.1).sum();
let users = if n == 1 {
crate::localization::text("a clip on the timeline, which is removed too.").to_owned()
"a clip on the timeline, which is removed too.".to_string()
} else {
crate::localized_format!("{n} clips on the timeline, which are removed too.", n = n)
format!("{n} clips on the timeline, which are removed too.")
};
match used.as_slice() {
[] => {}
[_] if files.len() == 1 => text += &crate::localized_format!(" It is used by {users}", users = users),
u if u.len() == files.len() => text += &crate::localized_format!(" They are used by {users}", users = users),
[(name, _)] => text += &crate::localized_format!(" \"{name}\" is used by {users}", name = name, users = users),
many => text += &crate::localized_format!(" {n} of the files are used by {users}", n = many.len(), users = users),
[_] if files.len() == 1 => text += &format!(" It is used by {users}"),
u if u.len() == files.len() => text += &format!(" They are used by {users}"),
[(name, _)] => text += &format!(" \"{name}\" is used by {users}"),
many => text += &format!(" {} of the files are used by {users}", many.len()),
}
if !files.is_empty() && files.iter().all(|f| !f.unsaved) {
text += if files.len() == 1 {
crate::localization::text(" The file stays on disk.")
} else {
crate::localization::text(" The files stay on disk.")
};
text += if files.len() == 1 { " The file stays on disk." } else { " The files stay on disk." };
}
Some(text)
}
@@ -321,10 +298,10 @@ pub fn bounce_path(path: &str, format: EncodeFormat) -> std::path::PathBuf {
/// The Bounce form's file row: a path field and a Browse button that also picks the format.
fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, format: &mut EncodeFormat) {
ui.horizontal(|ui| {
ui.label(crate::localization::text("File"));
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("File"));
ui.label("File");
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "File");
if let Some(pick) = &app.services.pick_save
&& ui.button(crate::localization::text("Browse…")).clicked()
&& ui.button("Browse…").clicked()
&& let Some(p) = pick("file.bounce_mix", std::path::Path::new(path.as_str()))
{
match unicode(&p) {
@@ -334,7 +311,7 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
*format = picked;
}
}
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
Err(e) => app.ui.status = e.to_string(),
}
}
});
@@ -342,60 +319,42 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
/// The path prompt's form; the command to run once it is confirmed.
fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut String, key: &str, enter: bool) -> Option<(String, Value)> {
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("Path"));
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), "Path");
let mut picked = None;
// Import Audio picks several files at once; every other open dialog takes one.
let multi = cmd == "file.import_audio" && app.services.pick_open_many.is_some();
if multi
&& let Some(pick) = &app.services.pick_open_many
&& ui.button(crate::localization::text("Browse…")).clicked()
{
let mut files = pick(cmd);
if files.len() > 1 {
let texts: Result<Vec<&str>, _> = files.iter().map(|f| unicode(f)).collect();
match texts {
Ok(texts) => return Some((cmd.to_string(), json!({"paths": texts}))),
Err(e) => app.ui.status = crate::localization::error_text(&e.to_string()),
}
} else {
picked = files.pop();
}
}
if let Some(pick) = &app.services.pick_open
&& !multi
&& cmd != "session.save_as"
&& cmd != "session.save_copy"
&& key != "dir"
&& ui.button(crate::localization::text("Browse…")).clicked()
&& ui.button("Browse…").clicked()
&& let Some(p) = pick(cmd, &[])
{
picked = Some(p);
}
if let Some(pick) = &app.services.pick_folder
&& key == "dir"
&& ui.button(crate::localization::text("Browse…")).clicked()
&& ui.button("Browse…").clicked()
&& let Some(p) = pick(std::path::Path::new(path.as_str()))
{
picked = Some(p);
}
if let Some(pick) = &app.services.pick_save
&& (cmd == "session.save_as" || cmd == "session.save_copy")
&& ui.button(crate::localization::text("Browse…")).clicked()
&& ui.button("Browse…").clicked()
&& let Some(p) = pick(cmd, std::path::Path::new(path.as_str()))
{
picked = Some(p);
}
match picked.as_deref().map(unicode) {
Some(Ok(text)) => *path = text.to_owned(),
Some(Err(e)) => app.ui.status = crate::localization::error_text(&e.to_string()),
Some(Err(e)) => app.ui.status = e.to_string(),
None => {}
}
let file = soundcraft_engine::io::session_file(path);
let replaces = soundcraft_engine::io::replaces(&app.engine, cmd, &file);
if replaces {
ui.label(crate::localized_format!("“{}” already exists. Do you want to replace it?", file.file_name().unwrap_or_default().to_string_lossy()));
ui.label(format!("“{}” already exists. Do you want to replace it?", file.file_name().unwrap_or_default().to_string_lossy()));
}
if buttons(ui, crate::localization::text(if replaces { "Replace" } else { "OK" }), enter && !replaces) {
if buttons(ui, if replaces { "Replace" } else { "OK" }, enter && !replaces) {
let mut v = json!({});
v[key] = json!(path);
if replaces {
@@ -417,10 +376,10 @@ fn strip_silence_form(
let mut rename_from = None;
let [threshold, min_ms, pre_ms, post_ms] = values;
let before = [*threshold, *min_ms, *pre_ms, *post_ms];
crate::widgets::fine_slider(ui, threshold, -96.0..=0.0, crate::localization::text("Threshold dB"));
crate::widgets::fine_slider(ui, min_ms, 0.0..=4000.0, crate::localization::text("Min strip duration ms"));
crate::widgets::fine_slider(ui, pre_ms, 0.0..=500.0, crate::localization::text("Clip start pad ms"));
crate::widgets::fine_slider(ui, post_ms, 0.0..=2000.0, crate::localization::text("Clip end pad ms"));
ui.add(egui::Slider::new(threshold, -96.0..=0.0).text("Threshold dB"));
ui.add(egui::Slider::new(min_ms, 0.0..=4000.0).text("Min strip duration ms"));
ui.add(egui::Slider::new(pre_ms, 0.0..=500.0).text("Clip start pad ms"));
ui.add(egui::Slider::new(post_ms, 0.0..=2000.0).text("Clip end pad ms"));
let values = [*threshold, *min_ms, *pre_ms, *post_ms];
// The Edit window is drawn before this window, so it draws the rectangles for new values in the next frame.
if values != before {
@@ -434,13 +393,13 @@ fn strip_silence_form(
ui.horizontal(|ui| {
let mut mode = None;
let mut rename = false;
if ui.button(crate::localization::text("Extract")).clicked() {
if ui.button("Extract").clicked() {
mode = Some("extract");
}
if ui.button(crate::localization::text("Rename…")).clicked() {
if ui.button("Rename…").clicked() {
rename = true;
}
if ui.button(crate::localization::text("Separate")).clicked() {
if ui.button("Separate").clicked() {
mode = Some("separate");
}
// Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked.
@@ -466,16 +425,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
if !matches!(app.dialogs.open, Some(Dialog::StripSilence { .. } | Dialog::StripSilenceRename { .. })) {
app.dialogs.strip_rectangles = StripRectangles::default();
}
let Some(mut d) = app.dialogs.open.take() else {
app.dialogs.shown = false;
return;
};
// On the first frame a dialog is drawn, clear the keyboard focus a widget outside it may still hold, and ignore Enter:
// an Enter in that frame is the one that opened the dialog from a menu item or the command palette.
let first_frame = !std::mem::replace(&mut app.dialogs.shown, true);
if first_frame {
ctx.memory_mut(|m| m.stop_text_input());
}
let Some(mut d) = app.dialogs.open.take() else { return };
let mut keep = true;
let mut action: Option<(String, Value)> = None;
let mut bounce_params: Option<Value> = None;
@@ -508,14 +458,9 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::SaveChanges { .. } => "Unsaved Changes",
}
.to_string();
// egui treats Enter on a focused button, checkbox, radio button or combo box as a click, so Enter presses the default
// button only when no widget has the keyboard focus or a text field has it. A held Enter's repeats do not press it.
let fresh_enter =
|i: &egui::InputState| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }));
let enter = !first_frame && ctx.input(fresh_enter) && (ctx.memory(|m| m.focused().is_none()) || ctx.text_edit_focused());
let enter = ctx.input(|i| i.key_pressed(egui::Key::Enter));
let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape));
egui::Window::new(egui::RichText::new(crate::localization::text(&title)).font(bold(13.0)))
.id(egui::Id::unique(&title))
egui::Window::new(egui::RichText::new(&title).font(bold(13.0)))
.collapsible(false)
.resizable(false)
.anchor(Align2::CENTER_CENTER, vec2(0.0, -80.0))
@@ -533,15 +478,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
Dialog::NewSession { name, sample_rate, demo } => {
ui.horizontal(|ui| {
ui.label(crate::localization::text("Name"));
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
ui.label("Name");
crate::widgets::named_text_field(ui.text_edit_singleline(name), "Name");
});
craft_ui::ComboBox::from_label(crate::localization::text("Sample Rate")).selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label("Sample Rate").selected_text(format!("{sample_rate} Hz")).show_ui(ui, |ui| {
for r in soundcraft_time::SampleRate::COMMON {
ui.selectable_value(sample_rate, r, format!("{r} Hz"));
}
});
crate::widgets::checkbox(ui, demo, crate::localization::text("Start from the demo session"));
crate::widgets::checkbox(ui, demo, "Start from the demo session");
if buttons(ui, "Create", enter) {
action = Some((
"session.new".into(),
@@ -552,25 +497,25 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::Bounce { path, format, bit_depth, normalize, dither } => {
bounce_file_row(app, ui, path, format);
ui.horizontal(|ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Format")).selected_text(format.container().name()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label("Format").selected_text(format.container().name()).show_ui(ui, |ui| {
for &f in EncodeFormat::ALL {
ui.selectable_value(format, f, f.container().name());
}
});
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label("Bit Depth").selected_text(format!("{bit_depth}-bit")).show_ui(ui, |ui| {
for b in ["16", "24", "32f"] {
ui.selectable_value(bit_depth, b.to_string(), crate::localized_format!("{b}-bit", b = b));
ui.selectable_value(bit_depth, b.to_string(), format!("{b}-bit"));
}
});
});
crate::widgets::checkbox(ui, normalize, crate::localization::text("Normalize to -0.1 dBFS"));
crate::widgets::checkbox(ui, normalize, "Normalize to -0.1 dBFS");
// 32-bit float keeps every sample as it is: there is nothing to dither.
ui.add_enabled_ui(bit_depth.as_str() != "32f", |ui| {
crate::widgets::checkbox(ui, dither, crate::localization::text("Dither (TPDF)"))
.on_hover_text(crate::localization::text("Adds ±1 LSB triangular dither when writing 16- or 24-bit files. Leave it off when the master chain already dithers."));
crate::widgets::checkbox(ui, dither, "Dither (TPDF)")
.on_hover_text("Adds ±1 LSB triangular dither when writing 16- or 24-bit files. Leave it off when the master chain already dithers.");
});
ui.label(
egui::RichText::new(crate::localization::text("Bounces the edit selection, or the whole session when nothing is selected."))
egui::RichText::new("Bounces the edit selection, or the whole session when nothing is selected.")
.small()
.color(Tokens::current().text_dim),
);
@@ -613,7 +558,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
Dialog::Number { cmd, key, value, suffix, .. } => {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(value).speed(0.1)).accessible_name(crate::localized_format!("Value in {suffix}", suffix = suffix));
ui.add(egui::DragValue::new(value).speed(0.1)).accessible_name(format!("Value in {suffix}"));
ui.label(suffix.as_str());
});
if buttons(ui, "OK", enter) {
@@ -624,8 +569,8 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::TempoChange { at, bpm } => {
ui.horizontal(|ui| {
// Same limits the engine enforces (time crate `valid_bpm`).
ui.add(egui::DragValue::new(bpm).speed(0.1).range(5.0..=1000.0)).accessible_name(crate::localization::text("Tempo (BPM)"));
ui.label(crate::localization::text("bpm"));
ui.add(egui::DragValue::new(bpm).speed(0.1).range(5.0..=1000.0)).accessible_name("Tempo (BPM)");
ui.label("bpm");
});
if buttons(ui, "OK", enter) {
action = Some(tempo_change_action(*at, *bpm));
@@ -640,7 +585,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
Dialog::Fades { shape } => {
for s in soundcraft_model::FadeShape::ALL {
ui.radio_value(shape, s.label().to_lowercase(), crate::localization::text(s.label()));
ui.radio_value(shape, s.label().to_lowercase(), s.label());
}
if buttons(ui, "OK", enter) {
action = Some(("edit.fades_create".into(), json!({"shape": shape})));
@@ -655,7 +600,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
Dialog::StripSilenceRename { names, .. } => {
strip_name_fields(ui, names, STRIP_NAME_LABELS);
let cleared = ui.button(crate::localization::text("Clear")).clicked();
let cleared = ui.button("Clear").clicked();
if cleared {
*names = StripNames::default();
}
@@ -665,7 +610,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
}
Dialog::AutoRename { clips, names } => {
ui.label(crate::localization::text("Text for naming the clips that editing makes from the selected clips:"));
ui.label("Text for naming the clips that editing makes from the selected clips:");
strip_name_fields(ui, names, AUTO_NAME_LABELS);
if buttons(ui, "OK", enter) {
action = Some(auto_rename_action(clips, names));
@@ -673,14 +618,14 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
Dialog::Group { id, name, edit, mix, members } => {
ui.horizontal(|ui| {
ui.label(crate::localization::text("Name"));
crate::widgets::named_text_field(ui.text_edit_singleline(name), crate::localization::text("Name"));
ui.label("Name");
crate::widgets::named_text_field(ui.text_edit_singleline(name), "Name");
});
ui.horizontal(|ui| {
crate::widgets::checkbox(ui, edit, crate::localization::text("Edit group"));
crate::widgets::checkbox(ui, mix, crate::localization::text("Mix group"));
crate::widgets::checkbox(ui, edit, "Edit group");
crate::widgets::checkbox(ui, mix, "Mix group");
});
ui.label(crate::localization::text("Tracks"));
ui.label("Tracks");
egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {
for (_, n, on) in members.iter_mut() {
crate::widgets::checkbox(ui, on, n.as_str());
@@ -701,14 +646,14 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
}
Dialog::Session { frame_rate, bit_depth } => {
craft_ui::ComboBox::from_label(crate::localization::text("Timecode Rate")).selected_text(crate::localization::text(frame_rate.as_str())).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label("Timecode Rate").selected_text(frame_rate.as_str()).show_ui(ui, |ui| {
for r in soundcraft_time::FrameRate::ALL {
ui.selectable_value(frame_rate, r.label().to_string(), crate::localization::text(r.label()));
ui.selectable_value(frame_rate, r.label().to_string(), r.label());
}
});
craft_ui::ComboBox::from_label(crate::localization::text("Bit Depth")).selected_text(crate::localization::text(bit_depth.as_str())).show_ui(ui, |ui| {
craft_ui::ComboBox::from_label("Bit Depth").selected_text(bit_depth.as_str()).show_ui(ui, |ui| {
for b in ["16", "24", "32f"] {
ui.selectable_value(bit_depth, b.to_string(), crate::localization::text(b));
ui.selectable_value(bit_depth, b.to_string(), b);
}
});
if buttons(ui, "OK", enter) {
@@ -718,15 +663,15 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::Loop { by, count, length, format, start, filled } => {
let s = app.engine.session();
ui.horizontal(|ui| {
let count_label = ui.radio_value(by, LoopBy::Count, crate::localization::text("Number of Loops"));
let count_label = ui.radio_value(by, LoopBy::Count, "Number of Loops");
ui.add_enabled(*by == LoopBy::Count, egui::DragValue::new(count).range(1..=512)).labelled_by(count_label.id);
});
ui.horizontal(|ui| {
let length_label = ui.radio_value(by, LoopBy::Length, crate::localization::text("Loop Length"));
let length_label = ui.radio_value(by, LoopBy::Length, "Loop Length");
ui.add_enabled(*by == LoopBy::Length, egui::TextEdit::singleline(length).desired_width(140.0)).labelled_by(length_label.id);
ui.label(crate::localization::text(format.label()));
ui.label(format.label());
});
ui.radio_value(by, LoopBy::Fill, crate::localization::text("Loop Until End of Session or Next Clip"));
ui.radio_value(by, LoopBy::Fill, "Loop Until End of Session or Next Clip");
let params = loop_params(s, *by, *count, length, *format, *start, filled);
if buttons_enabled(ui, "OK", enter, params.is_some()) {
action = params.map(|p| ("clip.loop".into(), p));
@@ -734,18 +679,18 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
}
Dialog::ScoreSetup { title, composer, bars_per_system, show_track_names } => {
egui::Grid::new("score_setup").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
ui.label(crate::localization::text("Title"));
ui.label("Title");
// The painted label is not an accesskit name; name the field itself.
crate::widgets::named_text_field(ui.text_edit_singleline(title), crate::localization::text("Score title"));
crate::widgets::named_text_field(ui.text_edit_singleline(title), "Score title");
ui.end_row();
ui.label(crate::localization::text("Composer"));
crate::widgets::named_text_field(ui.text_edit_singleline(composer), crate::localization::text("Score composer"));
ui.label("Composer");
crate::widgets::named_text_field(ui.text_edit_singleline(composer), "Score composer");
ui.end_row();
ui.label(crate::localization::text("Bars per system"));
ui.add(egui::DragValue::new(bars_per_system).range(1..=16)).accessible_name(crate::localization::text("Bars per system"));
ui.label("Bars per system");
ui.add(egui::DragValue::new(bars_per_system).range(1..=16)).accessible_name("Bars per system");
ui.end_row();
});
crate::widgets::checkbox(ui, show_track_names, crate::localization::text("Show track names"));
crate::widgets::checkbox(ui, show_track_names, "Show track names");
if buttons(ui, "OK", enter) {
action = Some((
"file.score_setup".into(),
@@ -758,19 +703,19 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let revert = then.0 == "session.revert";
if revert || cfg!(target_arch = "wasm32") {
let (question, ok) = if revert {
(crate::localized_format!("Revert “{name}” to its last saved version?", name = name), "Revert")
(format!("Revert “{name}” to its last saved version?"), "Revert")
} else {
(crate::localized_format!("Close “{name}” without saving?", name = name), "Don't Save")
(format!("Close “{name}” without saving?"), "Don't Save")
};
ui.label(crate::localized_format!("{question} Your changes will be lost.", question = question));
ui.label(format!("{question} Your changes will be lost."));
if buttons(ui, ok, false) {
action = Some(then.clone());
}
} else {
ui.label(crate::localized_format!("Save changes to “{name}” before closing?", name = name));
ui.label(format!("Save changes to “{name}” before closing?"));
ui.separator();
ui.horizontal(|ui| {
if ui.button(crate::localization::text("Don't Save")).clicked() {
if ui.button("Don't Save").clicked() {
action = Some(then.clone());
}
if buttons(ui, "Save", enter) {
@@ -845,7 +790,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
} else {
match run_then(app, &cmd, params) {
Ok(v) if cmd == "file.export_clips" => {
app.ui.status = crate::localized_format!("Exported {} clip(s) to {}", v["written"], v["dir"].as_str().unwrap_or_default());
app.ui.status = format!("Exported {} clip(s) to {}", v["written"], v["dir"].as_str().unwrap_or_default());
}
Ok(_) => {}
Err(e) => app.ui.status = e,
@@ -884,11 +829,11 @@ pub(crate) fn buttons_enabled(ui: &mut egui::Ui, ok: &str, enter: bool, ready: b
let mut canceled = false;
ui.separator();
ui.horizontal(|ui| {
if ui.button(crate::localization::text("Cancel")).clicked() {
if ui.button("Cancel").clicked() {
canceled = true;
ui.ctx().memory_mut(|m| m.data.insert_temp(egui::Id::unique("dlg_cancel"), true));
}
let b = egui::Button::new(egui::RichText::new(crate::localization::text(ok)).strong()).fill(Tokens::current().accent);
let b = egui::Button::new(egui::RichText::new(ok).strong()).fill(Tokens::current().accent);
if ui.add_enabled(ready, b).clicked() {
pressed = true;
}
@@ -899,7 +844,7 @@ pub(crate) fn buttons_enabled(ui: &mut egui::Ui, ok: &str, enter: bool, ready: b
/// A name field that takes the focus with its text selected, so typing replaces the old name.
fn name_field(ui: &mut egui::Ui, name: &mut String) {
let mut out = egui::TextEdit::singleline(name).show(ui);
let _ = crate::widgets::named_text_field(out.response.response.clone(), crate::localization::text("Name"));
let _ = crate::widgets::named_text_field(out.response.response.clone(), "Name");
if !out.response.has_focus() {
out.response.request_focus();
let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(name.chars().count()));
@@ -1316,28 +1261,6 @@ mod tests {
assert_eq!(named[..2], ["SFX023.Reel1", "SFX024.Reel1"]);
}
#[test]
fn clear_question_is_assembled_in_portuguese() {
let _scope = crate::localization::enter(crate::localization::Language::PortugueseBrazil);
let mut e = soundcraft_engine::demo::demo_engine();
let kick = e.session().sources.iter().find(|f| f.name == "Kick").map(|f| f.id).unwrap();
let kick_clips: Vec<ClipId> = e.session().clips_using(kick).map(|c| c.id).collect();
let message = |d: &Dialogs| match &d.open {
Some(Dialog::ClearClips { message, .. }) => message.clone(),
other => panic!("{other:?}"),
};
let mut d = Dialogs::default();
assert!(d.open_clear(&e, kick_clips, vec![kick]));
let combined = message(&d);
assert_eq!(combined, "Remover 3 clipes e 1 arquivo da sessão?");
e.session_mut().sources.iter_mut().for_each(|f| f.unsaved = false);
assert!(d.open_clear(&e, vec![], vec![kick]));
assert_eq!(
message(&d),
"Remover o arquivo \"Kick\" da sessão? Ele é usado por 3 clipes na linha do tempo, que também serão removidos. O arquivo permanece no disco."
);
}
#[test]
fn clear_always_asks_and_names_the_timeline_clips_that_go_too() {
let mut e = soundcraft_engine::demo::demo_engine();
+10 -24
View File
@@ -18,60 +18,46 @@ pub(super) fn audiosuite_window(app: &mut SoundApp, ctx: &egui::Context) {
if let Some(info) = soundcraft_dsp::plugin_info(&process) {
for p in info.params {
let v = params.entry(p.id.to_string()).or_insert(p.default);
let mut wide = f64::from(*v);
crate::widgets::FineSlider::new(&mut wide, f64::from(p.min)..=f64::from(p.max))
.text(crate::localization::text(p.name))
.default_value(f64::from(p.default))
.show(ui);
*v = wide as f32;
ui.add(egui::Slider::new(v, p.min..=p.max).text(p.name));
}
} else {
match process.as_str() {
"normalize" => {
let v = params.entry("target_db".into()).or_insert(-0.1);
let mut wide = f64::from(*v);
crate::widgets::FineSlider::new(&mut wide, -24.0..=0.0).text(crate::localization::text("Peak dB")).default_value(-0.1).show(ui);
*v = wide as f32;
ui.add(egui::Slider::new(v, -24.0..=0.0).text("Peak dB"));
}
"time_stretch" => {
let v = params.entry("ratio".into()).or_insert(1.0);
let mut wide = f64::from(*v);
crate::widgets::FineSlider::new(&mut wide, 0.25..=4.0)
.text(crate::localization::text("Length ratio"))
.default_value(1.0)
.show(ui);
*v = wide as f32;
ui.add(egui::Slider::new(v, 0.25..=4.0).text("Length ratio"));
}
"pitch_shift" => {
let v = params.entry("semitones".into()).or_insert(0.0);
let mut wide = f64::from(*v);
crate::widgets::FineSlider::new(&mut wide, -24.0..=24.0).text(crate::localization::text("Semitones")).default_value(0.0).show(ui);
*v = wide as f32;
ui.add(egui::Slider::new(v, -24.0..=24.0).text("Semitones"));
}
"speed_ramp" => {
for (id, label, default, choices) in SPEED_RAMP_CHOICES {
let v = params.entry(id.to_string()).or_insert(default);
ui.horizontal(|ui| {
ui.label(crate::localization::text(label));
ui.label(label);
for &(value, name) in choices {
ui.radio_value(v, value, crate::localization::text(name));
ui.radio_value(v, value, name);
}
});
}
}
_ => {
ui.label(crate::localization::text("No parameters."));
ui.label("No parameters.");
}
}
}
ui.ctx().memory_mut(|m| m.data.insert_temp(key, params.clone()));
let hint = if soundcraft_dsp::is_generator(&process) {
crate::localization::text("Fills the selection on the selected tracks with a new clip.")
"Fills the selection on the selected tracks with a new clip."
} else {
crate::localization::text("Processes the selected clips and replaces them with rendered audio.")
"Processes the selected clips and replaces them with rendered audio."
};
ui.label(egui::RichText::new(hint).small());
if ui.button(egui::RichText::new(crate::localization::text("Render")).strong()).clicked() {
if ui.button(egui::RichText::new("Render").strong()).clicked() {
let p: serde_json::Map<String, Value> = params.iter().map(|(k, v)| (k.clone(), json!(v))).collect();
let _ = app.run("audiosuite.process", json!({"process": process, "params": p}));
}
+4 -8
View File
@@ -14,7 +14,7 @@ pub fn ask_to_save(app: &mut SoundApp, id: &str, params: &Value) -> bool {
if !app.engine.is_dirty() {
return false;
}
app.dialogs.set(Dialog::SaveChanges { then: (id.into(), params.clone()) });
app.dialogs.open = Some(Dialog::SaveChanges { then: (id.into(), params.clone()) });
true
}
@@ -52,7 +52,7 @@ pub fn open_path(app: &mut SoundApp, path: &std::path::Path) {
Ok(p) => p,
Err(e) => {
log::warn!("{e}");
app.ui.status = crate::localization::error_text(&e.to_string());
app.ui.status = e.to_string();
return;
}
};
@@ -98,13 +98,9 @@ pub(super) fn open_pending_session(app: &mut SoundApp) {
Ok(missing) => {
// This path replaces the document without going through `SoundApp::run`.
app.document_replaced();
if missing.is_empty() {
crate::localized_format!("Opened {name}", name = name)
} else {
crate::localized_format!("Opened {name} ({missing} missing media)", name = name, missing = missing.len())
}
if missing.is_empty() { format!("Opened {name}") } else { format!("Opened {name} ({} missing media)", missing.len()) }
}
Err(e) => crate::localization::error_text(&e.to_string()),
Err(e) => e.to_string(),
};
}
+19 -27
View File
@@ -162,7 +162,7 @@ impl NewTracks {
let id = egui::Id::unique(("new_tracks_row", row.key));
let rect = egui::Rect::from_min_size(ui.available_rect_before_wrap().min, vec2(ui.available_width(), ui.spacing().interact_size.y));
ui.scope_builder(egui::UiBuilder::new().scope_id(id).max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
let label = ui.label(crate::localization::text("Create"));
let label = ui.label("Create");
let counter = ui
.scope_builder(egui::UiBuilder::new().scope_id(id.with("count")), |ui| {
ui.spacing_mut().interact_size.x = widths.count;
@@ -180,19 +180,19 @@ impl NewTracks {
if counter.gained_focus() {
counter.scroll_to_me(Some(egui::Align::Center));
}
ui.label(crate::localization::text("new"));
ui.label("new");
let format = if has_format(&row.kind) {
Some(
craft_ui::ComboBox::from_id_salt("nt_fmt")
.width(widths.format)
.selected_text(crate::localization::text(&row.format))
.selected_text(&row.format)
.show_ui(ui, |ui| {
for f in ChannelFormat::ALL {
ui.selectable_value(&mut row.format, f.label().to_string(), crate::localization::text(f.label()));
ui.selectable_value(&mut row.format, f.label().to_string(), f.label());
}
})
.response
.accessible_name(crate::localization::text("Channel format")),
.accessible_name("Channel format"),
)
} else {
ui.allocate_space(vec2(widths.format, ui.spacing().interact_size.y));
@@ -200,55 +200,47 @@ impl NewTracks {
};
let kind = craft_ui::ComboBox::from_id_salt("nt_kind")
.width(widths.kind)
.selected_text(crate::localization::text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label())))
.selected_text(TrackKind::from_id(&row.kind).map_or("Audio Track", |k| k.label()))
.show_ui(ui, |ui| {
for k in TrackKind::ALL {
if ui.selectable_label(row.kind == k.id(), crate::localization::text(k.label())).clicked() {
if ui.selectable_label(row.kind == k.id(), k.label()).clicked() {
set_new_track_kind(&mut row.kind, &mut row.name, k);
}
}
})
.response
.accessible_name(crate::localization::text("Track kind"));
.accessible_name("Track kind");
let timebase = if has_timebase(&row.kind) {
ui.label(crate::localization::text("in"));
ui.label("in");
Some(
craft_ui::ComboBox::from_id_salt("nt_tb")
.width(widths.timebase)
.selected_text(crate::localization::text(if row.timebase == "ticks" { "Ticks" } else { "Samples" }))
.selected_text(if row.timebase == "ticks" { "Ticks" } else { "Samples" })
.show_ui(ui, |ui| {
ui.selectable_value(&mut row.timebase, "samples".to_string(), crate::localization::text("Samples"));
ui.selectable_value(&mut row.timebase, "ticks".to_string(), crate::localization::text("Ticks"));
ui.selectable_value(&mut row.timebase, "samples".to_string(), "Samples");
ui.selectable_value(&mut row.timebase, "ticks".to_string(), "Ticks");
})
.response
.accessible_name(crate::localization::text("Timebase")),
.accessible_name("Timebase"),
)
} else {
ui.allocate_space(vec2(text_width(ui, crate::localization::text("in")), ui.spacing().interact_size.y));
ui.allocate_space(vec2(text_width(ui, "in"), ui.spacing().interact_size.y));
ui.allocate_space(vec2(widths.timebase, ui.spacing().interact_size.y));
None
};
let label = ui.label(crate::localization::text("Name:"));
let label = ui.label("Name:");
let name = crate::widgets::named_text_field(
ui.add(egui::TextEdit::singleline(&mut row.name).id(id.with("name")).desired_width(NAME_WIDTH)).labelled_by(label.id),
crate::localization::text("Name:"),
"Name:",
);
if format.iter().chain(timebase.iter()).chain([&kind, &name]).any(|r| r.clicked() || r.has_focus()) {
self.active = index;
}
let size = vec2(ROW_BUTTON_WIDTH, ui.spacing().interact_size.y);
if ui
.add_enabled(len > 1, egui::Button::new(crate::localization::text("−")).min_size(size))
.on_hover_text(crate::localization::text("Remove this row"))
.clicked()
{
if ui.add_enabled(len > 1, egui::Button::new("−").min_size(size)).on_hover_text("Remove this row").clicked() {
remove = Some(index);
}
if ui
.add_enabled(len < MAX_TRACKS, egui::Button::new(crate::localization::text("+")).min_size(size))
.on_hover_text(crate::localization::text("Add a row below"))
.clicked()
{
if ui.add_enabled(len < MAX_TRACKS, egui::Button::new("+").min_size(size)).on_hover_text("Add a row below").clicked() {
insert = Some(index);
}
});
@@ -266,7 +258,7 @@ impl NewTracks {
let total = self.rows.iter().fold(0_u32, |total, row| total.saturating_add(row.count));
let can_create = !self.rows.is_empty() && total <= MAX_TRACKS as u32;
if !can_create {
ui.colored_label(ui.visuals().error_fg_color, crate::localization::text("Create up to 128 tracks at a time."));
ui.colored_label(ui.visuals().error_fg_color, "Create up to 128 tracks at a time.");
}
// Enter on a focused row button changes that row only; it must not also submit the dialog.
if crate::dialogs::buttons_enabled(ui, "Create", enter && !row_action, can_create) && !row_action {
+141 -174
View File
@@ -94,44 +94,39 @@ fn beat_detective(app: &mut SoundApp, ctx: &egui::Context) {
if !open {
return;
}
egui::Window::new(crate::localization::text("Beat Analysis"))
.id(egui::Id::unique("Beat Analysis"))
.open(&mut open)
.default_size(vec2(360.0, 220.0))
.show(ctx, |ui| {
ui.label(crate::localization::text("Analyses the edit selection on the selected tracks."));
ui.add(egui::Slider::new(&mut app.ops.beat_sensitivity, 0.0..=1.0).text(crate::localization::text("Sensitivity")));
crate::widgets::checkbox(ui, &mut app.ops.beat_separate, crate::localization::text("Separate clips at detected beats"));
crate::widgets::checkbox(ui, &mut app.ops.beat_set_tempo, crate::localization::text("Set the session tempo from the beats"));
ui.horizontal(|ui| {
if ui.button(crate::localization::text("Analyze")).clicked() {
let r = app.run("event.beat_detective", json!({"sensitivity": app.ops.beat_sensitivity, "separate": false, "set_tempo": false}));
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
}
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
let r = app.run(
"event.beat_detective",
json!({"sensitivity": app.ops.beat_sensitivity, "separate": app.ops.beat_separate, "set_tempo": app.ops.beat_set_tempo}),
);
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
}
});
ui.separator();
ui.horizontal(|ui| {
ui.label(crate::localization::text("Identify Beat: selection is"));
ui.add(egui::DragValue::new(&mut app.ops.identify_bars).range(1..=64))
.accessible_name(crate::localization::text("Identify beat bars"));
ui.label(crate::localization::text("bar(s)"));
if ui.button(crate::localization::text("Set Tempo")).clicked() {
let r = app.run("event.identify_beat", json!({"bars": app.ops.identify_bars}));
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
}
});
if !app.ops.beat_result.is_empty() {
let s = app.ops.beat_result.clone();
ui.label(egui::RichText::new(if s.len() > 300 { format!("{}…", &s[..300]) } else { s }).small());
egui::Window::new("Beat Analysis").open(&mut open).default_size(vec2(360.0, 220.0)).show(ctx, |ui| {
ui.label("Analyses the edit selection on the selected tracks.");
ui.add(egui::Slider::new(&mut app.ops.beat_sensitivity, 0.0..=1.0).text("Sensitivity"));
crate::widgets::checkbox(ui, &mut app.ops.beat_separate, "Separate clips at detected beats");
crate::widgets::checkbox(ui, &mut app.ops.beat_set_tempo, "Set the session tempo from the beats");
ui.horizontal(|ui| {
if ui.button("Analyze").clicked() {
let r = app.run("event.beat_detective", json!({"sensitivity": app.ops.beat_sensitivity, "separate": false, "set_tempo": false}));
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
}
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
let r = app.run(
"event.beat_detective",
json!({"sensitivity": app.ops.beat_sensitivity, "separate": app.ops.beat_separate, "set_tempo": app.ops.beat_set_tempo}),
);
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
}
});
ui.separator();
ui.horizontal(|ui| {
ui.label("Identify Beat: selection is");
ui.add(egui::DragValue::new(&mut app.ops.identify_bars).range(1..=64)).accessible_name("Identify beat bars");
ui.label("bar(s)");
if ui.button("Set Tempo").clicked() {
let r = app.run("event.identify_beat", json!({"bars": app.ops.identify_bars}));
app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
}
});
if !app.ops.beat_result.is_empty() {
let s = app.ops.beat_result.clone();
ui.label(egui::RichText::new(if s.len() > 300 { format!("{}…", &s[..300]) } else { s }).small());
}
});
app.ui.show_beat_detective = open;
}
@@ -157,34 +152,26 @@ fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) {
if !open {
return;
}
egui::Window::new(crate::localization::text("Tempo Operations"))
.id(egui::Id::unique("Tempo Operations"))
.open(&mut open)
.default_size(vec2(360.0, 200.0))
.show(ctx, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Curve"))
.selected_text(crate::localization::text(&app.ops.tempo_curve))
.show_ui(ui, |ui| {
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), crate::localization::text(c));
}
});
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix(crate::localization::text("start bpm ")))
.accessible_name(crate::localization::text("Start tempo (BPM)"));
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix(crate::localization::text("end bpm ")))
.accessible_name(crate::localization::text("End tempo (BPM)"));
ui.label(
egui::RichText::new(crate::localization::text(
"Applies across the edit selection (constant: at the insertion point; scale: factor = end / start; stretch: factor = start / end).",
))
.small(),
);
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
let (id, p) = tempo_ops_apply(&app.ops.tempo_curve, app.ops.tempo_start, app.ops.tempo_end);
let r = app.run(id, p);
result_line(ui, &r);
egui::Window::new("Tempo Operations").open(&mut open).default_size(vec2(360.0, 200.0)).show(ctx, |ui| {
craft_ui::ComboBox::from_label("Curve").selected_text(app.ops.tempo_curve.clone()).show_ui(ui, |ui| {
for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), c);
}
});
ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix("start bpm ")).accessible_name("Start tempo (BPM)");
ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix("end bpm ")).accessible_name("End tempo (BPM)");
ui.label(
egui::RichText::new(
"Applies across the edit selection (constant: at the insertion point; scale: factor = end / start; stretch: factor = start / end).",
)
.small(),
);
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
let (id, p) = tempo_ops_apply(&app.ops.tempo_curve, app.ops.tempo_start, app.ops.tempo_end);
let r = app.run(id, p);
result_line(ui, &r);
}
});
app.ui.show_tempo_ops = open;
}
@@ -195,51 +182,43 @@ fn time_ops(app: &mut SoundApp, ctx: &egui::Context) {
if !open {
return;
}
egui::Window::new(crate::localization::text("Time Operations"))
.id(egui::Id::unique("Time Operations"))
.open(&mut open)
.default_size(vec2(360.0, 200.0))
.show(ctx, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
.selected_text(crate::localization::text(&app.ops.time_op))
.show_ui(ui, |ui| {
for c in ["insert", "cut", "change meter", "move song start"] {
ui.selectable_value(&mut app.ops.time_op, c.to_string(), crate::localization::text(c));
}
});
match app.ops.time_op.as_str() {
"change meter" => {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64))
.accessible_name(crate::localization::text("Meter numerator"));
ui.label(crate::localization::text("/"));
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
for d in [2u32, 4, 8, 16] {
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
}
});
den.response.accessible_name(crate::localization::text("Meter denominator"));
});
}
"insert" => {
ui.add(egui::DragValue::new(&mut app.ops.time_seconds).range(0.0..=3600.0).suffix(" s"))
.accessible_name(crate::localization::text("Time (seconds)"));
}
_ => {
ui.label(egui::RichText::new(crate::localization::text("Uses the edit selection.")).small());
}
}
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
let at = app.engine.session().edit.selection.start;
let r = match app.ops.time_op.as_str() {
"insert" => app.run("event.insert_time", json!({"start": at, "length": {"seconds": app.ops.time_seconds}})),
"cut" => app.run("event.cut_time", json!({})),
"change meter" => app.run("event.meter", json!({"numerator": app.ops.meter_num, "denominator": app.ops.meter_den, "at": at})),
_ => app.run("event.move_song_start", json!({"to": at})),
};
result_line(ui, &r);
egui::Window::new("Time Operations").open(&mut open).default_size(vec2(360.0, 200.0)).show(ctx, |ui| {
craft_ui::ComboBox::from_label("Operation").selected_text(app.ops.time_op.clone()).show_ui(ui, |ui| {
for c in ["insert", "cut", "change meter", "move song start"] {
ui.selectable_value(&mut app.ops.time_op, c.to_string(), c);
}
});
match app.ops.time_op.as_str() {
"change meter" => {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64)).accessible_name("Meter numerator");
ui.label("/");
let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
for d in [2u32, 4, 8, 16] {
ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
}
});
den.response.accessible_name("Meter denominator");
});
}
"insert" => {
ui.add(egui::DragValue::new(&mut app.ops.time_seconds).range(0.0..=3600.0).suffix(" s")).accessible_name("Time (seconds)");
}
_ => {
ui.label(egui::RichText::new("Uses the edit selection.").small());
}
}
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
let at = app.engine.session().edit.selection.start;
let r = match app.ops.time_op.as_str() {
"insert" => app.run("event.insert_time", json!({"start": at, "length": {"seconds": app.ops.time_seconds}})),
"cut" => app.run("event.cut_time", json!({})),
"change meter" => app.run("event.meter", json!({"numerator": app.ops.meter_num, "denominator": app.ops.meter_den, "at": at})),
_ => app.run("event.move_song_start", json!({"to": at})),
};
result_line(ui, &r);
}
});
app.ui.show_time_ops = open;
}
@@ -248,49 +227,44 @@ fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) {
if !open {
return;
}
egui::Window::new(crate::localization::text("MIDI Operations"))
.id(egui::Id::unique("MIDI Operations"))
.open(&mut open)
.default_size(vec2(360.0, 220.0))
.show(ctx, |ui| {
craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
.selected_text(crate::localization::text(&app.ops.midi_op))
.show_ui(ui, |ui| {
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), crate::localization::text(c));
}
});
match app.ops.midi_op.as_str() {
"quantize" => {
craft_ui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
}
});
ui.add(egui::Slider::new(&mut app.ops.quant_strength, 0.0..=100.0).text(crate::localization::text("Strength %")));
ui.add(egui::Slider::new(&mut app.ops.quant_swing, 0.0..=100.0).text(crate::localization::text("Swing %")));
}
"transpose" => {
ui.add(egui::Slider::new(&mut app.ops.transpose, -48..=48).text(crate::localization::text("Semitones")));
}
"change velocity" => {
ui.add(egui::Slider::new(&mut app.ops.velocity_add, -127..=127).text(crate::localization::text("Add")));
}
_ => {}
}
ui.label(egui::RichText::new(crate::localization::text("Applies to the selected MIDI clips (or those under the selection).")).small());
if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
let r = match app.ops.midi_op.as_str() {
"quantize" => app
.run("event.quantize", json!({"grid": app.ops.quant_grid, "strength": app.ops.quant_strength, "swing": app.ops.quant_swing})),
"transpose" => app.run("event.transpose", json!({"semitones": app.ops.transpose})),
"change velocity" => app.run("event.change_velocity", json!({"add": app.ops.velocity_add})),
"flatten performance" => app.run("event.flatten_performance", json!({})),
_ => app.run("event.restore_performance", json!({})),
};
result_line(ui, &r);
egui::Window::new("MIDI Operations").open(&mut open).default_size(vec2(360.0, 220.0)).show(ctx, |ui| {
craft_ui::ComboBox::from_label("Operation").selected_text(app.ops.midi_op.clone()).show_ui(ui, |ui| {
for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
ui.selectable_value(&mut app.ops.midi_op, c.to_string(), c);
}
});
match app.ops.midi_op.as_str() {
"quantize" => {
craft_ui::ComboBox::from_label("Grid").selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
}
});
ui.add(egui::Slider::new(&mut app.ops.quant_strength, 0.0..=100.0).text("Strength %"));
ui.add(egui::Slider::new(&mut app.ops.quant_swing, 0.0..=100.0).text("Swing %"));
}
"transpose" => {
ui.add(egui::Slider::new(&mut app.ops.transpose, -48..=48).text("Semitones"));
}
"change velocity" => {
ui.add(egui::Slider::new(&mut app.ops.velocity_add, -127..=127).text("Add"));
}
_ => {}
}
ui.label(egui::RichText::new("Applies to the selected MIDI clips (or those under the selection).").small());
if ui.button(egui::RichText::new("Apply").strong()).clicked() {
let r = match app.ops.midi_op.as_str() {
"quantize" => {
app.run("event.quantize", json!({"grid": app.ops.quant_grid, "strength": app.ops.quant_strength, "swing": app.ops.quant_swing}))
}
"transpose" => app.run("event.transpose", json!({"semitones": app.ops.transpose})),
"change velocity" => app.run("event.change_velocity", json!({"add": app.ops.velocity_add})),
"flatten performance" => app.run("event.flatten_performance", json!({})),
_ => app.run("event.restore_performance", json!({})),
};
result_line(ui, &r);
}
});
app.ui.show_midi_ops = open;
}
@@ -301,36 +275,29 @@ fn rtp(app: &mut SoundApp, ctx: &egui::Context) {
}
let targets = app.engine.target_tracks();
sync_rtp_form(&mut app.ops, app.engine.session(), targets, ctx.dragged_id().is_some());
egui::Window::new(crate::localization::text("MIDI Real-Time Properties"))
.id(egui::Id::unique("MIDI Real-Time Properties"))
.open(&mut open)
.default_size(vec2(340.0, 200.0))
.show(ctx, |ui| {
ui.label(crate::localization::text("Non-destructive, applied at playback to the selected MIDI tracks."));
let mut changed = RtpChanged::default();
changed.velocity =
ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text(crate::localization::text("Velocity +"))).changed();
changed.transpose =
ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text(crate::localization::text("Transpose"))).changed();
changed.duration =
ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text(crate::localization::text("Duration %"))).changed();
changed.delay = ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text(crate::localization::text("Delay (ticks)"))).changed();
if let Some(p) = rtp_params(changed, &app.ops) {
let _ = app.engine.execute_merged("event.midi_rtp", &p, "rtp");
egui::Window::new("MIDI Real-Time Properties").open(&mut open).default_size(vec2(340.0, 200.0)).show(ctx, |ui| {
ui.label("Non-destructive, applied at playback to the selected MIDI tracks.");
let mut changed = RtpChanged::default();
changed.velocity = ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text("Velocity +")).changed();
changed.transpose = ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text("Transpose")).changed();
changed.duration = ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text("Duration %")).changed();
changed.delay = ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text("Delay (ticks)")).changed();
if let Some(p) = rtp_params(changed, &app.ops) {
let _ = app.engine.execute_merged("event.midi_rtp", &p, "rtp");
}
ui.horizontal(|ui| {
if ui.button("Write to Notes").clicked() {
let _ = app.run("track.write_midi_rtp", json!({}));
}
if ui.button("Clear").clicked() {
let _ = app.run("event.midi_rtp", json!({"clear": true}));
app.ops.rtp_velocity = 0;
app.ops.rtp_transpose = 0;
app.ops.rtp_duration = 100.0;
app.ops.rtp_delay = 0;
}
ui.horizontal(|ui| {
if ui.button(crate::localization::text("Write to Notes")).clicked() {
let _ = app.run("track.write_midi_rtp", json!({}));
}
if ui.button(crate::localization::text("Clear")).clicked() {
let _ = app.run("event.midi_rtp", json!({"clear": true}));
app.ops.rtp_velocity = 0;
app.ops.rtp_transpose = 0;
app.ops.rtp_duration = 100.0;
app.ops.rtp_delay = 0;
}
});
});
});
app.ui.show_rtp = open;
}
+6 -9
View File
@@ -85,9 +85,9 @@ impl SoundApp {
/// The File › Open Recent submenu.
pub fn menu(app: &mut SoundApp, ui: &mut egui::Ui) {
ui.menu_button(crate::localization::text("Open Recent"), |ui| {
ui.menu_button("Open Recent", |ui| {
if app.ui.recent_sessions.is_empty() {
ui.add_enabled(false, egui::Button::new(crate::localization::text("No Recent Sessions")));
ui.add_enabled(false, egui::Button::new("No Recent Sessions"));
return;
}
let now = ui.ctx().input(|i| i.time);
@@ -95,17 +95,14 @@ pub fn menu(app: &mut SoundApp, ui: &mut egui::Ui) {
let mut open = None;
for (i, path) in app.ui.recent_sessions.iter().enumerate() {
let here = exists.get(i).copied().unwrap_or(true);
let text = if here { label(path) } else { crate::localized_format!("{} (missing)", label(path)) };
let r = ui
.add_enabled(here, egui::Button::new(text))
.on_hover_text(path.as_str())
.on_disabled_hover_text(crate::localized_format!("{path}\nnot found", path = path));
let text = if here { label(path) } else { format!("{} (missing)", label(path)) };
let r = ui.add_enabled(here, egui::Button::new(text)).on_hover_text(path.as_str()).on_disabled_hover_text(format!("{path}\nnot found"));
if r.clicked() {
open = Some(path.clone());
}
}
ui.separator();
if ui.button(crate::localization::text("Clear Recent")).clicked() {
if ui.button("Clear Recent").clicked() {
app.ui.recent_sessions.clear();
app.recent_changed = true;
ui.close();
@@ -115,7 +112,7 @@ pub fn menu(app: &mut SoundApp, ui: &mut egui::Ui) {
// Through the dialog layer, so unsaved changes are asked about first.
if let Err(e) = crate::dialogs::run_or_ask(app, "session.open", json!({"path": path})) {
log::warn!("{path}: {e}");
app.ui.status = crate::localized_format!("Could not open {path}: {e}", path = path, e = e);
app.ui.status = format!("Could not open {path}: {e}");
}
}
});
+9 -20
View File
@@ -9,28 +9,22 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let Some(left) = app.leftovers.first().cloned() else { return };
let mut open = true;
let mut recover = None;
egui::Window::new(egui::RichText::new(crate::localization::text("Recover Unsaved Work")).font(bold(13.0)))
.id(egui::Id::unique("Recover Unsaved Work"))
egui::Window::new(egui::RichText::new("Recover Unsaved Work").font(bold(13.0)))
.open(&mut open)
.collapsible(false)
.resizable(false)
.anchor(Align2::CENTER_CENTER, vec2(0.0, -80.0))
.show(ctx, |ui| {
let age = left.saved.elapsed().map_or_else(|_| crate::localization::text("recently").to_owned(), |d| ago(d.as_secs()));
let what = crate::localization::text(if left.recording { "unsaved changes and an unfinished recording" } else { "unsaved changes" });
ui.label(crate::localized_format!("“{name}” has {what} from an earlier run, autosaved {age}.", name = left.name, what = what, age = age));
let age = left.saved.elapsed().map_or_else(|_| "recently".into(), |d| ago(d.as_secs()));
let what = if left.recording { "unsaved changes and an unfinished recording" } else { "unsaved changes" };
ui.label(format!("“{}” has {what} from an earlier run, autosaved {age}.", left.name));
ui.separator();
ui.horizontal(|ui| {
if ui.button(crate::localization::text("Discard")).clicked() {
if ui.button("Discard").clicked() {
recover = Some(false);
}
let recover_button =
egui::Button::new(egui::RichText::new(crate::localization::text("Recover")).strong()).fill(Tokens::current().accent);
if ui
.add_enabled(!app.engine.transport.recording, recover_button)
.on_disabled_hover_text(crate::localization::text("Stop recording first"))
.clicked()
{
let recover_button = egui::Button::new(egui::RichText::new("Recover").strong()).fill(Tokens::current().accent);
if ui.add_enabled(!app.engine.transport.recording, recover_button).on_disabled_hover_text("Stop recording first").clicked() {
recover = Some(true);
}
});
@@ -47,15 +41,10 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
fn ago(secs: u64) -> String {
let (n, unit) = match secs {
0..60 => return crate::localization::text("less than a minute ago").to_owned(),
0..60 => return "less than a minute ago".into(),
60..3_600 => (secs / 60, "minute"),
3_600..86_400 => (secs / 3_600, "hour"),
_ => (secs / 86_400, "day"),
};
let unit = crate::localization::text(unit);
if n == 1 {
crate::localized_format!("{n} {unit} ago", n = n, unit = unit)
} else {
crate::localized_format!("{n} {unit}s ago", n = n, unit = unit)
}
format!("{n} {unit}{} ago", if n == 1 { "" } else { "s" })
}
+9 -10
View File
@@ -141,10 +141,10 @@ fn spot_field_row(ui: &mut Ui, s: &Session, d: &mut Spot, i: usize, label: &str)
}
fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples) {
ui.label(crate::localization::text("Original Time Stamp"));
ui.label("Original Time Stamp");
ui.horizontal(|ui| {
ui.label(RichText::new(s.format_position(at, TimeFormat::Timecode)).font(mono(13.0)));
if ui.button(crate::localization::text("Use")).on_hover_text(crate::localization::text("Spot to where it was recorded")).clicked() {
if ui.button("Use").on_hover_text("Spot to where it was recorded").clicked() {
d.start = at;
}
});
@@ -154,13 +154,12 @@ fn original_time_stamp_row(ui: &mut Ui, s: &Session, d: &mut Spot, at: Samples)
/// The dialog's fields; the caller adds OK and Cancel.
pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
egui::Grid::new("spot").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
let scale = ui.label(crate::localization::text("Time Scale"));
let time_scale =
craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(crate::localization::text(d.format.label())).show_ui(ui, |ui| {
for f in TimeFormat::ALL {
ui.selectable_value(&mut d.format, f, crate::localization::text(f.label()));
}
});
let scale = ui.label("Time Scale");
let time_scale = craft_ui::ComboBox::from_id_salt("spot_scale").selected_text(d.format.label()).show_ui(ui, |ui| {
for f in TimeFormat::ALL {
ui.selectable_value(&mut d.format, f, f.label());
}
});
time_scale.response.labelled_by(scale.id);
ui.end_row();
for (i, label) in FIELDS.into_iter().enumerate() {
@@ -169,7 +168,7 @@ pub fn fields(ui: &mut Ui, s: &Session, d: &mut Spot) {
}
spot_field_row(ui, s, d, i, label);
}
ui.label(crate::localization::text("Duration"));
ui.label("Duration");
ui.label(RichText::new(format_length(d.start, d.len, d.format, s.sample_rate, &s.tempo, s.frame_rate)).font(mono(13.0)));
ui.end_row();
if let Some(at) = d.stamp {
+6 -6
View File
@@ -150,23 +150,23 @@ pub(super) const AUTO_NAME_LABELS: [&str; 2] = ["Starting Number", "Number of Pl
pub(super) fn strip_name_fields(ui: &mut egui::Ui, names: &mut StripNames, labels: [&str; 2]) {
let [number, zeros] = labels;
egui::Grid::new("strip_names").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
let name = ui.label(crate::localization::text("Name"));
let name = ui.label("Name");
ui.text_edit_singleline(&mut names.name).labelled_by(name.id);
ui.end_row();
let number = ui.label(crate::localization::text(number));
let number = ui.label(number);
ui.add(egui::DragValue::new(&mut names.number).range(0..=StripNames::MAX_NUMBER)).labelled_by(number.id);
ui.end_row();
let zeros = ui.label(crate::localization::text(zeros));
let zeros = ui.label(zeros);
ui.add(egui::DragValue::new(&mut names.zeros).range(0..=StripNames::MAX_ZEROS)).labelled_by(zeros.id);
ui.end_row();
let suffix = ui.label(crate::localization::text("Suffix"));
let suffix = ui.label("Suffix");
ui.text_edit_singleline(&mut names.suffix).labelled_by(suffix.id);
ui.end_row();
});
let example = if names.name.trim().is_empty() {
crate::localization::text("Without a name, the clips keep their names.").to_string()
"Without a name, the clips keep their names.".to_string()
} else {
crate::localized_format!("First clip: {}", names.clip_name(0))
format!("First clip: {}", names.clip_name(0))
};
ui.label(egui::RichText::new(example).small().color(Tokens::current().text_dim));
}
+3 -3
View File
@@ -452,7 +452,7 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
if edit { std::mem::replace(&mut app.ui.docking, edit_default()) } else { std::mem::replace(&mut app.ui.mix_docking, mix_default()) };
let before_sync = workspace.clone();
if let Err(error) = (if edit { validate(&workspace) } else { validate_mix(&workspace) }).and_then(|()| sync(&mut workspace, app, edit)) {
app.ui.status = crate::localized_format!("Panel layout could not be restored: {error}", error = error);
app.ui.status = format!("Panel layout could not be restored: {error}");
workspace = if edit { edit_default() } else { mix_default() };
let _ = sync(&mut workspace, app, edit);
}
@@ -481,7 +481,7 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
ui,
&workspace.layout,
&style,
|panel| crate::localization::text(panel.label()).into(),
|panel| panel.label().into(),
permissions,
panel_limits,
|ui, panel| match panel {
@@ -508,7 +508,7 @@ pub fn show(app: &mut crate::SoundApp, ui: &mut egui::Ui, window: crate::MainWin
store(app, workspace, edit);
for action in output.actions {
if let Err(error) = command_for(app, &DockCommand::Layout { action }, edit) {
app.ui.status = crate::localized_format!("Panel move was not applied: {error}", error = error);
app.ui.status = format!("Panel move was not applied: {error}");
}
}
}
+16 -17
View File
@@ -27,13 +27,9 @@ mod universe;
#[cfg(test)]
use automation::automation_id;
pub(crate) use clips::draw_clip_labels;
pub use clips::strip_silence_stroke;
#[cfg(test)]
use clips::{
ClipCut, PILL_BG, PILL_HEIGHT, PILL_INSET, PILL_MIN_WIDTH, PILL_PAD, clip_cut, clip_cut_in, clip_cuts, clip_marks, fade_curve_points,
marks_pill_left, name_pill_width,
};
use clips::{clip_name_height, fade_curve_points};
use drag::drive_drag;
#[cfg(test)]
use drag::fade_drag_range;
@@ -47,8 +43,6 @@ use layout::COLUMN_TITLES_H;
use layout::lane_rect;
pub use layout::{COLUMN_W, EditLayout, HEADER_W, LANE_H, RULER_H, edit_columns, header_width, rect, sample_at, track_height, x_of};
use overlay::overlay;
#[cfg(test)]
use overlay::playhead_colour;
pub use rulers::ruler_height;
use rulers::{column_titles, draw_rulers, views_button};
pub use scroll::zoom_toggle;
@@ -81,7 +75,7 @@ fn dock_tabs(app: &mut SoundApp, ui: &mut Ui) {
("MEMORY LOCATIONS", app.ui.show_memory_locations, "window.memory_locations"),
("UNDO HISTORY", app.ui.show_undo_history, "window.undo_history"),
] {
let g = ui.painter().layout_no_wrap(crate::localization::text(label).to_string(), bold(10.5), if on { Color32::WHITE } else { t.text_dim });
let g = ui.painter().layout_no_wrap(label.to_string(), bold(10.5), if on { Color32::WHITE } else { t.text_dim });
let tr = Rect::from_min_size(pos2(x, r.min.y + 2.0), vec2(g.size().x + 16.0, r.height() - 4.0));
if on {
ui.painter().rect_filled(tr, 3.0, t.accent_dark);
@@ -98,20 +92,25 @@ fn status_bar(app: &mut SoundApp, ui: &mut Ui) {
let t = Tokens::current();
let r = ui.max_rect();
let s = app.engine.session();
let depth = match s.bit_depth {
soundcraft_model::BitDepthSetting::Int16 => crate::localization::text("16-bit"),
soundcraft_model::BitDepthSetting::Int24 => crate::localization::text("24-bit"),
soundcraft_model::BitDepthSetting::Float32 => crate::localization::text("32-bit float"),
};
let tracks = if s.tracks.len() == 1 { crate::localized_format!("1 track") } else { crate::localized_format!("{n} tracks", n = s.tracks.len()) };
let mut left = crate::localized_format!("{} · {} Hz · {} · {} · {}", s.name, s.sample_rate.hz(), depth, tracks, app.ui.status);
let mut left = format!(
"{} · {} Hz · {} · {} tracks · {}",
s.name,
s.sample_rate.hz(),
match s.bit_depth {
soundcraft_model::BitDepthSetting::Int16 => "16-bit",
soundcraft_model::BitDepthSetting::Int24 => "24-bit",
soundcraft_model::BitDepthSetting::Float32 => "32-bit float",
},
s.tracks.len(),
app.ui.status
);
soundcraft_model::truncate_chars(&mut left, 4 * soundcraft_model::MAX_NAME_CHARS);
ui.painter().text(pos2(r.min.x + 10.0, r.center().y), Align2::LEFT_CENTER, left, regular(11.0), t.text_dim);
let undo = app.engine.undo_label().map_or(String::new(), |l| crate::localized_format!("Undo {l}", l = crate::localization::text(l)));
let undo = app.engine.undo_label().map_or(String::new(), |l| format!("Undo {l}"));
ui.painter().text(
pos2(r.max.x - 10.0, r.center().y),
Align2::RIGHT_CENTER,
if app.frame_ms < 50.0 { crate::localized_format!("{undo} {ms:.1} ms/frame", undo = undo, ms = app.frame_ms) } else { undo },
if app.frame_ms < 50.0 { format!("{undo} {:.1} ms/frame", app.frame_ms) } else { undo },
regular(11.0),
t.text_dim,
);
+36 -203
View File
@@ -2,10 +2,9 @@ use super::drag::fade_drag_preview;
use super::input::{clip_gain_icon, near_fade_midpoint};
use super::layout::{sample_at, x_of};
use super::{
Align2, AutoParam, Clip, ClipContent, Color32, CornerRadius, Gesture, GridValue, NoteValue, Pos2, Range, Rect, Samples, Session, Shape, SoundApp,
Stroke, StrokeKind, TimeFormat, Tokens, Tool, Track, bold, clip_colors, format_position, pos2, regular, vec2,
Align2, AutoParam, Clip, ClipContent, Color32, CornerRadius, Gesture, GridValue, NoteValue, Pos2, Range, Rect, Session, Shape, SoundApp, Stroke,
StrokeKind, TimeFormat, Tokens, Tool, Track, bold, clip_colors, format_position, pos2, regular, vec2,
};
use std::sync::Arc;
/// The outline of the Strip Silence rectangles.
pub fn strip_silence_stroke() -> Stroke {
@@ -67,9 +66,8 @@ impl GridLines {
}
}
/// Whether clips show their name (View › Clip › Name) in a lane tall enough to carry it.
pub(super) fn clip_name_shown(s: &Session, lane: Rect) -> bool {
lane.height() >= 40.0 && s.edit.flag("view.clip.name")
pub(super) fn clip_name_height(s: &Session, lane: Rect) -> f32 {
if lane.height() >= 40.0 && s.edit.flag("view.clip.name") { 13.0 } else { 0.0 }
}
pub(super) fn fade_curve_points(fade: soundcraft_model::Fade, fade_in: bool, a: f32, b: f32, body: Rect, pixels_per_point: f32) -> Vec<Pos2> {
@@ -179,6 +177,7 @@ struct ClipGeom<'a> {
vis: Rect,
x0: f32,
x1: f32,
name_h: f32,
body: Color32,
wave: Color32,
selected: bool,
@@ -186,44 +185,48 @@ struct ClipGeom<'a> {
fade_in: soundcraft_model::Fade,
fade_out: soundcraft_model::Fade,
prev: Option<&'a Clip>,
/// How the clip meets its neighbours in its playlist (see [`clip_cuts`]).
cut: ClipCut,
}
/// `cut`: how the clip meets its neighbours in its playlist (see [`clip_cuts`]).
pub(super) fn draw_clip(cl: &ClipLane<'_>, clip: &Clip, cut: ClipCut, dim: bool) {
pub(super) fn draw_clip(cl: &ClipLane<'_>, clip: &Clip, dim: bool) {
let ClipLane { app, painter, s, track, tl, lane, .. } = *cl;
let r = clip_rect(s, tl, lane, clip);
let (x0, x1) = (r.min.x, r.max.x);
let x0 = x_of(s, tl, clip.start);
let x1 = x_of(s, tl, clip.end()).max(x0 + 1.0);
let r = Rect::from_min_max(pos2(x0, lane.min.y + 1.0), pos2(x1, lane.max.y - 1.0));
let selected = s.edit.selected_clips.contains(&clip.id)
|| (s.edit.selected_tracks.contains(&track.id)
&& !s.edit.selection.is_empty()
&& s.edit.selection.start <= clip.start
&& s.edit.selection.end >= clip.end());
let color = clip.color.unwrap_or(track.color);
let (mut body, _, mut wave) = clip_colors(color, selected);
let (mut body, bar, mut wave) = clip_colors(color, selected);
if clip.muted || dim {
body = body.gamma_multiply(0.45);
wave = Color32::from_rgb(70, 70, 70);
}
let body = if s.edit.flag("view.clip.transparency") { body.gamma_multiply(0.55) } else { body };
let corners = cut.corners();
let outline = Stroke::new(1.0, CLIP_OUTLINE);
if cut.right {
// The cut's single line is drawn by the next clip: stroke past our right edge and clip it away.
painter.rect_filled(r, corners, body);
let past = Rect::from_min_max(r.min, pos2(r.max.x + 2.0, r.max.y));
painter.with_clip_rect(painter.clip_rect().intersect(r)).rect_stroke(past, corners, outline, StrokeKind::Inside);
} else {
painter.rect(r, corners, body, outline, StrokeKind::Inside);
painter.rect(r, CornerRadius::same(2), body, Stroke::new(1.0, Color32::from_rgb(10, 10, 10)), StrokeKind::Inside);
let name_h = clip_name_height(s, lane);
if name_h > 0.0 {
let nb = Rect::from_min_max(r.min, pos2(r.max.x, r.min.y + name_h));
painter.rect_filled(nb, CornerRadius { nw: 2, ne: 2, sw: 0, se: 0 }, if clip.muted { Color32::from_rgb(70, 70, 70) } else { bar });
let name_clip = nb.intersect(lane);
// Narrower than this, no glyph would show: the name starts 4 points in.
if name_clip.width() > 6.0 {
painter.with_clip_rect(name_clip).text(
pos2(nb.min.x.max(lane.min.x) + 4.0, nb.center().y),
Align2::LEFT_CENTER,
&clip.name,
bold(10.5),
Color32::from_rgb(12, 12, 12),
);
}
}
// The body is the whole clip: the name is a small pill drawn over it (see `draw_clip_pills`).
let body_r = r;
let body_r = Rect::from_min_max(pos2(r.min.x, r.min.y + name_h), r.max);
let vis = body_r.intersect(lane);
// The waveform and fade curve share the same temporary envelope every frame.
let (fade_in, fade_out) = clip_preview_fades(clip, app.gesture.as_ref().filter(|_| !dim));
let prev = crossfade_partner(track, clip);
let g = ClipGeom { r, body_r, vis, x0, x1, body, wave, selected, dim, fade_in, fade_out, prev, cut };
let g = ClipGeom { r, body_r, vis, x0, x1, name_h, body, wave, selected, dim, fade_in, fade_out, prev };
draw_clip_content(cl, clip, &g);
draw_crossfade_tail(cl, &g);
draw_gain_line(cl, clip, &g);
@@ -263,13 +266,7 @@ fn draw_clip_content(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) {
}
}
} else {
painter.text(
body_r.center(),
Align2::CENTER_CENTER,
crate::localization::text("media offline"),
regular(10.0),
Color32::from_rgb(220, 120, 120),
);
painter.text(body_r.center(), Align2::CENTER_CENTER, "media offline", regular(10.0), Color32::from_rgb(220, 120, 120));
}
}
ClipContent::Video { .. } => {} // thumbnails: video_track::draw_lane
@@ -386,9 +383,12 @@ fn draw_fades(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) {
/// Optional clip overlays (View › Clip).
fn draw_clip_overlays(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) {
let ClipLane { painter, s, track, sorted, tl, lane, .. } = *cl;
let ClipGeom { r, cut, .. } = *g;
let ClipGeom { r, name_h, .. } = *g;
// Optional clip overlays (View › Clip).
let ov = Color32::from_rgb(16, 16, 16);
if s.edit.flag("view.clip.rating") && clip.rating > 0 && name_h > 0.0 {
painter.text(pos2(r.max.x - 18.0, r.min.y + 7.0), Align2::RIGHT_CENTER, "★".repeat(usize::from(clip.rating.min(5))), regular(9.0), ov);
}
if s.edit.flag("view.clip.sync_point") && clip.sync_point > 0 {
let x = x_of(s, tl, clip.start + clip.sync_point);
painter.add(Shape::convex_polygon(
@@ -396,7 +396,7 @@ fn draw_clip_overlays(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) {
Color32::WHITE,
Stroke::NONE,
));
painter.line_segment([pos2(x, r.min.y), pos2(x, r.max.y)], Stroke::new(1.0, Color32::from_rgba_unmultiplied(255, 255, 255, 90)));
painter.line_segment([pos2(x, r.min.y + name_h), pos2(x, r.max.y)], Stroke::new(1.0, Color32::from_rgba_unmultiplied(255, 255, 255, 90)));
}
let time_text = clip_time_text(s, clip);
if let Some(tt) = time_text
@@ -425,13 +425,8 @@ fn draw_clip_overlays(cl: &ClipLane<'_>, clip: &Clip, g: &ClipGeom<'_>) {
}
}
}
// Video clips get their pills from `video_track::draw_lane`, after their thumbnails.
if !clip.is_video() {
draw_clip_labels(painter, s, tl, lane, clip);
}
if cut.left {
// The cut's one line, on top of the waveform so it runs the full height.
painter.rect_filled(Rect::from_min_size(r.min, vec2(1.0, r.height())), 0.0, CLIP_OUTLINE);
if clip.edit_locked || clip.time_locked {
painter.text(pos2(r.max.x - 10.0, r.min.y + 7.0), Align2::CENTER_CENTER, "🔒", regular(9.0), Color32::WHITE);
}
}
@@ -456,168 +451,6 @@ fn clip_time_text(s: &Session, clip: &Clip) -> Option<String> {
}
}
/// Where a clip sits in its lane: one point in from the lane's top and bottom, at least one point wide.
pub(super) fn clip_rect(s: &Session, tl: Rect, lane: Rect, clip: &Clip) -> Rect {
let x0 = x_of(s, tl, clip.start);
let x1 = x_of(s, tl, clip.end()).max(x0 + 1.0);
Rect::from_min_max(pos2(x0, lane.min.y + 1.0), pos2(x1, lane.max.y - 1.0))
}
/// The pills of `clip` (name, marks). Drawn right after the clip itself, so clips and overlays drawn later cover them.
pub(crate) fn draw_clip_labels(painter: &egui::Painter, s: &Session, tl: Rect, lane: Rect, clip: &Clip) {
let r = clip_rect(s, tl, lane, clip);
if r.max.x < lane.min.x || r.min.x > lane.max.x {
return;
}
let show_name = clip_name_shown(s, lane);
let marks = clip_marks(clip, s.edit.flag("view.clip.rating"));
draw_clip_pills(painter, lane, r, show_name.then_some(clip.name.as_str()), &marks);
}
/// The marks a clip carries at its top-right: its star rating and a lock when edit- or time-locked.
pub(super) fn clip_marks(clip: &Clip, show_rating: bool) -> String {
let mut marks = if show_rating && clip.rating > 0 { "★".repeat(usize::from(clip.rating.min(5))) } else { String::new() };
if clip.edit_locked || clip.time_locked {
if !marks.is_empty() {
marks.push(' ');
}
marks.push('🔒');
}
marks
}
/// Gap between a pill and the clip outline's inner edge (so the pill sits 1 pt inside the outline).
pub(super) const PILL_INSET: f32 = 2.0;
pub(super) const PILL_HEIGHT: f32 = 14.0;
/// Horizontal padding between a pill's edge and its text.
pub(super) const PILL_PAD: f32 = 3.0;
/// The narrowest name pill worth drawing: its padding plus about one letter.
pub(super) const PILL_MIN_WIDTH: f32 = 12.0;
/// Half-transparent black behind white text, readable on the light and the dark clip bodies alike.
pub(super) const PILL_BG: Color32 = Color32::from_black_alpha(125);
/// Width of the name pill: the text plus its padding, capped to the `room` the clip leaves it (the text is then
/// cut cleanly at the pill's edge, with no ellipsis). `None` when there is no room for anything useful.
pub(super) fn name_pill_width(room: f32, text_w: f32) -> Option<f32> {
if room.is_nan() || room < PILL_MIN_WIDTH {
return None;
}
Some((text_w.max(0.0) + 2.0 * PILL_PAD).min(room))
}
/// Left edge of the marks pill, which sits at the clip's top-right: `None` when the clip is too narrow to hold it
/// (it would veil the clip), where `left` is the leftmost x a pill may use.
pub(super) fn marks_pill_left(left: f32, clip_right: f32, w: f32) -> Option<f32> {
let x = clip_right - PILL_INSET - w;
(x >= left).then_some(x)
}
/// The clip's name as a small rounded pill at its top-left, and its marks (rating, lock) as a matching pill at the
/// top-right. The name keeps clear of the marks and floats to the left edge of the lane when the clip starts
/// off-screen, so it stays readable while scrolling.
fn draw_clip_pills(painter: &egui::Painter, lane: Rect, r: Rect, name: Option<&str>, marks: &str) {
let p = painter.with_clip_rect(painter.clip_rect().intersect(r));
let pill = |rect: Rect, galley: Arc<egui::Galley>| {
p.rect_filled(rect, CornerRadius::same(3), PILL_BG);
let at = pos2(rect.min.x + PILL_PAD, rect.center().y - galley.size().y * 0.5);
p.with_clip_rect(p.clip_rect().intersect(rect)).galley(at, galley, Color32::WHITE);
};
let top = r.min.y + PILL_INSET;
let left = r.min.x.max(lane.min.x) + PILL_INSET;
let mut right = r.max.x.min(lane.max.x) - PILL_INSET;
if !marks.is_empty() {
let galley = p.layout_no_wrap(marks.to_owned(), regular(9.0), Color32::WHITE);
let w = galley.size().x + 2.0 * PILL_PAD;
if let Some(x) = marks_pill_left(left, r.max.x, w) {
right = right.min(x - PILL_INSET);
pill(Rect::from_min_size(pos2(x, top), vec2(w, PILL_HEIGHT)), galley);
}
}
// No layout where no pill fits: zoomed out on a large session, most clips are too narrow.
if let Some(name) = name.filter(|n| !n.is_empty() && right - left >= PILL_MIN_WIDTH) {
let galley = p.layout_no_wrap(name.to_owned(), bold(10.0), Color32::WHITE);
if let Some(w) = name_pill_width(right - left, galley.size().x) {
pill(Rect::from_min_size(pos2(left, top), vec2(w, PILL_HEIGHT)), galley);
}
}
}
/// The 1 pt outline around a clip.
const CLIP_OUTLINE: Color32 = Color32::from_rgb(10, 10, 10);
/// How a clip meets its neighbours in the playlist. Two clips butted at a cut share ONE 1 pt line, as in
/// the incumbent: the later clip draws it (its left edge), the earlier one drops its right edge, and both
/// sides of the cut have square corners. A gap or an overlap leaves the clip drawn on its own.
/// Selection only recolours the body, so it never changes which edges are drawn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ClipCut {
/// Starts exactly where the clip before it ends.
pub(super) left: bool,
/// Ends exactly where the clip after it starts.
pub(super) right: bool,
}
impl ClipCut {
/// The body's corners: square on a side that meets another clip, rounded otherwise.
pub(super) fn corners(self) -> CornerRadius {
let (nw, ne) = (if self.left { 0 } else { 2 }, if self.right { 0 } else { 2 });
CornerRadius { nw, ne, sw: nw, se: ne }
}
}
/// The cut of the clip spanning `start..end`, given the `(start, end)` of every other clip of its playlist, in any
/// order (a playlist's order is its stacking order, not its time order). A side is butted when another clip ends
/// (or starts) exactly there and no third clip covers that point.
pub(super) fn clip_cut(start: Samples, end: Samples, others: impl IntoIterator<Item = (Samples, Samples)>) -> ClipCut {
// An empty clip has no span to share a line with.
if end <= start {
return ClipCut::default();
}
let (mut left, mut right, mut left_covered, mut right_covered) = (false, false, false, false);
for (s, e) in others.into_iter().filter(|(s, e)| e > s) {
left |= e == start;
right |= s == end;
left_covered |= s < start && start < e;
right_covered |= s < end && end < e;
}
ClipCut { left: left && !left_covered, right: right && !right_covered }
}
/// [`clip_cut`] for `clip` among its playlist's `clips`, scanning them all.
pub(super) fn clip_cut_in(clips: &[Clip], clip: &Clip) -> ClipCut {
clip_cut(clip.start, clip.end(), clips.iter().filter(|c| c.id != clip.id).map(|c| (c.start, c.end())))
}
/// [`clip_cut`] for each clip of a playlist. Sorted by start (the usual case), one pass over the playlist and two
/// binary searches per clip, so large sessions do no per-clip scan every frame; unsorted, a scan per clip.
pub(super) fn clip_cuts(clips: &[Clip]) -> impl Fn(&Clip) -> ClipCut + '_ {
// reach[k]: the furthest end of the first k clips (empty clips reach nothing).
let reach: Option<Vec<Samples>> = clips.is_sorted_by_key(|c| c.start).then(|| {
std::iter::once(Samples::MIN)
.chain(clips.iter().scan(Samples::MIN, |far, c| {
if c.end() > c.start {
*far = (*far).max(c.end());
}
Some(*far)
}))
.collect()
});
move |clip| {
let Some(reach) = &reach else { return clip_cut_in(clips, clip) };
let (start, end) = (clip.start, clip.end());
if end <= start {
return ClipCut::default();
}
let reached = |k: usize| reach.get(k).copied().unwrap_or(Samples::MIN);
// Butted and uncovered on the left: the clips starting before it reach exactly its start. On the right: the
// clips starting before its end (itself included) reach exactly its end, and a clip starts there.
let before = clips.partition_point(|c| c.start < start);
let upto = clips.partition_point(|c| c.start < end);
let next = clips.get(upto..).unwrap_or_default().iter().take_while(|c| c.start == end).any(|c| c.end() > c.start);
ClipCut { left: reached(before) == start, right: next && reached(upto) == end }
}
}
/// The earlier clip of a crossfade pair: the one before `clip` in its playlist, overlapping its start.
fn crossfade_partner<'a>(track: &'a Track, clip: &Clip) -> Option<&'a Clip> {
let (p, i) = track.playlists.iter().find_map(|p| {
+1 -1
View File
@@ -315,7 +315,7 @@ fn trim_clip(app: &mut SoundApp, clip: ClipId, to: Samples, start: bool) {
pub(super) fn spot_or_run(app: &mut SoundApp, spot: Option<Spot>) {
let Some(spot) = spot else { return };
if app.engine.session().edit.edit_mode == EditMode::Spot {
app.dialogs.set(Dialog::Spot(spot));
app.dialogs.open = Some(Dialog::Spot(spot));
} else if let Some((id, params)) = spot.command(app.engine.session()) {
let _ = app.run(&id, params);
}
+37 -207
View File
@@ -1,8 +1,8 @@
use super::layout::STRIP_W;
use super::tracks::{click_track, folder_depth, height_targets, in_edit_window, track_context_menu, view_label, view_menu};
use super::{
Align2, AutoParam, Color32, Gesture, Pos2, Rect, Sense, Shape, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, bold,
groove, json, level_pos, meter_pos, pos2, raised_key, regular, rgb, shade, vec2,
Align2, AutoParam, Color32, Pos2, Rect, Sense, Shape, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, bold, groove, json,
level_pos, meter_pos, pos2, raised_key, regular, rgb, shade, vec2,
};
/// Draw one track header: resize edge, selection and context menu, folder/options control, automation-lane toggle,
@@ -94,11 +94,11 @@ fn strip_buttons(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
ui.painter().circle_filled(round.center(), 5.0, shade(strip, if rresp.hovered() { 0.6 } else { 0.45 }));
arrow(ui.painter(), round.center(), !track.is_folder() || track.folder_open, ink);
if track.is_folder() {
if rresp.on_hover_text(crate::localization::text(if track.folder_open { "Close folder" } else { "Open folder" })).clicked() {
if rresp.on_hover_text(if track.folder_open { "Close folder" } else { "Open folder" }).clicked() {
let _ = app.run("track.folder_toggle", json!({"track": id.0}));
}
} else {
egui::Popup::menu(&rresp.on_hover_text(crate::localization::text("Track options"))).show(|ui| track_context_menu(app, ui, id));
egui::Popup::menu(&rresp.on_hover_text("Track options")).show(|ui| track_context_menu(app, ui, id));
}
if h >= 40.0 && track.kind.has_playlist() {
let ar = at(3.0, h - 12.0, 9.0, 9.0);
@@ -109,7 +109,7 @@ fn strip_buttons(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
ui.painter().line_segment([a, b], Stroke::new(1.0, ink));
ui.painter().circle_filled(a, 1.3, ink);
ui.painter().circle_filled(b, 1.3, ink);
if aresp.on_hover_text(crate::localization::text(if showing { "Hide automation" } else { "Show volume automation" })).clicked() {
if aresp.on_hover_text(if showing { "Hide automation" } else { "Show volume automation" }).clicked() {
let view = if !showing {
"volume"
} else if track.kind.is_midi() {
@@ -199,14 +199,14 @@ fn playlist_menu(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, hea
let presp = ui.interact(pl_r, ui.scope_id().with(("pl", id.0)), Sense::click());
ui.painter().rect_filled(pl_r, 1.5, shade(head_bg, if presp.hovered() { -0.2 } else { -0.35 }));
arrow(ui.painter(), pos2(pl_r.center().x, pl_r.min.y + 5.75), true, t.text);
egui::Popup::menu(&presp.on_hover_text(crate::localization::text("Playlists"))).show(|ui| {
if ui.button(crate::localization::text("New...")).clicked() {
egui::Popup::menu(&presp.on_hover_text("Playlists")).show(|ui| {
if ui.button("New...").clicked() {
let _ = app.run("track.playlist_new", json!({"track": id.0}));
}
if ui.button(crate::localization::text("Duplicate...")).clicked() {
if ui.button("Duplicate...").clicked() {
let _ = app.run("track.playlist_duplicate", json!({"track": id.0}));
}
if ui.button(crate::localization::text("Delete Unused...")).clicked() {
if ui.button("Delete Unused...").clicked() {
let _ = app.run("track.playlist_delete_unused", json!({"track": id.0}));
}
ui.separator();
@@ -256,10 +256,10 @@ fn view_selector(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
ui,
at(17.0, view_y, 105.0, 17.0),
ui.scope_id().with(("view", id.0)),
crate::localization::text(&view_label(&track.view)),
&view_label(&track.view),
t.text,
true,
&crate::localized_format!("Track view for {}", track.name),
&format!("Track view for {}", track.name),
);
egui::Popup::menu(&vresp).show(|ui| view_menu(app, ui, track));
}
@@ -272,19 +272,11 @@ fn view_selector(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
soundcraft_model::AutomationMode::Latch => t.auto_latch,
_ => t.text_dim,
};
let mode_name = crate::localized_format!("Automation mode for {}", track.name);
let aresp = header_selector(
ui,
at(17.0, 39.0, 105.0, 17.0),
ui.scope_id().with(("auto_mode", id.0)),
crate::localization::text(mode.label()),
col,
true,
&mode_name,
);
let mode_name = format!("Automation mode for {}", track.name);
let aresp = header_selector(ui, at(17.0, 39.0, 105.0, 17.0), ui.scope_id().with(("auto_mode", id.0)), mode.label(), col, true, &mode_name);
egui::Popup::menu(&aresp).show(|ui| {
for m in soundcraft_model::AutomationMode::ALL {
if ui.selectable_label(m == mode, crate::localization::text(m.label())).clicked() {
if ui.selectable_label(m == mode, m.label()).clicked() {
let _ = app.run("mix.automation_mode", json!({"track": id.0, "mode": m.label()}));
}
}
@@ -311,25 +303,17 @@ fn voice_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
let d = vec2(a.to_radians().sin(), a.to_radians().cos()) * 3.5;
ui.painter().line_segment([r.center() - d, r.center() + d], Stroke::new(1.5, t.text));
}
if resp.on_hover_text(crate::localization::text(if track.frozen { "Unfreeze" } else { "Freeze" })).clicked() {
if resp.on_hover_text(if track.frozen { "Unfreeze" } else { "Freeze" }).clicked() {
let _ = app.run("track.freeze", json!({"tracks": [id.0]}));
}
}
if !matches!(track.kind, TrackKind::Master | TrackKind::Vca | TrackKind::Folder) {
let (voice, color) = if track.inactive { ("off", t.text_dim) } else { ("dyn", t.text) };
let voice_name = crate::localized_format!("Voice for {}", track.name);
let resp = header_selector(
ui,
at(31.0, 57.0, 31.0, 17.0),
ui.scope_id().with(("voice", id.0)),
crate::localization::text(voice),
color,
false,
&voice_name,
);
egui::Popup::menu(&resp.on_hover_text(crate::localization::text("Voice: dyn plays the track, off makes it inactive"))).show(|ui| {
let voice_name = format!("Voice for {}", track.name);
let resp = header_selector(ui, at(31.0, 57.0, 31.0, 17.0), ui.scope_id().with(("voice", id.0)), voice, color, false, &voice_name);
egui::Popup::menu(&resp.on_hover_text("Voice: dyn plays the track, off makes it inactive")).show(|ui| {
for (label, inactive) in [("dyn", false), ("off", true)] {
if ui.selectable_label(track.inactive == inactive, crate::localization::text(label)).clicked() {
if ui.selectable_label(track.inactive == inactive, label).clicked() {
let _ = app.run("track.make_inactive", json!({"tracks": [id.0], "inactive": inactive}));
}
}
@@ -343,19 +327,11 @@ fn voice_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect) {
soundcraft_model::AutomationMode::Latch => t.auto_latch,
_ => t.text_dim,
};
let mode_name = crate::localized_format!("Automation mode for {}", track.name);
let aresp = header_selector(
ui,
at(63.0, 57.0, 59.0, 17.0),
ui.scope_id().with(("auto_mode", id.0)),
crate::localization::text(mode.label()),
col,
true,
&mode_name,
);
let mode_name = format!("Automation mode for {}", track.name);
let aresp = header_selector(ui, at(63.0, 57.0, 59.0, 17.0), ui.scope_id().with(("auto_mode", id.0)), mode.label(), col, true, &mode_name);
egui::Popup::menu(&aresp).show(|ui| {
for m in soundcraft_model::AutomationMode::ALL {
if ui.selectable_label(m == mode, crate::localization::text(m.label())).clicked() {
if ui.selectable_label(m == mode, m.label()).clicked() {
let _ = app.run("mix.automation_mode", json!({"track": id.0, "mode": m.label()}));
}
}
@@ -402,13 +378,10 @@ fn field_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, head_bg
let resp = ui.interact(field, ui.scope_id().with(("field", id.0)), Sense::click());
ui.painter().rect_filled(field, 2.0, shade(head_bg, if resp.hovered() { -0.02 } else { -0.1 }));
if track.kind == TrackKind::Instrument {
let name = track
.instrument
.as_ref()
.and_then(|i| crate::mix_window::plugin_info(&i.plugin))
.map_or_else(|| crate::localization::text("no instrument"), |p| p.short_name);
let name =
track.instrument.as_ref().and_then(|i| crate::mix_window::plugin_info(&i.plugin)).map_or("no instrument", |p| p.short_name);
ui.painter().with_clip_rect(field).text(pos2(field.min.x + 5.0, field.center().y), Align2::LEFT_CENTER, name, bold(10.0), t.text);
egui::Popup::menu(&resp.on_hover_text(crate::localization::text("Instrument")))
egui::Popup::menu(&resp.on_hover_text("Instrument"))
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show(|ui| crate::mix_window::instrument_menu(app, ui, id));
} else {
@@ -424,7 +397,7 @@ fn field_row(app: &mut SoundApp, ui: &mut Ui, track: &Track, head: Rect, head_bg
t.text,
);
}
egui::Popup::menu(&resp.on_hover_text(crate::localization::text("Elastic Audio"))).show(|ui| {
egui::Popup::menu(&resp.on_hover_text("Elastic Audio")).show(|ui| {
for alg in ["none", "polyphonic", "rhythmic", "monophonic", "varispeed", "x-form"] {
let current = track.elastic.as_deref().unwrap_or("none") == alg;
if ui.selectable_label(current, soundcraft_engine::feature_names::display_label(alg)).clicked() {
@@ -454,7 +427,6 @@ pub(super) fn header_selector(ui: &Ui, r: Rect, id: egui::Id, text: &str, color:
let resp = ui.interact(r, id, Sense::click());
resp.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::accesskit::Role::ComboBox, ui.is_enabled(), name);
// `text` can be a user-defined route name (a bus called "File"), so show it unchanged.
info.current_text_value = Some(text.to_string());
info
});
@@ -479,23 +451,14 @@ enum HeaderKey {
/// mute that another track's solo implies). Record keys stay dark red when off, as in Pro Tools.
fn header_toggle(ui: &Ui, r: Rect, track: TrackId, track_name: &str, key: HeaderKey, lit: bool, implied: bool) -> egui::Response {
let t = Tokens::current();
let (source_label, color) = match key {
let (label, color) = match key {
HeaderKey::Rec => ("Record enable", t.rec),
HeaderKey::Input => ("Input monitoring", t.input),
HeaderKey::Solo => ("Solo", t.solo),
HeaderKey::Mute => ("Mute", t.mute),
};
let label = crate::localization::text(source_label);
// Fixed badges, independent of the translated label: in some languages the translated
// labels for two different buttons would otherwise start with the same letter.
let badge = match key {
HeaderKey::Rec => "",
HeaderKey::Input => "I",
HeaderKey::Solo => "S",
HeaderKey::Mute => "M",
};
let name = crate::localized_format!("{} for {}", label, track_name);
let resp = ui.interact(r, ui.scope_id().with((source_label, track.0)), Sense::click());
let name = format!("{label} for {track_name}");
let resp = ui.interact(r, ui.scope_id().with((label, track.0)), Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), lit, &name));
let rec = key == HeaderKey::Rec;
let (tint, k) = if lit {
@@ -519,7 +482,7 @@ fn header_toggle(ui: &Ui, r: Rect, track: TrackId, track_name: &str, key: Header
if rec {
ui.painter().circle_filled(r.center(), 4.0, if lit { Color32::WHITE } else { t.text.lerp_to_gamma(color, 0.3) });
} else {
ui.painter().text(r.center(), Align2::CENTER_CENTER, badge, bold(11.0), ink);
ui.painter().text(r.center(), Align2::CENTER_CENTER, label.get(..1).unwrap_or_default(), bold(11.0), ink);
}
resp.on_hover_text(label)
}
@@ -569,7 +532,7 @@ pub(super) fn header_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, col:
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r.shrink(3.0)));
let field = crate::widgets::named_text_field(
child.add(egui::TextEdit::multiline(&mut c).desired_width(r.width() - 6.0).font(regular(10.0))),
&crate::localized_format!("Comments for {}", track.name),
&format!("Comments for {}", track.name),
);
if field.changed() {
let _ =
@@ -587,11 +550,10 @@ fn io_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, r: Rect) {
ui.painter().rect_filled(r, 0.0, t.slot_well);
let ui = column_ui(ui, "io", r);
let row = |y: f32, h: f32| (r.height() >= y + h + 1.0).then_some(Rect::from_min_size(r.min + vec2(7.0, y), vec2(r.width() - 14.0, h)));
if let Some(input) = row(4.0, 15.0).filter(|_| crate::mix_window::has_input_selector(track.kind)) {
if let Some(input) = row(4.0, 15.0) {
let input_name = crate::mix_window::input_name(app, track);
let name = crate::localized_format!("Input for {}", track.name);
let resp = header_selector(&ui, input, ui.scope_id().with(("in", id.0)), &input_name, t.text, true, &name);
crate::mix_window::route_popup(app, &resp.on_hover_text(crate::localization::text("Input")), id, true);
let resp = header_selector(&ui, input, ui.scope_id().with(("in", id.0)), &input_name, t.text, true, &format!("Input for {}", track.name));
crate::mix_window::route_popup(app, &resp.on_hover_text("Input"), id, true);
}
if let Some(out) = row(21.0, 17.0) {
let (sel, fader) = (out.with_max_x(out.max.x - 11.0), out.with_min_x(out.max.x - 11.0));
@@ -609,8 +571,8 @@ fn io_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, r: Rect) {
let c = fader.center() + vec2(0.5, 0.0);
ui.painter().vline(c.x, c.y - 5.0..=c.y + 5.0, Stroke::new(1.0, t.text));
ui.painter().rect_filled(Rect::from_center_size(c + vec2(0.0, -1.5), vec2(5.0, 2.5)), 0.5, t.text);
crate::mix_window::route_popup(app, &resp.on_hover_text(crate::localization::text("Output")), id, false);
if fresp.on_hover_text(crate::localization::text("Show in the Mix window")).clicked() {
crate::mix_window::route_popup(app, &resp.on_hover_text("Output"), id, false);
if fresp.on_hover_text("Show in the Mix window").clicked() {
let _ = app.run("edit.select", json!({"tracks": [id.0]}));
let _ = app.run("window.mix", json!({}));
}
@@ -622,143 +584,11 @@ fn io_column(app: &mut SoundApp, ui: &mut Ui, track: &Track, r: Rect) {
let pan = m.pan.first().map_or("-".into(), |p| crate::widgets::pan_text(*p));
// The readout is black in both themes, so it takes the dark palette's green.
let ink = Tokens::DARK.counter_text;
// The two rows are buttons: a click opens a fader or pan sliders, an Alt-click resets.
// The Mix window's strip has no stereo pan for a VCA or for a track on a multichannel output (it shows a surround panner), so the pan stays text.
// ponytail: surround-panned tracks are placed in the Mix window. Upgrade: `widgets::surround_panner` in the pan popup.
let pannable = !m.pan.is_empty() && track.kind != TrackKind::Vca && !crate::mix_window::surround_panned(app, track);
let vol_row = Rect::from_x_y_ranges(vr.x_range(), vr.min.y + 1.5..=vr.min.y + 14.0).shrink2(vec2(1.5, 0.0));
let pan_row = Rect::from_x_y_ranges(vr.x_range(), vr.min.y + 15.0..=vr.max.y - 1.5).shrink2(vec2(1.5, 0.0));
let vol_text = crate::widgets::db_text(m.volume_db);
let vol = readout_button(
&ui,
vol_row,
ui.scope_id().with(("vol", id.0)),
&format!("{} volume", track.name),
&vol_text,
"Volume: click for a fader, Alt-click for 0 dB",
);
let pan_resp = pannable.then(|| {
readout_button(
&ui,
pan_row,
ui.scope_id().with(("pan", id.0)),
&format!("{} pan", track.name),
&pan,
"Pan: click for sliders, Alt-click to reset",
)
});
let alt = ui.input(|i| i.modifiers.alt);
if vol.clicked() && alt && m.volume_db.abs() > f32::EPSILON {
// Merged, so a reset during an automation pass joins the pass's undo step; the merge ends by itself on the next frame.
let _ = app.engine.execute_merged("mix.volume", &json!({"track": id.0, "db": 0.0}), &format!("fader:{}", id.0));
}
if let Some(resp) = &pan_resp
&& resp.clicked()
&& alt
{
reset_pan(app, track);
}
for (y, label, value) in [(7.5, "vol", vol_text), (22.0, "pan", pan)] {
for (y, label, value) in [(7.5, "vol", crate::widgets::db_text(m.volume_db)), (22.0, "pan", pan)] {
ui.painter().text(pos2(vr.min.x + 7.0, vr.min.y + y), Align2::LEFT_CENTER, label, bold(10.0), ink);
ui.painter().text(pos2(vr.max.x - 6.5, vr.min.y + y), Align2::RIGHT_CENTER, value, bold(10.0), ink);
}
ui.painter().hline(vr.min.x + 7.0..=vr.max.x - 6.0, vr.min.y + 14.5, Stroke::new(1.0, Color32::from_gray(35)));
readout_popup(&vol, !alt).show(|ui| volume_fader(app, ui, track));
if let Some(resp) = &pan_resp {
readout_popup(resp, !alt).show(|ui| pan_sliders(app, ui, track));
}
}
}
/// A readout row of the I/O column as a button, named `name` (the track's, so two tracks showing the same value differ) and its value. It lights up under the pointer, with the keyboard focus or while its popup is open,
/// and paints nothing otherwise, so an untouched column looks the same as before.
fn readout_button(ui: &Ui, r: Rect, id: egui::Id, name: &str, value: &str, tip: &str) -> egui::Response {
let resp = ui.interact(r, id, Sense::click()).on_hover_text(tip).on_hover_cursor(egui::CursorIcon::PointingHand);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{name} {value}")));
if resp.hovered() || resp.has_focus() || egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&resp)) {
ui.painter().rect_filled(r, 1.5, Color32::from_gray(38));
}
resp
}
/// The popup of a readout button, to its right so it doesn't hide the tracks below. An Alt-click
/// resets instead of opening (`toggle` false). Clicks inside it keep it open; Escape or a click outside closes it.
fn readout_popup(resp: &egui::Response, toggle: bool) -> egui::Popup<'static> {
egui::Popup::from_response(resp)
.open_memory((toggle && resp.clicked()).then_some(egui::SetOpenCommand::Toggle))
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.align(egui::RectAlign::RIGHT_START)
.gap(2.0)
}
/// What a panner returns to: centre on a mono track, hard left or right on a stereo one, as on a new track.
fn default_pan(track: &Track, index: usize) -> f32 {
soundcraft_model::Mixer::new(track.format).pan.get(index).copied().unwrap_or(0.0)
}
/// Put every panner of the track (L and R on a stereo one) back to its default, as one undo step. The merge ends by itself on the next frame.
fn reset_pan(app: &mut SoundApp, track: &Track) {
let key = format!("pan-reset:{}", track.id.0);
for (i, now) in track.mixer.pan.iter().enumerate().take(2) {
let to = default_pan(track, i);
// Only a real change may start the merged step: a no-op first call would leave the next one folded into an older edit.
if (now - to).abs() > f32::EPSILON {
let _ = app.engine.execute_merged("mix.pan", &json!({"track": track.id.0, "pan": to, "index": i}), &key);
}
}
}
/// The volume popup: a fader like the Mix window's, over a readout that takes a typed value.
/// A drag is one undo step and goes through [`Gesture::Fader`], so Touch and Latch automation write it.
fn volume_fader(app: &mut SoundApp, ui: &mut Ui, track: &Track) {
let t = Tokens::current();
let id = track.id;
let db = track.mixer.volume_db;
let key = format!("fader:{}", id.0);
let (well, _) = ui.allocate_exact_size(vec2(56.0, 16.0), Sense::hover());
crate::widgets::inset(ui.painter(), well, t.counter_bg);
let readout_id = ui.scope_id().with(("io-vol", id.0));
let (_, typed) = crate::mix_window::editable_readout(
ui,
well,
readout_id,
crate::mix_window::Readout {
name: &format!("{} volume", track.name),
display: &crate::widgets::db_text(db),
edit_initial: &format!("{db:.1}"),
parse: crate::mix_window::parse_db,
reset: 0.0,
},
);
if let Some(db) = typed {
let _ = app.engine.execute_merged("mix.volume", &json!({"track": id.0, "db": db}), &key);
}
ui.add_space(4.0);
// ponytail: the fader is drawn, not focusable, so the keyboard sets the volume in the readout above it. Upgrade: arrow keys in `widgets::fader`.
let (slot, _) = ui.allocate_exact_size(vec2(56.0, 170.0), Sense::hover());
if let Some(moved) = crate::widgets::fader(ui, slot, db, ui.scope_id().with(("io-fader", id.0)), &format!("{} level", track.name)) {
app.gesture = Some(Gesture::Fader { track: id, start_db: db });
let _ = app.engine.execute_merged("mix.volume", &json!({"track": id.0, "db": moved}), &key);
}
}
/// The pan popup: one slider, or L and R on a stereo track. A drag is one undo step per panner.
fn pan_sliders(app: &mut SoundApp, ui: &mut Ui, track: &Track) {
ui.spacing_mut().slider_width = 120.0;
let stereo = track.mixer.pan.len() > 1;
for (i, side) in ["L", "R"].into_iter().enumerate().take(track.mixer.pan.len()) {
let before = track.mixer.pan.get(i).copied().unwrap_or(0.0);
let mut pan = before;
// ponytail: no double-click reset on the sliders; the readout's Alt-click resets every panner at once.
// No step either: a slider rounds to it when drawn, which would rewrite a pan off the grid just by opening the popup.
let slider = egui::Slider::new(&mut pan, -1.0..=1.0)
.text(if stereo { side } else { "Pan" })
.custom_formatter(|v, _| crate::widgets::pan_text(v as f32))
.custom_parser(|s| crate::mix_window::parse_pan(s).map(f64::from));
ui.add(slider);
if (pan - before).abs() > f32::EPSILON {
let _ = app.engine.execute_merged("mix.pan", &json!({"track": track.id.0, "pan": pan, "index": i}), &format!("pan:{}:{i}", track.id.0));
}
}
}
+9 -15
View File
@@ -1,5 +1,5 @@
use super::automation::{automation_id, breakpoint_at, plugin_range, shown_automation};
use super::clips::fade_control_position;
use super::clips::{clip_name_height, fade_control_position};
use super::drag::{drag_snap, fade_curve_drag_value, fade_drag_range, spot_or_run};
use super::layout::{sample_at, x_of};
use super::{
@@ -24,7 +24,7 @@ fn fade_handle_at(s: &Session, tl: Rect, lane: Rect, clip: &Clip, p: Pos2) -> Op
if clip.length <= 0 || clip.end() <= clip.start {
return None;
}
let y = lane.min.y + 1.0;
let y = lane.min.y + 1.0 + clip_name_height(s, lane);
[(true, clip.fade_in), (false, clip.fade_out)]
.into_iter()
.filter(|(_, fade)| fade.len > 0)
@@ -55,7 +55,7 @@ pub(super) fn fade_midpoint(s: &Session, tl: Rect, lane: Rect, clip: &Clip, fade
if b - a < 32.0 {
return None;
}
let body = Rect::from_min_max(pos2(a, lane.min.y + 1.0), pos2(b, lane.max.y - 1.0));
let body = Rect::from_min_max(pos2(a, lane.min.y + 1.0 + clip_name_height(s, lane)), pos2(b, lane.max.y - 1.0));
let p = fade_control_position(fade, a, b, body);
lane.contains(p).then_some(p)
}
@@ -277,7 +277,7 @@ fn start_gesture(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::
{
let fade = if fade_in { c.fade_in } else { c.fade_out };
let anchor = (origin.y, fade.gain(0.5));
let height = (lane.height() - 2.0).max(1.0);
let height = (lane.height() - 2.0 - clip_name_height(s, lane)).max(1.0);
app.gesture = Some(Gesture::FadeCurve { clip: c.id, fade_in, curvature: fade_curve_drag_value(fade, anchor, height, p.y), anchor, height });
ui.ctx().request_repaint();
} else if resp.drag_started()
@@ -356,20 +356,14 @@ fn lane_click(app: &mut SoundApp, ui: &mut Ui, c: &LaneCtx<'_>, resp: &egui::Res
ids.push(c.id.0);
let _ = app.run("edit.select", json!({"clips": ids}));
if s.edit.edit_mode == EditMode::Spot {
match Spot::clips(s, vec![c.id], None, 0) {
Some(spot) => app.dialogs.set(Dialog::Spot(spot)),
None => app.dialogs.open = None,
}
app.dialogs.open = Spot::clips(s, vec![c.id], None, 0).map(Dialog::Spot);
}
}
}
Tool::Trim if s.edit.edit_mode == EditMode::Spot && hit.is_some() => {
if let Some(c) = &hit {
let start = at - c.start < c.end() - at;
match Spot::trim(s, c.id, start, if start { c.start } else { c.end() }) {
Some(spot) => app.dialogs.set(Dialog::Spot(spot)),
None => app.dialogs.open = None,
}
app.dialogs.open = Spot::trim(s, c.id, start, if start { c.start } else { c.end() }).map(Dialog::Spot);
}
}
Tool::Zoom => {
@@ -513,7 +507,7 @@ pub(super) fn new_midi_clip(app: &mut SoundApp, s: &Session, track: TrackId, fro
fn clip_context_menu(app: &mut SoundApp, ui: &mut Ui, clip: Option<ClipId>) {
let Some(c) = clip else {
if ui.button(crate::localization::text("Paste")).clicked() {
if ui.button("Paste").clicked() {
let _ = app.run("edit.paste", json!({}));
}
return;
@@ -535,11 +529,11 @@ fn clip_context_menu(app: &mut SoundApp, ui: &mut Ui, clip: Option<ClipId>) {
}
}
ui.separator();
if ui.button(crate::localization::text("Rename...")).clicked() {
if ui.button("Rename...").clicked() {
let name = app.engine.session().find_clip(c).map(|(_, x)| x.name.clone()).unwrap_or_default();
app.dialogs.open_rename_clip(c, &name);
}
if ui.button(crate::localization::text("Delete")).clicked() {
if ui.button("Delete").clicked() {
let s = app.engine.session();
let selected: Vec<u64> = s.edit.selected_clips.iter().map(|id| id.0).collect();
let track: Vec<u64> = s.find_clip(c).map(|(t, _)| t.0).into_iter().collect();
+1 -7
View File
@@ -4,12 +4,6 @@ use super::layout::x_of;
use super::scroll::{FollowFrame, follow_update};
use super::{Color32, Gesture, Rect, Samples, Shape, SoundApp, Stroke, StrokeKind, Tokens, TrackId, Ui, json, ops, pos2, rgb};
/// The playback cursor is red only while recording; plain playback draws it in its own neutral
/// grey, apart from the insertion colour of the edit cursor that stands beside it.
pub(super) fn playhead_colour(t: &Tokens, recording: bool) -> Color32 {
if recording { t.playhead } else { t.playback }
}
/// Selection overlay, insertion point and playhead across rulers and tracks.
/// While playing, auto-scroll keeps the playhead in view for the follow
/// modes (`page`/`continuous`/`center`) — but any outside view move (a manual
@@ -67,7 +61,7 @@ pub(super) fn overlay(app: &mut SoundApp, ui: &mut Ui, tl: Rect, area: Rect) {
}
if app.is_playing() {
let x = x_of(s, tl, app.position());
painter.line_segment([pos2(x, area.min.y), pos2(x, area.max.y)], Stroke::new(1.5, playhead_colour(&t, app.engine.transport.recording)));
painter.line_segment([pos2(x, area.min.y), pos2(x, area.max.y)], Stroke::new(1.5, t.playhead));
// Session reads first (owned copies), then the layout mutation: the
// two borrow disjoint fields.
let pos = app.position();
+9 -21
View File
@@ -99,13 +99,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
let lab = Rect::from_min_max(pos2(area.min.x, y0), pos2(area.min.x + HEADER_W, y0 + h));
y0 += h;
let painter = ui.painter().with_clip_rect(row);
ui.painter().text(
pos2(lab.max.x - 12.0, lab.center().y),
Align2::RIGHT_CENTER,
crate::localization::text(ruler_label(id)),
bold(11.0),
t.ruler_text,
);
ui.painter().text(pos2(lab.max.x - 12.0, lab.center().y), Align2::RIGHT_CENTER, ruler_label(id), bold(11.0), t.ruler_text);
let fmt = TimeFormat::from_id(id);
match id.as_str() {
"tempo" => {
@@ -116,7 +110,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
{
let at = snap(&s, sample_at(&s, tl, p.x).max(0));
let bpm = s.tempo.tempo_at_tick(s.tempo.samples_to_ticks(at, sr));
app.dialogs.set(crate::dialogs::Dialog::TempoChange { at, bpm });
app.dialogs.open = Some(crate::dialogs::Dialog::TempoChange { at, bpm });
}
let mut last_label = f32::MIN;
for ev in s.tempo.tempos() {
@@ -157,13 +151,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
"key" => {
painter.rect_filled(row, 0.0, Color32::from_rgb(64, 52, 88));
if s.key_signatures.is_empty() {
painter.text(
pos2(tl.min.x + 6.0, row.center().y),
Align2::LEFT_CENTER,
crate::localization::text("C major"),
bold(11.0),
Color32::from_rgb(220, 214, 236),
);
painter.text(pos2(tl.min.x + 6.0, row.center().y), Align2::LEFT_CENTER, "C major", bold(11.0), Color32::from_rgb(220, 214, 236));
}
for (at, k) in &s.key_signatures {
let x = x_of(&s, tl, *at);
@@ -386,7 +374,7 @@ pub(super) fn column_titles(ui: &Ui, rulers: Rect, cols: &[Column]) {
ui.painter().vline(end - 0.5, row.y_range(), line);
for &(_, _, title, w) in cols {
ui.painter().vline(x + 0.5, row.y_range(), line);
ui.painter().text(pos2(x + w / 2.0, row.center().y), Align2::CENTER_CENTER, crate::localization::text(title), bold(10.0), t.section_label);
ui.painter().text(pos2(x + w / 2.0, row.center().y), Align2::CENTER_CENTER, title, bold(10.0), t.section_label);
x += w;
}
}
@@ -395,9 +383,9 @@ pub(super) fn column_titles(ui: &Ui, rulers: Rect, cols: &[Column]) {
pub(super) fn views_button(app: &mut SoundApp, ui: &mut Ui, rulers: Rect) {
let r = Rect::from_min_size(rulers.min + vec2(6.0, 5.0), vec2(50.0, 18.0));
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r));
let resp = crate::widgets::selector_box(&mut child, r.width(), r.height(), crate::localization::text("Views"), Tokens::current().text);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, child.is_enabled(), crate::localization::text("Views")));
let resp = resp.on_hover_text(crate::localization::text("Columns beside the track headers: inserts, sends, I/O…"));
let resp = crate::widgets::selector_box(&mut child, r.width(), r.height(), "Views", Tokens::current().text);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, child.is_enabled(), "Views"));
let resp = resp.on_hover_text("Columns beside the track headers: inserts, sends, I/O…");
egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
let shown = edit_columns(app.engine.session());
for (id, label, _, _) in COLUMNS {
@@ -406,10 +394,10 @@ pub(super) fn views_button(app: &mut SoundApp, ui: &mut Ui, rulers: Rect) {
}
}
ui.separator();
if ui.button(crate::localization::text("All")).clicked() {
if ui.button("All").clicked() {
let _ = app.run("view.edit_all", json!({}));
}
if ui.button(crate::localization::text("Minimal")).clicked() {
if ui.button("Minimal").clicked() {
let _ = app.run("view.edit_minimal", json!({}));
}
});
+1 -326
View File
@@ -1043,7 +1043,7 @@ fn fade_midpoint_handles_remain_visible_and_can_be_grabbed_again() {
h.step();
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeVertical);
start_drag(&mut h, control);
let to = control - vec2(0.0, (lane.height() - 2.0) * 0.1);
let to = control - vec2(0.0, (lane.height() - 2.0 - clip_name_height(&before, lane)) * 0.1);
h.hover_at(to);
h.step();
assert!(
@@ -1574,331 +1574,6 @@ fn alt_click_on_a_breakpoint_deletes_it() {
}
}
const ALONE: ClipCut = ClipCut { left: false, right: false };
#[test]
fn butted_pair_shares_one_seam() {
// 0..100 then 100..200: the first drops its right edge, the second draws the seam on its left.
assert_eq!(clip_cut(0, 100, [(100, 200)]), ClipCut { left: false, right: true });
assert_eq!(clip_cut(100, 200, [(0, 100)]), ClipCut { left: true, right: false });
}
#[test]
fn middle_clip_of_a_run_is_butted_on_both_sides() {
let cut = clip_cut(100, 200, [(0, 100), (200, 300)]);
assert_eq!(cut, ClipCut { left: true, right: true });
let c = cut.corners();
assert_eq!((c.nw, c.sw, c.ne, c.se), (0, 0, 0, 0));
}
#[test]
fn gap_overlap_and_lone_clips_keep_their_own_outline() {
// First and last clips: nothing on the open side.
assert_eq!(clip_cut(0, 100, []), ALONE);
// A gap of one sample is not a cut.
assert_eq!(clip_cut(101, 200, [(0, 100), (201, 300)]), ALONE);
// Overlaps (crossfades, layers) keep both outlines.
assert_eq!(clip_cut(90, 200, [(0, 100), (150, 300)]), ALONE);
assert_eq!(clip_cut(0, 100, [(60, 160)]), ALONE);
// A third clip lying across the cut hides it: no shared seam.
assert_eq!(clip_cut(100, 200, [(0, 100), (50, 150)]), ALONE);
// Empty clips share nothing, and are not neighbours either.
assert_eq!(clip_cut(100, 100, [(0, 100), (100, 200)]), ALONE);
assert_eq!(clip_cut(100, 200, [(100, 100)]), ALONE);
}
#[test]
fn sorted_playlists_find_the_same_cuts_without_a_scan() {
let layouts: [&[(Samples, Samples)]; 8] = [
&[(0, 100), (100, 100)],
&[(0, 100), (100, 100), (200, 100)],
&[(0, 100), (101, 99), (201, 99)],
&[(0, 100), (90, 110), (150, 150)],
&[(0, 100), (50, 100), (100, 100)],
&[(0, 100), (100, 0), (100, 100)],
&[(0, 1000), (100, 100), (200, 100)],
&[(0, 100), (100, 50), (100, 100), (200, 100)],
];
for spans in layouts {
let clips: Vec<Clip> = spans.iter().zip(1..).map(|(&(start, len), id)| test_clip(id, start, len)).collect();
let cut_of = clip_cuts(&clips);
for c in &clips {
assert_eq!(cut_of(c), clip_cut_in(&clips, c), "{spans:?}, clip at {}", c.start);
}
}
// Not vacuous: the middle clip of a run is butted on both sides.
let run: Vec<Clip> = (0..3).map(|i| test_clip(i + 1, i as Samples * 100, 100)).collect();
assert_eq!(clip_cuts(&run)(&run[1]), ClipCut { left: true, right: true });
}
#[test]
fn only_butted_sides_lose_their_round_corners() {
let round = ALONE.corners();
assert_eq!((round.nw, round.sw, round.ne, round.se), (2, 2, 2, 2));
let first = ClipCut { left: false, right: true }.corners();
assert_eq!((first.nw, first.sw, first.ne, first.se), (2, 2, 0, 0));
let second = ClipCut { left: true, right: false }.corners();
assert_eq!((second.nw, second.sw, second.ne, second.se), (0, 0, 2, 2));
}
#[test]
fn name_pill_is_as_wide_as_its_text_and_cut_cleanly_on_short_clips() {
// Room to spare: the text plus its padding on both sides.
assert_eq!(name_pill_width(200.0, 50.0), Some(50.0 + 2.0 * PILL_PAD));
// A short clip caps the pill at the room it leaves; the text is then cut at the pill's edge.
assert_eq!(name_pill_width(30.0, 80.0), Some(30.0));
assert_eq!(name_pill_width(PILL_MIN_WIDTH, 80.0), Some(PILL_MIN_WIDTH));
// Too narrow to show anything useful, or nonsense numbers: no pill.
assert_eq!(name_pill_width(PILL_MIN_WIDTH - 0.1, 80.0), None);
assert_eq!(name_pill_width(-5.0, 80.0), None);
assert_eq!(name_pill_width(f32::NAN, 80.0), None);
// A bogus text width never makes a negative or NaN pill.
assert_eq!(name_pill_width(100.0, f32::NAN), Some(2.0 * PILL_PAD));
assert_eq!(name_pill_width(100.0, -40.0), Some(2.0 * PILL_PAD));
}
#[test]
fn marks_list_the_rating_and_the_lock() {
let mut clip = test_clip(1, 0, 100);
assert_eq!(clip_marks(&clip, true), "");
clip.rating = 3;
assert_eq!(clip_marks(&clip, true), "★★★");
assert_eq!(clip_marks(&clip, false), "");
clip.edit_locked = true;
assert_eq!(clip_marks(&clip, true), "★★★ 🔒");
assert_eq!(clip_marks(&clip, false), "🔒");
clip.rating = 200;
assert_eq!(clip_marks(&clip, true), "★★★★★ 🔒");
}
#[test]
fn the_clip_name_is_a_pill_over_the_waveform_not_a_bar() {
for show_name in [true, false] {
let mut h = smart_demo();
h.state_mut().engine.execute("view.clip_name", &json!({"value": show_name})).unwrap();
h.step();
let tl = timeline(&h);
let (clip, lane) = clip_on_screen(&h, |xs, xe| xs > tl.min.x + 30.0 && xe < tl.max.x - 100.0 && xe - xs > 100.0);
let s = h.state().engine.session();
let (xs, xe) = (x_of(s, tl, clip.start), x_of(s, tl, clip.end()));
let clip_rect = Rect::from_min_max(pos2(xs, lane.min.y), pos2(xe, lane.max.y));
let shapes = &h.output().shapes;
let pills: Vec<Rect> = shapes
.iter()
.filter_map(|shape| match &shape.shape {
Shape::Rect(r) if r.fill == PILL_BG && clip_rect.contains_rect(r.rect) => Some(r.rect),
_ => None,
})
.collect();
if !show_name {
assert!(pills.is_empty(), "names are off");
continue;
}
assert_eq!(pills.len(), 1, "one pill per clip");
let pill = pills[0];
// At the top-left, 1 pt inside the outline, as wide as its text plus padding: far from a full-width bar.
assert_eq!(pill.min, pos2(xs + PILL_INSET, lane.min.y + 1.0 + PILL_INSET));
assert_eq!(pill.height(), PILL_HEIGHT);
let text_w = shapes
.iter()
.find_map(|shape| match &shape.shape {
Shape::Text(t) if t.galley.text() == clip.name && pill.contains(t.pos) => Some(t.galley.size().x),
_ => None,
})
.expect("the name is drawn on the pill");
assert_eq!(pill.width(), text_w + 2.0 * PILL_PAD);
assert!(pill.width() < clip_rect.width() * 0.5);
}
}
#[test]
fn the_rating_stars_follow_the_rating_switch_whatever_the_name_switch_says() {
for (show_name, show_rating) in [(false, true), (true, true), (true, false), (false, false)] {
let mut h = smart_demo();
for (cmd, on) in [("view.clip_name", show_name), ("view.clip_rating", show_rating)] {
h.state_mut().engine.execute(cmd, &json!({"value": on})).unwrap();
}
h.state_mut().engine.session_mut().tracks.iter_mut().flat_map(|t| &mut t.playlists).flat_map(|p| &mut p.clips).for_each(|c| c.rating = 3);
h.step();
let stars = h.output().shapes.iter().filter(|c| matches!(&c.shape, Shape::Text(t) if t.galley.text() == "★★★")).count();
assert_eq!(stars > 0, show_rating, "names {show_name}, rating {show_rating}: {stars} rated clips drew their stars");
}
}
#[test]
fn alternate_playlist_lanes_draw_only_the_clips_on_screen() {
let mut h = harness(1);
let tl = timeline(&h);
let s = h.state().engine.session();
let (view, color) = (Range::new(sample_at(s, tl, tl.min.x), sample_at(s, tl, tl.max.x)), s.tracks[0].color);
let len = (view.end - view.start) / 20;
// One clip well inside the view, one running past its right edge, two far beyond it.
let starts = [view.start + 4 * len, view.end - len / 2, view.end + 20 * len, view.end + 2_000 * len];
let s = h.state_mut().engine.session_mut();
let mut alt = soundcraft_model::Playlist::new("alt");
alt.clips = starts.iter().map(|&at| test_clip(s.new_clip_id().0, at, len)).collect();
let track = s.tracks.first_mut().unwrap();
(track.view, track.active_playlist) = ("playlists".into(), 0);
track.playlists.push(alt);
h.run_steps(3);
// The main playlist is empty: every clip body in the track's rows belongs to the alternate lane.
let bodies: Vec<Rect> = h
.output()
.shapes
.iter()
.filter_map(|c| match &c.shape {
Shape::Rect(r) if r.fill == clip_colors(color, false).0 => Some(r.rect),
_ => None,
})
.collect();
assert_eq!(bodies.len(), 2, "only the two clips that show are drawn: {bodies:?}");
assert!(bodies.iter().all(|r| r.max.x > tl.min.x && r.min.x < tl.max.x), "{bodies:?} are not all on screen");
}
fn test_clip(id: u64, start: Samples, len: Samples) -> Clip {
Clip::audio(ClipId(id), "c", soundcraft_model::SourceId(0), 0, start, len)
}
#[test]
fn cut_is_found_among_the_playlist_neighbours() {
// Selection never enters: it recolours the body, so a selected clip gets the same edges as any other.
let clips = [test_clip(1, 0, 100), test_clip(2, 100, 100), test_clip(3, 200, 100), test_clip(4, 400, 50)];
let cuts: Vec<ClipCut> = clips.iter().map(|c| clip_cut_in(&clips, c)).collect();
assert_eq!(cuts, [ClipCut { left: false, right: true }, ClipCut { left: true, right: true }, ClipCut { left: true, right: false }, ALONE]);
}
#[test]
fn cut_does_not_depend_on_the_playlist_order() {
// Bring to Front / Send to Back reorder a playlist (its order is the stacking order): the seam stays.
let (a, b) = (test_clip(1, 0, 100), test_clip(2, 100, 100));
let reordered = [b.clone(), a.clone()];
assert_eq!(clip_cut_in(&reordered, &a), ClipCut { left: false, right: true });
assert_eq!(clip_cut_in(&reordered, &b), ClipCut { left: true, right: false });
let run = [test_clip(3, 200, 100), test_clip(1, 0, 100), test_clip(2, 100, 100)];
let cuts: Vec<ClipCut> = run.iter().map(|c| clip_cut_in(&run, c)).collect();
assert_eq!(cuts, [ClipCut { left: true, right: false }, ClipCut { left: false, right: true }, ClipCut { left: true, right: true }]);
}
#[test]
fn layered_clips_share_a_seam_only_where_they_really_meet() {
// A short clip inside a long one does not hide the seam between the long clip and the next.
let clips = [test_clip(1, 0, 100), test_clip(2, 10, 10), test_clip(3, 100, 100)];
assert_eq!(clip_cut_in(&clips, &clips[2]), ClipCut { left: true, right: false });
assert_eq!(clip_cut_in(&clips, &clips[0]), ClipCut { left: false, right: true });
assert_eq!(clip_cut_in(&clips, &clips[1]), ALONE);
// Two clips on one start, and a lone clip.
let same = [test_clip(1, 0, 100), test_clip(2, 0, 100), test_clip(3, 300, 100)];
assert_eq!(clip_cut_in(&same, &same[1]), ALONE);
assert_eq!(clip_cut_in(&same, &same[2]), ALONE);
assert_eq!(clip_cut_in(&[], &test_clip(9, 0, 100)), ALONE);
}
#[test]
fn marks_pill_is_hidden_when_the_clip_is_too_narrow_for_it() {
// A 60 pt clip from x=100 (pills start at 102) holds a 30 pt pill at its right end.
assert_eq!(marks_pill_left(102.0, 160.0, 30.0), Some(128.0));
// Exactly full: the pill's left edge meets the leftmost x.
assert_eq!(marks_pill_left(102.0, 134.0, 30.0), Some(102.0));
// Any narrower and it would veil the clip: hidden.
assert_eq!(marks_pill_left(102.0, 133.0, 30.0), None);
assert_eq!(marks_pill_left(102.0, f32::NAN, 30.0), None);
}
#[test]
fn an_overlapping_clip_covers_the_pill_of_the_clip_below() {
let mut h = smart_demo();
h.step();
let tl = timeline(&h);
let (below, lane) = clip_on_screen(&h, |xs, xe| xs > tl.min.x + 30.0 && xe < tl.max.x - 100.0 && xe - xs > 100.0);
// A copy on top (last in the playlist), starting at the same place.
let s = h.state_mut().engine.session_mut();
let (track, _) = s.find_clip(below.id).unwrap();
let id = s.new_clip_id();
let top = Clip { id, name: "Top".into(), ..below.clone() };
s.track_mut(track).unwrap().playlist_mut().unwrap().clips.push(top);
h.step();
h.step();
let s = h.state().engine.session();
let at = pos2(x_of(s, tl, below.start) + PILL_INSET, lane.min.y + 1.0 + PILL_INSET);
let shapes = &h.output().shapes;
let pills: Vec<(usize, Rect)> = shapes
.iter()
.enumerate()
.filter_map(|(i, shape)| match &shape.shape {
Shape::Rect(r) if r.fill == PILL_BG && r.rect.min == at => Some((i, r.rect)),
_ => None,
})
.collect();
assert_eq!(pills.len(), 2, "both clips draw a pill at the same spot");
let ((lower, pill), (upper, _)) = (pills[0], pills[1]);
assert!(
shapes[lower + 1..upper].iter().any(|shape| matches!(&shape.shape, Shape::Rect(r) if r.fill != PILL_BG && r.rect.contains_rect(pill))),
"the top clip's body is painted between the two pills, so it hides the lower pill"
);
}
#[test]
fn playhead_is_red_only_while_recording() {
for t in [Tokens::DARK, Tokens::LIGHT] {
assert_eq!(playhead_colour(&t, true), t.playhead);
assert_eq!(playhead_colour(&t, false), t.playback);
assert_ne!(t.playback, t.playhead, "plain playback must not read as the record line");
}
}
/// WCAG contrast ratio between two colours (1 = identical, 21 = black on white).
fn contrast(a: Color32, b: Color32) -> f32 {
let lum = |c: Color32| {
let lin = |v: u8| {
let v = f32::from(v) / 255.0;
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b())
};
let (hi, lo) = (lum(a).max(lum(b)), lum(a).min(lum(b)));
(hi + 0.05) / (lo + 0.05)
}
/// The edit cursor stands still beside the moving playback line while playing: in both themes
/// they must be two clearly different greys, and the line must still read on the lanes.
#[test]
fn the_playback_line_is_set_apart_from_the_insertion_point_in_both_themes() {
for (name, t) in [("dark", Tokens::DARK), ("light", Tokens::LIGHT)] {
let apart = contrast(t.playback, t.insertion);
assert!(apart >= 2.5, "{name}: playback {:?} and insertion {:?} are only {apart:.2}:1 apart", t.playback, t.insertion);
let reads = contrast(t.playback, t.playlist_bg);
assert!(reads >= 3.0, "{name}: the playback line is only {reads:.2}:1 on the lanes");
}
}
/// The colour `overlay` gives the full-height playback line (width 1.5) in this transport state.
fn playback_line_colour(recording: bool) -> Option<Color32> {
use egui::{Rect, pos2};
let _palette = crate::theme::lock_test_palette();
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.engine.session_mut().edit.zoom.samples_per_px = 1_000.0;
app.engine.transport.playing = true;
app.engine.transport.recording = recording;
app.engine.transport.position = 80_000;
let tl = Rect::from_min_max(pos2(100.0, 100.0), pos2(900.0, 500.0));
let area = Rect::from_min_max(pos2(100.0, 50.0), tl.max);
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| overlay(&mut app, ui, tl, area));
output.textures_delta.clear();
output.shapes.iter().find_map(|s| match &s.shape {
Shape::LineSegment { points, stroke } if points[0].x == 180.0 && stroke.width == 1.5 => Some(stroke.color),
_ => None,
})
}
#[test]
fn overlay_draws_the_playback_line_neutral_and_the_record_line_red() {
let _palette = crate::theme::lock_test_palette();
let t = Tokens::current();
assert_eq!(playback_line_colour(false), Some(t.playback));
assert_eq!(playback_line_colour(true), Some(t.playhead));
}
#[test]
fn alt_click_on_a_marker_deletes_it() {
let mut engine = soundcraft_engine::demo::demo_engine();
+11 -15
View File
@@ -1,5 +1,5 @@
use super::automation::draw_automation;
use super::clips::{ClipLane, GridLines, clip_cuts, draw_clip, draw_live_take, draw_strip_silence};
use super::clips::{ClipLane, GridLines, draw_clip, draw_live_take, draw_strip_silence};
use super::header::{header_column, track_header};
use super::input::lane_interaction;
use super::layout::{Column, HEADER_W, LANE_H, STRIP_W, lane_rect, sample_at, x_of};
@@ -90,12 +90,11 @@ pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect,
let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x));
let auto_view = AutoParam::parse(&track.view);
let sorted = track.clips().is_sorted_by_key(|c| c.start);
let cut_of = clip_cuts(track.clips());
for clip in track.clips() {
if !clip.range().overlaps(&view) {
continue;
}
draw_clip(&ClipLane { app, painter: &painter, s: &s, track, sorted, tl, lane }, clip, cut_of(clip), auto_view.is_some());
draw_clip(&ClipLane { app, painter: &painter, s: &s, track, sorted, tl, lane }, clip, auto_view.is_some());
}
draw_live_take(app, &painter, &s, track, tl, lane);
crate::video_track::draw_lane(app, &painter, &s, track, tl, lane);
@@ -144,9 +143,8 @@ fn playlist_lanes(app: &mut SoundApp, ui: &mut Ui, track: &Track, row: Rect, mai
let painter = ui.painter().with_clip_rect(lane.intersect(ui.clip_rect()));
let sorted = track.clips().is_sorted_by_key(|c| c.start);
let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x));
let cut_of = clip_cuts(&pl.clips);
for c in pl.clips.iter().filter(|c| c.range().overlaps(&view)) {
draw_clip(&ClipLane { app, painter: &painter, s: &s, track, sorted, tl, lane }, c, cut_of(c), false);
draw_clip(&ClipLane { app, painter: &painter, s: &s, track, sorted, tl, lane }, c, false);
}
let resp = ui.interact(lane, ui.scope_id().with(("pl_lane", track.id.0, i)), Sense::click());
if resp.clicked()
@@ -163,7 +161,7 @@ fn playlist_lanes(app: &mut SoundApp, ui: &mut Ui, track: &Track, row: Rect, mai
let _ = app.run("track.playlist_promote", json!({"track": track.id.0, "playlist": i, "start": a, "end": b}));
}
}
resp.on_hover_text(crate::localization::text("Click a take (or the selection) to promote it to the main playlist"));
resp.on_hover_text("Click a take (or the selection) to promote it to the main playlist");
y += LANE_H;
}
}
@@ -185,7 +183,7 @@ pub(super) fn view_menu(app: &mut SoundApp, ui: &mut Ui, track: &Track) {
}
opts.extend(["volume", "pan", "mute"]);
for o in opts {
if ui.selectable_label(track.view == o, crate::localization::text(&view_label(o))).clicked() {
if ui.selectable_label(track.view == o, view_label(o)).clicked() {
let _ = app.run("track.view", json!({"track": id, "view": o}));
}
}
@@ -240,7 +238,7 @@ pub(crate) fn track_context_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
.map(|track| (track.id.0, track.name.clone()))
.collect();
if !folders.is_empty() {
ui.menu_button(crate::localization::text("Move to Folder"), |ui| {
ui.menu_button("Move to Folder", |ui| {
for (folder, name) in &folders {
if ui.button(name).clicked() {
let _ = app.run("track.move_to_folder", json!({"tracks": selection, "folder": folder}));
@@ -248,26 +246,24 @@ pub(crate) fn track_context_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
}
});
}
if app.engine.session().track(id).is_some_and(|track| track.folder.is_some())
&& ui.button(crate::localization::text("Remove from Folder")).clicked()
{
if app.engine.session().track(id).is_some_and(|track| track.folder.is_some()) && ui.button("Remove from Folder").clicked() {
let _ = app.run("track.remove_from_folder", json!({"tracks": selection}));
}
// Only the track clicked: the command has one target, and the selection stays as it is.
if ui.button(crate::localization::text("Scroll Into View")).clicked() {
if ui.button("Scroll Into View").clicked() {
let _ = app.run("view.scroll_into_view", json!({"track": id.0}));
}
ui.separator();
ui.menu_button(crate::localization::text("Track Height"), |ui| {
ui.menu_button("Track Height", |ui| {
for h in TrackHeight::ALL {
if ui.button(crate::localization::text(h.label())).clicked() {
if ui.button(h.label()).clicked() {
let own: Vec<TrackId> = selection.iter().map(|&t| TrackId(t)).collect();
let tracks = height_targets(app.engine.session(), ui.input(|i| i.modifiers), &own);
let _ = app.run("track.height", json!({"tracks": tracks, "height": h.label()}));
}
}
});
ui.menu_button(crate::localization::text("Track Color"), |ui| {
ui.menu_button("Track Color", |ui| {
for (i, c) in soundcraft_model::TRACK_COLORS.iter().enumerate() {
let (r, resp) = ui.allocate_exact_size(vec2(120.0, 14.0), Sense::click());
ui.painter().rect_filled(r, 2.0, rgb(*c));
+1 -6
View File
@@ -1,4 +1,3 @@
use super::overlay::playhead_colour;
use super::{Color32, Rect, Samples, Sense, Session, SoundApp, Stroke, StrokeKind, Tokens, Track, Ui, json, pos2, rgb, vec2};
/// The Universe's clip blocks for one document revision and area: each track's clips merged into
@@ -83,11 +82,7 @@ pub(super) fn universe(app: &mut SoundApp, ui: &mut Ui) {
ui.painter().rect_stroke(vr, 2.0, Stroke::new(1.5, Tokens::current().universe_view), StrokeKind::Outside);
if app.is_playing() {
let x = r.min.x + app.position() as f32 / total * r.width();
let line = [pos2(x, r.min.y), pos2(x, r.max.y)];
// The Universe paints clips in their raw track colours, some as light as the neutral playback line: a dark
// edge on each side keeps it readable over all of them.
ui.painter().line_segment(line, Stroke::new(3.0, Color32::from_black_alpha(160)));
ui.painter().line_segment(line, Stroke::new(1.0, playhead_colour(&Tokens::current(), app.engine.transport.recording)));
ui.painter().line_segment([pos2(x, r.min.y), pos2(x, r.max.y)], Stroke::new(1.0, Tokens::current().playhead));
}
let resp = ui.interact(r, ui.scope_id().with("universe"), Sense::click_and_drag());
if let Some(p) = resp.interact_pointer_pos()
+3 -39
View File
@@ -46,30 +46,8 @@ impl Imports {
}
/// Imports the audio file `params["path"]` names (the `file.import_audio` params) in the
/// background; several `paths` queue one import each. Anything else (no path, the browser) runs the command now.
/// background. Anything else (several `paths`, no path, the browser) runs the command now.
pub fn start(app: &mut SoundApp, params: Value) {
// Several picked files: one queue entry each, so they decode one at a time and the app stays responsive.
if !cfg!(target_arch = "wasm32")
&& params.get("path").is_none()
&& let Some(paths) = params.get("paths").and_then(Value::as_array)
{
let singles: Vec<Value> = paths
.iter()
.filter_map(Value::as_str)
.map(|p| {
let mut one = params.clone();
if let Some(o) = one.as_object_mut() {
o.remove("paths");
o.insert("path".into(), Value::from(p));
}
one
})
.collect();
if !singles.is_empty() {
app.imports.queue.extend(singles);
return;
}
}
if cfg!(target_arch = "wasm32") || params.get("path").and_then(Value::as_str).is_none() {
run_now(app, params);
return;
@@ -137,7 +115,7 @@ fn finish(app: &mut SoundApp) {
Ok(decoded) => {
app.engine.offer_import(decoded);
if run_now(app, params) {
app.ui.status = crate::localized_format!("Imported {name}", name = name);
app.ui.status = format!("Imported {name}");
}
app.engine.drop_offered_imports();
}
@@ -166,7 +144,7 @@ pub fn show(app: &SoundApp, ctx: &egui::Context) {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new());
let more = if waiting > 0 { format!(" ({waiting} more)") } else { String::new() };
ui.label(crate::localized_format!("Importing {name}{more}", name = name, more = more));
ui.label(format!("Importing {name}{more}"));
});
});
},
@@ -235,20 +213,6 @@ mod tests {
assert_eq!(app.engine.session().tracks.len(), 1, "the good file still imports");
}
/// Issue #1089: several files picked in one Browse go to the queue, one entry each.
#[test]
fn several_paths_import_one_after_another() {
let ctx = egui::Context::default();
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let (a, b, c) = (tone_wav("many-a.wav"), tone_wav("many-b.wav"), tone_wav("many-c.wav"));
start(&mut app, json!({"paths": [a, b, c]}));
assert_eq!(app.imports.queue.len(), 3);
step(&mut app, &ctx);
assert_eq!(app.imports.label().map(|l| l.1), Some(2), "the other two wait for the first");
settle(&mut app, &ctx);
assert_eq!(app.engine.session().tracks.len(), 3);
}
#[test]
fn a_failed_import_stays_on_the_status_line_while_the_next_one_starts() {
let ctx = egui::Context::default();
-4
View File
@@ -23,7 +23,6 @@ pub mod edit_window;
pub mod fonts;
pub mod icons;
pub mod import;
pub mod localization;
pub mod menus;
pub mod mix_window;
pub mod palette;
@@ -144,8 +143,6 @@ pub struct UiState {
pub video_burn_in: bool,
pub workspace_dir: String,
pub configurations: Vec<(String, Value)>,
/// Interface language (`ui.language`).
pub language: localization::Language,
/// Appearance (`ui.theme`): dark by default, light or follow the system on request.
pub theme: theme::ThemeMode,
/// The main window's size (logical points) and maximized state, and the interface scale, as
@@ -215,7 +212,6 @@ impl Default for UiState {
video_burn_in: false,
workspace_dir: String::new(),
configurations: Vec::new(),
language: localization::Language::default(),
theme: theme::ThemeMode::Dark,
window_size: [1600.0, 1000.0],
window_maximized: false,
-542
View File
@@ -1,542 +0,0 @@
//! Language selection and source-language fallback for UI strings.
#[path = "../locales/pt-BR/mod.rs"]
mod pt_br;
use std::cell::Cell;
thread_local! {
static CURRENT_LANGUAGE: Cell<Language> = const { Cell::new(Language::English) };
}
/// A language supported by the UI.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Language {
#[default]
#[serde(rename = "en")]
English,
#[serde(rename = "pt-BR")]
PortugueseBrazil,
}
impl Language {
/// All supported languages, in the order they are shown in the language menu.
pub const ALL: [Self; 2] = [Self::English, Self::PortugueseBrazil];
/// Stable language tag used in preferences and control commands.
pub const fn id(self) -> &'static str {
match self {
Self::English => "en",
Self::PortugueseBrazil => "pt-BR",
}
}
/// English source name of the language; translate it with `text` for display.
pub const fn native_name(self) -> &'static str {
match self {
Self::English => "English",
Self::PortugueseBrazil => "Portuguese (Brazil)",
}
}
pub fn parse(tag: &str) -> Option<Self> {
Self::ALL.into_iter().find(|language| language.id().eq_ignore_ascii_case(tag.trim()))
}
/// Rewrites the decimal point of a rendered number for this language.
pub fn localize_decimal(self, number: &str) -> String {
match self {
Self::English => number.to_owned(),
Self::PortugueseBrazil => number.replace('.', ","),
}
}
/// Translates a UI string, falling back to its English source when no translation exists.
pub fn text(self, source: &str) -> &str {
match self {
Self::English => source,
Self::PortugueseBrazil => pt_br::translate(source).unwrap_or(source),
}
}
}
/// Sets the language used by text widgets on this thread for the duration of a UI frame.
pub fn enter(language: Language) -> LanguageScope {
let previous = CURRENT_LANGUAGE.with(|current| current.replace(language));
LanguageScope(previous)
}
/// The language selected for the current UI frame.
pub fn current_language() -> Language {
CURRENT_LANGUAGE.with(Cell::get)
}
/// Translates a source string using the language selected for the current UI frame.
pub fn text(source: &str) -> &str {
current_language().text(source)
}
/// Translates an engine error message for display. Messages are matched against the catalog's
/// error templates and their embedded values are carried over; text that matches no template is
/// returned unchanged, so low-level library errors stay in English.
pub fn error_text(message: &str) -> String {
error_text_in(current_language(), message, 0)
}
const MAX_ERROR_DEPTH: usize = 4;
fn error_text_in(language: Language, message: &str, depth: usize) -> String {
let templates: &[(&str, &str)] = match language {
Language::English => &[],
Language::PortugueseBrazil => pt_br::ERROR_TEMPLATES,
};
let mut best: Option<(usize, &str, Vec<(String, String)>)> = None;
for (template, translation) in templates {
if let Some((weight, captures)) = match_template(template, message)
&& best.as_ref().is_none_or(|(w, ..)| weight > *w)
{
best = Some((weight, translation, captures));
}
}
let Some((_, translation, captures)) = best else { return message.to_owned() };
let captures: Vec<(String, String)> = captures
.into_iter()
.map(|(name, value)| {
let value = if depth < MAX_ERROR_DEPTH { error_text_in(language, &value, depth + 1) } else { value };
(name, value)
})
.collect();
fill_captures(language, translation, &captures)
}
enum Piece<'a> {
Literal(String),
Field(&'a str),
}
fn split_template(template: &str) -> Vec<Piece<'_>> {
let mut pieces = Vec::new();
let mut literal = String::new();
let mut rest = template;
while let Some(ch) = rest.chars().next() {
if let Some(after) = rest.strip_prefix("{{") {
literal.push('{');
rest = after;
} else if let Some(after) = rest.strip_prefix("}}") {
literal.push('}');
rest = after;
} else if ch == '{'
&& let Some(end) = rest.find('}')
{
if !literal.is_empty() {
pieces.push(Piece::Literal(std::mem::take(&mut literal)));
}
pieces.push(Piece::Field(rest.get(1..end).unwrap_or_default()));
rest = rest.get(end + 1..).unwrap_or_default();
} else {
literal.push(ch);
rest = rest.get(ch.len_utf8()..).unwrap_or_default();
}
}
if !literal.is_empty() {
pieces.push(Piece::Literal(literal));
}
pieces
}
/// Matches `message` against `template`. Returns the template's literal length, used to prefer
/// the most specific template, and the captured values by placeholder name.
fn match_template(template: &str, message: &str) -> Option<(usize, Vec<(String, String)>)> {
let pieces = split_template(template);
let mut captures = Vec::new();
let mut pos = 0usize;
let mut weight = 0usize;
let mut index = 0usize;
while let Some(piece) = pieces.get(index) {
match piece {
Piece::Literal(text) => {
if !message.get(pos..)?.starts_with(text.as_str()) {
return None;
}
pos += text.len();
weight += text.len();
}
Piece::Field(name) => {
let rest = message.get(pos..)?;
let end = match pieces.get(index + 1) {
None => rest.len(),
Some(Piece::Literal(next)) if pieces.len() == index + 2 => {
if rest.len() < next.len() || !rest.ends_with(next.as_str()) {
return None;
}
rest.len() - next.len()
}
Some(Piece::Literal(next)) => rest.find(next.as_str())?,
Some(Piece::Field(_)) => return None,
};
if end == 0 {
return None;
}
let name = name.split(':').next().unwrap_or_default();
captures.push((name.to_owned(), rest.get(..end)?.to_owned()));
pos += end;
}
}
index += 1;
}
(pos == message.len() && weight > 0).then_some((weight, captures))
}
fn fill_captures(language: Language, translation: &str, captures: &[(String, String)]) -> String {
let mut out = String::with_capacity(translation.len());
for piece in split_template(translation) {
match piece {
Piece::Literal(text) => out.push_str(&text),
Piece::Field(field) => {
let name = field.split(':').next().unwrap_or_default();
match captures.iter().find(|(captured, _)| captured == name) {
Some((_, value)) if value.parse::<f64>().is_ok() => out.push_str(&language.localize_decimal(value)),
Some((_, value)) => out.push_str(value),
None => {
out.push('{');
out.push_str(field);
out.push('}');
}
}
}
}
}
out
}
/// Whether the Brazilian Portuguese catalog has an entry for `source`, even an identical one.
#[cfg(test)]
pub(crate) fn has_pt_br_entry(source: &str) -> bool {
pt_br::translate(source).is_some()
}
/// Guard that restores the previously active language when dropped.
pub struct LanguageScope(Language);
impl Drop for LanguageScope {
/// Restores the language that was active when the scope was created.
fn drop(&mut self) {
CURRENT_LANGUAGE.with(|language| language.set(self.0));
}
}
/// One formatting argument, kept as a reference and rendered only when the template asks for it.
///
/// The template is only known at run time, so the format specifier is too: the formatter reads a
/// `:.N` precision from it and renders the value with that precision.
pub struct Arg<'a> {
value: &'a dyn std::fmt::Display,
}
impl<'a> Arg<'a> {
/// Wraps the argument without rendering it.
pub fn new<T: std::fmt::Display>(value: &'a T) -> Self {
Self { value }
}
/// Renders the argument for the given precision specifier (`.0` to `.3`), if any. A number
/// given a precision uses the active language's decimal separator.
fn render(&self, spec: Option<&str>) -> String {
let precision = spec.and_then(|spec| spec.strip_prefix('.')).and_then(|digits| digits.parse::<usize>().ok()).filter(|n| *n <= 3);
match precision {
Some(n) => {
let text = format!("{:.*}", n, self.value);
if text.parse::<f64>().is_ok() { current_language().localize_decimal(&text) } else { text }
}
None => self.value.to_string(),
}
}
}
/// Formats the translated `source` with positional arguments. Placeholders may carry a `:.N`
/// precision, as in `format!`; other specifiers are ignored.
pub fn format_positional(source: &str, args: &[Arg<'_>]) -> String {
format_template(source, args, &[], true)
}
/// Formats the translated `source` with named arguments (`name = value`).
pub fn format_named(source: &str, args: &[(&str, Arg<'_>)]) -> String {
format_template(source, &[], args, false)
}
/// Shared implementation behind `format_positional` and `format_named`.
fn format_template(source: &str, positional: &[Arg<'_>], named: &[(&str, Arg<'_>)], positional_mode: bool) -> String {
let template = text(source);
let mut out = String::with_capacity(template.len());
let mut next = 0usize;
let mut chars = template.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'{' if chars.peek() == Some(&'{') => {
chars.next();
out.push('{');
}
'}' if chars.peek() == Some(&'}') => {
chars.next();
out.push('}');
}
'{' => {
let mut field = String::new();
let mut closed = false;
for ch in chars.by_ref() {
if ch == '}' {
closed = true;
break;
}
field.push(ch);
}
if !closed {
out.push('{');
out.push_str(&field);
break;
}
let (key, spec) = match field.split_once(':') {
Some((key, spec)) => (key, Some(spec)),
None => (field.as_str(), None),
};
let value = if positional_mode {
let value = positional.get(next);
next += 1;
value
} else {
named.iter().find(|(name, _)| *name == key).map(|(_, value)| value)
};
match value {
Some(value) => out.push_str(&value.render(spec)),
None => {
out.push('{');
out.push_str(&field);
out.push('}');
}
}
}
'}' => out.push('}'),
ch => out.push(ch),
}
}
out
}
#[macro_export]
macro_rules! localized_format {
($source:literal) => {
$crate::localization::text($source).to_owned()
};
($source:literal, $($name:ident = $value:expr),+ $(,)?) => {{
$crate::localization::format_named(
$source,
&[$( (stringify!($name), $crate::localization::Arg::new(&$value)) ),+],
)
}};
($source:literal, $($value:expr),+ $(,)?) => {{
$crate::localization::format_positional(
$source,
&[$($crate::localization::Arg::new(&$value)),+],
)
}};
}
#[cfg(test)]
mod tests {
use super::{Arg, Language, enter, error_text, format_named, format_positional, text};
#[test]
fn language_tags_are_stable_and_round_trip() {
for language in Language::ALL {
assert_eq!(Language::parse(language.id()), Some(language));
let encoded = serde_json::to_value(language).unwrap_or_default();
let decoded: Language = serde_json::from_value(encoded).unwrap_or_default();
assert_eq!(decoded, language);
}
assert_eq!(Language::parse(" PT-br "), Some(Language::PortugueseBrazil));
assert_eq!(Language::parse("fr"), None);
}
#[test]
fn language_translations_fall_back_to_the_english_source() {
assert_ne!(Language::PortugueseBrazil.text("Appearance"), "Appearance");
assert_eq!(Language::PortugueseBrazil.text("A source string with no catalog entry"), "A source string with no catalog entry");
assert_eq!(Language::English.text("Appearance"), "Appearance");
}
#[test]
fn language_scope_restores_the_previous_language() {
assert_eq!(text("Appearance"), "Appearance");
{
let _scope = enter(Language::PortugueseBrazil);
assert_ne!(text("Appearance"), "Appearance");
{
let _inner = enter(Language::English);
assert_eq!(text("Appearance"), "Appearance");
}
assert_ne!(text("Appearance"), "Appearance");
}
assert_eq!(text("Appearance"), "Appearance");
}
#[test]
fn portuguese_catalog_covers_every_menu_label() {
for path in include_str!("../../engine/catalog/menus.txt").lines() {
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
assert!(super::pt_br::translate(label).is_some(), "missing pt-BR menu label: {label}");
}
}
}
#[test]
fn engine_errors_are_translated_with_their_values() {
assert_eq!(error_text("select a clip"), "select a clip");
let _scope = enter(Language::PortugueseBrazil);
assert_ne!(error_text("select a clip"), "select a clip");
assert_ne!(error_text("no track"), "no track");
let wrapped = error_text("bad parameters for `track.new`: `name` required");
assert!(wrapped.contains("`track.new`") && wrapped.contains("`name`"), "{wrapped}");
assert!(!wrapped.contains("bad parameters") && !wrapped.contains("required"), "{wrapped}");
let ratio = error_text("stretch ratio 12.500 is outside 0.1..10");
assert!(ratio.contains("12,500"), "{ratio}");
assert_eq!(error_text("some unknown library failure"), "some unknown library failure");
}
#[test]
fn positional_templates_fill_in_order() {
assert_eq!(format_positional("{} of {}", &[Arg::new(&1), Arg::new(&"two")]), "1 of two");
assert_eq!(format_positional("no fields", &[Arg::new(&1)]), "no fields");
}
#[test]
fn named_templates_fill_by_name_in_any_order() {
assert_eq!(format_named("{b}-{a}-{b}", &[("a", Arg::new(&1)), ("b", Arg::new(&2))]), "2-1-2");
}
#[test]
fn precision_specifiers_are_honoured() {
let value = 3.14259_f64;
for (template, expected) in [("{:.0}", "3"), ("{:.1}", "3.1"), ("{:.2}", "3.14"), ("{:.3}", "3.143"), ("{}", "3.14259")] {
assert_eq!(format_positional(template, &[Arg::new(&value)]), expected, "{template}");
}
}
#[test]
fn braces_can_be_escaped() {
assert_eq!(format_positional("{{{}}}", &[Arg::new(&5)]), "{5}");
}
#[test]
fn missing_unknown_and_unclosed_fields_are_kept_verbatim() {
assert_eq!(format_positional("{} {}", &[Arg::new(&1)]), "1 {}");
assert_eq!(format_named("{nope}", &[("a", Arg::new(&1))]), "{nope}");
assert_eq!(format_positional("open {", &[]), "open {");
assert_eq!(format_positional("tail {abc", &[]), "tail {abc");
}
#[test]
fn portuguese_numbers_use_a_decimal_comma_only_with_a_precision() {
let _scope = enter(Language::PortugueseBrazil);
assert_eq!(format_positional("{:.1} dB", &[Arg::new(&-6.04_f64)]), "-6,0 dB");
assert_eq!(format_positional("{}", &[Arg::new(&"v1.2")]), "v1.2");
let _english = enter(Language::English);
assert_eq!(format_positional("{:.1}", &[Arg::new(&2.5_f64)]), "2.5");
}
/// Parses a Rust string literal at the start of `s`; returns its value and the rest.
fn literal(s: &str) -> Option<(String, &str)> {
let mut chars = s.strip_prefix('"')?.char_indices();
let mut out = String::new();
while let Some((i, c)) = chars.next() {
match c {
'"' => return Some((out, &s[i + 2..])),
'\\' => match chars.next()?.1 {
'n' => out.push('\n'),
other => out.push(other),
},
c => out.push(c),
}
}
None
}
/// Every `"source" => "translation"` pair of the catalog, read from its source file.
fn catalog_entries() -> Vec<(String, String)> {
let text = include_str!("../locales/pt-BR/mod.rs");
let mut lines = text.lines().map(str::trim);
let mut entries = Vec::new();
while let Some(line) = lines.next() {
let Some((key, rest)) = literal(line) else { continue };
let Some(rest) = rest.trim_start().strip_prefix("=>") else { continue };
let rest = rest.trim();
let value =
if rest.starts_with('{') { lines.next().and_then(|next| literal(next).map(|(v, _)| v)) } else { literal(rest).map(|(v, _)| v) };
if let Some(value) = value {
entries.push((key, value));
}
}
entries
}
fn placeholders(template: &str) -> Vec<String> {
let mut found = Vec::new();
let mut chars = template.chars().peekable();
while let Some(c) = chars.next() {
if c == '{' && chars.peek() == Some(&'{') {
chars.next();
} else if c == '{' {
let field: String = chars.by_ref().take_while(|c| *c != '}').collect();
found.push(field);
}
}
found.sort();
found
}
#[test]
fn catalog_entries_are_parsed_and_unique() {
let entries = catalog_entries();
assert!(entries.len() > 1000, "parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "duplicate catalog keys");
}
#[test]
fn catalog_translations_keep_the_english_placeholders() {
for (source, translation) in catalog_entries() {
assert_eq!(placeholders(&source), placeholders(&translation), "placeholders differ for {source:?}");
assert_eq!(super::pt_br::translate(&source), Some(translation.as_str()), "lookup differs for {source:?}");
}
}
#[test]
fn every_localized_source_string_has_a_catalog_entry() {
fn visit(dir: &std::path::Path, missing: &mut Vec<String>) {
let Ok(read) = std::fs::read_dir(dir) else { return };
for entry in read.flatten() {
let path = entry.path();
if path.is_dir() {
visit(&path, missing);
} else if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("localization.rs") {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
for marker in ["localization::text(\"", "localized_format!(\""] {
for (at, _) in text.match_indices(marker) {
let start = at + marker.len() - 1;
if let Some((source, _)) = literal(&text[start..])
&& super::pt_br::translate(&source).is_none()
{
missing.push(format!("{}: {source:?}", path.display()));
}
}
}
}
}
}
let mut missing = Vec::new();
visit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut missing);
assert!(missing.is_empty(), "strings without a pt-BR entry:\n{}", missing.join("\n"));
}
}
+21 -46
View File
@@ -77,7 +77,6 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
("ui.new_tracks_dialog", "New Tracks…", "", None),
("ui.bounce_dialog", "Bounce Mix…", "", None),
("ui.set", "Set UI State", "", None),
("ui.language", "Language", "", None),
("ui.theme", "Appearance", "", None),
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
("ui.undo_levels", "Levels of Undo", "", None),
@@ -273,32 +272,32 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
ui,
|ui| {
egui::MenuBar::new().ui(ui, |ui| {
ui.menu_button(crate::localization::text("SoundCraft"), |ui| {
ui.menu_button("SoundCraft", |ui| {
ui.add_enabled_ui(menu_entries_enabled, |ui| {
if ui.button(crate::localization::text("About SoundCraft")).clicked() {
if ui.button("About SoundCraft").clicked() {
app.ui.show_about = true;
}
if ui.add_enabled(preferences_enabled, egui::Button::new(crate::localization::text("Preferences..."))).clicked() {
if ui.add_enabled(preferences_enabled, egui::Button::new("Preferences...")).clicked() {
let _ = app.run("setup.preferences", json!({"value": true}));
}
if ui.button(crate::localization::text("Check for Updates…")).clicked() {
if ui.button("Check for Updates…").clicked() {
let _ = app.run("app.checkForUpdates", json!({}));
}
if ui.button(crate::localization::text("Session Info")).clicked() {
if ui.button("Session Info").clicked() {
app.ui.show_session_info = true;
}
if ui.button(crate::localization::text("Session Audio Health")).clicked() {
if ui.button("Session Audio Health").clicked() {
let _ = app.run("window.audio_health", json!({"value": true}));
}
ui.separator();
if ui.button(crate::localization::text("Quit")).clicked() {
if ui.button("Quit").clicked() {
let _ = crate::dialogs::run_or_ask(app, "app.quit", json!({}));
}
});
});
let extra = ui_aliases();
for root in tree() {
ui.menu_button(crate::localization::text(&root.label), |ui| {
ui.menu_button(&root.label, |ui| {
scrolling(ui, |ui| {
ui.add_enabled_ui(menu_entries_enabled, |ui| {
for c in &root.children {
@@ -312,16 +311,14 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
}
if root.path == "AudioSuite" {
ui.separator();
ui.label(
egui::RichText::new(crate::localization::text("Processes selected clips offline")).small().color(t.text_dim),
);
ui.label(egui::RichText::new("Processes selected clips offline").small().color(t.text_dim));
}
if root.path == "Window" {
ui.separator();
let mut separate = app.ui.mix_separate;
if ui
.checkbox(&mut separate, crate::localization::text("Mix in Separate Window"))
.on_hover_text(crate::localization::text("Show Edit and Mix at once, e.g. one per monitor"))
.checkbox(&mut separate, "Mix in Separate Window")
.on_hover_text("Show Edit and Mix at once, e.g. one per monitor")
.changed()
{
let _ = run_ui_command(app, "window.mix_separate", &json!({"value": separate}));
@@ -336,11 +333,7 @@ pub fn menu_bar(app: &mut SoundApp, ui: &mut egui::Ui) {
"{}{} — {}",
app.engine.session().name,
if app.engine.is_dirty() { " *" } else { "" },
if app.ui.window == MainWindow::Edit || app.ui.mix_separate {
crate::localization::text("Edit")
} else {
crate::localization::text("Mix")
}
if app.ui.window == MainWindow::Edit || app.ui.mix_separate { "Edit" } else { "Mix" }
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(egui::RichText::new(title).color(t.text_dim));
@@ -360,11 +353,10 @@ fn scrolling<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
fn instrument_menu(app: &mut SoundApp, ui: &mut egui::Ui) {
match instrument_track(app.engine.session()) {
Some(id) => {
ui.menu_button(crate::localization::text("Instrument"), |ui| crate::mix_window::instrument_menu(app, ui, id));
ui.menu_button("Instrument", |ui| crate::mix_window::instrument_menu(app, ui, id));
}
None => {
ui.add_enabled(false, egui::Button::new(crate::localization::text("Instrument")))
.on_disabled_hover_text(crate::localization::text("Select an instrument track"));
ui.add_enabled(false, egui::Button::new("Instrument")).on_disabled_hover_text("Select an instrument track");
}
}
}
@@ -376,7 +368,7 @@ fn instrument_track(s: &soundcraft_model::Session) -> Option<soundcraft_model::T
fn menu_node(app: &mut SoundApp, ui: &mut egui::Ui, n: &MenuNode, extra: &[(&str, &str)]) {
if !n.children.is_empty() {
ui.menu_button(crate::localization::text(&n.label).to_string(), |ui| {
ui.menu_button(&n.label, |ui| {
scrolling(ui, |ui| {
for c in &n.children {
menu_node(app, ui, c, extra);
@@ -387,13 +379,12 @@ fn menu_node(app: &mut SoundApp, ui: &mut egui::Ui, n: &MenuNode, extra: &[(&str
}
let id = command_for_path(&n.path, extra);
let (enabled, checked) = item_state(app, &n.path, id.as_deref());
let label = live_label(app, id.as_deref()).unwrap_or_else(|| crate::localization::text(&n.label).to_string());
let label = live_label(app, id.as_deref()).unwrap_or_else(|| n.label.clone());
let label = if checked { format!("✔ {label}") } else { label };
let shortcut = id.as_deref().and_then(shortcut_for).unwrap_or("");
let btn = egui::Button::new(label).shortcut_text(crate::shortcuts::display_shortcut(shortcut, ui.ctx().os().is_mac()));
let btn = egui::Button::new(label).shortcut_text(crate::shortcuts::shortcut_label(shortcut, ui.ctx().os().is_mac()));
let response = ui.add_enabled(enabled, btn);
let response =
if catalog::is_placeholder(&n.path) { response.on_disabled_hover_text(crate::localization::text("Not available yet.")) } else { response };
let response = if catalog::is_placeholder(&n.path) { response.on_disabled_hover_text("Not available yet.") } else { response };
if response.clicked()
&& let Some(id) = id
{
@@ -545,14 +536,8 @@ pub fn shortcut_for(id: &str) -> Option<&'static str> {
pub fn live_label(app: &SoundApp, id: Option<&str>) -> Option<String> {
let e = &app.engine;
match id? {
"edit.undo" => Some(e.undo_label().map_or_else(
|| crate::localization::text("Can't Undo").into(),
|l| crate::localized_format!("Undo {l}", l = crate::localization::text(l)),
)),
"edit.redo" => Some(e.redo_label().map_or_else(
|| crate::localization::text("Can't Redo").into(),
|l| crate::localized_format!("Redo {l}", l = crate::localization::text(l)),
)),
"edit.undo" => Some(e.undo_label().map_or_else(|| "Can't Undo".into(), |l| format!("Undo {l}"))),
"edit.redo" => Some(e.redo_label().map_or_else(|| "Can't Redo".into(), |l| format!("Redo {l}"))),
_ => None,
}
}
@@ -622,16 +607,6 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
json!({"value": *v})
};
let r = match id {
"ui.language" => {
let Some(tag) = p.get("language").and_then(Value::as_str) else {
return Some(Ok(json!({"language": app.ui.language.id()})));
};
let Some(language) = crate::localization::Language::parse(tag) else {
return Some(Err(format!("unknown language `{tag}` (en or pt-BR)")));
};
app.ui.language = language;
json!({"language": language.id()})
}
"app.checkForUpdates" | "help.checkForUpdates" => {
crate::updates_ui::check(app);
json!({})
@@ -738,7 +713,7 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
}
"window.arrange_tile" | "window.arrange_tile_h" | "window.arrange_tile_v" | "window.arrange_cascade" => {
if let Err(error) = crate::docking::arrange(app) {
app.ui.status = crate::localized_format!("Panel windows could not be arranged: {error}", error = error);
app.ui.status = format!("Panel windows could not be arranged: {error}");
}
app.arrange_request = true;
json!({})
+43 -84
View File
@@ -20,7 +20,7 @@ pub use plugin_menu::{instrument_menu, plugin_info, plugin_menu};
pub(crate) use routing::{input_name, route_name, route_popup};
#[cfg(test)]
use sends::dragged_send_db;
pub(crate) use sends::{Readout, editable_readout, parse_db, parse_pan};
use sends::{Readout, editable_readout, parse_db, parse_pan};
pub(crate) use sends::{send_slot, send_window};
pub(crate) use slots::{insert_slot, instrument_slot};
@@ -36,7 +36,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) {
/// be seen at once, e.g. one per monitor. Closing that window brings Mix back into the main one.
/// Backends without multiple windows show it as a floating egui window instead.
pub fn show_separate(app: &mut SoundApp, ctx: &egui::Context) {
let title = format!("{} — {}", app.engine.session().name, crate::localization::text("Mix"));
let title = format!("{} — Mix", app.engine.session().name);
let builder = egui::ViewportBuilder::default().with_title(title).with_inner_size([1100.0, 720.0]).with_min_inner_size([480.0, 320.0]);
ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("soundcraft.mix"), builder, |ui, _class| {
ui.set_style(ui.ctx().global_style());
@@ -90,12 +90,6 @@ fn output_format(app: &SoundApp, track: &Track) -> ChannelFormat {
}
}
/// Whether the strip pans a track with the surround panner, because its output is multichannel, instead of the stereo pans.
pub(crate) fn surround_panned(app: &SoundApp, track: &Track) -> bool {
let out_fmt = output_format(app, track);
out_fmt.channels() > 2 && !out_fmt.is_ambisonic() && !matches!(track.kind, TrackKind::Master | TrackKind::Vca) && track.channels() <= 2
}
/// Speaker dots of a format, placed on the panner square.
fn panner_speakers(fmt: ChannelFormat) -> Vec<PannerSpeaker> {
let sp = fmt.speakers();
@@ -147,13 +141,10 @@ fn short_label(text: &str) -> &str {
fn section_label(ui: &Ui, r: Rect, text: &str, narrow: bool) {
let p = ui.painter();
let color = Tokens::current().section_label;
let source = text;
let short = crate::localization::text(short_label(source));
let text = crate::localization::text(source);
let label = if narrow { short } else { text };
let mut galley = p.layout_no_wrap(label.to_owned(), bold(10.0), color);
let text = if narrow { short_label(text) } else { text };
let mut galley = p.layout_no_wrap(text.to_owned(), bold(10.0), color);
if galley.size().x > r.width() - 8.0 {
galley = p.layout_no_wrap(short.to_owned(), bold(10.0), color);
galley = p.layout_no_wrap(short_label(text).to_owned(), bold(10.0), color);
}
p.galley(Align2::CENTER_CENTER.anchor_size(pos2(r.center().x, r.min.y + 7.0), galley.size()).min, galley, color);
}
@@ -240,7 +231,7 @@ fn preamp_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(kr));
let resp = c
.add_sized(kr.size(), egui::DragValue::new(&mut db).range(-24.0..=24.0).speed(0.1).suffix(" dB").max_decimals(1))
.accessible_name(crate::localization::text("Input trim (dB)"));
.accessible_name("Input trim (dB)");
if resp.changed() {
let _ = app.engine.execute_merged("mix.trim", &json!({"tracks": [id.0], "db": db}), &format!("trim:{}", id.0));
}
@@ -267,7 +258,7 @@ fn instrument_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y:
_ if track.kind == TrackKind::Instrument => instrument_slot(app, ui, track, sr),
Some(k) => insert_slot(app, ui, track, k, sr),
None if track.kind == TrackKind::Midi => {
ui.painter().text(sr.center(), Align2::CENTER_CENTER, crate::localization::text("MIDI in: all"), regular(9.0), t.text_dim);
ui.painter().text(sr.center(), Align2::CENTER_CENTER, "MIDI in: all", regular(9.0), t.text_dim);
}
None => {}
}
@@ -285,11 +276,8 @@ fn object_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
if has_input {
let on = app.engine.session().edit.flag(&format!("object.{}", id.0));
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(sec));
let label = egui::RichText::new(crate::localization::text(if on { "OBJECT" } else { "BED" })).font(bold(9.0));
if c.add_sized(sec.size(), egui::Button::new(label).selected(on))
.on_hover_text(crate::localization::text("Route as an immersive object or to the bed"))
.clicked()
{
let label = egui::RichText::new(if on { "OBJECT" } else { "BED" }).font(bold(9.0));
if c.add_sized(sec.size(), egui::Button::new(label).selected(on)).on_hover_text("Route as an immersive object or to the bed").clicked() {
let _ = app.run("track.object", json!({"tracks": [id.0], "object": !on}));
}
}
@@ -370,10 +358,10 @@ fn comments_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f
let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 44.0));
let mut c = track.comments.clone();
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(sec));
let hint = if narrow { "" } else { crate::localization::text("comments") };
let hint = if narrow { "" } else { "comments" };
let field = crate::widgets::named_text_field(
child.add(egui::TextEdit::multiline(&mut c).desired_width(inner_w).desired_rows(2).hint_text(hint).font(regular(10.0))),
&crate::localized_format!("Comments for {}", track.name),
&format!("Comments for {}", track.name),
);
if field.changed() {
let _ = app.engine.execute_merged("track.comments", &json!({"track": id.0, "comments": c}), &format!("comments:{}", id.0));
@@ -383,40 +371,27 @@ fn comments_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f
y
}
/// Whether a track shows an input selector. A master fader has no input of its own:
/// it only shows the output of the path it controls.
pub(crate) fn has_input_selector(kind: TrackKind) -> bool {
kind != TrackKind::Master
}
/// Input (except on master faders), output and automation mode selectors.
/// Input, output and automation mode selectors.
fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -> f32 {
let StripCtx { track, id, narrow, x0, inner_w, .. } = *cx;
let t = Tokens::current();
if cx.shows("io") {
let has_input = has_input_selector(track.kind);
let sec = Rect::from_min_size(pos2(x0, y), vec2(inner_w, 16.0 + 2.0 * 18.0 + 30.0));
inset(ui.painter(), sec, t.strip_section);
section_label(ui, sec, "I / O", narrow);
let in_r = Rect::from_min_size(pos2(x0 + 2.0, sec.min.y + 15.0), vec2(inner_w - 4.0, 16.0));
let out_r = if has_input { Rect::from_min_size(pos2(x0 + 2.0, sec.min.y + 33.0), vec2(inner_w - 4.0, 16.0)) } else { in_r };
if has_input {
let mut c = ui.new_child(egui::UiBuilder::new().id_salt(("mix-input", id.0)).max_rect(in_r));
let input = input_name(app, track);
let resp = selector_box_named(
&mut c,
in_r.width(),
in_r.height(),
&input,
t.text,
SelectorLabels {
name: &crate::localized_format!("Input for {}", track.name),
value: &input,
tooltip: crate::localization::text("Input"),
},
);
route_popup(app, &resp, id, true);
}
let out_r = Rect::from_min_size(pos2(x0 + 2.0, sec.min.y + 33.0), vec2(inner_w - 4.0, 16.0));
let mut c = ui.new_child(egui::UiBuilder::new().id_salt(("mix-input", id.0)).max_rect(in_r));
let input = input_name(app, track);
let resp = selector_box_named(
&mut c,
in_r.width(),
in_r.height(),
&input,
t.text,
SelectorLabels { name: &format!("Input for {}", track.name), value: &input, tooltip: "Input" },
);
route_popup(app, &resp, id, true);
let mut c = ui.new_child(egui::UiBuilder::new().id_salt(("mix-output", id.0)).max_rect(out_r));
let output = route_name(app, &track.mixer.output);
let resp = selector_box_named(
@@ -425,15 +400,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
out_r.height(),
&output,
t.text,
SelectorLabels {
name: &crate::localized_format!("Output for {}", track.name),
value: &output,
tooltip: crate::localization::text("Output"),
},
SelectorLabels { name: &format!("Output for {}", track.name), value: &output, tooltip: "Output" },
);
route_popup(app, &resp, id, false);
// Automation mode.
let am_r = Rect::from_min_size(pos2(x0 + 2.0, sec.min.y + 15.0 + 2.0 * 18.0), vec2(inner_w - 4.0, 16.0));
let am_r = Rect::from_min_size(pos2(x0 + 2.0, sec.min.y + 51.0), vec2(inner_w - 4.0, 16.0));
ui.painter().text(pos2(am_r.center().x, am_r.min.y - 1.0), Align2::CENTER_BOTTOM, "", regular(9.0), t.text_dim);
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(am_r));
let mode = track.mixer.automation_mode;
@@ -444,11 +415,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
} else {
t.auto_write
};
let full_label = crate::localized_format!("auto {}", crate::localization::text(mode.label()));
let full_label = format!("auto {}", mode.label());
let label = if mode == soundcraft_model::AutomationMode::TouchLatch {
if narrow { "t/l" } else { crate::localization::text(mode.label()) }
if narrow { "t/l" } else { mode.label() }
} else if narrow {
crate::localization::text(mode.label())
mode.label()
} else {
&full_label
};
@@ -458,11 +429,11 @@ fn io_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) ->
am_r.height(),
label,
col,
SelectorLabels { name: &crate::localized_format!("Automation mode for {}", track.name), value: &full_label, tooltip: &full_label },
SelectorLabels { name: &format!("Automation mode for {}", track.name), value: &full_label, tooltip: &full_label },
);
egui::Popup::menu(&resp).show(|ui| {
for m in soundcraft_model::AutomationMode::ALL {
if ui.selectable_label(m == mode, crate::localization::text(m.label())).clicked() {
if ui.selectable_label(m == mode, m.label()).clicked() {
let _ = app.run("mix.automation_mode", json!({"track": id.0, "mode": m.label()}));
}
}
@@ -478,13 +449,7 @@ fn group_selector(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
let t = Tokens::current();
// Group selector.
let no_group = if narrow { "nogrp" } else { "no group" };
let gname = app
.engine
.session()
.groups
.iter()
.find(|g| g.members.contains(&id))
.map_or(crate::localization::text(no_group).to_string(), |g| g.name.clone());
let gname = app.engine.session().groups.iter().find(|g| g.members.contains(&id)).map_or(no_group.to_string(), |g| g.name.clone());
let gr = Rect::from_min_size(pos2(x0 + 2.0, y), vec2(inner_w - 4.0, 16.0));
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(gr));
let _ = selector_box_named(
@@ -493,7 +458,7 @@ fn group_selector(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32
gr.height(),
&gname,
t.text_dim,
SelectorLabels { name: &crate::localized_format!("Group for {}", track.name), value: &gname, tooltip: crate::localization::text("Group") },
SelectorLabels { name: &format!("Group for {}", track.name), value: &gname, tooltip: "Group" },
);
y += 22.0;
y
@@ -505,7 +470,9 @@ fn pan_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
let t = Tokens::current();
// Pan: a surround panner when the output is multichannel, else the stereo knobs.
let out_fmt = output_format(app, track);
if surround_panned(app, track) {
let surround_out =
out_fmt.channels() > 2 && !out_fmt.is_ambisonic() && !matches!(track.kind, TrackKind::Master | TrackKind::Vca) && track.channels() <= 2;
if surround_out {
let size = (inner_w - 4.0).min(88.0);
let sp = track.mixer.surround.unwrap_or_else(|| {
SurroundPan::from_stereo(if track.mixer.pan.len() == 1 { track.mixer.pan.first().copied().unwrap_or(0.0) } else { 0.0 })
@@ -546,7 +513,7 @@ fn pan_section(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
pr,
ui.scope_id().with(("pan-value", id.0, i)),
Readout {
name: &crate::localized_format!("{} pan {}", track.name, i + 1),
name: &format!("{} pan {}", track.name, i + 1),
display: &pan_text(v),
edit_initial: &format!("{:.0}", v * 100.0),
parse: parse_pan,
@@ -573,11 +540,11 @@ fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
);
row.spacing_mut().item_spacing.x = 6.0;
if track.kind.has_playlist() {
let input_label = crate::localized_format!("Input monitoring for {}", track.name);
let input_label = format!("Input monitoring for {}", track.name);
if text_toggle(&mut row, vec2(bw, 18.0), "I", track.mixer.input_monitor, t.input, &input_label).clicked() {
let _ = app.run("mix.input_monitor", json!({"track": id.0}));
}
let record_label = crate::localized_format!("Record enable for {}", track.name);
let record_label = format!("Record enable for {}", track.name);
if rec_toggle(&mut row, vec2(bw, 18.0), track.mixer.record_arm, &record_label).clicked() {
let _ = app.run("mix.record_arm", json!({"track": id.0}));
}
@@ -588,11 +555,11 @@ fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
);
row.spacing_mut().item_spacing.x = 6.0;
if track.kind != TrackKind::Master {
let solo_label = crate::localized_format!("Solo for {}", track.name);
let solo_label = format!("Solo for {}", track.name);
if text_toggle(&mut row, vec2(bw, 18.0), "S", track.mixer.solo, t.solo, &solo_label).clicked() {
let _ = app.run("mix.solo", json!({"track": id.0}));
}
let mute_label = crate::localized_format!("Mute for {}", track.name);
let mute_label = format!("Mute for {}", track.name);
if text_toggle(&mut row, vec2(bw, 18.0), "M", track.mixer.mute, t.mute, &mute_label).clicked() {
let _ = app.run("mix.mute", json!({"track": id.0}));
}
@@ -652,7 +619,7 @@ fn name_and_readout(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>) {
vr,
ui.scope_id().with(("volume-value", id.0)),
Readout {
name: &crate::localized_format!("{} volume", track.name),
name: &format!("{} volume", track.name),
display: &db_text(track.mixer.volume_db),
edit_initial: &format!("{:.1}", track.mixer.volume_db),
parse: parse_db,
@@ -672,7 +639,7 @@ fn name_and_readout(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>) {
TrackKind::Folder => "folder",
TrackKind::Video => "video",
};
ui.painter().text(pos2(vr.center().x, vr.max.y + 9.0), Align2::CENTER_CENTER, crate::localization::text(kind), regular(9.5), t.text_dim);
ui.painter().text(pos2(vr.center().x, vr.max.y + 9.0), Align2::CENTER_CENTER, kind, regular(9.5), t.text_dim);
let nr = Rect::from_min_size(pos2(x0, r.max.y - 26.0), vec2(inner_w, 18.0));
ui.painter().rect(
nr,
@@ -700,14 +667,6 @@ fn name_and_readout(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>) {
mod tests {
use super::{Readout, dragged_send_db, editable_readout, parse_db, parse_pan};
use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2};
use soundcraft_model::TrackKind;
#[test]
fn master_strip_has_no_input_selector() {
assert!(!super::has_input_selector(TrackKind::Master));
assert!(super::has_input_selector(TrackKind::Audio));
assert!(super::has_input_selector(TrackKind::Aux));
}
#[test]
fn typed_db_accepts_console_notation_and_clamps() {
+17 -19
View File
@@ -3,7 +3,7 @@ use super::{Color32, Rect, SoundApp, TrackId, Ui, json, pos2, vec2};
/// An insert's menu: a search field that takes typing at once, then (until something is typed)
/// Bypass and removal and the plugins by category and format.
pub fn plugin_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, occupied: bool) {
let search = MenuSearch::show(ui, egui::Id::unique(("plugin-search", id.0, slot)), crate::localization::text("Search plugins…"));
let search = MenuSearch::show(ui, egui::Id::unique(("plugin-search", id.0, slot)), "Search plugins…");
if search.typing() {
if let Some(plugin) = plugin_search(ui, &search, false) {
pick_insert(app, ui, id, slot, &plugin);
@@ -11,10 +11,10 @@ pub fn plugin_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, oc
return;
}
if occupied {
if ui.button(crate::localization::text("Bypass")).clicked() {
if ui.button("Bypass").clicked() {
run_pick(app, ui, "mix.insert_bypass", json!({"track": id.0, "slot": slot}));
}
if ui.button(crate::localization::text("no insert")).clicked() {
if ui.button("no insert").clicked() {
run_pick(app, ui, "mix.insert_remove", json!({"track": id.0, "slot": slot}));
}
ui.separator();
@@ -44,7 +44,7 @@ pub fn plugin_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, oc
/// instruments.
pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
let slot = soundcraft_mix::INSTRUMENT_SLOT;
let search = MenuSearch::show(ui, egui::Id::unique(("instrument-search", id.0)), crate::localization::text("Search instruments…"));
let search = MenuSearch::show(ui, egui::Id::unique(("instrument-search", id.0)), "Search instruments…");
if search.typing() {
if let Some(plugin) = plugin_search(ui, &search, true) {
run_pick(app, ui, "mix.instrument", json!({"track": id.0, "plugin": plugin}));
@@ -54,9 +54,7 @@ pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
let current = app.engine.session().track(id).and_then(|t| t.instrument.clone());
if let Some(info) = current.as_ref().and_then(|i| plugin_info(&i.plugin)) {
ui.label(egui::RichText::new(info.name).strong());
if current.as_ref().is_some_and(|i| !soundcraft_mix::is_third_party(&i.plugin))
&& ui.button(crate::localization::text("Edit Parameters…")).clicked()
{
if current.as_ref().is_some_and(|i| !soundcraft_mix::is_third_party(&i.plugin)) && ui.button("Edit Parameters…").clicked() {
if !app.ui.plugin_windows.contains(&(id, slot)) {
app.ui.plugin_windows.push((id, slot));
}
@@ -66,13 +64,13 @@ pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
&& p.has_editor(id, slot)
{
if p.editor_open(id, slot) {
if ui.button(crate::localization::text("Close Plugin Editor")).clicked() {
if ui.button("Close Plugin Editor").clicked() {
p.close_editor(id, slot);
ui.close();
}
} else if ui.button(crate::localization::text("Open Plugin Editor")).clicked() {
} else if ui.button("Open Plugin Editor").clicked() {
if let Err(e) = p.open_editor(id, slot) {
app.ui.status = format!("{}: {}", info.name, crate::localization::error_text(&e.to_string()));
app.ui.status = format!("{}: {e}", info.name);
}
ui.close();
}
@@ -80,7 +78,7 @@ pub fn instrument_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
ui.separator();
}
let mut picked = None;
ui.menu_button(crate::localization::text("Built-in"), |ui| {
ui.menu_button("Built-in", |ui| {
for p in soundcraft_dsp::plugins().iter().filter(|p| p.is_instrument) {
if ui.button(p.name).clicked() {
picked = Some(p.id.to_string());
@@ -143,15 +141,15 @@ fn plugin_search(ui: &mut Ui, search: &MenuSearch, instruments: bool) -> Option<
}
});
if n == 0 {
ui.weak(crate::localization::text("No matches"));
ui.weak("No matches");
}
if clap.is_none() || vst3.is_none() {
ui.separator();
ui.horizontal(|ui| {
if clap.is_none() && ui.small_button(crate::localization::text("Scan CLAP")).clicked() {
if clap.is_none() && ui.small_button("Scan CLAP").clicked() {
soundcraft_clap_host::scan();
}
if vst3.is_none() && ui.small_button(crate::localization::text("Scan VST3")).clicked() {
if vst3.is_none() && ui.small_button("Scan VST3").clicked() {
soundcraft_vst3_host::scan();
}
});
@@ -258,20 +256,20 @@ struct MenuPlugin {
/// id picked. Each format is scanned the first time its submenu opens, then cached by its host.
fn hosted_menus(ui: &mut Ui, instruments: bool) -> Option<String> {
let mut picked = None;
ui.menu_button(crate::localization::text("CLAP"), |ui| {
ui.menu_button("CLAP", |ui| {
let list = soundcraft_clap_host::scan().into_iter().filter(|d| d.is_instrument == instruments);
if let Some(p) = vendor_menus(ui, list.map(|d| MenuPlugin { id: d.id, name: d.name, vendor: d.vendor }).collect(), "No CLAP plugins found") {
picked = Some(p);
}
});
ui.menu_button(crate::localization::text("VST3"), |ui| {
ui.menu_button("VST3", |ui| {
let list = soundcraft_vst3_host::scan().into_iter().filter(|d| d.is_instrument == instruments);
if let Some(p) = vendor_menus(ui, list.map(|d| MenuPlugin { id: d.id, name: d.name, vendor: d.vendor }).collect(), "No VST3 plugins found") {
picked = Some(p);
}
});
if cfg!(target_os = "macos") {
ui.menu_button(crate::localization::text("Audio Units"), |ui| {
ui.menu_button("Audio Units", |ui| {
let list = soundcraft_au_host::scan().into_iter().filter(|d| d.is_instrument == instruments);
if let Some(p) = vendor_menus(ui, list.map(|d| MenuPlugin { id: d.id, name: d.name, vendor: d.vendor }).collect(), "No Audio Units found")
{
@@ -286,7 +284,7 @@ fn hosted_menus(ui: &mut Ui, instruments: bool) -> Option<String> {
/// within the screen so that every plugin stays reachable however many are installed.
fn vendor_menus(ui: &mut Ui, mut list: Vec<MenuPlugin>, none: &str) -> Option<String> {
if list.is_empty() {
ui.label(crate::localization::text(none));
ui.label(none);
return None;
}
list.sort_by_cached_key(|p| (p.vendor.to_lowercase(), p.name.to_lowercase()));
@@ -296,7 +294,7 @@ fn vendor_menus(ui: &mut Ui, mut list: Vec<MenuPlugin>, none: &str) -> Option<St
let mut picked = None;
egui::ScrollArea::vertical().id_salt("vendors").max_height(max_h).show(ui, |ui| {
for v in vendors {
ui.menu_button(if v.is_empty() { crate::localization::text("Unknown vendor") } else { v }, |ui| {
ui.menu_button(if v.is_empty() { "Unknown vendor" } else { v }, |ui| {
egui::ScrollArea::vertical().id_salt("plugins").max_height(max_h).show(ui, |ui| {
for p in list.iter().filter(|p| p.vendor == v) {
if ui.button(&p.name).clicked() {
+8 -8
View File
@@ -3,8 +3,8 @@ use super::{Route, SoundApp, Track, TrackId, Ui, json};
pub(crate) fn route_name(app: &SoundApp, r: &Route) -> String {
match r {
Route::None => crate::localization::text("no output").to_string(),
Route::Main => app.engine.session().outputs.first().map_or_else(|| crate::localization::text("Out 1-2").to_string(), |o| o.name.clone()),
Route::None => "no output".into(),
Route::Main => app.engine.session().outputs.first().map_or_else(|| "Out 1-2".into(), |o| o.name.clone()),
Route::Bus(b) => app.engine.session().bus(*b).map_or_else(|| "bus?".into(), |b| b.name.clone()),
Route::Hardware(h) => h.clone(),
}
@@ -13,7 +13,7 @@ pub(crate) fn route_name(app: &SoundApp, r: &Route) -> String {
pub(crate) fn input_name(app: &SoundApp, track: &Track) -> String {
if track.kind.has_playlist() && track.mixer.input == Route::None {
let channels = track.format.channels();
if channels == 1 { crate::localized_format!("In {}", 1) } else { crate::localized_format!("In 1-{}", channels) }
if channels == 1 { "In 1".to_string() } else { format!("In 1-{channels}") }
} else {
route_name(app, &track.mixer.input)
}
@@ -30,14 +30,14 @@ pub(crate) fn route_popup(app: &mut SoundApp, resp: &egui::Response, id: TrackId
fn route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, input: bool) {
let key = if input { "input" } else { "output" };
let cmd = if input { "track.input" } else { "track.output" };
let hint = crate::localization::text(if input { "Search inputs…" } else { "Search outputs…" });
let hint = if input { "Search inputs…" } else { "Search outputs…" };
let search = MenuSearch::show(ui, egui::Id::unique(("route-search", id.0, input)), hint);
let busses: Vec<String> = app.engine.session().busses.iter().map(|b| b.name.clone()).collect();
let main_name = app.engine.session().outputs.first().map_or_else(|| "Out 1-2".to_string(), |o| o.name.clone());
// (label, the route the command is given)
let mut fixed = vec![(crate::localization::text(if input { "no input" } else { "no output" }).to_string(), "none".to_string())];
let mut fixed = vec![(if input { "no input" } else { "no output" }.to_string(), "none".to_string())];
if input {
fixed.extend((1..=8).map(|i| (crate::localized_format!("In {}", i), format!("In {i}"))));
fixed.extend((1..=8).map(|i| (format!("In {i}"), format!("In {i}"))));
} else {
fixed.push((main_name, "main".to_string()));
}
@@ -58,7 +58,7 @@ fn route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, input: bool) {
}
}
ui.separator();
ui.strong(crate::localization::text("Bus"));
ui.strong("Bus");
if let Some(bus) = search
.rows(ui, busses.len(), 420.0, |ui, i, highlighted| busses.get(i).is_some_and(|b| menu_row(ui, highlighted, b)))
.and_then(|i| busses.get(i))
@@ -66,7 +66,7 @@ fn route_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, input: bool) {
let _ = app.run(cmd, json!({"track": id.0, key: bus}));
ui.close();
}
if ui.button(crate::localization::text("new bus...")).clicked() {
if ui.button("new bus...").clicked() {
let mut n = busses.len() + 1;
while busses.contains(&format!("Bus {n}")) || app.engine.session().track_by_name(&format!("Bus {n}")).is_some() {
n += 1;
+33 -43
View File
@@ -18,9 +18,8 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
let level_r = if compact { r } else { level_icon(r).expand2(vec2(3.0, 0.0)).with_min_y(r.min.y).with_max_y(r.max.y) };
let route_r = Rect::from_min_max(r.min, pos2((level_r.min.x - 1.0).max(r.min.x), r.max.y));
let route_resp = ui.interact(if snd.is_some() { route_r } else { r }, ui.scope_id().with(("snd-route", id.0, slot)), Sense::click());
route_resp.widget_info(|| {
egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localized_format!("Send {} for {}", (b'A' + slot as u8) as char, track.name))
});
route_resp
.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Send {} for {}", (b'A' + slot as u8) as char, track.name)));
let mark = if compact { Mark::Arrow } else { Mark::Letter((b'a' + slot as u8) as char) };
match &snd {
Some(s) => {
@@ -31,13 +30,7 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
let which = (b'A' + slot as u8) as char;
let shown = app.ui.send_window == Some((id, slot));
let level_resp = ui.interact(level_r, ui.scope_id().with(("send-value", id.0, slot)), Sense::click_and_drag());
level_resp.widget_info(|| {
egui::WidgetInfo::labeled(
egui::Role::Button,
true,
crate::localized_format!("Send {which} level for {track}", which = which, track = track.name),
)
});
level_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Send {which} level for {}", track.name)));
if shown {
ui.painter().rect_stroke(level_r.shrink(0.5), 1.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
}
@@ -57,11 +50,9 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
let _ =
app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "db": db}), &format!("send:{}:{slot}", id.0));
}
let _ = level_resp.clone().on_hover_text(crate::localized_format!(
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options",
which = which,
name = name,
db = db_text(s.level_db)
let _ = level_resp.clone().on_hover_text(format!(
"Send {which} to {name}: {} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options",
db_text(s.level_db)
));
level_resp.context_menu(|ui| send_options_menu(app, ui, id, slot, s));
}
@@ -95,7 +86,7 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
};
let t = Tokens::current();
let mut open = true;
egui::Window::new(crate::localized_format!("{name} · Send {letter}", name = name, letter = (b'A' + slot as u8) as char))
egui::Window::new(format!("{name} · Send {}", (b'A' + slot as u8) as char))
.id(egui::Id::unique("send_window"))
.open(&mut open)
.auto_sized()
@@ -126,7 +117,7 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
}
ui.label(egui::RichText::new(pan_text(send.pan)).color(t.counter_text).small());
let (fr, fresp) = ui.allocate_exact_size(vec2(56.0, 220.0), Sense::hover());
fresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, true, crate::localization::text("Send level")));
fresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, true, "Send level"));
// Distinct from the strip's "Send A level for <track>" icon and from the slot's "Send level", so a
// label query while the window is open still picks one node.
if let Some(db) = fader(ui, fr, send.level_db, ui.scope_id().with("send_fader"), "Send level fader") {
@@ -145,7 +136,7 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
rr,
ui.scope_id().with("send_level_value"),
Readout {
name: &crate::localized_format!("{name} send level", name = name),
name: &format!("{name} send level"),
display: &shown,
edit_initial: &format!("{:.1}", send.level_db),
parse: parse_db,
@@ -165,9 +156,9 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
/// Secondary controls live behind the amount readout, separate from the bus selector like Logic.
fn send_options_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, send: &soundcraft_model::SendSlot) {
ui.set_min_width(230.0);
ui.strong(crate::localized_format!("Send {} · {}", (b'A' + slot as u8) as char, route_name(app, &send.target)));
ui.strong(format!("Send {} · {}", (b'A' + slot as u8) as char, route_name(app, &send.target)));
let mut db = send.level_db.max(-60.0);
if ui.add(egui::Slider::new(&mut db, -60.0..=12.0).text(crate::localization::text("Level")).suffix(" dB")).changed() {
if ui.add(egui::Slider::new(&mut db, -60.0..=12.0).text("Level").suffix(" dB")).changed() {
let _ = app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "db": db}), &format!("send:{}:{slot}", id.0));
}
send_level_scale(ui, send.level_db);
@@ -178,31 +169,31 @@ fn send_options_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize,
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": db}));
}
}
if ui.small_button(crate::localization::text("0 dB")).clicked() {
if ui.small_button("0 dB").clicked() {
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": 0.0}));
}
if ui.small_button(crate::localization::text("−∞")).clicked() {
if ui.small_button("−∞").clicked() {
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": -144.0}));
}
});
let mut pan = send.pan;
if ui.add(egui::Slider::new(&mut pan, -1.0..=1.0).text(crate::localization::text("Pan"))).changed() {
if ui.add(egui::Slider::new(&mut pan, -1.0..=1.0).text("Pan")).changed() {
let _ = app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "pan": pan}), &format!("send-pan:{}:{slot}", id.0));
}
ui.horizontal(|ui| {
let mut mute = send.mute;
if crate::widgets::checkbox(ui, &mut mute, crate::localization::text("Mute")).changed() {
if crate::widgets::checkbox(ui, &mut mute, "Mute").changed() {
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "mute": mute}));
}
let mut pre = send.pre_fader;
if crate::widgets::checkbox(ui, &mut pre, crate::localization::text("Pre-fader")).changed() {
if crate::widgets::checkbox(ui, &mut pre, "Pre-fader").changed() {
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "pre_fader": pre}));
}
});
if let Route::Bus(bus) = send.target
&& let Some(aux) =
app.engine.session().tracks.iter().find(|t| t.kind == TrackKind::Aux && t.mixer.input == Route::Bus(bus)).map(|t| (t.id, t.name.clone()))
&& ui.button(crate::localization::text("Rename bus…")).clicked()
&& ui.button("Rename bus…").clicked()
{
app.dialogs.open_rename_track(aux.0, &aux.1);
ui.close();
@@ -217,22 +208,22 @@ pub(super) fn dragged_send_db(db: f32, dy: f32, fine: bool) -> f32 {
}
/// What an [`editable_readout`] shows and how a typed value is parsed.
pub(crate) struct Readout<'a> {
pub(super) struct Readout<'a> {
/// Accessible name of the text field shown while editing.
pub(crate) name: &'a str,
pub(super) name: &'a str,
/// The value painted while not editing.
pub(crate) display: &'a str,
pub(super) display: &'a str,
/// The editor's initial text.
pub(crate) edit_initial: &'a str,
pub(crate) parse: fn(&str) -> Option<f32>,
pub(super) edit_initial: &'a str,
pub(super) parse: fn(&str) -> Option<f32>,
/// The value an Alt-click sets.
pub(crate) reset: f32,
pub(super) reset: f32,
}
/// Paint a value until clicked, then replace it with a focused text field. Enter or clicking away
/// commits a valid value; Escape cancels, and so does the field losing focus while hidden.
/// Alt-click returns `reset`. The interaction response remains available for dragging.
pub(crate) fn editable_readout(ui: &mut Ui, r: Rect, id: egui::Id, readout: Readout<'_>) -> (Option<egui::Response>, Option<f32>) {
pub(super) fn editable_readout(ui: &mut Ui, r: Rect, id: egui::Id, readout: Readout<'_>) -> (Option<egui::Response>, Option<f32>) {
let Readout { name, display, edit_initial, parse, reset } = readout;
let t = Tokens::current();
let active_id = id.with("active");
@@ -289,7 +280,7 @@ pub(crate) fn editable_readout(ui: &mut Ui, r: Rect, id: egui::Id, readout: Read
(response, value)
}
pub(crate) fn parse_db(text: &str) -> Option<f32> {
pub(super) fn parse_db(text: &str) -> Option<f32> {
let cleaned = text.trim().to_ascii_lowercase().replace("db", "").replace(',', ".");
if matches!(cleaned.trim(), "-inf" | "-infinity" | "off") {
return Some(-144.0);
@@ -297,7 +288,7 @@ pub(crate) fn parse_db(text: &str) -> Option<f32> {
cleaned.trim().parse::<f32>().ok().filter(|v| v.is_finite()).map(|v| v.clamp(-144.0, 12.0))
}
pub(crate) fn parse_pan(text: &str) -> Option<f32> {
pub(super) fn parse_pan(text: &str) -> Option<f32> {
let cleaned = text.trim().to_ascii_lowercase().replace(',', ".");
let (sign, number) = if let Some(v) = cleaned.strip_prefix('<').or_else(|| cleaned.strip_prefix('l')) {
(-1.0, v)
@@ -344,6 +335,7 @@ enum SendFooter {
/// that scrolls, "new bus..." (and "Remove send" for an existing send) fixed under it.
/// `current` is the send's destination and its name, if the slot has a send.
fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: TrackId, slot: usize, current: Option<(Route, String)>) {
let busses = app.engine.session().busses.clone();
let which = (b'A' + slot as u8) as char;
let has_send = current.is_some();
let header = |ui: &mut Ui| {
@@ -351,19 +343,18 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
match &current {
Some((_, name)) => {
ui.horizontal(|ui| {
ui.strong(crate::localized_format!("Send {which}", which = which));
ui.strong(format!("Send {which}"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(egui::RichText::new(name).color(Tokens::current().counter_text));
});
});
ui.label(egui::RichText::new(crate::localization::text("DESTINATION")).size(8.0).color(Tokens::current().text_dim));
ui.label(egui::RichText::new("DESTINATION").size(8.0).color(Tokens::current().text_dim));
}
None => {
ui.strong(crate::localized_format!("Send {which} · Choose destination", which = which));
ui.strong(format!("Send {which} · Choose destination"));
}
}
let search = MenuSearch::show(ui, egui::Id::unique(("send-bus-search", id.0, slot)), crate::localization::text("Search buses…"));
let busses = &app.engine.session().busses;
let search = MenuSearch::show(ui, egui::Id::unique(("send-bus-search", id.0, slot)), "Search buses…");
let visible: Vec<_> = busses.iter().filter(|bus| search.matches(&bus.name)).collect();
(search, visible)
};
@@ -385,11 +376,11 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
})
},
|ui| {
if ui.button(crate::localization::text("new bus...")).clicked() {
if ui.button("new bus...").clicked() {
ui.close();
return Some(SendFooter::NewBus);
}
if has_send && ui.button(crate::localization::text("Remove send")).clicked() {
if has_send && ui.button("Remove send").clicked() {
ui.close();
return Some(SendFooter::RemoveSend);
}
@@ -411,7 +402,6 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
}
match footer {
Some(SendFooter::NewBus) => {
let busses = &app.engine.session().busses;
let mut n = busses.len() + 1;
while busses.iter().any(|bus| bus.name.eq_ignore_ascii_case(&format!("Bus {n}")))
|| app.engine.session().track_by_name(&format!("Bus {n}")).is_some()
+3 -6
View File
@@ -10,7 +10,7 @@ pub(crate) fn instrument_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, r:
let ins = track.instrument.as_ref();
let info = ins.and_then(|i| plugin_info(&i.plugin));
let resp = ui.interact(r, ui.scope_id().with(("instrument", id.0)), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localized_format!("Instrument for {}", track.name)));
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Instrument for {}", track.name)));
match info {
Some(info) => used_slot(ui.painter(), r, t.slot_face, Mark::Dot, info.short_name, t.text, None),
None => empty_slot(ui.painter(), r, resp.hovered(), Mark::Dot),
@@ -19,8 +19,7 @@ pub(crate) fn instrument_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, r:
if resp.clicked() && hosted && !app.ui.plugin_windows.contains(&(id, slot)) {
app.ui.plugin_windows.push((id, slot));
}
let menu_resp =
if hosted { resp.clone().on_hover_text(crate::localization::text("Click: open instrument · right-click: change")) } else { resp.clone() };
let menu_resp = if hosted { resp.clone().on_hover_text("Click: open instrument · right-click: change") } else { resp.clone() };
let popup = if hosted { egui::Popup::context_menu(&menu_resp) } else { egui::Popup::menu(&menu_resp) };
let popup = popup.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
popup.show(|ui| instrument_menu(app, ui, id));
@@ -104,9 +103,7 @@ pub(crate) fn insert_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot:
let id = track.id;
let ins = track.mixer.inserts.get(slot).cloned().flatten();
let resp = ui.interact(r, ui.scope_id().with(("ins", id.0, slot)), Sense::click());
resp.widget_info(|| {
egui::WidgetInfo::labeled(egui::Role::Button, true, crate::localized_format!("Insert {} for {}", (b'A' + slot as u8) as char, track.name))
});
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Insert {} for {}", (b'A' + slot as u8) as char, track.name)));
let info = ins.as_ref().and_then(|i| plugin_info(&i.plugin));
let name = ins.as_ref().map(|i| info.map_or(i.plugin.as_str(), |p| p.short_name)).unwrap_or_default();
match &ins {
+8 -20
View File
@@ -65,30 +65,19 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let t = Tokens::current();
let mut run: Option<String> = None;
let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
egui::Window::new(crate::localization::text("Search"))
.id(egui::Id::unique("Search"))
egui::Window::new("Search")
.collapsible(false)
.resizable(false)
.title_bar(false)
.anchor(Align2::CENTER_TOP, vec2(0.0, 90.0))
.fixed_size(vec2(560.0, 380.0))
.show(ctx, |ui| {
let r = ui.add(
egui::TextEdit::singleline(&mut app.palette.query)
.hint_text(crate::localization::text("Search commands…"))
.desired_width(f32::INFINITY)
.font(mono(15.0)),
);
let r = ui
.add(egui::TextEdit::singleline(&mut app.palette.query).hint_text("Search commands…").desired_width(f32::INFINITY).font(mono(15.0)));
r.request_focus();
let q = app.palette.query.trim().to_string();
let mut hits: Vec<(i32, Entry)> = entries()
.into_iter()
.filter_map(|e| {
let label = crate::localization::text(&e.label);
let path = e.path.split(" › ").map(crate::localization::text).collect::<Vec<_>>().join(" › ");
score(&format!("{label} {path} {} {} {}", e.label, e.path, e.id), &q).map(|s| (s, e))
})
.collect();
let mut hits: Vec<(i32, Entry)> =
entries().into_iter().filter_map(|e| score(&format!("{} {} {}", e.label, e.path, e.id), &q).map(|s| (s, e))).collect();
hits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.label.cmp(&b.1.label)));
hits.truncate(14);
let (down, up, enter) = ctx.input(|i| (i.key_pressed(Key::ArrowDown), i.key_pressed(Key::ArrowUp), i.key_pressed(Key::Enter)));
@@ -103,11 +92,10 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
for (i, (_, e)) in hits.iter().enumerate() {
let sel = i == app.palette.selected;
let resp = ui.horizontal(|ui| {
let l = ui.selectable_label(sel, crate::localization::text(&e.label));
let path = e.path.split(" › ").map(crate::localization::text).collect::<Vec<_>>().join(" › ");
ui.label(egui::RichText::new(path).small().color(t.text_dim));
let l = ui.selectable_label(sel, &e.label);
ui.label(egui::RichText::new(&e.path).small().color(t.text_dim));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let sc = crate::shortcuts::display_shortcut(&e.shortcut, ctx.os().is_mac());
let sc = crate::shortcuts::shortcut_label(&e.shortcut, ctx.os().is_mac());
ui.label(egui::RichText::new(sc).font(mono(10.0)).color(t.text_dim));
});
l
+1 -1
View File
@@ -33,7 +33,7 @@ fn panel_header(ui: &mut Ui, title: &str) {
let t = Tokens::current();
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::hover());
ui.painter().rect_filled(r, 0.0, t.panel_bg2);
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, crate::localization::text(title), bold(11.5), t.header_text);
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, title, bold(11.5), t.header_text);
ui.painter().line_segment([pos2(r.min.x, r.max.y), pos2(r.max.x, r.max.y)], Stroke::new(1.0, t.border));
}
+26 -35
View File
@@ -7,35 +7,30 @@ pub(super) fn about(app: &mut SoundApp, ctx: &egui::Context) {
return;
}
let tab_id = egui::Id::unique("about_tab");
egui::Window::new(crate::localization::text("About SoundCraft"))
.id(egui::Id::unique("About SoundCraft"))
.open(&mut open)
.default_size(vec2(820.0, 420.0))
.collapsible(false)
.show(ctx, |ui| {
let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);
ui.horizontal(|ui| {
for (i, l) in (0u8..).zip(["About", "Contributors", "Models"]) {
if ui.selectable_label(tab == i, crate::localization::text(l)).clicked() {
tab = i;
}
}
});
ui.data_mut(|d| d.insert_temp(tab_id, tab));
ui.separator();
match tab {
1 => crate::credits::contributors_ui(ui),
2 => crate::credits::models_ui(ui),
_ => {
ui.label(egui::RichText::new(crate::localization::text("SoundCraft")).font(bold(22.0)));
ui.label(crate::localized_format!("Version {}", env!("CARGO_PKG_VERSION")));
ui.label(crate::localization::text("An open-source digital audio workstation from the ArtCraft team."));
ui.label(crate::localization::text("Dual-licensed MIT OR Apache-2.0. Made with Rust and egui."));
ui.hyperlink_to("getartcraft.com/apps/soundcraft", "https://getartcraft.com/apps/soundcraft");
ui.hyperlink_to(crate::localization::text("Join us on Discord"), "https://discord.gg/artcraft");
egui::Window::new("About SoundCraft").open(&mut open).default_size(vec2(820.0, 420.0)).collapsible(false).show(ctx, |ui| {
let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);
ui.horizontal(|ui| {
for (i, l) in (0u8..).zip(["About", "Contributors", "Models"]) {
if ui.selectable_label(tab == i, l).clicked() {
tab = i;
}
}
});
ui.data_mut(|d| d.insert_temp(tab_id, tab));
ui.separator();
match tab {
1 => crate::credits::contributors_ui(ui),
2 => crate::credits::models_ui(ui),
_ => {
ui.label(egui::RichText::new("SoundCraft").font(bold(22.0)));
ui.label(format!("Version {}", env!("CARGO_PKG_VERSION")));
ui.label("An open-source digital audio workstation from the ArtCraft team.");
ui.label("Dual-licensed MIT OR Apache-2.0. Made with Rust and egui.");
ui.hyperlink_to("getartcraft.com/apps/soundcraft", "https://getartcraft.com/apps/soundcraft");
ui.hyperlink_to("Join us on Discord", "https://discord.gg/artcraft");
}
}
});
app.ui.show_about = open;
}
@@ -44,15 +39,11 @@ pub(super) fn session_info(app: &mut SoundApp, ctx: &egui::Context) {
if !open {
return;
}
egui::Window::new(crate::localization::text("Session Info"))
.id(egui::Id::unique("Session Info"))
.open(&mut open)
.default_size(vec2(480.0, 360.0))
.show(ctx, |ui| {
let text = soundcraft_engine::inspect::session_text(&app.engine);
egui::ScrollArea::vertical().show(ui, |ui| {
ui.label(egui::RichText::new(text).font(mono(11.0)));
});
egui::Window::new("Session Info").open(&mut open).default_size(vec2(480.0, 360.0)).show(ctx, |ui| {
let text = soundcraft_engine::inspect::session_text(&app.engine);
egui::ScrollArea::vertical().show(ui, |ui| {
ui.label(egui::RichText::new(text).font(mono(11.0)));
});
});
app.ui.show_session_info = open;
}
+5 -5
View File
@@ -34,7 +34,7 @@ pub fn clip_list(app: &mut SoundApp, ui: &mut Ui) {
panel_header(ui, "CLIPS");
let fkey = egui::Id::unique("clip_filter");
let mut filter: String = ui.ctx().memory(|m| m.data.get_temp(fkey)).unwrap_or_default();
ui.add(egui::TextEdit::singleline(&mut filter).hint_text(crate::localization::text("🔍 Find clips")).desired_width(f32::INFINITY));
ui.add(egui::TextEdit::singleline(&mut filter).hint_text("🔍 Find clips").desired_width(f32::INFINITY));
ui.ctx().memory_mut(|m| m.data.insert_temp(fkey, filter.clone()));
let needle = filter.to_lowercase();
let rkey = egui::Id::unique("clip_rows");
@@ -73,26 +73,26 @@ pub fn clip_list(app: &mut SoundApp, ui: &mut Ui) {
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), if whole { Sense::click_and_drag() } else { Sense::click() });
resp.context_menu(|ui| {
if whole {
if ui.button(crate::localization::text("Place on New Track")).clicked() {
if ui.button("Place on New Track").clicked() {
let _ = app.run("clip.place_source", json!({"source": id}));
ui.close();
}
let sel_track = app.engine.session().edit.selected_tracks.first().map(|t| t.0);
if let Some(t) = sel_track
&& ui.button(crate::localization::text("Place on Selected Track")).clicked()
&& ui.button("Place on Selected Track").clicked()
{
let _ = app.run("clip.place_source", json!({"source": id, "track": t}));
ui.close();
}
ui.separator();
}
if !whole && ui.button(crate::localization::text("Auto Rename…")).clicked() {
if !whole && ui.button("Auto Rename…").clicked() {
// The selected clips when the row is one of them, otherwise the row's clip.
let clips = if selected { app.engine.session().edit.selected_clips.clone() } else { vec![ClipId(id)] };
app.dialogs.open_auto_rename(&app.engine, clips);
ui.close();
}
if ui.button(crate::localization::text("Clear…")).clicked() {
if ui.button("Clear…").clicked() {
let (clips, sources) = if whole { (vec![], vec![SourceId(id)]) } else { (vec![ClipId(id)], vec![]) };
app.dialogs.open_clear(&app.engine, clips, sources);
ui.close();
+32 -56
View File
@@ -105,13 +105,10 @@ fn renderer(app: &mut SoundApp, ctx: &egui::Context) {
(tr.name.clone(), sp.x, sp.y, sp.z)
})
.collect();
egui::Window::new(egui::RichText::new(crate::localization::text("Renderer")).font(bold(13.0)))
.id(egui::Id::unique("Renderer"))
.open(&mut open)
.default_size(vec2(380.0, 440.0))
.resizable(true)
.show(ctx, |ui| {
ui.label(egui::RichText::new(crate::localized_format!("Main output: {}", fmt.label())).font(regular(11.0)).color(t.text));
egui::Window::new(egui::RichText::new("Renderer").font(bold(13.0))).open(&mut open).default_size(vec2(380.0, 440.0)).resizable(true).show(
ctx,
|ui| {
ui.label(egui::RichText::new(format!("Main output: {}", fmt.label())).font(regular(11.0)).color(t.text));
let side = ui.available_width().min(360.0);
let (r, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
let p = ui.painter_at(r);
@@ -120,7 +117,7 @@ fn renderer(app: &mut SoundApp, ctx: &egui::Context) {
let rad = side * 0.40;
p.circle_stroke(c, rad, Stroke::new(1.0, Color32::from_rgb(60, 68, 78)));
p.circle_stroke(c, rad * 0.55, Stroke::new(1.0, Color32::from_rgb(44, 50, 58)));
p.text(pos2(c.x, r.min.y + 8.0), Align2::CENTER_TOP, crate::localization::text("front"), regular(9.0), t.text_dim);
p.text(pos2(c.x, r.min.y + 8.0), Align2::CENTER_TOP, "front", regular(9.0), t.text_dim);
for (i, sp) in fmt.speakers().iter().enumerate() {
let level = peaks.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0);
let ring = if sp.is_height() { rad * 0.55 } else { rad };
@@ -139,32 +136,27 @@ fn renderer(app: &mut SoundApp, ctx: &egui::Context) {
ui.add_space(4.0);
if objects.is_empty() {
ui.label(
egui::RichText::new(crate::localization::text(
"No object tracks. Use the Object view in the Mix window to route tracks as objects.",
))
.small()
.color(t.text_dim),
egui::RichText::new("No object tracks. Use the Object view in the Mix window to route tracks as objects.")
.small()
.color(t.text_dim),
);
} else {
ui.label(egui::RichText::new(crate::localized_format!("{} object track(s)", objects.len())).small().color(t.text_dim));
ui.label(egui::RichText::new(format!("{} object track(s)", objects.len())).small().color(t.text_dim));
}
});
},
);
app.extra.show_renderer = open;
}
/// Appearance window: interface scale, reduce visual effects, theme, language, auto-update configuration and Reset.
/// Appearance window: interface scale, reduce-motion, theme, auto-update configuration and Reset.
fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
let mut open = app.extra.show_ui_customization;
if !open {
return;
}
let language = app.ui.language;
egui::Window::new(egui::RichText::new(crate::localization::text("Appearance")).font(bold(13.0)))
.id(egui::Id::unique("Appearance"))
.open(&mut open)
.default_size(vec2(320.0, 210.0))
.resizable(false)
.show(ctx, |ui| {
egui::Window::new(egui::RichText::new("Appearance").font(bold(13.0))).open(&mut open).default_size(vec2(320.0, 180.0)).resizable(false).show(
ctx,
|ui| {
// Each control carries its own visible label, which is also its accessible name. A
// label in a neighbouring grid cell is only painted text: a screen reader (and the
// kittest accessibility check) would see an unnamed slider, checkbox or combo box.
@@ -172,54 +164,38 @@ fn ui_customization(app: &mut SoundApp, ctx: &egui::Context) {
egui::Slider::new(&mut app.extra.ui_scale, 0.75..=1.5)
.step_by(0.05)
.custom_formatter(|v, _| format!("{:.0} %", v * 100.0))
.text(crate::localization::text("Interface scale")),
.text("Interface scale"),
);
let mut chosen_effects = None;
craft_ui::ComboBox::from_label(crate::localization::text("Reduce visual effects"))
.selected_text(crate::localization::text(app.ui.reduce_visual_effects.label()))
.show_ui(ui, |ui| {
for mode in crate::preferences::ReduceVisualEffects::ALL {
if ui.selectable_label(app.ui.reduce_visual_effects == mode, crate::localization::text(mode.label())).clicked() {
chosen_effects = Some(mode);
}
craft_ui::ComboBox::from_label("Reduce visual effects").selected_text(app.ui.reduce_visual_effects.label()).show_ui(ui, |ui| {
for mode in crate::preferences::ReduceVisualEffects::ALL {
if ui.selectable_label(app.ui.reduce_visual_effects == mode, mode.label()).clicked() {
chosen_effects = Some(mode);
}
});
}
});
if let Some(mode) = chosen_effects {
let _ = app.run("ui.reduce_visual_effects", json!({"mode": mode.id()}));
}
let mut selected_language = None;
craft_ui::ComboBox::from_label(crate::localization::text("Language"))
.selected_text(crate::localization::text(language.native_name()))
.show_ui(ui, |ui| {
for choice in crate::localization::Language::ALL {
if ui.selectable_label(language == choice, crate::localization::text(choice.native_name())).clicked() {
selected_language = Some(choice);
}
}
});
if let Some(choice) = selected_language {
let _ = app.run("ui.language", json!({"language": choice.id()}));
}
let mut chosen = None;
craft_ui::ComboBox::from_label(crate::localization::text("Theme"))
.selected_text(crate::localization::text(app.ui.theme.label()))
.show_ui(ui, |ui| {
for mode in crate::theme::ThemeMode::ALL {
if ui.selectable_label(app.ui.theme == mode, crate::localization::text(mode.label())).clicked() {
chosen = Some(mode);
}
craft_ui::ComboBox::from_label("Theme").selected_text(app.ui.theme.label()).show_ui(ui, |ui| {
for mode in crate::theme::ThemeMode::ALL {
if ui.selectable_label(app.ui.theme == mode, mode.label()).clicked() {
chosen = Some(mode);
}
});
}
});
if let Some(mode) = chosen {
let _ = app.run("ui.theme", json!({"mode": mode.id()}));
}
crate::widgets::checkbox(ui, &mut app.extra.auto_update_config, crate::localization::text("Auto-update configuration"));
crate::widgets::checkbox(ui, &mut app.extra.auto_update_config, "Auto-update configuration");
ui.add_space(4.0);
if ui.button(crate::localization::text("Reset")).clicked() {
if ui.button("Reset").clicked() {
app.extra.ui_scale = 1.0;
let _ = app.run("ui.reduce_visual_effects", json!({"mode": "never"}));
let _ = app.run("ui.theme", json!({"mode": crate::theme::ThemeMode::default().id()}));
}
});
},
);
app.extra.show_ui_customization = open;
}
+2 -6
View File
@@ -5,18 +5,14 @@ pub(crate) fn undo_history(app: &mut SoundApp, ui: &mut Ui) {
let n = hist.len();
egui::ScrollArea::vertical().show(ui, |ui| {
for (i, h) in hist.iter().enumerate() {
if ui.selectable_label(i + 1 == n, format!("{} {}", i + 1, crate::localization::text(h))).clicked() {
if ui.selectable_label(i + 1 == n, format!("{} {h}", i + 1)).clicked() {
for _ in 0..(n - i - 1) {
let _ = app.run("edit.undo", json!({}));
}
}
}
if let Some(r) = app.engine.redo_label() {
ui.label(
egui::RichText::new(crate::localized_format!("(redo) {r}", r = crate::localization::text(r)))
.italics()
.color(Tokens::current().text_dim),
);
ui.label(egui::RichText::new(format!("(redo) {r}")).italics().color(Tokens::current().text_dim));
}
});
}
+6 -6
View File
@@ -2,12 +2,12 @@ use super::{SoundApp, Ui, json, mono};
/// One recallable memory-location row: number button, editable name, time, length, kind and delete.
fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc: &str, len: &str, kind: &str) {
if ui.button(n.to_string()).on_hover_text(crate::localization::text("Recall")).clicked() {
if ui.button(n.to_string()).on_hover_text("Recall").clicked() {
let _ = app.run("markers.recall", json!({"number": n}));
}
let key = egui::Id::unique(("mem_name", n));
let mut edit: String = ui.ctx().memory(|m| m.data.get_temp(key)).unwrap_or_else(|| name.to_string());
let r = crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(&mut edit).desired_width(140.0)), crate::localization::text("Name"));
let r = crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(&mut edit).desired_width(140.0)), "Name");
if r.changed() {
ui.ctx().memory_mut(|m| m.data.insert_temp(key, edit.clone()));
}
@@ -17,7 +17,7 @@ fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc:
}
ui.label(egui::RichText::new(loc).font(mono(11.0)));
ui.label(egui::RichText::new(len).font(mono(11.0)));
ui.label(crate::localization::text(kind));
ui.label(kind);
if crate::widgets::close_button(ui, "Delete marker").clicked() {
let _ = app.run("markers.delete", json!({"number": n}));
}
@@ -26,10 +26,10 @@ fn memory_location_row(app: &mut SoundApp, ui: &mut Ui, n: u32, name: &str, loc:
pub(crate) fn memory_locations(app: &mut SoundApp, ui: &mut Ui) {
ui.horizontal(|ui| {
if ui.button(crate::localization::text("+ Marker")).clicked() {
if ui.button("+ Marker").clicked() {
let _ = app.run("markers.add", json!({}));
}
if ui.button(crate::localization::text("+ Selection")).clicked() {
if ui.button("+ Selection").clicked() {
let _ = app.run("markers.add", json!({"kind": "selection"}));
}
});
@@ -52,7 +52,7 @@ pub(crate) fn memory_locations(app: &mut SoundApp, ui: &mut Ui) {
egui::ScrollArea::vertical().show(ui, |ui| {
egui::Grid::new("mem_grid").striped(true).num_columns(6).show(ui, |ui| {
for h in ["#", "Name", "Location", "Length", "Type", ""] {
ui.label(egui::RichText::new(crate::localization::text(h)).strong());
ui.label(egui::RichText::new(h).strong());
}
ui.end_row();
for (n, name, loc, len, kind) in &rows {

Some files were not shown because too many files have changed in this diff Show More