mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-06 12:37:59 -06:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e700934fd | ||
|
|
e5122485bb | ||
|
|
c54d2c33b3 | ||
|
|
a52bbdccbe | ||
|
|
7e58c3a617 | ||
|
|
89bd8d86ff | ||
|
|
487b5ebde0 | ||
|
|
04878f8fda |
@@ -83,9 +83,7 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [SoundCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
if: >-
|
||||
github.repository == 'storytold/soundcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/soundcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/soundcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/soundcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/soundcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'soundcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -1,10 +1,8 @@
|
||||
name: SoundCraft unsigned nightly
|
||||
|
||||
# Runs automatically on the reviewed nightly schedule and for supervised manual runs
|
||||
# by the reviewed manual actors.
|
||||
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and a reviewed dispatcher with it).
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 5 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
Generated
-9
@@ -1478,14 +1478,6 @@ dependencies = [
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -5984,7 +5976,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
"craft-audio",
|
||||
"craft-nightly",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
|
||||
@@ -79,7 +79,6 @@ craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/c
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
@@ -216,9 +216,7 @@ The realtime audio thread never writes a record itself: the logger keeps the fir
|
||||
Everything you can click is also a command with an id and JSON parameters, and the same commands
|
||||
are reachable from the menus, the keyboard, the command line, a JSON control channel and an
|
||||
[MCP](https://modelcontextprotocol.io) server. Programmatic calls never open dialogs, and
|
||||
`session.inspect` returns the session's current state (tracks, clips, mixer, markers) and the
|
||||
last undo and redo step labels, so an agent can check its own work by comparing inspections from
|
||||
before and after.
|
||||
`session.inspect` reports exactly what changed, so an agent can check its own work.
|
||||
|
||||
```sh
|
||||
# Headless: load the demo, turn the kick down, add an EQ, bounce.
|
||||
@@ -353,8 +351,6 @@ RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Current prebuilt FreeBSD release packages require FreeBSD 15.1 or later. They are built using the shared FreeBSD 15.1-STABLE release target; older FreeBSD releases are not supported by these binaries.
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `soundcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
|
||||
+1
-7
@@ -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: room tone fill, strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (Languages table: Spanish full; previously trivial: French and Spanish partial; previously minor: long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
|
||||
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
|
||||
@@ -125,9 +125,7 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
## Progress log
|
||||
|
||||
- **2026-11-18 (MIDI input):** MIDI input devices: keyboards play record-enabled and input-monitored MIDI and instrument tracks live and are recorded into MIDI clips, with a device and channel choice per track. The device switches are in the MIDI inputs section of Setup › Playback Engine (Setup › MIDI › MIDI Input Devices opens the same window) and are kept in the app preferences, per computer, not in the session. Controllers, pitch bend and aftertouch reach the instrument live; a pitch held on two devices or channels sounds until both release it; a full input queue releases the notes of its device and marks the take incomplete. On Linux, live play was checked with a hardware keyboard (Akai MPK mini 3) and recording with a virtual one; macOS and Windows are type-checked only, and there is no MIDI input on FreeBSD or the web. Guide: `docs/midi-input.md`. No readiness percentage change until that is measured.
|
||||
- **2026-11-15 (27 October–15 November recap):** Releases v0.14.0 through v0.20.1; clips draw as a small name pill with shared cut seams, alternate playlist lanes draw on screen and rating stars follow their own switch; the Edit window's I/O column sets volume and pan; edit modes, playback and record colours; Grid and Nudge time scales; a new-tracks workflow; Smart Tool/Pencil shortcuts, held zoom keys, track-colour Color Palette, Sub-counter format menu, searchable I/O menus, scrolling menus, distinct link icons and Insertion Follows Playback; folder-track indentation, stereo input pairs, sends that open their Send window, Alt-click marker deletion and selection-aware Clip menus; the playback engine applies the chosen device and buffer (#1077) and volume automation is read at every sample (#1355); a 256 MiB session cap with a tree-free parser (#892), overflow and bounds hardening across H.264, FLAC, WAV, CAF, tempo, grid, automation and timecode, MIDI tempo/track-flood limits (#890), bounded command journal and score output (#995, #993), clip-FX gain and send-level clamps (#884), clip-group path-traversal rejection and VST3 multi-out instruments with up to 64 buses; MIDI export keeps only the notes a trimmed clip plays, key signatures follow Insert/Cut Time, score export keeps short-bar notes and strips XML-forbidden characters, and WAV bounces carry BWF timecode; Enter presses the default button only without button focus (#1243), the 1/4t quantize grid (#1453), VST3 scan paths (#1450) and portable.txt (#1341) are fixed, CLAP resets keep note-offs (#1464, #1470) and hosted plugins learn when they render offline; the #1144 demo benchmark recorded about a 20 % faster mix bounce on its stated setup; shared craft-update with Flatpak self-update and Linux signing fixes, and a nightly release dry run (#1508); session format and H.264/ProRes codecs move to craft-libs, and audio formats to craft-audio; commands --json (#744), malformed control requests close the connection and Import Audio Browse selects several files (#1089). This is a historical summary, not a new measurement of readiness.
|
||||
- **2026-11-14:** AAF import supports a strict CompositionMob SourceClip/Filler subset with external mono/stereo PCM WAV media, editable clips and handles, relink and absolute or relative timecode mapping. The reader shares cached object properties, caps retained property data at 128 MiB and rejects duplicate local references before expansion. AAF export, OMF and `.ptx` remain missing. No readiness percentage change.
|
||||
- **2026-11-12:** Edit › Room Tone fills gaps with recorded silence instead of digital silence, beyond Pro Tools' own menus. Set Room Tone (`edit.room_tone_set`) takes the selected clip, or the selected part of it, as the session's room tone, and the session file keeps it. Fill Gaps with Room Tone (`edit.room_tone_fill`) puts ordinary, editable clips of that tone in every empty stretch of the selection on the selected audio tracks. When a gap is longer than the tone, the clips overlap with equal-power crossfades (10 ms by default) so the background keeps its level, and each gap's edges get a 2 ms fade so it doesn't click. Clear Room Tone forgets the tone and keeps the clips. A synthesised tone that doesn't repeat comes later. No readiness percentage change.
|
||||
- **2026-11-09:** A built-in Frequency Shifter (`freq_shifter`) moves every frequency in the signal by the same number of hertz, from 0.01 Hz to 5 kHz: up, down, both ways at once, or down on the left and up on the right of a stereo track. The unwanted sideband stays at least 100 dB down from 20 Hz to 20 Hz below Nyquist at 44.1 to 96 kHz. Feedback sends the output round again for a trail of further shifts, Mix blends in the dry signal, and every change glides without a click. No readiness percentage change.
|
||||
- **2026-11-08:** Command-click near an existing automation breakpoint keeps that point as the click target with every active tool, and existing fade and clip-gain controls retain their normal priority. Empty automation space shows a crosshair and an insertion hint while Command is held. The active tool's drag gestures stay unchanged. No readiness percentage change.
|
||||
- **2026-11-05:** Command-click in an automation lane adds a point at the clicked time and value with the current editing tool (#1394), using the existing Pencil mapping. Command-click preserves the existing selection and also works on the fallback volume lanes of Master, Aux and VCA tracks. Plain clicks and clip contents stay unchanged, and one Undo removes the new point. No readiness percentage change.
|
||||
@@ -135,12 +133,10 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
- **2026-10-27 (plugin editors on Linux):** VST3 editors and embedded CLAP editors open in a SoundCraft X11 host window on Linux and the BSDs (XWayland on Wayland desktops), resized on request and closed from its title bar; the host run loop (VST3 `Linux::IRunLoop`, CLAP `timer-support` and `posix-fd-support`) lets X11 editors read their display connection and repaint. Verified with Graillon 3 and Surge XT Effects (JUCE) in both formats (#527). No readiness percentage change.
|
||||
- **2026-10-25:** Alt+Shift+E (`view.zoom_toggle_cancel`) and an Alt-click on the Zoom Toggle button cancel Zoom Toggle and keep the current view: the zoom, the scroll and the track heights stay as they are, and the button is no longer lit. The next Zoom Toggle zooms in from that view and goes back to it. No readiness percentage change.
|
||||
- **2026-10-25:** Tracks and Groups and the Clip List sit in dock columns that run the Edit window's full height at its left and right edges, with the MIDI Editor under the session view between them; Mix docks Tracks and Groups at its left edge. A panel dragged onto a dock group joins it as a tab, stacks above or below it, or makes a new column; one dragged to an empty window edge makes a dock there. A list with no saved place reopens in its dock, and makes the dock again when it is gone. Preferences and window configurations saved with the earlier split-frame layouts load with the new default layouts and keep their other settings. No readiness percentage change.
|
||||
- **2026-10-25:** A vertical drag on a send's level moves it as finely with Ctrl (Command on a Mac) held as with Shift, as a fader's Ctrl-drag does. The Level and Pan sliders of a send's options menu, the Send window's pan knob and the tracks' pan knobs move a tenth as far for the same drag while Ctrl (Command on a Mac) is held. No readiness percentage change.
|
||||
- **2026-10-25:** Auto Pan moves the balance of a stereo track: the left channel's level falls as the position moves right and the right channel's as it moves left, at constant power, and each channel stays on its own side. At the center the track passes unchanged, so a wide or out-of-phase stereo image keeps its width, and the envelope follower follows the louder channel. No readiness percentage change.
|
||||
- **2026-10-24:** An Alt-click (Option-click on a Mac) on a parameter in the plugin window, the Clip Effects window or an AudioSuite plugin's window returns it to its default value, on a slider or a slider's value box, and in the plugin window on a choice list too, as an Alt-click returns a fader to 0 dB. In the plugin window and the Clip Effects window the reset is one undo step. While Alt is held, a drag on a slider leaves the value where it is. No readiness percentage change.
|
||||
- **2026-10-24:** The parameter sliders of the plugin window, the Clip Effects window and AudioSuite plugins move a tenth as far for the same drag while Ctrl (Command on a Mac) is held, as the Strip Silence sliders do. Logarithmic sliders move a tenth as far along the slider, and whole-number sliders stay on whole numbers. No readiness percentage change.
|
||||
- **2026-10-24:** The Strip Silence window's four sliders move a tenth as far for the same drag while Ctrl (Command on a Mac) is held, on the slider and on its value box. Pressing or releasing the key during a drag leaves the value where it is. The Threshold and Clip Start Pad boxes show one decimal place. No readiness percentage change.
|
||||
- **2026-10-24:** Clip › Unloop… opens the Unloop dialog. Remove deletes the loop iterations and keeps the source clip, and Flatten keeps each loop iteration as its own clip. No readiness percentage change.
|
||||
- **2026-10-24:** Clip List › Auto Rename (`clip.auto_rename`) sets the names that editing gives the clips it separates from the selected clips: a name, a starting number, a number of places (zeros before the number) and a suffix. The piece after each cut takes the next name, the piece before it keeps its name, and all the pieces count up one number sequence. Pieces that Strip Silence names with its own Rename fields, or removes, take no Auto Rename name. Copied clips keep their scheme when they are pasted, saved sessions hold the schemes, and Import Session Data brings them along. No readiness percentage change.
|
||||
- **2026-10-24:** While the Strip Silence window is open, the Edit window draws a rectangle around each range that Strip would keep on the selected tracks, padded by Clip Start Pad and Clip End Pad, and the rectangles follow the sliders as they move. They are removed when the window closes. `edit.strip_silence_preview` returns the same ranges without changing the session. No readiness percentage change.
|
||||
- **2026-10-24:** The Strip Silence window has a Rename button. It opens Rename Selected Clips, where a name, a starting number, a count of zeros and a suffix set the names of the clips that Strip, Extract and Separate leave in the selection (for example SFX023.Reel1, SFX024.Reel1). The app keeps the scheme for later uses of Strip Silence until the app quits, or until Clear and then OK empty it. No readiness percentage change.
|
||||
@@ -196,9 +192,7 @@ mutated and truncated movies. Field reports from the first public week are track
|
||||
| 2026-11-27 | trivial | Languages table: Spanish catalog complete with native-speaker review. Estimates unchanged |
|
||||
| 2026-11-24 | trivial | Languages table: French and Spanish catalogs, partial (≈ 62 %), PR #143. Estimates unchanged |
|
||||
| 2026-11-22 | minor | Languages table: Simplified Chinese (zh-Hans) covers the fixed UI strings through the `locales/zh-Hans` catalog, with a Han system-font fallback and an OFL web subset; needs native review. Localization estimate 70–110 → 55–90 h |
|
||||
| 2026-11-15 | minor | Historical 27 October–15 November progress recap through v0.20.1; menu breadth, readiness and effort were not re-measured |
|
||||
| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged |
|
||||
| 2026-11-12 | trivial | Progress log: room tone fill; readiness estimates unchanged |
|
||||
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
|
||||
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
|
||||
| 2026-11-05 | trivial | Progress log: Command-click adds an undoable automation point (#1394); readiness estimates unchanged |
|
||||
|
||||
@@ -17,7 +17,6 @@ asio = ["soundcraft-playback/asio"]
|
||||
[dependencies]
|
||||
soundcraft-engine.workspace = true
|
||||
craft-audio.workspace = true
|
||||
craft-nightly.workspace = true
|
||||
soundcraft-ui-egui.workspace = true
|
||||
soundcraft-playback.workspace = true
|
||||
soundcraft-automation.workspace = true
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(soundcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open SoundCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable SoundCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
@@ -23,7 +36,6 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -32,6 +44,20 @@ mod tests {
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.20.1"), "0.20.1");
|
||||
|
||||
@@ -10,6 +10,12 @@ use soundcraft_ui_egui::docking;
|
||||
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
|
||||
/// The portable marker in `dir`, if it is a regular file (never a link or a directory).
|
||||
pub(crate) fn portable_marker(dir: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
let marker = dir.join(PORTABLE_MARKER);
|
||||
std::fs::symlink_metadata(&marker).ok().filter(|m| m.file_type().is_file()).map(|_| marker)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Platform {
|
||||
Mac,
|
||||
@@ -38,7 +44,7 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<Path
|
||||
}
|
||||
|
||||
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option<PathBuf> {
|
||||
// The compiled Nightly flavor always selects an isolated profile (`launch_profile::prepare`),
|
||||
// The compiled Nightly flavor cannot run without a profile (`build_flavor::require_profile`),
|
||||
// so this is the complete settings folder and never falls back to Stable data.
|
||||
if let Some(root) = nightly {
|
||||
return Some(root.to_path_buf());
|
||||
|
||||
@@ -1,289 +1,214 @@
|
||||
//! Nightly-v1 bootstrap and profile fencing via `craft-nightly`.
|
||||
//!
|
||||
//! Selected before logging, updates, fonts or saved state. Direct launches of a nightly build
|
||||
//! self-isolate into `craft_nightly::canonical_profile_root("soundcraft")`; launcher launches
|
||||
//! pass `--launch-profile nightly-v1 --profile-root <dir> -- <args...>`. Stable builds keep
|
||||
//! their original arguments and directory policy.
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use craft_nightly::{AppProfileSpec, Launch, Profile, ProfileError, StartupOptions};
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
use crate::build_flavor;
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
const APP_ID: &str = "soundcraft";
|
||||
const DISPLAY_NAME: &str = "SoundCraft";
|
||||
const STABLE_DIR_NAMES: &[&str] = &["soundcraft", "SoundCraft"];
|
||||
const STABLE_PACKAGE_ID: &str = "ai.storyteller.soundcraft";
|
||||
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.soundcraft.nightly";
|
||||
const FORBIDDEN_ENV_VARS: &[&str] = &[crate::env::CONFIG_DIR];
|
||||
const PORTABLE_MARKERS: &[&str] = &[crate::config::PORTABLE_MARKER];
|
||||
const FOLDER_ONLY_ENTRIES: &[&str] = &["Autosave", "Presets", "logs"];
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
fn non_empty_abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
path.is_absolute().then_some(path)
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi).
|
||||
if let Some(local) = non_empty_abs_env(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if let Some(profile) = non_empty_abs_env(&env, "USERPROFILE") {
|
||||
roots.push(profile.join("AppData").join("Local").join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs_env(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("SoundCraft"));
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
if let Some(home) = non_empty_abs_env(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.soundcraft"));
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
roots.push(PathBuf::from("/Applications/SoundCraft.app"));
|
||||
if let Some(home) = non_empty_abs_env(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.soundcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.soundcraft.savedState"));
|
||||
roots.push(home.join("Applications/SoundCraft.app"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
let _ = env;
|
||||
|
||||
roots
|
||||
}
|
||||
|
||||
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: DISPLAY_NAME,
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: STABLE_PACKAGE_ID,
|
||||
nightly_package_id: NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: FORBIDDEN_ENV_VARS,
|
||||
portable_markers: PORTABLE_MARKERS,
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots_with(env),
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with(|key| std::env::var_os(key))
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
pub fn prepare(args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
craft_nightly::prepare_launch(build_flavor::COMPILED, &spec(), args, &StartupOptions::new())
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old portable/config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
// SoundCraft keeps no Documents agent folder and has no craft-settings data/cache roots: one
|
||||
// settings folder holds ui.json, Autosave/, Presets/ and logs/, and `config::writable` is the
|
||||
// app's existing exclusive write probe.
|
||||
crate::profile_root::validate(root, env, exe, crate::config::writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, canonical_profile_root, launch_arguments, parse_startup, validate_and_prepare_root};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use std::cell::Cell;
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\soundcraft" } else { "/nightly-data/profiles/soundcraft" }
|
||||
}
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(prefix: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
|
||||
loop {
|
||||
let candidate = base.join(format!("{prefix}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => return Self(candidate),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create temp dir: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soundcraft_spec_preserves_stable_fences_and_folder_entries() {
|
||||
let spec = spec();
|
||||
assert_eq!(spec.app_id, "soundcraft");
|
||||
assert_eq!(spec.display_name, "SoundCraft");
|
||||
assert_eq!(spec.stable_dir_names, &["soundcraft", "SoundCraft"]);
|
||||
assert_eq!(spec.stable_package_id, "ai.storyteller.soundcraft");
|
||||
assert_eq!(spec.nightly_package_id, "ai.storyteller.soundcraft.nightly");
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert_eq!(spec.forbidden_env_vars, &["SOUNDCRAFT_CONFIG_DIR"]);
|
||||
assert_eq!(spec.portable_markers, &["portable.txt"]);
|
||||
assert_eq!(spec.folder_only_entries, &["Autosave", "Presets", "logs"]);
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "image with spaces.psd"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = spec();
|
||||
let expected_root = canonical_profile_root("soundcraft").unwrap();
|
||||
let argv = args(&["--demo", "song.scraft"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
assert!(launch.leading_flags.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_launcher_invocation_round_trips_and_preserves_file_arguments() {
|
||||
let spec = spec();
|
||||
let root = PathBuf::from(absolute());
|
||||
let user_args = args(&["--profile-root", "session with spaces.scraft"]);
|
||||
let argv = launch_arguments(&root, &user_args);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(root));
|
||||
assert_eq!(launch.passthrough_args, user_args);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_build_keeps_arguments_and_refuses_nightly_flags() {
|
||||
let spec = spec();
|
||||
for argv in [args(&[]), args(&["--demo", "a.scraft"]), args(&["--", "--launch-profile", "file.scraft"])] {
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
let nightly = launch_arguments(Path::new(absolute()), &[]);
|
||||
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec, nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_queries_are_recognized_for_plain_and_launcher_invocations() {
|
||||
let spec = spec();
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
|
||||
assert!(plain.is_version_query());
|
||||
|
||||
for header in [
|
||||
["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()],
|
||||
["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT],
|
||||
] {
|
||||
let mut query = args(&header);
|
||||
query.push(flag.into());
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, query.clone(), &StartupOptions::new()).unwrap().is_version_query());
|
||||
query.push("recording with spaces.wav".into());
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, query, &StartupOptions::new()).unwrap();
|
||||
assert!(!launch.is_version_query());
|
||||
assert_eq!(launch.passthrough_args, args(&[flag, "recording with spaces.wav"]));
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
|
||||
let dir = TempDir::new("soundcraft-nightly-reopen");
|
||||
let root = dir.path().join("profile");
|
||||
let spec = spec();
|
||||
|
||||
let prepared = validate_and_prepare_root(&root, &spec).unwrap();
|
||||
assert_eq!(prepared, root);
|
||||
|
||||
for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(prepared.join(file), b"saved profile data").unwrap();
|
||||
}
|
||||
for folder in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(prepared.join(folder)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&root, &spec).unwrap(), prepared);
|
||||
|
||||
for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(prepared.join(file)).unwrap(), b"saved profile data", "{file} remains intact after reopen");
|
||||
}
|
||||
for folder in FOLDER_ONLY_ENTRIES {
|
||||
let path = prepared.join(folder);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(
|
||||
matches!(validate_and_prepare_root(&root, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
|
||||
"{folder} must remain a directory"
|
||||
);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_roots_fence_soundcraft_install_locations() {
|
||||
let dir = TempDir::new("soundcraft-extra-fence");
|
||||
let custom_forbidden = dir.path().join("forbidden-install");
|
||||
let mut spec = spec();
|
||||
spec.extra_forbidden_roots.push(custom_forbidden.clone());
|
||||
assert!(matches!(validate_and_prepare_root(&custom_forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_extra_forbidden_roots_include_expected_paths() {
|
||||
let home = if cfg!(windows) { r"C:\Users\tester" } else { "/Users/tester" };
|
||||
let local = if cfg!(windows) { r"C:\Users\tester\AppData\Local" } else { "/unused" };
|
||||
let program_files = if cfg!(windows) { r"C:\Program Files" } else { "/unused" };
|
||||
let spec = spec_with(|key| match key {
|
||||
"HOME" | "USERPROFILE" => Some(OsString::from(home)),
|
||||
"LOCALAPPDATA" => Some(OsString::from(local)),
|
||||
"ProgramFiles" => Some(OsString::from(program_files)),
|
||||
_ => None,
|
||||
});
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(local).join("Programs").join("ArtCraft").join("SoundCraft")));
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(program_files).join("ArtCraft").join("SoundCraft")));
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/soundcraft")));
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join(".var/app/ai.storyteller.soundcraft")));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/Applications/SoundCraft.app")));
|
||||
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join("Library/Preferences/ai.storyteller.soundcraft.plist")));
|
||||
}
|
||||
let _ = (home, local, program_files, &spec);
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
|
||||
+23
-20
@@ -26,6 +26,7 @@ mod logging;
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod switch;
|
||||
|
||||
use env::Env;
|
||||
@@ -250,34 +251,36 @@ fn report_launch_profile_error(error: &str) {
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before the logger, updates, fonts or saved state.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version` / `-V` on Nightly: answered before canonical root resolution, validation,
|
||||
// process identity, IPC or any window, even in environments without HOME/LOCALAPPDATA.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window, as
|
||||
// `SoundCraft <version> (nightly-v1)` on standard output with nothing on standard error.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::prepare(argv).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
|
||||
// `craft_nightly::prepare_launch` skips root validation and profile installation for version queries.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable };
|
||||
if let Err(error) = os_window::select_identity(identity) {
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.passthrough_args)
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
|
||||
@@ -0,0 +1,705 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::config::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The Nightly Flatpak's own app id (packaging/linux/flatpak-bundle.sh). Inside that instance the
|
||||
/// sandbox is the isolation, so it is the one Flatpak whose environment a Nightly launch accepts.
|
||||
const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.soundcraft.nightly";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("SoundCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
|
||||
// install folder is not known here; the executable's own folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("SoundCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("SoundCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("soundcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.soundcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/SoundCraft"),
|
||||
library.join("Caches/SoundCraft"),
|
||||
library.join("Caches/ai.storyteller.soundcraft"),
|
||||
library.join("Preferences/SoundCraft"),
|
||||
library.join("Preferences/ai.storyteller.soundcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.soundcraft.savedState"),
|
||||
home.join("Applications/SoundCraft.app"),
|
||||
PathBuf::from("/Applications/SoundCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
match std::fs::symlink_metadata(&child) {
|
||||
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve
|
||||
/// inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
|
||||
// marker only counts beside a SoundCraft executable, so an unrelated portable.txt higher up
|
||||
// (in a user folder or at a drive root) does not refuse the profile.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
portable_marker(ancestor).is_some() && (depth == 0 || ["soundcraft.exe", "soundcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
|
||||
/// boundary tests exercise the real policy without starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if env("SOUNDCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
// The Launcher protocol is the one root the app validates. A wrapper that isolates with
|
||||
// the stable override variable instead passes the profile explicitly; the message names
|
||||
// that, because this is what a Linux nightly launcher hits when it exports the variable.
|
||||
return Err(
|
||||
"nightly-v1 cannot be combined with SOUNDCRAFT_CONFIG_DIR; pass --launch-profile nightly-v1 --profile-root <dir> -- instead".into()
|
||||
);
|
||||
}
|
||||
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its
|
||||
// runtime socket namespace could point another profile at the stable app's socket. The
|
||||
// Nightly Flatpak is the exception: its own app id is the sandbox, so $HOME and the XDG
|
||||
// folders in there are already this package's own.
|
||||
if platform != Platform::Windows
|
||||
&& let Some(instance) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
&& instance.to_string_lossy() != NIGHTLY_FLATPAK_ID
|
||||
{
|
||||
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable SoundCraft installation or its SoundCraftData settings folder".into());
|
||||
}
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Autosave is swept and rewritten on start and Presets are written in place: never let either
|
||||
// alias leave this private profile, including toward a Stable portable directory we cannot know.
|
||||
private_subdirectory(&chosen, "Autosave", "autosave folder")?;
|
||||
private_subdirectory(&chosen, "Presets", "presets folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "Autosave", "autosave folder")?;
|
||||
private_subdirectory(&confirmed, "Presets", "presets folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 3] = ["Autosave", "Presets", "logs"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("soundcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/soundcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
|
||||
assert!(!probed.get(), "reject portable data before a writable probe");
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
|
||||
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("SoundCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn autosave_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/state/soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("Autosave")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "Autosave must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-self");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&private, private.join("Autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "Autosave cannot treat all profile settings as autosaves");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn autosave_alias_to_a_private_subfolder_keeps_the_profile_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let autosave = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&autosave).unwrap();
|
||||
std::os::unix::fs::symlink(&autosave, private.join("Autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("Autosave")).unwrap(), autosave);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/soundcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Autosave"), platform));
|
||||
assert!(overlaps(&root.join("Autosave"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("soundcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/soundcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/SoundCraft Nightly.app/Contents/MacOS/SoundCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/SoundCraft",
|
||||
"Caches/SoundCraft",
|
||||
"Caches/ai.storyteller.soundcraft",
|
||||
"Preferences/SoundCraft",
|
||||
"Saved Application State/ai.storyteller.soundcraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/soundcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/soundcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_msi_install_folders_are_fenced() {
|
||||
let mut fixture = Fixture::new();
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("SoundCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("soundcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not SoundCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let portable = fixture.root.join("D/PC");
|
||||
std::fs::create_dir_all(&portable).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
|
||||
std::fs::write(portable.join("soundcraft.exe"), b"stable portable executable, never run").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("portable"));
|
||||
assert!(!probed.get());
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
}
|
||||
// A portable.txt that no SoundCraft executable sits beside is someone else's file.
|
||||
let unrelated = fixture.root.join("user folder");
|
||||
std::fs::create_dir_all(&unrelated).unwrap();
|
||||
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
|
||||
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/soundcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.soundcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn any_profile_entry_alias_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/soundcraft/Presets");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap();
|
||||
for name in ["Presets", "logs", "settings.json"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-presets")).unwrap();
|
||||
std::fs::write(private.join("settings.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/soundcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("SOUNDCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("SOUNDCRAFT_CONFIG_DIR"));
|
||||
fixture.env.remove("SOUNDCRAFT_CONFIG_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
// The Nightly Flatpak is its own instance: the profile inside it is a sandbox-local folder.
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft.nightly".into());
|
||||
let sandboxed = fixture.home().join(".var/app/ai.storyteller.soundcraft.nightly/config/soundcraft-nightly");
|
||||
assert_eq!(fixture.check(Platform::Linux, &sandboxed).unwrap(), sandboxed);
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"do not replace me").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file).is_err());
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
|
||||
let candidate = fixture.home().join("nightly");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert!(!fixture.home().join(".config/soundcraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/soundcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
|
||||
let alias = fixture.home().join("alias");
|
||||
symlink(&stable, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
|
||||
let missing = fixture.home().join("missing-target");
|
||||
let dangling = fixture.home().join("dangling");
|
||||
symlink(&missing, &dangling).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
|
||||
assert!(!missing.exists());
|
||||
assert!(!stable.join("nightly").exists());
|
||||
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
|
||||
}
|
||||
}
|
||||
@@ -70,10 +70,6 @@ sync_github_name = true
|
||||
real_name = "Kushagra Kumar"
|
||||
sync_github_name = true
|
||||
|
||||
[people.JonRC]
|
||||
real_name = "Jonathan Cardoso"
|
||||
display_name = "Jonathan Cardoso"
|
||||
|
||||
# Display name explicitly chosen by the contributor on 2026-10-19.
|
||||
[people.vhhr7]
|
||||
display_name = "Vic Herrera (@vhhr)"
|
||||
|
||||
@@ -182,7 +182,6 @@ fn writes(dir: &Path) -> Vec<(&'static str, Value)> {
|
||||
("file.print_score", json!({"path": p("k.svg")})),
|
||||
("file.export_clip_groups", json!({"path": p("l.scgrp"), "clips": [clip]})),
|
||||
("track.save_preset", json!({"path": p("m.json"), "tracks": ["Kick"]})),
|
||||
("setup.disk_allocation", json!({"path": p("recordings")})),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -302,7 +301,6 @@ fn links_out_of_the_roots_are_refused() {
|
||||
refused(&mut srv, "file.bounce_mix", json!({"path": s(f.write.join("away/x.wav"))}), "outside the write root");
|
||||
refused(&mut srv, "file.bounce_stems", json!({"dir": s(f.write.join("away/stems"))}), "outside the write root");
|
||||
refused(&mut srv, "session.save_as", json!({"path": s(f.write.join("away/x.scraft"))}), "outside the write root");
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"path": s(f.write.join("away/rec"))}), "outside the write root");
|
||||
refused(&mut srv, "file.bounce_mix", json!({"path": s(f.write.join("dangling.wav"))}), "a link that leads nowhere");
|
||||
assert_eq!(listing(&f.outside), before, "nothing was written through a link");
|
||||
assert!(!f.outside.join("not-yet.wav").exists());
|
||||
@@ -373,56 +371,6 @@ fn media_a_session_names_outside_the_read_root_is_not_loaded() {
|
||||
assert!(inspect(&mut free)["sources"].as_array().unwrap().iter().all(|x| x["loaded"] == true));
|
||||
}
|
||||
|
||||
/// `setup.disk_allocation` stores its path trimmed and cut to 200 characters, so that string is
|
||||
/// what gets checked. With the working folder as the write root, `" /abs/outside"` read as given
|
||||
/// would be `<cwd>/ /abs/outside` and pass, yet `/abs/outside` would be kept. The outside folder
|
||||
/// is the working directory's parent, so this does not depend on `TMPDIR`. A space at character
|
||||
/// 200 would be checked and then trimmed off again: `<pad>/link ` can sit inside the root while
|
||||
/// `<pad>/link` is a symlink out of it. An empty path still clears the setting.
|
||||
#[test]
|
||||
fn the_record_folder_is_checked_as_it_is_stored() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let outside = cwd.parent().expect("the working directory has a parent");
|
||||
let mut srv = demo_server(None, Some(&cwd));
|
||||
let spaced = format!(" {}", s(outside.join("rec")));
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"path": spaced}), "outside the write root");
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"track": "Kick", "path": spaced}), "outside the write root");
|
||||
ok(&mut srv, "setup.disk_allocation", json!({"path": " rec "}));
|
||||
ok(&mut srv, "setup.disk_allocation", json!({"path": ""}));
|
||||
ok(&mut srv, "setup.disk_allocation", json!({"path": " "}));
|
||||
|
||||
// Character 200 is a space, and more follows so the first trim leaves it. The cut used to
|
||||
// keep that space for the check and drop it when the same string was stored.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::symlink;
|
||||
// A folder of our own in the working folder: `create_dir` fails rather than reuse one that
|
||||
// is already there, so only what this run made is removed, and parallel runs don't meet.
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let own = format!("sc-record-{}-{nanos}", std::process::id());
|
||||
std::fs::create_dir(cwd.join(&own)).unwrap();
|
||||
struct RemoveDir(PathBuf);
|
||||
impl Drop for RemoveDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
let _cleanup = RemoveDir(cwd.join(&own));
|
||||
let tail = "/link";
|
||||
let pad = "d".repeat(199 - own.len() - 1 - tail.len());
|
||||
let rel = format!("{own}/{pad}{tail}");
|
||||
assert_eq!(rel.chars().count(), 199, "the stored path is 199 characters");
|
||||
let dir = cwd.join(&own).join(&pad);
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
symlink(outside, dir.join("link")).unwrap();
|
||||
let input = format!("{rel} x");
|
||||
assert_eq!(input.chars().nth(199), Some(' '), "character 200 is a space");
|
||||
refused(&mut srv, "setup.disk_allocation", json!({"path": input}), "outside the write root");
|
||||
let reported = ok(&mut srv, "setup.disk_allocation", json!({}));
|
||||
assert!(!reported.contains(&pad), "a refused record folder was stored: {reported}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_roots_nothing_is_confined() {
|
||||
let f = fixture("free");
|
||||
|
||||
@@ -287,11 +287,6 @@ impl GuiLink {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
self.dispatch(&g);
|
||||
if g.created {
|
||||
// a timer-driven editor's WM_TIMERs and the paints they invalidate are starved while
|
||||
// the transport keeps the queue busy (#1447)
|
||||
if let Some(w) = &g.window {
|
||||
w.service();
|
||||
}
|
||||
let resize = self.host.gui_resize.swap(0, Ordering::Relaxed);
|
||||
if resize != 0
|
||||
&& let Some(win) = &g.window
|
||||
|
||||
@@ -16,9 +16,6 @@ impl HostWindow {
|
||||
clap_window_handle { ptr: std::ptr::null_mut() }
|
||||
}
|
||||
pub fn raise(&self) {}
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -2,14 +2,12 @@ use clap_sys::ext::gui::clap_window_handle;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::OnceLock;
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
|
||||
use windows_sys::Win32::Graphics::Gdi::{RDW_ALLCHILDREN, RDW_UPDATENOW, RedrawWindow};
|
||||
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GWL_EXSTYLE,
|
||||
GWL_STYLE, GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, MSG, PM_REMOVE, PeekMessageW, PostQuitMessage, RegisterClassExW,
|
||||
SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WM_QUIT, WM_TIMER,
|
||||
WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
|
||||
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, GWL_EXSTYLE, GWL_STYLE,
|
||||
GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, RegisterClassExW, SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE,
|
||||
SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
|
||||
};
|
||||
|
||||
pub const SUPPORTED: bool = true;
|
||||
@@ -150,18 +148,6 @@ impl HostWindow {
|
||||
self.live().is_some_and(|h| unsafe { IsWindowVisible(h) } != 0)
|
||||
}
|
||||
|
||||
/// Per-frame service on the main thread (#1447): while the transport plays eframe always keeps a
|
||||
/// repaint pending, and Win32 only synthesizes `WM_TIMER` and `WM_PAINT` when the queue runs dry —
|
||||
/// so a timer-driven editor is starved until playback pauses. Dispatches the thread's pending
|
||||
/// timers (thread-wide on purpose: nothing else on this thread uses Win32 timers, and a timer
|
||||
/// with a `TIMERPROC` only runs through dispatch) and flushes the paint they invalidate.
|
||||
pub fn service(&self) {
|
||||
let Some(hwnd) = self.live() else { return };
|
||||
pump_timers();
|
||||
// SAFETY: a live window of this thread; ALLCHILDREN reaches the plugin's child windows.
|
||||
unsafe { RedrawWindow(hwnd, std::ptr::null(), std::ptr::null_mut(), RDW_UPDATENOW | RDW_ALLCHILDREN) };
|
||||
}
|
||||
|
||||
pub fn close(self) {
|
||||
if let Some(h) = self.live() {
|
||||
// SAFETY: our own live window; the plugin's GUI was destroyed first.
|
||||
@@ -182,94 +168,3 @@ pub fn resize(window: *mut c_void, w: f64, h: f64) {
|
||||
// SAFETY: as above; only the size changes.
|
||||
unsafe { SetWindowPos(window, std::ptr::null_mut(), 0, 0, ow, oh, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE) };
|
||||
}
|
||||
|
||||
/// Dispatches up to 32 `WM_TIMER`s pending on this thread (main thread only). The cap keeps a timer
|
||||
/// that re-arms on every dispatch from starving the frame; leftovers are served next tick.
|
||||
fn pump_timers() {
|
||||
// SAFETY: `PeekMessageW`/`DispatchMessageW`/`PostQuitMessage` on this thread's own queue;
|
||||
// `msg` outlives them all.
|
||||
unsafe {
|
||||
let mut msg: MSG = std::mem::zeroed();
|
||||
for _ in 0..32 {
|
||||
if PeekMessageW(&mut msg, std::ptr::null_mut(), WM_TIMER, WM_TIMER, PM_REMOVE) == 0 {
|
||||
break;
|
||||
}
|
||||
if msg.message == WM_QUIT {
|
||||
// PeekMessageW returns WM_QUIT regardless of the filter — repost it with its
|
||||
// exit code so the app's own message loop still sees the quit, and stop here.
|
||||
PostQuitMessage(msg.wParam as i32);
|
||||
break;
|
||||
}
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use windows_sys::Win32::Graphics::Gdi::{GetUpdateRect, InvalidateRect};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{KillTimer, SetTimer};
|
||||
|
||||
static FIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
unsafe extern "system" fn on_timer(hwnd: HWND, _msg: u32, _id: usize, _time: u32) {
|
||||
FIRED.fetch_add(1, Ordering::Relaxed);
|
||||
// SAFETY: a live window of this thread.
|
||||
unsafe { InvalidateRect(hwnd, std::ptr::null(), 1) };
|
||||
}
|
||||
|
||||
/// #1447: while the transport plays eframe always has a repaint pending, and Win32 only
|
||||
/// synthesizes `WM_TIMER`/`WM_PAINT` when the queue runs dry — an editor that animates from a
|
||||
/// timer freezes until Pause. `service` must dispatch the timer and its paint without a
|
||||
/// message loop ever waiting.
|
||||
#[test]
|
||||
fn an_editors_timer_and_paint_run_while_the_thread_never_waits_for_messages() {
|
||||
// windows are created and served on the app's UI thread — named "main" here.
|
||||
std::thread::Builder::new()
|
||||
.name("main".into())
|
||||
.spawn(|| {
|
||||
let window = HostWindow::new("timer test", 120.0, 80.0).expect("host window");
|
||||
let h = window.raw() as HWND;
|
||||
FIRED.store(0, Ordering::Relaxed);
|
||||
// SAFETY: live window of this thread; proc outlives the timer (killed below).
|
||||
unsafe { SetTimer(h, 1, 10, Some(on_timer)) };
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
assert_eq!(FIRED.load(Ordering::Relaxed), 0, "the timer fired without anyone pumping");
|
||||
window.service();
|
||||
assert!(FIRED.load(Ordering::Relaxed) > 0, "service() did not dispatch WM_TIMER");
|
||||
// SAFETY: `GetUpdateRect` accepts any window; false means the paint was flushed.
|
||||
assert_eq!(unsafe { GetUpdateRect(h, std::ptr::null_mut(), 0) }, 0, "the timer's paint is still pending");
|
||||
unsafe { KillTimer(h, 1) };
|
||||
window.close();
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("join");
|
||||
}
|
||||
|
||||
/// `PeekMessageW` returns `WM_QUIT` regardless of the filter range, so the pump can swallow
|
||||
/// the quit the app's own loop is waiting for. It must repost it — with its exit code — and
|
||||
/// stop, leaving the signal for the owning loop.
|
||||
#[test]
|
||||
fn the_pump_leaves_a_quit_and_its_exit_code_for_the_owning_loop() {
|
||||
std::thread::Builder::new()
|
||||
.name("main".into())
|
||||
.spawn(|| {
|
||||
// SAFETY: this thread owns the queue it posts to and peeks.
|
||||
unsafe { PostQuitMessage(7) };
|
||||
pump_timers();
|
||||
// SAFETY: `MSG` is a plain Win32 data struct made of integer and pointer fields,
|
||||
// so an all-zero value is valid initialized storage.
|
||||
let mut msg: MSG = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: `msg` is live owned storage, so `&mut msg` remains valid and writable
|
||||
// for the duration of the call.
|
||||
assert_ne!(unsafe { PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) }, 0, "the pump swallowed the quit");
|
||||
assert_eq!((msg.message, msg.wParam), (WM_QUIT, 7), "the quit signal or its exit code changed");
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("join");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,9 +142,6 @@ impl HostWindow {
|
||||
self.shown.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return false };
|
||||
x.pump();
|
||||
|
||||
@@ -8,8 +8,6 @@ use std::sync::atomic::Ordering;
|
||||
|
||||
/// Largest block we activate a plugin for.
|
||||
const MAX_BLOCK: usize = 1 << 16;
|
||||
/// Most `on_main_thread` calls one `idle` runs for a plugin that keeps asking for more.
|
||||
const MAX_CALLBACKS_PER_IDLE: usize = 8;
|
||||
/// Most channels a host strip may ask for.
|
||||
const MAX_CHANNELS: usize = 64;
|
||||
/// Queue slots that only releases from `note_off` may take: one per key, so a queue that
|
||||
@@ -45,8 +43,6 @@ pub struct ClapPlugin {
|
||||
channels: usize,
|
||||
max_block: usize,
|
||||
latency: usize,
|
||||
/// What the last `prepare` was asked for, to restart the plugin the same way.
|
||||
prepared: Option<(f32, usize, usize)>,
|
||||
steady: i64,
|
||||
transport: Option<Transport>,
|
||||
}
|
||||
@@ -71,7 +67,6 @@ impl ClapPlugin {
|
||||
channels: 2,
|
||||
max_block: 0,
|
||||
latency: 0,
|
||||
prepared: None,
|
||||
steady: 0,
|
||||
transport: None,
|
||||
}
|
||||
@@ -236,7 +231,6 @@ impl Plugin for ClapPlugin {
|
||||
}
|
||||
|
||||
fn prepare(&mut self, sample_rate: f32, max_block: usize, channels: usize) {
|
||||
self.prepared = Some((sample_rate, max_block, channels));
|
||||
let sr = if sample_rate.is_finite() && sample_rate > 0.0 { f64::from(sample_rate) } else { 48_000.0 };
|
||||
let mb = max_block.clamp(1, MAX_BLOCK);
|
||||
self.channels = channels.clamp(1, MAX_CHANNELS);
|
||||
@@ -364,25 +358,6 @@ impl Plugin for ClapPlugin {
|
||||
self.latency
|
||||
}
|
||||
|
||||
fn idle(&mut self) {
|
||||
// A plugin that finds a new latency while processing asks for `on_main_thread`, and from
|
||||
// there for a restart (maybe after more callbacks): the new value only counts once it is
|
||||
// activated again. Run every callback it asks for here, a bounded number of them.
|
||||
for _ in 0..MAX_CALLBACKS_PER_IDLE {
|
||||
if !self.inst.state().callback.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
self.inst.service_callback();
|
||||
}
|
||||
if self.inst.state().restart.swap(false, Ordering::Relaxed) {
|
||||
if let Some((sr, mb, ch)) = self.prepared {
|
||||
self.prepare(sr, mb, ch);
|
||||
}
|
||||
} else if self.inst.is_active() && self.inst.state().latency_changed.swap(false, Ordering::Relaxed) {
|
||||
self.latency = self.inst.latency() as usize;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_transport(&mut self, transport: &Transport) {
|
||||
self.transport = Some(*transport);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
//! Test-only CLAP plugins for soundcraft-clap-host: a gain effect and a "DC synth".
|
||||
//!
|
||||
//! - `org.soundcraft.test.gain`: stereo in/out, param 7 "Gain" (0..2, default 1), param 3 "Mode"
|
||||
//! (stepped enum A/B/C), hidden param 9, latency 3 samples. Mode C needs 16: like LSP, the
|
||||
//! plugin finds that out in `process`, asks for `on_main_thread`, from there for a second
|
||||
//! `on_main_thread`, and from that one for a restart; it reports 16 once activated again.
|
||||
//! (stepped enum A/B/C), hidden param 9, latency 3 samples.
|
||||
//! - `org.soundcraft.test.synth`: instrument, stereo out, CLAP note port; outputs a constant equal
|
||||
//! to the velocity of the held note (0 when none), switching at the event's sample offset. A
|
||||
//! MIDI CC 7 (volume) sets the constant to its value / 127. `reset` leaves the note sounding.
|
||||
@@ -101,11 +99,6 @@ struct Fx {
|
||||
gain: f64,
|
||||
mode: f64,
|
||||
level: f64,
|
||||
/// The latency the plugin was activated with, and whether it asked for a restart to change it.
|
||||
latency: u32,
|
||||
restart_wanted: bool,
|
||||
/// The first `on_main_thread` after a latency change only asks for another one.
|
||||
second_callback_asked: bool,
|
||||
active: bool,
|
||||
processing: bool,
|
||||
gui_created: bool,
|
||||
@@ -153,14 +146,9 @@ unsafe extern "C" fn activate(p: *const clap_plugin, sr: f64, min: u32, max: u32
|
||||
return false;
|
||||
}
|
||||
f.active = true;
|
||||
f.latency = latency_for(f.mode);
|
||||
true
|
||||
}
|
||||
|
||||
fn latency_for(mode: f64) -> u32 {
|
||||
if mode >= 2.0 { 16 } else { 3 }
|
||||
}
|
||||
|
||||
unsafe extern "C" fn deactivate(p: *const clap_plugin) {
|
||||
let f = unsafe { fx(p) };
|
||||
assert!(!f.processing, "deactivate while processing");
|
||||
@@ -322,11 +310,6 @@ unsafe extern "C" fn process(p: *const clap_plugin, pr: *const clap_process) ->
|
||||
unsafe { *o.add(i) = v };
|
||||
}
|
||||
}
|
||||
if latency_for(f.mode) != f.latency && !f.restart_wanted {
|
||||
f.restart_wanted = true;
|
||||
let host = unsafe { &*f.host };
|
||||
unsafe { (host.request_callback.unwrap())(f.host) };
|
||||
}
|
||||
CLAP_PROCESS_CONTINUE
|
||||
}
|
||||
|
||||
@@ -439,8 +422,8 @@ unsafe extern "C" fn ports_get(p: *const clap_plugin, index: u32, is_input: bool
|
||||
|
||||
static PORTS: clap_plugin_audio_ports = clap_plugin_audio_ports { count: Some(ports_count), get: Some(ports_get) };
|
||||
|
||||
unsafe extern "C" fn latency_get(p: *const clap_plugin) -> u32 {
|
||||
unsafe { fx(p) }.latency
|
||||
unsafe extern "C" fn latency_get(_p: *const clap_plugin) -> u32 {
|
||||
3
|
||||
}
|
||||
|
||||
static LATENCY: clap_plugin_latency = clap_plugin_latency { get: Some(latency_get) };
|
||||
@@ -603,20 +586,7 @@ unsafe extern "C" fn get_extension(p: *const clap_plugin, id: *const c_char) ->
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn on_main_thread(p: *const clap_plugin) {
|
||||
let f = unsafe { fx(p) };
|
||||
if !f.restart_wanted {
|
||||
return;
|
||||
}
|
||||
let host = unsafe { &*f.host };
|
||||
if std::mem::replace(&mut f.second_callback_asked, true) {
|
||||
f.restart_wanted = false;
|
||||
f.second_callback_asked = false;
|
||||
unsafe { (host.request_restart.unwrap())(f.host) };
|
||||
} else {
|
||||
unsafe { (host.request_callback.unwrap())(f.host) };
|
||||
}
|
||||
}
|
||||
unsafe extern "C" fn on_main_thread(_p: *const clap_plugin) {}
|
||||
|
||||
// ---- factory + entry ----
|
||||
|
||||
@@ -671,9 +641,6 @@ unsafe extern "C" fn factory_create(_f: *const clap_plugin_factory, host: *const
|
||||
gain: 1.0,
|
||||
mode: 0.0,
|
||||
level: 0.0,
|
||||
latency: 3,
|
||||
restart_wanted: false,
|
||||
second_callback_asked: false,
|
||||
active: false,
|
||||
processing: false,
|
||||
gui_created: false,
|
||||
|
||||
@@ -80,27 +80,6 @@ fn gain_processes_audio_and_follows_params() {
|
||||
p.process(&mut io, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_latency_counts_after_the_restart_the_plugin_asks_for() {
|
||||
fixture_dir();
|
||||
let mut p = soundcraft_clap_host::create(GAIN).unwrap();
|
||||
p.prepare(48_000.0, 64, 2);
|
||||
assert_eq!(p.latency(), 3);
|
||||
assert!(p.set_param("3", 2.0), "mode C takes 16 samples");
|
||||
let mut io = vec![vec![0.5f32; 64]; 2];
|
||||
p.process(&mut io, 64);
|
||||
assert_eq!(p.latency(), 3, "so far the plugin only asked for on_main_thread");
|
||||
// One idle runs both callbacks the plugin asks for (the second one asks for the restart).
|
||||
p.idle();
|
||||
assert_eq!(p.latency(), 16, "restarted with its new latency");
|
||||
assert_eq!(p.param("3"), Some(2.0));
|
||||
let mut io = vec![vec![0.5f32; 64]; 2];
|
||||
p.process(&mut io, 64);
|
||||
assert!(io[0].iter().all(|&x| (x - 0.5).abs() < 1e-6), "still processing after the restart: {:?}", &io[0][..4]);
|
||||
p.idle();
|
||||
assert_eq!(p.latency(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synth_plays_notes_at_their_offsets() {
|
||||
fixture_dir();
|
||||
|
||||
@@ -210,15 +210,6 @@ pub trait Plugin: Send {
|
||||
fn latency(&self) -> usize {
|
||||
0
|
||||
}
|
||||
/// Main-thread time between blocks, for hosted plugins: runs the callbacks the plugin asked
|
||||
/// for, restarts it when it asked to, and reads its latency again (some plugins only know it
|
||||
/// once they have processed). Offline renders call it after every block; the realtime audio
|
||||
/// thread never does.
|
||||
///
|
||||
/// For implementors: it runs between two `process` calls, on the thread that owns the instance,
|
||||
/// so it may allocate, block and re-activate the plugin, and it may change what `latency()`
|
||||
/// reports; callers read `latency()` again afterwards.
|
||||
fn idle(&mut self) {}
|
||||
/// How long the output keeps ringing after the input stops, in samples.
|
||||
fn tail_samples(&self) -> usize {
|
||||
0
|
||||
|
||||
@@ -27,7 +27,6 @@ mod more_util;
|
||||
mod options;
|
||||
mod plugin_state;
|
||||
mod query;
|
||||
mod room_tone;
|
||||
pub(crate) mod sampler;
|
||||
mod setup_more;
|
||||
mod strip_silence;
|
||||
@@ -63,7 +62,6 @@ mod panic_probe {
|
||||
}
|
||||
}
|
||||
|
||||
pub use clip_more::is_looped;
|
||||
pub use file::bounce_job;
|
||||
|
||||
pub(crate) use edit::remember_selection;
|
||||
@@ -167,7 +165,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(video::specs());
|
||||
v.extend(zoom_toggle::specs());
|
||||
v.extend(strip_silence::specs());
|
||||
v.extend(room_tone::specs());
|
||||
#[cfg(test)]
|
||||
v.extend(panic_probe::specs());
|
||||
v
|
||||
|
||||
@@ -40,9 +40,7 @@ fn audio_as_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
seq.sort();
|
||||
let count = seq.notes.len();
|
||||
let clip = Clip::midi(ClipId(0), "Audio as MIDI", 0, r.len(), seq);
|
||||
let mut clipboard = Clipboard { automation: vec![Vec::new()], ..Clipboard::of_range(s, r) };
|
||||
clipboard.push_clips(s, r.start, vec![clip]);
|
||||
e.clipboard = clipboard;
|
||||
e.clipboard = Clipboard { tracks: vec![vec![clip]], automation: vec![Vec::new()], ..Clipboard::of_range(e.session(), r) };
|
||||
Ok(json!({"notes": count, "length": r.len()}))
|
||||
}
|
||||
|
||||
|
||||
@@ -55,10 +55,6 @@ fn clear(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
pl.clips.retain(|c| !gone.contains(&c.id));
|
||||
}
|
||||
s.sources.retain(|f| !sources.contains(&f.id));
|
||||
// The room tone plays one of the removed files: nothing is left for it to play.
|
||||
if s.room_tone.is_some_and(|t| sources.contains(&t.source)) {
|
||||
s.room_tone = None;
|
||||
}
|
||||
for f in &sources {
|
||||
s.pool.remove(*f);
|
||||
}
|
||||
@@ -110,18 +106,6 @@ mod tests {
|
||||
assert_eq!(e.session().clips_using(f).count(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_room_tones_file_forgets_the_room_tone() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
let (f, clips) = kick(&e);
|
||||
e.execute("edit.room_tone_set", &json!({"clip": clips[0]})).unwrap();
|
||||
assert_eq!(e.session().room_tone.map(|t| t.source), Some(f));
|
||||
e.execute("clip.clear", &json!({"sources": [f], "with_clips": true})).unwrap();
|
||||
assert_eq!(e.session().room_tone, None);
|
||||
assert!(e.undo());
|
||||
assert_eq!(e.session().room_tone.map(|t| t.source), Some(f), "undo brings it back with the file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_a_files_clips_too_is_enough() {
|
||||
let mut e = crate::demo::demo_engine();
|
||||
|
||||
@@ -150,11 +150,6 @@ fn loop_chain(s: &Session, t: TrackId, id: ClipId) -> Vec<ClipId> {
|
||||
chain
|
||||
}
|
||||
|
||||
/// Whether a clip belongs to a loop that `clip.unloop` changes: two or more back-to-back copies.
|
||||
pub fn is_looped(s: &Session, id: ClipId) -> bool {
|
||||
s.find_clip(id).is_some_and(|(t, _)| loop_chain(s, t, id).len() >= 2)
|
||||
}
|
||||
|
||||
fn unloop(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "clip.unloop";
|
||||
let remove = match str_param(p, "mode") {
|
||||
|
||||
@@ -259,9 +259,7 @@ fn cut_copy(e: &mut Engine, p: &Value, cut: bool, id: &str) -> Result<Value> {
|
||||
let follow = e.session().edit.automation_follows_edit;
|
||||
for t in &tracks {
|
||||
// Cut carries only what it removes; a locked clip stays where it is (see `ops::take_range`).
|
||||
let s = e.session();
|
||||
let clips = if cut { ops::take_range(s, *t, range) } else { ops::copy_range(s, *t, range) };
|
||||
cb.push_clips(s, range.start, clips);
|
||||
cb.tracks.push(if cut { ops::take_range(e.session(), *t, range) } else { ops::copy_range(e.session(), *t, range) });
|
||||
let lanes = e
|
||||
.session()
|
||||
.track(*t)
|
||||
@@ -1219,9 +1217,9 @@ mod tests {
|
||||
let (mut e, t, at) = keys();
|
||||
let s = e.session_mut();
|
||||
let cc = soundcraft_midi::CtrlEvent { tick: 0, channel: 0, kind: soundcraft_midi::CtrlKind::Cc(1), value: 64 };
|
||||
let a = soundcraft_midi::Sequence { notes: vec![note(0, 1, 60), note(3, 2, 62), note(5, 1, 63)], ..Default::default() };
|
||||
let b = soundcraft_midi::Sequence { notes: vec![note(0, 1, 64)], ..Default::default() };
|
||||
let c = soundcraft_midi::Sequence { notes: vec![note(1, 1, 65)], ctrls: vec![cc], ..Default::default() };
|
||||
let a = soundcraft_midi::Sequence { notes: vec![note(0, 1, 60), note(3, 2, 62), note(5, 1, 63)], ctrls: vec![], sysex: vec![] };
|
||||
let b = soundcraft_midi::Sequence { notes: vec![note(0, 1, 64)], ctrls: vec![], sysex: vec![] };
|
||||
let c = soundcraft_midi::Sequence { notes: vec![note(1, 1, 65)], ctrls: vec![cc], sysex: vec![] };
|
||||
for (start, end, seq, muted) in [(0, 4, a, false), (6, 8, b, true), (8, 12, c, false)] {
|
||||
let id = s.new_clip_id();
|
||||
let mut clip = Clip::midi(id, "Keys", at(start), at(end) - at(start), seq);
|
||||
|
||||
@@ -448,19 +448,6 @@ fn paste_clip_effects(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"clips": ids.len()}))
|
||||
}
|
||||
|
||||
fn retain_midi_window(sequence: &mut soundcraft_midi::Sequence, end: i64) {
|
||||
let window = 0..end;
|
||||
sequence.notes.retain_mut(|note| {
|
||||
if !window.contains(¬e.start) {
|
||||
return false;
|
||||
}
|
||||
note.length = note.length.min(end - note.start);
|
||||
true
|
||||
});
|
||||
sequence.ctrls.retain(|event| window.contains(&event.tick));
|
||||
sequence.sysex.retain(|event| window.contains(&event.tick));
|
||||
}
|
||||
|
||||
fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "edit.paste_merge_midi";
|
||||
let tracks = tracks_required(e, id, p)?;
|
||||
@@ -473,22 +460,16 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let mut placed = 0;
|
||||
for (i, t) in tracks.iter().enumerate() {
|
||||
let Some(clips) = cb.tracks.get(i % cb.tracks.len().max(1)) else { continue };
|
||||
for source in clips {
|
||||
let mut c = source.clone();
|
||||
for c in clips {
|
||||
let pos = at.saturating_add(c.start);
|
||||
let ClipContent::Midi { sequence } = &mut c.content else {
|
||||
c.id = s.new_clip_id();
|
||||
c.start = pos;
|
||||
ops::place_clip(s, *t, c);
|
||||
let ClipContent::Midi { sequence } = &c.content else {
|
||||
let mut nc = c.clone();
|
||||
nc.id = s.new_clip_id();
|
||||
nc.start = pos;
|
||||
ops::place_clip(s, *t, nc);
|
||||
placed += 1;
|
||||
continue;
|
||||
};
|
||||
let paste_tick = tempo.samples_to_ticks(pos, sr);
|
||||
let sample_end = pos.saturating_add(c.length);
|
||||
let ticks = cb.midi_tick_lengths.get(&c.id).copied().unwrap_or_else(|| tempo.samples_to_ticks(sample_end, sr).saturating_sub(paste_tick));
|
||||
retain_midi_window(sequence, ticks);
|
||||
// At a slower destination tempo the same musical window needs more samples.
|
||||
let want_end = sample_end.max(tempo.tick_to_samples(paste_tick.saturating_add(ticks), sr));
|
||||
let target = s.track(*t).and_then(|tr| {
|
||||
let host = tr.clips().iter().find(|x| matches!(x.content, ClipContent::Midi { .. }) && x.range().contains(pos))?;
|
||||
let next_start = tr.clips().iter().filter(|x| x.start > host.start && x.id != host.id).map(|x| x.start).min();
|
||||
@@ -496,23 +477,22 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
});
|
||||
match target {
|
||||
Some((hid, hstart, next_start)) => {
|
||||
let diff = paste_tick - tempo.samples_to_ticks(hstart, sr);
|
||||
let diff = tempo.samples_to_ticks(pos, sr) - tempo.samples_to_ticks(hstart, sr);
|
||||
let want_end = pos.saturating_add(c.length);
|
||||
let limit = next_start.unwrap_or(Samples::MAX);
|
||||
if let Some(h) = s.find_clip_mut(hid)
|
||||
&& let ClipContent::Midi { sequence: hs } = &mut h.content
|
||||
{
|
||||
for mut n in sequence.notes.drain(..) {
|
||||
for n in &sequence.notes {
|
||||
let mut n = *n;
|
||||
n.start = n.start.saturating_add(diff);
|
||||
hs.notes.push(n);
|
||||
}
|
||||
for mut cc in sequence.ctrls.drain(..) {
|
||||
for cc in &sequence.ctrls {
|
||||
let mut cc = *cc;
|
||||
cc.tick = cc.tick.saturating_add(diff);
|
||||
hs.ctrls.push(cc);
|
||||
}
|
||||
for mut event in sequence.sysex.drain(..) {
|
||||
event.tick = event.tick.saturating_add(diff);
|
||||
hs.sysex.push(event);
|
||||
}
|
||||
hs.sort();
|
||||
if want_end > h.end() {
|
||||
h.trim_end_to(want_end.min(limit));
|
||||
@@ -521,17 +501,10 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Only extend through empty space. Keep the existing placement behavior
|
||||
// inside the original sample range and preserve material beyond it.
|
||||
if want_end > sample_end
|
||||
&& let Some(track) = s.track(*t)
|
||||
{
|
||||
let limit = track.clips().iter().filter(|other| other.end() > sample_end).map(|other| other.start.max(sample_end)).min();
|
||||
c.length = want_end.min(limit.unwrap_or(Samples::MAX)).saturating_sub(pos);
|
||||
}
|
||||
c.id = s.new_clip_id();
|
||||
c.start = pos;
|
||||
ops::place_clip(s, *t, c);
|
||||
let mut nc = c.clone();
|
||||
nc.id = s.new_clip_id();
|
||||
nc.start = pos;
|
||||
ops::place_clip(s, *t, nc);
|
||||
placed += 1;
|
||||
}
|
||||
}
|
||||
@@ -1170,7 +1143,7 @@ mod tests {
|
||||
e.execute("edit.select", &json!({"tracks": [keys.0], "start": r.start, "end": r.end})).unwrap();
|
||||
e.execute("edit.copy", &json!({})).unwrap();
|
||||
let copied = match &e.clipboard.tracks[0][0].content {
|
||||
ClipContent::Midi { sequence } => sequence.notes_in(0, e.clipboard.midi_tick_lengths[&clip.id]).count(),
|
||||
ClipContent::Midi { sequence } => sequence.notes.len(),
|
||||
_ => 0,
|
||||
};
|
||||
e.execute("edit.paste_merge_midi", &json!({"at": clip.start + 96_000})).unwrap();
|
||||
|
||||
@@ -349,9 +349,9 @@ fn select_split(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut nc = c.clone();
|
||||
nc.id = s.new_clip_id();
|
||||
// Note-split copies only the matching notes, not controllers or SysEx: packets stay on the
|
||||
// source clip. (Split, trim, Merge MIDI and consolidate re-anchor packets to the new clip
|
||||
// start.)
|
||||
// Note-split has always copied only the matching notes, not controllers. SysEx is the same
|
||||
// default now that Sequence has that field: packets stay on the source clip. Full SysEx
|
||||
// split/trim/heal is storytold/soundcraft#1618.
|
||||
nc.content = ClipContent::Midi { sequence: soundcraft_midi::Sequence { notes: hit, ctrls: Vec::new(), sysex: Vec::new() } };
|
||||
crate::edit::place_clip(s, nt, nc);
|
||||
}
|
||||
@@ -965,7 +965,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Note-split copies only the notes in the pitch range. SysEx already on the clip stays there;
|
||||
/// the new clip's sysex list is empty.
|
||||
/// the new clip's sysex list is empty (storytold/soundcraft#1618 owns split/trim of packets).
|
||||
#[test]
|
||||
fn note_split_leaves_sysex_on_the_source_clip() {
|
||||
let (mut e, t) = midi_engine();
|
||||
|
||||
@@ -44,7 +44,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
for t in &mut s.tracks { for pl in &mut t.playlists { pl.clips.clear() } }
|
||||
s.sources.clear();
|
||||
s.videos.clear();
|
||||
s.room_tone = None;
|
||||
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
||||
// A template too large to open is not saved (#892).
|
||||
crate::io::session_size(file.display(), text.len() as u64, true)?;
|
||||
@@ -74,21 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let at = position_param(e, "file.import_midi", p, "at")?.unwrap_or(0);
|
||||
let bytes = crate::io::read_file(&path)?;
|
||||
let tracks = crate::io::import_midi_bytes(e, &bytes, at, bool_or(p, "tempo_map", true))?;
|
||||
let sysex_packets: usize = tracks
|
||||
.iter()
|
||||
.filter_map(|id| e.session().track(*id))
|
||||
.flat_map(|t| t.clips())
|
||||
.map(|c| match &c.content {
|
||||
soundcraft_model::ClipContent::Midi { sequence } => sequence.sysex.len(),
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
let mut result = json!({"tracks": tracks});
|
||||
if sysex_packets > 0 {
|
||||
result["sysex_packets"] = json!(sysex_packets);
|
||||
result["warnings"] = json!(["SysEx packets are retained for session saves and MIDI export; SysEx playback is not supported."]);
|
||||
}
|
||||
Ok(result)
|
||||
Ok(json!({"tracks": tracks}))
|
||||
}),
|
||||
cmd!(
|
||||
"file.import_video",
|
||||
|
||||
@@ -36,17 +36,12 @@ pub fn set_flags(e: &mut Engine, ids: &[&str], on: bool) -> Value {
|
||||
json!({"flags": ids, "value": on})
|
||||
}
|
||||
|
||||
/// A string setting as [`set_text`] stores it: trimmed, cut to 200 characters, then trimmed again.
|
||||
/// The second trim drops a space at the cut, so a later call returns the same string. Empty clears it.
|
||||
pub fn text_value(value: &str) -> String {
|
||||
value.trim().chars().take(200).collect::<String>().trim_end().to_string()
|
||||
}
|
||||
|
||||
/// String settings live in `edit.flags` as `key=value` (one per key).
|
||||
pub fn set_text(edit: &mut EditState, key: &str, value: Option<&str>) {
|
||||
let prefix = format!("{key}=");
|
||||
edit.flags.retain(|f| !f.starts_with(&prefix));
|
||||
if let Some(v) = value.map(text_value).filter(|v| !v.is_empty()) {
|
||||
if let Some(v) = value.map(str::trim).filter(|v| !v.is_empty()) {
|
||||
let v: String = v.chars().take(200).collect();
|
||||
edit.flags.insert(format!("{prefix}{v}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,489 +0,0 @@
|
||||
//! Room tone: choose a stretch of recorded silence and fill gaps with it instead of digital silence.
|
||||
//!
|
||||
//! The fill is made of ordinary audio clips that play the chosen window, overlapped and
|
||||
//! crossfaded where the gap is longer than the tone, so it can be edited like any other clip.
|
||||
|
||||
use super::{CommandSpec, always, bad, clip_ids_param, f64_or, has_range, range_param, tracks_required};
|
||||
use crate::{Engine, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{Clip, ClipContent, Fade, FadeShape, RoomTone, Session, TrackId, TrackKind};
|
||||
use soundcraft_time::{Range, Samples};
|
||||
|
||||
const SET: &str = "edit.room_tone_set";
|
||||
const FILL: &str = "edit.room_tone_fill";
|
||||
|
||||
/// The shortest room tone accepted, in seconds: shorter windows tile into a buzz and many clips.
|
||||
const MIN_TONE_SECONDS: f64 = 0.1;
|
||||
/// The most clips one fill makes, so a huge range can't flood the playlist.
|
||||
const MAX_FILL_CLIPS: usize = 20_000;
|
||||
/// The name the fill clips get.
|
||||
const CLIP_NAME: &str = "Room Tone";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"edit.room_tone_set",
|
||||
"Set Room Tone",
|
||||
["Edit", "Room Tone"],
|
||||
None,
|
||||
"{clip?} — the clip (default: the selected clip) becomes the session's room tone; with no `clip`, an edit selection inside the clip picks just that part. At least 0.1 s, not elastic. Returns the window",
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!(
|
||||
"edit.room_tone_fill",
|
||||
"Fill Gaps with Room Tone",
|
||||
["Edit", "Room Tone"],
|
||||
None,
|
||||
"{tracks?, start?, end?, fade_ms?: 10, edge_fade_ms?: 2, min_gap_ms?: 0} — fills every empty stretch of the range on each audio track with clips of the room tone, tiled with crossfades of `fade_ms` where the gap is longer than the tone, and faded in and out over `edge_fade_ms` at the edges of each gap (short, so the background does not dip next to speech); gaps shorter than `min_gap_ms` are left alone. Returns {clips, gaps}",
|
||||
fillable,
|
||||
fill
|
||||
),
|
||||
cmd!(
|
||||
"edit.room_tone_clear",
|
||||
"Clear Room Tone",
|
||||
["Edit", "Room Tone"],
|
||||
None,
|
||||
"{} — forgets the room tone; clips already filled stay",
|
||||
has_tone,
|
||||
|e, _| {
|
||||
let was = e.session_mut().room_tone.take();
|
||||
Ok(json!({"cleared": was.is_some()}))
|
||||
}
|
||||
),
|
||||
cmd!(query "edit.room_tone", "Room Tone", [], None, "{} — the room tone window {source, offset, length, gain_db}, or null", always, |e, _| {
|
||||
Ok(e.session().room_tone.map_or(Value::Null, |t| describe(e.session(), t)))
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
fn has_tone(e: &Engine) -> std::result::Result<(), String> {
|
||||
if e.session().room_tone.is_some() { Ok(()) } else { Err("set a room tone first (Edit › Room Tone › Set Room Tone)".into()) }
|
||||
}
|
||||
|
||||
fn fillable(e: &Engine) -> std::result::Result<(), String> {
|
||||
has_tone(e)?;
|
||||
has_range(e)
|
||||
}
|
||||
|
||||
fn describe(s: &Session, t: RoomTone) -> Value {
|
||||
let name = s.source(t.source).map(|f| f.name.clone());
|
||||
json!({"source": t.source.0, "source_name": name, "offset": t.offset, "length": t.length, "gain_db": t.gain_db})
|
||||
}
|
||||
|
||||
fn set(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let explicit = p.get("clip").is_some() || p.get("clips").is_some();
|
||||
let ids = clip_ids_param(e, p);
|
||||
let s = e.session();
|
||||
let id = match ids.as_slice() {
|
||||
[id] => *id,
|
||||
[] => return Err(bad(SET, "select the clip of room tone, or pass `clip`")),
|
||||
_ => return Err(bad(SET, "select one clip of room tone, not several")),
|
||||
};
|
||||
let (_, clip) = s.find_clip(id).ok_or_else(|| bad(SET, format!("no clip with id {}", id.0)))?;
|
||||
let ClipContent::Audio { source, .. } = clip.content else {
|
||||
return Err(bad(SET, format!("“{}” is not an audio clip", clip.name)));
|
||||
};
|
||||
if (clip.stretch - 1.0).abs() > f64::EPSILON {
|
||||
return Err(bad(SET, format!("“{}” is time-stretched; render it first", clip.name)));
|
||||
}
|
||||
// An edit selection inside the clip picks part of it.
|
||||
let sel = s.edit.selection;
|
||||
let window = if explicit || sel.is_empty() {
|
||||
clip.range()
|
||||
} else {
|
||||
sel.intersect(&clip.range()).ok_or_else(|| bad(SET, "the edit selection is outside the clip"))?
|
||||
};
|
||||
let offset = clip.source_offset().saturating_add(window.start - clip.start);
|
||||
let stored = s.source(source).map(|f| f.frames).ok_or_else(|| bad(SET, format!("the audio file of “{}” is missing", clip.name)))?;
|
||||
// The stored count isn't refreshed when a session reopens; the decoded audio is what plays.
|
||||
let frames = s.pool.get(source).map_or(stored, |a| a.frames() as u64);
|
||||
let tone = RoomTone { source, offset, length: window.len(), gain_db: clip.gain_db }
|
||||
.sanitized(frames)
|
||||
.ok_or_else(|| bad(SET, format!("“{}” plays no audio from its file", clip.name)))?;
|
||||
if tone.length < s.sample_rate.samples(MIN_TONE_SECONDS) {
|
||||
return Err(bad(SET, format!("room tone must be at least {MIN_TONE_SECONDS} s long")));
|
||||
}
|
||||
let s = e.session_mut();
|
||||
// A session reopens with the room tone cut to the stored count, so record the decoded one.
|
||||
if let Some(f) = s.sources.iter_mut().find(|f| f.id == source && f.frames < frames) {
|
||||
f.frames = frames;
|
||||
}
|
||||
s.room_tone = Some(tone);
|
||||
Ok(describe(e.session(), tone))
|
||||
}
|
||||
|
||||
/// The empty stretches of `range` on `track`'s active playlist, at least `min` samples long.
|
||||
fn gaps(s: &Session, track: TrackId, range: Range, min: Samples) -> Vec<Range> {
|
||||
let Some(t) = s.track(track) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut at = range.start;
|
||||
let mut clips: Vec<Range> = t.clips().iter().map(Clip::range).filter(|r| r.end > range.start && r.start < range.end).collect();
|
||||
clips.sort_by_key(|r| r.start);
|
||||
for c in clips {
|
||||
if c.start > at {
|
||||
out.push(Range::new(at, c.start));
|
||||
}
|
||||
at = at.max(c.end);
|
||||
}
|
||||
if at < range.end {
|
||||
out.push(Range::new(at, range.end));
|
||||
}
|
||||
out.retain(|g| g.len() >= min.max(1));
|
||||
out
|
||||
}
|
||||
|
||||
/// The clips that fill `gap` with `tone`: whole tone windows, each overlapping the one before by
|
||||
/// `fade` samples with a crossfade, the last cut to the gap's end; the first fades in and the last
|
||||
/// fades out over `edge` (or less, in a short gap). `None` when that takes more than `budget` clips.
|
||||
fn tiles(tone: RoomTone, gap: Range, fade: Samples, edge: Samples, budget: usize) -> Option<Vec<Clip>> {
|
||||
let edge = edge.max(0);
|
||||
// The overlap must leave each tile moving forward.
|
||||
let fade = fade.clamp(0, tone.length / 2);
|
||||
let step = tone.length - fade;
|
||||
if step <= 0 {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
// Count before allocating: a long gap and a short tone could otherwise make millions.
|
||||
let needed = gap.len().saturating_sub(fade).max(1).saturating_add(step - 1) / step;
|
||||
if usize::try_from(needed).map_or(true, |n| n > budget) {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<Clip> = Vec::new();
|
||||
let mut at = gap.start;
|
||||
while at < gap.end && out.len() <= budget {
|
||||
let length = tone.length.min(gap.end - at);
|
||||
let mut c = Clip::audio(soundcraft_model::ClipId(0), CLIP_NAME, tone.source, tone.offset, at, length);
|
||||
c.gain_db = tone.gain_db;
|
||||
let crossfade = Fade { len: fade.min(length), shape: FadeShape::EqualPower, curvature: 0.0 };
|
||||
if let Some(prev) = out.last_mut() {
|
||||
prev.fade_out = crossfade;
|
||||
c.fade_in = crossfade;
|
||||
} else {
|
||||
c.fade_in = Fade { len: edge.min(length / 2), ..crossfade };
|
||||
}
|
||||
if at + length >= gap.end {
|
||||
// The last tile also fades out to the gap's edge, leaving room for its fade in.
|
||||
c.fade_out = Fade { len: edge.min(length - c.fade_in.len).max(0), ..crossfade };
|
||||
out.push(c);
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
at = at.saturating_add(step);
|
||||
}
|
||||
(out.len() <= budget).then_some(out)
|
||||
}
|
||||
|
||||
fn fill(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let tone = e.session().room_tone.ok_or_else(|| bad(FILL, "set a room tone first"))?;
|
||||
let tracks = tracks_required(e, FILL, p)?;
|
||||
let range = range_param(e, FILL, p)?;
|
||||
if range.is_empty() {
|
||||
return Err(bad(FILL, "select a range to fill"));
|
||||
}
|
||||
let s = e.session();
|
||||
let name = s.source(tone.source).map_or_else(|| "the room tone's audio file".to_string(), |f| format!("`{}`", f.name));
|
||||
let Some(audio) = s.pool.get(tone.source) else {
|
||||
return Err(bad(FILL, format!("{name} is not loaded; relink it before filling")));
|
||||
};
|
||||
// The window was checked against the session file's frame count, which can be stale when the
|
||||
// file was replaced by a shorter one: tile only audio that decoded.
|
||||
let tone = tone
|
||||
.sanitized(audio.frames() as u64)
|
||||
.filter(|t| t.length >= s.sample_rate.samples(MIN_TONE_SECONDS))
|
||||
.ok_or_else(|| bad(FILL, format!("{name} is now shorter than the room tone; set the room tone again")))?;
|
||||
let ms = |k: &str, d: f64| s.sample_rate.samples(f64_or(p, k, d).clamp(0.0, 10_000.0) / 1000.0);
|
||||
let (fade, edge, min_gap) = (ms("fade_ms", 10.0), ms("edge_fade_ms", 2.0), ms("min_gap_ms", 0.0));
|
||||
// Plan every track first, so a fill that would be too big changes nothing.
|
||||
let mut plan: Vec<(TrackId, Vec<Clip>)> = Vec::new();
|
||||
let (mut count, mut gap_count) = (0usize, 0usize);
|
||||
for t in tracks {
|
||||
if s.track(t).is_none_or(|tr| tr.kind != TrackKind::Audio) {
|
||||
continue;
|
||||
}
|
||||
let mut clips = Vec::new();
|
||||
for gap in gaps(s, t, range, min_gap) {
|
||||
let budget = MAX_FILL_CLIPS.saturating_sub(count.saturating_add(clips.len()));
|
||||
let made = tiles(tone, gap, fade, edge, budget).ok_or_else(|| {
|
||||
bad(FILL, format!("that would make more than {MAX_FILL_CLIPS} clips; fill a shorter range or use a longer room tone"))
|
||||
})?;
|
||||
clips.extend(made);
|
||||
gap_count += 1;
|
||||
}
|
||||
count += clips.len();
|
||||
plan.push((t, clips));
|
||||
}
|
||||
if gap_count == 0 {
|
||||
return Err(bad(FILL, "no empty space to fill on the audio tracks in that range"));
|
||||
}
|
||||
let s = e.session_mut();
|
||||
for (t, mut clips) in plan {
|
||||
for c in &mut clips {
|
||||
c.id = s.new_clip_id();
|
||||
}
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.extend(clips);
|
||||
pl.sort();
|
||||
}
|
||||
}
|
||||
Ok(json!({"clips": count, "gaps": gap_count}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_model::{ChannelFormat, ClipId, FileFormat, SourceAudio, SourceId};
|
||||
use std::sync::Arc;
|
||||
|
||||
const RATE: Samples = 48_000;
|
||||
|
||||
/// A session with one mono track holding `clips` (start, length) of a 10 s source, the first
|
||||
/// of which plays 1 s of room tone from the start of the file.
|
||||
fn engine(clips: &[(Samples, Samples)]) -> (Engine, TrackId, Vec<ClipId>) {
|
||||
let mut e = Engine::default();
|
||||
let s = e.session_mut();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Narration"));
|
||||
let src = SourceId(s.alloc());
|
||||
let frames = 10 * RATE as usize;
|
||||
s.sources.push(soundcraft_model::Source {
|
||||
id: src,
|
||||
name: "Take".into(),
|
||||
path: "Take.wav".into(),
|
||||
channels: 1,
|
||||
frames: frames as u64,
|
||||
sample_rate: 48_000,
|
||||
format: FileFormat::Wav,
|
||||
time_reference: 0,
|
||||
unsaved: false,
|
||||
});
|
||||
// Quiet white noise, like a room: uncorrelated from one moment to the next.
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let noise: Vec<f32> = (0..frames)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
(seed as f32 / u32::MAX as f32 - 0.5) * 0.02
|
||||
})
|
||||
.collect();
|
||||
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![noise] };
|
||||
s.pool.insert(src, Arc::new(SourceAudio::new(buffer)));
|
||||
let mut ids = Vec::new();
|
||||
for (i, (start, length)) in clips.iter().enumerate() {
|
||||
let id = s.new_clip_id();
|
||||
let offset = if i == 0 { 0 } else { RATE * 2 };
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.push(Clip::audio(id, format!("Clip {i}"), src, offset, *start, *length));
|
||||
pl.sort();
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
s.edit.selected_tracks = vec![t];
|
||||
(e, t, ids)
|
||||
}
|
||||
|
||||
fn clips(e: &Engine, t: TrackId) -> Vec<Clip> {
|
||||
e.session().track(t).map(|tr| tr.clips().to_vec()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_takes_the_selected_clip_or_the_selected_part_of_it() {
|
||||
let (mut e, _, ids) = engine(&[(0, RATE)]);
|
||||
e.session_mut().edit.selected_clips = vec![ids[0]];
|
||||
let r = e.execute(SET, &json!({})).unwrap();
|
||||
assert_eq!((r["offset"].as_i64(), r["length"].as_i64()), (Some(0), Some(RATE)));
|
||||
e.session_mut().edit.selected_clips.clear();
|
||||
e.session_mut().edit.selection = Range::new(RATE / 4, RATE / 2);
|
||||
let r = e.execute(SET, &json!({})).unwrap();
|
||||
assert_eq!((r["offset"].as_i64(), r["length"].as_i64()), (Some(RATE / 4), Some(RATE / 4)));
|
||||
e.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(e.session().room_tone.map(|t| t.length), Some(RATE), "undo restores the previous tone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tone_past_a_stale_stored_length_survives_a_reload() {
|
||||
// The session file says 3 s, but 10 s decoded: the tone at 4..5 s plays.
|
||||
let (mut e, t, _) = engine(&[]);
|
||||
let s = e.session_mut();
|
||||
let src = s.sources.first().map(|f| f.id).unwrap();
|
||||
s.sources.iter_mut().for_each(|f| f.frames = 3 * RATE as u64);
|
||||
let id = s.new_clip_id();
|
||||
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
|
||||
pl.clips.push(Clip::audio(id, "Late", src, 4 * RATE, 0, RATE));
|
||||
}
|
||||
e.execute(SET, &json!({"clip": id.0})).unwrap();
|
||||
let tone = e.session().room_tone;
|
||||
assert_eq!(tone.map(|t| (t.offset, t.length)), Some((4 * RATE, RATE)));
|
||||
let loaded = Session::from_json(&e.session().to_json().unwrap()).unwrap();
|
||||
assert_eq!(loaded.room_tone, tone, "reopening keeps the tone that was set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_refuses_what_cannot_be_a_room_tone() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE / 20)]);
|
||||
assert!(e.execute(SET, &json!({"clip": ids[0].0})).is_err(), "50 ms is too short");
|
||||
assert!(e.execute(SET, &json!({"clip": 9999})).is_err(), "unknown clip");
|
||||
e.session_mut().edit.selected_tracks = vec![t];
|
||||
e.session_mut().edit.selection = Range::new(RATE * 5, RATE * 6);
|
||||
assert!(e.execute(SET, &json!({})).is_err(), "nothing selected");
|
||||
assert_eq!(e.session().room_tone, None);
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": RATE})).is_err(), "no tone to fill with");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_puts_crossfaded_tone_clips_in_every_gap_and_nowhere_else() {
|
||||
// Tone 0..1 s, speech 3..4 s; fill 0..6 s: gaps 1..3 s (2 s) and 4..6 s (2 s).
|
||||
let (mut e, t, ids) = engine(&[(0, RATE), (3 * RATE, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
let fade = RATE / 100;
|
||||
let r = e.execute(FILL, &json!({"start": 0, "end": 6 * RATE})).unwrap();
|
||||
assert_eq!(r["gaps"], 2);
|
||||
let fills: Vec<Clip> = clips(&e, t).into_iter().filter(|c| !ids.contains(&c.id)).collect();
|
||||
assert_eq!(r["clips"].as_u64(), Some(fills.len() as u64));
|
||||
for gap in [Range::new(RATE, 3 * RATE), Range::new(4 * RATE, 6 * RATE)] {
|
||||
let mut in_gap: Vec<&Clip> = fills.iter().filter(|c| gap.contains(c.start)).collect();
|
||||
in_gap.sort_by_key(|c| c.start);
|
||||
// 2 s of a 1 s tone with 10 ms overlaps: three tiles, the last cut short.
|
||||
assert_eq!(in_gap.len(), 3, "{gap:?}");
|
||||
assert_eq!(in_gap.first().map(|c| c.start), Some(gap.start));
|
||||
assert_eq!(in_gap.last().map(|c| c.end()), Some(gap.end), "the fill ends at the gap's edge");
|
||||
for pair in in_gap.windows(2) {
|
||||
assert_eq!(pair[0].end() - pair[1].start, fade, "neighbours overlap by the crossfade");
|
||||
assert_eq!((pair[0].fade_out.len, pair[1].fade_in.len), (fade, fade));
|
||||
}
|
||||
let edge = RATE / 500;
|
||||
assert_eq!(in_gap[0].fade_in.len, edge, "a short de-click fade at the gap's edges");
|
||||
assert!(in_gap.last().is_some_and(|c| c.fade_out.len == edge));
|
||||
for c in &in_gap {
|
||||
assert_eq!(c.name, CLIP_NAME);
|
||||
assert_eq!(c.source_offset(), 0);
|
||||
assert!(c.length <= RATE);
|
||||
}
|
||||
}
|
||||
// The original clips are untouched and nothing covers them.
|
||||
let all = clips(&e, t);
|
||||
for id in &ids {
|
||||
let c = all.iter().find(|c| c.id == *id).unwrap();
|
||||
assert!(fills.iter().all(|f| !f.range().overlaps(&c.range())), "fill over {}", c.name);
|
||||
}
|
||||
e.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(clips(&e, t).len(), 2, "undo removes the whole fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_plays_at_the_tones_level_through_every_crossfade() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
e.execute(FILL, &json!({"tracks": [t.0], "start": 0, "end": 5 * RATE, "fade_ms": 50})).unwrap();
|
||||
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 5 * RATE), 512);
|
||||
let left = &out[0];
|
||||
let rms = |a: usize, b: usize| (left[a..b].iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / (b - a) as f64).sqrt();
|
||||
let tone = rms(0, RATE as usize);
|
||||
assert!(tone > 0.0);
|
||||
// 20 ms windows from where the tone clip ends to the end of the fill: the edge fades are
|
||||
// too short to dip a window, and the crossfades keep the power.
|
||||
let win = (RATE / 50) as usize;
|
||||
for w in (RATE as usize..(5 * RATE) as usize - win).step_by(win) {
|
||||
let db = 20.0 * (rms(w, w + win) / tone).log10();
|
||||
assert!(db.abs() < 1.5, "level {db:.2} dB off the tone at {} s", w as f64 / RATE as f64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_skips_short_gaps_and_refuses_when_nothing_is_empty() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE), (RATE + 100, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": 2 * RATE + 100, "min_gap_ms": 5})).is_err(), "the 100-sample gap is under 5 ms");
|
||||
let r = e.execute(FILL, &json!({"start": 0, "end": 2 * RATE + 100})).unwrap();
|
||||
assert_eq!((r["gaps"].as_u64(), r["clips"].as_u64()), (Some(1), Some(1)));
|
||||
let short = clips(&e, t).into_iter().find(|c| !ids.contains(&c.id)).unwrap();
|
||||
assert_eq!((short.start, short.length), (RATE, 100));
|
||||
assert!(short.fade_in.len + short.fade_out.len <= short.length, "fades fit a short gap");
|
||||
assert_eq!((short.fade_in.len, short.fade_out.len), (50, 50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_too_big_changes_nothing() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE / 5)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
// 200 ms tiles over 4 hours is far more than the cap.
|
||||
let r = e.execute(FILL, &json!({"start": 0, "end": RATE * 4 * 3600}));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(clips(&e, t).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_ignores_non_audio_tracks_and_needs_loaded_audio() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
let aux = e.session_mut().add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
|
||||
let r = e.execute(FILL, &json!({"tracks": [t.0, aux.0], "start": 0, "end": 2 * RATE})).unwrap();
|
||||
assert_eq!(r["gaps"], 1);
|
||||
let tone = e.session().room_tone.unwrap();
|
||||
e.session_mut().pool.remove(tone.source);
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": 3 * RATE})).is_err(), "unloaded audio is not filled with");
|
||||
}
|
||||
|
||||
/// Replaces the tone's pooled audio with `frames` frames of silence, as when its file was
|
||||
/// swapped for a shorter one: the stored `Source.frames` keeps the old length.
|
||||
fn shorten_audio(e: &mut Engine, frames: usize) {
|
||||
let src = e.session().sources.first().map(|f| f.id).unwrap();
|
||||
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; frames]] };
|
||||
e.session_mut().pool.insert(src, Arc::new(SourceAudio::new(buffer)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_reads_only_the_audio_that_decoded() {
|
||||
// Tone 0..1 s; the file now decodes to 0.5 s.
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
shorten_audio(&mut e, (RATE / 2) as usize);
|
||||
e.execute(FILL, &json!({"start": 0, "end": 3 * RATE})).unwrap();
|
||||
let fills: Vec<Clip> = clips(&e, t).into_iter().filter(|c| !ids.contains(&c.id)).collect();
|
||||
assert!(!fills.is_empty());
|
||||
for c in &fills {
|
||||
assert!(c.source_offset() + c.length <= RATE / 2, "a fill clip reads past the decoded audio: {c:?}");
|
||||
}
|
||||
// Less than the minimum left: refused, nothing placed.
|
||||
shorten_audio(&mut e, (RATE / 20) as usize);
|
||||
let before = clips(&e, t).len();
|
||||
assert!(e.execute(FILL, &json!({"start": 0, "end": 6 * RATE})).is_err());
|
||||
assert_eq!(clips(&e, t).len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_measures_the_window_against_the_decoded_audio() {
|
||||
let (mut e, _, ids) = engine(&[(0, RATE)]);
|
||||
shorten_audio(&mut e, (RATE / 2) as usize);
|
||||
let r = e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
assert_eq!(r["length"].as_i64(), Some(RATE / 2));
|
||||
shorten_audio(&mut e, (RATE / 20) as usize);
|
||||
assert!(e.execute(SET, &json!({"clip": ids[0].0})).is_err(), "only 50 ms decoded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_forgets_the_tone_but_keeps_the_fill() {
|
||||
let (mut e, t, ids) = engine(&[(0, RATE)]);
|
||||
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
|
||||
e.execute(FILL, &json!({"start": 0, "end": 2 * RATE})).unwrap();
|
||||
e.execute("edit.room_tone_clear", &json!({})).unwrap();
|
||||
assert_eq!(e.session().room_tone, None);
|
||||
assert_eq!(e.execute("edit.room_tone", &json!({})).unwrap(), Value::Null);
|
||||
assert_eq!(clips(&e, t).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_never_stall_or_overrun_on_odd_lengths() {
|
||||
let tone = RoomTone { source: SourceId(1), offset: 0, length: 3, gain_db: 0.0 };
|
||||
for (gap, fade) in [(Range::new(0, 1), 10), (Range::new(5, 17), 2), (Range::new(0, 1000), 0), (Range::new(0, 7), 1000)] {
|
||||
let t = tiles(tone, gap, fade, fade, MAX_FILL_CLIPS).unwrap();
|
||||
assert_eq!(t.first().map(|c| c.start), Some(gap.start));
|
||||
assert_eq!(t.last().map(Clip::end), Some(gap.end));
|
||||
assert!(t.iter().all(|c| c.length > 0 && c.fade_in.len + c.fade_out.len <= c.length), "{gap:?} {fade}");
|
||||
}
|
||||
let huge = Range::new(0, soundcraft_time::MAX_POSITION);
|
||||
assert!(tiles(tone, huge, 0, 0, MAX_FILL_CLIPS).is_none(), "refused before allocating");
|
||||
assert_eq!(tiles(tone, Range::new(0, 9), 0, 0, 3).map(|t| t.len()), Some(3), "exactly the budget is fine");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! shortcuts, MIDI setup) and File › Import › Session Data.
|
||||
use super::{CommandSpec, always, bad, command_specs, i64_or, str_param, track_param, tracks_param};
|
||||
|
||||
use super::more_util::{set_text, store_value, text, text_value, toggle_flag, values_with_prefix};
|
||||
use super::more_util::{set_text, store_value, text, toggle_flag, values_with_prefix};
|
||||
use crate::{Engine, EngineError, Result, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_model::{BusId, ChannelFormat, ClipContent, OutputPath, Route, Session, SourceId, TrackId, TrackKind};
|
||||
@@ -242,16 +242,8 @@ fn engine_settings(e: &mut Engine, p: &Value, id: &str) -> Result<Value> {
|
||||
fn disk_allocation(e: &mut Engine, p: &Value) -> Result<Value> {
|
||||
let id = "setup.disk_allocation";
|
||||
let t = track_param(e, id, p, "track")?;
|
||||
// The path that is checked is the path that is stored. `text_value` trims, cuts to 200
|
||||
// characters, and trims again, which is what `set_text` keeps.
|
||||
// An empty one clears the setting and names no folder, so it isn't checked.
|
||||
let path = str_param(p, "path").map(text_value);
|
||||
// Checked before `session_mut` so a refused path leaves the session untouched.
|
||||
if let Some(path) = path.as_deref().filter(|v| !v.is_empty()) {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Io)?;
|
||||
}
|
||||
let s = e.session_mut();
|
||||
if let Some(path) = path.as_deref() {
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let key = t.map_or_else(|| "disk.root".to_string(), |t| format!("disk.track.{}", t.0));
|
||||
set_text(&mut s.edit, &key, Some(path));
|
||||
}
|
||||
|
||||
@@ -295,23 +295,7 @@ fn new_track_row(e: &mut Engine, p: &Value) -> Result<Vec<TrackId>> {
|
||||
};
|
||||
let name = str_param(p, "name").map(str::to_string);
|
||||
let ticks = str_param(p, "timebase").map(|t| t == "ticks");
|
||||
// A missing instrument asks for the default; an explicit value must be a string plugin id,
|
||||
// even before a non-instrument row ignores it, so a number is not silently treated as absent.
|
||||
let instrument = match p.get("instrument") {
|
||||
None => None,
|
||||
Some(value) => {
|
||||
let id = value.as_str().ok_or_else(|| bad("track.new", "`instrument` must be a plugin id string"))?;
|
||||
if kind == TrackKind::Instrument {
|
||||
let info = super::clap::plugin_info(id).ok_or_else(|| bad("track.new", format!("unknown plugin `{id}`")))?;
|
||||
if !info.is_instrument {
|
||||
return Err(bad("track.new", format!("`{id}` is not an instrument")));
|
||||
}
|
||||
Some(info.id.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let instrument = str_param(p, "instrument").map(str::to_string);
|
||||
let s = e.session_mut();
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..count {
|
||||
@@ -1297,30 +1281,4 @@ mod tests {
|
||||
assert!(e.undo());
|
||||
assert_eq!(vca(&e), Some(master.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_instrument_track_validates_the_instrument_id() {
|
||||
let mut e = Engine::default();
|
||||
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": "no.such.plugin"})).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": "eq_7band"})).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
// An explicit non-string is malformed, not a request for the default.
|
||||
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": 42})).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
// In a batch, a malformed second row rolls the first row back too.
|
||||
let batch = json!({"rows": [
|
||||
{"kind": "instrument", "instrument": "drum_synth"},
|
||||
{"kind": "instrument", "instrument": 42},
|
||||
]});
|
||||
assert!(e.execute("track.new", &batch).is_err());
|
||||
assert_eq!(e.session().tracks.len(), 0);
|
||||
// Omitted still asks for the default instrument.
|
||||
let r = e.execute("track.new", &json!({"kind": "instrument"})).unwrap();
|
||||
let id = TrackId(r["tracks"][0].as_u64().unwrap());
|
||||
assert_eq!(e.session().track(id).unwrap().instrument.as_ref().unwrap().plugin, "subtractive_synth");
|
||||
let r = e.execute("track.new", &json!({"kind": "instrument", "instrument": "drum_synth"})).unwrap();
|
||||
let id = TrackId(r["tracks"][0].as_u64().unwrap());
|
||||
assert_eq!(e.session().track(id).unwrap().instrument.as_ref().unwrap().plugin, "drum_synth");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,9 +325,6 @@ mod tests {
|
||||
doc.pool.remove(SourceId(900));
|
||||
check(&saved, &doc, false, "decoded audio removed");
|
||||
let mut doc = saved.clone();
|
||||
doc.room_tone = Some(soundcraft_model::RoomTone { source: SourceId(900), offset: 0, length: 10, gain_db: 0.0 });
|
||||
check(&saved, &doc, false, "session room tone");
|
||||
let mut doc = saved.clone();
|
||||
doc.folder = Some(std::path::PathBuf::from("session"));
|
||||
check(&saved, &doc, false, "session folder");
|
||||
let mut doc = saved.clone();
|
||||
|
||||
@@ -48,19 +48,14 @@ pub fn split_clip(clip: &Clip, at: Samples, new_id: ClipId, t: TimeCtx<'_>) -> O
|
||||
let boundary = t.ticks(at) - t.ticks(clip.start);
|
||||
ls.notes.retain(|n| n.start < boundary);
|
||||
ls.ctrls.retain(|c| c.tick < boundary);
|
||||
ls.sysex.retain(|e| e.tick < boundary);
|
||||
rs.notes.retain(|n| n.start >= boundary);
|
||||
rs.ctrls.retain(|c| c.tick >= boundary);
|
||||
rs.sysex.retain(|e| e.tick >= boundary);
|
||||
for n in &mut rs.notes {
|
||||
n.start -= boundary;
|
||||
}
|
||||
for c in &mut rs.ctrls {
|
||||
c.tick -= boundary;
|
||||
}
|
||||
for e in &mut rs.sysex {
|
||||
e.tick -= boundary;
|
||||
}
|
||||
}
|
||||
Some((left, right))
|
||||
}
|
||||
@@ -74,16 +69,12 @@ fn rebase_midi_start(clip: &mut Clip, old_start: Samples, t: TimeCtx<'_>) {
|
||||
}
|
||||
sequence.notes.retain(|n| n.start >= delta);
|
||||
sequence.ctrls.retain(|c| c.tick >= delta);
|
||||
sequence.sysex.retain(|e| e.tick >= delta);
|
||||
for n in &mut sequence.notes {
|
||||
n.start -= delta;
|
||||
}
|
||||
for c in &mut sequence.ctrls {
|
||||
c.tick -= delta;
|
||||
}
|
||||
for e in &mut sequence.sysex {
|
||||
e.tick -= delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,10 +323,6 @@ pub fn consolidate_midi(s: &mut Session, track: TrackId, range: Range) -> bool {
|
||||
c.tick += at;
|
||||
merged.ctrls.push(c);
|
||||
}
|
||||
for mut e in sequence.sysex.into_iter().filter(|e| (0..len).contains(&e.tick)) {
|
||||
e.tick += at;
|
||||
merged.sysex.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
merged.sort();
|
||||
|
||||
@@ -335,8 +335,6 @@ pub struct Bounce {
|
||||
gain: f32,
|
||||
peak: f32,
|
||||
meter: soundcraft_dsp::meter::LoudnessMeter,
|
||||
/// The file has an integer bit depth, so the encoder clips to full scale (a float file keeps its headroom).
|
||||
integer: bool,
|
||||
enc: Option<craft_audio::FileEncoder<Out>>,
|
||||
}
|
||||
|
||||
@@ -411,7 +409,6 @@ impl Bounce {
|
||||
peak: 0.0,
|
||||
meter,
|
||||
enc: Some(enc),
|
||||
integer: opts.bit_depth != craft_audio::BitDepth::Float32,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -441,19 +438,6 @@ impl Bounce {
|
||||
Some((chunk, n)) => {
|
||||
fill(&mut self.block, chunk, n, self.fold, self.gain);
|
||||
self.done += n;
|
||||
if !self.measuring {
|
||||
// The encoder clips an integer file to full scale and maps a float file's NaN to 0 and
|
||||
// infinities to +-1, so the report must describe what it writes.
|
||||
for v in self.block.iter_mut().flatten() {
|
||||
*v = if v.is_nan() {
|
||||
0.0
|
||||
} else if self.integer || v.is_infinite() {
|
||||
v.clamp(-1.0, 1.0)
|
||||
} else {
|
||||
*v
|
||||
};
|
||||
}
|
||||
}
|
||||
self.peak = self.peak.max(soundcraft_dsp::offline::peak(&self.block));
|
||||
if !self.measuring {
|
||||
self.meter.process(&self.block, n);
|
||||
|
||||
@@ -22,11 +22,7 @@ pub(super) const MAX_MIDI_TRACKS: usize = 512;
|
||||
pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: bool) -> Result<Vec<TrackId>> {
|
||||
let smf = match soundcraft_midi::read_smf(bytes) {
|
||||
Ok(smf) => smf,
|
||||
Err(
|
||||
err @ (soundcraft_midi::MidiError::TooManyEvents(_)
|
||||
| soundcraft_midi::MidiError::TooManyTracks(_)
|
||||
| soundcraft_midi::MidiError::SysExTooLarge(_)),
|
||||
) => {
|
||||
Err(err @ (soundcraft_midi::MidiError::TooManyEvents(_) | soundcraft_midi::MidiError::TooManyTracks(_))) => {
|
||||
return Err(EngineError::Io(err.to_string()));
|
||||
}
|
||||
Err(_) => {
|
||||
@@ -34,10 +30,9 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
|
||||
// The strict reader stops at the first damage, so a limit further on shows only here.
|
||||
if read.over_limit {
|
||||
return Err(EngineError::Io(format!(
|
||||
"MIDI file exceeds a limit of {} events, {} tracks, or {} bytes of SysEx payload",
|
||||
"MIDI file: more than {} events or {} tracks",
|
||||
soundcraft_midi::MAX_EVENTS,
|
||||
soundcraft_midi::MAX_TRACKS,
|
||||
soundcraft_midi::MAX_SYSEX_BYTES
|
||||
soundcraft_midi::MAX_TRACKS
|
||||
)));
|
||||
}
|
||||
for warning in &read.warnings {
|
||||
@@ -55,8 +50,7 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
|
||||
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TEMPOS} tempo changes")));
|
||||
}
|
||||
}
|
||||
let tracks_to_import =
|
||||
smf.tracks.iter().filter(|tr| !tr.sequence.notes.is_empty() || !tr.sequence.ctrls.is_empty() || !tr.sequence.sysex.is_empty()).count();
|
||||
let tracks_to_import = smf.tracks.iter().filter(|tr| !tr.sequence.notes.is_empty() || !tr.sequence.ctrls.is_empty()).count();
|
||||
if tracks_to_import > MAX_MIDI_TRACKS {
|
||||
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TRACKS} tracks")));
|
||||
}
|
||||
@@ -78,13 +72,12 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
|
||||
let base_tick = tempo.samples_to_ticks(at, s.sample_rate);
|
||||
let mut clips = Vec::new();
|
||||
for (i, tr) in smf.tracks.iter().enumerate() {
|
||||
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.is_empty() && tr.sequence.sysex.is_empty() {
|
||||
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// A controller on the clip's last tick would not play, so the clip runs one tick past the last one.
|
||||
let past_ctrls = tr.sequence.ctrls.iter().map(|c| c.tick.saturating_add(1)).max().unwrap_or(0);
|
||||
let past_sysex = tr.sequence.sysex.iter().map(|e| e.tick.saturating_add(1)).max().unwrap_or(0);
|
||||
let end_tick = base_tick.saturating_add(tr.sequence.end_tick().max(past_ctrls).max(past_sysex).max(1));
|
||||
let end_tick = base_tick.saturating_add(tr.sequence.end_tick().max(past_ctrls).max(1));
|
||||
let len = tempo.tick_to_samples(end_tick, s.sample_rate).saturating_sub(at);
|
||||
if len > s.sample_rate.samples(86_400.0) {
|
||||
return Err(EngineError::Io(format!("MIDI track {}: longer than 24 hours", i + 1)));
|
||||
@@ -132,14 +125,8 @@ pub fn export_midi(e: &Engine, only: Option<&[TrackId]>) -> Result<Vec<u8>> {
|
||||
for c in t.clips() {
|
||||
if let ClipContent::Midi { sequence } = &c.content {
|
||||
let base = s.tempo.samples_to_ticks(c.start, s.sample_rate);
|
||||
// Only what plays: notes starting inside the clip (cut at its end), and the
|
||||
// controllers and SysEx inside it.
|
||||
// Only what plays: notes starting inside the clip, cut at its end.
|
||||
let clip_end = s.tempo.samples_to_ticks(c.end(), s.sample_rate);
|
||||
for event in sequence.sysex.iter().filter(|event| event.tick.saturating_add(base) < clip_end) {
|
||||
let mut event = event.clone();
|
||||
event.tick = event.tick.saturating_add(base);
|
||||
seq.sysex.push(event);
|
||||
}
|
||||
for n in sequence.notes.iter().filter(|n| n.start.saturating_add(base) < clip_end) {
|
||||
let mut n = *n;
|
||||
n.start = n.start.saturating_add(base);
|
||||
|
||||
@@ -113,9 +113,6 @@ pub struct TransportStatus {
|
||||
pub struct Clipboard {
|
||||
pub length: Samples,
|
||||
pub tracks: Vec<Vec<Clip>>,
|
||||
/// Visible duration at copy time. An ordinary paste keeps the underlying clip's trim handles,
|
||||
/// whereas merging materializes only its selected MIDI events, even after a tempo change.
|
||||
pub midi_tick_lengths: std::collections::BTreeMap<soundcraft_model::ClipId, i64>,
|
||||
pub automation: Vec<Vec<soundcraft_model::AutomationLane>>,
|
||||
/// Copy Special › Clip Gain: per track, (offset from the copied range start, dB) breakpoints.
|
||||
pub clip_gain: Vec<Vec<(Samples, f32)>>,
|
||||
@@ -134,19 +131,6 @@ pub struct Clipboard {
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
/// Store one track of range-relative clips and capture the source tempo before a paste.
|
||||
pub(crate) fn push_clips(&mut self, session: &Session, range_start: Samples, clips: Vec<Clip>) {
|
||||
for clip in &clips {
|
||||
if matches!(clip.content, soundcraft_model::ClipContent::Midi { .. }) {
|
||||
let start = range_start.saturating_add(clip.start);
|
||||
let end = start.saturating_add(clip.length);
|
||||
let ticks = |at| session.tempo.samples_to_ticks(at, session.sample_rate);
|
||||
self.midi_tick_lengths.insert(clip.id, ticks(end).saturating_sub(ticks(start)));
|
||||
}
|
||||
}
|
||||
self.tracks.push(clips);
|
||||
}
|
||||
|
||||
/// An empty clipboard for material copied from `range`.
|
||||
pub fn of_range(s: &Session, range: soundcraft_time::Range) -> Clipboard {
|
||||
let line = s.grid_line_at_or_before(range.start);
|
||||
|
||||
@@ -66,39 +66,6 @@ fn scratch(name: &str) -> PathBuf {
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_bounce_reports_the_levels_of_the_clipped_file() {
|
||||
let mut e = soundcraft_engine::Engine::default();
|
||||
let sr = e.session().sample_rate.hz();
|
||||
let frames = sr as usize;
|
||||
let samples: Vec<f32> = (0..frames).map(|i| 1.5 * (std::f32::consts::TAU * 440.0 * i as f32 / sr as f32).sin()).collect();
|
||||
let audio = craft_audio::AudioBuffer { sample_rate: sr, channels: vec![samples.clone(), samples] };
|
||||
let s = e.session_mut();
|
||||
let track = s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::Stereo, Some("Hot"));
|
||||
let source = soundcraft_engine::io::add_source(s, "hot", audio, None, FileFormat::Wav);
|
||||
let clip = soundcraft_model::Clip::audio(s.new_clip_id(), "hot", source, 0, 0, frames as i64);
|
||||
soundcraft_engine::edit::place_clip(s, track, clip);
|
||||
let mix = soundcraft_mix::render_range(e.session(), Range::new(0, frames as i64), 1024);
|
||||
assert!(soundcraft_dsp::offline::peak(&mix) > 1.0);
|
||||
let dir = scratch("bounce-int-clipped");
|
||||
let path = dir.join("Mix.wav");
|
||||
let r = e.execute("file.bounce_mix", &serde_json::json!({"path": path, "bit_depth": 16, "dither": false, "start": 0, "end": frames})).unwrap();
|
||||
let (_, file) = craft_audio::decode(&std::fs::read(&path).unwrap(), None).unwrap();
|
||||
assert!(file.peak() <= 1.0);
|
||||
let mut meter = soundcraft_dsp::meter::LoudnessMeter::new(sr as f32, file.channels.len());
|
||||
meter.process(&file.channels, file.frames());
|
||||
for (key, value, tolerance) in [
|
||||
("peak_db", soundcraft_dsp::offline::peak_db(&file.channels), 0.01),
|
||||
("lufs", meter.integrated_lufs(), 0.05),
|
||||
("true_peak_db", meter.true_peak_db(), 0.05),
|
||||
] {
|
||||
let reported = r[key].as_f64().unwrap();
|
||||
assert!((reported - f64::from(value)).abs() < tolerance, "{key}: reported {reported}, file {value}");
|
||||
}
|
||||
assert!(r["peak_db"].as_f64().unwrap() <= 0.0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounces_write_exactly_the_mix_and_report_its_levels() {
|
||||
let e = soundcraft_engine::demo::demo_engine();
|
||||
|
||||
@@ -17,10 +17,8 @@ mod new_track_rows;
|
||||
mod processing_keeps_crossfades;
|
||||
mod random_edits;
|
||||
mod recording;
|
||||
mod session_inspect;
|
||||
mod session_transport;
|
||||
mod split_into_mono;
|
||||
mod sysex_import;
|
||||
mod time_key_signatures;
|
||||
mod track_name_collisions;
|
||||
mod trim_to_selection;
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
//! `session.inspect` reports what the README promises: tracks, clips, mixer, markers and the last
|
||||
//! undo and redo labels, so two inspections taken around an edit show what the edit changed.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_engine::Engine;
|
||||
|
||||
/// The engine's current `session.inspect` reply, with default (summary) detail.
|
||||
fn inspect(e: &mut Engine) -> Value {
|
||||
e.execute("session.inspect", &json!({})).expect("session.inspect")
|
||||
}
|
||||
|
||||
/// The engine's current `session.inspect` reply with `{"detail": "full"}`.
|
||||
fn inspect_full(e: &mut Engine) -> Value {
|
||||
e.execute("session.inspect", &json!({"detail": "full"})).expect("session.inspect full")
|
||||
}
|
||||
|
||||
/// Asserts the README's promise on one reply: typed mixer fields and clips on every track, typed
|
||||
/// markers, and history labels that are each a string or null.
|
||||
fn assert_reports_session_state(v: &Value) {
|
||||
let tracks = v["tracks"].as_array().expect("tracks");
|
||||
assert!(!tracks.is_empty());
|
||||
for t in tracks {
|
||||
assert!(t["clips"].is_array(), "{t}");
|
||||
assert!(t["volume_db"].is_number(), "volume_db in {t}");
|
||||
let pan = t["pan"].as_array().expect("pan is one value per channel");
|
||||
assert!(!pan.is_empty() && pan.iter().all(Value::is_number), "pan in {t}");
|
||||
assert!(t["mute"].is_boolean(), "mute in {t}");
|
||||
assert!(t["solo"].is_boolean(), "solo in {t}");
|
||||
assert!(t["inserts"].is_array(), "inserts in {t}");
|
||||
assert!(t["sends"].is_array(), "sends in {t}");
|
||||
}
|
||||
assert!(tracks.iter().any(|t| !t["clips"].as_array().unwrap().is_empty()), "the demo has clips");
|
||||
let markers = v["markers"].as_array().expect("markers");
|
||||
assert!(!markers.is_empty(), "the demo has markers");
|
||||
for m in markers {
|
||||
assert!(m["id"].is_u64(), "id in {m}");
|
||||
assert!(m["number"].is_u64(), "number in {m}");
|
||||
assert!(m["name"].is_string(), "name in {m}");
|
||||
assert!(m["start"].is_u64(), "start in {m}");
|
||||
assert!(m["end"].is_u64(), "end in {m}");
|
||||
}
|
||||
for key in ["undo", "redo"] {
|
||||
let label = v.get(key).unwrap_or_else(|| panic!("{key} missing from {v}"));
|
||||
assert!(label.is_string() || label.is_null(), "{key} in {v}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The README text with line breaks and indentation folded to single spaces.
|
||||
fn readme() -> String {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../README.md");
|
||||
std::fs::read_to_string(path).expect("README.md").split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Adds one track with default parameters and returns its id.
|
||||
fn new_track(e: &mut Engine) -> Value {
|
||||
e.execute("track.new", &json!({})).expect("track.new")["tracks"][0].clone()
|
||||
}
|
||||
|
||||
/// The track with this id in an inspection; panics with the whole reply when it is absent.
|
||||
fn track<'a>(v: &'a Value, id: &Value) -> &'a Value {
|
||||
v["tracks"].as_array().and_then(|ts| ts.iter().find(|t| &t["id"] == id)).unwrap_or_else(|| panic!("track {id} in {v}"))
|
||||
}
|
||||
|
||||
/// The README describes `session.inspect` as current state plus history labels, not a change report.
|
||||
#[test]
|
||||
fn readme_describes_inspect_as_current_state() {
|
||||
let text = readme();
|
||||
let sentence =
|
||||
["`session.inspect` returns the session's current state (tracks, clips, mixer, markers)", "and the last undo and redo step labels"];
|
||||
assert!(text.contains(&sentence.join(" ")), "README sentence about session.inspect");
|
||||
assert!(!text.contains("reports exactly what changed"), "the old change-report wording is back");
|
||||
}
|
||||
|
||||
/// Every track carries its clips and mixer fields, and the session lists its markers.
|
||||
#[test]
|
||||
fn inspect_reports_tracks_clips_mixer_and_markers() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
assert_reports_session_state(&inspect(&mut e));
|
||||
}
|
||||
|
||||
/// Full detail reports the same state, and adds each insert's parameters.
|
||||
#[test]
|
||||
fn full_detail_reports_the_same_state_with_insert_params() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
e.execute("mix.volume", &json!({"track": "Kick", "db": -6.0})).unwrap();
|
||||
let summary = inspect(&mut e);
|
||||
let full = inspect_full(&mut e);
|
||||
assert_reports_session_state(&full);
|
||||
assert_eq!(full["undo"], json!("Set Volume"), "{full}");
|
||||
assert_eq!(full["undo"], summary["undo"]);
|
||||
assert_eq!(full["redo"], summary["redo"]);
|
||||
assert_eq!(full["markers"], summary["markers"]);
|
||||
let inserts = |v: &Value| v["tracks"].as_array().unwrap().iter().flat_map(|t| t["inserts"].as_array().unwrap().clone()).collect::<Vec<_>>();
|
||||
let (s, f) = (inserts(&summary), inserts(&full));
|
||||
assert!(!f.is_empty(), "the demo has inserts");
|
||||
assert_eq!(s.len(), f.len());
|
||||
assert!(s.iter().all(|i| i["params"].is_null()), "summary leaves params out");
|
||||
assert!(f.iter().all(|i| !i["params"].is_null()), "full includes params");
|
||||
}
|
||||
|
||||
/// With no edits yet, both history labels are null.
|
||||
#[test]
|
||||
fn a_fresh_session_has_no_undo_or_redo_step() {
|
||||
let mut e = Engine::default();
|
||||
let v = inspect(&mut e);
|
||||
assert_eq!(v.get("undo"), Some(&Value::Null), "{v}");
|
||||
assert_eq!(v.get("redo"), Some(&Value::Null), "{v}");
|
||||
}
|
||||
|
||||
/// The undo label is the label of the command that ran last.
|
||||
#[test]
|
||||
fn undo_names_the_last_edit() {
|
||||
let mut e = Engine::default();
|
||||
let t = new_track(&mut e);
|
||||
e.execute("mix.volume", &json!({"track": t, "db": -6.0})).unwrap();
|
||||
let v = inspect(&mut e);
|
||||
assert_eq!(v["undo"], json!("Set Volume"), "{v}");
|
||||
assert_eq!(v["redo"], Value::Null, "{v}");
|
||||
}
|
||||
|
||||
/// Undo moves the step's label to redo, and redo moves it back.
|
||||
#[test]
|
||||
fn undo_moves_the_step_label_to_redo() {
|
||||
let mut e = Engine::default();
|
||||
let t = new_track(&mut e);
|
||||
e.execute("mix.volume", &json!({"track": t, "db": -6.0})).unwrap();
|
||||
let before = inspect(&mut e);
|
||||
assert!(e.undo());
|
||||
let after = inspect(&mut e);
|
||||
assert_eq!(after["redo"], before["undo"], "{after}");
|
||||
assert_ne!(after["undo"], before["undo"], "{after}");
|
||||
assert!(e.redo());
|
||||
let again = inspect(&mut e);
|
||||
assert_eq!(again["undo"], before["undo"], "{again}");
|
||||
assert_eq!(again["redo"], Value::Null, "{again}");
|
||||
}
|
||||
|
||||
/// Inspecting is read-only: two calls in a row agree and add no undo step.
|
||||
#[test]
|
||||
fn inspecting_does_not_change_the_session_or_history() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
let history = e.undo_history().len();
|
||||
let first = inspect(&mut e);
|
||||
let second = inspect(&mut e);
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(e.undo_history().len(), history, "an inspection is not an undo step");
|
||||
}
|
||||
|
||||
/// A volume change shows up in that track's `volume_db` and leaves its other fields alone.
|
||||
#[test]
|
||||
fn comparing_inspections_shows_a_mixer_change() {
|
||||
let mut e = Engine::default();
|
||||
let t = new_track(&mut e);
|
||||
let before = inspect(&mut e);
|
||||
e.execute("mix.volume", &json!({"track": t, "db": -6.0})).unwrap();
|
||||
let after = inspect(&mut e);
|
||||
assert_ne!(track(&before, &t)["volume_db"], track(&after, &t)["volume_db"]);
|
||||
assert_eq!(track(&after, &t)["volume_db"].as_f64(), Some(-6.0));
|
||||
assert_eq!(track(&before, &t)["pan"], track(&after, &t)["pan"], "untouched fields stay equal");
|
||||
}
|
||||
|
||||
/// An added marker appears with its name and start, and becomes the last undo step.
|
||||
#[test]
|
||||
fn comparing_inspections_shows_a_new_marker() {
|
||||
let mut e = Engine::default();
|
||||
let before = inspect(&mut e);
|
||||
e.execute("markers.add", &json!({"name": "Verse", "at": 48_000})).unwrap();
|
||||
let after = inspect(&mut e);
|
||||
let count = |v: &Value| v["markers"].as_array().map_or(0, Vec::len);
|
||||
assert_eq!(count(&after), count(&before) + 1, "{after}");
|
||||
let m = after["markers"].as_array().unwrap().iter().find(|m| m["name"] == "Verse").expect("the new marker");
|
||||
assert_eq!(m["start"], json!(48_000), "{m}");
|
||||
assert_ne!(after["undo"], before["undo"], "the marker is the last undo step");
|
||||
}
|
||||
|
||||
/// A new track appears in the list, with no clips.
|
||||
#[test]
|
||||
fn comparing_inspections_shows_a_new_track() {
|
||||
let mut e = Engine::default();
|
||||
let before = inspect(&mut e);
|
||||
let t = new_track(&mut e);
|
||||
let after = inspect(&mut e);
|
||||
assert_eq!(after["tracks"].as_array().unwrap().len(), before["tracks"].as_array().unwrap().len() + 1);
|
||||
assert!(track(&after, &t)["clips"].as_array().unwrap().is_empty(), "a new track has no clips");
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
use soundcraft_engine::{Engine, edit, io};
|
||||
use soundcraft_model::ClipContent;
|
||||
use soundcraft_time::Range;
|
||||
|
||||
fn fixture() -> Vec<u8> {
|
||||
let body = [0, 0xF0, 8, 0x43, 0x10, 0x4C, 0, 0, 0x7E, 0, 0xF7, 0x83, 0x60, 0xF7, 1, 0xF8, 0x83, 0x60, 0xF0, 2, 0x43, 0xF7, 0, 0xFF, 0x2F, 0];
|
||||
smf_track(&body)
|
||||
}
|
||||
|
||||
fn smf_track(body: &[u8]) -> Vec<u8> {
|
||||
let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\x03\xC0MTrk".to_vec();
|
||||
bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
|
||||
bytes.extend_from_slice(body);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn exported(engine: &Engine) -> Vec<soundcraft_midi::SysExEvent> {
|
||||
soundcraft_midi::read_smf(&io::export_midi(engine, None).unwrap()).unwrap().tracks.into_iter().flat_map(|t| t.sequence.sysex).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysex_only_track_is_imported_at_the_requested_offset_and_exported() {
|
||||
let mut e = Engine::default();
|
||||
let tracks = io::import_midi_bytes(&mut e, &fixture(), 48_000, false).unwrap();
|
||||
assert_eq!(tracks.len(), 1, "a SysEx-only setup track must not disappear");
|
||||
let clip = &e.session().track(tracks[0]).unwrap().clips()[0];
|
||||
assert_eq!(clip.start, 48_000);
|
||||
assert!(clip.end() > 72_000, "the final packet must lie inside the clip");
|
||||
let packets = exported(&e);
|
||||
assert_eq!(packets.iter().map(|e| e.tick).collect::<Vec<_>>(), [1920, 2400, 2880]);
|
||||
assert_eq!(packets[0].data, [0x43, 0x10, 0x4C, 0, 0, 0x7E, 0, 0xF7]);
|
||||
assert_eq!(packets[1].status, 0xF7);
|
||||
assert_eq!(packets[1].data, [0xF8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_command_reports_retention_and_the_remaining_playback_limit() {
|
||||
let path = std::env::temp_dir().join(format!("soundcraft-sysex-command-{}.mid", std::process::id()));
|
||||
std::fs::write(&path, fixture()).unwrap();
|
||||
let mut e = Engine::default();
|
||||
let result = e.execute("file.import_midi", &serde_json::json!({"path":path})).unwrap();
|
||||
assert_eq!(result["sysex_packets"], 3);
|
||||
assert!(result["warnings"][0].as_str().unwrap().contains("playback is not supported"));
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
// Delta 0, F0, then a four-byte VLQ declaring 16 MiB + 1 payload bytes.
|
||||
const LARGE_SYSEX_HEADER: [u8; 6] = [0, 0xF0, 0x88, 0x80, 0x80, 1];
|
||||
|
||||
#[test]
|
||||
fn truncated_sysex_is_salvaged_without_hitting_the_size_limit() {
|
||||
let bytes = smf_track(&LARGE_SYSEX_HEADER);
|
||||
assert!(matches!(soundcraft_midi::read_smf(&bytes), Err(soundcraft_midi::MidiError::Truncated(_))));
|
||||
let read = soundcraft_midi::read_smf_lenient(&bytes).unwrap();
|
||||
assert!(!read.warnings.is_empty());
|
||||
assert!(!read.over_limit);
|
||||
let mut e = Engine::default();
|
||||
assert!(io::import_midi_bytes(&mut e, &bytes, 0, true).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_sysex_is_refused_without_changing_the_session() {
|
||||
let limit = soundcraft_midi::MAX_SYSEX_BYTES;
|
||||
let mut body = LARGE_SYSEX_HEADER.to_vec();
|
||||
body.resize(body.len() + limit, 0);
|
||||
body.push(0xF7);
|
||||
body.extend_from_slice(&[0, 0xFF, 0x2F, 0]);
|
||||
let bytes = smf_track(&body);
|
||||
let expected = soundcraft_midi::MidiError::SysExTooLarge(limit);
|
||||
assert_eq!(soundcraft_midi::read_smf(&bytes).unwrap_err(), expected);
|
||||
assert!(soundcraft_midi::read_smf_lenient(&bytes).unwrap().over_limit);
|
||||
let mut e = Engine::default();
|
||||
let before = serde_json::to_value(e.session()).unwrap();
|
||||
let error = io::import_midi_bytes(&mut e, &bytes, 0, true).unwrap_err();
|
||||
assert!(error.to_string().contains(&expected.to_string()), "{error}");
|
||||
assert_eq!(serde_json::to_value(e.session()).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysex_survives_a_real_session_save_reopen_and_midi_export() {
|
||||
let mut e = Engine::default();
|
||||
io::import_midi_bytes(&mut e, &fixture(), 0, false).unwrap();
|
||||
let before = exported(&e);
|
||||
let path = std::env::temp_dir().join(format!("soundcraft-sysex-roundtrip-{}.scraft", std::process::id()));
|
||||
io::save_session(&mut e, &path.to_string_lossy()).unwrap();
|
||||
let mut reopened = Engine::default();
|
||||
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
|
||||
assert_eq!(exported(&reopened), before);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splitting_and_consolidating_keep_packet_times_and_order() {
|
||||
let mut e = Engine::default();
|
||||
let track = io::import_midi_bytes(&mut e, &fixture(), 0, false).unwrap()[0];
|
||||
let before = exported(&e);
|
||||
let clip = e.session().track(track).unwrap().clips()[0].clone();
|
||||
let new_id = e.session_mut().new_clip_id();
|
||||
let (left, right) = edit::split_clip(&clip, 12_000, new_id, edit::TimeCtx::of(e.session())).unwrap();
|
||||
match (&left.content, &right.content) {
|
||||
(ClipContent::Midi { sequence: a }, ClipContent::Midi { sequence: b }) => {
|
||||
assert_eq!(a.sysex.len(), 1);
|
||||
assert_eq!(b.sysex.iter().map(|e| e.tick).collect::<Vec<_>>(), [0, 480]);
|
||||
}
|
||||
_ => panic!("expected MIDI"),
|
||||
}
|
||||
e.session_mut().track_mut(track).unwrap().playlist_mut().unwrap().clips = vec![left, right];
|
||||
assert_eq!(exported(&e), before);
|
||||
assert!(edit::consolidate_midi(e.session_mut(), track, Range::new(0, clip.end())));
|
||||
assert_eq!(exported(&e), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimming_drops_packets_before_the_new_start_and_reanchors_the_rest() {
|
||||
let mut e = Engine::default();
|
||||
let track = io::import_midi_bytes(&mut e, &fixture(), 0, false).unwrap()[0];
|
||||
assert_eq!(edit::trim_start_to(e.session_mut(), track, 12_000), 1);
|
||||
let packets = exported(&e);
|
||||
assert_eq!(packets.iter().map(|e| e.tick).collect::<Vec<_>>(), [480, 960]);
|
||||
assert_eq!(packets[0].status, 0xF7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_copy_merge_exports_only_the_selected_midi_events() {
|
||||
use serde_json::json;
|
||||
use soundcraft_midi::{CtrlEvent, CtrlKind, Note, Sequence, SysExEvent};
|
||||
use soundcraft_model::{ChannelFormat, Clip, TrackKind};
|
||||
|
||||
let mut e = Engine::default();
|
||||
let s = e.session_mut();
|
||||
let source = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
|
||||
let host = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
|
||||
let mut sequence = Sequence::default();
|
||||
for (tick, key) in [(119, 60), (120, 61), (240, 62), (360, 63), (480, 64)] {
|
||||
sequence.notes.push(Note { start: tick, length: 180, pitch: key, velocity: 100, release_velocity: 64, channel: 0 });
|
||||
sequence.ctrls.push(CtrlEvent { tick, channel: 0, kind: CtrlKind::Cc(11), value: i32::from(key) });
|
||||
sequence.sysex.push(SysExEvent { tick, status: 0xf0, data: vec![0x7d, key, 0xf7] });
|
||||
}
|
||||
let source_id = s.new_clip_id();
|
||||
let host_id = s.new_clip_id();
|
||||
edit::place_clip(s, source, Clip::midi(source_id, "source", 0, 24_000, sequence));
|
||||
edit::place_clip(s, host, Clip::midi(host_id, "destination", 12_000, 96_000, Sequence::default()));
|
||||
// At 120 BPM and 48 kHz, [3000, 9000) samples selects source ticks [120, 360).
|
||||
e.execute("edit.copy", &json!({"tracks":[source.0], "start":3000, "end":9000})).unwrap();
|
||||
let result = e.execute("edit.paste_merge_midi", &json!({"tracks":[host.0], "at":24_000})).unwrap();
|
||||
assert_eq!(result["merged"], 1);
|
||||
|
||||
let smf = soundcraft_midi::read_smf(&io::export_midi(&e, Some(&[host])).unwrap()).unwrap();
|
||||
let exported = &smf.tracks.iter().find(|t| !t.sequence.notes.is_empty()).unwrap().sequence;
|
||||
let ClipContent::Midi { sequence: merged } = &e.session().find_clip(host_id).unwrap().1.content else { panic!("expected MIDI") };
|
||||
// Host-relative ticks and the decoded SMF both retain inclusive start and exclusive end.
|
||||
for (seq, base) in [(exported, 960), (merged, 480)] {
|
||||
let notes: Vec<_> = seq.notes.iter().map(|n| (n.start, n.pitch, n.length)).collect();
|
||||
let ctrls: Vec<_> = seq.ctrls.iter().map(|c| (c.tick, c.kind, c.value)).collect();
|
||||
let packets: Vec<_> = seq.sysex.iter().map(|s| (s.tick, s.status, s.data.as_slice())).collect();
|
||||
assert_eq!(
|
||||
(notes, ctrls, packets),
|
||||
(
|
||||
vec![(base, 61, 180), (base + 120, 62, 120)],
|
||||
vec![(base, CtrlKind::Cc(11), 61), (base + 120, CtrlKind::Cc(11), 62)],
|
||||
vec![(base, 0xf0, &[0x7d, 61, 0xf7][..]), (base + 120, 0xf0, &[0x7d, 62, 0xf7][..])],
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// At the faster destination tempo the same sample length spans twice as many ticks.
|
||||
// A repeated paste on an empty track must still use the source window.
|
||||
e.session_mut().tempo.set_tempo(0, 240.).unwrap();
|
||||
let empty = e.session_mut().add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
|
||||
let result = e.execute("edit.paste_merge_midi", &json!({"tracks":[empty.0], "at":24_000})).unwrap();
|
||||
assert_eq!(result["placed"], 1);
|
||||
let smf = soundcraft_midi::read_smf(&io::export_midi(&e, Some(&[empty])).unwrap()).unwrap();
|
||||
let seq = &smf.tracks.iter().find(|t| !t.sequence.notes.is_empty()).unwrap().sequence;
|
||||
assert_eq!(seq.notes.iter().map(|n| (n.start, n.length)).collect::<Vec<_>>(), [(1920, 180), (2040, 120)]);
|
||||
assert_eq!(seq.ctrls.iter().map(|c| c.tick).collect::<Vec<_>>(), [1920, 2040]);
|
||||
assert_eq!(seq.sysex.iter().map(|s| s.tick).collect::<Vec<_>>(), [1920, 2040]);
|
||||
|
||||
// At half tempo the original sample duration would end at the second retained event.
|
||||
// Both placement and extension of a short host must cover the full source-tick window.
|
||||
e.session_mut().tempo.set_tempo(0, 60.).unwrap();
|
||||
let s = e.session_mut();
|
||||
let short = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
|
||||
let short_id = s.new_clip_id();
|
||||
edit::place_clip(s, short, Clip::midi(short_id, "short host", 23_000, 2_000, Sequence::default()));
|
||||
let blank = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
|
||||
for (track, action) in [(blank, "placed"), (short, "merged")] {
|
||||
let result = e.execute("edit.paste_merge_midi", &json!({"tracks":[track.0], "at":24_000})).unwrap();
|
||||
assert_eq!(result[action], 1);
|
||||
let smf = soundcraft_midi::read_smf(&io::export_midi(&e, Some(&[track])).unwrap()).unwrap();
|
||||
let seq = &smf.tracks.iter().find(|t| !t.sequence.notes.is_empty()).unwrap().sequence;
|
||||
assert_eq!(seq.notes.iter().map(|n| (n.start, n.length)).collect::<Vec<_>>(), [(480, 180), (600, 120)]);
|
||||
assert_eq!(seq.ctrls.iter().map(|c| c.tick).collect::<Vec<_>>(), [480, 600]);
|
||||
assert_eq!(seq.sysex.iter().map(|s| s.tick).collect::<Vec<_>>(), [480, 600]);
|
||||
}
|
||||
|
||||
let s = e.session_mut();
|
||||
let adjacent = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
|
||||
let neighbor_id = s.new_clip_id();
|
||||
edit::place_clip(s, adjacent, Clip::midi(neighbor_id, "neighbor", 32_000, 4_000, Sequence::default()));
|
||||
e.execute("edit.paste_merge_midi", &json!({"tracks":[adjacent.0], "at":24_000})).unwrap();
|
||||
let clips = e.session().track(adjacent).unwrap().clips();
|
||||
assert_eq!(clips.len(), 2);
|
||||
assert_eq!((clips[0].end(), clips[1].id, clips[1].start, clips[1].length), (32_000, neighbor_id, 32_000, 4_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovered_track_over_the_sysex_budget_reports_the_payload_limit() {
|
||||
// A damaged first track sends import down the lenient path before it sees track two.
|
||||
let mut bytes = smf_track(&[0, 0x90, 60]);
|
||||
bytes[9] = 1; // SMF format 1
|
||||
bytes[11] = 2;
|
||||
let mut body = LARGE_SYSEX_HEADER.to_vec();
|
||||
body.resize(body.len() + soundcraft_midi::MAX_SYSEX_BYTES + 1, 0);
|
||||
bytes.extend_from_slice(b"MTrk");
|
||||
bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
|
||||
bytes.extend_from_slice(&body);
|
||||
assert!(matches!(soundcraft_midi::read_smf(&bytes), Err(soundcraft_midi::MidiError::Truncated(_))));
|
||||
assert!(soundcraft_midi::read_smf_lenient(&bytes).unwrap().over_limit);
|
||||
let mut e = Engine::default();
|
||||
let before = serde_json::to_value(e.session()).unwrap();
|
||||
let error = io::import_midi_bytes(&mut e, &bytes, 0, true).unwrap_err().to_string();
|
||||
assert!(error.contains("SysEx") && error.contains(&soundcraft_midi::MAX_SYSEX_BYTES.to_string()), "{error}");
|
||||
assert_eq!(serde_json::to_value(e.session()).unwrap(), before);
|
||||
}
|
||||
@@ -14,8 +14,8 @@ pub mod ops;
|
||||
mod rng;
|
||||
|
||||
pub use craft_midi::{
|
||||
CtrlEvent, CtrlKind, LenientRead, MAX_EVENTS, MAX_SYSEX_BYTES, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, SysExEvent, read_smf,
|
||||
read_smf_lenient, write_smf,
|
||||
CtrlEvent, CtrlKind, LenientRead, MAX_EVENTS, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, SysExEvent, read_smf, read_smf_lenient,
|
||||
write_smf,
|
||||
};
|
||||
pub use names::{gm_drum_name, gm_program_name, note_name};
|
||||
pub use rng::XorShift;
|
||||
|
||||
@@ -293,36 +293,6 @@ impl MixEngine {
|
||||
self.main_meter.reset_levels();
|
||||
}
|
||||
|
||||
/// [`MixEngine::reset`], then prepares the hosted plugins again: their own `reset` may keep
|
||||
/// audio (a VST3 processor's only flushes notes), and activating them again clears it.
|
||||
/// Offline only: plugins allocate when they activate.
|
||||
pub(crate) fn reset_and_reprepare(&mut self) {
|
||||
self.reset();
|
||||
let (sr, mb) = (self.sample_rate, self.max_block);
|
||||
for s in self.strips.values_mut() {
|
||||
for p in s.plugins.iter_mut().flatten().chain(s.instrument.as_mut()) {
|
||||
if is_third_party(&p.id) {
|
||||
p.plugin.prepare(sr, mb, p.ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main-thread time for every plugin ([`Plugin::idle`]): offline renders give it between
|
||||
/// blocks, the audio thread never does. True when an insert's or an instrument's latency
|
||||
/// changed (both are delay-compensated).
|
||||
pub(crate) fn idle_plugins(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
for s in self.strips.values_mut() {
|
||||
for p in s.plugins.iter_mut().flatten().chain(s.instrument.as_mut()) {
|
||||
let before = p.plugin.latency();
|
||||
p.plugin.idle();
|
||||
changed |= p.plugin.latency() != before;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Bring plugin instances in line with the session (creates/destroys as needed). Allocates;
|
||||
/// call outside the realtime thread when the document changes, or let `render` do it.
|
||||
pub fn sync(&mut self, s: &Session) {
|
||||
|
||||
@@ -42,9 +42,6 @@ pub fn source_channels(s: &Session, bus: Option<BusId>) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times [`RangeRender`] renders its first block again while a plugin's latency changes.
|
||||
const FIRST_BLOCK_TRIES: usize = 4;
|
||||
|
||||
/// [`render_range`] or [`render_bus`] of any length, a block at a time.
|
||||
pub struct RangeRender {
|
||||
eng: MixEngine,
|
||||
@@ -67,12 +64,6 @@ impl RangeRender {
|
||||
RangeRender { eng, bus, tmp, start: range.start, done: 0, total: len, latency: 0 }
|
||||
}
|
||||
|
||||
/// The engine, for tests that hand it fake hosted plugins.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn engine(&mut self) -> &mut MixEngine {
|
||||
&mut self.eng
|
||||
}
|
||||
|
||||
fn render(&mut self, s: &Session, pos: Samples, n: usize) {
|
||||
match self.bus {
|
||||
Some(id) => {
|
||||
@@ -92,27 +83,6 @@ impl RangeRender {
|
||||
}
|
||||
let n = (self.total - self.done).min(self.eng.max_block());
|
||||
self.render(s, self.start + self.done as i64, n);
|
||||
// Hosted plugins may only find their latency once they process, and apply it when they
|
||||
// are restarted. If one did on the first block, start over from a clean state, so that
|
||||
// block and the latency trimmed off it line up too. The head trim is the first block's:
|
||||
// a later change (an automated lookahead) moves the alignment from that block on, as in
|
||||
// playback, since the audio before it has already gone out.
|
||||
if self.eng.idle_plugins() && self.done == 0 {
|
||||
// A plugin may settle in more than one step: start over until none changes, a few
|
||||
// times at most.
|
||||
let mut settled = false;
|
||||
for _ in 0..FIRST_BLOCK_TRIES {
|
||||
self.eng.reset_and_reprepare();
|
||||
self.render(s, self.start, n);
|
||||
if !self.eng.idle_plugins() {
|
||||
settled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !settled {
|
||||
log::warn!("a plugin's latency kept changing on the first block; the render may not line up with the timeline");
|
||||
}
|
||||
}
|
||||
if self.done == 0 {
|
||||
// The first block tells the mix's latency: render that much more and drop the head.
|
||||
self.latency = match self.bus {
|
||||
|
||||
@@ -1492,268 +1492,6 @@ fn volume_automation_follows_its_breakpoints_in_any_block_size() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delays its input by `n` samples from its first block, like a lookahead limiter, but reports
|
||||
/// that latency only after its first block and an `idle`, the way a CLAP plugin applies a new
|
||||
/// latency through a restart (LSP Limiter: 0 at `activate`, a restart request once it processed).
|
||||
struct LateLatency {
|
||||
inner: Box<dyn Plugin>,
|
||||
n: usize,
|
||||
lines: Vec<std::collections::VecDeque<f32>>,
|
||||
processed: bool,
|
||||
reported: usize,
|
||||
/// What it reports at each `idle` once it has processed (the last one stays).
|
||||
steps: std::collections::VecDeque<usize>,
|
||||
/// How many times it was prepared.
|
||||
prepares: Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
impl LateLatency {
|
||||
/// Prepared, as the host hands it over.
|
||||
fn new(n: usize) -> Self {
|
||||
Self::stepping(n, &[n])
|
||||
}
|
||||
|
||||
/// Delays by `n` from the start, but reports `steps` one `idle` at a time.
|
||||
fn stepping(n: usize, steps: &[usize]) -> Self {
|
||||
let mut p = LateLatency {
|
||||
inner: soundcraft_dsp::create("gain").unwrap(),
|
||||
n,
|
||||
lines: Vec::new(),
|
||||
processed: false,
|
||||
reported: 0,
|
||||
steps: steps.iter().copied().collect(),
|
||||
prepares: Arc::default(),
|
||||
};
|
||||
p.prepare(48_000.0, 512, 2);
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
impl Plugin for LateLatency {
|
||||
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
|
||||
self.inner.info()
|
||||
}
|
||||
fn prepare(&mut self, sr: f32, mb: usize, ch: usize) {
|
||||
self.inner.prepare(sr, mb, ch);
|
||||
self.lines = vec![std::iter::repeat_n(0.0, self.n).collect(); ch];
|
||||
self.prepares.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|x| *x = 0.0));
|
||||
}
|
||||
fn set_param(&mut self, id: &str, v: f32) -> bool {
|
||||
self.inner.set_param(id, v)
|
||||
}
|
||||
fn param(&self, id: &str) -> Option<f32> {
|
||||
self.inner.param(id)
|
||||
}
|
||||
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
|
||||
for (c, line) in io.iter_mut().zip(&mut self.lines) {
|
||||
for x in c.iter_mut().take(frames) {
|
||||
line.push_back(*x);
|
||||
*x = line.pop_front().unwrap();
|
||||
}
|
||||
}
|
||||
self.processed = true;
|
||||
}
|
||||
fn latency(&self) -> usize {
|
||||
self.reported
|
||||
}
|
||||
fn idle(&mut self) {
|
||||
if self.processed
|
||||
&& let Some(r) = self.steps.pop_front()
|
||||
{
|
||||
self.reported = r;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hosted insert that reports its latency only after the first block (on a track, or on the
|
||||
/// master, whose latency is read before it processes) still lines up from the first sample.
|
||||
#[test]
|
||||
fn offline_renders_follow_a_latency_reported_after_the_first_block() {
|
||||
for kind in [TrackKind::Audio, TrackKind::Master] {
|
||||
let mut s = Session::default();
|
||||
s.edit.delay_compensation = true;
|
||||
let n = 4096;
|
||||
let mut clicks = vec![0.0f32; n];
|
||||
for at in [100, 3000] {
|
||||
clicks[at] = 0.25;
|
||||
}
|
||||
s.pool.insert(SourceId(902), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] })));
|
||||
let mut tracks = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None);
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(902), 0, 0, n as i64));
|
||||
tracks.push(t);
|
||||
}
|
||||
let target = if kind == TrackKind::Audio { tracks[0] } else { s.add_track(TrackKind::Master, ChannelFormat::Stereo, None) };
|
||||
s.track_mut(target).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late"));
|
||||
let render = |s: &Session| {
|
||||
let mut r = RangeRender::new(s, None, Range::new(0, n as i64), 512);
|
||||
r.engine().set_external_instances(true);
|
||||
r.engine().adopt(vec![PreparedInstance {
|
||||
track: target,
|
||||
slot: 0,
|
||||
id: "clap:test.late".into(),
|
||||
ch: 2,
|
||||
plugin: Box::new(LateLatency::new(240)),
|
||||
}]);
|
||||
let mut out = vec![Vec::new(); 2];
|
||||
while let Some((chunk, k)) = r.next_block(s) {
|
||||
for (o, c) in out.iter_mut().zip(chunk) {
|
||||
o.extend_from_slice(&c[..k]);
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
// Both tracks play the clicks: they land where they are on the timeline.
|
||||
let out = render(&s);
|
||||
assert_eq!(out[0].len(), n);
|
||||
assert_eq!(impulse_at(&out[0]), vec![100, 3000], "{kind:?}: the plugin's 240 samples are compensated from the start");
|
||||
// The second track flipped: with the two lined up, nothing is left.
|
||||
s.track_mut(tracks[1]).unwrap().mixer.phase_invert = true;
|
||||
let out = render(&s);
|
||||
assert!(out.iter().flatten().all(|x| x.abs() < 1e-6), "{kind:?}: the tracks line up");
|
||||
}
|
||||
}
|
||||
|
||||
/// An echo 1000 samples later whose memory survives `reset` and is cleared only by `prepare`,
|
||||
/// like a VST3 processor: its reset only flushes notes, and activating it again clears its audio.
|
||||
struct KeepsTail {
|
||||
inner: Box<dyn Plugin>,
|
||||
ring: Vec<Vec<f32>>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl KeepsTail {
|
||||
/// Prepared, as the host hands it over.
|
||||
fn new() -> Self {
|
||||
let mut p = KeepsTail { inner: soundcraft_dsp::create("gain").unwrap(), ring: Vec::new(), pos: 0 };
|
||||
p.prepare(48_000.0, 512, 2);
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
impl Plugin for KeepsTail {
|
||||
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
|
||||
self.inner.info()
|
||||
}
|
||||
fn prepare(&mut self, sr: f32, mb: usize, ch: usize) {
|
||||
self.inner.prepare(sr, mb, ch);
|
||||
self.ring = vec![vec![0.0; 1000]; ch];
|
||||
self.pos = 0;
|
||||
}
|
||||
fn reset(&mut self) {}
|
||||
fn set_param(&mut self, id: &str, v: f32) -> bool {
|
||||
self.inner.set_param(id, v)
|
||||
}
|
||||
fn param(&self, id: &str) -> Option<f32> {
|
||||
self.inner.param(id)
|
||||
}
|
||||
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
|
||||
for i in 0..frames {
|
||||
for (c, ring) in io.iter_mut().zip(&mut self.ring) {
|
||||
let old = std::mem::replace(&mut ring[self.pos], c[i]);
|
||||
c[i] += 0.5 * old;
|
||||
}
|
||||
self.pos = (self.pos + 1) % 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starting the first block over must not keep what the discarded pass left in an insert whose
|
||||
/// own reset keeps its audio (a VST3 tail), on any track.
|
||||
#[test]
|
||||
fn a_first_block_rendered_again_carries_nothing_from_the_discarded_pass() {
|
||||
let mut s = Session::default();
|
||||
s.edit.delay_compensation = true;
|
||||
let n = 4096;
|
||||
let mut clicks = vec![0.0f32; n];
|
||||
for at in [100, 3000] {
|
||||
clicks[at] = 0.25;
|
||||
}
|
||||
s.pool.insert(SourceId(903), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] })));
|
||||
let mut tracks = Vec::new();
|
||||
for slot in ["clap:test.late", "clap:test.tail"] {
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None);
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(903), 0, 0, n as i64));
|
||||
s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new(slot));
|
||||
tracks.push(t);
|
||||
}
|
||||
let mut r = RangeRender::new(&s, None, Range::new(0, n as i64), 512);
|
||||
r.engine().set_external_instances(true);
|
||||
r.engine().adopt(vec![
|
||||
PreparedInstance { track: tracks[0], slot: 0, id: "clap:test.late".into(), ch: 2, plugin: Box::new(LateLatency::new(240)) },
|
||||
PreparedInstance { track: tracks[1], slot: 0, id: "clap:test.tail".into(), ch: 2, plugin: Box::new(KeepsTail::new()) },
|
||||
]);
|
||||
let mut out = vec![Vec::new(); 2];
|
||||
while let Some((chunk, k)) = r.next_block(&s) {
|
||||
for (o, c) in out.iter_mut().zip(chunk) {
|
||||
o.extend_from_slice(&c[..k]);
|
||||
}
|
||||
}
|
||||
assert_eq!(impulse_at(&out[0]), vec![100, 1100, 3000, 4000], "the clicks and their echoes, and no echo of the first pass");
|
||||
}
|
||||
|
||||
/// Clicks at 100 and 3000 on a stereo track with `plugin` as its insert, rendered in 512-sample
|
||||
/// blocks: where the clicks land.
|
||||
fn clicks_through(plugin: LateLatency) -> Vec<usize> {
|
||||
let mut s = Session::default();
|
||||
s.edit.delay_compensation = true;
|
||||
let n = 4096;
|
||||
let mut clicks = vec![0.0f32; n];
|
||||
for at in [100, 3000] {
|
||||
clicks[at] = 0.25;
|
||||
}
|
||||
s.pool.insert(SourceId(904), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] })));
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None);
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(904), 0, 0, n as i64));
|
||||
s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late"));
|
||||
let mut r = RangeRender::new(&s, None, Range::new(0, n as i64), 512);
|
||||
r.engine().set_external_instances(true);
|
||||
r.engine().adopt(vec![PreparedInstance { track: t, slot: 0, id: "clap:test.late".into(), ch: 2, plugin: Box::new(plugin) }]);
|
||||
let mut out = Vec::new();
|
||||
while let Some((chunk, k)) = r.next_block(&s) {
|
||||
out.extend_from_slice(&chunk[0][..k]);
|
||||
}
|
||||
impulse_at(&out)
|
||||
}
|
||||
|
||||
/// A plugin whose latency settles in two steps (it changes again on the first block rendered a
|
||||
/// second time) still lines up: the render starts over until no latency changes.
|
||||
#[test]
|
||||
fn a_latency_that_settles_in_two_steps_still_lines_up() {
|
||||
assert_eq!(clicks_through(LateLatency::stepping(240, &[120, 240])), vec![100, 3000]);
|
||||
assert_eq!(clicks_through(LateLatency::new(240)), vec![100, 3000], "one step");
|
||||
}
|
||||
|
||||
/// An instrument's latency is compensated like an insert's (#1476), so either one reported late
|
||||
/// renders the first block again (every hosted instance is prepared a second time).
|
||||
#[test]
|
||||
fn an_insert_or_instrument_latency_reported_late_renders_the_first_block_again() {
|
||||
for insert_too in [false, true] {
|
||||
let (mut s, a) = session_with_dc(0.5, 4096);
|
||||
let inst = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, None);
|
||||
s.track_mut(inst).unwrap().instrument = Some(Insert::new("clap:test.inst"));
|
||||
let synth = LateLatency::new(64);
|
||||
let prepares = Arc::clone(&synth.prepares);
|
||||
let mut adopt = vec![PreparedInstance { track: inst, slot: INSTRUMENT_SLOT, id: "clap:test.inst".into(), ch: 2, plugin: Box::new(synth) }];
|
||||
if insert_too {
|
||||
s.track_mut(a).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late"));
|
||||
adopt.push(PreparedInstance { track: a, slot: 0, id: "clap:test.late".into(), ch: 1, plugin: Box::new(LateLatency::new(240)) });
|
||||
}
|
||||
let mut r = RangeRender::new(&s, None, Range::new(0, 4096), 512);
|
||||
r.engine().set_external_instances(true);
|
||||
r.engine().adopt(adopt);
|
||||
while r.next_block(&s).is_some() {}
|
||||
assert_eq!(prepares.load(std::sync::atomic::Ordering::Relaxed), 2, "with an insert reporting late too: {insert_too}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A master fader's breakpoint acts on its own sample too.
|
||||
#[test]
|
||||
fn master_volume_automation_follows_its_breakpoints_in_any_block_size() {
|
||||
|
||||
@@ -168,7 +168,7 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
|
||||
assert!(ui.main.peak[0] > 0.5 && ui.main.peaks.iter().all(|p| *p > 0.5), "{:?}", ui.main);
|
||||
// Taking starts a new period: the next quiet blocks read quiet.
|
||||
st.fill(&mut out, 2);
|
||||
assert!(take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui));
|
||||
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).
|
||||
|
||||
@@ -154,8 +154,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"new" => "novo",
|
||||
"New Bus" => "Novo bus",
|
||||
"new bus..." => "novo bus...",
|
||||
"new mono bus" => "novo bus mono",
|
||||
"new stereo bus" => "novo bus estéreo",
|
||||
"New Configuration…" => "Nova configuração…",
|
||||
"New Group…" => "Novo grupo…",
|
||||
"New..." => "Novo...",
|
||||
@@ -783,10 +781,6 @@ fn menu_translate(source: &str) -> Option<&'static str> {
|
||||
"Start to Insertion" => "Do início até o ponto de inserção",
|
||||
"Step Input..." => "Entrada passo a passo...",
|
||||
"Stretch..." => "Alongar...",
|
||||
"Room Tone" => "Som ambiente",
|
||||
"Set Room Tone" => "Definir som ambiente",
|
||||
"Fill Gaps with Room Tone" => "Preencher lacunas com som ambiente",
|
||||
"Clear Room Tone" => "Limpar som ambiente",
|
||||
"Strip Silence" => "Remover silêncio",
|
||||
"Sync Point" => "Ponto de sincronização",
|
||||
"Synchronization" => "Sincronização",
|
||||
@@ -2076,8 +2070,8 @@ fn menu_translate(source: &str) -> Option<&'static str> {
|
||||
"♩ = {bpm:.2} {n}/{d}" => "♩ = {bpm:.2} {n}/{d}",
|
||||
"{n} ch" => "{n} canais",
|
||||
"{b}-bit" => "{b} bits",
|
||||
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · {fine_drag} or Shift-drag for fine control · Alt-click for 0 dB · right-click for options" => {
|
||||
"Envio {which} para {name}: {db} dB\nClique para abrir o fader do envio · arraste na vertical para ajustar · {fine_drag} ou Shift-arraste para controle fino · Alt-clique para 0 dB · clique com o botão direito para opções"
|
||||
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options" => {
|
||||
"Envio {which} para {name}: {db} dB\nClique para abrir o fader do envio · arraste na vertical para ajustar · Shift-arraste para controle fino · Alt-clique para 0 dB · clique com o botão direito para opções"
|
||||
}
|
||||
"1 {what}" => "1 {what}",
|
||||
"{n} {what}s" => "{n} {what}s",
|
||||
@@ -2093,11 +2087,6 @@ fn menu_translate(source: &str) -> Option<&'static str> {
|
||||
" {n} of the files are used by {users}" => " {n} dos arquivos são usados por {users}",
|
||||
" The file stays on disk." => " O arquivo permanece no disco.",
|
||||
" The files stay on disk." => " Os arquivos permanecem no disco.",
|
||||
"Unloop" => "Desativar loop",
|
||||
"Flatten" => "Consolidar",
|
||||
"Remove deletes the loop iterations and keeps the source clip. Flatten keeps each loop iteration as its own clip." => {
|
||||
"Remover exclui as iterações do loop e mantém o clipe de origem. Consolidar mantém cada iteração do loop como um clipe próprio."
|
||||
}
|
||||
_ => return error_translation(source),
|
||||
})
|
||||
}
|
||||
@@ -2126,7 +2115,6 @@ error_templates! {
|
||||
"internal error in `{c}`: {why}" => "erro interno em `{c}`: {why}",
|
||||
"stop recording first" => "pare a gravação primeiro",
|
||||
"journal entry cap" => "limite de entradas do diário atingido",
|
||||
"MIDI file exceeds a limit of {events} events, {tracks} tracks, or {bytes} bytes of SysEx payload" => "O arquivo MIDI excede um dos limites: {events} eventos, {tracks} pistas ou {bytes} bytes de dados SysEx",
|
||||
"MIDI file: more than {n} meter changes" => "arquivo MIDI: mais de {n} mudanças de compasso",
|
||||
"MIDI file: more than {n} tempo changes" => "arquivo MIDI: mais de {n} mudanças de andamento",
|
||||
"MIDI file: more than {n} tracks" => "arquivo MIDI: mais de {n} pistas",
|
||||
|
||||
@@ -405,7 +405,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"Finish or cancel the bounce first" => "请先完成或取消当前导出",
|
||||
"First clip: {name}" => "首个片段:{name}",
|
||||
"First clip: {}" => "首个片段:{}",
|
||||
"Flatten" => "展平",
|
||||
"Flatten Performance..." => "展平演奏...",
|
||||
"Folder Lines" => "文件夹连线",
|
||||
"Folder path" => "文件夹路径",
|
||||
@@ -829,7 +828,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"Remove Sync Point" => "移除同步点",
|
||||
"Remove Tempo Change" => "移除速度更改",
|
||||
"Remove Warp" => "移除扭曲",
|
||||
"Remove deletes the loop iterations and keeps the source clip. Flatten keeps each loop iteration as its own clip." => "移除会删除循环迭代并保留源片段。展平会将每个循环迭代保留为单独的片段。",
|
||||
"Remove from Folder" => "从文件夹中移除",
|
||||
"Remove send" => "移除发送",
|
||||
"Remove this row" => "移除此行",
|
||||
@@ -1181,7 +1179,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"Ungroup All" => "全部取消编组",
|
||||
"Universe" => "总览",
|
||||
"Unknown vendor" => "未知厂商",
|
||||
"Unloop" => "取消循环",
|
||||
"Unloop..." => "取消循环...",
|
||||
"Unsaved Changes" => "未保存的更改",
|
||||
"Update Active Configuration" => "更新当前配置",
|
||||
@@ -1288,8 +1285,6 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"mute" => "静音",
|
||||
"new" => "个新",
|
||||
"new bus..." => "新建总线...",
|
||||
"new mono bus" => "新建单声道总线",
|
||||
"new stereo bus" => "新建立体声总线",
|
||||
"no audio engine" => "无音频引擎",
|
||||
"no audio input device" => "没有音频输入设备",
|
||||
"no audio track is record-enabled" => "没有已启用录音的音频轨道",
|
||||
|
||||
@@ -416,7 +416,7 @@ impl SoundApp {
|
||||
if self.meters_live() {
|
||||
let hz = if self.ui.window == MainWindow::Mix { 60 } else { 30 };
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(1000 / hz));
|
||||
} else if self.main_meter.is_moving() || self.meters.values().any(MeterDisplay::is_moving) {
|
||||
} else if self.meters.values().any(|m| m.level[0] > 0.0001) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(80));
|
||||
} else if !self.pending_shots.is_empty() || !self.synthetic.is_empty() {
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -173,106 +173,35 @@ fn one_driver_per_process(cfg: &soundcraft_playback::AudioConfig) -> bool {
|
||||
cfg.system.as_deref().is_some_and(|s| s.eq_ignore_ascii_case("ASIO"))
|
||||
}
|
||||
|
||||
/// Fold one reading into a strip's meter. `peak` is the stereo pair (a mono strip repeats its one
|
||||
/// channel), `peaks` every channel of the strip: channels from the third on read from `peaks`.
|
||||
pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], peaks: &[f32], gr: f32, dt: f32) {
|
||||
pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], gr: f32, dt: f32) {
|
||||
// Instant attack, ~26 dB/s release, 2 s peak hold.
|
||||
let fall = 10f32.powf(-26.0 * dt / 20.0);
|
||||
// Each channel times its own hold, so activity on one channel cannot keep another's hold up.
|
||||
let channels = d.level.iter_mut().zip(&mut d.hold).zip(&mut d.hold_age).enumerate();
|
||||
for (c, ((lvl, hold), age)) in channels {
|
||||
let v = if c < 2 { peak.get(c) } else { peaks.get(c) }.copied().filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let nv = if v >= *lvl { v } else { (*lvl * fall).max(v) };
|
||||
*lvl = if nv < 1e-5 { 0.0 } else { nv };
|
||||
if v >= *hold {
|
||||
*hold = v;
|
||||
*age = 0.0;
|
||||
for c in 0..2 {
|
||||
let v = peak.get(c).copied().unwrap_or(0.0);
|
||||
let lvl = d.level.get(c).copied().unwrap_or(0.0);
|
||||
let nv = if v >= lvl { v } else { (lvl * fall).max(v) };
|
||||
if let Some(x) = d.level.get_mut(c) {
|
||||
*x = if nv < 1e-5 { 0.0 } else { nv };
|
||||
}
|
||||
*age += dt;
|
||||
if *age > 2.0 {
|
||||
*hold = *lvl;
|
||||
// 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 let Some(h) = d.hold.get_mut(c) {
|
||||
*h = v;
|
||||
}
|
||||
d.hold_age = 0.0;
|
||||
}
|
||||
if v >= 1.0 {
|
||||
d.clip = true;
|
||||
}
|
||||
}
|
||||
d.hold_age += dt;
|
||||
if d.hold_age > 2.0 {
|
||||
d.hold = d.level;
|
||||
}
|
||||
d.gr = if gr > d.gr { gr } else { d.gr * fall };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MeterDisplay, feed_meter};
|
||||
|
||||
#[test]
|
||||
fn surround_channels_get_levels_holds_and_clip_like_the_stereo_pair() {
|
||||
let mut d = MeterDisplay::default();
|
||||
// A 5.1 strip: L R C LFE Ls Rs; the surround right channel clips.
|
||||
let peaks = [0.5, 0.4, 0.3, 0.2, 0.1, 1.0];
|
||||
feed_meter(&mut d, [0.5, 0.4], &peaks, 0.0, 0.05);
|
||||
assert_eq!(d.level.get(..6), Some(&peaks[..]));
|
||||
assert_eq!(d.hold.get(..6), Some(&peaks[..]));
|
||||
assert!(d.clip, "a clip on any channel lights the clip light");
|
||||
assert!(d.level.get(6..).is_some_and(|rest| rest.iter().all(|v| *v == 0.0)));
|
||||
// Silence: every channel falls back smoothly, and its peak hold stays up for now.
|
||||
feed_meter(&mut d, [0.0, 0.0], &[], 0.0, 0.05);
|
||||
let c = d.level.get(2).copied().unwrap_or_default();
|
||||
assert!(c > 0.0 && c < 0.3, "C falls, not drops: {c}");
|
||||
assert_eq!(d.hold.get(2).copied(), Some(0.3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peak_holds_expire_after_two_seconds_of_silence_on_a_strip_with_unused_channels() {
|
||||
let mut d = MeterDisplay::default();
|
||||
// A stereo strip: every channel past the pair is unused and reads 0.
|
||||
feed_meter(&mut d, [0.5, 0.4], &[0.5, 0.4], 0.0, 0.05);
|
||||
for _ in 0..50 {
|
||||
feed_meter(&mut d, [0.0, 0.0], &[], 0.0, 0.05);
|
||||
}
|
||||
let l = d.hold.first().copied().unwrap_or_default();
|
||||
assert!(l < 0.5, "the L hold drops back to the falling level: {l}");
|
||||
assert_eq!(d.hold, d.level);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_busy_channel_does_not_keep_a_silent_channels_peak_hold_up() {
|
||||
let mut d = MeterDisplay::default();
|
||||
// A 5.1 strip: L peaks once, then only C carries a steady signal.
|
||||
feed_meter(&mut d, [0.5, 0.0], &[0.5, 0.0, 0.3], 0.0, 0.05);
|
||||
for _ in 0..50 {
|
||||
feed_meter(&mut d, [0.0, 0.0], &[0.0, 0.0, 0.3], 0.0, 0.05);
|
||||
}
|
||||
let l = d.hold.first().copied().unwrap_or_default();
|
||||
assert!(l < 0.5, "the L hold expires while C plays on: {l}");
|
||||
assert_eq!(d.hold.get(2).copied(), Some(0.3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_meter_moving_only_past_the_stereo_pair_still_needs_repaints() {
|
||||
let mut d = MeterDisplay::default();
|
||||
assert!(!d.is_moving());
|
||||
// A 5.1 strip with signal on C only.
|
||||
feed_meter(&mut d, [0.0, 0.0], &[0.0, 0.0, 0.3], 0.0, 0.05);
|
||||
assert!(d.is_moving());
|
||||
// Its level has fallen away but the C hold is still up.
|
||||
d.level = Default::default();
|
||||
assert!(d.is_moving(), "the hold has yet to expire");
|
||||
d.hold = Default::default();
|
||||
assert!(!d.is_moving());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_misbehaving_plugin_cannot_stick_a_meter() {
|
||||
let mut d = MeterDisplay::default();
|
||||
// Non-finite readings on the stereo pair and past it read as silence, not as a clip.
|
||||
feed_meter(&mut d, [f32::NAN, f32::INFINITY], &[f32::NAN, f32::INFINITY, f32::NAN, f32::NEG_INFINITY], 0.0, 0.05);
|
||||
assert!(d.level.iter().chain(&d.hold).all(|v| *v == 0.0) && !d.clip, "{d:?}");
|
||||
// And the next good reading shows on every channel.
|
||||
feed_meter(&mut d, [0.5, 0.4], &[0.5, 0.4, 0.3, 0.2], 0.0, 0.05);
|
||||
assert_eq!(d.level.get(..4), Some(&[0.5, 0.4, 0.3, 0.2][..]));
|
||||
assert_eq!(d.hold.get(..4), Some(&[0.5, 0.4, 0.3, 0.2][..]));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a track needs the audio input opened: an audio track (or an aux) that is
|
||||
/// record-enabled or input-monitored. A MIDI or instrument track listens to MIDI devices, so
|
||||
/// arming one does not open an audio device or complain that there is none.
|
||||
@@ -409,8 +338,8 @@ mod meter_tests {
|
||||
age_meters(&mut snap, fresh, now, &mut last_block);
|
||||
last_poll = now;
|
||||
}
|
||||
let (peak, peaks) = snap.tracks.get(&t).map_or(([0.0; 2], Vec::new()), |m| (m.peak, m.peaks.clone()));
|
||||
feed_meter(&mut d, peak, &peaks, 0.0, dt as f32);
|
||||
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]);
|
||||
}
|
||||
@@ -423,15 +352,15 @@ mod meter_tests {
|
||||
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.iter().chain(&d.hold).all(|v| *v == 0.0), "the meter still reads {d:?}");
|
||||
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 other channel's hold time.
|
||||
/// 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.iter().chain(&d.hold).all(|v| *v == 0.0), "the meter still reads {d:?}");
|
||||
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,7 +12,6 @@ impl SoundApp {
|
||||
// The Output window shows a track of the old session: a track of the new one can have
|
||||
// the same id.
|
||||
self.ui.output_window = None;
|
||||
self.dialogs.session_replaced();
|
||||
}
|
||||
|
||||
/// The session is modified, or a plugin editor gesture still holds a state the session hasn't
|
||||
|
||||
@@ -529,7 +529,7 @@ impl SoundApp {
|
||||
let snap = &self.meter_snapshot;
|
||||
for (id, m) in &snap.tracks {
|
||||
let d = self.meters.entry(*id).or_default();
|
||||
feed_meter(d, m.peak, &m.peaks, m.gain_reduction_db, dt);
|
||||
feed_meter(d, m.peak, m.gain_reduction_db, dt);
|
||||
if m.plugin_failures.count != d.plugin_failures {
|
||||
d.plugin_failures = m.plugin_failures.count;
|
||||
if let Some(msg) = failed_plugin_status(self.engine.session(), *id, m.plugin_failures.last) {
|
||||
@@ -537,7 +537,8 @@ impl SoundApp {
|
||||
}
|
||||
}
|
||||
}
|
||||
feed_meter(&mut self.main_meter, snap.main.peak, &snap.main.peaks, 0.0, dt);
|
||||
let main = snap.main.peak;
|
||||
feed_meter(&mut self.main_meter, main, 0.0, dt);
|
||||
if ended {
|
||||
self.stop_play();
|
||||
}
|
||||
@@ -557,9 +558,9 @@ impl SoundApp {
|
||||
}
|
||||
if !self.meters_live() {
|
||||
for d in self.meters.values_mut() {
|
||||
feed_meter(d, [0.0, 0.0], &[], 0.0, dt);
|
||||
feed_meter(d, [0.0, 0.0], 0.0, dt);
|
||||
}
|
||||
feed_meter(&mut self.main_meter, [0.0, 0.0], &[], 0.0, dt);
|
||||
feed_meter(&mut self.main_meter, [0.0, 0.0], 0.0, dt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,6 @@ pub enum Dialog {
|
||||
RenameClip { id: ClipId, name: String },
|
||||
RenameMarker { id: soundcraft_model::MarkerId, name: String },
|
||||
ClearClips { clips: Vec<ClipId>, sources: Vec<SourceId>, message: String },
|
||||
// Clip › Unloop…: the clips `clip.unloop` would take when it opened.
|
||||
Unloop { clips: Vec<ClipId> },
|
||||
PathPrompt { cmd: String, title: String, path: String, key: String },
|
||||
Number { cmd: String, title: String, key: String, value: f64, suffix: String },
|
||||
TempoChange { at: Samples, bpm: f64 }, // from double-clicking the tempo ruler
|
||||
@@ -99,7 +97,6 @@ impl Dialogs {
|
||||
Dialog::RenameClip { .. } => "rename_clip",
|
||||
Dialog::RenameMarker { .. } => "rename_marker",
|
||||
Dialog::ClearClips { .. } => "clear_clips",
|
||||
Dialog::Unloop { .. } => "unloop",
|
||||
Dialog::PathPrompt { .. } => "path",
|
||||
Dialog::Number { .. } => "number",
|
||||
Dialog::TempoChange { .. } => "tempo_change",
|
||||
@@ -129,26 +126,6 @@ impl Dialogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// The open session was replaced: closes a dialog that holds track, clip, source, marker or group ids, since the new
|
||||
/// session can reuse those ids for other objects.
|
||||
pub(crate) fn session_replaced(&mut self) {
|
||||
if matches!(
|
||||
self.open,
|
||||
Some(
|
||||
Dialog::RenameTrack { .. }
|
||||
| Dialog::RenameClip { .. }
|
||||
| Dialog::RenameMarker { .. }
|
||||
| Dialog::ClearClips { .. }
|
||||
| Dialog::Unloop { .. }
|
||||
| Dialog::AutoRename { .. }
|
||||
| Dialog::Spot(_)
|
||||
| Dialog::Group { .. }
|
||||
)
|
||||
) {
|
||||
self.open = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_rename_track(&mut self, id: TrackId, name: &str) {
|
||||
self.set(Dialog::RenameTrack { id, name: name.to_string() });
|
||||
}
|
||||
@@ -197,11 +174,6 @@ impl Dialogs {
|
||||
|
||||
/// Open the dialog for a command; false when the command has no dialog.
|
||||
pub fn open_for_command(&mut self, e: &Engine, id: &str) -> bool {
|
||||
// Unloop with no looped clip opens nothing, so it leaves a pending Save-then-continue action in place.
|
||||
let unloop_clips = if id == "clip.unloop" { soundcraft_engine::cmd::clip_ids_param(e, &json!({})) } else { Vec::new() };
|
||||
if id == "clip.unloop" && !unloop_clips.iter().any(|&c| soundcraft_engine::cmd::is_looped(e.session(), c)) {
|
||||
return false;
|
||||
}
|
||||
self.after_save = None;
|
||||
let home = default_dir();
|
||||
let name = e.session().name.clone();
|
||||
@@ -210,7 +182,6 @@ impl Dialogs {
|
||||
let ed = &e.session().edit;
|
||||
return self.open_clear(e, ed.selected_clips.clone(), ed.selected_sources.clone());
|
||||
}
|
||||
"clip.unloop" => Dialog::Unloop { clips: unloop_clips },
|
||||
"track.new" => Dialog::NewTracks(new_tracks::NewTracks::default()),
|
||||
"session.new" => Dialog::NewSession { name: "Untitled".into(), sample_rate: 48_000, demo: false },
|
||||
"file.bounce_mix" => {
|
||||
@@ -525,7 +496,6 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
Dialog::RenameClip { .. } => "Rename Clip",
|
||||
Dialog::RenameMarker { .. } => "Rename Marker",
|
||||
Dialog::ClearClips { .. } => "Clear",
|
||||
Dialog::Unloop { .. } => "Unloop",
|
||||
Dialog::PathPrompt { title, .. } | Dialog::Number { title, .. } => title.as_str(),
|
||||
Dialog::TempoChange { .. } => "Tempo Change (BPM)",
|
||||
Dialog::Spot(_) => "Spot",
|
||||
@@ -639,22 +609,6 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
action = Some(("clip.clear".into(), json!({"clips": clips, "sources": sources, "with_clips": true})));
|
||||
}
|
||||
}
|
||||
Dialog::Unloop { clips } => {
|
||||
ui.set_max_width(340.0);
|
||||
ui.label(crate::localization::text(
|
||||
"Remove deletes the loop iterations and keeps the source clip. Flatten keeps each loop iteration as its own clip.",
|
||||
));
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(crate::localization::text("Flatten")).clicked() {
|
||||
action = Some(unloop_action(clips, false));
|
||||
}
|
||||
// A Flatten click in the same frame as Enter wins.
|
||||
if buttons(ui, "Remove", enter && action.is_none()) {
|
||||
action = Some(unloop_action(clips, true));
|
||||
}
|
||||
});
|
||||
}
|
||||
Dialog::PathPrompt { cmd, path, key, .. } => {
|
||||
if let Some(c) = path_prompt_form(app, ui, cmd, path, key, enter) {
|
||||
action = Some(c);
|
||||
@@ -957,11 +911,6 @@ fn name_field(ui: &mut egui::Ui, name: &mut String) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The command the Unloop dialog runs: Remove (`remove`) or Flatten.
|
||||
fn unloop_action(clips: &[ClipId], remove: bool) -> (String, Value) {
|
||||
("clip.unloop".into(), json!({"clips": clips, "mode": if remove { "remove" } else { "flatten" }}))
|
||||
}
|
||||
|
||||
/// The command the tempo-change dialog runs on OK.
|
||||
fn tempo_change_action(at: Samples, bpm: f64) -> (String, Value) {
|
||||
("event.tempo".into(), json!({"bpm": bpm, "at": at}))
|
||||
@@ -1277,64 +1226,6 @@ mod tests {
|
||||
assert!(matches!(d.open, Some(Dialog::ScoreSetup { bars_per_system: 4, .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_unloop_opens_unloop_and_sends_the_chosen_mode() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
let mut d = Dialogs::default();
|
||||
e.execute("edit.select_none", &json!({})).unwrap();
|
||||
assert!(!d.open_for_command(&e, "clip.unloop"));
|
||||
let track = e.session().track_by_name("Snare").unwrap().id;
|
||||
let clip = e.session().track(track).unwrap().clips()[0].id;
|
||||
e.execute("edit.select", &json!({"clips": [clip.0]})).unwrap();
|
||||
assert!(!d.open_for_command(&e, "clip.unloop"), "a clip that is not looped opens no dialog");
|
||||
assert!(d.open.is_none());
|
||||
e.execute("clip.loop", &json!({"clip": clip.0, "count": 3})).unwrap();
|
||||
e.execute("edit.select", &json!({"clips": [clip.0]})).unwrap();
|
||||
assert!(d.open_for_command(&e, "clip.unloop"));
|
||||
assert_eq!(d.open_name(), Some("unloop"));
|
||||
let Some(Dialog::Unloop { clips }) = d.open.take() else { panic!("Unloop… did not open the Unloop dialog") };
|
||||
assert_eq!(clips, vec![clip]);
|
||||
let count = |e: &Engine| e.session().track(track).map_or(0, |t| t.clips().len());
|
||||
let before = count(&e);
|
||||
let (cmd, params) = unloop_action(&clips, false);
|
||||
assert_eq!(params["mode"], "flatten");
|
||||
e.execute(&cmd, ¶ms).unwrap();
|
||||
assert_eq!(count(&e), before, "Flatten keeps every iteration");
|
||||
assert!(e.session().track(track).unwrap().clips().iter().all(|c| c.loop_id.is_none()));
|
||||
e.execute("edit.undo", &json!({})).unwrap();
|
||||
let (cmd, params) = unloop_action(&clips, true);
|
||||
assert_eq!(params["mode"], "remove");
|
||||
e.execute(&cmd, ¶ms).unwrap();
|
||||
assert_eq!(count(&e), before - 2, "Remove keeps only the source clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unloop_without_a_looped_clip_keeps_the_pending_save_action() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
let mut d = Dialogs { after_save: Some(("app.quit".into(), json!({}))), ..Dialogs::default() };
|
||||
let clip = e.session().track_by_name("Snare").unwrap().clips()[0].id;
|
||||
e.execute("edit.select", &json!({"clips": [clip.0]})).unwrap();
|
||||
assert!(!d.open_for_command(&e, "clip.unloop"));
|
||||
assert!(d.after_save.is_some(), "an Unloop that opens nothing must not drop the action waiting on Save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_session_closes_dialogs_that_hold_its_ids() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, crate::Services::default());
|
||||
app.dialogs.set(Dialog::Unloop { clips: vec![ClipId(1)] });
|
||||
app.document_replaced();
|
||||
assert!(app.dialogs.open.is_none(), "Unloop must not act on clips of the new session");
|
||||
app.dialogs.set(Dialog::ClearClips { clips: vec![ClipId(1)], sources: Vec::new(), message: String::new() });
|
||||
app.document_replaced();
|
||||
assert!(app.dialogs.open.is_none());
|
||||
app.dialogs.set(Dialog::Group { id: None, name: "Group".into(), edit: true, mix: true, members: vec![(1, "Kick".into(), true)] });
|
||||
app.document_replaced();
|
||||
assert!(app.dialogs.open.is_none(), "Create Group must not group tracks of the new session");
|
||||
app.dialogs.set(Dialog::NewSession { name: "Untitled".into(), sample_rate: 48_000, demo: false });
|
||||
app.document_replaced();
|
||||
assert_eq!(app.dialogs.open_name(), Some("new_session"), "a dialog without session ids stays open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_rename_opens_the_rename_dialog_for_the_selected_clip() {
|
||||
let mut e = soundcraft_engine::demo::demo_engine();
|
||||
|
||||
@@ -45,10 +45,7 @@ use input::{clip_at, fade_midpoint};
|
||||
use layout::COLUMN_TITLES_H;
|
||||
#[cfg(test)]
|
||||
use layout::lane_rect;
|
||||
pub use layout::{
|
||||
COLUMN_W, EditLayout, HEADER_W, LANE_H, RULER_H, edit_columns, header_width, meter_channels, meter_width, rect, sample_at, track_header_width,
|
||||
track_height, x_of,
|
||||
};
|
||||
pub use layout::{COLUMN_W, EditLayout, HEADER_W, LANE_H, RULER_H, edit_columns, header_width, rect, sample_at, track_height, x_of};
|
||||
use overlay::overlay;
|
||||
#[cfg(test)]
|
||||
use overlay::playhead_colour;
|
||||
@@ -128,7 +125,7 @@ pub(crate) fn main_area(app: &mut SoundApp, ui: &mut Ui) {
|
||||
if session.edit.flag("view.ruler.tempo_editor") && session.edit.rulers.iter().any(|ruler| ruler == "tempo") {
|
||||
ruler_height_total += ruler_height("tempo_editor");
|
||||
}
|
||||
let minimum = vec2(header_width(session, &edit_columns(session)) + 64.0, ruler_height_total + 100.0);
|
||||
let minimum = vec2(header_width(&edit_columns(session)) + 64.0, ruler_height_total + 100.0);
|
||||
crate::docking::minimum_body(ui, minimum, |ui| main_area_content(app, ui));
|
||||
}
|
||||
|
||||
@@ -147,8 +144,7 @@ fn main_area_content(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let titles_h = if cols.is_empty() { 0.0 } else { COLUMN_TITLES_H };
|
||||
let rulers_h = rulers.iter().map(|r| ruler_height(r)).sum::<f32>() + 6.0 + titles_h;
|
||||
let hscroll_h = 14.0;
|
||||
let head_w = track_header_width(app.engine.session());
|
||||
let hw = head_w + cols.iter().map(|c| c.3).sum::<f32>();
|
||||
let hw = header_width(&cols);
|
||||
let header = Rect::from_min_max(full.min, pos2(full.min.x + hw, full.max.y - hscroll_h));
|
||||
let tl = Rect::from_min_max(pos2(full.min.x + hw, full.min.y + rulers_h), pos2(full.max.x - 12.0, full.max.y - hscroll_h));
|
||||
let rulers_rect = Rect::from_min_max(pos2(full.min.x, full.min.y), pos2(full.max.x, full.min.y + rulers_h));
|
||||
@@ -158,7 +154,7 @@ fn main_area_content(app: &mut SoundApp, ui: &mut Ui) {
|
||||
scroll_and_zoom(app, ui, full, tl);
|
||||
draw_rulers(app, ui, rulers_rect, tl, &rulers);
|
||||
views_button(app, ui, rulers_rect);
|
||||
column_titles(ui, app.engine.session(), rulers_rect, &cols);
|
||||
column_titles(ui, rulers_rect, &cols);
|
||||
if let Some(id) = app.edit_scroll_into_view.take() {
|
||||
scroll_into_view(app, id, tl.height());
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::layout::{HEADER_W, METER_W, STRIP_W, meter_channels, meter_width};
|
||||
use super::layout::STRIP_W;
|
||||
use super::tracks::{click_track, folder_depth, height_targets, in_edit_window, track_context_menu, view_label, view_menu};
|
||||
use super::{
|
||||
Align2, AutoParam, Color32, Gesture, Pos2, Rect, Sense, Shape, SoundApp, Stroke, StrokeKind, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui,
|
||||
@@ -25,11 +25,7 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head:
|
||||
voice_row(app, ui, track, head);
|
||||
field_row(app, ui, track, head, head_bg);
|
||||
let md = app.meters.get(&id).copied().unwrap_or_default();
|
||||
let channels = meter_channels(app.engine.session(), track);
|
||||
// Every track's meter starts where a stereo meter would; wider ones run on into the space the
|
||||
// header widened by (`track_header_width`).
|
||||
let x = head.min.x + HEADER_W - METER_W;
|
||||
header_meter(ui, Rect::from_min_max(pos2(x, head.min.y + 1.0), pos2(x + meter_width(channels), head.max.y - 1.5)), &md, channels);
|
||||
header_meter(ui, Rect::from_min_max(pos2(head.max.x - 8.0, head.min.y + 1.0), pos2(head.max.x, head.max.y - 1.5)), &md, track.channels() >= 2);
|
||||
}
|
||||
|
||||
/// The colour strip: a click selects the track as the header does, a double click opens the Color
|
||||
@@ -528,9 +524,8 @@ fn header_toggle(ui: &Ui, r: Rect, track: TrackId, track_name: &str, key: Header
|
||||
resp.on_hover_text(label)
|
||||
}
|
||||
|
||||
/// The header's level meter: one black-rimmed bar per channel (a mono meter fills the width with
|
||||
/// one), dim where unlit, with a clip light on top.
|
||||
fn header_meter(ui: &Ui, r: Rect, md: &crate::MeterDisplay, channels: usize) {
|
||||
/// The header's level meter: black-rimmed bars, dim where unlit, with a clip light on top.
|
||||
fn header_meter(ui: &Ui, r: Rect, md: &crate::MeterDisplay, stereo: bool) {
|
||||
let t = Tokens::current();
|
||||
let p = ui.painter();
|
||||
p.rect_filled(r, 0.0, Color32::BLACK);
|
||||
@@ -538,20 +533,20 @@ fn header_meter(ui: &Ui, r: Rect, md: &crate::MeterDisplay, channels: usize) {
|
||||
let clip = inner.with_max_y(inner.min.y + 4.0);
|
||||
p.rect_filled(clip, 0.0, if md.clip { t.meter_red } else { t.meter_red.gamma_multiply(0.18) });
|
||||
let body = inner.with_min_y(clip.max.y + 1.0);
|
||||
let n = channels.clamp(1, md.level.len());
|
||||
let w = ((body.width() - (n - 1) as f32) / n as f32).max(1.0);
|
||||
let n = if stereo { 2 } else { 1 };
|
||||
let w = (body.width() - (n - 1) as f32) / n as f32;
|
||||
let (amber, red) = (meter_pos(-12.0), meter_pos(-3.0));
|
||||
for ch in 0..n {
|
||||
let bar = Rect::from_min_size(pos2(body.min.x + ch as f32 * (w + 1.0), body.min.y), vec2(w, body.height()));
|
||||
let y = |f: f32| bar.max.y - bar.height() * f;
|
||||
let lv = level_pos(md.level.get(ch).copied().unwrap_or(0.0));
|
||||
let lv = level_pos(md.level[ch]);
|
||||
for (lo, hi, col) in [(0.0, amber, t.meter_green), (amber, red, t.meter_yellow), (red, 1.0, t.meter_red)] {
|
||||
p.rect_filled(Rect::from_x_y_ranges(bar.x_range(), y(hi)..=y(lo)), 0.0, col.gamma_multiply(0.18));
|
||||
if lv > lo {
|
||||
p.rect_filled(Rect::from_x_y_ranges(bar.x_range(), y(lv.min(hi))..=y(lo)), 0.0, col);
|
||||
}
|
||||
}
|
||||
let hv = level_pos(md.hold.get(ch).copied().unwrap_or(0.0));
|
||||
let hv = level_pos(md.hold[ch]);
|
||||
if hv > 0.01 {
|
||||
p.hline(bar.x_range(), y(hv), Stroke::new(1.0, if hv > red { t.meter_red } else { t.meter_yellow }));
|
||||
}
|
||||
|
||||
@@ -32,33 +32,8 @@ pub fn edit_columns(s: &Session) -> Vec<Column> {
|
||||
COLUMNS.into_iter().filter(|c| all || s.edit.flag(&format!("edit_view.{}", c.0))).collect()
|
||||
}
|
||||
|
||||
/// The meter at the right of a track header: one bar per channel as Pro Tools draws it, at the
|
||||
/// density of the stereo meter (2.5 pt bars, 1 pt apart, inside a 1 pt rim). Mono and stereo
|
||||
/// meters share the stereo width.
|
||||
pub(super) const METER_W: f32 = 8.0;
|
||||
|
||||
/// The width of a track header's meter for `channels` channels.
|
||||
pub fn meter_width(channels: usize) -> f32 {
|
||||
let n = channels.clamp(1, soundcraft_mix::MAX_CHANNELS) as f32;
|
||||
(2.0 + 2.5 * n + (n - 1.0)).max(METER_W)
|
||||
}
|
||||
|
||||
/// How many bars a track's header meter has: its own channels, or the main output's for the
|
||||
/// master fader (as on its Mix window strip).
|
||||
pub fn meter_channels(s: &Session, t: &Track) -> usize {
|
||||
let format = if t.kind == soundcraft_model::TrackKind::Master { s.main_format() } else { t.format };
|
||||
format.channels().clamp(1, soundcraft_mix::MAX_CHANNELS)
|
||||
}
|
||||
|
||||
/// The width of the track headers (without the optional columns). Like Pro Tools, it widens to fit
|
||||
/// the widest meter of the tracks shown, so every track's meter starts at the same place.
|
||||
pub fn track_header_width(s: &Session) -> f32 {
|
||||
let widest = s.tracks.iter().filter(|t| super::tracks::in_edit_window(s, t)).map(|t| meter_channels(s, t)).max().unwrap_or(1);
|
||||
HEADER_W + meter_width(widest) - METER_W
|
||||
}
|
||||
|
||||
pub fn header_width(s: &Session, cols: &[Column]) -> f32 {
|
||||
track_header_width(s) + cols.iter().map(|c| c.3).sum::<f32>()
|
||||
pub fn header_width(cols: &[Column]) -> f32 {
|
||||
HEADER_W + cols.iter().map(|c| c.3).sum::<f32>()
|
||||
}
|
||||
|
||||
pub const RULER_H: f32 = 17.0;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::input::snap;
|
||||
use super::layout::{COLUMN_TITLES_H, COLUMNS, Column, RULER_H, edit_columns, sample_at, track_header_width, x_of};
|
||||
use super::layout::{COLUMN_TITLES_H, COLUMNS, Column, HEADER_W, RULER_H, edit_columns, header_width, sample_at, x_of};
|
||||
use super::{
|
||||
Align2, Color32, GridValue, NoteValue, Range, Rect, Samples, Sense, Session, Shape, SoundApp, Stroke, TimeFormat, Tokens, Ui, bold,
|
||||
format_position, json, pos2, regular, rgb, vec2,
|
||||
@@ -138,7 +138,6 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
|
||||
ui.painter().rect_filled(area, 0.0, t.ruler_bg);
|
||||
let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x));
|
||||
let sr = s.sample_rate;
|
||||
let head_w = track_header_width(&s);
|
||||
// The selection is marked in the main timebase ruler, or in the top one when that is hidden.
|
||||
let main = rulers.iter().position(|id| TimeFormat::from_id(id) == Some(s.edit.main_counter)).unwrap_or(0);
|
||||
let marker = selection_marker_colour(&t, s.tracks.iter().any(|track| track.mixer.record_arm));
|
||||
@@ -146,7 +145,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
|
||||
for (i, id) in rulers.iter().enumerate() {
|
||||
let h = ruler_height(id);
|
||||
let row = Rect::from_min_max(pos2(tl.min.x, y0), pos2(tl.max.x, y0 + h));
|
||||
let lab = Rect::from_min_max(pos2(area.min.x, y0), pos2(area.min.x + head_w, y0 + h));
|
||||
let lab = Rect::from_min_max(pos2(area.min.x, y0), pos2(area.min.x + HEADER_W, y0 + h));
|
||||
y0 += h;
|
||||
let painter = ui.painter().with_clip_rect(row);
|
||||
ui.painter().text(
|
||||
@@ -432,14 +431,14 @@ fn timebase_ruler(painter: &egui::Painter, s: &Session, place: &RulerRow, f: Tim
|
||||
}
|
||||
|
||||
/// Captions over the header columns, boxed in their own row under the rulers.
|
||||
pub(super) fn column_titles(ui: &Ui, s: &Session, rulers: Rect, cols: &[Column]) {
|
||||
pub(super) fn column_titles(ui: &Ui, rulers: Rect, cols: &[Column]) {
|
||||
if cols.is_empty() {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::current();
|
||||
let line = Stroke::new(1.0, t.border);
|
||||
let mut x = rulers.min.x + track_header_width(s);
|
||||
let end = x + cols.iter().map(|c| c.3).sum::<f32>();
|
||||
let mut x = rulers.min.x + HEADER_W;
|
||||
let end = rulers.min.x + header_width(cols);
|
||||
let row = Rect::from_min_max(pos2(x, rulers.max.y - COLUMN_TITLES_H - 3.0), pos2(end, rulers.max.y));
|
||||
ui.painter().rect_filled(row, 0.0, t.panel_bg2);
|
||||
ui.painter().hline(rulers.min.x..=end, row.min.y + 0.5, line);
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::automation::draw_automation;
|
||||
use super::clips::{ClipLane, GridLines, clip_cuts, draw_clip, draw_live_take, draw_strip_silence};
|
||||
use super::header::{header_column, track_header};
|
||||
use super::input::lane_interaction;
|
||||
use super::layout::{Column, LANE_H, STRIP_W, lane_rect, sample_at, x_of};
|
||||
use super::layout::{Column, HEADER_W, LANE_H, STRIP_W, lane_rect, sample_at, x_of};
|
||||
use super::{
|
||||
Align2, AutoParam, Range, Rect, Sense, Session, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, json, ops, pos2, regular,
|
||||
rgb, vec2,
|
||||
@@ -58,16 +58,13 @@ pub(crate) fn click_track(app: &mut SoundApp, id: TrackId, mods: egui::Modifiers
|
||||
|
||||
// ---- track rows ------------------------------------------------------------------------------
|
||||
|
||||
/// Draw one track: its header, optional columns and lane, with grid positions shared by all lanes
|
||||
/// in the current frame. The header is the same width for every track (the widest meter shown):
|
||||
/// what the row leaves of the header column `tl` starts after, once the columns take theirs.
|
||||
/// Draw one track with grid positions shared by all lanes in the current frame.
|
||||
pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect, tl: Rect, cols: &[Column], grid: &GridLines) {
|
||||
let t = Tokens::current();
|
||||
let s = app.engine.session_arc();
|
||||
let Some(track) = s.track(id) else { return };
|
||||
let selected = s.edit.selected_tracks.contains(&id);
|
||||
let head_w = tl.min.x - row.min.x - cols.iter().map(|c| c.3).sum::<f32>();
|
||||
let head = Rect::from_min_max(row.min, pos2(row.min.x + head_w, row.max.y));
|
||||
let head = Rect::from_min_max(row.min, pos2(row.min.x + HEADER_W, row.max.y));
|
||||
let (head_bg, lane_bg) = crate::theme::track_backgrounds(track.color, selected, app.ui.track_tint);
|
||||
let mut x = head.max.x;
|
||||
for &(col, _, _, w) in cols {
|
||||
|
||||
@@ -693,9 +693,6 @@
|
||||
Remove from Folder 从文件夹中移除
|
||||
Remove send 移除发送
|
||||
Remove 移除
|
||||
Remove deletes the loop iterations and keeps the source clip. Flatten keeps each loop iteration as its own clip. 移除会删除循环迭代并保留源片段。展平会将每个循环迭代保留为单独的片段。
|
||||
Flatten 展平
|
||||
Unloop 取消循环
|
||||
Rename bus… 重命名总线…
|
||||
Renders and AudioSuite processes run to completion before returning. 渲染与 AudioSuite 处理会执行完毕后再返回。
|
||||
Reopen the audio devices with these settings 使用这些设置重新打开音频设备
|
||||
@@ -868,8 +865,6 @@ automation trim 微调
|
||||
bpm BPM
|
||||
no insert 无插入
|
||||
new bus... 新建总线...
|
||||
new mono bus 新建单声道总线
|
||||
new stereo bus 新建立体声总线
|
||||
OK 确定
|
||||
Replace 替换
|
||||
Revert “{name}” to its last saved version? Your changes will be lost. 将“{name}”恢复到上次保存的版本?你的更改将丢失。
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 796 and column 11.
|
@@ -271,29 +271,18 @@ pub fn fit_window_to_screen(ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ballistic meter display state per strip, one level and peak hold per channel. Channels 0 and 1
|
||||
/// are the stereo pair (a mono strip repeats channel 0 in 1); a surround or immersive strip fills
|
||||
/// as many as it has, up to [`soundcraft_mix::MAX_CHANNELS`].
|
||||
/// Ballistic meter display state per strip.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct MeterDisplay {
|
||||
pub level: [f32; soundcraft_mix::MAX_CHANNELS],
|
||||
pub hold: [f32; soundcraft_mix::MAX_CHANNELS],
|
||||
/// Seconds since each channel's peak hold was last set.
|
||||
pub hold_age: [f32; soundcraft_mix::MAX_CHANNELS],
|
||||
pub level: [f32; 2],
|
||||
pub hold: [f32; 2],
|
||||
pub hold_age: f32,
|
||||
pub clip: bool,
|
||||
pub gr: f32,
|
||||
/// [`soundcraft_mix::PluginFailures::count`] as last seen.
|
||||
pub plugin_failures: u32,
|
||||
}
|
||||
|
||||
impl MeterDisplay {
|
||||
/// Whether any channel still shows a level or a peak hold, so the meter keeps falling (or its
|
||||
/// hold has yet to expire) and needs repainting.
|
||||
pub fn is_moving(&self) -> bool {
|
||||
self.level.iter().chain(&self.hold).any(|v| *v > 0.0001)
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-progress mouse gesture in the Edit window.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Gesture {
|
||||
|
||||
@@ -439,14 +439,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn room_tone_menu_labels_are_translated() {
|
||||
for label in ["Room Tone", "Set Room Tone", "Fill Gaps with Room Tone", "Clear Room Tone"] {
|
||||
let translated = super::pt_br::translate(label).expect("room tone menu translation");
|
||||
assert_ne!(translated, label);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanish_catalog_covers_every_menu_label() {
|
||||
for path in include_str!("../../engine/catalog/menus.txt").lines() {
|
||||
|
||||
@@ -158,7 +158,6 @@ pub const AUDIOSUITE: &[(&str, &str)] = &[
|
||||
/// Commands that open a dialog when invoked from a menu (programmatic calls never do).
|
||||
const DIALOG_COMMANDS: &[&str] = &[
|
||||
"clip.clear",
|
||||
"clip.unloop",
|
||||
"track.new",
|
||||
"file.bounce_mix",
|
||||
"session.new",
|
||||
@@ -256,14 +255,6 @@ pub fn tree() -> Vec<MenuNode> {
|
||||
let at = clip.children.iter().position(|n| n.path == "Clip > Identify Sync Point").map_or(clip.children.len(), |i| i + 1);
|
||||
clip.children.insert(at, MenuNode { label: "Remove Sync Point".into(), path: "Clip > Remove Sync Point".into(), children: Vec::new() });
|
||||
}
|
||||
// Not in the incumbent catalog: room tone fills gaps left by edits (and by Strip Silence) with
|
||||
// recorded silence, so it sits right under Strip Silence.
|
||||
if let Some(edit) = roots.iter_mut().find(|n| n.path == "Edit") {
|
||||
let at = edit.children.iter().position(|n| n.path == "Edit > Strip Silence").map_or(edit.children.len(), |i| i + 1);
|
||||
let leaf = |label: &str| MenuNode { label: label.into(), path: format!("Edit > Room Tone > {label}"), children: Vec::new() };
|
||||
let children = vec![leaf("Set Room Tone"), leaf("Fill Gaps with Room Tone"), leaf("Clear Room Tone")];
|
||||
edit.children.insert(at, MenuNode { label: "Room Tone".into(), path: "Edit > Room Tone".into(), children });
|
||||
}
|
||||
// Not in the incumbent catalog, but the only UI path to an empty MIDI clip (#282).
|
||||
// It creates a clip rather than acting on the selected ones, so it leads the Clip menu.
|
||||
insert_path(&mut roots, "Clip > New MIDI Clip");
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::widgets::{
|
||||
use egui::{Align2, Color32, CornerRadius, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use serde_json::json;
|
||||
use soundcraft_model::{ChannelFormat, Route, SurroundPan, Track, TrackId, TrackKind};
|
||||
use soundcraft_playback::MeterSnapshot;
|
||||
|
||||
mod output;
|
||||
mod plugin_menu;
|
||||
@@ -61,6 +62,9 @@ pub fn separate_closed(app: &mut SoundApp) {
|
||||
/// New Tracks when the space past the last strip is double-clicked.
|
||||
pub(crate) fn content(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let ids: Vec<TrackId> = app.engine.session().tracks.iter().filter(|x| !x.hidden && x.kind != TrackKind::Video).map(|x| x.id).collect();
|
||||
// Per-channel peaks for multichannel meters, from the snapshot `logic` takes from the player
|
||||
// (taking them here too would split each period's peaks between two readers).
|
||||
let snap = (app.player.is_some() && app.meters_live()).then(|| app.meter_snapshot.clone());
|
||||
// Taken for this frame only: a strip that isn't drawn (hidden track) must not scroll the Mix
|
||||
// whenever it comes back. A request made during this frame (the strip's menu) waits for the next.
|
||||
let scroll_to = app.mix_scroll_into_view.take();
|
||||
@@ -68,7 +72,7 @@ pub(crate) fn content(app: &mut SoundApp, ui: &mut Ui) {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 1.0;
|
||||
for id in ids {
|
||||
strip(app, ui, id, scroll_to == Some(id));
|
||||
strip(app, ui, id, snap.as_ref(), scroll_to == Some(id));
|
||||
}
|
||||
let rest = Rect::from_min_max(pos2(ui.cursor().min.x, ui.clip_rect().min.y), ui.clip_rect().max);
|
||||
if rest.width() > 4.0 && ui.interact(rest, ui.scope_id().with("past_strips"), Sense::click()).double_clicked() {
|
||||
@@ -108,6 +112,24 @@ fn panner_speakers(fmt: ChannelFormat) -> Vec<PannerSpeaker> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ballistic per-channel meter levels for multichannel strips, kept in egui memory.
|
||||
fn channel_levels(ui: &Ui, key: (&str, u64), peaks: &[f32], n: usize) -> Vec<f32> {
|
||||
let id = egui::Id::unique(key);
|
||||
let dt = ui.input(|i| i.stable_dt).clamp(0.0, 0.25);
|
||||
let fall = 10f32.powf(-26.0 * dt / 20.0);
|
||||
let mut lv: Vec<f32> = ui.data(|d| d.get_temp(id)).unwrap_or_default();
|
||||
lv.resize(n, 0.0);
|
||||
for (i, l) in lv.iter_mut().enumerate() {
|
||||
let p = peaks.get(i).copied().filter(|x| x.is_finite()).unwrap_or(0.0);
|
||||
*l = if p >= *l { p } else { (*l * fall).max(p) };
|
||||
if *l < 1e-5 {
|
||||
*l = 0.0;
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, lv.clone()));
|
||||
lv
|
||||
}
|
||||
|
||||
/// Pro Tools' names for sections in narrow strips, and in any strip too narrow for the full ones.
|
||||
fn short_label(text: &str) -> &str {
|
||||
match text {
|
||||
@@ -164,7 +186,7 @@ impl StripCtx<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, scroll_here: bool) {
|
||||
fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapshot>, scroll_here: bool) {
|
||||
let t = Tokens::current();
|
||||
let session = app.engine.session_arc();
|
||||
let Some(track) = session.track(id) else { return };
|
||||
@@ -200,7 +222,7 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, scroll_here: bool) {
|
||||
y = group_selector(app, ui, &cx, y);
|
||||
y = pan_section(app, ui, &cx, y);
|
||||
y = toggle_rows(app, ui, &cx, y);
|
||||
fader_and_meter(app, ui, &cx, y);
|
||||
fader_and_meter(app, ui, &cx, y, snap);
|
||||
name_and_readout(app, ui, &cx);
|
||||
}
|
||||
|
||||
@@ -582,7 +604,7 @@ fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
|
||||
}
|
||||
|
||||
/// The fader and its meter.
|
||||
fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32) {
|
||||
fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32, snap: Option<&MeterSnapshot>) {
|
||||
let StripCtx { track, id, narrow, x0, inner_w, r, .. } = *cx;
|
||||
let t = Tokens::current();
|
||||
// Fader + meter.
|
||||
@@ -604,10 +626,10 @@ fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32) {
|
||||
let chans = if track.kind == TrackKind::Master { 2 } else { track.channels().min(2) };
|
||||
if all_chans > 2 {
|
||||
// One bar per channel, labelled (L R C LFE …).
|
||||
let peaks = snap.and_then(|s| s.tracks.get(&id)).map(|m| m.peaks.as_slice()).unwrap_or(&[]);
|
||||
let lv = channel_levels(ui, ("mc_meter", id.0), peaks, all_chans);
|
||||
let labels: Vec<String> = (0..all_chans).map(|c| strip_fmt.channel_label(c)).collect();
|
||||
let level = md.level.get(..all_chans).unwrap_or_default();
|
||||
let hold = md.hold.get(..all_chans).unwrap_or_default();
|
||||
multi_meter(ui, mr, level, hold, &labels, md.clip);
|
||||
multi_meter(ui, mr, &lv, &labels, md.clip);
|
||||
} else if chans >= 2 {
|
||||
let mw = mr.width() / 2.0 - 1.0;
|
||||
meter(ui, Rect::from_min_size(mr.min, vec2(mw, mr.height())), md.level[0], md.hold[0], md.clip);
|
||||
|
||||
@@ -50,20 +50,17 @@ pub(crate) fn send_slot(app: &mut SoundApp, ui: &mut Ui, track: &Track, slot: us
|
||||
if level_resp.dragged() {
|
||||
// Use this frame's pointer movement. `Response::drag_delta()` is cumulative, so
|
||||
// applying it to the already-updated value made trackpad adjustment accelerate.
|
||||
// Ctrl (Command on a Mac) gives fine control, as on a fader, and so does Shift.
|
||||
let (dy, fine) = ui.input(|i| (i.pointer.delta().y, i.modifiers.shift || i.modifiers.command || i.modifiers.ctrl));
|
||||
let (dy, fine) = ui.input(|i| (i.pointer.delta().y, i.modifiers.shift));
|
||||
let db = dragged_send_db(s.level_db, dy, fine);
|
||||
app.gesture = Some(crate::Gesture::SendFader { track: id, slot });
|
||||
let _ =
|
||||
app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "db": db}), &format!("send:{}:{slot}", id.0));
|
||||
}
|
||||
let fine_drag = if ui.ctx().os().is_mac() { "⌘-drag" } else { "Ctrl-drag" };
|
||||
let _ = level_resp.clone().on_hover_text(crate::localized_format!(
|
||||
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · {fine_drag} or Shift-drag for fine control · Alt-click for 0 dB · right-click for options",
|
||||
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options",
|
||||
which = which,
|
||||
name = name,
|
||||
db = db_text(s.level_db),
|
||||
fine_drag = fine_drag
|
||||
db = db_text(s.level_db)
|
||||
));
|
||||
level_resp.context_menu(|ui| send_options_menu(app, ui, id, slot, s));
|
||||
}
|
||||
@@ -168,11 +165,8 @@ fn send_window_contents(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
fn send_options_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize, send: &soundcraft_model::SendSlot) {
|
||||
ui.set_min_width(230.0);
|
||||
ui.strong(crate::localized_format!("Send {} · {}", (b'A' + slot as u8) as char, route_name(app, &send.target)));
|
||||
let before = send.level_db.max(-60.0);
|
||||
let mut db = f64::from(before);
|
||||
crate::widgets::FineSlider::new(&mut db, -60.0..=12.0).text(crate::localization::text("Level")).suffix(" dB").show(ui);
|
||||
let db = db as f32;
|
||||
if (db - before).abs() > f32::EPSILON {
|
||||
let mut db = send.level_db.max(-60.0);
|
||||
if ui.add(egui::Slider::new(&mut db, -60.0..=12.0).text(crate::localization::text("Level")).suffix(" dB")).changed() {
|
||||
let _ = app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "db": db}), &format!("send:{}:{slot}", id.0));
|
||||
}
|
||||
send_level_scale(ui, send.level_db);
|
||||
@@ -190,10 +184,8 @@ fn send_options_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId, slot: usize,
|
||||
let _ = app.run("mix.send_level", json!({"track": id.0, "slot": slot, "db": -144.0}));
|
||||
}
|
||||
});
|
||||
let mut pan = f64::from(send.pan);
|
||||
crate::widgets::FineSlider::new(&mut pan, -1.0..=1.0).text(crate::localization::text("Pan")).show(ui);
|
||||
let pan = pan as f32;
|
||||
if (pan - send.pan).abs() > f32::EPSILON {
|
||||
let mut pan = send.pan;
|
||||
if ui.add(egui::Slider::new(&mut pan, -1.0..=1.0).text(crate::localization::text("Pan"))).changed() {
|
||||
let _ = app.engine.execute_merged("mix.send_level", &json!({"track": id.0, "slot": slot, "pan": pan}), &format!("send-pan:{}:{slot}", id.0));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
@@ -402,13 +394,12 @@ fn header_footer_menu<H, R, F>(
|
||||
|
||||
/// What the send menu's footer was used for.
|
||||
enum SendFooter {
|
||||
/// A new bus in this format (`mono` or `stereo`), with the send going to it.
|
||||
NewBus(&'static str),
|
||||
NewBus,
|
||||
RemoveSend,
|
||||
}
|
||||
|
||||
/// The send's destination menu: a title and the bus search on top, the matching buses in a list
|
||||
/// that scrolls, "new mono bus" / "new stereo bus" (and "Remove send" for an existing send) fixed under it.
|
||||
/// that scrolls, "new bus..." (and "Remove send" for an existing send) fixed under it.
|
||||
/// `current` is the send's destination and its name, if the slot has a send.
|
||||
fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: TrackId, slot: usize, current: Option<(Route, String)>) {
|
||||
let which = (b'A' + slot as u8) as char;
|
||||
@@ -454,11 +445,9 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
})
|
||||
},
|
||||
|ui| {
|
||||
for (label, format) in [(crate::localization::text("new mono bus"), "mono"), (crate::localization::text("new stereo bus"), "stereo")] {
|
||||
if ui.button(label).clicked() {
|
||||
ui.close();
|
||||
return Some(SendFooter::NewBus(format));
|
||||
}
|
||||
if ui.button(crate::localization::text("new bus...")).clicked() {
|
||||
ui.close();
|
||||
return Some(SendFooter::NewBus);
|
||||
}
|
||||
if has_send && ui.button(crate::localization::text("Remove send")).clicked() {
|
||||
ui.close();
|
||||
@@ -489,7 +478,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
|
||||
show_new_send(app);
|
||||
}
|
||||
match footer {
|
||||
Some(SendFooter::NewBus(format)) => {
|
||||
Some(SendFooter::NewBus) => {
|
||||
let busses = &app.engine.session().busses;
|
||||
let mut n = busses.len() + 1;
|
||||
while busses.iter().any(|bus| bus.name.eq_ignore_ascii_case(&format!("Bus {n}")))
|
||||
@@ -497,7 +486,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}"), "format": format})).is_ok()
|
||||
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()
|
||||
{
|
||||
show_new_send(app);
|
||||
@@ -516,7 +505,6 @@ mod tests {
|
||||
use crate::Services;
|
||||
use crate::preferences::SendsDefault;
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use soundcraft_model::ChannelFormat;
|
||||
|
||||
/// Filtering the destination list to nothing shrinks the menu; clearing the filter grows it
|
||||
/// back, with the search field in the same place and the footer under the list.
|
||||
@@ -550,7 +538,7 @@ mod tests {
|
||||
let field = |h: &Harness<'_, (SoundApp, TrackId)>| h.get_by_role(egui::accesskit::Role::TextInput).rect();
|
||||
let footer = |h: &Harness<'_, (SoundApp, TrackId)>| h.get_by_label("Remove send").rect();
|
||||
let (search, full) = (field(&h), footer(&h));
|
||||
assert!(h.query_by_label("new stereo bus").is_some(), "the footer offers a new stereo bus");
|
||||
assert!(h.query_by_label("new bus...").is_some(), "the footer lists new bus...");
|
||||
assert!(full.top() > search.bottom() + 150.0, "the list sits between the search and the footer: {search:?} {full:?}");
|
||||
|
||||
h.get_by_role(egui::accesskit::Role::TextInput).type_text("zzzz");
|
||||
@@ -611,7 +599,7 @@ mod tests {
|
||||
assert_eq!(app.ui.send_window, Some((kick, 0)), "the new send's window is open");
|
||||
}
|
||||
|
||||
/// So does a send made with "new stereo bus".
|
||||
/// So does a send made with "new bus...".
|
||||
#[test]
|
||||
fn a_send_to_a_new_bus_opens_its_send_window() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
@@ -619,32 +607,13 @@ mod tests {
|
||||
h.run();
|
||||
h.get_by_label("Send A for Kick").click();
|
||||
h.run();
|
||||
h.get_by_label("new stereo bus").click();
|
||||
h.get_by_label("new bus...").click();
|
||||
h.run();
|
||||
let (app, _) = h.state();
|
||||
assert!(app.engine.session().track(kick).and_then(|t| t.mixer.sends.first().cloned().flatten()).is_some(), "the send was created");
|
||||
assert_eq!(app.ui.send_window, Some((kick, 0)), "the new send's window is open");
|
||||
}
|
||||
|
||||
/// #1388: the send menu asks for mono or stereo, and the new bus has the format picked.
|
||||
#[test]
|
||||
fn a_new_bus_from_the_send_menu_is_mono_or_stereo_as_picked() {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
for (label, format) in [("new mono bus", ChannelFormat::Mono), ("new stereo bus", ChannelFormat::Stereo)] {
|
||||
let (mut h, kick) = kick_send_harness(false);
|
||||
h.run();
|
||||
h.get_by_label("Send A for Kick").click();
|
||||
h.run();
|
||||
h.get_by_label(label).click();
|
||||
h.run();
|
||||
let (app, _) = h.state();
|
||||
let s = app.engine.session();
|
||||
let send = s.track(kick).and_then(|t| t.mixer.sends.first().cloned().flatten()).unwrap();
|
||||
let bus = s.busses.iter().find(|b| Route::Bus(b.id) == send.target).unwrap();
|
||||
assert_eq!(bus.format, format, "{label} makes a bus in that format");
|
||||
}
|
||||
}
|
||||
|
||||
/// Moving an existing send to another bus keeps the Send window as it was.
|
||||
#[test]
|
||||
fn changing_a_sends_destination_leaves_the_send_window_alone() {
|
||||
@@ -684,7 +653,7 @@ mod tests {
|
||||
let _palette = crate::theme::lock_test_palette();
|
||||
assert_eq!(level_after_picking(false, SendsDefault::NegativeInfinity, "Aux"), Some(-144.0));
|
||||
assert_eq!(level_after_picking(false, SendsDefault::Unity, "Aux"), Some(0.0));
|
||||
assert_eq!(level_after_picking(false, SendsDefault::Unity, "new stereo bus"), 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.
|
||||
|
||||
@@ -89,8 +89,6 @@ pub(super) fn plugin_windows(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
x = idx as f32;
|
||||
// An Alt-click (Option-click on a Mac) returns the choice to its
|
||||
// default, as on the sliders, instead of opening the list.
|
||||
if r.response.clicked() && ui.input(|i| i.modifiers.alt) {
|
||||
x = p.default;
|
||||
egui::Popup::close_all(ui.ctx());
|
||||
|
||||
@@ -1013,17 +1013,13 @@ pub fn clip_effects(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.show(col);
|
||||
v = wide as f32;
|
||||
if (v - before).abs() > f32::EPSILON {
|
||||
let gesture = format!("cfx:{}:{key}", cid.0);
|
||||
// An Alt-click that resets the value is its own undo step, even
|
||||
// right after typing in the value box, which keeps the merge open.
|
||||
// During an automation pass the merge holds the pass's key, and the
|
||||
// reset joins the pass's undo step.
|
||||
if col.input(|i| i.modifiers.alt && i.pointer.any_released()) && app.engine.merge_key() == Some(gesture.as_str()) {
|
||||
app.engine.end_merge();
|
||||
}
|
||||
let mut m = serde_json::Map::new();
|
||||
m.insert(key.clone(), json!(v));
|
||||
let _ = app.engine.execute_merged("clip.effects_set", &json!({"clips": [cid.0], "params": m}), &gesture);
|
||||
let _ = app.engine.execute_merged(
|
||||
"clip.effects_set",
|
||||
&json!({"clips": [cid.0], "params": m}),
|
||||
&format!("cfx:{}:{key}", cid.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1037,12 +1033,8 @@ pub fn clip_effects(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
.show(ui);
|
||||
g = wide as f32;
|
||||
if (g - before).abs() > f32::EPSILON {
|
||||
let gesture = format!("cfx:{}:gain", cid.0);
|
||||
// An Alt-click that resets the gain is its own undo step, as on the parameters above.
|
||||
if ui.input(|i| i.modifiers.alt && i.pointer.any_released()) && app.engine.merge_key() == Some(gesture.as_str()) {
|
||||
app.engine.end_merge();
|
||||
}
|
||||
let _ = app.engine.execute_merged("clip.effects_set", &json!({"clips": [cid.0], "params": {"gain": g}}), &gesture);
|
||||
let _ =
|
||||
app.engine.execute_merged("clip.effects_set", &json!({"clips": [cid.0], "params": {"gain": g}}), &format!("cfx:{}:gain", cid.0));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,9 +24,6 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let full = ui.max_rect();
|
||||
ui.painter().rect_filled(full, 0.0, t.toolbar_bg);
|
||||
ui.add_space(4.0);
|
||||
// Solid bar: it takes its own strip under the groups instead of floating over their bottom row.
|
||||
// ponytail: HEIGHT (4 + 64 + the 10 pt bar) is sized for it by hand; taller groups would clip it.
|
||||
ui.spacing_mut().scroll = egui::style::ScrollStyle::solid();
|
||||
egui::ScrollArea::horizontal()
|
||||
.id_salt("edit_toolbar_scroll")
|
||||
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded)
|
||||
@@ -182,9 +179,7 @@ fn zoom_group(app: &mut SoundApp, ui: &mut Ui) {
|
||||
fn tools(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let t = Tokens::current();
|
||||
let cur = app.engine.session().edit.tool;
|
||||
// 7 buttons of 36 + 6 gaps of 2 + the group's 2 x 5 padding: no dead strip on the right (#704).
|
||||
// ponytail: still a hand-counted width, stale if a button is added; upgrade: size the group from its content.
|
||||
group(ui, 7.0 * 36.0 + 6.0 * 2.0 + 10.0, 52.0, |ui, r| {
|
||||
group(ui, 268.0 + 38.0, 52.0, |ui, r| {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(2.0, 3.0);
|
||||
let row = ui.horizontal(|ui| {
|
||||
@@ -588,8 +583,7 @@ fn transport(app: &mut SoundApp, ui: &mut Ui) {
|
||||
let playing = app.is_playing();
|
||||
let recording = app.engine.transport.recording;
|
||||
let looped = app.engine.session().edit.loop_playback;
|
||||
// 4 buttons of 38 + 3 gaps of 3 + the group's 2 x 5 padding (ponytail: hand-counted, as in `tools`).
|
||||
group(ui, 4.0 * 38.0 + 3.0 * 3.0 + 10.0, 64.0, |ui, g| {
|
||||
group(ui, 176.0, 64.0, |ui, g| {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(3.0, 4.0);
|
||||
ui.horizontal(|ui| {
|
||||
|
||||
@@ -333,16 +333,14 @@ pub(crate) fn selector_box_named(ui: &mut Ui, width: f32, height: f32, text: &st
|
||||
resp.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
/// Rotary knob for pan / send pan (-1..1). Drag vertically; double-click resets. While Ctrl
|
||||
/// (Command on a Mac) is held, a drag turns it a tenth as far, as on a [`fader`].
|
||||
/// Rotary knob for pan / send pan (-1..1). Drag vertically; double-click resets.
|
||||
pub fn pan_knob(ui: &mut Ui, size: f32, value: &mut f32, tip: &str) -> Response {
|
||||
let t = Tokens::current();
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), tip));
|
||||
if resp.dragged() {
|
||||
let d = resp.drag_delta();
|
||||
let fine = ui.input(|i| i.modifiers.command || i.modifiers.ctrl);
|
||||
*value = (*value + (d.x - d.y) * if fine { 0.001 } else { 0.01 }).clamp(-1.0, 1.0);
|
||||
*value = (*value + (d.x - d.y) * 0.01).clamp(-1.0, 1.0);
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
*value = 0.0;
|
||||
@@ -550,11 +548,10 @@ struct FineDrag {
|
||||
}
|
||||
|
||||
/// A horizontal slider that moves a tenth as far for the same drag while Ctrl (Command on a Mac)
|
||||
/// is held, as a [`fader`] does, on the rail and on the value box. A press on the rail with the
|
||||
/// key held, and pressing or releasing the key during a drag on the rail or the value box, leave
|
||||
/// the value where it is, and the drag goes on from there. The value box shows the decimal places
|
||||
/// that a tenth of a point's step needs, and a drag on the rail that the key has touched rounds
|
||||
/// the value to them.
|
||||
/// is held, as a [`fader`] does, on the rail and on the value box. Pressing or releasing the key
|
||||
/// during a drag on the rail or the value box leaves the value where it is, and the drag goes on
|
||||
/// from there. The value box shows the decimal places that a tenth of a point's step needs, and a
|
||||
/// drag on the rail that the key has touched rounds the value to them.
|
||||
pub fn fine_slider(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive<f64>, text: &str) -> Response {
|
||||
FineSlider::new(value, range).text(text).show(ui)
|
||||
}
|
||||
@@ -569,18 +566,11 @@ pub struct FineSlider<'a> {
|
||||
logarithmic: bool,
|
||||
integer: bool,
|
||||
default: Option<f64>,
|
||||
suffix: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> FineSlider<'a> {
|
||||
pub fn new(value: &'a mut f64, range: std::ops::RangeInclusive<f64>) -> Self {
|
||||
Self { value, range, text: "", id_salt: None, show_value: true, logarithmic: false, integer: false, default: None, suffix: "" }
|
||||
}
|
||||
|
||||
/// Text after the number in the value box, as `egui::Slider::suffix`.
|
||||
pub fn suffix(mut self, suffix: &'a str) -> Self {
|
||||
self.suffix = suffix;
|
||||
self
|
||||
Self { value, range, text: "", id_salt: None, show_value: true, logarithmic: false, integer: false, default: None }
|
||||
}
|
||||
|
||||
/// The value that an Alt-click (Option-click on a Mac) on the slider or its value box sets,
|
||||
@@ -625,7 +615,7 @@ impl<'a> FineSlider<'a> {
|
||||
}
|
||||
|
||||
pub fn show(self, ui: &mut Ui) -> Response {
|
||||
let Self { value, range, text, id_salt, show_value, logarithmic, integer, default, suffix } = self;
|
||||
let Self { value, range, text, id_salt, show_value, logarithmic, integer, default } = self;
|
||||
let id = ui.scope_id().with(("fine_slider", id_salt.unwrap_or(text)));
|
||||
let before = *value;
|
||||
let (fine, x) = ui.input(|i| (i.modifiers.command || i.modifiers.ctrl, i.pointer.interact_pos().map(|p| p.x)));
|
||||
@@ -654,16 +644,12 @@ impl<'a> FineSlider<'a> {
|
||||
if let (Some(d), Some(x)) = (&mut drag, x) {
|
||||
if d.fine != fine || reset {
|
||||
*d = FineDrag { x, value: *value, fine, relative: true, pass };
|
||||
} else if d.relative && x == d.x {
|
||||
// Until the pointer moves, the value stays at the anchor as it was, unrounded.
|
||||
*value = d.value;
|
||||
} else if d.relative {
|
||||
let moved = at(along(d.value) + f64::from(x - d.x) / travel * scale);
|
||||
let moved = if show_value || integer { egui::emath::round_to_decimals(moved, decimals) } else { moved };
|
||||
*value = moved.clamp(lo, hi);
|
||||
}
|
||||
}
|
||||
let start = *value;
|
||||
let hold = reset || drag.is_some_and(|d| d.relative);
|
||||
let speed = per_point(*value) * scale;
|
||||
let mut slider = egui::Slider::from_get_set(range, |v| {
|
||||
@@ -677,7 +663,6 @@ impl<'a> FineSlider<'a> {
|
||||
.show_value(show_value)
|
||||
.logarithmic(log)
|
||||
.min_decimals(decimals)
|
||||
.suffix(suffix)
|
||||
.text(text);
|
||||
if integer {
|
||||
slider = slider.integer();
|
||||
@@ -704,11 +689,6 @@ impl<'a> FineSlider<'a> {
|
||||
}
|
||||
let rail = Rect::from_min_size(resp.rect.min, vec2(ui.spacing().slider_width, resp.rect.height()));
|
||||
let on_rail = resp.dragged() && ui.input(|i| i.pointer.press_origin()).is_some_and(|p| rail.contains(p));
|
||||
// On the pass that starts a drag, egui has already set the value under the pointer. A drag
|
||||
// that starts with the key held keeps the value from before the press instead.
|
||||
if on_rail && drag.is_none() && fine {
|
||||
*value = start;
|
||||
}
|
||||
let next = match (on_rail, drag, x) {
|
||||
(true, Some(d), _) => Some(FineDrag { pass, ..d }),
|
||||
(true, None, Some(x)) => Some(FineDrag { x, value: *value, fine, relative: fine, pass }),
|
||||
@@ -834,9 +814,8 @@ pub fn surround_panner(ui: &mut Ui, size: f32, speakers: &[PannerSpeaker], puck:
|
||||
edit
|
||||
}
|
||||
|
||||
/// A bank of thin vertical peak meters, one per channel with its peak hold (`holds`, matched by
|
||||
/// index), labelled underneath (rotated text).
|
||||
pub fn multi_meter(ui: &Ui, r: Rect, levels: &[f32], holds: &[f32], labels: &[String], clip: bool) {
|
||||
/// A bank of thin vertical peak meters, one per channel, labelled underneath (rotated text).
|
||||
pub fn multi_meter(ui: &Ui, r: Rect, levels: &[f32], labels: &[String], clip: bool) {
|
||||
let n = levels.len().max(1);
|
||||
let label_h = 16.0;
|
||||
let mr = Rect::from_min_max(r.min, pos2(r.max.x, r.max.y - label_h));
|
||||
@@ -845,7 +824,7 @@ pub fn multi_meter(ui: &Ui, r: Rect, levels: &[f32], holds: &[f32], labels: &[St
|
||||
for (i, lv) in levels.iter().enumerate() {
|
||||
let x = mr.min.x + i as f32 * (w + gap);
|
||||
let br = Rect::from_min_size(pos2(x, mr.min.y), vec2(w, mr.height()));
|
||||
meter(ui, br, *lv, holds.get(i).copied().unwrap_or(*lv), clip);
|
||||
meter(ui, br, *lv, *lv, clip);
|
||||
if let Some(l) = labels.get(i) {
|
||||
let galley = ui.painter().layout_no_wrap(l.clone(), regular(7.0), Tokens::current().text_dim);
|
||||
let gw = galley.size().x;
|
||||
|
||||
@@ -107,22 +107,6 @@ fn new_midi_clip_is_in_the_clip_menu() {
|
||||
assert_eq!(clip.children[0].label, "New MIDI Clip", "creates rather than edits, so it comes first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn room_tone_follows_strip_silence_in_the_edit_menu() {
|
||||
let extra = menus::ui_aliases();
|
||||
for (label, id) in
|
||||
[("Set Room Tone", "edit.room_tone_set"), ("Fill Gaps with Room Tone", "edit.room_tone_fill"), ("Clear Room Tone", "edit.room_tone_clear")]
|
||||
{
|
||||
assert_eq!(catalog::implemented_by(&format!("Edit > Room Tone > {label}"), &extra).as_deref(), Some(id));
|
||||
assert!(menu_commands().contains(id), "{id}");
|
||||
}
|
||||
let tree = menus::tree();
|
||||
let edit = tree.iter().find(|n| n.label == "Edit").unwrap();
|
||||
let labels: Vec<&str> = edit.children.iter().map(|n| n.label.as_str()).collect();
|
||||
let at = labels.iter().position(|l| *l == "Strip Silence").unwrap();
|
||||
assert_eq!(labels.get(at + 1), Some(&"Room Tone"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_sync_point_follows_identify_and_is_greyed_out_without_a_point() {
|
||||
let tree = menus::tree();
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
//! Edit window track-header meters: one bar per channel, and a header column that widens to fit
|
||||
//! the widest meter shown, as Pro Tools draws them.
|
||||
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
use soundcraft_mix::MAX_CHANNELS;
|
||||
use soundcraft_ui_egui::edit_window::{HEADER_W, meter_channels, meter_width, track_header_width};
|
||||
use soundcraft_ui_egui::{Services, SoundApp};
|
||||
|
||||
fn harness(app: SoundApp) -> Harness<'static, SoundApp> {
|
||||
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| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// Where the timeline starts: the left edge of the window plus the header column.
|
||||
fn timeline_x(h: &Harness<'_, SoundApp>) -> f32 {
|
||||
h.state().edit_layout.timeline[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meter_widths_follow_the_channel_count() {
|
||||
// Mono and stereo keep the meter the headers always had.
|
||||
assert_eq!(meter_width(1), meter_width(2));
|
||||
// Every channel past the pair adds a bar.
|
||||
for n in 2..MAX_CHANNELS {
|
||||
assert!(meter_width(n + 1) > meter_width(n), "{n} → {}", n + 1);
|
||||
}
|
||||
// Hostile counts are clamped, not trusted.
|
||||
assert_eq!(meter_width(0), meter_width(1));
|
||||
assert_eq!(meter_width(usize::MAX), meter_width(MAX_CHANNELS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_surround_track_widens_every_header_and_hiding_it_narrows_them_again() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
// The demo session is mono and stereo: the headers keep their usual width.
|
||||
assert_eq!(track_header_width(app.engine.session()), HEADER_W);
|
||||
app.run("track.new", json!({"count": 1, "format": "5.1", "name": "Surround"})).unwrap();
|
||||
app.run("track.new", json!({"count": 1, "format": "7.1", "name": "Wide"})).unwrap();
|
||||
let s = app.engine.session();
|
||||
assert!(meter_channels(s, s.track_by_name("Wide").unwrap()) > meter_channels(s, s.track_by_name("Surround").unwrap()));
|
||||
// The widest meter sets the width, whichever track it is on.
|
||||
assert_eq!(track_header_width(s), HEADER_W + meter_width(8) - meter_width(2));
|
||||
|
||||
let mut h = harness(app);
|
||||
let widest = timeline_x(&h);
|
||||
// Hiding the 7.1 track falls back to the next widest meter shown, not to the stereo width.
|
||||
h.state_mut().run("track.hide", json!({"tracks": ["Wide"], "hidden": true})).unwrap();
|
||||
h.run_steps(4);
|
||||
let surround = timeline_x(&h);
|
||||
assert_eq!(widest - surround, meter_width(8) - meter_width(6), "the timeline moves by the 7.1 meter's extra width");
|
||||
assert_eq!(track_header_width(h.state().engine.session()), HEADER_W + meter_width(6) - meter_width(2));
|
||||
// Hiding the 5.1 track too brings the headers back to their usual width.
|
||||
h.state_mut().run("track.hide", json!({"tracks": ["Surround"], "hidden": true})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(timeline_x(&h) < surround);
|
||||
assert_eq!(track_header_width(h.state().engine.session()), HEADER_W);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_master_meter_has_one_bar_per_main_output_channel() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
app.run("track.new", json!({"count": 1, "kind": "master", "name": "Main"})).unwrap();
|
||||
app.run("setup.main_format", json!({"format": "5.1"})).unwrap();
|
||||
// The master meter reads the main output, even when the master track's own format lags.
|
||||
let master = app.engine.session().track_by_name("Main").unwrap().id;
|
||||
app.engine.session_mut().track_mut(master).unwrap().format = soundcraft_model::ChannelFormat::Stereo;
|
||||
let s = app.engine.session();
|
||||
assert_eq!(meter_channels(s, s.track(master).unwrap()), 6);
|
||||
}
|
||||
@@ -20,7 +20,6 @@ mod edit_modes;
|
||||
mod edit_window_headers;
|
||||
mod focused_dialog_buttons;
|
||||
mod group_dialog;
|
||||
mod header_meters;
|
||||
mod hide_floating;
|
||||
mod idle;
|
||||
mod import_browse;
|
||||
@@ -50,7 +49,6 @@ mod sampler_window;
|
||||
mod save_as_replace;
|
||||
mod save_changes;
|
||||
mod scroll_into_view;
|
||||
mod send_fine_adjustment;
|
||||
mod send_window;
|
||||
mod session_view_focus;
|
||||
mod shared_controls;
|
||||
@@ -62,7 +60,6 @@ mod strip_silence_rectangles;
|
||||
mod strip_silence_rename;
|
||||
mod strip_silence_sliders;
|
||||
mod sub_counter;
|
||||
mod toolbar_fit;
|
||||
mod toolbar_scroll;
|
||||
mod toolbar_tempo;
|
||||
mod track_height;
|
||||
@@ -71,7 +68,6 @@ mod track_name_menu;
|
||||
mod track_preset_state;
|
||||
mod trackpad;
|
||||
mod tracks_scroll_bar;
|
||||
mod unloop_dialog;
|
||||
mod waveform;
|
||||
mod window_shortcuts;
|
||||
mod zoom_toggle;
|
||||
|
||||
@@ -263,120 +263,6 @@ fn alt_click_returns_clip_effects_sliders_and_value_boxes_to_their_defaults() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Alt-click on a clip effects value box that is open for typing is an undo step of its own:
|
||||
/// one undo brings back the typed value, not the value from before the typing.
|
||||
#[test]
|
||||
fn alt_click_after_typing_in_a_clip_effects_value_box_is_its_own_undo_step() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let s = app.engine.session();
|
||||
let clip = s.track_by_name("Kick").unwrap().clips().iter().find(|c| c.is_audio()).unwrap().id;
|
||||
app.run("edit.select", json!({"clips": [clip.0]})).unwrap();
|
||||
app.run("clip.effects_set", json!({"clips": [clip.0], "params": {"comp.threshold": -6.0}})).unwrap();
|
||||
app.engine.end_merge();
|
||||
app.ui.show_clip_effects = true;
|
||||
let mut h = harness(app);
|
||||
let p = param("compressor", "threshold");
|
||||
let key = format!("clip_fx.{}.comp.threshold", clip.0);
|
||||
let read = |h: &Harness<'_, SoundApp>| h.state().engine.session().edit.values.get(&key).copied();
|
||||
let rail = h.get_by_role_and_label(Role::Slider, "Threshold").rect();
|
||||
let at = h
|
||||
.query_all_by_role(Role::SpinButton)
|
||||
.map(|n| n.rect())
|
||||
.find(|r| r.left() > rail.right() && (r.center().y - rail.center().y).abs() < 4.0)
|
||||
.unwrap()
|
||||
.center();
|
||||
move_to(&mut h, at);
|
||||
press(&mut h, at, true, Modifiers::NONE);
|
||||
press(&mut h, at, false, Modifiers::NONE);
|
||||
h.run_steps(2);
|
||||
assert!(h.ctx.egui_wants_keyboard_input(), "a plain click did not open Threshold's value box for typing");
|
||||
let steps = undo_steps(&h);
|
||||
h.event(Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
|
||||
h.event(Event::Text("-12".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(read(&h), Some(-12.0), "typing did not set Threshold");
|
||||
alt_press(&mut h, at, 0.0);
|
||||
assert_eq!(read(&h), Some(f64::from(p.default)), "Alt-click did not return Threshold to its default");
|
||||
assert_eq!(undo_steps(&h), steps + 2, "the typed value and the Alt-click are not two undo steps");
|
||||
h.state_mut().engine.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(read(&h), Some(-12.0), "Undo did not bring back the typed value");
|
||||
}
|
||||
|
||||
/// The gain's value box behaves as the parameters' value boxes do: one undo after an Alt-click
|
||||
/// brings back the typed gain.
|
||||
#[test]
|
||||
fn alt_click_after_typing_in_the_clip_effects_gain_box_is_its_own_undo_step() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let clip = app.engine.session().track_by_name("Kick").unwrap().clips().iter().find(|c| c.is_audio()).unwrap().id;
|
||||
app.run("edit.select", json!({"clips": [clip.0]})).unwrap();
|
||||
app.run("clip.effects_set", json!({"clips": [clip.0], "params": {"gain": 6.0}})).unwrap();
|
||||
app.engine.end_merge();
|
||||
app.ui.show_clip_effects = true;
|
||||
let mut h = harness(app);
|
||||
let key = format!("clip_fx.{}.gain", clip.0);
|
||||
let read = |h: &Harness<'_, SoundApp>| h.state().engine.session().edit.values.get(&key).copied();
|
||||
let input = h.get_by_role_and_label(Role::Slider, "Input").rect();
|
||||
move_to(&mut h, input.center());
|
||||
h.event(Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -2000.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
});
|
||||
h.run_steps(30);
|
||||
let rail = h.get_by_role_and_label(Role::Slider, "Clip effects gain (dB)").rect();
|
||||
let at = h
|
||||
.query_all_by_role(Role::SpinButton)
|
||||
.map(|n| n.rect())
|
||||
.find(|r| r.left() > rail.right() && (r.center().y - rail.center().y).abs() < 4.0)
|
||||
.unwrap()
|
||||
.center();
|
||||
move_to(&mut h, at);
|
||||
press(&mut h, at, true, Modifiers::NONE);
|
||||
press(&mut h, at, false, Modifiers::NONE);
|
||||
h.run_steps(2);
|
||||
assert!(h.ctx.egui_wants_keyboard_input(), "a plain click did not open the gain's value box for typing");
|
||||
let steps = undo_steps(&h);
|
||||
h.event(Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
|
||||
h.event(Event::Text("-12".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(read(&h), Some(-12.0), "typing did not set the gain");
|
||||
alt_press(&mut h, at, 0.0);
|
||||
assert_eq!(read(&h), Some(0.0), "Alt-click did not return the gain to 0 dB");
|
||||
assert_eq!(undo_steps(&h), steps + 2, "the typed value and the Alt-click are not two undo steps");
|
||||
h.state_mut().engine.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(read(&h), Some(-12.0), "Undo did not bring back the typed gain");
|
||||
}
|
||||
|
||||
/// An Alt-click on a clip effects slider during an automation pass joins the pass's undo step:
|
||||
/// the automation written before and after the reset, and the reset, undo together.
|
||||
#[test]
|
||||
fn alt_click_on_a_clip_effects_slider_during_an_automation_pass_keeps_the_pass_one_undo_step() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let s = app.engine.session();
|
||||
let clip = s.track_by_name("Kick").unwrap().clips().iter().find(|c| c.is_audio()).unwrap().id;
|
||||
app.run("edit.select", json!({"clips": [clip.0]})).unwrap();
|
||||
app.run("clip.effects_set", json!({"clips": [clip.0], "params": {"eq.input_gain": 6.0}})).unwrap();
|
||||
app.engine.end_merge();
|
||||
app.run("mix.automation_mode", json!({"tracks": ["Kick"], "mode": "write"})).unwrap();
|
||||
app.ui.show_clip_effects = true;
|
||||
let mut h = harness(app);
|
||||
let p = param("eq_7band", "input_gain");
|
||||
let key = format!("clip_fx.{}.eq.input_gain", clip.0);
|
||||
let rail = h.get_by_role_and_label(Role::Slider, "Input").rect();
|
||||
let steps = undo_steps(&h);
|
||||
h.state_mut().run("transport.play", json!({})).unwrap();
|
||||
h.run_steps(10);
|
||||
assert_eq!(undo_steps(&h), steps + 1, "the pass did not write automation");
|
||||
alt_press(&mut h, near_left(rail), 0.0);
|
||||
assert_eq!(h.state().engine.session().edit.values.get(&key).copied(), Some(f64::from(p.default)), "Alt-click did not reset Input");
|
||||
h.run_steps(10);
|
||||
h.state_mut().run("transport.stop", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_eq!(undo_steps(&h), steps + 1, "the Alt-click split the automation pass into two undo steps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_audiosuite_sliders_reset_with_alt_click() {
|
||||
for (process, label, id, default) in [
|
||||
|
||||
@@ -186,19 +186,17 @@ fn pressing_and_releasing_ctrl_during_a_drag_keeps_a_whole_number_slider_whole()
|
||||
fn a_small_ctrl_drag_at_the_low_end_of_a_log_slider_moves_the_value() {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let kick = app.engine.session().track_by_name("Kick").unwrap().id;
|
||||
let attack = slider_params("compressor")[2];
|
||||
assert_eq!(attack.id, "attack");
|
||||
app.run("mix.insert_param", json!({"track": kick.0, "slot": 1, "param": "attack", "value": attack.min})).unwrap();
|
||||
app.engine.end_merge();
|
||||
app.ui.plugin_windows = vec![(kick, 1)];
|
||||
let mut h = harness(app);
|
||||
let rails = window_sliders(&h, Id::unique(("plugin", kick.0, 1usize)));
|
||||
let attack = slider_params("compressor")[2];
|
||||
assert_eq!(attack.id, "attack");
|
||||
let from = rails[2].left_center() + vec2(1.0, 0.0);
|
||||
hold(&mut h, Modifiers::COMMAND);
|
||||
move_to(&mut h, from);
|
||||
press(&mut h, from, true, Modifiers::COMMAND);
|
||||
let start = insert_param(&h, kick, 1, attack);
|
||||
assert_eq!(start, f64::from(attack.min), "the press moved Attack from its lowest value");
|
||||
assert_eq!(start, f64::from(attack.min), "the press did not put Attack at its lowest value");
|
||||
move_to(&mut h, from + vec2(1.0, 0.0));
|
||||
let moved = insert_param(&h, kick, 1, attack);
|
||||
press(&mut h, from + vec2(1.0, 0.0), false, Modifiers::COMMAND);
|
||||
@@ -211,12 +209,10 @@ fn a_small_ctrl_drag_at_the_low_end_of_a_log_slider_with_a_value_box_moves_the_v
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let clip = app.engine.session().track_by_name("Kick").unwrap().clips().iter().find(|c| c.is_audio()).unwrap().id;
|
||||
app.run("edit.select", json!({"clips": [clip.0]})).unwrap();
|
||||
let attack = slider_params("compressor")[2];
|
||||
assert_eq!(attack.id, "attack");
|
||||
app.run("clip.effects_set", json!({"clips": [clip.0], "params": {"comp.attack": attack.min}})).unwrap();
|
||||
app.engine.end_merge();
|
||||
app.ui.show_clip_effects = true;
|
||||
let mut h = harness(app);
|
||||
let attack = slider_params("compressor")[2];
|
||||
assert_eq!(attack.id, "attack");
|
||||
let key = format!("clip_fx.{}.comp.attack", clip.0);
|
||||
let from = h.get_by_role_and_label(Role::Slider, attack.name).rect().left_center() + vec2(1.0, 0.0);
|
||||
hold(&mut h, Modifiers::COMMAND);
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
//! Fine adjustment of a send: Ctrl (Command on a Mac) makes a drag on a send's level, on the
|
||||
//! Level and Pan sliders of its options menu, and on the pan knobs move the value a fraction as far.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use soundcraft_model::SendSlot;
|
||||
use soundcraft_ui_egui::{MainWindow, Services, SoundApp};
|
||||
|
||||
fn harness() -> Harness<'static, SoundApp> {
|
||||
let mut engine = soundcraft_engine::Engine::default();
|
||||
engine.execute("track.new", &json!({"name": "Vox"})).unwrap();
|
||||
let vox = engine.session().tracks[0].id;
|
||||
engine.execute("mix.new_bus", &json!({"name": "Verb"})).unwrap();
|
||||
engine.execute("mix.send", &json!({"track": vox.0, "slot": 0, "bus": "Verb", "level_db": -10.0})).unwrap();
|
||||
let mut app = SoundApp::new(engine, None, Services::default());
|
||||
app.ui.window = MainWindow::Mix;
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(soundcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1400.0, 900.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn send(h: &Harness<SoundApp>) -> SendSlot {
|
||||
h.state().engine.session().tracks[0].mixer.sends[0].clone().unwrap()
|
||||
}
|
||||
|
||||
/// Puts the send back at -10 dB and centered, so that every drag starts from the same place.
|
||||
fn reset(h: &mut Harness<SoundApp>) {
|
||||
let vox = h.state().engine.session().tracks[0].id;
|
||||
h.state_mut().engine.execute("mix.send_level", &json!({"track": vox.0, "slot": 0, "db": -10.0, "pan": 0.0})).unwrap();
|
||||
h.state_mut().engine.execute("mix.pan", &json!({"track": vox.0, "pan": 0.0})).unwrap();
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn hold(h: &mut Harness<SoundApp>, modifiers: Modifiers) {
|
||||
h.event(Event::ModifiersChanged(modifiers));
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn press(h: &mut Harness<SoundApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers });
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn move_to(h: &mut Harness<SoundApp>, pos: Pos2) {
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
/// Presses `from` and drags by `by` in eight steps with `modifiers` held; returns how far `read`
|
||||
/// moved from where the press left it.
|
||||
fn drag(h: &mut Harness<SoundApp>, from: Pos2, by: egui::Vec2, modifiers: Modifiers, read: fn(&Harness<SoundApp>) -> f32) -> f32 {
|
||||
reset(h);
|
||||
hold(h, modifiers);
|
||||
move_to(h, from);
|
||||
press(h, from, true, modifiers);
|
||||
let start = read(h);
|
||||
for i in 1..=8 {
|
||||
move_to(h, from + by * (i as f32 / 8.0));
|
||||
}
|
||||
press(h, from + by, false, modifiers);
|
||||
hold(h, Modifiers::NONE);
|
||||
read(h) - start
|
||||
}
|
||||
|
||||
fn level(h: &Harness<SoundApp>) -> f32 {
|
||||
send(h).level_db
|
||||
}
|
||||
|
||||
fn pan(h: &Harness<SoundApp>) -> f32 {
|
||||
send(h).pan
|
||||
}
|
||||
|
||||
/// A vertical drag on a send's level moves it as little with Ctrl or Command held as with Shift.
|
||||
#[test]
|
||||
fn ctrl_dragging_a_sends_level_is_as_fine_as_shift_dragging_it() {
|
||||
let mut h = harness();
|
||||
let at = h.get_by_label("Send A level for Vox").rect().center();
|
||||
let by = vec2(0.0, -40.0);
|
||||
let plain = drag(&mut h, at, by, Modifiers::NONE, level);
|
||||
let shift = drag(&mut h, at, by, Modifiers::SHIFT, level);
|
||||
assert!(plain > 0.0, "a plain drag did not raise the send");
|
||||
assert!(shift > 0.0 && shift < plain * 0.2, "Shift-drag moved {shift} dB, a plain drag {plain} dB");
|
||||
for (name, modifiers) in [("Ctrl", Modifiers::CTRL), ("Command", Modifiers::COMMAND)] {
|
||||
let fine = drag(&mut h, at, by, modifiers, level);
|
||||
assert!((fine - shift).abs() < 1e-4, "{name}-drag moved {fine} dB, a Shift-drag {shift} dB");
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the send's options menu with a right-click on its level.
|
||||
fn options_menu(h: &mut Harness<SoundApp>) {
|
||||
let at = h.get_by_label("Send A level for Vox").rect().center();
|
||||
h.hover_at(at);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE });
|
||||
}
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_role_and_label(Role::CheckBox, "Pre-fader").is_some(), "the send's options menu is open");
|
||||
}
|
||||
|
||||
/// The Level and Pan sliders of a send's options menu move a tenth as far while Ctrl or Command is held.
|
||||
#[test]
|
||||
fn the_send_options_sliders_move_a_tenth_as_far_with_ctrl_held() {
|
||||
let mut h = harness();
|
||||
options_menu(&mut h);
|
||||
let read: [(&str, fn(&Harness<SoundApp>) -> f32); 2] = [("Level", level), ("Pan", pan)];
|
||||
for (label, read) in read {
|
||||
let rail = h.get_by_role_and_label(Role::Slider, label).rect().center();
|
||||
let plain = drag(&mut h, rail, vec2(30.0, 0.0), Modifiers::NONE, read);
|
||||
let fine = drag(&mut h, rail, vec2(30.0, 0.0), Modifiers::COMMAND, read);
|
||||
assert!(plain > 0.0, "{label}: a plain drag did not move the value");
|
||||
let ratio = fine / plain;
|
||||
assert!((0.08..=0.12).contains(&ratio), "{label}: Ctrl-drag moved {fine}, a plain drag {plain}");
|
||||
assert!(h.query_by_role_and_label(Role::CheckBox, "Pre-fader").is_some(), "{label}: the drags closed the menu");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Ctrl or Command press on the Level or Pan rail of a send's options menu leaves the value
|
||||
/// where it is, where a plain press sets the value under the pointer.
|
||||
#[test]
|
||||
fn a_ctrl_press_on_a_send_options_rail_leaves_the_value_where_it_is() {
|
||||
let mut h = harness();
|
||||
options_menu(&mut h);
|
||||
let read: [(&str, fn(&Harness<SoundApp>) -> f32); 2] = [("Level", level), ("Pan", pan)];
|
||||
for (label, read) in read {
|
||||
let at = h.get_by_role_and_label(Role::Slider, label).rect().left_center() + vec2(4.0, 0.0);
|
||||
for (name, modifiers) in [("plain", Modifiers::NONE), ("Ctrl", Modifiers::CTRL), ("Command", Modifiers::COMMAND)] {
|
||||
reset(&mut h);
|
||||
let start = read(&h);
|
||||
hold(&mut h, modifiers);
|
||||
move_to(&mut h, at);
|
||||
press(&mut h, at, true, modifiers);
|
||||
let moved = read(&h) - start;
|
||||
// Move on before the release, so that the press ends as a drag that leaves the menu open.
|
||||
for i in 1..=4 {
|
||||
move_to(&mut h, at + vec2(2.0 * i as f32, 0.0));
|
||||
}
|
||||
press(&mut h, at + vec2(8.0, 0.0), false, modifiers);
|
||||
hold(&mut h, Modifiers::NONE);
|
||||
assert!(h.query_by_role_and_label(Role::CheckBox, "Pre-fader").is_some(), "{label}: the {name} drag closed the menu");
|
||||
if modifiers.is_none() {
|
||||
assert!(moved.abs() > 0.5, "{label}: a plain press near the rail's left end moved the value by {moved}");
|
||||
} else {
|
||||
assert!(moved.abs() < 1e-4, "{label}: a {name} press moved the value by {moved}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Ctrl or Command press and release on the Level or Pan rail of a send's options menu, with
|
||||
/// the pointer kept still, leaves a value with more decimal places than the value box shows as it
|
||||
/// is.
|
||||
#[test]
|
||||
fn a_ctrl_press_without_a_move_keeps_an_unrounded_send_value() {
|
||||
let mut h = harness();
|
||||
options_menu(&mut h);
|
||||
let vox = h.state().engine.session().tracks[0].id;
|
||||
let read: [(&str, fn(&Harness<SoundApp>) -> f32); 2] = [("Level", level), ("Pan", pan)];
|
||||
for (label, read) in read {
|
||||
let at = h.get_by_role_and_label(Role::Slider, label).rect().center();
|
||||
for (name, modifiers) in [("Ctrl", Modifiers::CTRL), ("Command", Modifiers::COMMAND)] {
|
||||
h.state_mut().engine.execute("mix.send_level", &json!({"track": vox.0, "slot": 0, "db": -10.123456, "pan": 0.1234564})).unwrap();
|
||||
h.run_steps(2);
|
||||
let start = read(&h);
|
||||
hold(&mut h, modifiers);
|
||||
move_to(&mut h, at);
|
||||
press(&mut h, at, true, modifiers);
|
||||
hold(&mut h, modifiers);
|
||||
press(&mut h, at, false, modifiers);
|
||||
hold(&mut h, Modifiers::NONE);
|
||||
assert_eq!(read(&h), start, "{label}: a {name} press and release without a move changed the value");
|
||||
if h.query_by_role_and_label(Role::CheckBox, "Pre-fader").is_none() {
|
||||
options_menu(&mut h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn track_pan(h: &Harness<SoundApp>) -> f32 {
|
||||
h.state().engine.session().tracks[0].mixer.pan[0]
|
||||
}
|
||||
|
||||
/// The Send window's pan knob, and a track's pan knob, which is the same widget, turn a tenth as
|
||||
/// far while Ctrl or Command is held.
|
||||
#[test]
|
||||
fn pan_knobs_turn_a_tenth_as_far_with_ctrl_held() {
|
||||
let mut h = harness();
|
||||
h.get_by_label("Send A level for Vox").click();
|
||||
h.run_steps(3);
|
||||
let knobs: [(&str, fn(&Harness<SoundApp>) -> f32); 2] =
|
||||
[("Send pan (drag; double-click centres)", pan), ("Pan (drag; double-click centres)", track_pan)];
|
||||
for (label, read) in knobs {
|
||||
let at = h.get_by_role_and_label(Role::Slider, label).rect().center();
|
||||
let plain = drag(&mut h, at, vec2(0.0, -30.0), Modifiers::NONE, read);
|
||||
for (name, modifiers) in [("Ctrl", Modifiers::CTRL), ("Command", Modifiers::COMMAND)] {
|
||||
let fine = drag(&mut h, at, vec2(0.0, -30.0), modifiers, read);
|
||||
assert!(plain > 0.0, "{label}: a plain drag did not turn the knob");
|
||||
let ratio = fine / plain;
|
||||
assert!((0.08..=0.12).contains(&ratio), "{label}: {name}-drag turned it {fine}, a plain drag {plain}");
|
||||
}
|
||||
}
|
||||
assert!(h.state().ui.send_window.is_some(), "the drags closed the Send window");
|
||||
}
|
||||
|
||||
/// The Level value box of a send's options menu still shows its value in dB.
|
||||
#[test]
|
||||
fn the_send_options_level_box_shows_db() {
|
||||
let mut h = harness();
|
||||
options_menu(&mut h);
|
||||
let shown = h.get_by_role_and_label(Role::SpinButton, "Level").value().unwrap_or_default();
|
||||
assert!(shown.starts_with("-10") && shown.ends_with(" dB"), "the Level box shows {shown:?}");
|
||||
}
|
||||
@@ -98,8 +98,8 @@ fn ctrl_dragging_the_value_box_moves_a_tenth_as_far_too() {
|
||||
|
||||
#[test]
|
||||
fn ctrl_without_command_moves_a_tenth_as_far() {
|
||||
let mut h = strip_silence_dialog();
|
||||
for (role, dx, within) in [(Role::Slider, 30.0, 0.08..=0.12), (Role::SpinButton, 20.0, 0.07..=0.13)] {
|
||||
let mut h = strip_silence_dialog();
|
||||
let label = "Threshold dB";
|
||||
let plain = drag_on(&mut h, role, label, dx, Modifiers::NONE);
|
||||
let fine = drag_on(&mut h, role, label, dx, Modifiers::CTRL);
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
//! The Edit toolbar fits a default 13-inch MacBook window (#704), and in a narrower window its scroll
|
||||
//! bar sits under the controls instead of over them.
|
||||
|
||||
use egui::{Rect, Shape, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, theme::Tokens, toolbar};
|
||||
|
||||
/// What the toolbar painted: its panel, the group backgrounds, anything wide and thin (a scroll bar) and everything
|
||||
/// else it holds (the groups and what is not in one, such as the output meter).
|
||||
struct Painted {
|
||||
#[cfg_attr(not(target_os = "macos"), expect(dead_code, reason = "read by the macOS-only fit test"))]
|
||||
panel: Rect,
|
||||
groups: Vec<Rect>,
|
||||
bars: Vec<Rect>,
|
||||
content: Vec<Rect>,
|
||||
right: f32,
|
||||
}
|
||||
|
||||
fn paint(width: f32) -> Painted {
|
||||
let app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let mut harness =
|
||||
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(width, 956.0)).build_ui_state(
|
||||
|ui, app: &mut SoundApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..8 {
|
||||
harness.step();
|
||||
}
|
||||
// A floating scroll bar only appears under the pointer; this one is over the toolbar's lower row.
|
||||
harness.hover_at(pos2(width / 2.0, 100.0));
|
||||
for _ in 0..8 {
|
||||
harness.step();
|
||||
}
|
||||
let t = Tokens::current();
|
||||
let output = harness.output();
|
||||
let panel = output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
// The panel is painted twice, one pixel apart in height.
|
||||
Shape::Rect(r) if r.fill == t.toolbar_bg && (toolbar::HEIGHT - 2.0..=toolbar::HEIGHT).contains(&r.rect.height()) => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the toolbar panel is painted");
|
||||
let mut painted = Painted { panel, groups: vec![], bars: vec![], content: vec![], right: 0.0 };
|
||||
for s in &output.shapes {
|
||||
let r = s.shape.visual_bounding_rect();
|
||||
// Skip shapes outside the toolbar and the panel itself, but keep a full-width scroll bar track.
|
||||
let full_width = r.width() >= panel.width() - 1.0;
|
||||
if r.min.y < panel.min.y - 1.0 || r.max.y > panel.min.y + toolbar::HEIGHT + 1.0 || (full_width && r.height() >= toolbar::HEIGHT - 2.0) {
|
||||
continue;
|
||||
}
|
||||
// Full-width shapes (borders, a scroll bar track) span the window: they say nothing about the content's reach.
|
||||
if !full_width {
|
||||
painted.right = painted.right.max(r.max.x);
|
||||
}
|
||||
let is_bar = r.height() < 16.0 && r.width() > panel.width() / 2.0;
|
||||
if !full_width && !is_bar {
|
||||
painted.content.push(r);
|
||||
}
|
||||
if let Shape::Rect(rs) = &s.shape {
|
||||
if rs.fill == t.toolbar_group || rs.fill == t.counter_bg {
|
||||
painted.groups.push(r);
|
||||
} else if is_bar {
|
||||
painted.bars.push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
painted
|
||||
}
|
||||
|
||||
/// The window of #704 is a Mac's, and the toolbar is drawn there in the Mac's UI font (Helvetica Neue). Other systems
|
||||
/// draw it in their own, wider on Linux (DejaVu Sans), where it may scroll at this width: the narrow-window test covers
|
||||
/// that on every system.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn every_section_fits_a_1470_point_window_without_a_scroll_bar() {
|
||||
let p = paint(1470.0);
|
||||
assert!(p.groups.len() >= 7, "toolbar groups painted: {}", p.groups.len());
|
||||
assert!(p.bars.is_empty(), "scroll bar at 1470 pt: {:?}", p.bars);
|
||||
assert!(p.right <= p.panel.max.x, "toolbar content reaches x = {} in a {} pt window", p.right, p.panel.max.x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scroll_bar_in_a_narrow_window_does_not_cover_the_controls() {
|
||||
let p = paint(1280.0);
|
||||
assert!(!p.bars.is_empty(), "the toolbar no longer overflows at 1280 pt: this test needs a narrower window");
|
||||
for bar in &p.bars {
|
||||
for c in &p.content {
|
||||
assert!(!c.shrink(0.5).intersects(*bar), "scroll bar {bar:?} covers the content {c:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, vec2};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use serde_json::json;
|
||||
use soundcraft_model::TrackId;
|
||||
use soundcraft_ui_egui::{Services, SoundApp, menus};
|
||||
|
||||
/// Loops the Snare clip three times and selects it.
|
||||
fn looped_app() -> (SoundApp, TrackId, usize) {
|
||||
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
|
||||
let track = app.engine.session().track_by_name("Snare").unwrap().id;
|
||||
let clip = app.engine.session().track(track).unwrap().clips()[0].id;
|
||||
app.run("clip.loop", json!({"clip": clip.0, "count": 3})).unwrap();
|
||||
app.run("edit.select", json!({"clips": [clip.0]})).unwrap();
|
||||
let looped = app.engine.session().track(track).unwrap().clips().len();
|
||||
(app, track, looped)
|
||||
}
|
||||
|
||||
/// Loops the Snare clip three times, selects it and opens Clip > Unloop... from the menu.
|
||||
fn unloop_app() -> (SoundApp, TrackId, usize) {
|
||||
let (mut app, track, looped) = looped_app();
|
||||
menus::invoke_menu(&mut app, "clip.unloop", "Clip > Unloop...");
|
||||
assert_eq!(app.dialogs.open_name(), Some("unloop"));
|
||||
(app, track, looped)
|
||||
}
|
||||
|
||||
/// `unloop_app` in a test harness.
|
||||
fn unloop_dialog() -> (Harness<'static, SoundApp>, TrackId, usize) {
|
||||
let (app, track, looped) = unloop_app();
|
||||
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| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
(h, track, looped)
|
||||
}
|
||||
|
||||
fn clips(h: &Harness<'_, SoundApp>, track: TrackId) -> Vec<Option<u64>> {
|
||||
loop_ids(h.state(), track)
|
||||
}
|
||||
|
||||
/// The loop id of each clip on `track`.
|
||||
fn loop_ids(app: &SoundApp, track: TrackId) -> Vec<Option<u64>> {
|
||||
app.engine.session().track(track).map(|t| t.clips().iter().map(|c| c.loop_id).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unloop_dialogs_flatten_keeps_each_iteration_as_its_own_clip() {
|
||||
let (mut h, track, looped) = unloop_dialog();
|
||||
assert_eq!(clips(&h, track).len(), looped, "opening the dialog does not unloop yet");
|
||||
h.get_by_role_and_label(Role::Button, "Flatten").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialogs.open_name(), None);
|
||||
assert_eq!(clips(&h, track), vec![None; looped]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_on_a_focused_flatten_flattens() {
|
||||
let (mut h, track, looped) = unloop_dialog();
|
||||
h.get_by_role_and_label(Role::Button, "Flatten").focus();
|
||||
h.run_steps(2);
|
||||
h.event(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialogs.open_name(), None);
|
||||
assert_eq!(clips(&h, track), vec![None; looped]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_with_no_button_focused_removes() {
|
||||
let (mut h, track, looped) = unloop_dialog();
|
||||
h.event(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialogs.open_name(), None);
|
||||
assert_eq!(clips(&h, track).len(), looped - 2, "Enter presses Remove, which keeps only the source clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_on_a_focused_cancel_leaves_the_loop() {
|
||||
let (mut h, track, _) = unloop_dialog();
|
||||
let before = clips(&h, track);
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").focus();
|
||||
h.run_steps(2);
|
||||
h.event(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialogs.open_name(), None);
|
||||
assert_eq!(clips(&h, track), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flatten_click_with_enter_in_the_same_frame_flattens() {
|
||||
let (h, _, _) = unloop_dialog();
|
||||
let pos = h.get_by_role_and_label(Role::Button, "Flatten").rect().center();
|
||||
// The harness sends a pointer release and a key press in separate frames, so the frames are run by hand.
|
||||
let (mut app, track, looped) = unloop_app();
|
||||
let ctx = egui::Context::default();
|
||||
soundcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let button = |pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
for _ in 0..3 {
|
||||
run_frame(&ctx, &mut app, vec![]);
|
||||
}
|
||||
run_frame(&ctx, &mut app, vec![Event::PointerMoved(pos)]);
|
||||
run_frame(&ctx, &mut app, vec![button(true)]);
|
||||
run_frame(&ctx, &mut app, vec![button(false), enter_key(false)]);
|
||||
assert_eq!(app.dialogs.open_name(), None);
|
||||
assert_eq!(loop_ids(&app, track), vec![None; looped]);
|
||||
}
|
||||
|
||||
/// Runs one frame of `app` with `events`.
|
||||
fn run_frame(ctx: &egui::Context, app: &mut SoundApp, events: Vec<Event>) {
|
||||
let raw = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0))), events, ..Default::default() };
|
||||
ctx.run_ui(raw, |ui| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
}
|
||||
|
||||
fn enter_key(repeat: bool) -> Event {
|
||||
Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn enter_up() -> Event {
|
||||
Event::Key { key: Key::Enter, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unloop_dialog_that_replaces_an_open_dialog_ignores_the_enter_of_its_first_frame() {
|
||||
let (mut app, track, looped) = looped_app();
|
||||
let before = loop_ids(&app, track);
|
||||
let ctx = egui::Context::default();
|
||||
soundcraft_ui_egui::framework::install_headless(&ctx);
|
||||
menus::invoke_menu(&mut app, "setup.session", "Setup > Session");
|
||||
run_frame(&ctx, &mut app, vec![]);
|
||||
run_frame(&ctx, &mut app, vec![]);
|
||||
assert_eq!(app.dialogs.open_name(), Some("session"));
|
||||
menus::invoke_menu(&mut app, "clip.unloop", "Clip > Unloop...");
|
||||
run_frame(&ctx, &mut app, vec![enter_key(false), enter_up()]);
|
||||
assert_eq!(app.dialogs.open_name(), Some("unloop"), "the opening Enter leaves the Unloop dialog open");
|
||||
assert_eq!(loop_ids(&app, track), before, "the opening Enter does not unloop");
|
||||
run_frame(&ctx, &mut app, vec![enter_key(false)]);
|
||||
assert_eq!(app.dialogs.open_name(), None);
|
||||
assert_eq!(loop_ids(&app, track).len(), looped - 2, "the next Enter presses Remove");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_enter_does_not_press_remove_until_it_is_pressed_again() {
|
||||
let (mut app, track, looped) = looped_app();
|
||||
let before = loop_ids(&app, track);
|
||||
let ctx = egui::Context::default();
|
||||
soundcraft_ui_egui::framework::install_headless(&ctx);
|
||||
run_frame(&ctx, &mut app, vec![]);
|
||||
menus::invoke_menu(&mut app, "clip.unloop", "Clip > Unloop...");
|
||||
run_frame(&ctx, &mut app, vec![enter_key(false)]);
|
||||
run_frame(&ctx, &mut app, vec![enter_key(true)]);
|
||||
run_frame(&ctx, &mut app, vec![enter_key(true)]);
|
||||
assert_eq!(app.dialogs.open_name(), Some("unloop"), "the held Enter's repeats leave the dialog open");
|
||||
assert_eq!(loop_ids(&app, track), before, "the held Enter's repeats do not unloop");
|
||||
run_frame(&ctx, &mut app, vec![enter_up()]);
|
||||
run_frame(&ctx, &mut app, vec![enter_key(false)]);
|
||||
assert_eq!(app.dialogs.open_name(), None);
|
||||
assert_eq!(loop_ids(&app, track).len(), looped - 2, "a new press of Enter presses Remove");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unloop_dialog_is_shown_in_brazilian_portuguese() {
|
||||
let (mut app, track, looped) = unloop_app();
|
||||
app.ui.language = soundcraft_ui_egui::localization::Language::PortugueseBrazil;
|
||||
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| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Desativar loop");
|
||||
h.get_by_label("Remover exclui as iterações do loop e mantém o clipe de origem. Consolidar mantém cada iteração do loop como um clipe próprio.");
|
||||
h.get_by_role_and_label(Role::Button, "Remover");
|
||||
h.get_by_role_and_label(Role::Button, "Consolidar").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialogs.open_name(), None);
|
||||
assert_eq!(clips(&h, track), vec![None; looped]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unloop_dialogs_remove_keeps_only_the_source_clip() {
|
||||
let (mut h, track, looped) = unloop_dialog();
|
||||
h.get_by_role_and_label(Role::Button, "Remove").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialogs.open_name(), None);
|
||||
assert_eq!(clips(&h, track).len(), looped - 2);
|
||||
}
|
||||
@@ -278,15 +278,8 @@ impl EditorLink {
|
||||
let mut g = self.lock();
|
||||
if g.window.as_ref().is_some_and(|w| !w.is_visible()) {
|
||||
EditorLink::teardown(&mut g);
|
||||
} else {
|
||||
// a timer-driven editor's WM_TIMERs and the paints they invalidate are starved while
|
||||
// the transport keeps the queue busy (#1447)
|
||||
if let Some(w) = &g.window {
|
||||
w.service();
|
||||
}
|
||||
if let Some(f) = &g.frame {
|
||||
f.dispatch();
|
||||
}
|
||||
} else if let Some(f) = &g.frame {
|
||||
f.dispatch();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,9 +66,6 @@ impl HostWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
self.get().is_some_and(|w| w.isVisible())
|
||||
}
|
||||
|
||||
@@ -19,9 +19,6 @@ impl HostWindow {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
pub fn raise(&self) {}
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::sync::OnceLock;
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
|
||||
use windows_sys::Win32::Graphics::Gdi::{RDW_ALLCHILDREN, RDW_UPDATENOW, RedrawWindow};
|
||||
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GWL_EXSTYLE,
|
||||
GWL_STYLE, GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, MSG, PM_REMOVE, PeekMessageW, PostQuitMessage, RegisterClassExW,
|
||||
SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WM_QUIT, WM_TIMER,
|
||||
WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
|
||||
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, GWL_EXSTYLE, GWL_STYLE,
|
||||
GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, RegisterClassExW, SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE,
|
||||
SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
|
||||
};
|
||||
|
||||
pub const PLATFORM_TYPE: Option<*const c_char> = Some(vst3::Steinberg::kPlatformTypeHWND);
|
||||
@@ -145,18 +143,6 @@ impl HostWindow {
|
||||
self.live().is_some_and(|h| unsafe { IsWindowVisible(h) } != 0)
|
||||
}
|
||||
|
||||
/// Per-frame service on the main thread (#1447): while the transport plays eframe always keeps a
|
||||
/// repaint pending, and Win32 only synthesizes `WM_TIMER` and `WM_PAINT` when the queue runs dry —
|
||||
/// so a timer-driven editor is starved until playback pauses. Dispatches the thread's pending
|
||||
/// timers (thread-wide on purpose: nothing else on this thread uses Win32 timers, and a timer
|
||||
/// with a `TIMERPROC` only runs through dispatch) and flushes the paint they invalidate.
|
||||
pub fn service(&self) {
|
||||
let Some(hwnd) = self.live() else { return };
|
||||
pump_timers();
|
||||
// SAFETY: a live window of this thread; ALLCHILDREN reaches the plugin's child windows.
|
||||
unsafe { RedrawWindow(hwnd, std::ptr::null(), std::ptr::null_mut(), RDW_UPDATENOW | RDW_ALLCHILDREN) };
|
||||
}
|
||||
|
||||
pub fn close(self) {
|
||||
if let Some(h) = self.live() {
|
||||
// SAFETY: our own live window; the view was detached before (see `teardown`).
|
||||
@@ -177,94 +163,3 @@ pub fn resize(window: *mut c_void, w: f64, h: f64) {
|
||||
// SAFETY: as above; only the size changes.
|
||||
unsafe { SetWindowPos(window, std::ptr::null_mut(), 0, 0, ow, oh, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE) };
|
||||
}
|
||||
|
||||
/// Dispatches up to 32 `WM_TIMER`s pending on this thread (main thread only). The cap keeps a timer
|
||||
/// that re-arms on every dispatch from starving the frame; leftovers are served next tick.
|
||||
fn pump_timers() {
|
||||
// SAFETY: `PeekMessageW`/`DispatchMessageW`/`PostQuitMessage` on this thread's own queue;
|
||||
// `msg` outlives them all.
|
||||
unsafe {
|
||||
let mut msg: MSG = std::mem::zeroed();
|
||||
for _ in 0..32 {
|
||||
if PeekMessageW(&mut msg, std::ptr::null_mut(), WM_TIMER, WM_TIMER, PM_REMOVE) == 0 {
|
||||
break;
|
||||
}
|
||||
if msg.message == WM_QUIT {
|
||||
// PeekMessageW returns WM_QUIT regardless of the filter — repost it with its
|
||||
// exit code so the app's own message loop still sees the quit, and stop here.
|
||||
PostQuitMessage(msg.wParam as i32);
|
||||
break;
|
||||
}
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use windows_sys::Win32::Graphics::Gdi::{GetUpdateRect, InvalidateRect};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{KillTimer, SetTimer};
|
||||
|
||||
static FIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
unsafe extern "system" fn on_timer(hwnd: HWND, _msg: u32, _id: usize, _time: u32) {
|
||||
FIRED.fetch_add(1, Ordering::Relaxed);
|
||||
// SAFETY: a live window of this thread.
|
||||
unsafe { InvalidateRect(hwnd, std::ptr::null(), 1) };
|
||||
}
|
||||
|
||||
/// #1447: while the transport plays eframe always has a repaint pending, and Win32 only
|
||||
/// synthesizes `WM_TIMER`/`WM_PAINT` when the queue runs dry — an editor that animates from a
|
||||
/// timer freezes until Pause. `service` must dispatch the timer and its paint without a
|
||||
/// message loop ever waiting.
|
||||
#[test]
|
||||
fn an_editors_timer_and_paint_run_while_the_thread_never_waits_for_messages() {
|
||||
// windows are created and served on the app's UI thread — named "main" here.
|
||||
std::thread::Builder::new()
|
||||
.name("main".into())
|
||||
.spawn(|| {
|
||||
let window = HostWindow::new("timer test", 120.0, 80.0).expect("host window");
|
||||
let h = window.raw() as HWND;
|
||||
FIRED.store(0, Ordering::Relaxed);
|
||||
// SAFETY: live window of this thread; proc outlives the timer (killed below).
|
||||
unsafe { SetTimer(h, 1, 10, Some(on_timer)) };
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
assert_eq!(FIRED.load(Ordering::Relaxed), 0, "the timer fired without anyone pumping");
|
||||
window.service();
|
||||
assert!(FIRED.load(Ordering::Relaxed) > 0, "service() did not dispatch WM_TIMER");
|
||||
// SAFETY: `GetUpdateRect` accepts any window; false means the paint was flushed.
|
||||
assert_eq!(unsafe { GetUpdateRect(h, std::ptr::null_mut(), 0) }, 0, "the timer's paint is still pending");
|
||||
unsafe { KillTimer(h, 1) };
|
||||
window.close();
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("join");
|
||||
}
|
||||
|
||||
/// `PeekMessageW` returns `WM_QUIT` regardless of the filter range, so the pump can swallow
|
||||
/// the quit the app's own loop is waiting for. It must repost it — with its exit code — and
|
||||
/// stop, leaving the signal for the owning loop.
|
||||
#[test]
|
||||
fn the_pump_leaves_a_quit_and_its_exit_code_for_the_owning_loop() {
|
||||
std::thread::Builder::new()
|
||||
.name("main".into())
|
||||
.spawn(|| {
|
||||
// SAFETY: this thread owns the queue it posts to and peeks.
|
||||
unsafe { PostQuitMessage(7) };
|
||||
pump_timers();
|
||||
// SAFETY: `MSG` is a plain Win32 data struct made of integer and pointer fields,
|
||||
// so an all-zero value is valid initialized storage.
|
||||
let mut msg: MSG = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: `msg` is live owned storage, so `&mut msg` remains valid and writable
|
||||
// for the duration of the call.
|
||||
assert_ne!(unsafe { PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) }, 0, "the pump swallowed the quit");
|
||||
assert_eq!((msg.message, msg.wParam), (WM_QUIT, 7), "the quit signal or its exit code changed");
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("join");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,9 +142,6 @@ impl HostWindow {
|
||||
self.shown.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
|
||||
pub fn service(&self) {}
|
||||
|
||||
pub fn is_visible(&self) -> bool {
|
||||
let Some(x) = x().filter(|_| on_main_thread()) else { return false };
|
||||
x.pump();
|
||||
|
||||
@@ -359,15 +359,6 @@ impl Plugin for Vst3Plugin {
|
||||
self.latency
|
||||
}
|
||||
|
||||
fn idle(&mut self) {
|
||||
// A new latency is announced with `restartComponent(kLatencyChanged)`, which some plugins
|
||||
// send from a timer of their own, long after they started using it (LSP): ask instead.
|
||||
if self.inst.is_active() {
|
||||
self.inst.host().latency_changed.store(false, Ordering::Relaxed);
|
||||
self.latency = self.inst.latency() as usize;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_transport(&mut self, transport: &Transport) {
|
||||
self.transport = Some(*transport);
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
//! (connected through IConnectionPoint, synced through the component state). Params: 7 "Gain"
|
||||
//! (plain 0..2, linear, units dB), 3 "Mode" (3 steps: A/B/C), 12 "Freq" (20..20000 Hz, log),
|
||||
//! 9 hidden, 11 bypass. Starts at gain 0.5 (its state) although the declared default is 1.0.
|
||||
//! Reports 3 samples of latency, 16 in mode C (at once, but never announced with
|
||||
//! `restartComponent`, like a plugin that announces it later from a timer). State: the component stores the gain (one LE f64), the
|
||||
//! Reports 3 samples of latency. State: the component stores the gain (one LE f64), the
|
||||
//! controller the Freq value (one LE f64). Its controller has an editor view (`IPlugView`,
|
||||
//! 320×240, no real drawing) supporting NSView/HWND/X11.
|
||||
//! - "Fixture Synth" (`Instrument|Synth`): a single-component instrument (the component is also
|
||||
@@ -78,8 +77,6 @@ unsafe fn channels<'a>(bus: &AudioBusBuffers, frames: usize) -> Vec<&'a mut [f32
|
||||
struct GainProcessor {
|
||||
/// Normalized gain (plain = 2 × normalized).
|
||||
gain: AtomicU64,
|
||||
/// Normalized mode (C = 1.0).
|
||||
mode: AtomicU64,
|
||||
arrangement: AtomicU64,
|
||||
_live: Live,
|
||||
}
|
||||
@@ -182,7 +179,7 @@ impl IAudioProcessorTrait for GainProcessor {
|
||||
if size == SymbolicSampleSizes_::kSample32 as i32 { kResultOk } else { kNotImplemented }
|
||||
}
|
||||
unsafe fn getLatencySamples(&self) -> u32 {
|
||||
if f64::from_bits(self.mode.load(Ordering::Relaxed)) > 0.75 { 16 } else { 3 }
|
||||
3
|
||||
}
|
||||
unsafe fn setupProcessing(&self, setup: *mut ProcessSetup) -> tresult {
|
||||
let s = unsafe { &*setup };
|
||||
@@ -201,13 +198,8 @@ impl IAudioProcessorTrait for GainProcessor {
|
||||
let Some(q) = (unsafe { ComRef::from_raw(changes.getParameterData(i)) }) else { continue };
|
||||
let (mut off, mut v) = (0, 0.0);
|
||||
let n = unsafe { q.getPointCount() };
|
||||
if n == 0 || unsafe { q.getPoint(n - 1, &mut off, &mut v) } != kResultOk {
|
||||
continue;
|
||||
}
|
||||
match unsafe { q.getParameterId() } {
|
||||
7 => self.gain.store(v.to_bits(), Ordering::Relaxed),
|
||||
3 => self.mode.store(v.to_bits(), Ordering::Relaxed),
|
||||
_ => {}
|
||||
if unsafe { q.getParameterId() } == 7 && n > 0 && unsafe { q.getPoint(n - 1, &mut off, &mut v) } == kResultOk {
|
||||
self.gain.store(v.to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -787,7 +779,6 @@ impl IPluginFactoryTrait for Factory {
|
||||
let unknown = if cid == GAIN_CID {
|
||||
ComWrapper::new(GainProcessor {
|
||||
gain: AtomicU64::new(0.25f64.to_bits()),
|
||||
mode: AtomicU64::new(0f64.to_bits()),
|
||||
arrangement: AtomicU64::new(SpeakerArr::kStereo),
|
||||
_live: Live::new(&OBJECTS),
|
||||
})
|
||||
|
||||
@@ -71,19 +71,6 @@ fn identity_mapped_param_text_is_read_on_the_main_thread_only() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_reads_a_latency_the_plugin_has_not_announced_yet() {
|
||||
let mut p = soundcraft_vst3_host::create(&id_of("Fixture Gain")).unwrap();
|
||||
p.prepare(48_000.0, 64, 2);
|
||||
assert_eq!(p.latency(), 3);
|
||||
assert!(p.set_param("3", 2.0), "mode C takes 16 samples");
|
||||
let mut io = vec![vec![0.5f32; 64]; 2];
|
||||
p.process(&mut io, 64);
|
||||
assert_eq!(p.latency(), 3, "no restartComponent came");
|
||||
p.idle();
|
||||
assert_eq!(p.latency(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gain_processes_audio_and_follows_params() {
|
||||
let mut p = soundcraft_vst3_host::create(&id_of("Fixture Gain")).unwrap();
|
||||
|
||||
@@ -42,7 +42,7 @@ Errors: `{"id": 1, "ok": false, "error": "bad parameters for `mix.volume`: no tr
|
||||
| `engine.execute` (alias `command`) | `{command, params}` | Run a command programmatically. **Never opens a dialog**; empty params use defaults or the current selection. |
|
||||
| `engine.commands` | `{filter?}` | Every command: id, label, menu path, shortcut, params doc, enabled + reason. Includes UI-layer commands (`window.*`). |
|
||||
| `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 and redo labels (each null when there is no step). |
|
||||
| `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}`. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (retain SMF SysEx packets across import, sessions and export) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-14 · **Change:** minor (strict external-WAV AAF import; previously minor: audio formats come from craft-audio) · **Target:** Avid Pro Tools Ultimate 2026.4.1
|
||||
|
||||
Every format Pro Tools reads or writes, and ours. The Pro Tools list comes from the document types
|
||||
its bundle declares (`CFBundleDocumentTypes` in Info.plist: names only, nothing else read) and its
|
||||
@@ -58,14 +58,6 @@ Legend: ✅ supported and tested · 🟡 partial · ❌ missing · — not appli
|
||||
| MusicXML (to Sibelius) | export | — | ✅ | `file.export_sibelius`, `score.rs` |
|
||||
| Printable score | print | — | ✅ (SVG) | |
|
||||
|
||||
SMF `F0` and `F7` SysEx packets retain their payload, packet type and tick when imported,
|
||||
saved/reopened in a session and exported to MIDI, including setup tracks containing only
|
||||
SysEx. Split, trim, merge and consolidate preserve their clip-relative timing. Payload is
|
||||
limited to 16 MiB across one MIDI file; an oversized import is refused before changing the
|
||||
session. SysEx is retained for interchange, **not yet forwarded to instruments on playback**;
|
||||
the import command reports that limitation when such packets are present. This does not
|
||||
complete MIDI or XG playback parity.
|
||||
|
||||
## Video
|
||||
|
||||
| Format | Pro Tools | Read | Write | Tests / notes |
|
||||
@@ -89,7 +81,6 @@ complete MIDI or XG playback parity.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-18 | minor | Retain SMF SysEx packets through MIDI import/export and session saves, including SysEx-only tracks; playback forwarding remains unsupported |
|
||||
| 2026-11-14 | minor | Strict external-WAV AAF import with editable clips, relink and timecode mapping; export and the wider AAF/OMF feature set remain unsupported; readiness estimate unchanged |
|
||||
| 2026-11-11 | minor | Audio formats come from `craft-audio` (craft-libs); `crates/audio-io` is gone. New on import: Opus, AC-3/E-AC-3, `.mov`/`.mka` audio; AAC, ALAC and MP2 no longer go through symphonia; `.aifc` is a writable name |
|
||||
| 2026-11-02 | trivial | WAV bounces (mix and stems) write a `bext` TimeReference: session timecode start plus bounce start (#1296) |
|
||||
|
||||
+2
-2
@@ -43,8 +43,8 @@ works across the suite) keep the agent to the folders you give it:
|
||||
`session.save_as`, `session.save_copy`, `session.save_template`, `bounce_mix` and
|
||||
`file.bounce_mix`, `file.bounce_stems`, `file.export_clips`, `file.export_midi`,
|
||||
`file.export_session_text`, `file.export_selected_tracks_as_session`, `file.export_sibelius`,
|
||||
`file.send_to_sibelius`, `file.print_score`, `file.export_clip_groups`, `track.save_preset`
|
||||
and the record folder `setup.disk_allocation` sets, together with what a session save writes beside the session file
|
||||
`file.send_to_sibelius`, `file.print_score`, `file.export_clip_groups` and
|
||||
`track.save_preset`, together with what a session save writes beside the session file
|
||||
(`Audio Files/`, `Backups/`) and its temporary file. A score command given no `path` writes to
|
||||
the temp folder, which is outside the write roots unless you made it one, so it is refused.
|
||||
- Each flag may be given more than once (#874): a path inside any of the read roots may be read,
|
||||
|
||||
@@ -52,14 +52,13 @@ User report #152: a saved instrument level does not reach the bounce.
|
||||
| Sidechain / key input | ✅ | ❌ | All three hosts |
|
||||
| ARA 2 (pitch/time editors in the timeline) | ✅ | ❌ | Menu leaves Track/Clip/Window ▸ ARA still missing |
|
||||
| Crash isolation | in-process (DSP on HDX) | in-process | Out-of-process hosting would beat Pro Tools |
|
||||
| Plugin delay reporting changes on the fly | ✅ | 🟡 | Aux insert latency bug #103 (PR #133). Offline renders follow a latency a hosted plugin finds once it runs (CLAP restart, VST3 asked between blocks, #1287); realtime playback doesn't follow it yet |
|
||||
| Plugin delay reporting changes on the fly | ✅ | 🟡 | Aux insert latency bug #103 (PR #133) |
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-09 | trivial | Modulation: Frequency Shifter (`freq_shifter`); 28 processors + 3 instruments |
|
||||
| 2026-11-02 | minor | Offline renders give hosted plugins main-thread time between blocks: CLAP callbacks and restarts, VST3 latency read again; a latency found on the first block restarts the render (#1287) |
|
||||
| 2026-10-27 | minor | Editors: VST3 and embedded CLAP editors on Linux/X11, with the host run loop (VST3 `IRunLoop`, CLAP timer and fd support) (#527) |
|
||||
| 2026-10-25 | trivial | Auto Pan: constant-power balance of the left and right channels; stereo passes unchanged at the center |
|
||||
| 2026-10-24 | minor | AudioSuite speed ramps (`speed_ramp`): down to a stop and up from one, Fit To or Extend, fades on or off |
|
||||
|
||||
+2
-2
@@ -53,7 +53,7 @@ web build and are checked, the signing jobs are refused, and no release is draft
|
||||
| Linux riscv64 | `soundcraft-<v>-linux-riscv64.tar.gz` (glibc 2.39+) | `ubuntu-24.04` (cross-compiled; CLI smoke-tested under QEMU) |
|
||||
| AppImage updates | `soundcraft-<v>-linux-{x86_64,aarch64}.AppImage.zsync` | with the AppImage |
|
||||
| Flatpak x86_64, aarch64 | `soundcraft-<v>-linux-{x86_64,aarch64}.flatpak` | `ubuntu-24.04`, `ubuntu-24.04-arm` (repackages the Linux tarball) |
|
||||
| FreeBSD 15.1+ x86_64 | `soundcraft-<v>-freebsd-x86_64.tar.gz` (a `/usr/local` tree) | FreeBSD 15.1 release target on `ubuntu-latest` |
|
||||
| FreeBSD 14 x86_64 | `soundcraft-<v>-freebsd-x86_64.tar.gz` (a `/usr/local` tree) | FreeBSD 14.3 VM on `ubuntu-latest` |
|
||||
| Web | `soundcraft-web-<v>.zip` (static site; see [`packaging/web/README.md`](../packaging/web/README.md)) | `ubuntu-latest` |
|
||||
|
||||
The from-source Flatpak manifest (`packaging/linux/flatpak/ai.storyteller.soundcraft.yml`) is
|
||||
@@ -177,7 +177,7 @@ Locally (on Linux): install nfpm, then `packaging/linux/package.sh` (or `--forma
|
||||
|
||||
### FreeBSD
|
||||
|
||||
GitHub has no FreeBSD runners, so the `freebsd` job builds inside a FreeBSD 15.1 VM (shared 15.1-STABLE target)
|
||||
GitHub has no FreeBSD runners, so the `freebsd` job builds inside a FreeBSD 14.3 VM
|
||||
(`vmactions/freebsd-vm`, pinned by commit) and runs `packaging/freebsd/package.sh`, which stages
|
||||
a `/usr/local`-style tree (binaries, desktop entry, MIME type, metainfo, icons, docs, and
|
||||
`soundcraft-cli`'s man pages and shell completions) as a
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Target-app parity: SoundCraft vs Avid Pro Tools
|
||||
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-23 · **Change:** minor (archived the 27 October–15 November progress recap; Performance row: recording is to disk (#84, #888); scores unchanged; previously minor: strict external-WAV AAF import; previously trivial: Frequency Shifter: 28 built-in processors; G-09/localization: pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 (bundle 26.4.1.179, macOS)
|
||||
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-14 · **Change:** minor (Performance row: recording is to disk (#84, #888); scores unchanged; previously minor: strict external-WAV AAF import; previously trivial: Frequency Shifter: 28 built-in processors; G-09/localization: pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 (bundle 26.4.1.179, macOS)
|
||||
|
||||
The authoritative assessment of how close SoundCraft is to Pro Tools. [`ROADMAP.md`](../ROADMAP.md)
|
||||
summarizes it, [`gaps.md`](gaps.md) itemizes every shortfall, and the per-dimension docs go deeper:
|
||||
@@ -245,7 +245,6 @@ serializes more, because it needs hands-on testing.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Historical ROADMAP sync over 27 October–15 November: releases v0.14.0–v0.20.1, clip drawing and edit-mode colours, Edit-window I/O volume and pan, Grid/Nudge time scales, a new-tracks workflow, device/buffer application (#1077), sample-accurate volume automation (#1355), session and format hardening (#892, #890, #995, #993), VST3 multi-out and offline-render support, BWF timecode, about a 20 % faster mix bounce in the #1144 demo benchmark and craft-libs cutovers; no new measurement of menu breadth, readiness or effort |
|
||||
| 2026-11-14 | minor | Strict external-WAV AAF import added to format, interchange and alpha-gate evidence; readiness estimates unchanged |
|
||||
| 2026-11-09 | trivial | Built-in plugin counts: 28 processors + 3 instruments with the Frequency Shifter. Percentages unchanged |
|
||||
| 2026-11-05 | trivial | Localization row: English plus a near-complete pt-BR catalog for fixed UI strings (PR #1346), not native-reviewed. Percentages and hours unchanged |
|
||||
|
||||
@@ -182,8 +182,8 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
producer_platforms(source.replace(" " + current + "\n", ""))
|
||||
|
||||
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
|
||||
source = (ROOT / ".github/workflows" / workflow).read_text()
|
||||
expected = NightlyEnabledCallers.GUARDS[name]
|
||||
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
|
||||
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
|
||||
@@ -192,22 +192,15 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
(indicator, expression), = job_conditions(jobs)
|
||||
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
|
||||
|
||||
def test_nightly_triggers_and_schedule_match_review(self):
|
||||
expected_triggers = (
|
||||
("nightly.yml", [" schedule:", " workflow_dispatch:"]),
|
||||
("nightly-sign.yml", [" workflow_dispatch:"]),
|
||||
("nightly-dispatch.yml", [" workflow_run:"]),
|
||||
)
|
||||
for name, expected in expected_triggers:
|
||||
def test_no_nightly_schedule_is_registered(self):
|
||||
for name, event in (("nightly.yml", "workflow_dispatch"),
|
||||
("nightly-sign.yml", "workflow_dispatch")):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
|
||||
triggers = [line for line in events.splitlines() if line.startswith(" ")
|
||||
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(triggers, expected, "schedule/activation needs explicit review")
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
crons = re.findall(r"(?m)^ - cron: '([^']+)'$", producer)
|
||||
self.assertEqual(crons, ["30 5 * * *"], "nightly schedule must match the reviewed cadence")
|
||||
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
|
||||
|
||||
def test_signer_serialization_contract_is_enforced(self):
|
||||
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
|
||||
@@ -228,7 +221,7 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
assert_nightly_serialization(source.replace(old, new))
|
||||
|
||||
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"):
|
||||
for name in ("nightly.yml", "nightly-sign.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
executable = "\n".join(line for line in source.splitlines()
|
||||
if not line.lstrip().startswith("#"))
|
||||
@@ -326,7 +319,6 @@ class NightlyEnabledCallers(unittest.TestCase):
|
||||
"github.event_name == 'workflow_dispatch')",
|
||||
"nightly-sign.yml": "github.repository == 'storytold/soundcraft' && github.event_name == 'workflow_dispatch' && "
|
||||
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
|
||||
"nightly-dispatch.yml": "github.repository == 'storytold/soundcraft' && github.event_name == 'workflow_run'",
|
||||
}
|
||||
|
||||
def test_enabled_jobs_keep_exact_context_guards(self):
|
||||
@@ -343,8 +335,7 @@ class NightlyEnabledCallers(unittest.TestCase):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
|
||||
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
|
||||
"automatic signer actor must match the scheduled dispatcher")
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
|
||||
def test_an_actor_outside_the_release_managers_is_refused(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
@@ -803,22 +794,11 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
|
||||
"the signer guard is exactly the reviewed repository, dispatch and signer-branch expression")
|
||||
self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), ["soundcraft"],
|
||||
"the shared signer needs the reviewed registry app")
|
||||
dispatch_path = ROOT / ".github/workflows/nightly-dispatch.yml"
|
||||
self.assertTrue(dispatch_path.exists(), "scheduled nightly requires the reviewed automatic transport")
|
||||
dispatch = dispatch_path.read_text()
|
||||
producer_name = re.findall(r"(?m)^name: (.+)$", (ROOT / ".github/workflows/nightly.yml").read_text())
|
||||
self.assertEqual(producer_name, ["SoundCraft unsigned nightly"])
|
||||
self.assertIn(f"workflows: [{producer_name[0]}]", dispatch)
|
||||
self.assertIn("branches: [main]", dispatch)
|
||||
self.assertIn("\npermissions: {}\n", dispatch)
|
||||
self.assertIn("'ref': 'refs/heads/" + SIGNER_BRANCH + "'", dispatch)
|
||||
self.assertIn("https://api.github.com/repos/storytold/soundcraft/actions/workflows/nightly-sign.yml/dispatches",
|
||||
dispatch)
|
||||
assert_caller_secrets(dispatch, "dispatch", set())
|
||||
self.assertFalse((ROOT / ".github/workflows/nightly-dispatch.yml").exists(),
|
||||
"this app has no automatic transport; adding one needs its own reviewed PR")
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(policy["release_branch"], SIGNER_BRANCH)
|
||||
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
|
||||
"automatic signer actor must match the scheduled dispatcher")
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user