Compare commits

..
Author SHA1 Message Date
FredApps fe44c75b16 Merge branch 'main' into fix/sec-packaging 2026-11-28 12:28:09 +01:00
FredApps edf32e785d fix: parse flatpak archive size with tar --numeric-owner
GNU tar prints owner and group names unquoted, so a name with a
space shifts the size out of awk field 3 and the 2 GiB unpack
guard can fail open. Numeric IDs stay in one field.
2026-11-28 11:18:35 +01:00
FredApps 00ba1b66b6 Merge branch 'main' into fix/sec-packaging 2026-11-28 11:07:06 +01:00
Dylan M. Taylor 9bbb7e01dd packaging: keep the signing certificate in a private folder and bound the Flatpak tarball 2026-11-03 04:35:18 +00:00
60 changed files with 143 additions and 6597 deletions
+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1408486424,
"producer_workflow_id": 429730684,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+1 -1
View File
@@ -214,7 +214,7 @@ jobs:
with:
persist-credentials: false
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@main
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
+2 -16
View File
@@ -34,26 +34,12 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: main
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: soundcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+2 -3
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: main
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: soundcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
@@ -32,4 +32,3 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
Generated
-12
View File
@@ -1822,17 +1822,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2bfc45c49378effb801c6433758fb5aaa5d7808e#2bfc45c49378effb801c6433758fb5aaa5d7808e"
dependencies = [
"js-sys",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
]
[[package]]
name = "craft-win32"
version = "0.1.0"
@@ -6229,7 +6218,6 @@ name = "soundcraft-web"
version = "0.20.1"
dependencies = [
"craft-audio",
"craft-web-api",
"eframe",
"egui",
"js-sys",
+4 -6
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (Languages table: Spanish full; previously trivial: French and Spanish partial; previously minor: long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
@@ -87,10 +87,10 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
|---|---|---|---:|
| English | en | full | 100 % |
| Simplified Chinese | zh-Hans | none | 0 % |
| Spanish | es | full — 100 % of fixed UI strings and engine errors; tests pass | 100 % (native-speaker review done) |
| Spanish | es | none (PR #143 open) | 0 % |
| Hindi | hi | none | 0 % |
| Arabic | ar | none | 0 % |
| French | fr | partial — catalog of 1,368 strings, the rest in English | ≈ 62 % |
| French | fr | none (PR #143 open) | 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 % |
@@ -98,7 +98,7 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
| Korean | ko | none | 0 % |
| Vietnamese | vi | none | 0 % |
Other languages shipped: Spanish complete (fixed UI strings and engine errors, native-speaker review). French is partial (≈ 62 %). Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
Other languages shipped: 0 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
@@ -189,8 +189,6 @@ mutated and truncated movies. Field reports from the first public week are track
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | trivial | Languages table: Spanish catalog complete with native-speaker review. Estimates unchanged |
| 2026-11-24 | trivial | Languages table: French and Spanish catalogs, partial (≈ 62 %), PR #143. Estimates unchanged |
| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged |
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
+1 -2
View File
@@ -27,7 +27,6 @@ fn is_control_method(method: &str) -> bool {
| "ui.key"
| "ui.text"
| "ui.screenshot"
| "audio.health"
| "app.quit"
)
}
@@ -68,7 +67,7 @@ mod tests {
assert_eq!(m, "engine.execute");
let (m, _) = app_request("track.new", json!({}));
assert_eq!(m, "engine.execute");
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "audio.health", "app.quit"] {
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
assert_eq!(app_request(method, json!({})).0, method);
}
for (method, params) in [
-2
View File
@@ -17,8 +17,6 @@ path = "src/main.rs"
soundcraft-engine = { workspace = true }
craft-audio.workspace = true
soundcraft-ui-egui.workspace = true
# The page command API (storytold/craft-libs#413): window.soundcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2bfc45c49378effb801c6433758fb5aaa5d7808e", version = "0.1.0" }
soundcraft-playback = { workspace = true }
soundcraft-model = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
-79
View File
@@ -1,79 +0,0 @@
//! `window.soundcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
//!
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
//! `screenshot`, as promises with a timeout). This module is SoundCraft's part: a [`Request`] that
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
//! reply. SoundCraft's control request has no abandon state, so a call the page gave up on still runs
//! when the app reaches it, as it does for a desktop client that timed out.
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError, TrySendError, sync_channel};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use serde_json::{Value, json};
use soundcraft_ui_egui::ControlRequest;
use wasm_bindgen_futures::JsFuture;
/// The app id in `window.<app>`.
const APP: &str = "soundcraft";
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
/// How many control requests may wait for the app at once. `craft-web-api` already refuses calls past its own
/// in-flight limit; this bounds the app's queue too, so a flood of calls can't grow it without limit.
const QUEUE: usize = 64;
/// Put `window.soundcraft` on the page and return the queue the app drains each frame (hand it to
/// `SoundApp::with_control`). An existing `window.soundcraft` keeps the functions it already has.
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = sync_channel::<ControlRequest>(QUEUE);
let request: Request = Rc::new(move |method, params| {
let (control, reply) = ControlRequest::new(method, params);
if let Err(refused) = queue.try_send(control) {
let error = match refused {
TrySendError::Full(_) => format!("soundcraft is busy: {QUEUE} requests are already waiting for the app"),
TrySendError::Disconnected(_) => "the app is not running".to_string(),
};
return Box::pin(async move { json!({"ok": false, "error": error}) });
}
ctx.request_repaint();
Box::pin(wait(reply))
});
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
log::warn!("couldn't install window.{APP}: {e:?}");
}
requests
}
/// The app's reply, polled about once a frame.
async fn wait(reply: Receiver<Value>) -> Value {
loop {
match reply.try_recv() {
Ok(reply) => return reply,
Err(TryRecvError::Empty) => {
if !sleep(POLL_MS).await {
return json!({"ok": false, "error": "this page has no timer to wait for the app with"});
}
}
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
}
}
}
async fn sleep(ms: i32) -> bool {
// `false` when this page has no timer to wait with (no window, or the timer is refused): the caller ends the
// call with an error instead of going round again at once.
let timer = std::cell::Cell::new(false);
let promise = js_sys::Promise::new(&mut |resolve, _| {
let set = web_sys::window().is_some_and(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms).is_ok());
timer.set(set);
if !set {
let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED);
}
});
let _ = JsFuture::from(promise).await;
timer.get()
}
+1 -4
View File
@@ -6,8 +6,7 @@
//! from this directory (output in `dist/web`).
//!
//! Differences from the desktop app:
//! - no TCP control channel (browsers can't listen on sockets); `window.soundcraft` (`api`) drives the
//! same control channel from the page instead;
//! - no TCP control channel (browsers can't listen on sockets);
//! - no file system: File > Open Session…, Import > Audio…/MIDI… and files dropped on the page are
//! read as bytes through the browser's file picker; a session is saved as ONE bundle file
//! (`<name>.scraftz`: the `.scraft` and its `Audio Files/`), and every save or export arrives as a
@@ -19,8 +18,6 @@
//! empty session instead of the demo.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(target_arch = "wasm32")]
mod web;
+1 -1
View File
@@ -52,7 +52,7 @@ pub fn start() {
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
let app = SoundApp::new(engine, Some(player), Services::default()).with_control(crate::api::install(cc.egui_ctx.clone()));
let app = SoundApp::new(engine, Some(player), Services::default());
Ok(Box::new(WebShell { app, inbox: Rc::default(), samples: Rc::default() }))
}),
)
-109
View File
@@ -1,109 +0,0 @@
// Real-browser check of window.soundcraft (the page command API from craft-web-api): serve a built
// copy of the web app, load it in headless Chromium and drive every function the crate installs.
//
// Usage, from a folder where Playwright is installed (`npm i playwright`, then `npx playwright install chromium`):
// node <repo>/apps/soundcraft-web/tests/page-api.mjs <site folder>
// The site folder is a built copy of the web app: `trunk build --release` in apps/soundcraft-web
// (dist/web), or the unpacked `packaging/web/package.sh` zip. Exits non-zero on the first failed check.
//
// Not repeated here: the 30 s request timeout belongs to craft-web-api and is covered by that crate's own
// tests. The limit on calls waiting for the app (64) is exercised below: it needs a craft-web-api that has it
// (craft-libs#733) and the app's own bounded queue.
import { createRequire } from 'node:module'
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import assert from 'node:assert/strict'
const dir = process.argv[2]
if (!dir) { console.error('usage: node page-api.mjs <site folder>'); process.exit(2) }
const require = createRequire(path.join(process.cwd(), 'noop.js'))
const { chromium } = (() => { try { return require('playwright') } catch { return require('@playwright/test') } })()
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png' }
const server = http.createServer(async (req, res) => {
const route = decodeURIComponent(req.url.split('?')[0])
const file = path.join(dir, route === '/' ? 'index.html' : route)
try {
const body = await readFile(file)
res.writeHead(200, { 'content-type': types[path.extname(file)] || 'application/octet-stream' })
res.end(body)
} catch { res.writeHead(404); res.end() }
})
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
const origin = `http://127.0.0.1:${server.address().port}`
const browser = await chromium.launch({ headless: true, args: ['--disable-gpu'] })
try {
const page = await (await browser.newContext({ viewport: { width: 1280, height: 900 } })).newPage()
const errors = []
page.on('pageerror', (e) => errors.push(e.message))
// ?webgl forces the WebGL2 backend: headless Chromium has no WebGPU adapter.
await page.goto(`${origin}/?webgl`)
await page.locator('canvas').first().waitFor({ timeout: 180_000 })
await page.waitForFunction(() => window.soundcraft && typeof window.soundcraft.request === 'function', null, { timeout: 180_000 })
const names = await page.evaluate(() => Object.keys(window.soundcraft).sort())
for (const f of ['request', 'execute', 'commands', 'docInspect', 'uiInspect', 'screenshot']) {
assert(names.includes(f), `window.soundcraft.${f} is installed (found: ${names.join(' ')})`)
}
// A call that rejects is reported, not thrown, so each check can look at the error.
const call = (fn, ...args) => page.evaluate(async ([fn, args]) => {
try { return { ok: true, value: await window.soundcraft[fn](...args) } }
catch (e) { return { ok: false, error: String((e && e.message) || e), isError: e instanceof Error } }
}, [fn, args])
const commands = await call('commands')
assert(commands.ok && Array.isArray(commands.value) && commands.value.length > 0, `commands() lists the commands: ${JSON.stringify(commands).slice(0, 200)}`)
assert(commands.value.some((c) => c.id === 'track.new'), 'commands() includes track.new')
const doc = await call('docInspect')
assert(doc.ok && typeof doc.value === 'object', `docInspect() resolves with an object: ${JSON.stringify(doc).slice(0, 200)}`)
const ui = await call('uiInspect')
assert(ui.ok && typeof ui.value === 'object', `uiInspect() resolves with an object: ${JSON.stringify(ui).slice(0, 200)}`)
// execute changes the session, and docInspect shows it.
const docBefore = await call('docInspect')
assert(docBefore.ok, `docInspect() resolves before execute: ${JSON.stringify(docBefore).slice(0, 200)}`)
const ran = await call('execute', 'track.new', {})
assert(ran.ok, `execute('track.new') resolves: ${JSON.stringify(ran).slice(0, 300)}`)
const docAfter = await call('docInspect')
assert(docAfter.ok, `docInspect() resolves after execute: ${JSON.stringify(docAfter).slice(0, 200)}`)
assert.notEqual(JSON.stringify(docBefore.value), JSON.stringify(docAfter.value), 'docInspect() changes after execute(track.new)')
// Failures reject with an Error that names what went wrong.
const unknownCommand = await call('execute', 'no.such.command', {})
assert(!unknownCommand.ok && unknownCommand.isError && unknownCommand.error.includes('no.such.command'), `execute of an unknown command rejects with an Error naming it: ${JSON.stringify(unknownCommand)}`)
const unknownMethod = await call('request', 'no.such.method', {})
assert(!unknownMethod.ok && unknownMethod.isError && unknownMethod.error.includes('no.such.method'), `an unknown method rejects with an Error naming it: ${JSON.stringify(unknownMethod)}`)
const shot = await call('screenshot')
assert(shot.ok, `screenshot() resolves: ${JSON.stringify(shot).slice(0, 200)}`)
const data = shot.value && shot.value.data
assert(typeof data === 'string' && data.length > 1000, 'screenshot() carries base64 data')
assert.equal(Buffer.from(data, 'base64').subarray(1, 4).toString(), 'PNG', 'the screenshot is a PNG')
// Several calls at once all settle.
const settled = await page.evaluate(() => Promise.all([1, 2, 3, 4, 5].map(() => window.soundcraft.uiInspect())).then((r) => r.length))
assert.equal(settled, 5, 'five concurrent calls all settle')
// Overload: far more calls than may wait at once. The ones over the limit are refused at once as busy, the
// ones within it are answered, and the page can call again afterwards (the slots came back).
const burst = await page.evaluate(() => Promise.all(
Array.from({ length: 300 }, () => window.soundcraft.uiInspect().then(() => 'ok', (e) => String((e && e.message) || e))),
))
const refused = burst.filter((r) => r !== 'ok')
console.log(`burst of ${burst.length}: ${burst.length - refused.length} answered, ${refused.length} refused (${refused[0]})`)
assert(refused.length > 0, 'calls beyond the limit are refused')
assert(refused.every((r) => /busy/i.test(r)), `every refusal says busy: ${refused.find((r) => !/busy/i.test(r))}`)
assert(burst.includes('ok'), 'the calls within the limit are answered')
assert.equal(burst.length, 300, 'every call settled, none was left waiting')
const afterBurst = await call('uiInspect')
assert(afterBurst.ok, `a call after the burst is accepted again: ${JSON.stringify(afterBurst).slice(0, 200)}`)
assert.deepEqual(errors, [], 'no uncaught page errors')
console.log('PASS window.soundcraft: all six functions, the failure paths and concurrent calls work against the real app')
} finally {
await browser.close()
server.close()
}
+1 -4
View File
@@ -67,10 +67,7 @@ fn main() {
}
if let Err(e) = res.compile() {
if std::env::var_os("SOUNDCRAFT_REQUIRE_WINRES").is_some() {
// The workspace denies `clippy::panic`, build scripts included: stop the build with
// the reason on stderr.
eprintln!("embedding Windows resources failed: {e}");
std::process::exit(1);
panic!("embedding Windows resources failed: {e}");
}
println!("cargo:warning=soundcraft.exe built without icon/version resources: {e}");
}
+2 -2
View File
@@ -22,8 +22,8 @@
//! callback must never do. Code that runs on the audio thread logs anyway (the cpal error callback,
//! the synth's full event queue, a hosted plugin's failed `process`, a CLAP plugin calling the
//! host's `log` from its audio thread, the panic hook). So the cpal callbacks mark their thread
//! (`soundcraft_playback::mark_audio_thread`; the mix engine renders every strip on the marked
//! thread itself), and a record from a marked thread is not written
//! (`soundcraft_playback::mark_audio_thread`; the mix engine carries the mark into the worker
//! threads that render strips for it), and a record from a marked thread is not written
//! there: the first one is kept in a fixed buffer (`try_lock`, no allocation, never waits) and the
//! rest are only counted (an atomic). Another thread writes them out: the UI thread every frame
//! ([`AppLogger::report_audio_thread`]) and any other thread before its own next record.
+1 -79
View File
@@ -149,12 +149,6 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
@@ -168,56 +162,11 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
@@ -303,8 +252,6 @@ fn validate_for(
Ok(confirmed)
}
const PROFILE_FOLDERS: [&str; 3] = ["Autosave", "Presets", "logs"];
#[cfg(test)]
mod tests {
use super::*;
@@ -481,31 +428,6 @@ mod tests {
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
+18 -51
View File
@@ -10,8 +10,7 @@
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - The result must lie inside one of the roots of its kind, compared by whole components
//! (`/work2` isn't inside `/work`), by the case the disk stores (links are resolved first, so a
//! differently cased spelling of a root still lands inside it).
//! (`/work2` isn't inside `/work`), without regard to case on Windows.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
@@ -267,12 +266,24 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
}
}
/// Is `path` (resolved) `root` or inside it, component by component? Both come from
/// `canonicalize`, which gives the name's case as the disk stores it, so equal means the same
/// folder; folding case would equate two folders on a case-sensitive Windows directory.
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
/// Windows, whose file systems ignore it)?
fn inside(path: &Path, root: &Path) -> bool {
let mut path = path.components();
root.components().all(|r| path.next().is_some_and(|p| p == r))
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
}
fn same_component(a: Component, b: Component) -> bool {
if a == b {
return true;
}
if !cfg!(windows) {
return false;
}
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
_ => false,
}
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
@@ -465,7 +476,7 @@ mod tests {
#[cfg(windows)]
#[test]
fn windows_resolves_case_and_refuses_devices() {
fn windows_ignores_case_and_refuses_devices() {
let (base, roots) = folders("case");
let upper = s(base.join("IN/a.scraft"));
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
@@ -477,50 +488,6 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// On a case-sensitive Windows directory `Work` and `work` are two folders: a root on one
/// doesn't grant the other, while a differently cased spelling of a name that is the same
/// folder (the ordinary, case-insensitive directories) is still accepted. Skipped, with a
/// note, where `fsutil` can't switch a directory to case-sensitive (it needs rights and the
/// NTFS volume's support).
#[cfg(windows)]
#[test]
fn windows_case_sensitive_directory_keeps_case_equal_folders_apart() {
let (base, _) = folders("case-sensitive");
let cs = base.join("cs");
std::fs::create_dir_all(&cs).unwrap();
let switched = std::process::Command::new("fsutil")
.args(["file", "setCaseSensitiveInfo"])
.arg(&cs)
.arg("enable")
.output()
.is_ok_and(|o| o.status.success());
if !switched {
eprintln!("skipped: cannot make {} case-sensitive", cs.display());
let _ = std::fs::remove_dir_all(base);
return;
}
for d in ["Work/sub", "work"] {
std::fs::create_dir_all(cs.join(d)).unwrap();
}
std::fs::write(cs.join("Work/a.scraft"), "x").unwrap();
std::fs::write(cs.join("work/secret.scraft"), "x").unwrap();
let roots = AutomationRoots::new(&[&cs.join("Work")], &[&cs.join("Work")]).unwrap().unwrap();
for access in [Access::Read, Access::Write] {
assert_eq!(roots.check(s(cs.join("Work/a.scraft")), access), Ok(()));
assert_eq!(roots.check(s(cs.join("Work/sub/New.scraft")), access), Ok(()));
// The other folder exists, and so does a name no folder has: both are outside.
for outside in ["work/secret.scraft", "work/new.scraft", "WORK/new.scraft"] {
let e = roots.check(s(cs.join(outside)), access).unwrap_err();
assert!(e.contains("outside the"), "{outside}: {e}");
}
}
// A root on the lower-case folder grants that one only.
let lower = AutomationRoots::new(&[&cs.join("work")], &[]).unwrap().unwrap();
assert_eq!(lower.check(s(cs.join("work/secret.scraft")), Access::Read), Ok(()));
assert!(lower.check(s(cs.join("Work/a.scraft")), Access::Read).is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn scopes_nest_and_stay_on_their_thread() {
let (base, roots) = folders("scopes");
-119
View File
@@ -1,119 +0,0 @@
//! Existing commands/history and saved session PCM for bounded send automation.
use craft_audio::AudioBuffer;
use serde_json::json;
use soundcraft_engine::{Engine, io};
use soundcraft_model::{AutoParam, ChannelFormat, Clip, FileFormat, Route, Session, TrackKind};
use soundcraft_time::Range;
use std::sync::Arc;
fn fixture() -> Engine {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Original"));
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 512]] };
let src = io::add_source(&mut s, "Original synthetic", buffer, None, FileFormat::Wav);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original", src, 0, 0, 512));
s.track_mut(t).unwrap().mixer.output = Route::None;
let mut e = Engine::new(s);
e.execute("mix.new_bus", &json!({"name":"Send","format":"stereo"})).unwrap();
e.execute("mix.send", &json!({"track":"Original","bus":"Send","slot":"A","level_db":0})).unwrap();
e.execute("track.new", &json!({"name":"Return","kind":"aux","format":"stereo"})).unwrap();
let bus = e.session().busses.iter().find(|b| b.name == "Send").unwrap().id;
let aux = e.session().tracks.iter().find(|t| t.kind == TrackKind::Aux).unwrap().id;
e.session_mut().track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
e.mark_clean();
e
}
fn render(e: &Engine) -> Vec<Vec<f32>> {
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 512), 37);
assert_eq!(out.len(), 2);
assert!(out.iter().all(|c| c.len() == 512));
out
}
fn point(e: &mut Engine, param: &str, at: i64, value: f32) {
e.execute("automation.set_point", &json!({"track":"Original","param":param,"at":at,"value":value})).unwrap();
}
#[test]
fn commands_undo_redo_reuse_renderer_and_preserve_render_state() {
let mut e = fixture();
let baseline = render(&e);
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_pan", 173, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let before = render(&e);
point(&mut e, "send_a_mute", 97, 1.0);
let after = render(&e);
assert_ne!(before, after);
assert_ne!(baseline, before);
let arc = e.session_arc();
let serialized = e.session().to_json().unwrap();
let revision = e.revision;
let history = e.undo_history();
let dirty = e.is_dirty();
let mut mix = soundcraft_mix::MixEngine::new(48_000.0, 512);
let mut out = vec![vec![0.0; 512]; 2];
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
mix.render(e.session(), 97, 13, &mut out);
assert!(Arc::ptr_eq(&arc, &e.session_arc()));
assert_eq!(serialized, e.session().to_json().unwrap());
assert_eq!(revision, e.revision);
assert_eq!(history, e.undo_history());
assert_eq!(dirty, e.is_dirty());
assert!(e.undo());
assert_eq!(render(&e), before);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, before);
assert!(e.redo());
assert_eq!(render(&e), after);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
e.execute("mix.automation_mode", &json!({"track":"Original","mode":"off"})).unwrap();
assert_eq!(render(&e), baseline);
}
#[test]
fn lane_commands_survive_folder_and_bundle_save_reopen_with_exact_pcm() {
let mut e = fixture();
e.execute("mix.send_level", &json!({"track":"Original","slot":"A","pan":0.5,"mute":true})).unwrap();
point(&mut e, "send_a_pan", 37, -1.0);
point(&mut e, "send_a_pan", 401, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
e.execute("automation.write_range", &json!({"track":"Original","param":"send_a_mute","start":97,"end":173,"value":1.0})).unwrap();
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let dir = std::env::temp_dir().join(format!("soundcraft-send-automation-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("Original/Send.scraft").to_string_lossy().into_owned();
io::save_session(&mut e, &path).unwrap();
let mut reopened = Engine::default();
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
assert_eq!(render(&reopened), expected);
let tr = reopened.session().tracks.iter().find(|t| t.name == "Original").unwrap();
assert_eq!(tr.lane(&AutoParam::SendPan(0)).unwrap().points.len(), 2);
assert!(!reopened.is_dirty());
assert!(!reopened.can_undo());
let (bundle, _) = io::session_bundle(e.session()).unwrap();
let mut bundled = Engine::default();
io::open_session_bytes(&mut bundled, "Send.scraftz", &bundle).unwrap();
assert_eq!(render(&bundled), expected);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn absent_enabled_field_keeps_legacy_reader_behavior() {
let mut e = fixture();
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let mut json = serde_json::to_value(e.session()).unwrap();
for track in json["tracks"].as_array_mut().unwrap() {
for lane in track["automation"].as_array_mut().unwrap() {
lane.as_object_mut().unwrap().remove("enabled");
}
}
let mut old: Session = serde_json::from_value(json).unwrap();
old.pool = e.session().pool.clone();
let tr = old.tracks.iter().find(|t| t.name == "Original").unwrap();
assert!(tr.automation.iter().all(|l| !l.enabled));
assert_eq!(soundcraft_mix::render_range(&old, Range::new(0, 512), 100), expected);
}
+8 -38
View File
@@ -70,7 +70,6 @@ mod midi;
mod offline;
mod pan;
mod routing;
mod send_automation;
mod strip;
mod threads;
@@ -363,7 +362,7 @@ impl MixEngine {
}
for b in &s.busses {
let n = b.format.channels().clamp(1, MAX_CHANNELS);
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new(), age: send_automation::SignalAge::Empty });
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new() });
bus.fmt = b.format;
if bus.buf.len() != n {
bus.buf = vec![vec![0.0; mb]; n];
@@ -390,7 +389,7 @@ impl MixEngine {
self.begin_block(s, pos, frames);
let blk = Block { pos, frames, any_solo: any_solo(s) };
let order = std::mem::take(&mut self.order);
// Phase 1: independent strips (audio, instrument, MIDI), in parallel except on the audio thread.
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
let mut work = std::mem::take(&mut self.work);
work.clear();
for &i in &order {
@@ -455,7 +454,6 @@ impl MixEngine {
}
self.ensure_synced(s);
for b in self.busses.values_mut() {
b.age = send_automation::SignalAge::Empty;
for c in b.buf.iter_mut() {
c.iter_mut().take(frames).for_each(|x| *x = 0.0);
}
@@ -510,11 +508,9 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(lmax_t.saturating_sub(st.latency), ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
st.align_pre.set(lmax_t.saturating_sub(st.latency), ch);
st.align_pre.process(&mut st.pre, frames);
st.send_pre_age = st.send_pre_age.delayed(st.align_pre.len);
}
let waits = match &t.mixer.output {
Route::Main => true,
@@ -550,7 +546,6 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
st.out_extra.set(0, ch);
self.route_strip(t, &mut st, pos, frames);
self.strips.insert(t.id, st);
@@ -648,41 +643,22 @@ impl MixEngine {
let law = self.pan_law;
for (i, snd) in t.mixer.sends.iter().enumerate() {
let Some(snd) = snd else { continue };
if strip.muted {
continue;
}
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let age = if snd.pre_fader { strip.send_pre_age } else { strip.send_post_age };
let clock = age.clock(pos);
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
let ordinary = !src_fmt.is_ambisonic() && !dst.fmt.is_ambisonic();
let mute = ordinary.then(|| send_automation::Reader::for_send(t, AutoParam::SendMute, i, clock.at(0))).flatten();
if mute.is_none() && snd.mute {
if snd.mute || strip.muted {
continue;
}
let lvl = send_level(t, i, snd.level_db, pos);
let gain = db_to_gain(lvl);
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
if gain <= 0.0 {
continue;
}
dst.age.include(age);
let pan = (ordinary && src.len() == 1 && dst.fmt == ChannelFormat::Stereo)
.then(|| send_automation::Reader::for_send(t, AutoParam::SendPan, i, clock.at(0)))
.flatten();
if let Some(pan) = pan {
send_automation::apply_mono_stereo(src, frames, &mut dst.buf, gain, law, clock, pan, mute);
continue;
}
// Mono sends use the send's own pan; stereo sends go straight to L/R.
let stereo = if src.len() == 1 { [snd.pan, 0.0] } else { [-1.0, 1.0] };
let surround = snd.surround.as_ref().or(if snd.follow_main_pan { t.mixer.surround.as_ref() } else { None });
let m = build_matrix(src_fmt, src.len(), dst.fmt, dst.buf.len(), &PanSpec { stereo, surround }, law);
if let Some(mute) = mute {
send_automation::apply_gated(src, frames, &mut dst.buf, &m, gain, clock, mute);
} else {
apply_matrix(src, frames, &mut dst.buf, &m, gain);
}
apply_matrix(src, frames, &mut dst.buf, &m, gain);
}
let src: &[Vec<f32>] = match &t.mixer.output {
Route::Main | Route::Bus(_) if strip.out_extra.len > 0 => {
@@ -701,10 +677,7 @@ impl MixEngine {
let (dst, dst_fmt) = match &t.mixer.output {
Route::Main => (&mut self.main, self.main_fmt),
Route::Bus(b) => match self.busses.get_mut(b) {
Some(d) => {
d.age.include(strip.send_post_age.delayed(strip.out_extra.len));
(&mut d.buf, d.fmt)
}
Some(d) => (&mut d.buf, d.fmt),
None => return,
},
_ => return,
@@ -738,6 +711,3 @@ mod click;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod send_age_tests;
+1 -1
View File
@@ -1,7 +1,7 @@
use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains};
/// Per-block routing gains: `m[src][dst]`.
pub(crate) type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
/// How a source is panned: the stereo pan pair (mono uses `[0]`) and the optional surround pan.
pub(crate) struct PanSpec<'a> {
-120
View File
@@ -1,120 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use craft_audio::AudioBuffer;
use soundcraft_dsp::Plugin;
use super::send_automation::SignalAge;
use super::strip::{Block, BusBuf, LiveInput, MAX_LATENCY, PluginSlot, Strip, process_strip};
use super::*;
#[test]
fn known_bus_ages_accumulate_and_mixed_ages_keep_the_legacy_clock() {
let mut bus = SignalAge::Empty;
assert_eq!(bus.input(), SignalAge::Known(0));
bus.include(SignalAge::Known(71));
bus.include(SignalAge::Known(71));
assert_eq!(bus, SignalAge::Known(71));
let aux_pre = bus.delayed(23);
let aux_post = aux_pre.delayed(48);
assert_eq!(aux_pre, SignalAge::Known(94));
assert_eq!(aux_post, SignalAge::Known(142));
assert_eq!(aux_pre.clock(300).at(0), 206);
assert_eq!(aux_post.clock(300).at(0), 158);
let nested = aux_post.delayed(71);
assert_eq!(nested, SignalAge::Known(213));
bus.include(SignalAge::Known(142));
assert_eq!(bus, SignalAge::Mixed);
assert_eq!(bus.delayed(71).clock(300).at(0), 300);
}
#[test]
fn age_overflow_preserves_audio_with_the_legacy_clock_fallback() {
let age = SignalAge::Known(u64::MAX).delayed(1);
assert_eq!(age, SignalAge::Mixed);
assert_eq!(age.clock(-7).at(3), -4);
let mut bus = SignalAge::Known(71);
bus.include(SignalAge::Empty);
assert_eq!(bus, SignalAge::Known(71));
}
#[test]
fn processed_insert_age_is_uncapped_while_pdc_stays_capped_and_overflow_falls_back() {
struct DeclaredDelay {
inner: Box<dyn Plugin>,
latency: usize,
}
impl Plugin for DeclaredDelay {
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
self.inner.info()
}
fn prepare(&mut self, rate: f32, block: usize, channels: usize) {
self.inner.prepare(rate, block, channels);
}
fn reset(&mut self) {
self.inner.reset();
}
fn set_param(&mut self, id: &str, value: f32) -> bool {
self.inner.set_param(id, value)
}
fn param(&self, id: &str) -> Option<f32> {
self.inner.param(id)
}
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
self.inner.process(io, frames);
}
fn latency(&self) -> usize {
self.latency
}
}
fn slot(latency: usize) -> PluginSlot {
let mut inner = soundcraft_dsp::create("gain").unwrap();
inner.prepare(48_000.0, 16, 1);
PluginSlot::test_instance("gain".into(), 1, Box::new(DeclaredDelay { inner, latency }))
}
let mut source = Session::default();
source.edit.delay_compensation = false;
let audio = source.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let source_id = soundcraft_model::SourceId(900);
source.pool.insert(source_id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 16]] })));
let clip = source.new_clip_id();
let track = source.track_mut(audio).unwrap();
track.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared-age reference", source_id, 0, 0, 16));
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
track.mixer.inserts[1] = Some(soundcraft_model::Insert::new("gain"));
let mut pre = soundcraft_model::SendSlot::new(Route::None);
pre.pre_fader = true;
track.mixer.sends[0] = Some(pre);
let mut strip = Strip::new();
strip.buf = vec![vec![0.0; 16]];
strip.scratch = vec![0.0; 16];
strip.plugins = vec![Some(slot(MAX_LATENCY + 5)), Some(slot(MAX_LATENCY + 9))];
let busses = HashMap::new();
let live = LiveInput { input: &[], midi: &[], ports: None, midi_lost: 0, monitor_only: false, recording: false };
let blk = Block { pos: 0, frames: 16, any_solo: false };
process_strip(&source, source.track(audio).unwrap(), &mut strip, &busses, &live, blk);
let declared_sum = 2 * MAX_LATENCY as u64 + 14;
assert_eq!(strip.latency, MAX_LATENCY, "the existing PDC cap remains unchanged");
assert_eq!(strip.send_pre_age, SignalAge::Known(declared_sum));
assert_eq!(strip.send_post_age, SignalAge::Known(declared_sum));
assert_eq!(strip.align.len, 0);
assert_eq!(strip.align_pre.len, 0);
assert_eq!(strip.pre, vec![vec![0.25; 16]]);
assert_eq!(strip.buf, strip.pre, "declared age metadata never changes the processed PCM");
let bus = source.add_bus("Overflowing known input", ChannelFormat::Mono);
let aux = source.add_track(TrackKind::Aux, ChannelFormat::Mono, None);
let track = source.track_mut(aux).unwrap();
track.mixer.input = Route::Bus(bus);
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
let busses = HashMap::from([(bus, BusBuf { fmt: ChannelFormat::Mono, buf: vec![vec![0.25; 16]], age: SignalAge::Known(u64::MAX) })]);
let mut aux_strip = Strip::new();
aux_strip.buf = vec![vec![0.0; 16]];
aux_strip.plugins = vec![Some(slot(1))];
process_strip(&source, source.track(aux).unwrap(), &mut aux_strip, &busses, &live, blk);
assert_eq!(aux_strip.latency, 1);
assert_eq!(aux_strip.send_pre_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age.clock(300).at(0), 300);
assert_eq!(aux_strip.buf, vec![vec![0.25; 16]], "overflow preserves the output instead of silencing it");
}
-267
View File
@@ -1,267 +0,0 @@
//! Local send playback: sample-exact mono-to-stereo pan and stepped ordinary-bus mute.
//! No document mutation, allocation, locks or persistent cursor survive a callback/seek.
use super::MAX_CHANNELS;
use super::pan::Matrix;
use soundcraft_dsp::pan::{PanLaw, gains};
use soundcraft_model::{AutoParam, AutomationPoint, Track};
use soundcraft_time::Samples;
/// Source-sample age metadata only; it never changes routing or audio delay compensation.
/// A mixed-age sum has no single source clock, so new send readers retain their legacy clock.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub(crate) enum SignalAge {
#[default]
Empty,
Known(u64),
Mixed,
}
impl SignalAge {
pub(crate) fn input(self) -> Self {
match self {
Self::Empty => Self::Known(0),
other => other,
}
}
pub(crate) fn delayed(self, frames: usize) -> Self {
match self {
Self::Known(age) => u64::try_from(frames).ok().and_then(|frames| age.checked_add(frames)).map_or(Self::Mixed, Self::Known),
other => other,
}
}
pub(crate) fn include(&mut self, contribution: Self) {
*self = match (*self, contribution) {
(Self::Empty, age) | (age, Self::Empty) => age,
(Self::Known(a), Self::Known(b)) if a == b => Self::Known(a),
_ => Self::Mixed,
};
}
pub(crate) fn clock(self, position: Samples) -> Clock {
let age = match self {
Self::Known(age) => age,
Self::Empty | Self::Mixed => 0,
};
Clock::new(position, age)
}
}
/// A forward cursor rebuilt at each callback's absolute position. Like the existing mixer
/// readers, this deliberately ignores lane.enabled; global suspension/migration is separate.
/// Nonfinite or decreasing-time lanes fall back to the static control for the whole callback.
/// Finite values clamp to the control range; duplicate times deterministically use the last knot.
pub(super) struct Reader<'a> {
points: &'a [AutomationPoint],
next: usize,
mute: bool,
}
impl<'a> Reader<'a> {
pub(super) fn for_send(t: &'a Track, param: fn(u8) -> AutoParam, slot: usize, pos: Samples) -> Option<Self> {
if !t.mixer.automation_mode.reads() {
return None;
}
let param = param(u8::try_from(slot).ok()?);
let lane = t.lane(&param)?;
let points = &lane.points;
if points.is_empty() || points.iter().any(|p| !p.value.is_finite()) || points.windows(2).any(|p| p[0].at > p[1].at) {
return None;
}
Some(Self { points, next: points.partition_point(|p| p.at <= pos), mute: matches!(param, AutoParam::SendMute(_)) })
}
pub(super) fn value(&mut self, pos: Samples) -> f32 {
while self.points.get(self.next).is_some_and(|p| p.at <= pos) {
self.next = self.next.saturating_add(1);
}
let Some(a) = self.points.get(self.next.saturating_sub(1)) else { return 0.0 };
let lo = if self.mute { 0.0 } else { -1.0 };
let av = a.value.clamp(lo, 1.0);
if self.next == 0 || self.mute {
return av;
}
let Some(b) = self.points.get(self.next) else { return av };
// Valid timestamps may span i64::MIN..MAX. Widen before subtraction, and interpolate
// bounded values in f64 so neither timestamp nor value arithmetic can overflow.
let width = i128::from(b.at) - i128::from(a.at);
if width <= 0 {
return av;
}
let fraction = ((i128::from(pos) - i128::from(a.at)) as f64 / width as f64).clamp(0.0, 1.0);
(f64::from(av) + (f64::from(b.value.clamp(lo, 1.0)) - f64::from(av)) * fraction) as f32
}
}
/// Timeline position represented by a delayed source tap. Widen the entire expression before
/// clamping, so advancing a frame near MIN/MAX does not lose an earlier delay subtraction.
#[derive(Clone, Copy)]
pub(super) struct Clock {
position: Samples,
age: u64,
}
impl Clock {
pub(super) fn new(position: Samples, age: u64) -> Self {
Self { position, age }
}
pub(super) fn at(self, frame: usize) -> Samples {
let frame = i128::try_from(frame).unwrap_or(i128::MAX);
let at = i128::from(self.position).saturating_add(frame).saturating_sub(i128::from(self.age));
at.clamp(i128::from(Samples::MIN), i128::from(Samples::MAX)) as Samples
}
}
impl From<Samples> for Clock {
fn from(position: Samples) -> Self {
Self::new(position, 0)
}
}
#[cfg(test)]
fn frame_position(pos: Samples, frame: usize) -> Samples {
Clock::from(pos).at(frame)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn apply_mono_stereo(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
gain: f32,
law: PanLaw,
pos: impl Into<Clock>,
mut pan: Reader<'_>,
mut mute: Option<Reader<'_>>,
) {
let clock = pos.into();
let Some(src) = src.first() else { return };
for (i, sample) in src.iter().enumerate().take(frames) {
let at = clock.at(i);
if mute.as_mut().is_some_and(|m| m.value(at) >= 0.5) {
continue;
}
let (left, right) = gains(pan.value(at), law);
for (channel, factor) in [(0, left), (1, right)] {
if let Some(out) = dst.get_mut(channel).and_then(|c| c.get_mut(i)) {
*out += sample * gain * factor;
}
}
}
}
/// Keep the existing static routing matrix (including mono folds and surround positions),
/// applying only the exact mute gate. Sparse taps are prepared on the stack once per block.
pub(super) fn apply_gated(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
matrix: &Matrix,
gain: f32,
pos: impl Into<Clock>,
mut mute: Reader<'_>,
) {
let clock = pos.into();
let mut taps = [[(0usize, 0.0f32); MAX_CHANNELS]; MAX_CHANNELS];
let mut counts = [0usize; MAX_CHANNELS];
for (d, (taps, count)) in taps.iter_mut().zip(counts.iter_mut()).enumerate().take(dst.len()) {
for (s, row) in matrix.iter().enumerate().take(src.len().min(MAX_CHANNELS)) {
let g = row.get(d).copied().unwrap_or(0.0);
if g != 0.0
&& let Some(tap) = taps.get_mut(*count)
{
*tap = (s, g);
*count += 1;
}
}
}
for i in 0..frames {
if mute.value(clock.at(i)) >= 0.5 {
continue;
}
for (d, channel) in dst.iter_mut().enumerate().take(MAX_CHANNELS) {
let Some(out) = channel.get_mut(i) else { continue };
let mut acc = 0.0;
for &(s, g) in taps.get(d).and_then(|t| counts.get(d).and_then(|n| t.get(..*n))).unwrap_or(&[]) {
acc += src.get(s).and_then(|c| c.get(i)).copied().unwrap_or(0.0) * gain * g;
}
*out += acc;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use soundcraft_model::{AutomationLane, ChannelFormat, Session, TrackKind};
fn track(points: &[(i64, f32)], mute: bool) -> Track {
let mut s = Session::default();
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let t = s.track_mut(id).unwrap();
let mut lane = AutomationLane::new(if mute { AutoParam::SendMute(0) } else { AutoParam::SendPan(0) });
lane.points = points.iter().map(|&(at, value)| AutomationPoint { at, value }).collect();
t.automation.push(lane);
t.clone()
}
#[test]
fn wide_interpolation_does_not_overflow() {
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MIN).unwrap();
assert_eq!(r.value(i64::MIN), -1.0);
assert!(r.value(0).abs() < 1e-7);
assert_eq!(r.value(i64::MAX), 1.0);
assert_eq!(frame_position(i64::MAX - 1, 3), i64::MAX);
}
#[test]
fn endpoints_duplicates_and_finite_extremes_are_deterministic() {
let t = track(&[(3, -f32::MAX), (3, 0.25), (7, f32::MAX)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, 0).unwrap();
assert_eq!(r.value(0), -1.0);
assert_eq!(r.value(3), 0.25);
assert_eq!(r.value(5), 0.625);
assert_eq!(r.value(9), 1.0);
let t = track(&[(i64::MIN, -f32::MAX), (i64::MAX, f32::MAX)], true);
let mut r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MIN).unwrap();
assert_eq!(r.value(0), 0.0);
assert_eq!(r.value(i64::MAX), 1.0);
}
#[test]
fn short_buffers_and_saturating_positions_do_not_panic() {
let t = track(&[(i64::MIN, 0.0), (i64::MAX, 1.0)], true);
let r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MAX - 1).unwrap();
let mut dst = vec![vec![0.0; 1]];
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
apply_gated(&[vec![0.25; 2]], 4, &mut dst, &matrix, 1.0, i64::MAX - 1, r);
assert_eq!(dst, vec![vec![0.25]]);
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MAX - 1).unwrap();
apply_mono_stereo(&[vec![0.25; 2]], 4, &mut [], 1.0, PanLaw::Minus3, i64::MAX - 1, r, None);
}
#[test]
fn source_clock_clamps_after_the_composite_delay_expression() {
assert_eq!(Clock::new(i64::MIN + 5, 10).at(8), i64::MIN + 3);
assert_eq!(Clock::new(i64::MAX, 10).at(3), i64::MAX - 7);
assert_eq!(Clock::new(i64::MAX, 10).at(20), i64::MAX);
assert_eq!(Clock::new(-5, 10).at(3), -12);
assert_eq!(Clock::new(i64::MAX, u64::MAX).at(0), i64::MIN);
assert_eq!(Clock::new(i64::MIN, u64::MAX).at(0), i64::MIN);
}
#[test]
fn delayed_reader_seed_and_gate_advancement_use_the_same_clock() {
let t = track(&[(0, 0.0), (30, 1.0), (40, 0.0)], true);
let clock = Clock::new(45, 25);
let reader = Reader::for_send(&t, AutoParam::SendMute, 0, clock.at(0)).unwrap();
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
let mut destination = vec![vec![0.0; 25]];
apply_gated(&[vec![0.25; 25]], 25, &mut destination, &matrix, 1.0, clock, reader);
assert_eq!(destination[0], (0..25).map(|frame| if (10..20).contains(&frame) { 0.0 } else { 0.25 }).collect::<Vec<_>>());
}
}
+6 -33
View File
@@ -5,7 +5,6 @@ use super::live_midi::{LiveMidi, LiveNotes, MidiPorts, midi_thru};
use super::midi::{chase_controllers, schedule_notes};
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
use super::routing::solo_muted;
use super::send_automation::SignalAge;
use super::{
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
db_to_gain,
@@ -17,8 +16,6 @@ use std::sync::Arc;
pub(crate) struct BusBuf {
pub(crate) fmt: ChannelFormat,
pub(crate) buf: Vec<Vec<f32>>,
/// Age shared by the routed contributions in this block, or Mixed when they differ.
pub(crate) age: SignalAge,
}
pub(crate) struct PluginSlot {
@@ -38,13 +35,6 @@ pub(crate) struct PluginSlot {
pub(crate) retried: bool,
}
#[cfg(test)]
impl PluginSlot {
pub(crate) fn test_instance(id: String, ch: usize, plugin: Box<dyn Plugin>) -> Self {
Self { id, ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }
}
}
pub(crate) struct Strip {
pub(crate) buf: Vec<Vec<f32>>,
/// Pre-fader copy for pre-fader sends.
@@ -69,9 +59,6 @@ pub(crate) struct Strip {
clipbuf: Vec<Vec<f32>>,
/// Total latency of the active inserts (samples).
pub(crate) latency: usize,
/// Sample ages of the selected send taps after their actual applied alignment.
pub(crate) send_pre_age: SignalAge,
pub(crate) send_post_age: SignalAge,
/// Delay compensation: align this strip with the slowest one (post- and pre-fader paths),
/// plus extra delay for direct-to-main outputs so they line up with aux returns.
pub(crate) align: DelayLine,
@@ -170,8 +157,6 @@ impl Strip {
clip_fx: HashMap::new(),
clipbuf: Vec::new(),
latency: 0,
send_pre_age: SignalAge::Known(0),
send_post_age: SignalAge::Known(0),
align: DelayLine::default(),
align_pre: DelayLine::default(),
out_extra: DelayLine::default(),
@@ -304,11 +289,10 @@ fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) {
}
/// An aux or folder reads the bus its input is routed from.
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) -> SignalAge {
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) {
if let Route::Bus(b) = &t.mixer.input
&& let Some(src) = busses.get(b)
{
let input_age = src.age.input();
let (ns, nd) = (src.buf.len(), strip.buf.len());
let dst_fmt = strip_format(t, nd);
let m = if src.fmt == dst_fmt && ns == nd {
@@ -324,9 +308,7 @@ fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, f
build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3)
};
apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0);
return input_age;
}
SignalAge::Known(0)
}
/// Render the track's instrument into the strip.
@@ -411,12 +393,10 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
}
/// Run the active inserts in order; records their latency and the first gain reduction.
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport, input_age: SignalAge) {
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) {
let Block { pos, frames, .. } = blk;
let mut gr = 0.0f32;
let inst_latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
let mut latency = inst_latency;
let mut send_age = input_age.delayed(inst_latency);
let mut latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
for (i, ins) in t.mixer.inserts.iter().enumerate() {
let (Some(ins), Some(Some(slot))) = (ins, strip.plugins.get_mut(i)) else { continue };
if !ins.active || ins.bypass || slot.failed {
@@ -429,17 +409,13 @@ fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport,
strip.failures.record(i);
continue;
}
let declared_latency = slot.plugin.latency();
latency = latency.saturating_add(declared_latency);
send_age = send_age.delayed(declared_latency);
latency = latency.saturating_add(slot.plugin.latency());
if gr == 0.0 {
gr = slot.plugin.gain_reduction_db();
}
}
strip.gr = gr;
strip.latency = latency.min(MAX_LATENCY);
strip.send_pre_age = send_age;
strip.send_post_age = send_age;
}
/// Fader gain (volume, trim and VCA automation), read at every sample of the block.
@@ -490,7 +466,6 @@ fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) {
pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, live: &LiveInput<'_>, blk: Block) {
let Block { pos, frames, any_solo } = blk;
zero_buf(&mut strip.buf, frames);
let mut input_age = SignalAge::Known(0);
let transport = transport_at(s, pos, !live.monitor_only, live.recording);
match t.kind {
TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => {
@@ -501,9 +476,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
// doing so, to release its notes).
TrackKind::Instrument | TrackKind::Midi if live.monitor_only && !midi_thru(t) && !strip.live.touched() => {}
TrackKind::Audio => render_audio_clips(s, t, strip, blk),
TrackKind::Aux | TrackKind::Folder => {
input_age = read_aux_bus(t, strip, busses, frames);
}
TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames),
TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, live, blk, &transport),
_ => {}
}
@@ -513,7 +486,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
c.iter_mut().take(frames).for_each(|x| *x *= trim);
}
}
run_inserts(t, strip, blk, &transport, input_age);
run_inserts(t, strip, blk, &transport);
let soloed_out = solo_muted(s, t, any_solo);
strip.muted = t.mixer.mute || soloed_out;
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
+5 -8
View File
@@ -1,15 +1,16 @@
use super::AUDIO_THREAD;
/// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks
/// do, every call: one thread-local store). [`MixEngine::render`] renders every strip on that
/// thread itself instead of handing strips to worker threads. Code that might run there asks
/// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads
/// count as the audio thread while they render for it. Code that might run there asks
/// [`on_audio_thread`] before doing anything that blocks; the desktop app's logger does, so a
/// `log::` record from the audio thread never takes a lock or touches a file.
pub fn mark_audio_thread() {
AUDIO_THREAD.set(true);
}
/// True on the thread [`mark_audio_thread`] marked. Lock-free and allocation-free.
/// True on the thread [`mark_audio_thread`] marked, and on a worker while it renders strips for
/// it. Lock-free and allocation-free.
pub fn on_audio_thread() -> bool {
AUDIO_THREAD.get()
}
@@ -28,11 +29,7 @@ fn as_audio_thread(audio: bool, f: impl FnOnce()) {
f();
}
/// Process strips: in parallel on native targets when there are enough of them, except on the
/// realtime audio thread. There they render one after the other on the thread itself: the pool's
/// workers run at normal priority, so under load the callback would wait for starved workers
/// (priority inversion) and miss its deadline, and waiting on them blocks, which the callback
/// never may. Offline renders (bounces) keep the parallelism.
/// Process strips, in parallel on native targets when there are enough of them.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn run_strips<T: Send>(work: &mut [T], f: impl Fn(&mut T) + Sync + Send) {
use rayon::prelude::*;
-435
View File
@@ -1,435 +0,0 @@
//! Independent PCM references for the bounded send consumers, with no hosted plugins/devices.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus, render_range};
use soundcraft_model::{
AutoParam, AutomationLane, AutomationMode, AutomationPoint, BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId,
TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
const LEN: usize = 640;
const PAN: [(i64, f32); 3] = [(37, -1.0), (173, 0.75), (401, 1.0)];
const MUTE: [(i64, f32); 5] = [(37, 0.0), (97, 1.0), (173, 0.0), (257, 1.0), (349, 0.0)];
fn fixture(format: ChannelFormat) -> (Session, TrackId, BusId) {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, format, None);
let src = SourceId(900);
let channels = (0..format.channels()).map(|ch| (0..LEN).map(|n| signal(ch, n)).collect()).collect();
s.pool.insert(src, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels })));
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original synthetic", src, 0, 0, LEN as i64));
let bus = s.add_bus("Send", ChannelFormat::Stereo);
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
let tr = s.track_mut(t).unwrap();
tr.mixer.output = Route::None;
let mut send = SendSlot::new(Route::Bus(bus));
send.level_db = 0.0;
tr.mixer.sends[0] = Some(send);
(s, t, bus)
}
fn signal(ch: usize, n: usize) -> f32 {
if n % 17 < 9 { 0.25 + ch as f32 / 100.0 } else { -0.125 - ch as f32 / 200.0 }
}
fn lane(s: &mut Session, t: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
s.track_mut(t).unwrap().automation.push(lane);
}
fn automated() -> (Session, TrackId, BusId) {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
(s, t, bus)
}
// The expectation never calls AutomationLane::value_at, pan::gains or any mixer helper.
fn expected_pan(at: i64) -> f64 {
if at <= PAN[0].0 {
return f64::from(PAN[0].1);
}
for pair in PAN.windows(2) {
if at < pair[1].0 {
let f = (at - pair[0].0) as f64 / (pair[1].0 - pair[0].0) as f64;
return f64::from(pair[0].1) + f64::from(pair[1].1 - pair[0].1) * f;
}
}
f64::from(PAN[2].1)
}
fn muted(at: i64) -> bool {
MUTE.iter().rev().find(|p| p.0 <= at).unwrap_or(&MUTE[0]).1 >= 0.5
}
fn pan_factors(p: f64, law: PanLaw) -> [f64; 2] {
if law == PanLaw::Zero {
return [(1.0 - p).min(1.0), (1.0 + p).min(1.0)];
}
let depth = match law {
PanLaw::Minus3 => -3.0,
PanLaw::Minus4_5 => -4.5,
PanLaw::Minus6 => -6.0,
PanLaw::Zero => 0.0,
};
let angle = (p + 1.0) * std::f64::consts::PI / 4.0;
[angle.cos().max(0.0).powf(depth / -3.0103), angle.sin().max(0.0).powf(depth / -3.0103)]
}
fn assert_shape(out: &[Vec<f32>], channels: usize, frames: usize) {
assert_eq!(out.len(), channels);
for channel in out {
assert_eq!(channel.len(), frames);
}
}
fn check(out: &[Vec<f32>], start: i64, frames: usize, law: PanLaw, scale: f64) {
assert_shape(out, 2, frames);
for (ch, values) in out.iter().enumerate() {
for (n, &actual) in values.iter().enumerate() {
let at = start + n as i64;
let reference = if muted(at) { 0.0 } else { f64::from(signal(0, at as usize)) * scale * pan_factors(expected_pan(at), law)[ch] };
assert!((f64::from(actual) - reference).abs() < 2e-7, "channel {ch}, at {at}: {actual} vs {reference}");
}
}
}
fn chunks(eng: &mut MixEngine, s: &Session, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut out = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut k = 0;
while offset < length {
let n = sizes[k % sizes.len()].min(length - offset);
let mut block = vec![vec![0.0; n]; 2];
eng.render(s, start + offset as i64, n, &mut block);
for (out, block) in out.iter_mut().zip(block) {
out.extend(block);
}
offset += n;
k += 1;
}
out
}
#[test]
fn pan_and_mute_match_independent_pcm_across_chunks() {
let (s, _, bus) = automated();
for block in [1, 37, 64, 100, 512, 1024] {
let mut e = MixEngine::new(48_000.0, block.max(16));
let out = chunks(&mut e, &s, 0, LEN, &[block]);
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
let mut e = MixEngine::new(48_000.0, 1024);
check(&chunks(&mut e, &s, 0, LEN, &[1, 37, 64, 3, 100, 19]), 0, LEN, PanLaw::Minus3, 1.0);
check(&render_bus(&s, bus, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn all_pan_laws_match_numeric_reference_and_static_calibration() {
let (s, _, _) = automated();
for law in [PanLaw::Minus3, PanLaw::Minus4_5, PanLaw::Minus6, PanLaw::Zero] {
let mut e = MixEngine::new(48_000.0, 1024);
e.pan_law = law;
check(&chunks(&mut e, &s, 0, LEN, &[100]), 0, LEN, law, 1.0);
for at in [0, 77, 173, 349, 401] {
let (mut reference, t, _) = fixture(ChannelFormat::Mono);
reference.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pan = expected_pan(at) as f32;
let mut static_engine = MixEngine::new(48_000.0, 16);
static_engine.pan_law = law;
let static_pcm = chunks(&mut static_engine, &reference, at, 1, &[1]);
let automated_pcm = chunks(&mut e, &s, at, 1, &[1]);
assert_shape(&automated_pcm, 2, 1);
assert_shape(&static_pcm, 2, 1);
assert_eq!(automated_pcm, static_pcm);
}
}
}
#[test]
fn seeking_used_engine_has_no_cursor_history() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
let _ = chunks(&mut e, &s, 0, 520, &[100]);
for at in [31, 77, 97, 98, 173, 256, 257, 301] {
let out = chunks(&mut e, &s, at, 31, &[17, 1, 13]);
check(&out, at, 31, PanLaw::Minus3, 1.0);
let mut fresh = MixEngine::new(48_000.0, 1024);
assert_eq!(out, chunks(&mut fresh, &s, at, 31, &[17, 1, 13]));
}
}
#[test]
fn loop_wrap_and_tiny_final_chunks_use_absolute_knots() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
// Same loop splitting as playback: do not render past the loop end before wrapping.
for _ in 0..3 {
check(&chunks(&mut e, &s, 37, 264, &[100, 63]), 37, 264, PanLaw::Minus3, 1.0);
}
for _ in 0..2 {
check(&chunks(&mut e, &s, 97, 76, &[37]), 97, 76, PanLaw::Minus3, 1.0);
}
}
#[test]
fn modes_and_lane_enabled_preserve_existing_reader_policy() {
for mode in AutomationMode::ALL {
let (mut s, t, _) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.automation_mode = mode;
tr.mixer.sends[0].as_mut().unwrap().mute = true;
for lane in &mut tr.automation {
lane.enabled = false;
}
let out = render_range(&s, Range::new(0, LEN as i64), 37);
assert_shape(&out, 2, LEN);
if mode == AutomationMode::Off {
assert!(out.iter().flatten().all(|v| *v == 0.0));
} else {
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
}
}
#[test]
fn missing_and_empty_lanes_keep_static_pan_and_mute() {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendPan(0), &[]);
lane(&mut s, t, AutoParam::SendMute(0), &[]);
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().mute = true;
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
#[test]
fn static_matrix_mute_steps_and_threshold_match_reference() {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendMute(0), &[(0, 0.49), (97, 0.5), (173, 0.0)]);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, 2, LEN);
assert_shape(&reference, 2, LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if (97..173).contains(&i) { 0.0 } else { r });
}
}
}
#[test]
fn mute_preserves_routing_for_mono_surround_and_sixteen_channels() {
for fmt in [ChannelFormat::Mono, ChannelFormat::Stereo, ChannelFormat::Surround51, ChannelFormat::Atmos714, ChannelFormat::Atmos916] {
let (mut s, t, bus) = fixture(fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, fmt.channels(), LEN);
assert_shape(&reference, fmt.channels(), LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if muted(i as i64) { 0.0 } else { r });
}
}
}
}
#[test]
fn wider_source_and_destination_send_pan_keep_static_routing() {
for (src_fmt, dst_fmt) in [
(ChannelFormat::Stereo, ChannelFormat::Stereo),
(ChannelFormat::Mono, ChannelFormat::Surround51),
(ChannelFormat::Surround51, ChannelFormat::Stereo),
] {
let (mut s, t, bus) = fixture(src_fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = dst_fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
assert_shape(&reference, dst_fmt.channels(), LEN);
let actual = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert_shape(&actual, dst_fmt.channels(), LEN);
assert_eq!(actual, reference);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
}
}
#[test]
fn pre_post_fader_send_level_and_direct_output_are_preserved() {
for pre in [false, true] {
let (mut s, t, bus) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let snd = tr.mixer.sends[0].as_mut().unwrap();
snd.pre_fader = pre;
snd.level_db = -3.0;
let factor = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
check(&render_range(&s, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, factor);
// Keep the direct path isolated from the Aux while comparing source-main PCM.
let aux = s.tracks.iter().find(|tr| tr.kind == TrackKind::Aux).unwrap().id;
s.track_mut(aux).unwrap().inactive = true;
s.track_mut(t).unwrap().mixer.output = Route::Main;
let direct = render_range(&s, Range::new(0, LEN as i64), 37);
s.track_mut(t).unwrap().automation.clear();
s.track_mut(t).unwrap().mixer.sends[0] = None;
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 37), direct);
assert_eq!(s.bus(bus).unwrap().format, ChannelFormat::Stereo);
}
}
#[test]
fn track_solo_and_vca_suppression_cannot_be_unmuted_by_send_lane() {
for suppression in [0, 1, 2] {
let (mut s, t, _) = automated();
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pre_fader = true;
match suppression {
0 => s.track_mut(t).unwrap().mixer.mute = true,
1 => {
let other = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
s.track_mut(other).unwrap().mixer.solo = true;
}
_ => {
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, None);
s.track_mut(vca).unwrap().mixer.mute = true;
s.track_mut(t).unwrap().mixer.vca = Some(vca.0);
}
}
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
}
#[test]
fn slots_a_and_j_and_absent_slots_do_not_drive_each_other() {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let other = s.add_bus("J", ChannelFormat::Stereo);
let mut send = SendSlot::new(Route::Bus(other));
send.level_db = 0.0;
s.track_mut(t).unwrap().mixer.sends[9] = Some(send);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(9), &PAN);
lane(&mut s, t, AutoParam::SendMute(9), &MUTE);
lane(&mut s, t, AutoParam::SendMute(8), &[(0, 1.0)]);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
check(&render_bus(&s, other, Range::new(0, LEN as i64), 100), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn malformed_lanes_fall_back_without_changing_document() {
for points in [
vec![AutomationPoint { at: 3, value: -1.0 }, AutomationPoint { at: 1, value: 1.0 }],
vec![AutomationPoint { at: 0, value: f32::NAN }],
vec![AutomationPoint { at: 0, value: f32::INFINITY }],
] {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut lane = AutomationLane::new(param);
lane.points = points.clone();
s.track_mut(t).unwrap().automation.push(lane);
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
#[test]
fn stereo_sends_keep_legacy_left_right_routing_for_every_static_pan() {
for static_pan in [-1.0, -0.75, 0.0, 0.75, 1.0, f32::NAN, f32::INFINITY] {
for state in ["absent", "empty", "off", "malformed", "active"] {
for pre in [false, true] {
for gated in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = static_pan;
send.pre_fader = pre;
send.level_db = -3.0;
match state {
"absent" => {}
"empty" => lane(&mut s, t, AutoParam::SendPan(0), &[]),
"off" => {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
}
"malformed" => {
let mut pan = AutomationLane::new(AutoParam::SendPan(0));
pan.points = vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: -1.0 }];
s.track_mut(t).unwrap().automation.push(pan);
}
"active" => lane(&mut s, t, AutoParam::SendPan(0), &PAN),
_ => unreachable!(),
}
if gated {
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
}
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
// Existing stereo sends route channels directly to L/R. This reference
// does not call either routing matrices or a pan helper.
let expected = if gated && state != "off" && muted(n as i64) { 0.0 } else { f64::from(signal(ch, n)) * scale };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} gated={gated} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
assert_eq!(s.track(t).unwrap().mixer.sends[0].as_ref().unwrap().pan.to_bits(), static_pan.to_bits());
}
}
}
}
}
#[test]
fn inactive_mono_send_lanes_match_independent_static_controls() {
for state in ["absent", "empty", "off", "unordered", "nan", "infinite"] {
for pre in [false, true] {
for static_mute in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = -0.625;
send.mute = static_mute;
send.pre_fader = pre;
send.level_db = -3.0;
if state == "off" {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
} else if state != "absent" {
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut control = AutomationLane::new(param);
control.points = match state {
"empty" => vec![],
"unordered" => vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: 0.0 }],
"nan" => vec![AutomationPoint { at: 0, value: f32::NAN }],
"infinite" => vec![AutomationPoint { at: 0, value: f32::INFINITY }],
_ => unreachable!(),
};
s.track_mut(t).unwrap().automation.push(control);
}
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
let factors = pan_factors(-0.625, PanLaw::Minus3);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
let expected = if static_mute { 0.0 } else { f64::from(signal(0, n)) * scale * factors[ch] };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} muted={static_mute} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
}
}
-322
View File
@@ -1,322 +0,0 @@
//! Send automation follows the delayed audio at its tap, without changing existing PDC routing.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus};
use soundcraft_model::{
AutoParam, AutomationLane, BusId, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
// The built-in Maximizer uses 1.5 ms of lookahead: 72 samples at 48 kHz, with a declared
// and physical delay of 72 - 1 = 71. Its untouched threshold 0 dB gives unity drive;
// every synthetic level stays below the default -0.3 dB ceiling, so there is no limiting.
// Expected timelines use these declared values, not mixer latency fields or the clock helper.
const LOOKAHEAD: usize = 71;
const SOURCE_FRAMES: usize = 2048;
const MUTE_AT: i64 = 300;
const AMPLITUDE: f32 = 0.25;
struct Graph {
session: Session,
capture: BusId,
receiver: TrackId,
clip_start: i64,
pan_start: i64,
pan_end: i64,
}
fn maximizers(session: &mut Session, track: TrackId, count: usize) {
for slot in session.track_mut(track).unwrap().mixer.inserts.iter_mut().take(count) {
*slot = Some(Insert::new("maximizer"));
}
}
fn source(session: &mut Session, insert_count: usize, clip_start: i64) -> TrackId {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Declared DC"));
let id = SourceId(901);
session.pool.insert(id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![AMPLITUDE; SOURCE_FRAMES]] })));
let clip = session.new_clip_id();
let t = session.track_mut(track).unwrap();
t.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared DC", id, 0, clip_start, SOURCE_FRAMES as i64));
t.mixer.pan = vec![0.0];
t.mixer.output = Route::None;
maximizers(session, track, insert_count);
track
}
fn silent_audio(session: &mut Session, insert_count: usize) {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Unrelated silent lookahead"));
session.track_mut(track).unwrap().mixer.output = Route::None;
maximizers(session, track, insert_count);
}
fn aux(session: &mut Session, input: BusId, format: ChannelFormat, insert_count: usize) -> TrackId {
let track = session.add_track(TrackKind::Aux, format, None);
let t = session.track_mut(track).unwrap();
t.mixer.input = Route::Bus(input);
t.mixer.output = Route::None;
t.mixer.pan = if format == ChannelFormat::Mono { vec![0.0] } else { vec![-1.0, 1.0] };
maximizers(session, track, insert_count);
track
}
fn silent_aux(session: &mut Session, insert_count: usize) {
let input = session.add_bus("Unrelated empty input", ChannelFormat::Mono);
aux(session, input, ChannelFormat::Mono, insert_count);
}
fn return_to_main(session: &mut Session, input: BusId) -> TrackId {
let track = aux(session, input, ChannelFormat::Stereo, 0);
session.track_mut(track).unwrap().mixer.output = Route::Main;
track
}
fn automation(session: &mut Session, track: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
session.track_mut(track).unwrap().automation.push(lane);
}
fn send(session: &mut Session, sender: TrackId, capture: BusId, pre: bool, pan_start: i64, pan_end: i64, automated_pan: bool) {
let mut send = SendSlot::new(Route::Bus(capture));
send.level_db = 0.0;
send.pre_fader = pre;
send.pan = -1.0;
session.track_mut(sender).unwrap().mixer.sends[0] = Some(send);
automation(session, sender, AutoParam::SendMute(0), &[(-512, 0.0), (MUTE_AT, 1.0)]);
if automated_pan {
automation(session, sender, AutoParam::SendPan(0), &[(pan_start, -1.0), (pan_end, 1.0)]);
}
}
fn ordinary(pre: bool, own_inserts: usize, silent_inserts: usize, pdc: bool, clip_start: i64, pan_start: i64, pan_end: i64) -> Graph {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let sender = source(&mut session, own_inserts, clip_start);
if silent_inserts > 0 {
silent_audio(&mut session, silent_inserts);
}
let capture = session.add_bus("Automation capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, pan_start, pan_end, true);
let receiver = return_to_main(&mut session, capture);
Graph { session, capture, receiver, clip_start, pan_start, pan_end }
}
fn make_mix() -> MixEngine {
let mut mix = MixEngine::new(48_000.0, 1024);
mix.pan_law = PanLaw::Zero;
mix
}
fn capture_pcm(mix: &mut MixEngine, graph: &Graph, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut main = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut block = 0;
while offset < length {
let n = sizes[block % sizes.len()].min(length - offset);
let mut main_block = vec![vec![0.0; n]; 2];
mix.render(&graph.session, start + offset as i64, n, &mut main_block);
for (output, samples) in main.iter_mut().zip(main_block) {
assert_eq!(samples.len(), n);
output.extend(samples);
}
offset += n;
block += 1;
}
main
}
fn numeric_pan(at: i64, first: i64, last: i64) -> [f32; 2] {
let pan = if at <= first {
-1.0
} else if at >= last {
1.0
} else {
(-1.0 + 2.0 * (at - first) as f64 / (last - first) as f64) as f32
};
// Independent declared zero-depth pan law; no routing or automation helper is called.
[(1.0 - pan).min(1.0), (1.0 + pan).min(1.0)]
}
fn check_known(output: &[Vec<f32>], graph: &Graph, start: i64, delay: usize, length: usize) {
assert_eq!(output.len(), 2);
for (channel, samples) in output.iter().enumerate() {
assert_eq!(samples.len(), length);
for (offset, &sample) in samples.iter().enumerate() {
let source_time = start + offset as i64 - delay as i64;
let audible =
offset >= delay && source_time >= graph.clip_start && source_time < graph.clip_start + SOURCE_FRAMES as i64 && source_time < MUTE_AT;
let expected = if audible { AMPLITUDE * numeric_pan(source_time, graph.pan_start, graph.pan_end)[channel] } else { 0.0 };
assert!(sample.is_finite());
assert!(
(sample - expected).abs() < 2e-7,
"channel {channel}, emit {}, source {source_time}, delay {delay}: {sample} != {expected}",
start + offset as i64
);
}
}
assert!(output.iter().flatten().any(|sample| sample.abs() > 0.02), "declared capture must be audible");
}
#[test]
fn unrelated_silent_lookahead_keeps_audio_pre_post_pan_and_last_source_sample_299() {
for pre in [false, true] {
let graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 800, &[1, 7, 37, 100, 3, 64]);
assert_eq!(mix.latency, LOOKAHEAD, "the unrelated real Maximizer actually contributes latency");
check_known(&output, &graph, 0, LOOKAHEAD, 800);
let last = output[0].iter().rposition(|sample| sample.abs() > 1e-6).unwrap();
assert_eq!(last, MUTE_AT as usize - 1 + LOOKAHEAD);
// Public render_bus uses its default -3 dB law. This separate mute-only fixture
// holds the static send at its left endpoint, whose factors are exactly1/0.
let mut offline_session = graph.session.clone();
offline_session.tracks[0].automation.retain(|lane| lane.param != AutoParam::SendPan(0));
let offline = render_bus(&offline_session, graph.capture, Range::new(0, 640), 37);
assert_eq!(offline[0].len(), 640);
assert_eq!(offline[0].iter().rposition(|sample| sample.abs() > 1e-6), Some(299));
for (channel, samples) in offline.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let expected = if at < MUTE_AT as usize && channel == 0 { AMPLITUDE } else { 0.0 };
assert!((sample - expected).abs() < 2e-7);
}
}
}
}
#[test]
fn aux_pre_tap_omits_post_alignment_while_both_taps_include_upstream_and_own_delay() {
for pdc in [false, true] {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Own upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let sender = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Aux capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let tap_delay = if pdc && !pre { 3 * LOOKAHEAD } else { 2 * LOOKAHEAD };
let observation_delay = if pdc { 2 * LOOKAHEAD } else { 0 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[100, 17, 1, 37, 64]);
assert_eq!(mix.latency, if pdc { 3 * LOOKAHEAD } else { 0 });
check_known(&output, &graph, 0, tap_delay + observation_delay, 900);
}
}
}
#[test]
fn nested_aux_taps_accumulate_the_actual_upstream_path_instead_of_global_latency() {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
silent_audio(&mut session, 2);
let first_bus = session.add_bus("Nested first", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(first_bus);
let first_aux = aux(&mut session, first_bus, ChannelFormat::Mono, 1);
let second_bus = session.add_bus("Nested second", ChannelFormat::Mono);
session.track_mut(first_aux).unwrap().mixer.output = Route::Bus(second_bus);
let sender = aux(&mut session, second_bus, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Nested capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
// Upstream audio2*71; first Aux own+alignment2*71; target pre adds1*71,
// target post adds2*71. The scalar global mix delay is only4*71.
let tap_delay = if pre { 5 * LOOKAHEAD } else { 6 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 1100, &[37, 3, 100, 64, 1]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
check_known(&output, &graph, 0, tap_delay + observation_delay, 1100);
}
}
#[test]
fn output_extra_downstream_aux_and_master_delay_do_not_shift_the_send_clock() {
for pre in [false, true] {
let mut graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let source = graph.session.tracks[0].id;
graph.session.track_mut(source).unwrap().mixer.output = Route::Main;
maximizers(&mut graph.session, graph.receiver, 1);
silent_aux(&mut graph.session, 2);
let master = graph.session.add_track(TrackKind::Master, ChannelFormat::Stereo, None);
maximizers(&mut graph.session, master, 1);
let mut mix = make_mix();
let main = capture_pcm(&mut mix, &graph, 0, 900, &[100, 37, 1, 64]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
assert!(main.iter().all(|channel| channel[..4 * LOOKAHEAD].iter().all(|sample| *sample == 0.0)));
assert!(main[0][4 * LOOKAHEAD] > 0.4, "main really traverses the excluded output/Aux/Master delays");
for (channel, samples) in main.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let source_time = at as i64 - (4 * LOOKAHEAD) as i64;
let expected = if source_time < 0 {
0.0
} else {
let sent = if source_time < MUTE_AT { AMPLITUDE * numeric_pan(source_time, 0, 600)[channel] } else { 0.0 };
AMPLITUDE + sent
};
assert!((sample - expected).abs() < 2e-7, "exclusion channel {channel}, emit {at}: {sample} != {expected}");
}
}
}
}
#[test]
fn unequal_aux_pre_and_direct_bus_ages_keep_the_documented_raw_clock_fallback() {
for target_pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Mixed upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let contributor = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let mixed_bus = session.add_bus("Unequal actual ages", ChannelFormat::Mono);
session.track_mut(contributor).unwrap().mixer.output = Route::Bus(mixed_bus);
let mut pre_send = SendSlot::new(Route::Bus(mixed_bus));
pre_send.level_db = 0.0;
pre_send.pre_fader = true;
session.track_mut(contributor).unwrap().mixer.sends[0] = Some(pre_send);
let sender = aux(&mut session, mixed_bus, ChannelFormat::Mono, 0);
let capture = session.add_bus("Mixed capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, target_pre, 0, 600, false);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[37, 100, 1, 3, 64]);
let extra = if target_pre { 0 } else { 2 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let delays = [2 * LOOKAHEAD + extra + observation_delay, 3 * LOOKAHEAD + extra + observation_delay];
for (at, (&left, &right)) in output[0].iter().zip(&output[1]).enumerate() {
let contributions = delays.iter().filter(|&&delay| at >= delay).count();
let expected = if at < MUTE_AT as usize + observation_delay { AMPLITUDE * contributions as f32 } else { 0.0 };
assert!((left - expected).abs() < 2e-7, "mixed tap pre={target_pre} emit{at}: {left} != {expected}");
assert_eq!(right, 0.0);
}
assert!(output[0].iter().any(|sample| *sample > 0.02));
}
}
#[test]
fn negative_positions_and_reset_seek_use_the_delayed_source_clock_with_pdc_off() {
let graph = ordinary(false, 1, 0, false, -512, -300, 300);
let mut mix = make_mix();
let negative = capture_pcm(&mut mix, &graph, -128, 256, &[1, 37, 3, 64, 17]);
assert_eq!(mix.latency, 0, "PDC is off while the insert still physically delays its source");
check_known(&negative, &graph, -128, LOOKAHEAD, 256);
mix.reset();
let seek = capture_pcm(&mut mix, &graph, 240, 400, &[100, 1, 37, 3]);
check_known(&seek, &graph, 240, LOOKAHEAD, 400);
assert_eq!(seek[1].iter().rposition(|sample| sample.abs() > 1e-6), Some(130));
}
+5 -74
View File
@@ -1,7 +1,7 @@
use super::{
Arc, AtomicBool, AtomicU32, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering,
OutputTrouble, Plugin, PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared,
SyncSender, TrackId, devices, itu_stereo_fold, main_channels, midi, record, sync_channel,
Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin,
PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId,
itu_stereo_fold, main_channels, midi, record, sync_channel,
};
use soundcraft_mix::{LiveMidi, midi_port_bit, midi_thru};
use soundcraft_model::TrackKind;
@@ -17,29 +17,6 @@ pub(crate) struct Fault {
pub(crate) beats: std::sync::atomic::AtomicU64,
/// The UI has been told.
reported: AtomicBool,
/// Underruns the device reported, callbacks that overran their buffer period, and the worst
/// callback's share of its buffer time (‰), since the stream opened or the last
/// [`Player::take_health`], and the device callbacks in that time.
xruns: std::sync::atomic::AtomicU64,
late_callbacks: std::sync::atomic::AtomicU64,
worst_load: AtomicU32,
callbacks: std::sync::atomic::AtomicU64,
}
/// How the realtime audio path keeps up, for the UI and for stress tests: since the output
/// opened, or since the last [`Player::take_health`].
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub struct AudioHealth {
/// Device callbacks (none for the silent clock).
pub callbacks: u64,
/// Underruns (dropouts) the device reported.
pub xruns: u64,
/// Callbacks that overran their buffer period. Not every one is an audible gap, and the
/// device may report the same overrun as an xrun too (CoreAudio does).
pub late_callbacks: u64,
/// The slowest callback's render time as a share of its buffer period, to 0.001 (1.0 = it
/// overran).
pub worst_load: f64,
}
impl Fault {
@@ -56,50 +33,6 @@ impl Fault {
};
(!self.reported.swap(true, Ordering::Relaxed)).then_some(trouble)
}
/// A device callback rendered `frames` at `rate` in `took`. Lock-free and allocation-free.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn note_callback(&self, took: std::time::Duration, frames: usize, rate: f64) {
self.callbacks.fetch_add(1, Ordering::Relaxed);
if frames == 0 || rate <= 0.0 {
return;
}
let load = took.as_secs_f64() * rate / frames as f64;
if load > 1.0 {
self.late_callbacks.fetch_add(1, Ordering::Relaxed);
}
self.worst_load.fetch_max((load * 1000.0).min(f64::from(u32::MAX)) as u32, Ordering::Relaxed);
}
/// The stream reported an error (on the audio thread or another). A lost stream is recorded
/// as gone; a transient xrun is counted and the stream keeps playing.
pub(crate) fn note_stream_error(&self, e: &cpal::Error) {
if devices::stream_lost(e) {
self.gone.store(true, Ordering::Relaxed);
} else if e.kind() == cpal::ErrorKind::Xrun {
self.xruns.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.load(Ordering::Relaxed),
xruns: self.xruns.load(Ordering::Relaxed),
late_callbacks: self.late_callbacks.load(Ordering::Relaxed),
worst_load: f64::from(self.worst_load.load(Ordering::Relaxed)) / 1000.0,
}
}
/// The health so far, counting afresh from here: each counter is swapped for zero, so an
/// event the callback records meanwhile lands in this reading or the next, never in neither.
pub(crate) fn take_health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.swap(0, Ordering::Relaxed),
xruns: self.xruns.swap(0, Ordering::Relaxed),
late_callbacks: self.late_callbacks.swap(0, Ordering::Relaxed),
worst_load: f64::from(self.worst_load.swap(0, Ordering::Relaxed)) / 1000.0,
}
}
}
/// How long a playing output may go without a block before it counts as stalled.
@@ -1048,16 +981,14 @@ impl Side {
}
}
/// `false` when no block was rendered since the last take (`out` keeps its readings).
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) -> bool {
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) {
if !source.fresh {
// No block since the last take: keep the readings, but not those of deleted tracks.
out.tracks.retain(|id, _| source.tracks.contains_key(id));
return false;
return;
}
copy_meter_snapshot(source, out);
source.reset_levels();
true
}
pub(crate) fn copy_meter_snapshot(source: &MeterSnapshot, out: &mut MeterSnapshot) {
+8 -30
View File
@@ -48,9 +48,8 @@ const BLOCK: usize = 512;
/// Room for replaced snapshots on their way back; `update_session` empties it before each send.
const OLD_SESSIONS: usize = 16;
pub use callback::AudioHealth;
/// The realtime audio thread marker lives in the mix engine, which renders every strip on the
/// marked thread itself; the cpal callbacks here set it.
/// The realtime audio thread marker lives in the mix engine, which carries it into the strips it
/// renders on worker threads; the cpal callbacks here set it.
pub use soundcraft_mix::{mark_audio_thread, on_audio_thread};
mod callback;
@@ -106,12 +105,6 @@ impl MeterSnapshot {
self.fresh = true;
}
/// Zero every level, keeping the entries and their storage: for a reader whose readings went
/// stale because no block has arrived for a while (the device stopped calling back).
pub fn clear_levels(&mut self) {
self.reset_levels();
}
/// Drop the entries of deleted tracks.
fn forget(&mut self, gone: &[TrackId]) {
for id in gone {
@@ -222,19 +215,6 @@ impl Player {
self.fault.trouble(stalled)
}
/// How the realtime path has kept up since the output opened or the last
/// [`Player::take_health`]: callbacks, device-reported underruns, late callbacks and the
/// worst callback load.
pub fn health(&self) -> AudioHealth {
self.fault.health()
}
/// [`Player::health`] so far, then count afresh (a stress run measures from a take). No
/// event is lost between the reading and the restart.
pub fn take_health(&self) -> AudioHealth {
self.fault.take_health()
}
fn side(&self) -> std::sync::MutexGuard<'_, Side> {
self.side.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -571,15 +551,13 @@ impl Player {
/// Take the meters accumulated since the last call into reusable UI storage and start a new
/// period: `out` gets the highest peak of every block rendered in between. If no block was
/// rendered since (a large device buffer renders several blocks per callback), `out` keeps
/// the previous values rather than dropping to silence, and the call returns `false`: when
/// that goes on for longer than any device buffer lasts, the device has stopped calling back
/// and the reader should clear the readings ([`MeterSnapshot::clear_levels`]). Call it from
/// one place only (two readers would split the peaks between them). Once track/channel
/// counts are stable this performs no allocation. The audio thread only ever `try_lock`s, so
/// holding the lock here never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) -> bool {
/// the previous values rather than dropping to silence. Call it from one place only (two
/// readers would split the peaks between them). Once track/channel counts are stable this
/// performs no allocation. The audio thread only ever `try_lock`s, so holding the lock here
/// never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) {
let mut source = self.shared.meters.lock().unwrap_or_else(PoisonError::into_inner);
take_meter_snapshot(&mut source, out)
take_meter_snapshot(&mut source, out);
}
}
+4 -8
View File
@@ -1,5 +1,5 @@
use super::callback::{AudioState, Fault, guarded_block};
use super::{Arc, AudioConfig, Cmd, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
/// Start a freshly built output stream. `false` when the device refuses to start it, so the caller
/// treats it like a stream that failed to build and tries the next configuration.
@@ -63,14 +63,10 @@ where
let mut scratch = vec![0.0f32; 8192 * frame];
let chunk = scratch.len();
let (failed, guard, gone) = (Arc::clone(fault), Arc::clone(shared), Arc::clone(fault));
#[cfg(not(target_arch = "wasm32"))]
let rate = f64::from(config.sample_rate);
device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
mark_audio_thread();
#[cfg(not(target_arch = "wasm32"))]
let started = std::time::Instant::now();
for out in data.chunks_mut(chunk) {
let Some(s) = scratch.get_mut(..out.len()) else { return };
guarded_block(&failed, &guard, s, |d| state.fill(d, channels));
@@ -78,8 +74,6 @@ where
*o = T::from_sample(*x);
}
}
#[cfg(not(target_arch = "wasm32"))]
failed.note_callback(started.elapsed(), data.len() / frame, rate);
},
// cpal may call this on the audio thread (on ALSA in a loop while the device stays
// broken): marked, so the logger hands the record off instead of writing it.
@@ -89,7 +83,9 @@ where
// stream that must be rebuilt (`StreamInvalidated`), stops playback until the user
// reconnects; a rerouted default device (`DeviceChanged`) keeps playing on the new
// route, and an xrun is transient, so neither counts as losing the stream.
gone.note_stream_error(&e);
if devices::stream_lost(&e) {
gone.gone.store(true, Ordering::Relaxed);
}
log::warn!("audio stream error: {e}");
},
None,
+3 -28
View File
@@ -162,7 +162,7 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
// The last block alone (what the UI used to see) is quiet.
assert!(st.mix.meters[&t].peak[0] < 0.05);
let mut ui = MeterSnapshot::default();
assert!(take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui), "new blocks arrived");
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] > 0.85, "{:?}", ui.tracks[&t]);
assert!(ui.tracks[&t].peaks[0] > 0.85);
assert!(ui.main.peak[0] > 0.5 && ui.main.peaks.iter().all(|p| *p > 0.5), "{:?}", ui.main);
@@ -170,12 +170,9 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
st.fill(&mut out, 2);
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] < 0.05 && ui.main.peak[0] < 0.05);
// No block since the last take: the reading stays rather than dropping to silence, and the
// reader is told, so it can clear readings that stay stale (the device stopped calling back).
assert!(!take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui));
// No block since the last take: the reading stays rather than dropping to silence.
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] > 0.005);
ui.clear_levels();
assert!(ui.tracks[&t].peak[0] == 0.0 && ui.main.peak[0] == 0.0 && ui.tracks[&t].peaks.len() == 1, "{:?}", ui.tracks[&t]);
}
#[test]
@@ -289,28 +286,6 @@ fn a_lost_or_stalled_device_is_reported_once() {
assert_eq!((fault.trouble(false), fault.trouble(true)), (Some(OutputTrouble::Gone), None));
}
#[test]
fn underruns_and_late_callbacks_are_counted_until_taken() {
use std::time::Duration;
let f = Fault::default();
let error = |kind| cpal::Error::with_message(kind, "test");
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
// 512 frames at 48 kHz last 10.67 ms.
f.note_callback(Duration::from_millis(4), 512, 48_000.0);
f.note_callback(Duration::from_millis(16), 512, 48_000.0);
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
let h = f.health();
assert_eq!(h, AudioHealth { callbacks: 3, xruns: 2, late_callbacks: 1, worst_load: 1.5 });
assert!(!f.gone.load(Ordering::Relaxed), "an underrun is not a lost device");
assert_eq!(f.take_health(), h);
assert_eq!(f.health(), AudioHealth::default());
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
assert_eq!(f.health().callbacks, 1);
f.note_stream_error(&error(cpal::ErrorKind::DeviceNotAvailable));
assert!(f.gone.load(Ordering::Relaxed));
}
#[test]
fn audio_state_plays_and_stops_at_end() {
let s = Arc::new(soundcraft_model::Session::default());
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-5
View File
@@ -325,9 +325,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
}
"No engine" => "Sem mecanismo de áudio",
"default buffer" => "buffer padrão",
"The audio settings were changed outside this window; your unapplied changes were replaced." => {
"As configurações de áudio foram alteradas fora desta janela; suas alterações não aplicadas foram substituídas."
}
"The device allows {}–{} samples; it runs at its default buffer." => {
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão."
}
@@ -1782,8 +1779,6 @@ fn menu_translate(source: &str) -> Option<&'static str> {
"Enable Track Notes Dialog" => "Ativar o diálogo de notas da pista",
"English" => "Inglês",
"Portuguese (Brazil)" => "Português (Brasil)",
"French" => "Francês",
"Spanish" => "Espanhol",
"key:Space" => "Espaço",
"key:Up" => "Cima",
"key:Down" => "Baixo",
-1
View File
@@ -129,7 +129,6 @@ impl SoundApp {
frame_ms: 0.0,
last_frame: None,
last_meter_poll: f64::NEG_INFINITY,
last_meter_block: f64::NEG_INFINITY,
video: video_track::VideoPool::default(),
bounce: None,
imports: import::Imports::default(),
+1 -84
View File
@@ -133,24 +133,6 @@ impl SoundApp {
}
}
/// How long the meters keep the last readings while no audio block arrives. Longer than the
/// longest device buffer (8192 frames at 44.1 kHz, 186 ms) plus the slowest meter poll (50 ms), so
/// a large buffer never reads as silence between its callbacks; once it has passed, the device has
/// stopped calling back (switched off, unplugged, stalled) and the meters fall to silence.
pub(super) const METER_STALE_SECS: f64 = 0.5;
/// After a meter take that `fresh`ly brought new blocks or not, at `now` (uptime, seconds): note
/// when the last block came in `last_block`, and clear `snap`'s readings once none has come for
/// [`METER_STALE_SECS`]. Otherwise the last block's levels would be fed to the meters every frame
/// and never fall.
pub(super) fn age_meters(snap: &mut soundcraft_playback::MeterSnapshot, fresh: bool, now: f64, last_block: &mut f64) {
if fresh {
*last_block = now;
} else if now - *last_block >= METER_STALE_SECS {
snap.clear_levels();
}
}
/// Open the new device of `cfg` with `open` in place of the one in `slot`, and return it; the caller
/// stores it, which closes the old one if it is still there.
///
@@ -183,9 +165,7 @@ pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], gr: f32, dt: f32)
if let Some(x) = d.level.get_mut(c) {
*x = if nv < 1e-5 { 0.0 } else { nv };
}
// Only a signal holds: silence meeting a hold of 0 would restart the shared hold time
// every frame and keep the other channel's hold up for good.
if v > 0.0 && v >= d.hold.get(c).copied().unwrap_or(0.0) {
if v >= d.hold.get(c).copied().unwrap_or(0.0) {
if let Some(h) = d.hold.get_mut(c) {
*h = v;
}
@@ -309,66 +289,3 @@ mod audio_input_tests {
assert!(wants_audio_input(&s));
}
}
#[cfg(test)]
mod meter_tests {
use super::{METER_STALE_SECS, MeterDisplay, age_meters, feed_meter};
use soundcraft_mix::StripMeter;
use soundcraft_model::TrackId;
use soundcraft_playback::MeterSnapshot;
/// Runs the UI's meter loop for `secs` at 60 frames a second, polling at 20 Hz as the Edit
/// window does; `blocks(prev, now)` says whether a block (with `peak`) arrived since the
/// previous poll.
fn run(secs: f64, peak: [f32; 2], blocks: impl Fn(f64, f64) -> bool) -> (MeterDisplay, f32) {
let t = TrackId(1);
let mut snap = MeterSnapshot::default();
let mut d = MeterDisplay::default();
let (mut last_block, mut last_poll, mut lowest) = (f64::NEG_INFINITY, f64::NEG_INFINITY, f32::INFINITY);
let dt = 1.0 / 60.0;
let mut now = 0.0;
while now < secs {
if now - last_poll >= 1.0 / 20.0 {
let fresh = blocks(last_poll.max(-1e-9), now);
if fresh {
let m = snap.tracks.entry(t).or_insert_with(StripMeter::default);
m.peak = peak;
m.peaks = peak.to_vec();
}
age_meters(&mut snap, fresh, now, &mut last_block);
last_poll = now;
}
let m = snap.tracks.get(&t).map_or([0.0; 2], |m| m.peak);
feed_meter(&mut d, m, 0.0, dt as f32);
if now > 0.0 {
lowest = lowest.min(d.level[0]);
}
now += dt;
}
(d, lowest)
}
#[test]
fn meters_fall_to_silence_when_the_device_stops_calling_back() {
// Blocks come for a second, then the device is switched off: no callback ever again.
let (d, _) = run(6.0, [0.4; 2], |_, now| now < 1.0);
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
}
/// A silent channel does not keep the other channel's peak hold up: 0.0 meets a hold of 0.0
/// every frame, which must not restart the shared hold time.
#[test]
fn a_silent_channel_does_not_keep_the_other_channels_peak_hold() {
let (d, _) = run(6.0, [0.4, 0.0], |_, now| now < 1.0);
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
}
#[test]
fn a_large_device_buffer_keeps_the_meters_up_between_callbacks() {
// 8192 frames at 44.1 kHz: one block every 186 ms, several polls without one.
let period = 8192.0 / 44_100.0;
assert!(period + 1.0 / 20.0 < METER_STALE_SECS);
let (d, lowest) = run(3.0, [0.4; 2], |prev, now| (now / period).floor() > (prev / period).floor());
assert!(lowest >= 0.4 && d.level[0] >= 0.4, "the meter dropped to {lowest} between callbacks");
}
}
+2 -3
View File
@@ -1,4 +1,4 @@
use super::audio::{age_meters, feed_meter};
use super::audio::feed_meter;
use super::plugins::failed_plugin_status;
use super::{Gesture, MainWindow, MeterDisplay, Range, Samples, SoundApp, TrackId, TransportRequest, json};
@@ -522,8 +522,7 @@ impl SoundApp {
let now = self.uptime;
let meter_interval = if self.ui.window == MainWindow::Mix { 1.0 / 60.0 } else { 1.0 / 20.0 };
if now - self.last_meter_poll >= meter_interval {
let fresh = p.take_meters(&mut self.meter_snapshot);
age_meters(&mut self.meter_snapshot, fresh, now, &mut self.last_meter_block);
p.take_meters(&mut self.meter_snapshot);
self.last_meter_poll = now;
}
let snap = &self.meter_snapshot;
-13
View File
@@ -488,19 +488,6 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
"session.inspect" | "document.inspect" => {
ok(soundcraft_engine::inspect::session(&app.engine, p.get("detail").and_then(Value::as_str) == Some("full")))
}
"audio.health" => match &app.player {
Some(player) => {
let h = if p.get("reset").and_then(Value::as_bool) == Some(true) { player.take_health() } else { player.health() };
ok(json!({
"device": player.device_name,
"silent": player.silent,
"sample_rate": player.device_rate,
"buffer_frames": player.device_buffer,
"health": h,
}))
}
None => err("no audio output"),
},
"ui.inspect" => {
let mut v = app.inspect(ctx);
v["edit_layout"] = json!(app.edit_layout);
-5
View File
@@ -149,8 +149,6 @@ pub struct UiState {
pub preferences_window_pos: Option<[f32; 2]>,
pub reduce_visual_effects: preferences::ReduceVisualEffects,
pub undo_levels: usize,
/// The level a send made in the Mix window starts at (Preferences › Mixing).
pub sends_default: preferences::SendsDefault,
/// The audio device choice (Setup › Playback Engine), kept with the preferences: per machine.
pub audio: soundcraft_playback::AudioConfig,
/// The Mix window lives in its own native window (Window › Mix in Separate Window); the main
@@ -229,7 +227,6 @@ impl Default for UiState {
preferences_window_pos: None,
reduce_visual_effects: preferences::ReduceVisualEffects::default(),
undo_levels: 64,
sends_default: preferences::SendsDefault::default(),
audio: soundcraft_playback::AudioConfig::default(),
mix_separate: false,
show_io_setup: false,
@@ -484,8 +481,6 @@ pub struct SoundApp {
pub frame_ms: f32,
last_frame: Option<f64>,
last_meter_poll: f64,
/// When a meter take last brought new audio blocks (uptime, seconds).
last_meter_block: f64,
/// Movies for the Video window and Video track (decoded in the background).
pub video: video_track::VideoPool,
/// The Bounce Mix in progress, rendered a slice per frame.
+16 -58
View File
@@ -1,9 +1,5 @@
//! Language selection and source-language fallback for UI strings.
#[path = "../locales/es/mod.rs"]
mod es;
#[path = "../locales/fr/mod.rs"]
mod fr;
#[path = "../locales/pt-BR/mod.rs"]
mod pt_br;
@@ -21,23 +17,17 @@ pub enum Language {
English,
#[serde(rename = "pt-BR")]
PortugueseBrazil,
#[serde(rename = "fr")]
French,
#[serde(rename = "es")]
Spanish,
}
impl Language {
/// All supported languages, in the order they are shown in the language menu.
pub const ALL: [Self; 4] = [Self::English, Self::PortugueseBrazil, Self::French, Self::Spanish];
pub const ALL: [Self; 2] = [Self::English, Self::PortugueseBrazil];
/// Stable language tag used in preferences and control commands.
pub const fn id(self) -> &'static str {
match self {
Self::English => "en",
Self::PortugueseBrazil => "pt-BR",
Self::French => "fr",
Self::Spanish => "es",
}
}
@@ -46,8 +36,6 @@ impl Language {
match self {
Self::English => "English",
Self::PortugueseBrazil => "Portuguese (Brazil)",
Self::French => "French",
Self::Spanish => "Spanish",
}
}
@@ -59,7 +47,7 @@ impl Language {
pub fn localize_decimal(self, number: &str) -> String {
match self {
Self::English => number.to_owned(),
Self::PortugueseBrazil | Self::French | Self::Spanish => number.replace('.', ","),
Self::PortugueseBrazil => number.replace('.', ","),
}
}
@@ -68,8 +56,6 @@ impl Language {
match self {
Self::English => source,
Self::PortugueseBrazil => pt_br::translate(source).unwrap_or(source),
Self::French => fr::translate(source).unwrap_or(source),
Self::Spanish => es::translate(source).unwrap_or(source),
}
}
}
@@ -103,8 +89,6 @@ fn error_text_in(language: Language, message: &str, depth: usize) -> String {
let templates: &[(&str, &str)] = match language {
Language::English => &[],
Language::PortugueseBrazil => pt_br::ERROR_TEMPLATES,
Language::French => fr::ERROR_TEMPLATES,
Language::Spanish => es::ERROR_TEMPLATES,
};
let mut best: Option<(usize, &str, Vec<(String, String)>)> = None;
for (template, translation) in templates {
@@ -370,8 +354,7 @@ mod tests {
assert_eq!(decoded, language);
}
assert_eq!(Language::parse(" PT-br "), Some(Language::PortugueseBrazil));
assert_eq!(Language::parse(" FR "), Some(Language::French));
assert_eq!(Language::parse("de"), None);
assert_eq!(Language::parse("fr"), None);
}
#[test]
@@ -379,10 +362,6 @@ mod tests {
assert_ne!(Language::PortugueseBrazil.text("Appearance"), "Appearance");
assert_eq!(Language::PortugueseBrazil.text("A source string with no catalog entry"), "A source string with no catalog entry");
assert_eq!(Language::English.text("Appearance"), "Appearance");
for language in [Language::French, Language::Spanish] {
assert_ne!(language.text("Appearance"), "Appearance", "{language:?}");
assert_eq!(language.text("A source string with no catalog entry"), "A source string with no catalog entry");
}
}
#[test]
@@ -409,15 +388,6 @@ mod tests {
}
}
#[test]
fn spanish_catalog_covers_every_menu_label() {
for path in include_str!("../../engine/catalog/menus.txt").lines() {
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
assert!(super::es::translate(label).is_some(), "missing es menu label: {label}");
}
}
}
#[test]
fn engine_errors_are_translated_with_their_values() {
assert_eq!(error_text("select a clip"), "select a clip");
@@ -490,17 +460,9 @@ mod tests {
None
}
type Lookup = fn(&str) -> Option<&'static str>;
/// Every catalog: its tag, source file and lookup.
const CATALOGS: [(&str, &str, Lookup); 3] = [
("pt-BR", include_str!("../locales/pt-BR/mod.rs"), super::pt_br::translate),
("fr", include_str!("../locales/fr/mod.rs"), super::fr::translate),
("es", include_str!("../locales/es/mod.rs"), super::es::translate),
];
/// Every `"source" => "translation"` pair of a catalog, read from its source file.
fn catalog_entries(text: &str) -> Vec<(String, String)> {
/// Every `"source" => "translation"` pair of the catalog, read from its source file.
fn catalog_entries() -> Vec<(String, String)> {
let text = include_str!("../locales/pt-BR/mod.rs");
let mut lines = text.lines().map(str::trim);
let mut entries = Vec::new();
while let Some(line) = lines.next() {
@@ -533,24 +495,20 @@ mod tests {
#[test]
fn catalog_entries_are_parsed_and_unique() {
for (tag, text, _) in CATALOGS {
let entries = catalog_entries(text);
assert!(entries.len() > 1000, "{tag}: parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "{tag}: duplicate catalog keys");
}
let entries = catalog_entries();
assert!(entries.len() > 1000, "parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "duplicate catalog keys");
}
#[test]
fn catalog_translations_keep_the_english_placeholders() {
for (tag, text, translate) in CATALOGS {
for (source, translation) in catalog_entries(text) {
assert_eq!(placeholders(&source), placeholders(&translation), "{tag}: placeholders differ for {source:?}");
assert_eq!(translate(&source), Some(translation.as_str()), "{tag}: lookup differs for {source:?}");
}
for (source, translation) in catalog_entries() {
assert_eq!(placeholders(&source), placeholders(&translation), "placeholders differ for {source:?}");
assert_eq!(super::pt_br::translate(&source), Some(translation.as_str()), "lookup differs for {source:?}");
}
}
-58
View File
@@ -82,7 +82,6 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
("ui.theme", "Appearance", "", None),
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
("ui.undo_levels", "Levels of Undo", "", None),
("ui.sends_default", "Sends Default to", "", None),
];
/// Extra catalog mappings handled by the UI layer.
@@ -850,20 +849,6 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
}
json!({"levels": app.ui.undo_levels})
}
"ui.sends_default" => {
// No `level` reads the value back; a `level` that is not a string is an error, so
// `{"level": 0}` cannot look like it set 0 dB while changing nothing.
let level = match p.get("level") {
None => return Some(Ok(json!({"level": app.ui.sends_default.id()}))),
Some(Value::String(level)) => level.as_str(),
Some(other) => return Some(Err(format!("send default must be the string \"-inf\" or \"0\", not {other}"))),
};
let Some(level) = crate::preferences::SendsDefault::parse(level) else {
return Some(Err(format!("unknown send default `{level}` (-inf or 0)")));
};
app.ui.sends_default = level;
json!({"level": level.id()})
}
"ui.set" => match serde_json::to_value(&app.ui) {
Ok(mut cur) => {
if let (Some(obj), Some(patch)) = (cur.as_object_mut(), p.as_object()) {
@@ -968,49 +953,6 @@ mod tests {
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (64, 64));
}
/// The Sends Default to preference reads back, takes -inf or 0, and rejects anything else.
#[test]
fn sends_default_sets_reads_and_rejects_unknown_levels() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
assert_eq!(app.run("ui.sends_default", json!({})).unwrap(), json!({"level": "-inf"}));
assert_eq!(app.run("ui.sends_default", json!({"level": "0"})).unwrap(), json!({"level": "0"}));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(app.run("ui.sends_default", json!({"level": "-6"})).is_err());
assert_eq!(app.ui.sends_default, SendsDefault::Unity, "a rejected level changes nothing");
assert_eq!(app.run("ui.sends_default", json!({"level": "-inf"})).unwrap(), json!({"level": "-inf"}));
assert_eq!(app.ui.sends_default, SendsDefault::NegativeInfinity, "switching back to −∞ dB works");
assert!(!app.engine.is_dirty(), "a preference is not a document edit");
}
/// A `level` that is present but not a string is an error, not a read-back: `{"level": 0}` must
/// not look like it set 0 dB while changing nothing.
#[test]
fn sends_default_rejects_a_non_string_level() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for bad in [json!(0), json!(null), json!(false), json!(["0"])] {
assert!(app.run("ui.sends_default", json!({"level": bad})).is_err(), "{bad} accepted");
assert_eq!(app.ui.sends_default, SendsDefault::NegativeInfinity, "{bad} changed the setting");
}
}
/// `ui.set` takes the same `-inf` and `0` as `ui.sends_default`, and a bad value changes nothing.
#[test]
fn ui_set_takes_the_same_sends_default_levels() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let result = app.run("ui.set", json!({"sends_default": "0"})).unwrap();
assert_eq!((result["ui"]["sends_default"].clone(), app.ui.sends_default), (json!("0"), SendsDefault::Unity));
let result = app.run("ui.set", json!({"sends_default": "-inf"})).unwrap();
assert_eq!((result["ui"]["sends_default"].clone(), app.ui.sends_default), (json!("-inf"), SendsDefault::NegativeInfinity));
app.run("ui.set", json!({"sends_default": "0"})).unwrap();
for bad in [json!("unity"), json!("-6"), json!(0)] {
assert!(app.run("ui.set", json!({"sends_default": bad})).is_err(), "{bad} accepted");
assert_eq!(app.ui.sends_default, SendsDefault::Unity, "{bad} changed the setting");
}
}
fn recent_paths(count: usize) -> Vec<String> {
(0..count).map(|i| format!("{i}.scraft")).collect()
}
+2 -45
View File
@@ -464,16 +464,8 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
app.ui.send_window = Some((id, slot));
}
};
// A new send starts at the Sends Default to preference; re-targeting keeps the send's level.
let send_params = |app: &SoundApp, bus: &str| {
let mut p = json!({"track": id.0, "slot": slot, "bus": bus});
if !has_send {
p["level_db"] = json!(app.ui.sends_default.level_db());
}
p
};
if let Some(bus) = picked
&& app.run("mix.send", send_params(app, &bus)).is_ok()
&& app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": bus})).is_ok()
{
show_new_send(app);
}
@@ -487,7 +479,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
n += 1;
}
if app.run("mix.new_bus", json!({"name": format!("Bus {n}")})).is_ok()
&& app.run("mix.send", send_params(app, &format!("Bus {n}"))).is_ok()
&& app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": format!("Bus {n}")})).is_ok()
{
show_new_send(app);
}
@@ -503,7 +495,6 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
mod tests {
use super::*;
use crate::Services;
use crate::preferences::SendsDefault;
use egui_kittest::{Harness, kittest::Queryable};
/// Filtering the destination list to nothing shrinks the menu; clearing the filter grows it
@@ -629,38 +620,4 @@ mod tests {
assert_eq!(target.as_deref(), Some("Aux"), "the send moved");
assert_eq!(app.ui.send_window, None, "no window opened");
}
/// Picks `item` from Kick's send A menu with the Sends Default to preference set to `default`,
/// and returns the send's level.
fn level_after_picking(existing_send: bool, default: SendsDefault, item: &str) -> Option<f32> {
let (mut h, kick) = kick_send_harness(existing_send);
h.state_mut().0.ui.sends_default = default;
if existing_send {
h.state_mut().0.run("mix.send_level", json!({"track": kick.0, "slot": 0, "db": -9.0})).unwrap();
}
h.run();
h.get_by_label("Send A for Kick").click();
h.run();
h.get_by_label(item).click();
h.run();
let (app, _) = h.state();
app.engine.session().track(kick).and_then(|t| t.mixer.sends.first().cloned().flatten()).map(|s| s.level_db)
}
/// A new send starts at the level set in Preferences › Mixing › Sends Default to (#1423).
#[test]
fn a_new_send_starts_at_the_sends_default_preference() {
let _palette = crate::theme::lock_test_palette();
assert_eq!(level_after_picking(false, SendsDefault::NegativeInfinity, "Aux"), Some(-144.0));
assert_eq!(level_after_picking(false, SendsDefault::Unity, "Aux"), Some(0.0));
assert_eq!(level_after_picking(false, SendsDefault::Unity, "new bus..."), Some(0.0));
}
/// Moving an existing send to another bus keeps its level, whatever the preference says.
#[test]
fn changing_a_sends_destination_keeps_its_level() {
let _palette = crate::theme::lock_test_palette();
assert_eq!(level_after_picking(true, SendsDefault::Unity, "Aux"), Some(-9.0));
assert_eq!(level_after_picking(true, SendsDefault::NegativeInfinity, "Aux"), Some(-9.0));
}
}
+4 -50
View File
@@ -447,7 +447,6 @@ pub fn recall_configuration(app: &mut SoundApp, saved: &Value) -> Result<(), Str
st.preferences_window_pos = app.ui.preferences_window_pos;
st.reduce_visual_effects = app.ui.reduce_visual_effects;
st.undo_levels = app.ui.undo_levels.clamp(1, 64);
st.sends_default = app.ui.sends_default;
st.show_configurations = true;
crate::docking::cancel_replaced_state(app, &st);
app.engine.set_history_limit(st.undo_levels);
@@ -593,50 +592,14 @@ fn midi_inputs(app: &mut SoundApp, ui: &mut egui::Ui) {
ui.data_mut(|d| d.insert_temp(debug_id, debug));
}
/// What the Playback Engine says when a change made elsewhere replaced its unapplied edits.
const REPLACED_EDITS: &str = "The audio settings were changed outside this window; your unapplied changes were replaced.";
/// Drop the replacement notice from the status line when it is still this notice, so a later edit
/// or closing the window does not leave it there. Leave any other status message alone.
fn clear_replaced_edits_status(app: &mut SoundApp) {
if app.ui.status == crate::localization::text(REPLACED_EDITS) {
app.ui.status.clear();
}
}
/// Setup › Playback Engine / Hardware: choose the audio system, devices, rate and buffer size.
pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
let mut open = app.ui.show_playback_engine;
// The window's unapplied edits, with the choice they started from. A choice changed elsewhere
// (`ui.audio_device`, `setup.playback_engine`) replaces them, so the window never shows, or
// applies, an earlier choice. A reconnect reopens the same choice and leaves them alone.
let draft_id = egui::Id::unique("audio_draft");
// Set while the window shows a choice made elsewhere that replaced its unapplied edits.
let replaced_id = egui::Id::unique("audio_draft_replaced");
if !open {
// Closed from the menu or by command: unapplied edits go, as with the close button.
clear_replaced_edits_status(app);
ctx.data_mut(|d| {
d.remove_temp::<(AudioConfig, AudioConfig)>(draft_id);
d.remove_temp::<bool>(replaced_id);
});
return;
}
// Pro Tools' Playback Engine is modal, so nothing else changes the device under its edits
// (Reference Guide p. 109). This window is not: a change made elsewhere wins, and when it
// replaces unapplied edits the window and the status line say so.
let mut draft = match ctx.data(|d| d.get_temp::<(AudioConfig, AudioConfig)>(draft_id)) {
Some((from, draft)) if from == app.ui.audio => draft,
Some((from, draft)) => {
if draft != from && draft != app.ui.audio {
let note = crate::localization::text(REPLACED_EDITS);
app.ui.status = note.to_string();
ctx.data_mut(|d| d.insert_temp(replaced_id, true));
}
app.ui.audio.clone()
}
None => app.ui.audio.clone(),
};
let draft_id = egui::Id::unique("audio_draft");
let mut draft = ctx.data(|d| d.get_temp::<AudioConfig>(draft_id)).unwrap_or_else(|| app.ui.audio.clone());
let mut refresh = false;
let mut apply = false;
let systems = audio_systems(ctx, false);
@@ -695,13 +658,6 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
draft = app.ui.audio.clone();
}
});
if draft != app.ui.audio {
// A new edit: the replaced ones are no longer the news.
ui.ctx().data_mut(|d| d.remove_temp::<bool>(replaced_id));
clear_replaced_edits_status(app);
} else if ui.ctx().data(|d| d.get_temp::<bool>(replaced_id)).unwrap_or(false) {
ui.label(egui::RichText::new(crate::localization::text(REPLACED_EDITS)).color(ui.visuals().warn_fg_color));
}
ui.separator();
egui::Grid::new("pe-state").num_columns(2).show(ui, |ui| {
ui.label(crate::localization::text("Output"));
@@ -758,13 +714,11 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
app.ui.status = e;
}
if open {
ctx.data_mut(|d| d.insert_temp(draft_id, (app.ui.audio.clone(), draft)));
ctx.data_mut(|d| d.insert_temp(draft_id, draft));
} else {
// Closing discards unapplied edits and the device list (re-read on the next open).
clear_replaced_edits_status(app);
ctx.data_mut(|d| {
d.remove_temp::<(AudioConfig, AudioConfig)>(draft_id);
d.remove_temp::<bool>(replaced_id);
d.remove_temp::<AudioConfig>(draft_id);
d.remove_temp::<Arc<Vec<AudioSystem>>>(egui::Id::unique("audio_systems"));
});
}
+1 -109
View File
@@ -71,54 +71,6 @@ impl ReduceVisualEffects {
}
}
/// The level a send made in the Mix window starts at (Mixing › Sends Default to).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SendsDefault {
// Stored and set (`ui.set`) with the same ids as `ui.sends_default` takes.
#[default]
#[serde(rename = "-inf")]
NegativeInfinity,
#[serde(rename = "0")]
Unity,
}
impl SendsDefault {
pub const ALL: [Self; 2] = [Self::NegativeInfinity, Self::Unity];
/// Returns the text shown for this level in the preference selector.
pub const fn label(self) -> &'static str {
match self {
Self::NegativeInfinity => "−∞ dB",
Self::Unity => "0 dB",
}
}
/// Returns the stable command and persistence identifier for this level.
pub const fn id(self) -> &'static str {
match self {
Self::NegativeInfinity => "-inf",
Self::Unity => "0",
}
}
/// Parses a command or persistence identifier into a default send level.
pub fn parse(id: &str) -> Option<Self> {
match id {
"-inf" => Some(Self::NegativeInfinity),
"0" => Some(Self::Unity),
_ => None,
}
}
/// The send level in dB; −∞ is the mixer's -144 dB floor.
pub const fn level_db(self) -> f32 {
match self {
Self::NegativeInfinity => -144.0,
Self::Unity => 0.0,
}
}
}
impl PreferencesPage {
pub const ALL: [Self; 9] = [
Self::Display,
@@ -169,11 +121,9 @@ struct PreferencesDraft {
theme: ThemeMode,
reduce_visual_effects: ReduceVisualEffects,
undo_levels: usize,
sends_default: SendsDefault,
theme_edited: bool,
reduce_visual_effects_edited: bool,
undo_levels_edited: bool,
sends_default_edited: bool,
}
impl PreferencesDraft {
@@ -183,11 +133,9 @@ impl PreferencesDraft {
theme: app.ui.theme,
reduce_visual_effects: app.ui.reduce_visual_effects,
undo_levels: app.ui.undo_levels,
sends_default: app.ui.sends_default,
theme_edited: false,
reduce_visual_effects_edited: false,
undo_levels_edited: false,
sends_default_edited: false,
}
}
@@ -202,9 +150,6 @@ impl PreferencesDraft {
if !self.undo_levels_edited {
self.undo_levels = app.ui.undo_levels;
}
if !self.sends_default_edited {
self.sends_default = app.ui.sends_default;
}
}
/// Remembers which values the user changed during the current UI frame.
@@ -212,7 +157,6 @@ impl PreferencesDraft {
self.theme_edited |= self.theme != before.theme;
self.reduce_visual_effects_edited |= self.reduce_visual_effects != before.reduce_visual_effects;
self.undo_levels_edited |= self.undo_levels != before.undo_levels;
self.sends_default_edited |= self.sends_default != before.sends_default;
}
}
@@ -245,7 +189,6 @@ enum Control {
Theme,
ReduceVisualEffects,
UndoLevels,
SendsDefault,
}
impl Control {
@@ -261,7 +204,6 @@ impl Control {
Self::Theme => "UI Theme",
Self::ReduceVisualEffects => "Reduce Visual Effects",
Self::UndoLevels => "Levels of Undo",
Self::SendsDefault => "Sends Default to",
}
}
@@ -278,10 +220,6 @@ impl Control {
let modes = ReduceVisualEffects::ALL.map(|mode| both(mode.label())).join(" ");
format!("{} {modes}", both(self.label()))
}
Self::SendsDefault => {
let levels = SendsDefault::ALL.map(|level| both(level.label())).join(" ");
format!("{} {levels}", both(self.label()))
}
_ => both(self.label()),
}
}
@@ -494,7 +432,7 @@ const MIXING: &[Section] = &[
Section {
title: "Setup",
controls: &[
Control::SendsDefault,
Control::Value("Sends Default to", "−∞ dB"),
Control::Check("Send Pans Default to Follow Main Pan"),
Control::Check("Use Absolute Pan Linking"),
Control::Check("Allow Sends to Persist During Low-Latency Monitoring"),
@@ -876,7 +814,6 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let _ = app.run("ui.theme", json!({"mode": draft.theme.id()}));
let _ = app.run("ui.reduce_visual_effects", json!({"mode": draft.reduce_visual_effects.id()}));
let _ = app.run("ui.undo_levels", json!({"levels": draft.undo_levels}));
let _ = app.run("ui.sends_default", json!({"level": draft.sends_default.id()}));
open = false;
app.preferences.discard_draft();
}
@@ -1025,16 +962,6 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
ui.add(egui::DragValue::new(&mut draft.undo_levels).range(1..=64));
});
}
Control::SendsDefault => {
egui::ComboBox::new(id, label("Sends Default to")).selected_text(crate::localization::text(draft.sends_default.label())).show_ui(
ui,
|ui| {
for level in SendsDefault::ALL {
ui.selectable_value(&mut draft.sends_default, level, crate::localization::text(level.label()));
}
},
);
}
Control::Check(text) => {
let mut value = false;
ui.add_enabled(false, egui::Checkbox::new(&mut value, label(text)))
@@ -1176,16 +1103,6 @@ mod tests {
assert!(!text_matches(&control.search_text(), "mixagem"));
}
#[test]
fn sends_default_is_found_by_its_label_and_levels_in_both_languages() {
let _scope = crate::localization::enter(crate::localization::Language::PortugueseBrazil);
let text = Control::SendsDefault.search_text();
assert!(text_matches(&text, "sends default"), "English label");
assert!(text_matches(&text, crate::localization::Language::PortugueseBrazil.text("Sends Default to")), "pt-BR label");
assert!(text_matches(&text, "0 dB"), "a level");
assert!(!text_matches(&text, "mixagem"));
}
/// Creates a complete application harness with Preferences already open.
fn preferences_harness(size: egui::Vec2) -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(Engine::default(), None, crate::Services::default());
@@ -1217,11 +1134,9 @@ mod tests {
assert!(app.run("ui.theme", json!({"mode": ThemeMode::Light.id()})).is_ok());
assert!(app.run("ui.reduce_visual_effects", json!({"mode": "playback"})).is_ok());
assert!(app.run("ui.undo_levels", json!({"levels": 32})).is_ok());
assert!(app.run("ui.sends_default", json!({"level": "0"})).is_ok());
assert_eq!(app.ui.theme, ThemeMode::Light);
assert_eq!(app.ui.reduce_visual_effects, ReduceVisualEffects::Playback);
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (32, 32));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(!app.engine.is_dirty());
}
@@ -1235,7 +1150,6 @@ mod tests {
assert!(app.run("ui.theme", json!({"mode": ThemeMode::Light.id()})).is_ok());
assert!(app.run("ui.reduce_visual_effects", json!({"mode": "always"})).is_ok());
assert!(app.run("ui.undo_levels", json!({"levels": 17})).is_ok());
assert!(app.run("ui.sends_default", json!({"level": "0"})).is_ok());
}
harness.run_steps(2);
harness.get_by_label("OK").click();
@@ -1245,7 +1159,6 @@ mod tests {
assert_eq!(app.ui.theme, ThemeMode::Light);
assert_eq!(app.ui.reduce_visual_effects, ReduceVisualEffects::Always);
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (17, 17));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(!app.ui.show_preferences);
}
@@ -1261,13 +1174,11 @@ mod tests {
app.ui.theme = ThemeMode::System;
app.ui.reduce_visual_effects = ReduceVisualEffects::Always;
app.ui.undo_levels = 17;
app.ui.sends_default = SendsDefault::Unity;
draft.sync_unedited_from_live(&app);
assert_eq!(draft.theme, ThemeMode::Light);
assert_eq!(draft.reduce_visual_effects, ReduceVisualEffects::Always);
assert_eq!(draft.undo_levels, 17);
assert_eq!(draft.sends_default, SendsDefault::Unity);
}
/// Command inputs reject unknown modes and bound undo depth safely.
@@ -1450,25 +1361,6 @@ mod tests {
assert_eq!(harness.state().ui.theme, ThemeMode::Dark);
}
/// Choosing 0 dB for Sends Default to applies on OK and is discarded on Cancel (#1423).
#[test]
fn sends_default_choice_applies_on_ok_and_not_on_cancel() {
for (button, expected) in [("OK", SendsDefault::Unity), ("Cancel", SendsDefault::NegativeInfinity)] {
let mut harness = preferences_harness(egui::vec2(1280.0, 1000.0));
harness.state_mut().ui.preferences_page = PreferencesPage::Mixing;
harness.run_steps(4);
harness.get_by_value("−∞ dB").click();
harness.run_steps(2);
harness.get_by_label("0 dB").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.sends_default, SendsDefault::NegativeInfinity, "staged until {button}");
harness.get_by_label(button).click();
harness.run_steps(2);
assert_eq!(harness.state().ui.sends_default, expected, "after {button}");
assert!(!harness.state().ui.show_preferences);
}
}
/// Escape closes an open choice popup before it can cancel the complete window.
#[test]
fn escape_closes_a_choice_popup_before_preferences() {
+1 -12
View File
@@ -206,7 +206,7 @@ fn fixed(app: &mut SoundApp, key: Key, m: Modifiers, mac: bool) -> bool {
// No MIDI target can consume the notes any more: drop the stale selection.
app.midi.selected.clear();
}
if midi_editor_drawn(app) && !app.midi.selected.is_empty() {
if app.ui.show_midi_editor && !app.midi.selected.is_empty() {
return false;
}
let _ = app.run("edit.clear", json!({}));
@@ -511,17 +511,6 @@ fn centre_on_selection(app: &mut SoundApp, end: bool) -> bool {
true
}
/// Whether the MIDI editor's body was drawn on the last frame, and is still in front: docking
/// records its rect only when it draws the body (shortcuts run before the panels draw), and a
/// layout change since, such as a tab moved over it, has not redrawn the dock yet. Open behind
/// another tab, its notes aren't on screen and its keys aren't read, so Delete is the Edit
/// window's Clear there (#1627).
fn midi_editor_drawn(app: &SoundApp) -> bool {
app.ui.show_midi_editor
&& app.ui.docking.layout().panel_state(&crate::docking::Panel::Midi) == craft_behavior::dock::PanelState::Front
&& app.docking_context.as_ref().is_some_and(|c| c.data(|d| d.get_temp::<egui::Rect>(egui::Id::unique("soundcraft-midi-body"))).is_some())
}
/// Whether the pointer is over the MIDI editor, whose piano roll moves the selected notes with the arrow keys.
fn piano_roll_has_pointer(app: &SoundApp) -> bool {
app.ui.show_midi_editor
-1
View File
@@ -459,7 +459,6 @@ fn preferences_saved_before_the_window_was_remembered_keep_full_scale() {
assert_eq!((ui.window_size, ui.window_maximized, ui.ui_scale), ([1600.0, 1000.0], false, 1.0));
assert_eq!(ui.reduce_visual_effects, crate::preferences::ReduceVisualEffects::Never);
assert_eq!(ui.undo_levels, 64);
assert_eq!(ui.sends_default, crate::preferences::SendsDefault::NegativeInfinity);
}
#[test]
+1 -1
View File
@@ -591,7 +591,7 @@ mod tests {
assert_eq!(app.run("ui.language", json!({})), Ok(json!({"language": "en"})));
assert_eq!(app.run("ui.language", json!({"language": "pt-BR"})), Ok(json!({"language": "pt-BR"})));
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
assert!(app.run("ui.language", json!({"language": "xx"})).is_err());
assert!(app.run("ui.language", json!({"language": "fr"})).is_err());
assert_eq!(app.ui.language, crate::localization::Language::PortugueseBrazil);
assert!(crate::menus::UI_COMMANDS.iter().any(|command| command.0 == "ui.language"));
}
-99
View File
@@ -1,6 +1,4 @@
//! `ui.audio_device`: the audio device choice is kept only once the devices reopen with it.
use egui::vec2;
use egui_kittest::{Harness, kittest::Queryable};
use serde_json::json;
use soundcraft_ui_egui::{Services, SoundApp};
@@ -113,100 +111,3 @@ fn playback_engine_applies_the_same_device_choice_as_the_audio_command() {
assert!(app.ui.show_playback_engine, "the menu still opens the Playback Engine window");
assert_eq!(app.ui.audio, cfg, "opening the window does not change the device");
}
/// The Playback Engine window, rendered, with the app's audio choice set to `buffer` samples.
fn playback_engine_harness(buffer: u32) -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.ui.audio.buffer_size = Some(buffer);
app.ui.show_playback_engine = true;
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
/// Whether the Buffer size selector shows `text`.
fn shows(h: &Harness<'_, SoundApp>, text: &str) -> bool {
h.query_all_by_label("Buffer size").any(|n| n.value().is_some_and(|v| v == text))
}
/// A command (or another window) changes the audio choice while the Playback Engine is closed or
/// open: the window then shows the current choice, and Apply has nothing to apply, so it never
/// puts an earlier choice back.
#[test]
fn the_playback_engine_shows_the_current_choice_after_a_command_changes_it() {
let mut h = playback_engine_harness(256);
assert!(shows(&h, "256 samples"), "the window opens on the current choice");
// Closed from the menu (not its close button), then the choice changes by command.
h.state_mut().ui.show_playback_engine = false;
h.run_steps(2);
h.state_mut().ui.audio.buffer_size = Some(512);
h.state_mut().ui.show_playback_engine = true;
h.run_steps(3);
assert!(shows(&h, "512 samples"), "reopened on the choice the command made");
assert!(!shows(&h, "256 samples"), "not on the earlier one");
// Changed while the window is open.
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(shows(&h, "1024 samples"), "an open window follows a change made elsewhere");
assert!(h.query_by_label("Revert").is_none(), "nothing to revert: no edit differs from the current choice");
}
/// Make an unapplied edit in the window: its buffer size set to `buffer`, as if chosen in its
/// Buffer size selector (the window keeps its edits with the choice they started from).
fn edit_buffer(h: &mut Harness<'_, SoundApp>, buffer: u32) {
let from = h.state().ui.audio.clone();
let draft = soundcraft_playback::AudioConfig { buffer_size: Some(buffer), ..from.clone() };
h.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("audio_draft"), (from, draft)));
h.run_steps(2);
}
/// Pro Tools' Playback Engine is a modal dialog, so nothing else changes the device while it has
/// unapplied edits (Reference Guide p. 109). This window is not modal: when a command changes the
/// choice under unapplied edits, the window takes the new choice and says the edits were replaced.
#[test]
fn the_playback_engine_says_when_a_command_replaces_its_unapplied_edits() {
const NOTE: &str = "The audio settings were changed outside this window; your unapplied changes were replaced.";
let mut h = playback_engine_harness(256);
edit_buffer(&mut h, 128);
h.run_steps(2);
assert!(shows(&h, "128 samples"), "the edit is in the window");
assert!(h.query_by_label("Revert").is_some(), "an unapplied edit");
// A command changes the buffer to 1024 while the edit is unapplied.
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(shows(&h, "1024 samples"), "the window takes the current choice");
assert!(h.query_by_label(NOTE).is_some(), "and says the unapplied edit was replaced");
assert!(h.state().ui.status.contains(NOTE), "the status line says it too: {}", h.state().ui.status);
// The next edit takes the note away.
edit_buffer(&mut h, 512);
h.run_steps(2);
assert!(h.query_by_label(NOTE).is_none(), "a new edit: the note goes");
assert!(!h.state().ui.status.contains(NOTE), "and the status line too: {}", h.state().ui.status);
// Closing also clears the status line.
let mut h = playback_engine_harness(256);
edit_buffer(&mut h, 128);
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(h.state().ui.status.contains(NOTE), "the status line says it: {}", h.state().ui.status);
h.state_mut().ui.show_playback_engine = false;
h.run_steps(2);
assert!(!h.state().ui.status.contains(NOTE), "closing clears the status line: {}", h.state().ui.status);
// A change made elsewhere with no unapplied edit replaces nothing, so nothing is said.
let mut h = playback_engine_harness(256);
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(h.query_by_label(NOTE).is_none(), "no edit was replaced");
}
-59
View File
@@ -226,65 +226,6 @@ fn a_midi_editor_behind_another_tab_leaves_the_arrows_to_the_edit_window() {
assert!((x - middle).abs() < 1.0, "Left: the clip start at {x}, the middle at {middle}");
}
/// #1627: the MIDI editor open behind another tab isn't drawn, so its key handler doesn't run and
/// its notes aren't on screen. Delete there clears the Edit selection, as it does elsewhere in the
/// Edit window, instead of doing nothing; in front, the editor still takes the key for its notes.
#[test]
fn delete_with_the_midi_editor_behind_another_tab_clears_the_edit_selection() {
let clips = |app: &SoundApp| app.engine.session().track_by_name("Keys").and_then(|t| t.playlist()).map_or(0, |p| p.clips.len());
let clip_ids = |app: &SoundApp| -> Vec<_> {
app.engine.session().track_by_name("Keys").and_then(|t| t.playlist()).map(|p| p.clips.iter().map(|c| c.id).collect()).unwrap_or_default()
};
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.ui.show_midi_editor = true;
let end: i64 = 48_000 * 600;
app.run("edit.select", json!({"tracks": ["Keys"], "start": 0, "end": end})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
app_frame(&ctx, &mut app, vec![]);
}
app.run("ui.dock", json!({"operation": "open", "panel": "history"})).unwrap();
app.run("ui.dock", json!({"operation": "move", "panel": "history", "target": "midi", "zone": "tab"})).unwrap();
for _ in 0..3 {
app_frame(&ctx, &mut app, vec![]);
}
assert!(app.ui.show_midi_editor, "the MIDI editor is still open");
assert_ne!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
let before = clip_ids(&app);
assert!(!before.is_empty());
app.midi.selected = vec![0, 1];
app_frame(&ctx, &mut app, arrow(Key::Delete));
assert_eq!(clips(&app), 0, "Delete cleared the Edit selection");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(clip_ids(&app), before, "one Undo brings every clip back");
}
/// #1627: a layout change between frames that puts another tab over the MIDI Editor counts at
/// once. The editor's body rect from the frame before is stale, and Delete clears the Edit
/// selection on the very next key, not after the dock redraws.
#[test]
fn delete_right_after_a_tab_covers_the_midi_editor_clears_the_edit_selection() {
let clips = |app: &SoundApp| app.engine.session().track_by_name("Keys").and_then(|t| t.playlist()).map_or(0, |p| p.clips.len());
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.ui.show_midi_editor = true;
let end: i64 = 48_000 * 600;
app.run("edit.select", json!({"tracks": ["Keys"], "start": 0, "end": end})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
app_frame(&ctx, &mut app, vec![]);
}
assert_eq!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
app.run("ui.dock", json!({"operation": "open", "panel": "history"})).unwrap();
app.run("ui.dock", json!({"operation": "move", "panel": "history", "target": "midi", "zone": "tab"})).unwrap();
assert_ne!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
assert!(clips(&app) > 0);
app.midi.selected = vec![0, 1];
app_frame(&ctx, &mut app, arrow(Key::Delete));
assert_eq!(clips(&app), 0, "Delete cleared the Edit selection");
}
#[test]
fn pro_tools_shift_keys_bypass_inserts_and_mute_sends() {
for os in [OperatingSystem::Mac, OperatingSystem::Windows, OperatingSystem::Nix] {
-1
View File
@@ -44,7 +44,6 @@ Errors: `{"id": 1, "ok": false, "error": "bad parameters for `mix.volume`: no tr
| `engine.parity` | `{}` | Parity report against the incumbent's menu catalog. |
| `session.inspect` | `{detail?: "summary"|"full"}` | The document: tracks, clips (with times), inserts (+params when full), sends, routing, automation, markers, groups, busses, sources (`loaded` true when decoded audio is in the pool), selection, zoom (`samples_per_px`, `scroll`), transport, undo label. |
| `ui.inspect` | `{}` | UI state (`window`, panels, dialogs), window size, playing/position, audio device, MIDI inputs (`midi_inputs`: name, enabled, open; `midi_events`: messages received so far; `midi_events_dropped`: messages a full input queue dropped), and `edit_layout` (timeline rect and every track row's rect, for clicking). |
| `audio.health` | `{reset?: bool}` | How the realtime audio path keeps up since the output opened (or the last reset): `health` holds `callbacks`, `xruns` (underruns the device reported), `late_callbacks` (callbacks that overran their buffer period; not every one is audible, and the device may report the same overrun as an xrun) and `worst_load` (slowest callback as a share of its buffer period, to 0.001; 1.0 = it overran). Also `device`, `silent`, `sample_rate` and `buffer_frames` (`null`: the device default). The first blocks create plugins and may read late, so a stress run resets once playback is under way. `reset: true` returns the reading and counts afresh from it; no event falls between the two. |
| `ui.set` | any `UiState` fields | e.g. `{"window": "Mix", "narrow_mix": true}`. |
| `ui.menu.list` | `{}` | Every catalog menu path and the command that implements it (or null). |
| `ui.menu.invoke` | `{path}` or `{id}` | Like clicking the menu item: may open its dialog (e.g. `"Track > New..."`). |
+6 -16
View File
@@ -1,6 +1,6 @@
# Where SoundCraft falls short of Pro Tools
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-28 · **Change:** minor (G-05: the signed macOS app and CLI carry the plugin-loading entitlements; previously minor: G-01: the Playback Engine shows the current device choice after a command changes it, and a buffer size the driver does not take is reported; previously trivial: G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-25 · **Change:** minor (G-01: a buffer size the driver does not take is reported; previously trivial: G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing
real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker**
@@ -52,12 +52,6 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t
not rounded onto the window's power-of-two list. Headless (CLI, no app) still stores the request
and returns `applied: false`, with `buffer_size` null when unset; playback does not read those
session values.
- **Done (2026-11-25):** the Playback Engine shows the current choice when `ui.audio_device` or
`setup.playback_engine` changed it while the window was closed or open, and Apply no longer puts
an earlier choice back. Closing the window from the menu discards unapplied edits, as its close
button does. A change made elsewhere that replaces unapplied edits is said in the window and the
status line (Pro Tools' dialog is modal, so it never meets this case). Checked on macOS (Core
Audio, RME UFX and a second input device).
- **Done (2026-11-25):** a buffer size the driver does not take is reported: `ui.audio_device`,
`setup.playback_engine` and `setup.hardware` return a `buffer_note`, `ui.audio_device` also
returns the driver's range as `device.buffer_range`, and the Playback Engine shows the note under
@@ -69,7 +63,7 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t
- **Missing:** routing to physical channels (I/O Setup), one duplex stream on one clock (input and
output are still separate cpal streams), latency reporting and record-offset compensation, ASIO
in official builds (owner decision: Steinberg's SDK is proprietary or GPLv3), JACK, and
verification on Linux. The mix still runs in fixed 512-sample blocks.
verification on macOS and Linux. The mix still runs in fixed 512-sample blocks.
- **Evidence:** code above; Playback Engine window says "Mix block size: 512 samples"; issue #42
(no input device selection, forced monitoring feedback with virtual routing).
- **Impact:** blocks tracking with any multichannel interface; latency makes overdubs hard.
@@ -150,14 +144,11 @@ launch #142; Linux #45, #107.
### G-05. Plugin hosting on macOS
- **Fixed (pending release):** the `com.apple.security.cs.disable-library-validation` and
`com.apple.security.cs.allow-unsigned-executable-memory` entitlements are now in
`entitlements.plist` and applied to the app and the CLI (#153, #149); verify on a signed build
with `codesign -d --entitlements - SoundCraft.app` and a third-party VST3.
- **Missing:** AU editor views
- **Missing:** the `com.apple.security.cs.disable-library-validation` entitlement in the signed
build, so hardened runtime refuses third-party VST3 bundles (#153, #149). AU editor views
(`crates/au-host/src/lib.rs` header: "Not hosted yet: Audio Unit editor views"). Embedded CLAP
GUIs on macOS (#485). VST3 and embedded CLAP editors are hosted on Windows and Linux/X11.
- **Estimate:** ≈ 9–14 h (AU Cocoa views and embedded CLAP on macOS).
- **Estimate:** ≈ 10–15 h (entitlement ≈ 1 h; AU Cocoa views and embedded CLAP on macOS most of it).
### G-06. Memory-bound media
@@ -269,8 +260,7 @@ missing. Out of scope unless the owner decides otherwise.
| Date | Change | Summary |
|---|---|---|
| 2026-11-28 | minor | G-05: library-validation and unsigned-executable-memory entitlements for the macOS app and CLI, so signed builds load third-party plugins (#153, #149); G-05 estimate ≈ 9–14 h |
| 2026-11-25 | minor | G-01: the Playback Engine shows the current device choice after a command changes it, and Apply keeps it; a buffer size the driver does not take is reported, with the driver's range (#1757); estimates unchanged |
| 2026-11-25 | minor | G-01: a buffer size the driver does not take is reported, with the driver's range (#1757); estimates unchanged |
| 2026-11-23 | trivial | G-04: Clip Looping Number of Loops accepts up to 1,000; crossfade remains open; estimates unchanged |
| 2026-11-14 | minor | G-03: strict external-WAV AAF import with bounded property caching; AAF/OMF export, OMF import and `.ptx` remain; estimates unchanged |
| 2026-11-13 | trivial | G-09: the pt-BR catalog now covers tooltips localized inside buttons and toggles, the Edit-window status bar, the remove-session question, the send help text and engine errors shown in the status line; estimates unchanged |
+4 -4
View File
@@ -1,6 +1,6 @@
# Hardware parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (the Playback Engine shows the current device choice after a command changes it; buffer sizes verified on Core Audio; one the driver does not take is reported; previously minor: record to disk: done, #84 and #888, previously trivial: bounces of a bus fed by an aux compensate its latency, #246; previously minor: MIDI input devices, live play-through with controllers, and MIDI recording) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (buffer sizes verified on Core Audio; one the driver does not take is reported; previously minor: record to disk: done, #84 and #888, previously trivial: bounces of a bus fed by an aux compensate its latency, #246; previously minor: MIDI input devices, live play-through with controllers, and MIDI recording) · **Target:** Avid Pro Tools Ultimate 2026.4.1
A DAW is judged by how it drives audio interfaces, MIDI gear, control surfaces and sync. This is
SoundCraft's weakest dimension. Ours is measured from `crates/playback` (cpal) and the absence of
@@ -16,8 +16,8 @@ Legend: ✅ works · 🟡 partial · ❌ missing.
| Feature | Pro Tools (macOS / Windows) | SoundCraft macOS | Windows | Linux | FreeBSD | Web |
|---|---|---|---|---|---|---|
| Driver API | Core Audio / ASIO | 🟡 Core Audio via cpal | 🟡 WASAPI shared via cpal; ASIO with the opt-in `asio` build feature (verified with an SSL 2+) | 🟡 ALSA/Pulse via cpal; no JACK | 🟡 cpal (ALSA layer) | 🟡 Web Audio |
| Choose playback device | ✅ Playback Engine | ✅ Setup › Playback Engine and `ui.audio_device` (verified with an RME UFX and the built-in speakers; the window shows a choice made by command) | ✅ Setup › Playback Engine (WASAPI, ASIO) | 🟡 (not yet verified) | 🟡 (not yet verified) | ❌ |
| Choose input device | ✅ | ✅ Setup › Playback Engine and `ui.audio_device` (verified with an RME UFX and a second input device) | ✅ (WASAPI, ASIO) | 🟡 (not yet verified) | ❌ no recording | ❌ |
| Choose playback device | ✅ Playback Engine | 🟡 Setup › Playback Engine (not yet verified on macOS) | ✅ Setup › Playback Engine (WASAPI, ASIO) | 🟡 (not yet verified) | 🟡 (not yet verified) | ❌ |
| Choose input device | ✅ | 🟡 Setup › Playback Engine (not yet verified on macOS) | ✅ (WASAPI, ASIO) | 🟡 (not yet verified) | ❌ no recording | ❌ |
| Buffer size (32–2048) | ✅ | 🟡 device buffer when the driver allows it (16–2048 verified on an RME UFX, whose driver allows 15–3072); outside the driver's range the default buffer, and the Playback Engine says so; mix in 512-sample blocks | 🟡 device buffer 16–8192 (verified 128 on ASIO, 256 on WASAPI); mix in 512-sample blocks | 🟡 (not yet verified) | 🟡 | ❌ |
| Duplex stream on one clock | ✅ | ❌ separate input/output streams | ❌ | ❌ | ❌ | ❌ |
| Hardware I/O mapping (I/O Setup to physical channels) | ✅ | 🟡 multichannel output in order; no per-channel map | 🟡 | 🟡 | 🟡 | ❌ |
@@ -72,7 +72,7 @@ Legend: ✅ works · 🟡 partial · ❌ missing.
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | minor | Choosing the playback and input device verified on macOS; the Playback Engine shows a choice made by command; buffer sizes 16–2048 verified on Core Audio; a size the driver does not take is reported with its range (#1757) |
| 2026-11-25 | minor | Buffer sizes 16–2048 verified on Core Audio; a size the driver does not take is reported with its range (#1757) |
| 2026-11-18 | minor | MIDI input devices (`midir`): live play-through to record-enabled MIDI and instrument tracks (notes, pedal, controllers, pitch bend, aftertouch), MIDI recording into clips, per-track device and channel, device switches in Playback Engine; guide in `midi-input.md` |
| 2026-10-30 | minor | Record to disk: takes are written to disk as they record (#84) and long takes continue in a new file (#888) |
| 2026-10-13 | trivial | bounces of a bus fed by an aux compensate its latency (#246) |
+9 -13
View File
@@ -1,10 +1,8 @@
# Localization parity
> **Last reviewed:** 2026-11-13 · **Last updated:** 2026-11-27 · **Change:** minor (Spanish catalog completed, with native-speaker terminology review; previously minor: French and Spanish catalogs, partial; previously minor: pt-BR catalog completed: all fixed UI strings translated and covered by tests; native-speaker review, CJK/RTL font fallbacks and RTL script shaping still pending) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-13 · **Last updated:** 2026-11-13 · **Change:** minor (pt-BR catalog completed: all fixed UI strings translated and covered by tests; native-speaker review, CJK/RTL font fallbacks and RTL script shaping still pending) · **Target:** Avid Pro Tools Ultimate 2026.4.1
SoundCraft defaults to English and supports selecting Brazilian Portuguese, French and Spanish. The
Spanish catalog covers the same fixed UI strings and engine errors as pt-BR; the French catalog is
partial (missing strings show in English). The pt-BR catalog
SoundCraft defaults to English and supports selecting Brazilian Portuguese. The pt-BR catalog
covers all fixed UI strings found in the current source: command labels, menus, Appearance,
About/Credits, Audio Health, Playback Engine, System Usage, Workspace, plugin parameter and display
names, dialogs and buttons, tooltips (including those localized inside buttons and toggles),
@@ -22,17 +20,17 @@ CJK/Devanagari/Arabic (PR #141 open), RTL layout and complex-script shaping (egu
≈ 25–40 h, or ship Arabic/Hindi menus-only), then ≈ 3–5 h of agent translation per language, plus
native-speaker review (human).
Open work: completing the French catalog (rows also kept in storytold/craft-i18n for
when SoundCraft reads it), PR #141 (bundled multilingual font fallbacks), issue #67 (Ukrainian).
Open work: PR #143 (French and Spanish, a
Language setting), PR #141 (bundled multilingual font fallbacks), issue #67 (Ukrainian).
| Language | Code | UI strings translated | Dialogs / tooltips / help | Script support | Native review | Status | Est. to full (h) | In Pro Tools |
|---|---|---|---|---|---|---|---:|---|
| English | en | all (source) | ✅ | Latin ✅ | — | **full** | 0 | ✅ |
| Simplified Chinese | zh-Hans | 0 (0 %) | ❌ | ❌ no CJK font fallback, no IME testing | no | none | 6–10 | ✅ |
| Spanish | es | ✅ 100 % of fixed UI strings (1,960) and engine errors (254), as pt-BR; catalog and menu-coverage tests pass | 🟡 partial | Latin ✅ | yes (es-ES, sound engineer; terminology reviewed) | full | 0–2 | ✅ |
| Spanish | es | 0 (0 %) — PR #143 pending | ❌ | Latin ✅ | no | none | 3–5 | ✅ |
| Hindi | hi | 0 (0 %) | ❌ | ❌ no Devanagari font or shaping | no | none | 8–15 | ❌ |
| Arabic | ar | 0 (0 %) | ❌ | ❌ no RTL layout, no shaping | no | none | 15–25 | ❌ |
| French | fr | 🟡 1,368 of ~2,210 catalog strings (≈ 62 %); engine errors not yet translated | 🟡 partial | Latin ✅ | no | partial | 1–3 | ✅ |
| French | fr | 0 (0 %) — PR #143 pending | ❌ | Latin ✅ | no | none | 3–5 | ✅ |
|| Portuguese (Brazil) | pt-BR | ✅ 100 % of fixed UI strings: menus, dialogs, buttons, tooltips, accessibility names, status bar, formatted messages and engine errors; catalog tests pass | 🟡 partial | Latin ✅ | no (native review pending) | full | 0–4 | ❌ |
| Indonesian | id | 0 (0 %) | ❌ | Latin ✅ | no | none | 3–5 | ❌ |
| Japanese | ja | 0 (0 %) | ❌ | ❌ no CJK font fallback, no IME testing | no | none | 6–10 | ✅ |
@@ -47,20 +45,18 @@ Per-language hours exclude the shared catalog and script work above.
## Usage
- Pick the language in Appearance ▸ Language, or run the `ui.language` command with
`{"language": "pt-BR"}` (or `"en"`, `"fr"`, `"es"`); with no parameter it reports the current language.
`{"language": "pt-BR"}` (or `"en"`); with no parameter it reports the current language.
Example: `soundcraft-cli run --demo --cmd 'ui.language={"language":"pt-BR"}'`.
- The choice is a global preference saved with the UI state (like the theme); recalling a saved
window configuration does not change it.
- Strings missing from the catalog fall back to English. Add one with a `"English text" => "translated text"`
arm in `crates/ui-egui/locales/<tag>/mod.rs`; tests check placeholder parity, duplicates and that every
string passed to `text` / `localized_format!` has a pt-BR entry.
arm in `crates/ui-egui/locales/pt-BR/mod.rs`; tests check placeholder parity, duplicates and that every
string passed to `text` / `localized_format!` has an entry.
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | minor | Completed the Spanish catalog (all fixed UI strings and engine errors) with a native-speaker terminology review; Spanish menu-coverage test; the path prompt's `File path` and `Folder path` fields are translated apart from the Auto Pan `Path` parameter |
| 2026-11-24 | minor | French and Spanish catalogs (`locales/fr`, `locales/es`, 1,368 strings each) from PR #143, on the `localization` layer; Appearance ▸ Language lists them; estimates unchanged |
| 2026-11-13 | minor | Completed the pt-BR catalog: tooltips passed to buttons and toggles, `Not available yet.`, the send hover help, `no instrument`, the search placeholders, the Edit-window status bar (bit depth, track count, undo, ms/frame), the remove-session question and the transport/sample-rate readouts; engine errors now reach the status line through `error_text` |
| 2026-11-05 | minor | Added persisted language selection, the `ui.language` command, English fallback and a pt-BR catalog (menus, dialogs, tooltips, accessibility text, formatted messages); added a Usage section and catalog tests |
| 2026-10-10 | major | Created: English only, no catalog; the twelve key languages at 0 %; Pro Tools' 8 languages listed from its bundle |
+2 -6
View File
@@ -90,12 +90,8 @@ plugins), and WebAudio in the browser.
the default player. `NSMicrophoneUsageDescription` explains the recording prompt.
- **Signing** goes inside-out with the hardened runtime and a secure timestamp. The executable is
signed first, then the bundle. There's no `--deep` on the final signature. `entitlements.plist`
holds three exceptions: `com.apple.security.device.audio-input`, without which the hardened
runtime blocks recording; `com.apple.security.cs.disable-library-validation`, without which
`dlopen` refuses every third-party VST3/CLAP/AU bundle (signed by another Team ID); and
`com.apple.security.cs.allow-unsigned-executable-memory`, without which plugin runtimes that
create executable memory without `MAP_JIT` (UADx/PACE) are killed at load. The CLI is signed
with the same entitlements because it hosts plugins too.
holds a single exception, `com.apple.security.device.audio-input`, without which the hardened
runtime blocks recording.
- **Notarization:** the app is zipped and sent with `xcrun notarytool submit --wait`, then the
ticket is stapled to the app. The app goes on a DMG (`hdiutil`, with an `Applications` link).
The DMG is signed, notarized and stapled too.
+2 -4
View File
@@ -1,6 +1,6 @@
# SoundCraft roadmap: milestones and what's next
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (M15: Spanish catalog complete; previously trivial: M15: French and Spanish catalogs, partial; previously minor: M6: long takes continue in a new file (#888); previously minor: MIDI input landed, the gate row needs checking on macOS and Windows; strict external-WAV AAF import; previously trivial: 28 built-in processors with the Frequency Shifter; G-05 estimate after Linux/X11 plugin editors; M15: partial pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (M6: long takes continue in a new file (#888); previously minor: MIDI input landed, the gate row needs checking on macOS and Windows; strict external-WAV AAF import; previously trivial: 28 built-in processors with the Frequency Shifter; G-05 estimate after Linux/X11 plugin editors; M15: partial pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1
Forward-looking plan. Status and numbers: [`../ROADMAP.md`](../ROADMAP.md) and
[`target-app-parity.md`](target-app-parity.md); the ranked work list: [`gaps.md`](gaps.md).
@@ -49,7 +49,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started.
| M12 | **Hardware**: audio interfaces, MIDI devices, sync, control surfaces | ⬜ | 110–180 |
| M13 | **Interchange**: AAF/OMF import/export, disk streaming | 🟡 strict external-WAV AAF import; export, OMF and disk streaming missing | 65–115 |
| M14 | **Fidelity harness** against Pro Tools (null tests, plugin responses) | ⬜ | 20–30 |
| M15 | **Localization**: catalog, fonts/RTL, the 8 Pro Tools languages first | 🟡 partial (pt-BR catalog; Spanish complete; French partial; pt-BR needs native review; PR #141 open) | 45–80 |
| M15 | **Localization**: catalog, fonts/RTL, the 8 Pro Tools languages first | 🟡 partial (pt-BR catalog; needs native review; PRs #141, #143 open) | 45–80 |
| M16 | Built-in plugin depth, sidechain, ARA | ⬜ | 110–170 |
| M17 | Immersive delivery (ADM BWF, object renderer, binaural) and video depth | ⬜ | 80–130 |
@@ -88,8 +88,6 @@ There is no `cargo xtask scorecard` in this repo; the measured number is `cargo
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | trivial | M15: Spanish catalog complete (UI strings and engine errors, native-speaker review). Estimates unchanged |
| 2026-11-24 | trivial | M15: French and Spanish catalogs (partial, ≈ 62 %) on the `localization` layer (#143). Estimates unchanged |
| 2026-11-18 | minor | MIDI input devices landed (G-02 shrunk); the MIDI gate row is unverified until checked on macOS and Windows |
| 2026-11-14 | minor | M13 is in progress with strict external-WAV AAF import; the exchange gate still fails without AAF export, OMF or `.ptx`; estimates unchanged |
| 2026-11-09 | trivial | 28 built-in processors with the Frequency Shifter |
-89
View File
@@ -1,89 +0,0 @@
# Send pan and mute automation
Last reviewed: 2026-10-14. Last updated: 2026-10-14.
Bus sends read supported `SendPan` and `SendMute` automation during mixing. Pan automation
covers mono sources sent to ordinary stereo buses. Mute automation gates ordinary bus routes
using the existing channel-routing matrix.
## Reading and fallback
A valid nonempty lane in an automation mode that reads overrides the corresponding static send
control. A pan lane interpolates between knots and clamps finite values to -1 through 1. A mute
lane holds each knot's value, clamps to 0 through 1 and gates the send at values of at least 0.5.
Before the first knot, the reader holds its first value; at duplicate timestamps it uses the last
knot at that position.
Off mode, an absent or empty lane, nonfinite point values or decreasing timestamps use the
static control for the entire callback. This reader follows the existing mixer convention:
`lane.enabled` does not independently gate reading. Global lane-enable and suspension semantics
remain the existing mixer policy.
Each callback builds local forward cursors at the source-sample time represented by its send
buffer. Seeking, looping or rendering irregular chunks does not reuse a cursor from an earlier
callback. Reader initialization and per-frame lookup share that clock. Position, frame offset
and sample age are combined in widened arithmetic before clamping once to the supported bounds.
## Delay accounting
Audio send clocks account for processor-declared active insert latency and alignment already
applied to the selected buffer. Insert ages accumulate separately from the bounded delay-
compensation field; its safety cap does not shorten a send's clock. This assumes processors
report their delay accurately. Aux and folder sends also carry the upstream input bus's sample age, including
known ages propagated through nested Aux paths. Post-fader Aux buffers include their applied
alignment; the existing pre-fader Aux copy does not receive that alignment and uses its own age.
Pre-fader audio-track buffers do receive their existing pre-fader alignment.
Direct bus outputs contribute the age after any additional output delay. A send tap excludes
that later output delay, receiving processors and Master processing. Audio processing, routing,
delay-line placement and offline latency removal retain their existing behavior.
Bus age metadata is rebuilt with each block and introduces no new dynamic collection. Equal
known contribution ages retain a shared source clock. A sum of differently delayed contributors
has no single source age; mixed or overflowing age metadata retains the earlier render-position
clock for these send readers. This preserves the existing mixed-routing policy and does not
claim complete graph delay compensation. Empty bus inputs use zero upstream age. When delay
compensation is off, a known path still accounts for its actual processor delay.
## Routing compatibility
Without a qualifying pan lane, routing uses the current static matrix. Mono sends retain their
static send pan; stereo sends retain their left/right routing even when a stored static send pan
is nonzero. Automated stereo-send pan is outside this contribution.
A supported mute lane can override the static send mute, including unmuting it. Track mute and
the existing solo/VCA suppression still take precedence. Pre-fader sends use the existing
pre-fader buffer, post-fader sends use the existing processed buffer, and send level keeps its
current reader and timing policy.
Mute gating preserves the ordinary matrix for mono folds, stereo and supported surround widths.
Ambisonic routes and non-bus sends keep their existing handling. Main outputs, master processing,
audio delay compensation, hosted-plugin parameter delivery and routing-error policies are unchanged.
## Callback work and verification
Pan gains are computed per sample only for supported automated mono-to-stereo sends. Mute uses
a stepped gate at each sample. Static routing matrices and gated-path sparse taps are prepared outside the
sample loop; automated mono-pan routing needs no matrix. The new helpers use local cursors and fixed
stack storage without introducing heap allocation.
Lane validity is scanned once per callback over its stored points. Worst-case callback CPU and
the allocation behavior of the complete mixer remain unmeasured.
Synthetic regressions exercise independent PCM expectations, all pan laws, mute knots, static
fallback, pre/post-fader routing, send level, irregular chunks, seek/loop behavior, hostile
timestamps and short buffers. Engine cases cover command history and native save/reopen.
Static stereo compatibility checks use nonzero stored send-pan values and unchanged routing
references.
Latency regressions cover the unrelated silent Maximizer case, pan and mute source clocks,
Aux pre/post taps, nested upstream paths, subsequent output/processor delay, mixed-age fallback,
negative positions and reset/seek behavior with synthetic audio.
Unit regressions also check insert-age accounting beyond the delay-compensation cap and age overflow.
This contribution is limited to these send readers and bus-routing branches.
## Revision history
- 2026-10-14: Document supported bus-send automation, fallback, stereo compatibility and callback-work limits.
- 2026-10-14: Account for the actual delayed send tap and known upstream bus ages; retain mixed-age timing limits.
+2 -12
View File
@@ -1,20 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Hardened-runtime entitlements for SoundCraft. The host is Rust, loads third-party plugins,
and is not sandboxed (it opens files by path, from the command line and
<!-- Hardened-runtime entitlements for SoundCraft. The app is pure Rust, loads no unsigned code,
needs no JIT, and is not sandboxed (it opens files by path, from the command line and
drag-and-drop). Add exceptions here only with a reason in a comment. -->
<plist version="1.0">
<dict>
<!-- VST3/CLAP/AU plugins are signed by their own developers (or ad hoc for local builds).
Library validation otherwise rejects these modules in the signed host, even when
discovery succeeds in an unpackaged build. -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<!-- Third-party plugin runtimes can create executable memory without MAP_JIT. UADx/PACE
initialisation is killed with CODESIGNING/Invalid Page without this exception; allow-jit
alone does not suffice. Keep executable-page protection and the hardened runtime enabled. -->
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<!-- Recording: the hardened runtime blocks audio input (CoreAudio via cpal) without this,
even after the user grants microphone access (NSMicrophoneUsageDescription). -->
<key>com.apple.security.device.audio-input</key>
+2 -3
View File
@@ -33,12 +33,11 @@ OUTPUT="$DIST/soundcraft-$VERSION-macos-aarch64-nightly.zip"
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/SoundCraft"
chmod 755 "$APP/Contents/MacOS/SoundCraft"
cp "$ROOT/assets/app-icon/soundcraft-nightly.icns" "$APP/Contents/Resources/soundcraft-nightly.icns"
# Launcher admits notices under Resources/docs, not beside the icon.
nightly_copy_notices "$APP/Contents/Resources/docs"
nightly_copy_notices "$APP/Contents/Resources"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
+2 -74
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
import base64
import importlib.util
import json
@@ -27,8 +27,6 @@ COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"soundcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "SoundCraft Nightly.app"
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
@@ -185,44 +183,6 @@ class Fixture:
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def package(self):
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
source = HERE.parents[1]
checkout = self.root / "source"
checkout.mkdir()
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
"assets/app-icon/soundcraft-nightly.icns"):
target = checkout / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / relative, target)
env = self.env(**dict.fromkeys(SECRETS))
def git(*args):
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
git("init", "-q")
git("add", "--", ".")
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
commit = git("rev-parse", "HEAD").strip()
version = VERSION[:-12] + commit[:12]
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
(self.bin / "cargo").write_text(
'#!/bin/sh\nset -eu\n'
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/soundcraft"\n'
'mkdir -p "$(dirname "$gui")"\n'
"printf \"#!/bin/sh\\necho 'SoundCraft %s (nightly-v1)'\\n\" \"$SOUNDCRAFT_VERSION\" >\"$gui\"\n",
)
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"),
SOUNDCRAFT_BUILD_CHANNEL="nightly-v1", SOUNDCRAFT_VERSION=version,
SOUNDCRAFT_BUILD_SHA=commit, SOUNDCRAFT_BUILD_DATE="2026-11-23")
assert result.returncode == 0, result.stdout
return self.dist / ASSET.replace(VERSION, version)
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
@@ -450,38 +410,6 @@ class Verify(unittest.TestCase):
class Build(unittest.TestCase):
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
f = Fixture(self)
archive = f.package()
source = HERE.parents[1]
resources = f"{APP}/Contents/Resources"
icon = "soundcraft-nightly.icns"
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
contents = f"{APP}/Contents"
gui = f"{contents}/MacOS/SoundCraft"
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = {entry.filename for entry in entries}
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
for path, data in expected_files.items():
with self.subTest(path=path):
self.assertEqual(zipped.read(path), data)
mode = zipped.getinfo(path).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode))
self.assertFalse(mode & 0o111)
mode = zipped.getinfo(gui).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
self.assertEqual(result.returncode, 0, result.stdout)
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
+1 -3
View File
@@ -212,9 +212,7 @@ CLI_DIR="$WORK/soundcraft-cli-$VERSION-macos-$ARCH"
mkdir -p "$CLI_DIR"
cp "$WORK/bin/soundcraft-cli" "$CLI_DIR/"
copy_docs "$CLI_DIR"
# The CLI runs the same engine and hosts plugins too, so it needs the same entitlements (the
# plugin exceptions) or third-party plugins fail to load there as well.
sign --options runtime --entitlements "$HERE/entitlements.plist" "$CLI_DIR/soundcraft-cli"
sign --options runtime "$CLI_DIR/soundcraft-cli"
codesign --verify --strict --verbose=2 "$CLI_DIR/soundcraft-cli"
rm -f "$CLI_ZIP"
ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP"
+6 -96
View File
@@ -10,12 +10,6 @@ ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# The pinned shared registry enables Windows, Linux and macOS for SoundCraft.
SIGNER_SECRETS = {
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
}
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
@@ -49,49 +43,6 @@ def assert_nightly_serialization(source):
raise ValueError("nightly serialization must use its stable group and no cancellation")
def caller_entries(lines, indent):
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
entries = {}
children = None
for line in lines:
if children is not None and line.startswith(" " * (indent + 1)):
children.append(line)
continue
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
if row is None or row[1] in entries:
raise ValueError("malformed or duplicate caller mapping entry")
children = []
entries[row[1]] = row[2], children
return entries
def assert_caller_secrets(source, job_name, names):
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
root = caller_entries(lines, 0)
job_marker, job_lines = root.pop("jobs", (None, []))
jobs = caller_entries(job_lines, 2)
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
raise ValueError("the caller must have one plain job block")
job = caller_entries(jobs[job_name][1], 4)
if "environment" in job or "environment" in root or "secrets" in root:
raise ValueError("only the native callee may bind the environment")
if names:
if "secrets" not in job:
raise ValueError("signer requires an explicit target-specific secret map")
mode, secret_lines = job.pop("secrets")
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
if mode is not None or caller_entries(secret_lines, 6) != expected:
raise ValueError("signer must forward exactly the reviewed same-name secret references")
elif "secrets" in job:
raise ValueError("unsigned caller must not pass secrets")
for value, children in (*root.values(), *job.values()):
outside_map = "\n".join([value or "", *children])
# Scan all remaining text: quoted braces can appear before a secret reference.
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
raise ValueError("secret bindings belong only in the signer map")
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
lines = jobs.splitlines()
@@ -148,7 +99,7 @@ def reviewed_manual_actors(caller_source, policy):
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: (\S+)$",
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$",
(ROOT / ".github/workflows" / name).read_text())[0]
@@ -228,49 +179,8 @@ class TrustedSourcePreparation(unittest.TestCase):
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
header = " secrets:\n"
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
self.assertIn(linux, signer)
mutations = {
"missing name": signer.replace(linux, ""),
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
"duplicate name": signer.replace(linux, linux + linux),
"duplicate map": signer + header + linux,
"quoted duplicate map": signer + ' "secrets": inherit\n',
"inherit": signer.split(header)[0] + " secrets: inherit\n",
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
"yaml merge": signer + " <<: *other\n",
"environment": signer + " environment: release\n",
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
}
for change, source in mutations.items():
with self.subTest(change=change), self.assertRaises(ValueError):
assert_caller_secrets(source, "release", SIGNER_SECRETS)
def test_unsigned_caller_has_no_secrets(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
assert_caller_secrets(producer, "unsigned", set())
for suffix in (" secrets: {}\n", " secrets: inherit\n",
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
assert_caller_secrets(producer + suffix, "unsigned", set())
def test_unsigned_caller_refuses_secret_after_format_brace(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
# This inert fixture is never dispatched; the brace is part of the format string.
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
assert_caller_secrets(source, "unsigned", set())
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
class NightlyTrustAnchors(unittest.TestCase):
@@ -307,7 +217,7 @@ class NightlyTrustAnchors(unittest.TestCase):
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
class NightlyEnabledCallers(unittest.TestCase):
@@ -719,7 +629,7 @@ def trust_closure_problems(workflows):
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or ref != "main":
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
@@ -769,7 +679,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}
+2 -16
View File
@@ -87,19 +87,5 @@ A browser with neither WebGPU nor WebGL2 gets a message in place of the app.
Playback goes through WebAudio. Browsers only start an `AudioContext` after a user gesture, so
the first click or key press in the page may be needed before sound is heard. In an iframe,
`allow="autoplay"` lets the embedding page grant that up front. The web build has no recording
and no native file dialogs; it opens the synthesised demo session. There is no TCP control channel, but the page can drive the same one through `window.soundcraft` (below).
## Driving it from the page (`window.soundcraft`)
Every SoundCraft web build puts `window.soundcraft` on the page, from [`craft-web-api`](https://github.com/storytold/craft-libs/tree/main/crates/web-api) (storytold/craft-libs#413), the same shape in every Craft app. `soundcraft.request(method, params)` calls any method of the control channel the desktop app serves (`docs/control-protocol.md`), and `execute(command, params)`, `commands()`, `docInspect(params)`, `uiInspect(params)` and `screenshot(params)` are shortcuts for the common ones. Each returns a Promise that resolves with the method's result and rejects with an `Error`; a call the app does not answer within 30 seconds rejects. At most 64 calls wait for the app at once: a call made while that many wait rejects at once, as busy. SoundCraft's control requests cannot be withdrawn, so a call that times out in the page still runs when the app reaches it, as it does for a desktop client that timed out.
```js
const session = await soundcraft.docInspect(); // tracks, clips, routing
await soundcraft.execute("track.new", { count: 2, format: "Stereo" });
const { data } = await soundcraft.screenshot(); // the window as PNG (base64)
```
The API is installed in every session. Playback still needs a user gesture before the browser starts audio.
The repository holds a real-browser check of this API, `apps/soundcraft-web/tests/page-api.mjs`. It serves a built copy of the site (`trunk build --release` in `apps/soundcraft-web`, or the unpacked zip), loads it in headless Chromium with Playwright, and drives all six functions, a command that changes the session, the rejection of an unknown method and of an unknown command, the screenshot, several calls at once, and a burst of calls beyond the limit (the ones over it are refused as busy, and a call afterwards is accepted). Run it with `node apps/soundcraft-web/tests/page-api.mjs <site folder>` from a folder where `playwright` is installed. It is not part of `cargo xtask ci`.
`allow="autoplay"` lets the embedding page grant that up front. The web build has no recording,
no native file dialogs and no control channel; it opens the synthesised demo session.