diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml
index 8f118327..97cdfdf9 100644
--- a/.github/workflows/nix.yml
+++ b/.github/workflows/nix.yml
@@ -23,43 +23,5 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
git-sources:
- name: Git dependencies come from storytold
- runs-on: ubuntu-latest
- timeout-minutes: 5
- steps:
- - name: Harden runner
- uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
- with:
- egress-policy: audit
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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
+ # 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
diff --git a/AGENTS.md b/AGENTS.md
index e842724d..b3fcb022 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -109,9 +109,16 @@ 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]`.
-- **For UI work, look at the result** (render, read the PNG) and compare with `plan/protools/screenshots/`.
+- **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).
- 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.
diff --git a/Cargo.lock b/Cargo.lock
index 43717def..bdf8af71 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1064,7 +1064,7 @@ dependencies = [
[[package]]
name = "craft-audio"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
+source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"craft-media",
"log",
@@ -1073,6 +1073,11 @@ 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"
@@ -1109,7 +1114,7 @@ dependencies = [
[[package]]
name = "craft-media"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
+source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1118,7 +1123,40 @@ 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"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1175,13 +1213,23 @@ dependencies = [
[[package]]
name = "craft-video"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
+source = "git+https://github.com/storytold/craft-libs?rev=45a8e16669e70dadb780dfbc759c882dd5b7ea1c#45a8e16669e70dadb780dfbc759c882dd5b7ea1c"
dependencies = [
"craft-media",
"rayon",
"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"
@@ -1515,6 +1563,20 @@ 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"
@@ -2718,6 +2780,12 @@ 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"
@@ -4456,6 +4524,7 @@ version = "0.20.1"
dependencies = [
"craft-audio",
"craft-docpath",
+ "craft-scraft-format",
"log",
"proptest",
"serde",
@@ -4502,13 +4571,7 @@ dependencies = [
name = "soundcraft-model"
version = "0.20.1"
dependencies = [
- "craft-audio",
- "proptest",
- "serde",
- "serde_json",
- "soundcraft-midi",
- "soundcraft-time",
- "thiserror 2.0.21",
+ "craft-scraft-format",
]
[[package]]
@@ -4530,10 +4593,7 @@ dependencies = [
name = "soundcraft-time"
version = "0.20.1"
dependencies = [
- "proptest",
- "serde",
- "serde_json",
- "thiserror 2.0.21",
+ "craft-time",
]
[[package]]
@@ -4541,6 +4601,7 @@ name = "soundcraft-ui-egui"
version = "0.20.1"
dependencies = [
"craft-audio",
+ "craft-mime",
"craft-ui",
"craft-update",
"egui",
diff --git a/Cargo.toml b/Cargo.toml
index 625c145b..192fde9c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/soundcraft"
[workspace.dependencies]
+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" }
@@ -51,14 +52,16 @@ cpal = "0.18"
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
# Video containers and bitstreams, shared with the other craft apps.
-craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" }
+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 = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", default-features = false, features = ["h264-decode", "prores"] }
+craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "45a8e16669e70dadb780dfbc759c882dd5b7ea1c", default-features = false, features = ["h264-decode", "prores"] }
# 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 = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", features = ["serde"] }
-craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", features = ["decode", "lossless-encode", "peaks", "serde"] }
+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-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"] }
diff --git a/README.md b/README.md
index 0b7dfdb8..7d518d66 100644
--- a/README.md
+++ b/README.md
@@ -243,10 +243,10 @@ about egui, so the interface could be swapped for another one.
| Crate | What it does |
|---|---|
-| `soundcraft-time` | Timebases, tempo and meter maps, timecode, grid |
+| `soundcraft-time` | Compatibility re-export of `craft-time`'s SoundCraft sample-index API |
| `soundcraft-midi` | Standard MIDI Files and MIDI operations |
| `soundcraft-dsp` | Plugins, offline processing, meters, loudness, FFT |
-| `soundcraft-model` | The session document |
+| `soundcraft-model` | Compatibility re-export of `craft-scraft-format`'s schema, validation and JSON API |
| `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,8 +263,18 @@ 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 are missing too. The status, the stage and our effort
-estimates are in [`ROADMAP.md`](ROADMAP.md); the full assessment is in
+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
[`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
diff --git a/ROADMAP.md b/ROADMAP.md
index 749918c6..a25a45ba 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -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) | 70–110 | [localization-parity.md](docs/localization-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) |
| 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 | pt | none | 0 % |
+| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
| Indonesian | id | none | 0 % |
| Japanese | ja | none | 0 % |
| German | de | none | 0 % |
| Korean | ko | none | 0 % |
| Vietnamese | vi | none | 0 % |
-Other languages shipped: 0. Detail: [localization-parity.md](docs/localization-parity.md).
+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).
## Upcoming
@@ -180,6 +180,7 @@ 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 |
diff --git a/apps/soundcraft-web/src/web.rs b/apps/soundcraft-web/src/web.rs
index aac7cef6..d7208883 100644
--- a/apps/soundcraft-web/src/web.rs
+++ b/apps/soundcraft-web/src/web.rs
@@ -2,6 +2,8 @@
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;
@@ -12,10 +14,19 @@ 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;
@@ -48,7 +59,11 @@ pub fn start() {
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
- Err(e) => el.set_inner_html(&format!("
SoundCraft failed to start: {e:?}
A browser with WebGPU or WebGL2 is required.
")),
+ 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.")
+ ))),
}
}
});
@@ -92,11 +107,11 @@ impl Purpose {
}
}
- fn filter(self) -> (&'static str, Vec<&'static str>) {
+ fn filter(self) -> (String, Vec<&'static str>) {
match self {
- Self::Session => ("SoundCraft Session", SESSION_EXTS.to_vec()),
- Self::Audio => ("Audio", craft_audio::DECODE_EXTENSIONS.to_vec()),
- Self::Midi => ("MIDI", MIDI_EXTS.to_vec()),
+ 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()),
}
}
}
@@ -126,9 +141,12 @@ 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 (label, exts) = purpose.filter();
- let Some(file) = rfd::AsyncFileDialog::new().add_filter(label, &exts).pick_file().await else { return };
+ 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();
@@ -165,6 +183,7 @@ impl WebShell {
}
fn handle(&mut self, purpose: Purpose, name: String, bytes: Vec) {
+ 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 {
@@ -174,15 +193,15 @@ impl WebShell {
Purpose::Audio => {
let before = e.session_arc();
io::import_audio_bytes(e, &name, &bytes, None, None, at).map(|_| {
- e.push_undo("Import Audio", before);
- format!("Imported {name}")
+ e.push_undo(localization::text("Import Audio"), before);
+ localized_format!("Imported {name}", name = name)
})
}
Purpose::Midi => {
let before = e.session_arc();
io::import_midi_bytes(e, &bytes, at, true).map(|_| {
- e.push_undo("Import MIDI", before);
- format!("Imported {name}")
+ e.push_undo(localization::text("Import MIDI"), before);
+ localized_format!("Imported {name}", name = name)
})
}
};
@@ -221,7 +240,8 @@ 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 js = |e: wasm_bindgen::JsValue| format!("download failed: {e:?}");
+ let _language = localization::enter(browser_language());
+ let js = |e: wasm_bindgen::JsValue| localized_format!("Download failed: {}", format!("{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));
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index d6e8b85b..f9f1e2df 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -10,6 +10,7 @@ repository.workspace = true
[dependencies]
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
@@ -22,7 +23,6 @@ serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
log.workspace = true
-zip.workspace = true
craft-docpath.workspace = true
[target.'cfg(windows)'.dependencies]
@@ -30,6 +30,7 @@ winsafe = { version = "0.0.29", features = ["kernel"] }
[dev-dependencies]
proptest.workspace = true
+zip.workspace = true
[lints]
workspace = true
diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs
index 90979672..1880cc8c 100644
--- a/crates/engine/src/io.rs
+++ b/crates/engine/src/io.rs
@@ -182,46 +182,20 @@ 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<()> {
- 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})")
- }))
+ craft_scraft_format::check_session_size(&name.to_string(), len, session_limit(), saving).map_err(|error| EngineError::Io(error.to_string()))
}
/// [`read_text`] for a session file: refused, unread, past [`session_limit`].
pub(crate) fn read_session_text(path: impl AsRef) -> Result {
let path = path.as_ref();
- utf8(path, read_file_within(path, true)?)
+ 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()))
}
/// 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 {
- 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 {
- 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)
+ craft_scraft_format::read_session_bytes(name, bytes, session_limit()).map_err(|error| EngineError::Io(error.to_string()))
}
/// Is there a file at `path` the automation read root lets us see? A path outside the root is
@@ -795,11 +769,12 @@ 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 text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
- session_size(p.display(), text.len() as u64, true)?;
+ 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()))?;
Some(text)
} else {
- session_size(p.display(), json_len(&s), true)?;
+ let size = craft_scraft_format::session_json_len(&s).map_err(|error| EngineError::Io(error.to_string()))?;
+ session_size(p.display(), size, true)?;
None
};
let mut written = 0;
@@ -820,7 +795,10 @@ fn write_session(session: &Session, path: &str, overwrite: bool) -> Result<(Sess
}
let text = match checked {
Some(text) => text,
- None => s.to_json().map_err(|err| EngineError::Io(err.to_string()))?,
+ 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()))?
+ }
};
make_dir(&dir)?;
// Atomic-ish write: temp file then rename.
@@ -1107,45 +1085,11 @@ 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>)> {
- 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))
+ 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()))
}
/// The record-enabled audio tracks, each with the input channels it records (those its input
diff --git a/crates/engine/src/io/bundle.rs b/crates/engine/src/io/bundle.rs
index 47467b23..566a77c8 100644
--- a/crates/engine/src/io/bundle.rs
+++ b/crates/engine/src/io/bundle.rs
@@ -1,13 +1,13 @@
use super::render::sanitize_name;
use super::session::decode_source;
-use super::{Arc, EncodeOptions, Engine, EngineError, FileFormat, OsStr, Path, Result, Session, SourceAudio, read_bundle, write_file};
+use super::{Arc, Engine, EngineError, OsStr, Path, Result, Session, SourceAudio, read_bundle, session_limit, 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 = "scraftz";
+pub const BUNDLE_EXTENSION: &str = craft_scraft_format::BUNDLE_EXTENSION;
/// 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,54 +28,8 @@ pub fn session_bundle(session: &Session) -> Result<(Vec, Session)> {
/// [`session_bundle`], refused when it would hold more than `limits` allows.
fn session_bundle_within(session: &Session, limits: BundleLimits) -> Result<(Vec, Session)> {
- 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))
+ 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()))
}
/// Save as a bundle named after `path`'s file name, delivered through the host ([`write_file`]).
@@ -200,6 +154,48 @@ 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 _;
diff --git a/crates/engine/src/io/midi.rs b/crates/engine/src/io/midi.rs
index bced021f..d3042665 100644
--- a/crates/engine/src/io/midi.rs
+++ b/crates/engine/src/io/midi.rs
@@ -12,8 +12,35 @@ pub(super) const MAX_MIDI_TRACKS: usize = 512;
/// 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> {
- let smf = soundcraft_midi::read_smf(bytes).map_err(|err| EngineError::Io(err.to_string()))?;
+ 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
+ }
+ };
if tempo_map {
// Each meter is placed by walking the ones before it.
if smf.meters.len() > MAX_MIDI_METERS {
diff --git a/crates/engine/src/io/render.rs b/crates/engine/src/io/render.rs
index 39eed648..bcd3dbec 100644
--- a/crates/engine/src/io/render.rs
+++ b/crates/engine/src/io/render.rs
@@ -177,6 +177,71 @@ 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 };
diff --git a/crates/midi/src/lib.rs b/crates/midi/src/lib.rs
index 8ab5243f..aff14495 100644
--- a/crates/midi/src/lib.rs
+++ b/crates/midi/src/lib.rs
@@ -2,8 +2,9 @@
//!
//! - [`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. 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, 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.
//! - [`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)]
@@ -12,6 +13,8 @@ mod names;
pub mod ops;
mod rng;
-pub use craft_midi::{CtrlEvent, CtrlKind, MAX_EVENTS, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, read_smf, write_smf};
+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 names::{gm_drum_name, gm_program_name, note_name};
pub use rng::XorShift;
diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml
index 9422710a..b5d3157d 100644
--- a/crates/model/Cargo.toml
+++ b/crates/model/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "soundcraft-model"
-description = "SoundCraft session document: tracks, playlists, clips, mixer, routing, automation, markers"
+description = "Compatibility facade for SoundCraft's shared native session format"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,15 +8,7 @@ rust-version.workspace = true
repository.workspace = true
[dependencies]
-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
+craft-scraft-format.workspace = true
[lints]
workspace = true
diff --git a/crates/model/src/automation.rs b/crates/model/src/automation.rs
deleted file mode 100644
index 7bf7d2bd..00000000
--- a/crates/model/src/automation.rs
+++ /dev/null
@@ -1,394 +0,0 @@
-//! 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 {
- 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 {
- 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 {
- 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,
- #[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);
- }
-}
diff --git a/crates/model/src/b64.rs b/crates/model/src/b64.rs
deleted file mode 100644
index 1435d313..00000000
--- a/crates/model/src/b64.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! 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 {
- 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> {
- if text.bytes().filter(|c| !c.is_ascii_whitespace()).count() > MAX_DECODED_BYTES.div_ceil(3).saturating_mul(4) {
- return None;
- }
- let syms: Vec = 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 = (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}");
- }
- }
-}
diff --git a/crates/model/src/clip.rs b/crates/model/src/clip.rs
deleted file mode 100644
index 5b191424..00000000
--- a/crates/model/src/clip.rs
+++ /dev/null
@@ -1,544 +0,0 @@
-//! 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 {
- 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,
- /// 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,
- /// 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,
-}
-
-fn one() -> f64 {
- 1.0
-}
-
-impl Clip {
- pub fn audio(id: ClipId, name: impl Into, 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, 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, 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 {
- 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 {
- 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);
- }
-}
diff --git a/crates/model/src/ids.rs b/crates/model/src/ids.rs
deleted file mode 100644
index 441ced1a..00000000
--- a/crates/model/src/ids.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-//! 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);
diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs
index b5d225c6..1cf02589 100644
--- a/crates/model/src/lib.rs
+++ b/crates/model/src/lib.rs
@@ -1,32 +1,7 @@
-//! The SoundCraft session document.
+//! Compatibility facade for SoundCraft's shared session document crate.
//!
-//! 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.
+//! Engine and UI adapters depend on this name, while the wire schema, JSON reader/writer,
+//! validation, and bundle format live in `craft-scraft-format`.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
-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;
+pub use craft_scraft_format::*;
diff --git a/crates/model/src/markers.rs b/crates/model/src/markers.rs
deleted file mode 100644
index 4441ebca..00000000
--- a/crates/model/src/markers.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-//! 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,
-}
-
-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,
- 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,
-}
diff --git a/crates/model/src/mixer.rs b/crates/model/src/mixer.rs
deleted file mode 100644
index efdaf2d1..00000000
--- a/crates/model/src/mixer.rs
+++ /dev/null
@@ -1,714 +0,0 @@
-//! 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::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,
- #[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,
- /// The session audio source a sample-playing instrument (the built-in Sampler) plays.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub sample: Option,
-}
-
-fn yes() -> bool {
- true
-}
-
-impl Insert {
- pub fn new(plugin: impl Into) -> Self {
- Insert {
- plugin: plugin.into(),
- params: BTreeMap::new(),
- bypass: false,
- active: true,
- preset: String::from(""),
- state: None,
- sample: None,
- }
- }
-
- /// The decoded plugin state (`None` when absent or malformed).
- pub fn state_bytes(&self) -> Option> {
- 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,
-}
-
-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,
- 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