Compare commits

..
Author SHA1 Message Date
FredApps bc1642a9f0 Merge main into fredapps/macos-plugin-entitlements 2026-11-28 23:10:54 +01:00
Billy Coleman IIIandFredApps 0f26696507 Read bus-send pan and mute automation (#543)
* Read bus-send automation at the delayed source timeline

Keep send pan and mute aligned with the samples at each pre/post tap.
Track known upstream bus ages through Aux paths without changing audio
alignment or routing, and retain the existing clock for mixed-age sums.

Add independent latency, pre/post, nested-route and clock-boundary
regressions while preserving static fallback and existing send laws.

* style: group the send-automation imports

Move crate uses to the top of the module so rustfmt is more likely to accept the merge port.

* style: rustfmt the send-automation merge port

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 23:09:37 +01:00
c475779755 macOS: plugin-loading entitlements for the signed app and CLI
Add com.apple.security.cs.disable-library-validation and
com.apple.security.cs.allow-unsigned-executable-memory to the hardened-runtime
entitlements, and sign soundcraft-cli with the same entitlements, so signed
builds load third-party VST3/CLAP/AU plugins (including UADx/PACE). Combines
#395 and #1119.

Co-authored-by: IfritisZ <44840600+IfritisZ@users.noreply.github.com>
Co-authored-by: timlehmann1234567890-cell <346860803+timlehmann1234567890-cell@users.noreply.github.com>
2026-11-28 23:07:07 +01:00
d1694ebfd5 Playback: strips render on the audio thread itself; count underruns and late callbacks (#1074)
* Playback: strips render on the audio thread itself

The realtime callback handed strips to rayon's global pool whenever a session had four or
more, then waited for them. The pool's workers run at normal priority, so under CPU load the
callback waited for starved workers (priority inversion) and blocked, which the callback must
never do. On the audio thread strips now render one after the other on the thread itself;
offline renders (bounces) keep the parallelism. `as_audio_thread`, which marked pool workers
while they rendered for the audio thread, is no longer needed.

A headless stress test (opt-in: `cargo test -p soundcraft-playback -- --ignored`) plays a
16-track session with an EQ and a compressor per track, one callback per 512-frame period,
while all cores but one spin. Before: 23 and 30 of 1500 callbacks missed their deadline;
after: none in two runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Playback: count underruns and late callbacks; audio.health control method

cpal reports underruns as `ErrorKind::Xrun`; they were only logged. The player now counts
them, callbacks that overran their buffer period, and the worst callback load (relaxed
atomics and one `Instant::now()` per callback, nothing on wasm32). `Player::health()` reads
them; `Player::take_health()` reads and counts afresh without losing an event in between.
The control channel reports them as `audio.health` (with the device's rate and buffer), and
`soundcraft-cli app` knows it as a method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: rustfmt the audio.health port

cargo fmt --check failed on import grouping and a one-line if in the playback tests.

* fix: cpal 0.18 sample_rate is a u32, and drop an unused import

The output callback health timer used the old SampleRate newtype field, and note_stream_error removed the only use of Ordering in stream.rs.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 23:00:20 +01:00
66903aa4dc soundcraft-web: window.soundcraft, the page command API from craft-web-api (#1468)
* soundcraft-web: window.soundcraft, the page command API from craft-web-api

The web build had no control channel. It now installs window.soundcraft (request, execute, commands, docInspect, uiInspect, screenshot) from craft-web-api (storytold/craft-libs#413): the shell queues each call as a control request, the channel the desktop control server uses, and the app answers it on its next frame. SoundCraft's control requests cannot be withdrawn, so a call that times out in the page still runs when the app reaches it.

* soundcraft-web: the page wait ends with an error when the page has no timer

The wait for the app polled with a timer; with no window, or a timer the page refuses, the promise never settled and the wait hung. sleep now says whether a timer was set, and the wait ends the call with an error when none was, which releases the request.

* soundcraft-web: a real-browser check of window.soundcraft

apps/soundcraft-web/tests/page-api.mjs serves a built copy of the site, loads it in headless Chromium and drives all six functions, a command that changes the session, the rejection of an unknown method and of an unknown command, the screenshot and several calls at once. It is run by hand and is not part of cargo xtask ci. The README says how to run it.

* soundcraft-web: the browser check requires both docInspect calls to resolve before comparing

A rejected docInspect after track.new left its value undefined, which compared as a change.

* soundcraft-web: bound the calls waiting for the app, and test a burst

The queue behind window.soundcraft was unbounded and the pinned craft-web-api had no limit of its own, so a page loop could queue calls without end, including while the app was not draining.

craft-web-api is now pinned at the commit that refuses calls beyond an in-flight limit (craft-libs#733), and the queue of the app itself is bounded at 64 requests too: one more is refused at once with a busy error, and the call rejects. The browser check sends a burst of 300 calls and expects the ones over the limit to be refused as busy, the ones within it answered, and a later call accepted again.

* soundcraft-web: name SoundApp in the page API install comment

The install docs referred to WordApp::with_control, a leftover from the shared page API pattern.

---------

Co-authored-by: skylartaylor <hi@skylar.cc>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 22:48:29 +01:00
f5bcb64199 Add French and Spanish UI localization (#143)
* Add French and Spanish UI localization

French and Spanish join Brazilian Portuguese on the localization layer:
two Language variants (fr, es) with catalogs in locales/fr and
locales/es, listed in Appearance > Language and accepted by ui.language.
Numbers use a decimal comma, as in pt-BR.

The rows come from #143's earlier translation table, keyed to the
English strings main shows: 1,368 per language, about 62 % of the
pt-BR catalog. Positional {} templates take main's named placeholders.
Strings without a row show in English; engine error templates are not
translated yet.

The catalog tests (unique keys, placeholder parity, lookup) now run on
every catalog, and the fallback test covers French and Spanish.

* Complete the Spanish (es-ES) UI catalog

Fill in the remaining Spanish UI strings and all error templates, and
review studio terminology against common Spanish studio usage (native
speaker, sound engineer).

The file-path field in the path prompt now uses its own "File Path" key
(es "Ruta", fr "Chemin du fichier", pt-BR "Caminho do arquivo"), so the
auto-pan "Path" parameter can be translated as a direction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test that the Spanish catalog covers every menu label

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: Spanish catalog complete in the language tables

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: name the path prompt's File path and Folder path keys

---------

Co-authored-by: SondesonRS <SondesonRS@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 22:36:58 +01:00
Dylan M. Taylor 1e7dbcbe54 ci: pin storytold/craft-common-actions to @main universally (#1886) 2026-11-28 16:07:16 -05:00
Dylan M. Taylor acdc3efbc6 ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#1885) 2026-11-28 15:17:41 -05:00
eab00b3f01 Fail the build without panic! when SOUNDCRAFT_REQUIRE_WINRES is set (#1884)
The workspace denies clippy::panic, build scripts included. Print the reason on stderr and exit 1 instead.

Co-authored-by: Fredrik Hallin <fredrik.hallin@guidelinegeo.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 21:12:43 +01:00
Dylan M. Taylor 865baa99f1 Roll out nightly signing pin, macOS docs layout, and profile reopen fix (#1881) 2026-11-28 11:32:48 -05:00
Dylan M. TaylorandFredApps ab682bf54e Automation roots: compare canonical components exactly (#1348)
* Automation roots: compare canonical components exactly

* test(engine): a case-sensitive Windows directory keeps case-equal folders apart

Regression test for the exact-component comparison: on an NTFS directory switched to
case-sensitive, a root on Work grants neither work nor WORK. Run on Windows against NTFS;
it fails with the previous case-folding comparison.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 15:05:42 +01:00
mtlcl410andFredApps 728634732f Meters fall to silence when the audio device stops calling back (#1826)
* Meters fall to silence when the audio device stops calling back

A take with no new block keeps the previous readings, so a large device
buffer does not flash the meters to silence between callbacks. When the
device is lost or stalls no callback ever comes again, and the UI fed the
last block's peak to the meters every frame: they stayed lit and flickered
by the release of one frame.

take_meters now says whether new blocks arrived. The UI notes when one
last did, and once none has come for 0.5 s (longer than an 8192-frame
buffer at 44.1 kHz plus the slowest meter poll) it clears the readings, so
the meters fall at their normal release and the peak hold expires.

* Do not let a silent channel keep the other channel's peak hold up

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 13:48:30 +01:00
mtlcl410andFredApps f79cad0f16 fix(ui): show the current device choice in the Playback Engine after a command changes it (#1750)
* fix(ui): show the current device choice in the Playback Engine after a command changes it

The Playback Engine kept its edits in a draft that only its close button
cleared. Closed from the menu, or left open while ui.audio_device or
setup.playback_engine changed the choice, it reopened on the earlier
choice, and Apply then put that choice back without a word.

Keep the choice the draft started from with the draft, and start over
from the current choice when they differ; clear the draft however the
window closes.

* docs: note the Playback Engine following command changes in the G-01 gap and hardware parity

* docs: drop macOS from the G-01 verification still missing

* fix(ui): say when a change made elsewhere replaces the Playback Engine's unapplied edits

Pro Tools' Playback Engine is a modal dialog (Reference Guide p. 109), so
nothing else changes the device under its edits. This window is not modal:
when ui.audio_device or setup.playback_engine changes the choice while the
window holds unapplied edits, the window takes the new choice, as before,
and now says the edits were replaced, under its buttons and in the status
line, until the next edit or until it is closed.

* test: set the Playback Engine harness up headless, as main's craft-libs requires

The merge from main brings a craft-libs whose command board panics without
the headless framework setup in a kittest harness.

* docs: bring comments in line with the code

* fix: clear the replaced-edits notice from the status line

The Playback Engine wrote the notice to app.ui.status, but a later
edit or closing the window only cleared the in-window warning flag.
Clear the status when it still holds this notice, and test both paths.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 13:38:20 +01:00
Hamza NaveedandFredApps adda9dab37 Edit window: Delete clears when the MIDI Editor is open behind another tab (#1629)
* Edit window: Delete clears when the MIDI Editor is open behind another tab (#1627)

Delete deferred to the MIDI Editor whenever it was open in the layout with notes selected. Behind another tab its body isn't drawn, so its key handler never ran and Delete did nothing. It now defers only when the editor's body was drawn on the last frame (docking records its rect only then); otherwise it is Clear, as everywhere else in the Edit window.

* Edit window: Delete clears as soon as a tab covers the MIDI Editor, before the dock redraws

The MIDI body's rect is from the last dock pass, and a layout change between frames (a tab
moved over the editor) leaves it standing until the next one, which runs after the shortcuts.
Delete now also asks the stored layout whether the editor is in front.

* Edit window test: one Undo brings back every clip Delete cleared, by id

* fix: use layout() and craft_behavior PanelState for MIDI Delete

The docking layout field is private after merging main, and PanelState
moved to craft_behavior::dock, matching the nearby #214 tests.

* fix: install_headless in MIDI Delete tests that draw the dock

The two #1627 tests now call app_frame with the MIDI editor open.
Without install_headless, drawing the dock panics on dock.float_panel
(app-scope command state). The neighbouring tab-cover arrow test
already installs it.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 13:25:46 +01:00
1dc1aac99a feat(ui): make Preferences › Mixing › Sends Default to work (#1423) (#1428)
* feat(ui): make Preferences > Mixing > Sends Default to work (#1423)

The row was a disabled placeholder fixed at -inf dB. It is now a selector
with -inf dB and 0 dB, kept per machine like Levels of Undo: staged in the
Preferences window, applied on OK through a new ui.sends_default command, and
kept when a window configuration is recalled.

A send made from a Mix window send slot (a bus from the list or "new bus...")
starts at the chosen level. Re-targeting an existing send keeps its level.
The default stays -inf dB, so nothing changes for current users, and
mix.send without level_db is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ui): cover the Sends Default to row in the Preferences window (#1423)

Choosing 0 dB in the window applies on OK and is discarded on Cancel; the
draft follows a scripted ui.sends_default while the window is open; and
applying it does not dirty the session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ui): ui.set takes the same Sends Default to ids as ui.sends_default (#1423)

SendsDefault was stored and set through ui.set as "negative_infinity" and
"unity", while ui.sends_default takes "-inf" and "0". It now uses "-inf" and
"0" everywhere, like the other preferences whose stored names match their
command ids. A test checks ui.set accepts both and rejects bad values without
changing the setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ui): ui.sends_default rejects a level that is not a string (#1423)

A present but non-string `level` (e.g. `{"level": 0}`) read the value back
as if `level` were missing, so a script could think it set 0 dB while
nothing changed. No `level` still reads back; a string is parsed as before;
anything else is now an error. Found in review on #1428.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ui): ui.sends_default can switch back to -inf (#1423)

The command test only went from -inf to 0, so the `-inf` arm of
`SendsDefault::parse` was never exercised through `ui.sends_default`
(`ui.set` goes through serde instead). Switching back now has a check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: use egui::ComboBox for the Sends Default preference

craft_ui::ComboBox is gone after merging main; the other preference
dropdowns already use egui::ComboBox.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 12:50:59 +01:00
Dylan M. TaylorandFredApps 3988e34870 packaging: private certificate folder, bounded Flatpak tarball (#1317)
* packaging: keep the signing certificate in a private folder and bound the Flatpak tarball

* fix: parse flatpak archive size with tar --numeric-owner

GNU tar prints owner and group names unquoted, so a name with a
space shifts the size out of awk field 3 and the 2 GiB unpack
guard can fail open. Numeric IDs stay in one field.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 12:40:09 +01:00
mtlcl410andFredApps 0c22b29d4a Record a MIDI key held into the punch-in from the punch-in (#1845)
* Record a MIDI key held into the punch-in from the punch-in

A key pressed before the record range (during the pre-roll) and still
held when the range starts was left out of the take. Pro Tools records
it, with its start quantized to the punch-in point (Reference Guide
p.822). The take builder now follows the key presses before the range
and starts such a key at the first tick of the clip.

* Keep a punch-range note whose release is stamped before the range

A late audio callback can stamp the release of a key pressed in the
range before the range start. That entry was taken for pre-roll and the
note was dropped; it now ends the note at its press, as in the range.
Keys held into the range are told apart by their pre-range press sample.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 12:25:53 +01:00
mtlcl410andFredApps 213c6aa0e4 Shift+/ works from the keyboard: Shift chords match the key's position (#1827)
With Shift held, every platform reports the / key as `?` (egui Key::Questionmark), so the
registered "Shift+/" (Options > Link Timeline and Edit Selection) never matched a real key press;
only scripted `ui.key` presses, built from the shortcut string, did. When a Shift chord names no
command by its shifted character, the shortcut handler now looks it up again by the key's
punctuation position (`physical_key`).

Tests feed the events egui-winit sends for a real Shift+/ and a real Cmd+Shift+. (All MIDI Notes
Off, which must not nudge under Commands Keyboard Focus) on macOS, Windows and Linux.

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 12:14:22 +01:00
mtlcl410andFredApps c1a13d2e3e fix(playback): say when the device does not run at the chosen buffer size (#1762)
* fix(playback): say when the device does not run at the chosen buffer size

A buffer size outside the range the driver reports was accepted, then
replaced by the device's default without a word: `ui.audio_device` kept
the choice in `config` and showed a null `device.buffer_size`, and the
Playback Engine read "default buffer". On macOS an RME UFX's driver
allows 15–3072 frames, so 4096 opened at its default.

Keep the range the driver reports with the open output. `ui.audio_device`
returns it as `device.buffer_range`, both commands return a
`buffer_note` when the device does not run at the chosen size, and the
Playback Engine shows the note under Output. The size itself is still
not rounded, as G-01 describes.

The note has a pt-BR string, as every localized string does (every_localized_source_string_has_a_catalog_entry).

* docs: note the buffer size report in the G-01 gap and hardware parity

* Say which reply carries the driver's buffer range in the G-01 gap

* fix(playback): say a size inside the driver's range was refused, not outside it

buffer_note returned OutsideRange whenever the driver reported a range and
the device did not run at the chosen size, so a size inside the range that
still failed to open read "The device allows 15–3072 samples". Return
Refused when the range holds the size.

* docs: bring comments in line with the code

* fix(playback): say the buffer the device runs at, and 'runs only at' for a one-size device

A shared-mode WASAPI device reports a single size (its period, 480 frames
at 48 kHz), so the note read "The device allows 480–480 samples". It now
reads "The device runs only at 480 samples." The note also says the size
the open stream reports it runs at (Core Audio's device buffer, WASAPI's
period), and ui.audio_device returns it as device.buffer_running.

* docs: bring comments in line with the code

* fix(playback): note a buffer the device took but runs at another size

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 12:04:00 +01:00
mtlcl410andFredApps ef3b942d49 Make "no input" record and monitor nothing (#1853)
An audio track whose input is set to no input (`Route::None`) showed
"In 1" and still monitored and recorded hardware input 1, because the
mixer, the take planner and the input selector all read `Route::None` as
the default input. Pro Tools treats No Input as a track with no input
path (Reference Guide p.16, p.358).

- Monitoring a track with no input hears nothing, and a record pass
  writes digital silence for it.
- The input selector reads "no input" for `Route::None` on every
  non-MIDI track (an aux track read "no output" before).
- New audio tracks (Track > New, import to new tracks, Split into Mono,
  clip-group import) get their first input path explicitly: In 1,
  In 1-2, ... Pro Tools gives new tracks an input path (p.357).
- Sessions saved before this change used `Route::None` for input 1, so
  their audio tracks with `Route::None` are given In 1 / In 1-N when the
  engine takes them (open, recovery, Import Session Data). The engine
  marks the sessions it holds with the `io.none_is_no_input` flag, so a
  "no input" saved now stays "no input" after reopening.

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 11:52:25 +01:00
mtlcl410andFredApps 433c1d5b79 ASIO: close the old device before Apply or Reconnect opens the new one (#1872)
cpal 0.18.2 holds one ASIO driver per process. Apply and Reconnect
built the new player while the old one's stream still held the driver,
so the device list stopped at the first other driver: every second Apply
to ASIO4ALL, every switch from one ASIO driver to another, and Reconnect
on ASIO fell back to the silent clock.

On ASIO the old player now goes before the new one opens. Core Audio,
WASAPI, ALSA and JACK keep the old order (the new device opens while the
old one is still running), so Apply there is unchanged; closing first
would make Core Audio start the device cold and hold Apply on the UI
thread for about half a second.

Fixes #1864.

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 11:38:49 +01:00
Dylan M. TaylorandFredApps 6aa38dc14a AudioSuite: process each listed clip once, within a total budget (#1310)
* AudioSuite: process each listed clip once, within a total budget

A clip listed more than once in audiosuite.process was processed again
on its own result: the replacement keeps the clip id, so an expanding
process (time stretch, varispeed, pitch shift) compounded the clip's
length each time, and every intermediate result stayed in the source
pool for the rest of the command.

Deduplicate the clip ids, and before processing anything check each
clip's per-render limit and the projected output of all clips together
against MAX_RENDER_SAMPLES, the same total budget the signal generator
already uses.

* AudioSuite: budget pitch shift at its input length

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 11:26:49 +01:00
Dylan M. TaylorandFredApps 1f35225968 fix(log): escape control characters in log messages (#1335)
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 11:06:54 +01:00
c5b3732085 test(ui-egui): step bounce tests until the bounce ends, not until max_steps (#823) (#1728)
A bounce renders for a 30 ms wall-clock slice per frame, so a slow CPU
(the FreeBSD aarch64 CI job) needs more frames than the harness's
max_steps of 1000, and Harness::run panicked before the bounce finished.

The frames test now steps until `bounce` is none, under a shared
MAX_FRAMES cap of 100_000, before it calls run(). The hidden-window test
uses the same cap instead of 10_000. Production code is unchanged.

Under systemd-run CPUQuota=4% the frames test panicked with
"exceeded max_steps (1000)" before this change and passes after it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:57:45 +01:00
474719ed0e fix(ui): punching out keeps playback running (#1265) (#1591)
* fix(ui): punching out keeps playback running

* test(ui): punch-out asserts the take is placed, the punch clears and the playhead holds

finish_recording returned early when the recorder was already gone, leaving the
punch and take plan set and placing nothing; it now always clears the punch and
places what the plan's takes hold. The punch-out test writes a take file and
asserts the clip lands inside the punch range, the punch clears and the playhead
keeps its place; the stopped-recording test asserts the playhead is not reset.

* docs(ui): add docstring on finish_recording

* fix(ui): punch-out test encodes the take with the declared craft_audio crate

soundcraft_audio_io is not a dependency of soundcraft-ui-egui, so the
punch-out test's lib target could not compile under the gate. Switch the
fixture to craft_audio::EncodeOptions::new(EncodeFormat::Wav) and
craft_audio::encode, the same API soundcraft-engine::io uses, keeping
soundcraft_model::FileFormat::Wav for the session file format.

---------

Co-authored-by: rixpsed <183939167+rixpsed@users.noreply.github.com>
Co-authored-by: rixpsed <rixpsed@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:50:43 +01:00
58b3608bc5 Scale the To File Boundaries and To Fill Selection trims by clip stretch (#1732)
The mixer plays `offset + rel / stretch`, so on the timeline a stretched
clip's file starts `offset * stretch` before the clip and spans
`frames * stretch` samples. Both commands used the unscaled values, so
To File Boundaries on a 2x clip covering its whole file halved it and left
a non-zero source offset. A shared helper now gives the file's timeline
span with the same formula trim_clip uses.

Co-authored-by: lucasegen <281051305+lucasegen@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:41:19 +01:00
Jonathan CardosoandFredApps 7478ee70a7 mix.pan: a stereo track says which channel it pans (#1352)
* mix.pan: a stereo track says which channel it pans

A stereo track has a panner per channel. mix.pan defaulted index to 0, so
without it a stereo track moved only its left panner and folded the left
channel into the right. index is now required on stereo tracks, and an index
the track doesn't have (1 on a mono track, a non-number) is an error instead
of a silent no-op or 0.

* mix.pan: refuse a fractional index instead of rounding it

i64_or rounds, so index 1.4 picked the right panner. The number now has to be
whole first; 1.0 still counts as 1. null still means no index, as with slot.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:31:14 +01:00
grovebitandFredApps c217d5edf6 Pro Tools' Shift keys for Bypass Inserts and Mute Sends (#214)
* Pro Tools' Shift keys for Bypass Inserts and Mute Sends

Bind the keys the Pro Tools Shortcuts Guide (2025.6) gives for the
Track menu's Bypass Inserts and Mute Sends items:

- Bypass Inserts: All Shift+A, Inserts A-E Shift+2, F-J Shift+3,
  EQ Shift+E, Dynamics Shift+C, Reverb Shift+V, Delay Shift+D,
  Modulation Shift+W
- Mute Sends: All Shift+Q, Sends A-E Shift+4, F-J Shift+5

They are bare Shift chords, as in Pro Tools, and work the same on
Windows and Linux. Like every shortcut, they don't fire while a text
field has the keyboard.

Mute Sends > All now toggles when `mute` is omitted, like Sends A-E and
F-J, so a second Shift+Q unmutes the sends as in Pro Tools. Before, it
always muted.

* Shortcut test: assert Shift+E and Shift+C flip the EQ and the compressor

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:23:04 +01:00
70071415c9 fix(ui): ui.set keeps at most ten recent sessions (#924) (#1537)
* fix(ui): ui.set keeps at most ten recent sessions (#924)

`ui.set` stored a `recent_sessions` list of any length and it was saved
to ui.json. It now keeps the newest ten (`MAX_RECENT`), the same way it
clamps `undo_levels`, and the answer shows the kept list. A saved state
that already holds more is cut on the first frame, next to the existing
`undo_levels` clamp.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(ui): save the recent list when a loaded one is cut (#924)

Cutting an oversized saved list on the first frame changed it in memory
only, so ui.json kept the long list until a clean exit. It now raises
the recent-list save signal, and only when entries were removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:14:38 +01:00
e14357eff7 fix(engine): clippy and the movie relink test pass on Windows (#1535) (#1536)
* fix(engine): clippy and the movie relink test pass on Windows (#1535)

`cargo xtask ci` stopped on Windows at two clippy errors and one test:

- `create_unique_folder` only mutates its `DirBuilder` on Unix, so the
  `mut` is unused elsewhere. Allowed off Unix, as before (#571, #1017).
- `exclusive_tests` holds only Unix tests, so its `scratch` helper was
  dead code on Windows. The module is now Unix-only.
- `each_movie_is_kept_relinked_or_offline` built the expected path with
  `join("Video Files/filed.mov")`, which keeps the `/`; `relink_videos`
  joins part by part. The test now does the same.

No behaviour change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(engine): keep exclusive_tests under a plain cfg(test) (#1535)

`#[cfg(all(test, unix))]` stopped clippy from seeing the module as test
code, so on Unix `unwrap_used` fired in its `scratch` helper
(`allow-unwrap-in-tests` only looks for a plain `#[cfg(test)]`). The
two conditions are now separate attributes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 10:05:51 +01:00
MexandFredApps fdfe5aed76 i18n: give the file path field its own label (#1688)
* Give the file path field its own translation key

* Translate the SoundCraft file path label in Portuguese

* Translate the SoundCraft folder path label

* Use the folder path label for directory prompts

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:55:54 +01:00
91123a1b77 The Strip Silence button is its own localized string (#1695)
"Strip" was one key for the Strip Silence dialog's action button and
the Channel Strip plug-in's short name, so a translation had to pick
one word for both. The button now uses the dialog's own "Strip
Silence" key (Portuguese "Remover silêncio") and the plug-in keeps
"Strip" ("Canal").

Co-authored-by: midasmatterhorn <236787783+midasmatterhorn@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:47:06 +01:00
MexandFredApps e336e68449 docs: clarify video list availability and playback status (#1693)
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:38:17 +01:00
MexandFredApps 78dfb59b3b docs: align SoundCraft downloads with published packages (#1697)
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:29:31 +01:00
MexandFredApps 8b929d81b1 fix(cli): preserve existing conversion part files (#1691)
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:19:35 +01:00
MexandFredApps 7f8f278b8a fix(cli): accept UTF-8 BOM in script files (#1696)
* fix(cli): accept UTF-8 BOM in script files

Strip BOM from script file content if present.

* Test a script starting with a UTF-8 BOM

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:11:56 +01:00
MexandFredApps 0fce3e7aba Route SoundCraft CLI scroll and zoom to the UI handlers (#1698)
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 09:02:00 +01:00
FredApps 0894e882b8 soundcraft-cli: --version and -V on every subcommand (RFC-0018 rule 1.1) (#1851) 2026-11-28 08:54:21 +01:00
FredApps 4f91806d62 parity: headless column from the engine registry (RFC-0052) (#1871) 2026-11-27 23:14:32 +01:00
Dylan M. TaylorandFredApps 8f20500c9d ci: notify artcraft-services on release state changes (#1854)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-27 09:17:52 -05:00
skylar taylor-barrick 81766eebb6 test(clap): use portable descriptor readiness fixture (#1795) 2026-11-26 08:44:29 -06:00
FredApps f07dc9e221 Merge pull request #1581 from gmrmad1/fix/markers-add-kind
markers: reject an unknown marker kind in markers.add
2026-11-26 13:35:43 +01:00
FredApps 580ba762b0 Merge branch 'main' into fix/markers-add-kind 2026-11-26 13:27:43 +01:00
FredApps 2b21bf0853 Merge pull request #1579 from gmrmad1/fix/import-audio-track-kind
io: refuse a non-audio target track for audio import
2026-11-26 13:25:08 +01:00
FredApps 441a356994 Merge branch 'main' into fix/import-audio-track-kind 2026-11-26 13:15:30 +01:00
FredApps dd70599e24 Merge pull request #1578 from gmrmad1/fix/clip-loop-count-cap
clip: allow up to 1000 loops in Clip Looping
2026-11-26 10:07:54 +01:00
FredApps c65ae92001 Merge pull request #1682 from istefp/feat/failed-plugin-retry
mix: a plugin failed twice stays failed — one reset retry per slot (#919)
2026-11-26 10:07:24 +01:00
FredApps a92536f992 Merge pull request #1692 from MMexicann/patch-4
Reject invalid target playlist indexes before changing tracks
2026-11-26 10:05:28 +01:00
skylar taylor-barrick 417a326b90 Nightly: stop blocking a refused launch on macOS (#1803)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list where that applied, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2).
2026-11-26 00:47:18 -06:00
aiongg af9f2109ff Merge pull request #1738 from aiongg/minimal-port-next
SoundCraft: move to craft-libs next (minimal port)
2026-11-25 23:08:34 -05:00
skylar taylor-barrick b0562cbce0 Switch on supervised nightlies on the nightly-signer branch (#1800)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 20:45:15 -06:00
skylar taylor-barrick 97e38ba3c3 Use the shared nightly launcher template (#1787)
Renders the plain nightly tar's launcher from craft-common-actions' shared template.

Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5.
2026-11-25 16:17:35 -06:00
aiongg de4c997d6e Docking test: the MIDI editor's tab adds 28 points in the default layout 2026-11-25 21:07:34 +00:00
aiongg fcc4b98745 The MIDI editor keeps its body's height under the 28-point tab strip 2026-11-25 20:44:58 +00:00
aiongg 481b7e6a68 Floating windows carry the running channel's app id 2026-11-25 20:08:38 +00:00
aiongg 0321122ad4 The send menu stays on the side it opened on 2026-11-25 20:08:38 +00:00
aiongg a587aadec5 Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:24 +00:00
aiongg cb0c7395d8 A press in the focused session view asks for no focus again 2026-11-25 15:50:03 +00:00
aiongg 6338349f88 Repin craft-libs to storytold next aa401985d 2026-11-25 15:50:03 +00:00
aiongg e652100a53 The Mix window's Tab test lists both windows in each input, as eframe does 2026-11-25 14:35:27 +00:00
aiongg 528c245e6f The session view: no Tab trap in the Mix window, focus back after dialogs, held Tab stays 2026-11-25 14:09:08 +00:00
aiongg 84e07209a6 The canvas is one real Tab stop and takes the keyboard when pressed
The session view (the Edit window's tracks and timeline, the Mix window's strips) is declared as the host canvas with the
id of its own widget, so egui keeps the focus Tab gives it. A press in it and a view that opens or shows another document
give it the focus; a text field, a dialog or a menu keeps it. The focused view keeps Tab only while edit.tab has a stop
ahead, and leaves the keyboard to the shortcuts.
2026-11-25 13:57:53 +00:00
aiongg 5e0b41d291 Allow egui::ComboBox: craft-libs next has no drop-in craft_ui::ComboBox 2026-11-25 13:55:03 +00:00
aiongg d0c27acc5d Repin craft-libs to storytold d1bdf8e5da (craft-libs#3505 head); egui stays at storytold b15ffe9bfc 2026-11-25 13:43:14 +00:00
aiongg 30afd14075 Repin craft-libs to storytold next 980669cdce and egui to storytold b15ffe9bfc 2026-11-25 13:42:40 +00:00
aiongg 92894ee20a Merge main into minimal-port-next
Conflicts: Cargo.toml (kept the port's craft-libs dependency lines, craft-update feature ui and the host crates; main's rev bumps dropped), Cargo.lock (took the branch's).
2026-11-25 13:41:14 +00:00
Dylan M. Taylor 768c0f972d packaging(linux): support co-installable nightly packages (#1740)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-24 18:55:08 -06:00
aiongg 8f513c84c2 Repin craft-libs to 2f8d73e7cf; pass the app icon to the host; unbind the runtime's Quit for app.quit 2026-11-24 15:59:30 +00:00
FredApps 0c9c1b8ef6 Merge pull request #1733 from FredApps/imo778-aaf-linked-descriptors
interchange: read AAF WAVE and PCM descriptors through craft-aaf (craft-libs#778)
2026-11-24 14:57:08 +01:00
FredApps 66b8e9ad42 interchange: refuse physical track 1 of a stereo source on later edits too 2026-11-24 14:46:03 +01:00
FredApps daf06dfd7e interchange: read AAF WAVE and PCM descriptors through craft-aaf (craft-libs#778)
Open FilmCraft-style AAFs that reference one external mono PCM WAV per
channel. The file descriptor's class, SampleRate, Length and declared PCM
channel count come from craft_aaf::aaf::linked_audio (craft-libs#3180);
locators, slot policy and limits stay here.
2026-11-24 14:36:02 +01:00
aiongg f892550c91 Round 5: craft-libs 48e798653c; pane-key overrides by NavCommand id, so F6 reaches the Trim tool
SoundCraft unbound "window.nextPane"/"window.previousPane", but the commands' ids are
window.next_pane/window.previous_pane. The keymap skips an override key it cannot resolve, so
F6 stayed the pane move and the key stage took it out of egui's events. The overrides now use
NavCommand::NextPane.id() and NavCommand::PreviousPane.id().

The trackpad rig gets frame(events), and a test presses F6 from the keyboard and through the
control channel's ui.key and expects the Trim tool. cargo fmt on control.rs and fonts.rs.
2026-11-24 00:47:23 +00:00
aiongg 005150eb6d Round 4: semibold family in fonts::install, ui.key acknowledged by the runtime's injected-input idle signal 2026-11-24 00:09:16 +00:00
aiongg 8ebbad7c32 Trackpad test rig hands the runtime SoundCraft's frame input, as the shells do 2026-11-23 23:31:07 +00:00
aiongg 6fbaec65e8 Round 2 on craft-libs next-host-input: host canvas claims Alt+1-4, host_body panels, no Ctrl+wheel pinch 2026-11-23 23:25:30 +00:00
aiongg 404d49e0a9 Test round 1: app style for the dock's views, pinch-folded Ctrl+wheel acknowledged, font-load discard pass in the gate test, Id::unique 2026-11-23 22:41:38 +00:00
aiongg 5f0fe9bfb2 Root window handed to the runtime as a shared reference 2026-11-23 22:29:07 +00:00
aiongg 77c125f564 rustfmt the ported files 2026-11-23 22:28:20 +00:00
aiongg 55078b0f23 Tests on next: runtime installed in the UI harnesses, dock tests on commands and the model, renderer gesture tests removed 2026-11-23 22:26:48 +00:00
aiongg a86949df15 Minimal port to craft-libs next: runtime host, DockArea dock, app-local icon buttons, capture slot and send menu, update dialogs on the DialogHost 2026-11-23 22:22:14 +00:00
aiongg 4f7bb6796d probe: Node::Dock side is DockEdge 2026-11-23 21:46:16 +00:00
aiongg 72b061f31e probe: mechanical codemod for next 2026-11-23 21:41:44 +00:00
aiongg fbf3bcd7a4 probe: repin craft-libs to next 2026-11-23 21:41:19 +00:00
FredApps b34b86fd7e Resolve clip looping conflicts with main 2026-11-23 10:20:05 +01:00
Mex 733a17ffa6 Reject invalid target playlist indexes before changing tracks 2026-11-21 18:56:46 +01:00
Stefan Pantic 1b2c087f29 mix: a re-failed plugin stays failed, one reset retry per slot (#919) 2026-11-20 19:09:34 -05:00
gmrmad1 2d8931da1d review: reject a non-string markers.add kind instead of treating it as omitted (coderabbitai/non-string-kind) 2026-11-16 19:52:45 +05:30
Madhav Agarwal d516f2c1d1 markers: reject an unknown marker kind in markers.add 2026-11-15 19:14:42 +05:30
Madhav Agarwal c582bcb4d2 io: refuse a non-audio target track for audio import 2026-11-15 17:44:33 +05:30
Madhav Agarwal 27b0373761 clip: allow up to 1000 loops in Clip Looping (#G-04) 2026-11-15 15:54:30 +05:30
250 changed files with 17940 additions and 1718 deletions
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/soundcraft",
"repository_id": 1408486424,
"producer_workflow_id": 429730684,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "soundcraft-nightly-20261124",
"repository": "storytold/soundcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135771,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_soundcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_soundcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+251
View File
@@ -0,0 +1,251 @@
name: Nightly build check
# Builds the isolated Nightly flavor on all three platforms without secrets and checks each
# archive as the Launcher unpacks it. The real feed build and its signing live in the shared
# producer and release-ref signer (craft-common-actions), which call the same app scripts; this
# workflow exists so the three packaging paths are exercised on PRs and by hand.
#
# macOS runners are shared with release builds: the macOS leg runs only with the `full-ci` label
# (as ci.yml's Windows legs), never by changed paths.
on:
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. An event that will not build gets a group of
# its own, so it never cancels a real build.
concurrency:
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
linux:
name: Nightly Linux x86_64 (unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: ubuntu-latest
timeout-minutes: 60
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the desktop build dependencies
run: sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "SOUNDCRAFT_BUILD_SHA=$sha"
echo "SOUNDCRAFT_BUILD_DATE=$date"
echo "SOUNDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the GUI-only Nightly tar
env:
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
run: bash packaging/linux/nightly.sh --arch x86_64
- name: Check the archive and the isolated launch protocol
env:
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
run: |
set -euo pipefail
tz="$(mktemp -d)"
archive="$RUNNER_TEMP/nightly-dist/soundcraft-$SOUNDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
mkdir -p "$tz" && tar -xzf "$archive" -C "$tz"
# Flat, allowlisted members only: the launcher, the GUI it starts, the Nightly icon and
# the notices.
members="$(tar -tzf "$archive" | grep -v '/$' | sort | tr '\n' ' ')"
echo "$members"
case "$members" in *soundcraft-cli*|*portable.txt*|*.desktop*) echo 'GUI-only tar contains a CLI, marker or desktop entry' >&2; exit 1;; esac
test -x "$tz/soundcraft"
test -x "$tz/soundcraft-bin"
# The entry point is the launcher; the GUI beside it is what a launch starts with the
# profile, so an unpacked tar is isolated too.
head -n 1 "$tz/soundcraft" | grep -qx '#!/bin/sh' || { echo 'soundcraft is not the launcher' >&2; exit 1; }
test -f "$tz/soundcraft-nightly.png"
# The version query, plain and in the Launcher's form, with an empty environment (a shell
# script needs PATH for dirname/readlink even when everything else is cleared).
path=/usr/local/bin:/usr/bin:/bin
home="$(mktemp -d)"; profile="$(mktemp -d)"; xdg="$(mktemp -d)"
plain="$(env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" XDG_DATA_HOME="$xdg/d" XDG_CACHE_HOME="$xdg/k" XDG_STATE_HOME="$xdg/s" "$tz/soundcraft" --version)"
test "$plain" = "SoundCraft $SOUNDCRAFT_VERSION (nightly-v1)" || { echo "plain query: $plain" >&2; exit 1; }
launcher="$(env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" "$tz/soundcraft" --launch-profile nightly-v1 --profile-root "$profile" --version)"
test "$launcher" = "SoundCraft $SOUNDCRAFT_VERSION (nightly-v1)" || { echo "launcher query: $launcher" >&2; exit 1; }
# A native package refuses a Flatpak instance with exit status 2 (the same status whether or
# not a display exists), and no stable folder is created.
status=0
env -i PATH="$path" HOME="$home" XDG_CONFIG_HOME="$xdg/c" FLATPAK_ID=ai.storyteller.soundcraft "$tz/soundcraft" --launch-profile nightly-v1 --profile-root "$(mktemp -d)/p" -- >/dev/null 2>&1 || status=$?
test "$status" -eq 2 || { echo "a Flatpak instance must be refused with exit status 2, got $status" >&2; exit 1; }
# Look where the configured XDG folders actually point, not at $xdg/config and $xdg/data.
for dir in "$xdg/c" "$xdg/d" "$xdg/k" "$xdg/s"; do test ! -e "$dir/soundcraft" || { echo "stable folder created: $dir/soundcraft" >&2; exit 1; }; done
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: soundcraft-nightly-linux-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
if-no-files-found: error
retention-days: 7
compression-level: 0
windows:
name: Nightly Windows x86_64 (unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: windows-latest
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Prepare a Nightly identity for this commit
shell: pwsh
run: |
$inPkg = $false
$base = $null
foreach ($line in Get-Content Cargo.toml) {
if ($line -match '^\s*\[') { $inPkg = ($line.Trim() -eq '[workspace.package]'); continue }
if ($inPkg -and $line -match '^\s*version\s*=\s*"([^"]+)"') { $base = $Matches[1].Split('-')[0]; break }
}
if (-not $base) { throw 'could not read [workspace.package] version from Cargo.toml' }
$sha = (git rev-parse HEAD).Trim()
$date = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd')
$version = "$base-nightly.$($date.Replace('-','')).$env:GITHUB_RUN_NUMBER.$env:GITHUB_RUN_ATTEMPT.g$($sha.Substring(0,12))"
"SOUNDCRAFT_BUILD_SHA=$sha" >> $env:GITHUB_ENV
"SOUNDCRAFT_BUILD_DATE=$date" >> $env:GITHUB_ENV
"SOUNDCRAFT_VERSION=$version" >> $env:GITHUB_ENV
- name: Refuse signing material in the build environment
shell: pwsh
run: ./packaging/windows/sign.ps1 -CheckBuildEnvironment
- name: Build the GUI-only Nightly intermediate
shell: pwsh
env:
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly
- name: Check the PE, the version and the archive payload
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$exe = Join-Path $env:RUNNER_TEMP 'nightly-targets/x86_64-pc-windows-msvc/release/soundcraft.exe'
$bytes = [IO.File]::ReadAllBytes($exe)
$pe = [BitConverter]::ToInt32($bytes, 0x3C)
if ([BitConverter]::ToUInt16($bytes, $pe + 4) -ne 0x8664) { throw 'not an x86_64 executable' }
if ([BitConverter]::ToUInt16($bytes, $pe + 0x5C) -ne 2) { throw 'not a Windows GUI subsystem executable' }
$info = (Get-Item -LiteralPath $exe).VersionInfo
if ($info.ProductName -ne 'SoundCraft Nightly') { throw "ProductName: $($info.ProductName)" }
if ($info.ProductVersion -cne $env:SOUNDCRAFT_VERSION) { throw "ProductVersion: $($info.ProductVersion)" }
$version = (& $exe --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0 -or $version -cne "SoundCraft $env:SOUNDCRAFT_VERSION (nightly-v1)") { throw "version query: $version" }
$profile = Join-Path $env:RUNNER_TEMP 'nightly-profile'
New-Item -ItemType Directory -Force -Path $profile | Out-Null
$launcher = (& $exe --launch-profile nightly-v1 --profile-root $profile --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0 -or $launcher -cne "SoundCraft $env:SOUNDCRAFT_VERSION (nightly-v1)") { throw "launcher query: $launcher" }
# A Nightly build without its profile is refused before any window (exit status 2). The
# refusal dialog would need a desktop, so that path is covered by the Rust unit tests.
$zip = Join-Path $env:RUNNER_TEMP "nightly-dist/soundcraft-$env:SOUNDCRAFT_VERSION-windows-x86_64-nightly.unsigned.zip"
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
try {
$names = @($archive.Entries | ForEach-Object { $_.FullName })
if ('soundcraft.exe' -notin $names) { throw 'no soundcraft.exe in the archive' }
foreach ($forbidden in @('soundcraft-cli.exe', 'portable.txt', '.desktop')) {
if (@($names | Where-Object { $_ -like "*$forbidden*" }).Count -ne 0) { throw "archive holds $forbidden" }
}
} finally { $archive.Dispose() }
- name: Fixture suites
shell: pwsh
run: |
./packaging/windows/nightly-package-tests.ps1 -FixtureRoot (Join-Path $env:RUNNER_TEMP 'nightly-fixtures')
./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot (Join-Path $env:RUNNER_TEMP 'nightly-sign-fixtures')
- name: Keep the unsigned intermediate
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: soundcraft-nightly-windows-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
macos:
name: Nightly macOS aarch64 (unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@main
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "SOUNDCRAFT_BUILD_SHA=$sha"
echo "SOUNDCRAFT_BUILD_DATE=$date"
echo "SOUNDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
SOUNDCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle's version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/soundcraft-$SOUNDCRAFT_VERSION-macos-aarch64-nightly.zip"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: soundcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/soundcraft-${{ env.SOUNDCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+59
View File
@@ -0,0 +1,59 @@
name: SoundCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: soundcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/soundcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: main
app-name: soundcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+35
View File
@@ -0,0 +1,35 @@
name: SoundCraft unsigned nightly
# 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:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/soundcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: main
app-name: soundcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+20
View File
@@ -49,3 +49,23 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-synthetic-suites:
# The macOS and Windows Nightly scripts, the flat Linux archive and its launchers, and the
# shared caller contracts run as generated fixtures in seconds: no app build, no signing, no
# secrets.
name: Nightly synthetic suites (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run the synthetic suites, the launcher tests and bash -n
run: bash packaging/nightly-checks.sh
+8
View File
@@ -10,3 +10,11 @@ plan/
/craft-fonts/
plans/
.DS_Store
__pycache__/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
/craft-fonts
-69
View File
@@ -1,69 +0,0 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**SoundCraft** (`storytold/soundcraft`) is an open-source digital audio workstation (DAW) written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `soundcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/soundcraft`](https://github.com/storytold/soundcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/soundcraft`](https://github.com/storytold/soundcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/soundcraft`](https://github.com/storytold/soundcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
+1
View File
@@ -81,6 +81,7 @@ Layers, checked by `cargo xtask layers`; nothing below L6 depends on egui, efram
- Audio formats, codecs and waveform peaks come from `craft-audio` in `storytold/craft-libs`; `soundcraft_model::FileFormat` maps them onto the session model.
- Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`), each module with its own `specs()` registered in `crates/engine/src/cmd.rs`; UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Menus, shortcuts, CLI, control channel and MCP dispatch the same ids. Panels act through `engine.execute(id, params)`. Programmatic calls open no dialogs; `ui.menu.invoke` does.
- Parity: `crates/engine/catalog/menus.txt` lists the reference menu leaves; `cargo xtask parity` writes `docs/parity-checklist.md`; a test enforces a floor that only rises.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): the parity report marks a leaf `headless: yes` only when the engine registry implements it (what `soundcraft-cli` and the MCP server load); the UI layer's `parity_with` extras never count. Other leaves take their `no`/`partial` value and `reach:` (`window`, `os`, `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or read `unknown`. When a command lands, drop or narrow its mark; `headless_marks_are_current` fails on one that only hides a `yes`.
- Progress docs: `ROADMAP.md`, `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md` and the per-area `docs/*-parity.md`. Releases: `docs/releasing.md` (push to `release`; `cargo xtask version [set X.Y.Z]`). Control protocol: `docs/control-protocol.md`.
### Checks
+4
View File
@@ -54,4 +54,8 @@ here. The subset uses default_fonts; the parent face uses monochrome_emoji_fonts
| `assets/app-icon/soundcraft.icns` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
| `assets/app-icon/soundcraft.ico` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
| `assets/app-icon/hicolor/` | SoundCraft contributors | original, rendered from `icon.svg` (16–512 px PNGs and the scalable SVG) | MIT OR Apache-2.0 |
| `assets/app-icon/soundcraft-nightly.png` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
| `assets/app-icon/soundcraft-nightly-macos-512.png` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
| `assets/app-icon/soundcraft-nightly.icns` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
| `assets/app-icon/soundcraft-nightly.ico` | SoundCraft contributors | original, rendered from `icon.svg` with the Nightly badge | MIT OR Apache-2.0 |
| `docs/images/` | SoundCraft contributors | screenshots of SoundCraft rendered from the synthesised demo session | MIT OR Apache-2.0 |
Generated
+1306 -82
View File
File diff suppressed because it is too large Load Diff
+35 -28
View File
@@ -11,9 +11,9 @@ rust-version = "1.95"
repository = "https://github.com/storytold/soundcraft"
[workspace.dependencies]
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-score = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# internal
soundcraft-interchange = { path = "crates/interchange" }
soundcraft-time = { path = "crates/time" }
@@ -61,27 +61,34 @@ cpal = "0.18"
midir = "=0.11.1"
# Which file paths stored in a session may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Video containers and bitstreams, shared with the other craft apps.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# H.264 and ProRes codecs shared with the other Craft apps.
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["h264-decode", "prores", "mjpeg"] }
# Audio file formats, codecs and waveform overviews, shared with the other craft apps. It shares
# types with craft-media, so both stay on one rev.
# Standard MIDI Files and the note/controller model, shared with the other craft apps.
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-midi = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["serde"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["decode", "lossless-encode", "peaks", "serde"] }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# AAF property-stream framing, shared with the other craft apps.
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-aaf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["egui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb" }
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a3fca1707941bce4768586661ccbb94c44ee46eb", features = ["serde"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode
# the framework's components draw in (craft-libs).
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
egui = { version = "0.37" }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -124,18 +131,18 @@ debug = 0
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+27 -3
View File
@@ -88,7 +88,7 @@ where things are.
</tr>
<tr>
<td><b>Automation and markers.</b> Breakpoint automation for volume, pan, mute, sends and every plugin parameter, written live in Write, Touch and Latch, plus memory locations and a big counter.</td>
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64, x86, Arm), Linux (AppImage, deb, rpm, Flatpak), FreeBSD, and a WebAssembly build that runs in the browser.</td>
<td><b>Everywhere.</b> Signed builds for macOS (universal), Windows (x64 and ARM64), Linux (AppImage, deb, rpm, Flatpak, Arch), FreeBSD, and a WebAssembly build that runs in the browser.</td>
</tr>
<tr>
<td width="50%"><img alt="The Video window showing a colour-bar test movie with a timecode burn-in, above a Video track with thumbnails in the Edit window" src="docs/images/video.png"></td>
@@ -302,7 +302,9 @@ very welcome, in the issues or on Discord.
|---|---|---|
| x64 (64-bit Intel/AMD) | `soundcraft-<ver>-windows-x64.msi` | `soundcraft-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `soundcraft-<ver>-windows-arm64.msi` | `soundcraft-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `soundcraft-<ver>-windows-x86.msi` | `soundcraft-<ver>-windows-x86-portable.zip` |
For 32-bit Windows, [SoundCraft v0.18.0](https://github.com/storytold/soundcraft/releases/tag/v0.18.0)
was the last release with both an x86 MSI and portable ZIP.
Installers and executables are code-signed.
@@ -340,15 +342,19 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
| Flatpak | `soundcraft-<ver>-linux-x86_64.flatpak` | `soundcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `soundcraft-<ver>-linux-x86_64.deb` | `soundcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `soundcraft-<ver>-linux-x86_64.rpm` | `soundcraft-<ver>-linux-aarch64.rpm` | |
| Arch Linux | `soundcraft-<ver>-linux-x86_64.pkg.tar.zst` | `soundcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
| Tarball | `soundcraft-<ver>-linux-x86_64.tar.gz` | `soundcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64): `soundcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (glibc 2.39+, e.g. Ubuntu 24.04).
RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
`soundcraft-<ver>-linux-riscv64.rpm`, and `soundcraft-<ver>-linux-riscv64.tar.gz`
(glibc 2.39+, e.g. Ubuntu 24.04).
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `soundcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 (ARM64) | `soundcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
@@ -356,6 +362,24 @@ RISC-V (riscv64): `soundcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (glibc
|---|---|---|
| Static site | `soundcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
### Nightly (ArtCraft Launcher only)
A separate build channel, `nightly-v1`, ships untested previews of main. It is a different app
with a different identity, installed and updated by ArtCraft Launcher:
| | |
|---|---|
| Package, macOS bundle and Linux identity | `ai.storyteller.soundcraft.nightly` |
| Window app id and Windows taskbar id | `ai.storyteller.soundcraft.nightly-v1` |
| Data (settings, autosaves, presets, logs) | the Launcher's `profiles/soundcraft` folder, never the stable one |
| Launch | `soundcraft --launch-profile nightly-v1 --profile-root <dir> -- <files>` |
| Version | `soundcraft --version` → `SoundCraft <x.y.z>-nightly.<date>.<run>.<attempt>.g<sha12> (nightly-v1)` |
It carries no updater, control server or file associations, and it refuses to start without its
profile. Build artifacts are `soundcraft-<ver>-{windows-x86_64-nightly.zip,linux-x86_64-nightly.tar.gz,macos-aarch64-nightly.zip}`,
made by `packaging/windows/nightly.ps1`, `packaging/linux/nightly.sh` and `packaging/macos/nightly.sh`;
see `docs/nightly-release-preparation.md`. Nothing is enabled yet.
## The Crafting Apps
SoundCraft is one of the **Crafting Apps**: free, open-source creative tools from the
+6 -4
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (Languages table: Spanish full; previously trivial: French and Spanish partial; previously minor: long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
@@ -87,10 +87,10 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
|---|---|---|---:|
| English | en | full | 100 % |
| Simplified Chinese | zh-Hans | none | 0 % |
| Spanish | es | none (PR #143 open) | 0 % |
| Spanish | es | full — 100 % of fixed UI strings and engine errors; tests pass | 100 % (native-speaker review done) |
| Hindi | hi | none | 0 % |
| Arabic | ar | none | 0 % |
| French | fr | none (PR #143 open) | 0 % |
| French | fr | partial — catalog of 1,368 strings, the rest in English | ≈ 62 % |
| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
| Indonesian | id | none | 0 % |
| Japanese | ja | none | 0 % |
@@ -98,7 +98,7 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
| Korean | ko | none | 0 % |
| Vietnamese | vi | none | 0 % |
Other languages shipped: 0 complete. Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
Other languages shipped: Spanish complete (fixed UI strings and engine errors, native-speaker review). French is partial (≈ 62 %). Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
## Upcoming
@@ -189,6 +189,8 @@ mutated and truncated movies. Field reports from the first public week are track
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | trivial | Languages table: Spanish catalog complete with native-speaker review. Estimates unchanged |
| 2026-11-24 | trivial | Languages table: French and Spanish catalogs, partial (≈ 62 %), PR #143. Estimates unchanged |
| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged |
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
+10 -1
View File
@@ -22,9 +22,12 @@ fn is_control_method(method: &str) -> bool {
| "ui.move"
| "ui.click"
| "ui.drag"
| "ui.scroll"
| "ui.zoom"
| "ui.key"
| "ui.text"
| "ui.screenshot"
| "audio.health"
| "app.quit"
)
}
@@ -65,8 +68,14 @@ mod tests {
assert_eq!(m, "engine.execute");
let (m, _) = app_request("track.new", json!({}));
assert_eq!(m, "engine.execute");
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "audio.health", "app.quit"] {
assert_eq!(app_request(method, json!({})).0, method);
}
for (method, params) in [
("ui.scroll", json!({"x": 120, "y": 80, "dx": 5, "dy": -15, "unit": "line"})),
("ui.zoom", json!({"x": 120, "y": 80, "factor": 1.5, "steps": 4})),
] {
assert_eq!(app_request(method, params.clone()), (method.to_string(), params));
}
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ fn write_help() -> &'static str {
/// soundcraft-cli: SoundCraft without a window
#[derive(Parser)]
#[command(name = "soundcraft-cli", version = long_version(), arg_required_else_help = true)]
#[command(name = "soundcraft-cli", version = long_version(), propagate_version = true, arg_required_else_help = true)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
+5 -2
View File
@@ -40,9 +40,12 @@ pub(crate) fn parity(args: &ParityArgs, out: &mut dyn Write) -> Result<(), CliEr
for m in p["per_menu"].as_array().cloned().unwrap_or_default() {
md.push_str(&format!("| {} | {} | {} |\n", m["menu"].as_str().unwrap_or(""), m["implemented"], m["total"]));
}
md.push_str(&format!("\n{}\n", soundcraft_engine::catalog::headless_summary_line(&p)));
md.push_str("A leaf the engine implements is `headless: yes`: `soundcraft-cli` and the MCP server load that registry. The rest carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n");
md.push_str("\n## Not yet implemented\n\n");
for m in p["missing"].as_array().cloned().unwrap_or_default() {
md.push_str(&format!("- {}\n", m.as_str().unwrap_or("")));
for m in p["headless_missing"].as_array().cloned().unwrap_or_default() {
let reach = m["reach"].as_str().map(|r| format!(", reach: {r} ({})", m["why"].as_str().unwrap_or(""))).unwrap_or_default();
md.push_str(&format!("- {}: headless: {}{reach}\n", m["path"].as_str().unwrap_or(""), m["headless"].as_str().unwrap_or("")));
}
if let Some(path) = &args.write {
std::fs::write(path, &md).map_err(|source| CliError::File { path: path.clone(), source })?;
+2 -1
View File
@@ -73,10 +73,11 @@ fn at_rate(pos: u64, from: u32, to: u32) -> u64 {
fn write_replacing(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
let name = target.file_name().map_or_else(|| "output".into(), |n| n.to_string_lossy().into_owned());
let tmp = target.with_file_name(format!(".{name}.{}.part", std::process::id()));
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
let written = (|| {
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, target)
})();
if written.is_err() {
+52
View File
@@ -29,6 +29,24 @@ use info::info;
use mcp::mcp;
use session::{run_cmds, script};
/// A Launcher-only protocol argument, in either the separate or the `=` form. Everything after
/// `--` is a file name, so it is not inspected.
fn launcher_protocol_flag(args: &[OsString]) -> Option<&'static str> {
for arg in args {
if arg == "--" {
break;
}
let text = arg.to_string_lossy();
if text == "--launch-profile" || text.starts_with("--launch-profile=") {
return Some("--launch-profile");
}
if text == "--profile-root" || text.starts_with("--profile-root=") {
return Some("--profile-root");
}
}
None
}
/// The command line's clap definition.
pub fn command() -> clap::Command {
Cli::command()
@@ -44,6 +62,12 @@ where
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
// The Launcher's Nightly protocol belongs to the GUI alone. Refuse it here, with a usage error,
// before the subcommand is parsed: `soundcraft-cli` never opens a profile root or a window.
if let Some(flag) = launcher_protocol_flag(&args) {
let _ = writeln!(err, "soundcraft-cli: {flag} belongs to SoundCraft Nightly; this is the command-line tool");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match parse(&args) {
Ok(cli) => cli,
@@ -81,3 +105,31 @@ fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Resul
}
Ok(())
}
#[cfg(test)]
mod launcher_protocol_tests {
use super::*;
#[test]
fn the_launcher_only_protocol_is_a_usage_error_not_a_file() {
for args in [
vec!["--launch-profile", "nightly-v1", "--profile-root", "/tmp/profile", "--", "song.scraft"],
vec!["--launch-profile=nightly-v1"],
vec!["--profile-root=/tmp/profile"],
vec!["convert", "in.wav", "--launch-profile", "nightly-v1"],
] {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = run(args.iter().map(OsString::from), &mut out, &mut err);
assert_eq!(code, 2, "{args:?}");
let message = String::from_utf8_lossy(&err);
assert!(message.contains("SoundCraft Nightly"), "{args:?}: {message}");
}
}
#[test]
fn everything_after_the_delimiter_is_a_file_name() {
let args: Vec<OsString> = ["convert", "--", "--launch-profile", "--profile-root=./x"].map(OsString::from).to_vec();
assert_eq!(launcher_protocol_flag(&args), None);
assert_eq!(launcher_protocol_flag(&[OsString::from("--profile-root"), OsString::from("/p")]), Some("--profile-root"));
}
}
+1
View File
@@ -73,6 +73,7 @@ pub(crate) fn run_cmds(args: &RunArgs, out: &mut dyn Write, err: &mut dyn Write)
pub(crate) fn script(args: &ScriptArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
let path = &args.file;
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let mut e = load_engine(&args.engine, err)?;
let keep = args.keep_going;
let mut failed = false;
+13
View File
@@ -89,6 +89,19 @@ fn version_flags_print_the_long_version_to_stdout() {
}
}
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
/// return without running it (`mcp` and `app` would otherwise wait on something).
#[test]
fn every_subcommand_prints_the_version() {
let release = format!("{} ({} {})\n", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
for sub in ["info", "convert", "run", "script", "commands", "describe", "app", "mcp", "parity", "plugins"] {
for spelling in ["--version", "-V"] {
let got = invoke(&[sub, spelling]);
assert_eq!((got.code, got.stdout, got.stderr), (0, format!("soundcraft-cli-{sub} {release}"), String::new()), "{sub} {spelling}");
}
}
}
#[test]
fn version_is_not_a_subcommand() {
assert_usage_error(&invoke(&["version"]), "unrecognized subcommand 'version'");
@@ -26,6 +26,15 @@ fn invoke(dir: &Path, args: &[&str]) -> Output {
Command::new(crate::common::soundcraft_cli_binary()).current_dir(dir).env("SOUNDCRAFT_NO_PREFS", "1").args(args).output().unwrap()
}
#[test]
fn script_accepts_a_leading_utf8_bom() {
let dir = Scratch::new();
std::fs::write(dir.0.join("bom.txt"), "\u{feff}track.new {\"name\":\"BOM\",\"count\":1,\"format\":\"stereo\"}\n").unwrap();
let output = invoke(&dir.0, &["script", "bom.txt"]);
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
assert!(String::from_utf8_lossy(&output.stdout).contains("track.new:"));
}
#[test]
fn keep_going_runs_later_commands_and_finishes_but_reports_failure() {
let dir = Scratch::new();
+2
View File
@@ -17,6 +17,8 @@ path = "src/main.rs"
soundcraft-engine = { workspace = true }
craft-audio.workspace = true
soundcraft-ui-egui.workspace = true
# The page command API (storytold/craft-libs#413): window.soundcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2bfc45c49378effb801c6433758fb5aaa5d7808e", version = "0.1.0" }
soundcraft-playback = { workspace = true }
soundcraft-model = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
+79
View File
@@ -0,0 +1,79 @@
//! `window.soundcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
//!
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
//! `screenshot`, as promises with a timeout). This module is SoundCraft's part: a [`Request`] that
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
//! reply. SoundCraft's control request has no abandon state, so a call the page gave up on still runs
//! when the app reaches it, as it does for a desktop client that timed out.
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError, TrySendError, sync_channel};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use serde_json::{Value, json};
use soundcraft_ui_egui::ControlRequest;
use wasm_bindgen_futures::JsFuture;
/// The app id in `window.<app>`.
const APP: &str = "soundcraft";
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
/// How many control requests may wait for the app at once. `craft-web-api` already refuses calls past its own
/// in-flight limit; this bounds the app's queue too, so a flood of calls can't grow it without limit.
const QUEUE: usize = 64;
/// Put `window.soundcraft` on the page and return the queue the app drains each frame (hand it to
/// `SoundApp::with_control`). An existing `window.soundcraft` keeps the functions it already has.
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = sync_channel::<ControlRequest>(QUEUE);
let request: Request = Rc::new(move |method, params| {
let (control, reply) = ControlRequest::new(method, params);
if let Err(refused) = queue.try_send(control) {
let error = match refused {
TrySendError::Full(_) => format!("soundcraft is busy: {QUEUE} requests are already waiting for the app"),
TrySendError::Disconnected(_) => "the app is not running".to_string(),
};
return Box::pin(async move { json!({"ok": false, "error": error}) });
}
ctx.request_repaint();
Box::pin(wait(reply))
});
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
log::warn!("couldn't install window.{APP}: {e:?}");
}
requests
}
/// The app's reply, polled about once a frame.
async fn wait(reply: Receiver<Value>) -> Value {
loop {
match reply.try_recv() {
Ok(reply) => return reply,
Err(TryRecvError::Empty) => {
if !sleep(POLL_MS).await {
return json!({"ok": false, "error": "this page has no timer to wait for the app with"});
}
}
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
}
}
}
async fn sleep(ms: i32) -> bool {
// `false` when this page has no timer to wait with (no window, or the timer is refused): the caller ends the
// call with an error instead of going round again at once.
let timer = std::cell::Cell::new(false);
let promise = js_sys::Promise::new(&mut |resolve, _| {
let set = web_sys::window().is_some_and(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms).is_ok());
timer.set(set);
if !set {
let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED);
}
});
let _ = JsFuture::from(promise).await;
timer.get()
}
+4 -1
View File
@@ -6,7 +6,8 @@
//! from this directory (output in `dist/web`).
//!
//! Differences from the desktop app:
//! - no TCP control channel (browsers can't listen on sockets);
//! - no TCP control channel (browsers can't listen on sockets); `window.soundcraft` (`api`) drives the
//! same control channel from the page instead;
//! - no file system: File > Open Session…, Import > Audio…/MIDI… and files dropped on the page are
//! read as bytes through the browser's file picker; a session is saved as ONE bundle file
//! (`<name>.scraftz`: the `.scraft` and its `Audio Files/`), and every save or export arrives as a
@@ -18,6 +19,8 @@
//! empty session instead of the demo.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(target_arch = "wasm32")]
mod web;
+4 -1
View File
@@ -49,9 +49,10 @@ pub fn start() {
if let Some(rs) = &cc.wgpu_render_state {
log::info!("soundcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
}
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
let app = SoundApp::new(engine, Some(player), Services::default());
let app = SoundApp::new(engine, Some(player), Services::default()).with_control(crate::api::install(cc.egui_ctx.clone()));
Ok(Box::new(WebShell { app, inbox: Rc::default(), samples: Rc::default() }))
}),
)
@@ -224,12 +225,14 @@ impl eframe::App for WebShell {
self.app.logic(ctx);
// A prompt opened during this frame becomes a picker on the next one.
self.take_path_prompt(ctx);
self.app.close_path(ctx);
}
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
/// shell.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+109
View File
@@ -0,0 +1,109 @@
// Real-browser check of window.soundcraft (the page command API from craft-web-api): serve a built
// copy of the web app, load it in headless Chromium and drive every function the crate installs.
//
// Usage, from a folder where Playwright is installed (`npm i playwright`, then `npx playwright install chromium`):
// node <repo>/apps/soundcraft-web/tests/page-api.mjs <site folder>
// The site folder is a built copy of the web app: `trunk build --release` in apps/soundcraft-web
// (dist/web), or the unpacked `packaging/web/package.sh` zip. Exits non-zero on the first failed check.
//
// Not repeated here: the 30 s request timeout belongs to craft-web-api and is covered by that crate's own
// tests. The limit on calls waiting for the app (64) is exercised below: it needs a craft-web-api that has it
// (craft-libs#733) and the app's own bounded queue.
import { createRequire } from 'node:module'
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import assert from 'node:assert/strict'
const dir = process.argv[2]
if (!dir) { console.error('usage: node page-api.mjs <site folder>'); process.exit(2) }
const require = createRequire(path.join(process.cwd(), 'noop.js'))
const { chromium } = (() => { try { return require('playwright') } catch { return require('@playwright/test') } })()
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png' }
const server = http.createServer(async (req, res) => {
const route = decodeURIComponent(req.url.split('?')[0])
const file = path.join(dir, route === '/' ? 'index.html' : route)
try {
const body = await readFile(file)
res.writeHead(200, { 'content-type': types[path.extname(file)] || 'application/octet-stream' })
res.end(body)
} catch { res.writeHead(404); res.end() }
})
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
const origin = `http://127.0.0.1:${server.address().port}`
const browser = await chromium.launch({ headless: true, args: ['--disable-gpu'] })
try {
const page = await (await browser.newContext({ viewport: { width: 1280, height: 900 } })).newPage()
const errors = []
page.on('pageerror', (e) => errors.push(e.message))
// ?webgl forces the WebGL2 backend: headless Chromium has no WebGPU adapter.
await page.goto(`${origin}/?webgl`)
await page.locator('canvas').first().waitFor({ timeout: 180_000 })
await page.waitForFunction(() => window.soundcraft && typeof window.soundcraft.request === 'function', null, { timeout: 180_000 })
const names = await page.evaluate(() => Object.keys(window.soundcraft).sort())
for (const f of ['request', 'execute', 'commands', 'docInspect', 'uiInspect', 'screenshot']) {
assert(names.includes(f), `window.soundcraft.${f} is installed (found: ${names.join(' ')})`)
}
// A call that rejects is reported, not thrown, so each check can look at the error.
const call = (fn, ...args) => page.evaluate(async ([fn, args]) => {
try { return { ok: true, value: await window.soundcraft[fn](...args) } }
catch (e) { return { ok: false, error: String((e && e.message) || e), isError: e instanceof Error } }
}, [fn, args])
const commands = await call('commands')
assert(commands.ok && Array.isArray(commands.value) && commands.value.length > 0, `commands() lists the commands: ${JSON.stringify(commands).slice(0, 200)}`)
assert(commands.value.some((c) => c.id === 'track.new'), 'commands() includes track.new')
const doc = await call('docInspect')
assert(doc.ok && typeof doc.value === 'object', `docInspect() resolves with an object: ${JSON.stringify(doc).slice(0, 200)}`)
const ui = await call('uiInspect')
assert(ui.ok && typeof ui.value === 'object', `uiInspect() resolves with an object: ${JSON.stringify(ui).slice(0, 200)}`)
// execute changes the session, and docInspect shows it.
const docBefore = await call('docInspect')
assert(docBefore.ok, `docInspect() resolves before execute: ${JSON.stringify(docBefore).slice(0, 200)}`)
const ran = await call('execute', 'track.new', {})
assert(ran.ok, `execute('track.new') resolves: ${JSON.stringify(ran).slice(0, 300)}`)
const docAfter = await call('docInspect')
assert(docAfter.ok, `docInspect() resolves after execute: ${JSON.stringify(docAfter).slice(0, 200)}`)
assert.notEqual(JSON.stringify(docBefore.value), JSON.stringify(docAfter.value), 'docInspect() changes after execute(track.new)')
// Failures reject with an Error that names what went wrong.
const unknownCommand = await call('execute', 'no.such.command', {})
assert(!unknownCommand.ok && unknownCommand.isError && unknownCommand.error.includes('no.such.command'), `execute of an unknown command rejects with an Error naming it: ${JSON.stringify(unknownCommand)}`)
const unknownMethod = await call('request', 'no.such.method', {})
assert(!unknownMethod.ok && unknownMethod.isError && unknownMethod.error.includes('no.such.method'), `an unknown method rejects with an Error naming it: ${JSON.stringify(unknownMethod)}`)
const shot = await call('screenshot')
assert(shot.ok, `screenshot() resolves: ${JSON.stringify(shot).slice(0, 200)}`)
const data = shot.value && shot.value.data
assert(typeof data === 'string' && data.length > 1000, 'screenshot() carries base64 data')
assert.equal(Buffer.from(data, 'base64').subarray(1, 4).toString(), 'PNG', 'the screenshot is a PNG')
// Several calls at once all settle.
const settled = await page.evaluate(() => Promise.all([1, 2, 3, 4, 5].map(() => window.soundcraft.uiInspect())).then((r) => r.length))
assert.equal(settled, 5, 'five concurrent calls all settle')
// Overload: far more calls than may wait at once. The ones over the limit are refused at once as busy, the
// ones within it are answered, and the page can call again afterwards (the slots came back).
const burst = await page.evaluate(() => Promise.all(
Array.from({ length: 300 }, () => window.soundcraft.uiInspect().then(() => 'ok', (e) => String((e && e.message) || e))),
))
const refused = burst.filter((r) => r !== 'ok')
console.log(`burst of ${burst.length}: ${burst.length - refused.length} answered, ${refused.length} refused (${refused[0]})`)
assert(refused.length > 0, 'calls beyond the limit are refused')
assert(refused.every((r) => /busy/i.test(r)), `every refusal says busy: ${refused.find((r) => !/busy/i.test(r))}`)
assert(burst.includes('ok'), 'the calls within the limit are answered')
assert.equal(burst.length, 300, 'every call settled, none was left waiting')
const afterBurst = await call('uiInspect')
assert(afterBurst.ok, `a call after the burst is accepted again: ${JSON.stringify(afterBurst).slice(0, 200)}`)
assert.deepEqual(errors, [], 'no uncaught page errors')
console.log('PASS window.soundcraft: all six functions, the failure paths and concurrent calls work against the real app')
} finally {
await browser.close()
server.close()
}
+2
View File
@@ -48,3 +48,5 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["NSAppl
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
# The Nightly flavor's explicit taskbar identity (process_identity.rs); stable sets none.
winsafe = { version = "0.0.29", features = ["user", "shell"] }
+50 -3
View File
@@ -4,24 +4,71 @@
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `SOUNDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
//!
//! `SOUNDCRAFT_BUILD_CHANNEL=nightly-v1` compiles the isolated Nightly flavor: `cfg(soundcraft_nightly_v1)`,
//! the Nightly icon, `ProductName "SoundCraft Nightly"` and the exact feed version as
//! `ProductVersion` (the Launcher checks that field, not FileVersion). An unset, empty or `stable`
//! channel is the stable build; anything else is a build error.
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(soundcraft_nightly_v1)");
let nightly = match std::env::var("SOUNDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=soundcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported SOUNDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/soundcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/soundcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_VERSION");
println!("cargo:rerun-if-env-changed=SOUNDCRAFT_OVERRIDE_VERSION");
let built_version = if nightly {
// The feed identity is SOUNDCRAFT_VERSION. The packaging scripts (packaging/env.sh and the
// Linux package.sh, inherited from PhotoCraft) set the same value as
// SOUNDCRAFT_OVERRIDE_VERSION, which is accepted as the one alias so both agree.
let identity = std::env::var("SOUNDCRAFT_VERSION").or_else(|_| std::env::var("SOUNDCRAFT_OVERRIDE_VERSION"));
match identity {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit SOUNDCRAFT_VERSION feed identity (SOUNDCRAFT_OVERRIDE_VERSION is accepted)");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=SOUNDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/soundcraft.ico")
.set("ProductName", "SoundCraft")
.set("FileDescription", "SoundCraft digital audio workstation")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "SoundCraft Nightly" } else { "SoundCraft" })
.set("FileDescription", if nightly { "SoundCraft Nightly digital audio workstation" } else { "SoundCraft digital audio workstation" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the SoundCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "soundcraft.exe")
.set("InternalName", "soundcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("SOUNDCRAFT_REQUIRE_WINRES").is_some() {
// The workspace denies `clippy::panic`, build scripts included: stop the build with
// the reason on stderr.
eprintln!("embedding Windows resources failed: {e}");
std::process::exit(1);
}
+53
View File
@@ -0,0 +1,53 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/soundcraft-nightly.ico" } else { "../../assets/app-icon/soundcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/soundcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/soundcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.20.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.20.1",
"0.20.1-nightly",
"0.20.1-nightly.20261124",
"0.20.1-nightly.20261124.17.1.gABCDEF012345",
"0.20.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.20.1-nightly.20261124.1.1.gabcdef012345",
"0.20.1-nightly.20261124.1.1.gabcdef012345/other",
"0.20.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
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
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_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");
assert_eq!(version(BuildFlavor::NightlyV1, "0.20.1"), "0.20.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+75 -14
View File
@@ -7,8 +7,14 @@ use soundcraft_ui_egui::docking;
/// Portable mode (#268): this file beside the executable keeps settings, autosaves, presets and
/// logs in [`PORTABLE_DATA_DIR`] next to it instead of the user profile.
const PORTABLE_MARKER: &str = "portable.txt";
const PORTABLE_DATA_DIR: &str = "SoundCraftData";
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
/// 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 {
@@ -32,10 +38,17 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<Path
Platform::Other
};
let exe = std::env::current_exe().ok();
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent))
// The one place a validated Nightly profile replaces every data root: ui.json, Autosave/,
// Presets/ and logs/ all hang off this folder, before any of them is first used.
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent), crate::launch_profile::current().root())
}
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> Option<PathBuf> {
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option<PathBuf> {
// The compiled Nightly flavor 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());
}
if let Some(dir) = env(crate::env::CONFIG_DIR) {
return (!dir.is_empty()).then(|| PathBuf::from(dir));
}
@@ -55,12 +68,26 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, e
}
}
/// Create `dir` if needed and prove a file can be written in it.
fn writable(dir: &Path) -> std::io::Result<()> {
/// Create `dir` if needed and prove a file can be written in it. The Nightly profile validator
/// injects this same exclusive probe.
///
/// The probe never replaces an existing entry: `create_new` cannot truncate one, and a name that is
/// already taken (an interrupted run, or a file someone else made) is left untouched while the next
/// name is tried. Only a file this call created is removed again.
pub(crate) fn writable(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let probe = dir.join(format!(".write-test-{}", std::process::id()));
std::fs::write(&probe, b"")?;
std::fs::remove_file(probe)
for attempt in 0..8u32 {
let probe = dir.join(format!(".write-test-{}-{attempt}", std::process::id()));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(file) => {
drop(file);
return std::fs::remove_file(probe);
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name"))
}
/// Read bounded settings, recovering unreadable docking metadata independently of other settings.
@@ -156,10 +183,16 @@ mod config_tests {
app.ui = load_ui(&path).unwrap().unwrap();
assert_eq!(app.ui.theme, soundcraft_ui_egui::theme::ThemeMode::Light);
assert_eq!(serde_json::to_value(&app.ui.docking).unwrap(), edit);
assert_eq!(app.ui.mix_docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [140.0, 150.0, 280.0, 420.0]);
assert_eq!(
app.ui.mix_docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
egui::Rect::from_min_size(egui::pos2(140.0, 150.0), egui::vec2(280.0, 420.0))
);
app.ui.window = MainWindow::Edit;
app.run("ui.dock", serde_json::json!({"operation":"open","panel":"tracks"})).unwrap();
assert_eq!(app.ui.docking.layout.floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect, [80.0, 90.0, 260.0, 400.0]);
assert_eq!(
app.ui.docking.layout().floating.iter().find(|g| g.contains(&Panel::Tracks)).unwrap().rect,
egui::Rect::from_min_size(egui::pos2(80.0, 90.0), egui::vec2(260.0, 400.0))
);
let mut invalid_mix = app.ui.clone();
invalid_mix.mix_docking = soundcraft_ui_egui::docking::edit_default();
let invalid_bytes = serde_json::to_vec(&invalid_mix).unwrap();
@@ -251,7 +284,7 @@ mod config_tests {
}
fn resolve(platform: Platform, vars: &[(&str, &str)]) -> Option<PathBuf> {
config_dir_with(platform, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None)
config_dir_with(platform, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None, None)
}
#[test]
@@ -264,6 +297,7 @@ mod config_tests {
Some(OsString::from("isolated/settings"))
},
None,
None,
);
assert_eq!(actual, Some(PathBuf::from("isolated/settings")));
}
@@ -279,6 +313,7 @@ mod config_tests {
assert_eq!(name, "SOUNDCRAFT_CONFIG_DIR");
Some(OsString::new())
},
None,
None
),
None
@@ -318,7 +353,33 @@ mod config_tests {
}
fn resolve_with_exe(vars: &[(&str, &str)], exe: &Path) -> Option<PathBuf> {
config_dir_with(Platform::Windows, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), Some(exe))
config_dir_with(Platform::Windows, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), Some(exe), None)
}
#[test]
fn a_validated_nightly_profile_replaces_every_settings_root() {
let nightly = PathBuf::from("/launcher/profiles/soundcraft");
let vars = [("SOUNDCRAFT_CONFIG_DIR", "/custom"), ("HOME", "/user"), ("APPDATA", "/roaming"), ("XDG_CONFIG_HOME", "/xdg")];
for platform in [Platform::Mac, Platform::Windows, Platform::Other] {
let dir = config_dir_with(
platform,
|name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))),
None,
Some(&nightly),
);
assert_eq!(dir, Some(nightly.clone()), "the profile wins over the variable and the platform default");
}
// Even an empty override variable cannot take the Nightly settings folder away.
let dir = config_dir_with(Platform::Other, |_| Some(OsString::new()), None, Some(&nightly));
assert_eq!(dir, Some(nightly.clone()));
}
#[test]
fn the_stable_channel_keeps_its_own_resolution() {
let vars = [("XDG_CONFIG_HOME", "/xdg")];
let dir =
config_dir_with(Platform::Other, |name| vars.iter().find_map(|(key, value)| (*key == name).then(|| OsString::from(value))), None, None);
assert_eq!(dir, Some(PathBuf::from("/xdg/soundcraft")));
}
#[cfg(unix)]
@@ -326,6 +387,6 @@ mod config_tests {
fn config_override_preserves_non_unicode_paths() {
use std::os::unix::ffi::OsStringExt as _;
let value = OsString::from_vec(b"isolated/\xff".to_vec());
assert_eq!(config_dir_with(Platform::Mac, |_| Some(value.clone()), None), Some(PathBuf::from(value)));
assert_eq!(config_dir_with(Platform::Mac, |_| Some(value.clone()), None, None), Some(PathBuf::from(value)));
}
}
+8
View File
@@ -40,6 +40,14 @@ pub(crate) fn command() -> Command {
LaunchArgs::command().mut_args(blank_env_is_unset)
}
/// The command line for the selected channel. A Nightly window never inherits the stable
/// `SOUNDCRAFT_CONTROL_PORT` variable: its control server is not started and the Launcher owns
/// its lifecycle, so only its file list is meaningful.
pub(crate) fn command_for_profile(nightly: bool) -> Command {
let cmd = command();
if nightly { cmd.mut_arg("control", |arg| arg.env(None)) } else { cmd }
}
/// Parses the launch arguments (without the program name) with `cmd`, from [`command`]. macOS
/// passes a process serial number (`-psn_…`) when an app is started from Finder on old versions:
/// it is dropped first, unless it comes after `--`. A bad value from a variable is a usage error
+214
View File
@@ -0,0 +1,214 @@
//! 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::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
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 {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// 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 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());
}
}
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() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// 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)
}
/// 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 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" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[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 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 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());
}
}
#[test]
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"] {
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 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 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());
}
}
+9 -3
View File
@@ -22,8 +22,8 @@
//! callback must never do. Code that runs on the audio thread logs anyway (the cpal error callback,
//! the synth's full event queue, a hosted plugin's failed `process`, a CLAP plugin calling the
//! host's `log` from its audio thread, the panic hook). So the cpal callbacks mark their thread
//! (`soundcraft_playback::mark_audio_thread`; the mix engine carries the mark into the worker
//! threads that render strips for it), and a record from a marked thread is not written
//! (`soundcraft_playback::mark_audio_thread`; the mix engine renders every strip on the marked
//! thread itself), and a record from a marked thread is not written
//! there: the first one is kept in a fixed buffer (`try_lock`, no allocation, never waits) and the
//! rest are only counted (an atomic). Another thread writes them out: the UI thread every frame
//! ([`AppLogger::report_audio_thread`]) and any other thread before its own next record.
@@ -166,7 +166,13 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
let message = message.strip_suffix('\n').unwrap_or(message);
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
// Control characters are written escaped: a message quoting a session file (a plugin id, a
// path) must not start a line of its own in the log or steer the terminal.
let mut escaped = String::with_capacity(message.len());
for c in message.chars() {
if c.is_control() { escaped.extend(c.escape_default()) } else { escaped.push(c) }
}
format!("{ts} {level:<5} [{thread}] {target}: {escaped}\n")
}
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
+9 -2
View File
@@ -158,8 +158,15 @@ fn a_line_carries_time_level_thread_target_and_message() {
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "soundcraft_mix", "eq_7band: the plugin did not accept its stored state"),
"2026-10-08T07:59:17.728Z WARN [main] soundcraft_mix: eq_7band: the plugin did not accept its stored state\n"
);
// A multi-line message keeps its lines; the record still ends in exactly one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
// A message with breaks of its own stays one record; the record still ends in exactly one newline.
assert!(
format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\\nb\n"),
"a break inside the message is escaped, the final one dropped"
);
assert!(
format_line("t", log::Level::Error, "w", "x", "plugin \u{1b}[2J\r\n2026 INFO forged")
.ends_with("x: plugin \\u{1b}[2J\\r\\n2026 INFO forged\n")
);
}
#[test]
+187 -24
View File
@@ -11,20 +11,27 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod config;
mod control_server;
mod env;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod launch_args;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod process_identity;
mod profile_root;
mod switch;
use env::Env;
use soundcraft_engine::Engine;
use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs};
use soundcraft_ui_egui::{Services, SoundApp, UiState, dialogs, os_window};
use std::sync::Arc;
struct App(SoundApp, Option<&'static logging::AppLogger>, Env, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
@@ -64,8 +71,6 @@ impl eframe::App for App {
}
if self.0.quit_requested {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else if ctx.input(|i| i.viewport().close_requested()) && dialogs::ask_to_save(&mut self.0, "app.quit", &serde_json::json!({})) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
soundcraft_ui_egui::fit_window_to_screen(ctx);
let (inner, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().maximized.unwrap_or(false)));
@@ -80,24 +85,26 @@ impl eframe::App for App {
}
// With the system menu bar there is no egui bar showing the window and dirty state, so the
// title carries them; elsewhere the egui menu bar already does.
let app_name = os_window::name_for(os_window::identity());
let document = (self.0.engine.session().name.as_str(), self.0.engine.is_dirty());
let title = if self.0.native_menu_bar {
format!(
"{}{} — SoundCraft — {}",
self.0.engine.session().name,
if self.0.engine.is_dirty() { " *" } else { "" },
if self.0.ui.window == soundcraft_ui_egui::MainWindow::Edit { "Edit" } else { "Mix" }
)
let section = if self.0.ui.window == soundcraft_ui_egui::MainWindow::Edit { "Edit" } else { "Mix" };
soundcraft_ui_egui::os_title_with_section(app_name, Some(document), section)
} else {
format!("{} — SoundCraft", self.0.engine.session().name)
soundcraft_ui_egui::os_title(app_name, Some(document.0))
};
set_title(ctx, title);
// Last: the runtime's close path, which asks about unsaved changes before the window closes.
self.0.close_path(ctx);
}
/// Forward raw input to the shared app hook so scripted gestures and host-key protection behave like the desktop
/// shell.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.0.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
soundcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.0.guarded(|app| app.ui(ui));
}
fn on_exit(&mut self) {
@@ -112,6 +119,9 @@ impl eframe::App for App {
self.0.player = None;
soundcraft_engine::shutdown_plugin_hosts();
self.0.start_pending_update();
// The binary's last step: on Nightly, finishing the session-health record. macOS ends the
// process from inside AppKit's terminate, so this is that channel's only exit path.
self.0.services.run_exit_hook();
}
}
@@ -174,30 +184,122 @@ fn services() -> Services {
d.save_file()
})),
pick_folder: Some(Box::new(|start: &std::path::Path| rfd::FileDialog::new().set_directory(start).pick_folder())),
..Services::default()
}
}
/// The window, Dock, taskbar and Alt-Tab icon. macOS gets Apple's icon grid (transparent margin);
/// elsewhere the full tile. Regenerate with `packaging/icons.sh`.
fn app_icon() -> Option<egui::IconData> {
let nightly = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
#[cfg(target_os = "macos")]
let png: &[u8] = include_bytes!("../../../assets/app-icon/soundcraft-macos-512.png");
let png: &[u8] = if nightly {
include_bytes!("../../../assets/app-icon/soundcraft-nightly-macos-512.png")
} else {
include_bytes!("../../../assets/app-icon/soundcraft-macos-512.png")
};
#[cfg(not(target_os = "macos"))]
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft.png");
let png: &[u8] = if nightly {
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft-nightly.png")
} else {
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.soundcraft.png")
};
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
}
/// Set the immutable Windows AUMID for the Nightly flavor before any window or COM service.
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
os_window::id_for(os_window::LaunchIdentity::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Report a refused launch profile on standard error, and in a dialog on a Windows or X11/Wayland
/// desktop session: a Nightly build started from a file manager has no console to read. macOS keeps
/// the console line, because a modal before its event loop never appears.
fn report_launch_profile_error(error: &str) {
eprintln!("SoundCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("SoundCraft launch profile: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title("SoundCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any start-up service or side effect. `None` means
/// this process is done: a version query already answered, or a refused profile (exit status 2).
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before the logger, updates, fonts or saved state.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, 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::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) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
fn main() -> eframe::Result {
let Some(arguments) = prepare_launch() else { return Ok(()) };
// The compiled identity, so About and diagnostics report the Nightly feed version verbatim.
soundcraft_ui_egui::set_build_version(env!("SOUNDCRAFT_BUILT_VERSION").to_owned());
// Windows: the update helper is a copy of this program started with `--finish-update`.
// Nightly has no updater of its own: ArtCraft Launcher carries the next build.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&soundcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !launch_profile::current().is_nightly()
&& let Some(result) = craft_update::self_update::finish(&soundcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
std::process::exit(i32::from(result.is_err()));
}
// First, so every start-up record (and the engine's panic hook, installed with the first
// Engine) is captured; see `logging`.
let logger = logging::install(env::rust_log().as_deref());
// Help, version and usage errors print and exit here, before a window or a log file exists.
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
let launch = launch_args::parse(launch_args::command_for_profile(launch_profile::current().is_nightly()), arguments).unwrap_or_else(|e| e.exit());
// After the arguments and the logger: reading resolves the settings folder, which creates it,
// and a malformed switch is logged.
let env = Env::read();
@@ -226,12 +328,12 @@ fn main() -> eframe::Result {
let prefs = load_prefs(&env).unwrap_or_default();
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("SoundCraft")
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size(sane_window_size(prefs.window_size))
.with_maximized(prefs.window_maximized)
.with_min_inner_size([960.0, 600.0])
.with_drag_and_drop(true)
.with_app_id("ai.storyteller.soundcraft"),
.with_app_id(os_window::app_id()),
..Default::default()
};
if let Some(icon) = app_icon() {
@@ -240,34 +342,77 @@ fn main() -> eframe::Result {
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
#[cfg(target_os = "windows")]
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
#[cfg(all(unix, not(target_os = "macos")))]
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; SOUNDCRAFT_WAYLAND=1
// keeps the native Wayland backend.
if env.use_xwayland(std::env::var_os("DISPLAY").as_ref()) {
#[cfg(all(unix, not(target_os = "macos")))]
let forced_x11 = env.use_xwayland(std::env::var_os("DISPLAY").as_ref());
#[cfg(not(all(unix, not(target_os = "macos"))))]
let forced_x11 = false;
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
eframe::run_native(
"SoundCraft",
// Nightly session health: an owned lease plus a record removed only by a clean exit, so the
// next start can say when the previous one did not finish. Stable and a secondary window keep
// their existing behaviour and touch nothing. No document names or paths are collected.
let (nightly_session, session_health_warning) =
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("SOUNDCRAFT_BUILT_VERSION"), None) {
Ok(state) => state,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, true)
}
};
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
// Set once a window has posted the interruption notice; until then the record must survive.
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let notice_shown_in_callback = unclean_notice_shown.clone();
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
// The app's exit hook is the controlled return on macOS, where every quit ends the process
// inside AppKit's terminate and `run_native` never returns.
#[cfg(target_os = "macos")]
let finish_at_exit = {
let shared = nightly_session.clone();
let shown = unclean_notice_shown.clone();
move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed))
};
let result = eframe::run_native(
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
soundcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11)?;
let player =
if no_audio { None } else { Some(soundcraft_playback::Player::with_config(Arc::new(engine.session().clone()), &prefs.audio)) };
let mut app = SoundApp::new(engine, player, services());
app.set_startup_update_check(true);
// Nightly is updated by ArtCraft Launcher only, never from inside the app.
app.set_startup_update_check(!launch_profile::current().is_nightly());
app.set_system_fonts(env.system_fonts());
app.autosave_dir = env.config_dir.as_ref().map(|d| d.join("Autosave"));
app.leftovers = app.autosave_dir.as_deref().map(soundcraft_engine::autosave::leftovers).unwrap_or_default();
app.preset_dir = env.config_dir.as_ref().map(|d| d.join("Presets"));
app.extra.ui_scale = prefs.ui_scale;
app.ui = prefs;
if let Some(port) = control_port {
// The Nightly window has no control server: no inherited port, no stable token file.
if let Some(port) = control_port.filter(|_| !launch_profile::current().is_nightly()) {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
if previous_nightly_unclean || session_health_warning {
app.ui.status = if previous_nightly_unclean {
"The previous SoundCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent.".to_owned()
} else {
"SoundCraft Nightly could not record session health in its private profile; abnormal-exit detection is unavailable.".to_owned()
};
notice_shown_in_callback.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
}
#[cfg(target_os = "macos")]
{
app.services.at_exit = Some(Box::new(finish_at_exit));
}
for f in &files {
dialogs::open_path(&mut app, f);
}
@@ -291,7 +436,11 @@ fn main() -> eframe::Result {
menu,
)))
}),
)
);
// A controlled return, even for a handled start-up error. On macOS a window that was created
// has already finished in its exit hook, so this is then a no-op.
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
result
}
/// A saved window size, or the default when the prefs file holds nonsense (NaN, negative, tiny).
@@ -316,3 +465,17 @@ mod tests {
assert_eq!(titles("Song * — SoundCraft"), 1);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+267
View File
@@ -0,0 +1,267 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
/// Write `bytes` to `path` through an exclusively created temporary file in the same directory.
/// The temporary name is never reused and is opened with `create_new`, so an existing file or a
/// link at either name is replaced rather than followed; a failure leaves `path` untouched.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
use std::io::Write as _;
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| io::Error::other(error.to_string()))?.as_nanos();
let name = path.file_name().ok_or_else(|| io::Error::other("Nightly session state needs a file name"))?;
let temporary = path.with_file_name(format!(".{}.{}.{nonce}.tmp", name.to_string_lossy(), std::process::id()));
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
let written = (|| -> io::Result<()> {
file.write_all(bytes)?;
file.sync_all()?;
std::fs::rename(&temporary, path)
})();
if written.is_err() {
let _ = std::fs::remove_file(&temporary);
}
written
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
// Durable, exclusive creation: a raced destination link is replaced, never followed.
atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("soundcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The CPU retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug)]
pub struct IdentityError(String);
impl std::fmt::Display for IdentityError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.0)
}
}
impl std::error::Error for IdentityError {}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+705
View File
@@ -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");
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

-4
View File
@@ -2,8 +2,4 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+15 -16
View File
@@ -153,6 +153,9 @@ impl RunLoop {
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
#[test]
fn timers_and_descriptors_follow_registration() {
@@ -168,25 +171,21 @@ mod tests {
assert_eq!(due, vec![a, b], "a late frame fires each timer once");
assert!(rl.remove_timer(a) && !rl.remove_timer(a));
assert_eq!(rl.due(t0 + Duration::from_secs(2)), vec![b]);
let mut fds = [0; 2];
// SAFETY: `fds` holds the two descriptors `pipe` writes.
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
assert!(rl.add_fd(fds[0], CLAP_POSIX_FD_READ));
assert!(!rl.add_fd(fds[0], CLAP_POSIX_FD_READ), "registered once");
// A connected stream has defined read and write readiness on both Linux and BSD.
let (stream, mut peer) = UnixStream::pair().unwrap();
let fd = stream.as_raw_fd();
assert!(rl.add_fd(fd, CLAP_POSIX_FD_READ));
assert!(!rl.add_fd(fd, CLAP_POSIX_FD_READ), "registered once");
assert!(!rl.add_fd(-1, CLAP_POSIX_FD_READ));
assert!(rl.ready().is_empty(), "nothing to read");
// SAFETY: a valid one-byte buffer written to our own pipe.
assert_eq!(unsafe { libc::write(fds[1], b"x".as_ptr().cast(), 1) }, 1);
assert_eq!(rl.ready(), vec![(fds[0], CLAP_POSIX_FD_READ)]);
assert!(rl.modify_fd(fds[0], CLAP_POSIX_FD_WRITE));
assert!(rl.ready().is_empty(), "a read end never becomes writable");
assert!(rl.remove_fd(fds[0]) && !rl.has_fd(fds[0]));
peer.write_all(b"x").unwrap();
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_READ)]);
// The unread byte is still there, so reporting read as well would be a stale interest.
assert!(rl.modify_fd(fd, CLAP_POSIX_FD_WRITE));
assert_eq!(rl.ready(), vec![(fd, CLAP_POSIX_FD_WRITE)]);
assert!(rl.remove_fd(fd) && !rl.has_fd(fd));
assert!(rl.ready().is_empty(), "no callbacks for an unregistered descriptor");
rl.clear();
assert!(!rl.has_timer(b));
// SAFETY: closing the pipe we opened.
unsafe {
libc::close(fds[0]);
libc::close(fds[1]);
}
}
}
+1
View File
@@ -33,6 +33,7 @@ winsafe = { version = "0.0.29", features = ["kernel"] }
[dev-dependencies]
cfb.workspace = true
craft-aaf.workspace = true
proptest.workspace = true
zip.workspace = true
+2
View File
@@ -478,6 +478,8 @@ pub fn create_unique_folder(parent: &Path, prefix: &str) -> std::io::Result<Path
for _ in 0..16 {
let random = |_| std::collections::hash_map::RandomState::new().build_hasher().finish();
let dir = parent.join(format!("{prefix}-{:016x}{:016x}", random(0), random(1)));
// Only Unix sets a mode on the builder, so elsewhere it is never mutated.
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
+149 -1
View File
@@ -96,6 +96,92 @@ pub fn is_placeholder(path: &str) -> bool {
PLACEHOLDERS.contains(&path)
}
/// RFC-0052 hand marks for catalog leaves the engine registry doesn't implement:
/// `(path, headless, reach, why)`. A path ending in ` > ` marks every leaf under it; the longest
/// matching path wins.
///
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
/// command, isn't one yet). `yes` is never written here: a leaf is `yes` only when the engine registry
/// that `soundcraft-cli` and the MCP server load implements it. UI-layer ids (`parity_with`'s
/// `extra`) don't count. An unmarked missing leaf is `unknown`. [`headless_errors`] rejects marks
/// that match nothing or only hide a `yes`.
pub const HEADLESS: &[(&str, &str, &str, &str)] = &[
("File > Open > Project...", "no", "os", "online project service"),
("File > Open > Sketch...", "no", "engine-gap", "sketch files could be opened by a command"),
("File > Dashboard...", "no", "window", "the start dialog"),
("File > Start Collaboration...", "no", "os", "online collaboration service"),
("File > Import > ", "no", "engine-gap", "the import could be a command"),
("File > Export > ", "no", "engine-gap", "the export could be a command"),
("File > Sign In", "no", "os", "online account service"),
("Edit > Automation > ", "no", "engine-gap", "automation copies could be commands"),
("View > ", "no", "window", "shows or hides part of a desktop window"),
("Track > Change Track Width > Show / Hide...", "no", "window", "a desktop dialog"),
("Track > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
("Clip > ARA Plugins > ", "no", "engine-gap", "no plug-in extension host in the engine yet"),
("AudioSuite > ", "no", "engine-gap", "offline processing over the crates/dsp plug-ins could be commands"),
("Options > Activate HEAT", "no", "engine-gap", "the processor could be an engine option"),
("Setup > Machine Track Arming Profiles...", "no", "os", "external machine control hardware"),
("Window > ", "no", "window", "opens or arranges a desktop window"),
("Window > Collaboration > ", "no", "os", "online collaboration service"),
("Window > Splice", "no", "os", "online sample service"),
("Window > SoundFlow", "no", "os", "third-party automation service"),
];
/// Whether a `HEADLESS` mark path covers a catalog leaf.
fn mark_covers(mark: &str, leaf: &str) -> bool {
mark == leaf || (mark.ends_with(" > ") && leaf.starts_with(mark))
}
/// A leaf's RFC-0052 `headless:` value, `reach:` and reason: `yes` when the engine implements it,
/// else the longest `marks` path that covers it, else `unknown`.
pub fn headless_of<'a>(leaf: &str, in_engine: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) {
if in_engine {
return ("yes", None, "");
}
marks.iter().filter(|m| mark_covers(m.0, leaf)).max_by_key(|m| m.0.len()).map_or(("unknown", None, ""), |m| (m.1, Some(m.2), m.3))
}
/// Problems with `marks` against `leaves` (`(path, in_engine)`): bad values, a mark that covers no
/// leaf, and a mark whose leaves the engine all implements (it would only hide a `yes`).
pub fn headless_errors(marks: &[(&str, &str, &str, &str)], leaves: &[(&str, bool)]) -> Vec<String> {
let mut errs = Vec::new();
for (i, (path, value, reach, _)) in marks.iter().enumerate() {
if !matches!(*value, "no" | "partial") {
errs.push(format!("headless mark `{path}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
}
if !matches!(*reach, "window" | "os" | "engine-gap") {
errs.push(format!("headless mark `{path}`: reach `{reach}` is not window, os or engine-gap"));
}
if marks[..i].iter().any(|m| m.0 == *path) {
errs.push(format!("headless mark `{path}` is written twice"));
}
let covered: Vec<bool> = leaves.iter().filter(|l| mark_covers(path, l.0)).map(|l| l.1).collect();
if covered.is_empty() {
errs.push(format!("headless mark `{path}` matches no catalog leaf"));
} else if covered.iter().all(|live| *live) {
errs.push(format!("headless mark `{path}` is stale: the engine implements every leaf it covers"));
}
}
errs
}
/// The RFC-0052 summary line for a [`parity_with`] report.
pub fn headless_summary_line(p: &Value) -> String {
let h = &p["headless"];
let n = |v: &Value| v.as_u64().unwrap_or(0);
format!(
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**",
n(&h["yes"]),
n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]),
n(&h["no"]["window"]),
n(&h["no"]["os"]),
n(&h["no"]["engine-gap"]),
n(&h["partial"]),
n(&h["unknown"]),
)
}
pub fn catalog() -> Vec<&'static str> {
MENUS.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
}
@@ -122,17 +208,27 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
let mut done = 0usize;
let mut missing = Vec::new();
let mut per_menu: std::collections::BTreeMap<String, (usize, usize)> = Default::default();
let mut headless: Vec<(&str, Option<&str>)> = Vec::new();
let mut headless_missing = Vec::new();
for e in &cat {
let top = e.split(" > ").next().unwrap_or("").to_string();
let slot = per_menu.entry(top).or_default();
slot.1 += 1;
if implemented_by(e, extra).is_some() {
let in_engine = implemented_by(e, &[]).is_some();
let (value, reach, why) = headless_of(e, in_engine, HEADLESS);
headless.push((value, reach));
if value != "yes" {
headless_missing.push(json!({"path": e, "headless": value, "reach": reach, "why": why}));
}
if in_engine || (!extra.is_empty() && implemented_by(e, extra).is_some()) {
done += 1;
slot.0 += 1;
} else {
missing.push(*e);
}
}
let count = |v: &str| headless.iter().filter(|h| h.0 == v).count();
let no = |r: &str| headless.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count();
let pct = if cat.is_empty() { 0.0 } else { done as f64 * 100.0 / cat.len() as f64 };
json!({
"total": cat.len(),
@@ -140,6 +236,13 @@ pub fn parity_with(extra: &[(&str, &str)]) -> Value {
"percent": (pct * 10.0).round() / 10.0,
"per_menu": per_menu.iter().map(|(k, (d, t))| json!({"menu": k, "implemented": d, "total": t})).collect::<Vec<_>>(),
"missing": missing,
"headless": {
"yes": count("yes"),
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
"partial": count("partial"),
"unknown": count("unknown"),
},
"headless_missing": headless_missing,
})
}
@@ -159,6 +262,51 @@ mod tests {
}
}
#[test]
fn headless_marks_are_current() {
let leaves: Vec<(&str, bool)> = catalog().into_iter().map(|e| (e, implemented_by(e, &[]).is_some())).collect();
let errs = headless_errors(HEADLESS, &leaves);
assert!(errs.is_empty(), "{errs:?}");
}
#[test]
fn headless_yes_is_the_engine_only() {
let p = parity_json();
let h = &p["headless"];
assert_eq!(h["yes"], p["implemented"], "engine-only parity: every implemented leaf is yes");
// AudioSuite has no engine command: every leaf is marked, none reads as reachable.
let audiosuite: Vec<&Value> = p["headless_missing"]
.as_array()
.into_iter()
.flatten()
.filter(|m| m["path"].as_str().is_some_and(|x| x.starts_with("AudioSuite > ")))
.collect();
assert!(!audiosuite.is_empty());
assert!(audiosuite.iter().all(|m| m["headless"] == "no" && m["reach"] == "engine-gap"));
// A UI-layer alias makes a leaf implemented for the desktop report, not headless.
let ui = [("Window > Mix", "window.mix")];
let with_ui = parity_with(&ui);
assert!(with_ui["implemented"].as_u64() > p["implemented"].as_u64());
assert_eq!(with_ui["headless"], p["headless"]);
assert!(headless_summary_line(&p).contains(&format!("{} yes", h["yes"])));
}
#[test]
fn headless_marks_pick_the_longest_path_and_refuse_bad_ones() {
let marks = [("W > ", "no", "window", "a"), ("W > C > ", "no", "os", "b"), ("X", "partial", "engine-gap", "c")];
assert_eq!(headless_of("W > C > M", false, &marks), ("no", Some("os"), "b"));
assert_eq!(headless_of("W > Mix", false, &marks), ("no", Some("window"), "a"));
assert_eq!(headless_of("W > Mix", true, &marks).0, "yes");
assert_eq!(headless_of("Y", false, &marks).0, "unknown");
assert_eq!(headless_of("WX", false, &marks).0, "unknown", "a prefix mark needs the separator");
let leaves = [("W > Mix", false), ("X", true)];
let bad = [("W > ", "yes", "window", ""), ("W > ", "no", "desk", ""), ("X", "no", "os", ""), ("Z", "no", "os", "")];
let errs = headless_errors(&bad, &leaves);
for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`X` is stale", "`Z` matches no catalog leaf"] {
assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}");
}
}
#[test]
fn parity_floor() {
let p = parity_json();
+2 -1
View File
@@ -168,7 +168,8 @@ pub fn import(e: &mut Engine, path: &str, first: Option<TrackId>, at: Samples) -
.unwrap_or(2);
let kind = if audio_lane { soundcraft_model::TrackKind::Audio } else { soundcraft_model::TrackKind::Midi };
let fmt = if channels == 1 { soundcraft_model::ChannelFormat::Mono } else { soundcraft_model::ChannelFormat::Stereo };
s.add_track(kind, fmt, Some("Clip Group"))
let t = s.add_track(kind, fmt, Some("Clip Group"));
crate::no_input::assign_first_input(s, t)
}
};
let mut prepared = Vec::new();
+1
View File
@@ -66,6 +66,7 @@ pub use file::bounce_job;
pub(crate) use edit::remember_selection;
pub use strip_silence::strip_silence_scan;
pub use tab::tab_stop_ahead;
pub type Run = fn(&mut Engine, &Value) -> Result<Value>;
/// `Err(reason)` = disabled.
+69 -7
View File
@@ -21,14 +21,23 @@ pub fn specs() -> Vec<CommandSpec> {
)]
}
/// How many times longer than its input a process's output can be.
fn growth(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> f64 {
match name {
"time_stretch" => ratio,
"pitch_shift" => 2f64.powf(f64::from(semitones) / 12.0),
"varispeed" => f64::from(to) / sr,
"speed_ramp" if selection == SpeedRampSelection::Extend => 1.5,
_ => 1.0,
}
}
/// The most frames a process can take in: these processes cut their output at MAX_OFFLINE_SAMPLES frames.
fn frame_limit(name: &str, ratio: f64, semitones: f32, sr: f64, to: u32, selection: SpeedRampSelection) -> usize {
let longest = |grows: f64| (soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / grows) as usize;
match name {
"time_stretch" => longest(ratio),
"pitch_shift" => longest(2f64.powf(f64::from(semitones) / 12.0)),
"varispeed" => longest(f64::from(to) / sr),
"speed_ramp" => longest(if selection == SpeedRampSelection::Extend { 1.5 } else { 1.0 }),
"time_stretch" | "pitch_shift" | "varispeed" | "speed_ramp" => {
(soundcraft_dsp::offline::MAX_OFFLINE_SAMPLES as f64 / growth(name, ratio, semitones, sr, to, selection)) as usize
}
_ => usize::MAX,
}
}
@@ -80,14 +89,33 @@ fn process(e: &mut Engine, p: &Value) -> Result<Value> {
let selection = if get("selection", 0.0) >= 0.5 { SpeedRampSelection::Extend } else { SpeedRampSelection::FitTo };
let fades = get("fades", 1.0) >= 0.5;
let most = frame_limit(&name, ratio, semitones, sr.as_f64(), to, selection);
// Each clip once: a clip listed again would otherwise process the result of its first pass
// (an expanding process compounding its length every time).
let mut seen = std::collections::HashSet::new();
let ids: Vec<_> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
// Refuse before processing anything. Every result is kept as a new source for the life of
// the command (and undo holds it), so cap the total output across clips, not just each one.
// (pitch_shift resamples its stretched result back to the input length)
let grows = if name == "pitch_shift" { 1.0 } else { growth(&name, ratio, semitones, sr.as_f64(), to, selection).max(1.0) };
let mut budget = soundcraft_mix::MAX_RENDER_SAMPLES;
for id in &ids {
let Some((track, clip)) = e.session().find_clip(*id) else { continue };
if !clip.is_audio() {
continue;
}
let channels = e.session().track(track).map_or(1, |t| t.channels()).max(1);
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
let frames = (clip.length.max(0) as f64 * grows).ceil() as usize;
budget = budget
.checked_sub(frames.saturating_mul(channels))
.ok_or_else(|| bad("audiosuite.process", "too much audio to process in one command"))?;
}
let mut done = 0;
for id in ids {
let Some((track, clip)) = e.session().find_clip(id).map(|(t, c)| (t, c.clone())) else { continue };
if !clip.is_audio() {
continue;
}
let channels = e.session().track(track).map_or(1, |t| t.channels());
crate::io::refuse_longer(e.session(), "audiosuite.process", &clip.name, "process", clip.length, most.min(crate::io::render_limit(channels)))?;
let mut audio = soundcraft_mix::render_clips(e.session(), track, clip.range());
// Render without the clip's own fades: re-render a copy without fades so they stay editable.
let mut tmp = e.session().clone();
@@ -362,6 +390,40 @@ mod tests {
assert_eq!(e.session().tracks[0].clips().len(), 1, "one clip, not one per duplicate listing");
}
#[test]
fn a_clip_listed_twice_is_processed_once() {
let (mut e, id) = gained_clip();
let out =
e.execute("audiosuite.process", &json!({"process": "time_stretch", "params": {"ratio": 4.0}, "clips": [id.0, id.0, id.0]})).unwrap();
assert_eq!(out["processed"], 1);
let c = e.session().tracks[0].clips()[0].clone();
assert!(c.length <= 64 * 4 + 64, "stretched once, not compounded: {}", c.length);
assert_eq!(e.session().sources.len(), 2, "one new source, not one per listing");
}
#[test]
fn process_refuses_a_total_budget_across_clips() {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Tone"));
let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.5; 64]] };
let src = crate::io::add_source(&mut s, "tone", buf, None, FileFormat::Wav);
// Three clips each within the per-clip limit whose results together exceed the budget.
let len = (soundcraft_mix::MAX_RENDER_SAMPLES / 3 + 1) as i64;
let ids: Vec<u64> = (0..3)
.map(|k| {
let id = s.new_clip_id();
crate::edit::place_clip(&mut s, t, Clip::audio(id, "tone", src, 0, k * len, len));
id.0
})
.collect();
let mut e = crate::Engine::new(s);
let before = serde_json::to_value(e.session()).unwrap();
let out = e.execute("audiosuite.process", &json!({"process": "reverse", "clips": ids}));
let ok = matches!(out, Err(crate::EngineError::BadParams(_, ref m)) if m.contains("too much audio"));
assert!(ok, "three clips over budget, but got: {out:?}");
assert_eq!(serde_json::to_value(e.session()).unwrap(), before, "refused before processing anything");
}
#[test]
fn generate_refuses_a_total_budget_across_tracks() {
let mut e = Engine::new(Session::default());
+6 -2
View File
@@ -162,7 +162,11 @@ pub fn specs() -> Vec<CommandSpec> {
let t = match track {
Some(t) if s.track(t).is_some_and(|x| x.kind == soundcraft_model::TrackKind::Audio) => t,
Some(_) => return Err(bad("clip.place_source", "audio files go on audio tracks")),
None => s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name)),
None => {
let t =
s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::for_channels(chans.min(2)), Some(&name));
crate::no_input::assign_first_input(s, t)
}
};
let (sh, len) = (s.edit.edit_mode == soundcraft_model::EditMode::Shuffle, frames.max(1));
let at = if sh { crate::edit::shuffle_slot(s, t, at, &[]) } else { at };
@@ -301,7 +305,7 @@ const MAX_LOOPS: i64 = 1000;
fn loop_clips(e: &mut Engine, p: &Value) -> Result<Value> {
let ids = clip_ids_param(e, p);
let count = i64_or(p, "count", 4).clamp(1, 512);
let count = i64_or(p, "count", 4).clamp(1, MAX_LOOPS);
let total = position_param(e, "clip.loop", p, "length")?;
let fill = p.get("fill").and_then(Value::as_bool).unwrap_or(false);
let s = e.session_mut();
+7
View File
@@ -469,6 +469,13 @@ mod tests {
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "length": 100_100})).unwrap()["loops"], 1000);
}
#[test]
fn loop_count_accepts_up_to_the_documented_thousand() {
let (mut e, t, ids) = engine_with(&[(0, 100, 0)]);
assert_eq!(e.execute("clip.loop", &json!({"clip": ids[0].0, "count": 600})).unwrap()["loops"], 599);
assert_eq!(e.session().track(t).unwrap().clips().len(), 600);
}
#[test]
fn regroup_reuses_group() {
let (mut e, _, ids) = engine_with(&[(0, 100, 0), (500, 100, 0), (900, 100, 0)]);
+42 -7
View File
@@ -9,7 +9,7 @@ use super::more_util::toggle_flag;
use crate::edit as ops;
use crate::{Clipboard, Engine, Result, cmd};
use serde_json::{Value, json};
use soundcraft_model::{ClipId, EditMode, Fade, FadeShape, Session, TrackId};
use soundcraft_model::{Clip, ClipId, EditMode, Fade, FadeShape, Session, TrackId};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -741,10 +741,9 @@ fn trim_to_file(e: &mut Engine, p: &Value) -> Result<Value> {
if let Some((frames, lo, hi)) = trim_limits(s, id)
&& let Some(c) = s.find_clip_mut(id)
{
let off = c.source_offset();
let new_start = c.start - off;
c.trim_start_to(new_start.max(lo));
c.trim_end_to((new_start + frames).min(hi));
let (file_start, file_end) = file_span(c, frames);
c.trim_start_to(file_start.max(lo));
c.trim_end_to(file_end.min(hi));
n += 1;
}
}
@@ -760,15 +759,24 @@ fn trim_to_fill(e: &mut Engine, p: &Value) -> Result<Value> {
if let Some((frames, lo, hi)) = trim_limits(s, id)
&& let Some(c) = s.find_clip_mut(id)
{
let file_start = c.start - c.source_offset();
let (file_start, file_end) = file_span(c, frames);
c.trim_start_to(r.start.max(file_start).max(lo));
c.trim_end_to(r.end.min(file_start + frames).min(hi));
c.trim_end_to(r.end.min(file_end).min(hi));
n += 1;
}
}
Ok(json!({"trimmed": n}))
}
/// Where a clip's whole source file lies on the timeline. The mixer plays `offset + rel / stretch`,
/// so the file starts `offset * stretch` before the clip and spans `frames * stretch` samples.
fn file_span(c: &Clip, frames: Samples) -> (Samples, Samples) {
let stretch = if c.stretch.is_finite() && c.stretch > 0.0 { c.stretch } else { 1.0 };
let scale = |n: Samples| if (stretch - 1.0).abs() >= 1e-9 { (n as f64 * stretch).round() as Samples } else { n };
let start = c.start.saturating_sub(scale(c.source_offset()));
(start, start.saturating_add(scale(frames)))
}
/// How far a trim may extend an audio clip: its source length in frames, and the earliest
/// start and latest end before it would run over the clip before or after it on the playlist
/// (an extension never overwrites, like the trim tool). An overlap the clip already has with
@@ -1254,6 +1262,33 @@ mod tests {
assert_eq!(bounds(&e, t), vec![(0, 10_000, 0), (10_000, 40_000, 10_000), (40_000, 45_000, 0)]);
}
/// A lone stretched clip (start 20,000, length 10,000, source offset 5,000) over the 60,000-frame source.
fn stretched_trim_session(stretch: f64) -> (Engine, TrackId, Vec<ClipId>) {
let (mut e, t, ids) = trim_session(&[(20_000, 10_000, 5_000)]);
if let Some(c) = e.session_mut().find_clip_mut(ids[0]) {
c.stretch = stretch;
}
(e, t, ids)
}
#[test]
fn trim_to_file_boundaries_covers_the_whole_stretched_file() {
let (mut e, t, ids) = stretched_trim_session(2.0);
e.execute("edit.trim_to_file_boundaries", &json!({"clips": [ids[0].0]})).unwrap();
let (start, end, offset) = bounds(&e, t)[0];
assert_eq!(offset, 0, "the clip starts at the file start");
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "it plays every file frame: {start}..{end}");
}
#[test]
fn trim_to_fill_selection_stops_at_the_stretched_file() {
let (mut e, t, ids) = stretched_trim_session(2.0);
e.execute("edit.trim_to_fill_selection", &json!({"clips": [ids[0].0], "start": 0, "end": 500_000})).unwrap();
let (start, end, offset) = bounds(&e, t)[0];
assert_eq!(offset, 0);
assert!(((end - start) as f64 / 2.0 - 60_000.0).abs() <= 1.0, "a wider selection stops at the file: {start}..{end}");
}
#[test]
fn trim_to_fill_selection_stops_at_the_neighbours() {
let (mut e, t, ids) = trim_session(&[(0, 10_000, 0), (20_000, 10_000, 20_000), (40_000, 5_000, 0)]);
+34 -4
View File
@@ -313,10 +313,16 @@ fn add_marker(e: &mut Engine, p: &Value) -> Result<Value> {
let at = position_param(e, "markers.add", p, "at")?;
let st = position_param(e, "markers.add", p, "start")?;
let en = position_param(e, "markers.add", p, "end")?;
let kind = match str_param(p, "kind") {
Some("selection") => MarkerKind::Selection,
Some("none") => MarkerKind::None,
_ => MarkerKind::Marker,
let kind = match p.get("kind") {
None | Some(Value::Null) => MarkerKind::Marker,
Some(v) => match v.as_str() {
Some("marker") => MarkerKind::Marker,
Some("selection") => MarkerKind::Selection,
Some("none") => MarkerKind::None,
Some(other) => return Err(bad("markers.add", format!("unknown kind `{other}`"))),
// A present non-string is neither a documented kind nor an omitted one.
None => return Err(bad("markers.add", "kind must be a string")),
},
};
let (a, b) = match (at, st, en) {
(Some(a), _, _) => (a, a),
@@ -580,6 +586,30 @@ mod tests {
}
}
/// `markers.add` rejects an unknown or non-string `kind` instead of silently adding a plain
/// marker; an absent or null one still means a plain marker.
#[test]
fn markers_add_rejects_an_unknown_kind() {
let mut e = crate::Engine::default();
let err = e.execute("markers.add", &json!({"name": "x", "kind": "garbage"})).unwrap_err();
assert!(err.to_string().contains("kind"), "unexpected error: {err}");
assert!(e.session().markers.is_empty());
for bad in [json!(123), json!(true), json!(["marker"]), json!({"kind": "marker"}), json!(1.5)] {
let err = e.execute("markers.add", &json!({"name": "x", "kind": bad})).unwrap_err();
assert!(err.to_string().contains("kind"), "{bad}: unexpected error: {err}");
assert!(e.session().markers.is_empty(), "{bad}: a marker was added");
}
let plain = e.execute("markers.add", &json!({"name": "Plain", "kind": null, "at": 500})).unwrap();
assert_eq!(e.session().markers.len(), 1, "null is still an omitted kind");
let verse = e.execute("markers.add", &json!({"name": "Verse", "kind": "marker", "at": 1000})).unwrap();
let pre = e.execute("markers.add", &json!({"name": "Pre", "kind": "none", "at": 2000})).unwrap();
let kind_of =
|e: &crate::Engine, r: &serde_json::Value| e.session().markers.iter().find(|m| Some(m.id.0) == r["id"].as_u64()).map(|m| m.kind);
assert_eq!(kind_of(&e, &plain), Some(soundcraft_model::MarkerKind::Marker));
assert_eq!(kind_of(&e, &verse), Some(soundcraft_model::MarkerKind::Marker));
assert_eq!(kind_of(&e, &pre), Some(soundcraft_model::MarkerKind::None));
}
/// Constant replaces the tempo over [start, end) only; the tempo at the old end tick carries on after it.
#[test]
fn tempo_constant_is_bounded_by_its_range() {
+17
View File
@@ -52,6 +52,23 @@ fn import_audio_places_audio_offered_by_a_worker() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn import_audio_refuses_a_non_audio_target() {
let dir = std::env::temp_dir().join(format!("sc-import-non-audio-target-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let wav = tone_wav(&dir, "tone.wav");
let mut e = Engine::default();
e.execute("track.new", &json!({"kind": "instrument", "name": "Keys"})).unwrap();
let err = e.execute("file.import_audio", &json!({"path": wav, "track": "Keys"})).unwrap_err();
assert!(err.to_string().contains("audio track"), "{err}");
assert_eq!(e.session().tracks.len(), 1);
assert!(e.session().sources.is_empty());
assert!(e.session().tracks[0].clips().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn export_session_text_needs_replace_to_overwrite() {
let dir = std::env::temp_dir().join(format!("sc-export-text-replace-{}", std::process::id()));
+19 -2
View File
@@ -11,7 +11,7 @@ use soundcraft_model::{AutoParam, AutomationMode, INSERT_SLOTS, Insert, SEND_SLO
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mix.volume", "Set Volume", [], None, "{tracks?, db: -144..12 | delta_db}", has_selection, volume),
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1}", has_selection, pan),
cmd!("mix.pan", "Set Pan", [], None, "{tracks?, pan: -1..1, index?: 0|1 (stereo: required, 0 = left, 1 = right)}", has_selection, pan),
cmd!("mix.mute", "Mute", [], Some("Shift+M"), "{tracks?, value?: bool}", has_selection, |e, p| toggle(
e,
p,
@@ -280,8 +280,25 @@ fn pan(e: &mut Engine, p: &Value) -> Result<Value> {
let tracks = tracks_required(e, "mix.pan", p)?;
let v = (p.get("pan").and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("mix.pan", "`pan` (number) required"))? as f32)
.clamp(-1.0, 1.0);
let idx = i64_or(p, "index", 0).clamp(0, 1) as usize;
// A stereo track has one panner per channel, so it must say which: moving only the left one
// by default folded the left channel into the right. An index the track lacks is an error too.
// `null` means no index, as with `slot`. `i64_or` rounds, so the number has to be whole already.
let idx = match p.get("index") {
None | Some(Value::Null) => None,
Some(i) => {
let whole = i.as_f64().is_some_and(|f| f.fract() == 0.0);
Some(usize::try_from(i64_or(p, "index", -1)).ok().filter(|n| whole && *n <= 1).ok_or_else(|| bad("mix.pan", "`index` must be 0 or 1"))?)
}
};
let s = e.session_mut();
for tr in tracks.iter().filter_map(|t| s.track(*t)) {
match (idx, tr.mixer.pan.len()) {
(None, 2) => return Err(bad("mix.pan", format!("`{}` is stereo: give `index` 0 (left channel) or 1 (right channel)", tr.name))),
(Some(1), 1) => return Err(bad("mix.pan", format!("`{}` is mono: its only panner is `index` 0", tr.name))),
_ => {}
}
}
let idx = idx.unwrap_or(0);
for t in &tracks {
if let Some(tr) = s.track_mut(*t)
&& let Some(slot) = tr.mixer.pan.get_mut(idx)
+32
View File
@@ -413,6 +413,38 @@ fn clip_gain_to_volume_with_a_large_envelope_stays_fast() {
assert!(lane.points.len() as i64 >= n);
}
/// A stereo track has a panner per channel. `mix.pan` without `index` used to move only the left
/// one, which folded the left channel into the right.
#[test]
fn panning_a_stereo_track_names_the_channel() {
let mut e = Engine::default();
e.execute("track.new", &json!({"name": "Pad", "format": "stereo"})).unwrap();
e.execute("track.new", &json!({"name": "Vox", "format": "mono"})).unwrap();
let pans = |e: &Engine, name: &str| e.session().tracks.iter().find(|t| t.name == name).map(|t| t.mixer.pan.clone());
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3})).is_err());
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 1.0]), "a refused pan leaves the track alone");
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": -0.3, "index": 1})).unwrap();
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
// A whole number written as a float counts; a fraction is an error (1.4 used to round to 1).
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.4})).is_err());
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, -0.3]));
e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.9, "index": 1.0})).unwrap();
assert_eq!(pans(&e, "Pad"), Some(vec![-1.0, 0.9]));
// `null` means no index, as with `slot`, so a stereo track still needs one.
assert!(e.execute("mix.pan", &json!({"tracks": ["Pad"], "pan": 0.0, "index": null})).is_err());
// A mono track has one panner: no index needed, and any other index is an error, not a no-op.
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.25, "index": null})).unwrap();
assert_eq!(pans(&e, "Vox"), Some(vec![0.25]));
e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.5})).unwrap();
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
for index in [json!(1), json!(2), json!(-1), json!("1"), json!(0.4)] {
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox"], "pan": 0.0, "index": index})).is_err(), "index {index}");
}
// One stereo track without an index stops the whole command.
assert!(e.execute("mix.pan", &json!({"tracks": ["Vox", "Pad"], "pan": 0.2})).is_err());
assert_eq!(pans(&e, "Vox"), Some(vec![0.5]));
}
/// Live input toggles stay outside document history in both enabled and disabled states.
#[test]
fn live_input_states_are_transient_and_survive_document_history() {
+2 -1
View File
@@ -476,7 +476,8 @@ fn import_session_data(e: &mut Engine, p: &Value) -> Result<Value> {
let id = "file.import_session_data";
let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad(id, "`path` required"))?.to_string();
let text_v = crate::io::read_session_text(&path)?;
let other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
let mut other = Session::from_json(&text_v).map_err(|err| EngineError::Io(format!("{path}: {err}")))?;
crate::no_input::upgrade_legacy_inputs(&mut other);
let names: Option<Vec<String>> =
p.get("tracks").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
let picked: Vec<soundcraft_model::Track> = match &names {
+7
View File
@@ -58,6 +58,13 @@ fn tab(e: &mut Engine, p: &Value) -> Result<Value> {
Ok(json!({"selection": r}))
}
/// Whether Tab has a stop after the insertion point or the selection's start. Every stop of a clip lies at or before
/// its end, which is a stop itself.
pub fn tab_stop_ahead(s: &Session) -> bool {
let from = s.edit.selection.start;
s.tracks.iter().filter(|t| s.edit.selected_tracks.contains(&t.id)).flat_map(|t| t.clips()).any(|c| c.start.max(c.end()) > from)
}
/// The nearest stop after `from` (before it when `back`) on the selected tracks.
fn stop(s: &Session, from: Samples, back: bool) -> Option<Samples> {
let nearer = |x: Samples, best: Option<Samples>| {
+12 -16
View File
@@ -98,8 +98,16 @@ pub fn specs() -> Vec<CommandSpec> {
)),
cmd!("track.commit", "Commit...", ["Track"], Some("Alt+Shift+C"), "{tracks?}", has_selection, commit),
cmd!("track.bounce", "Bounce...", ["Track"], Some("Cmd+Alt+Shift+B"), "{tracks?}", has_selection, commit),
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
cmd!("track.mute_sends", "All", ["Track", "Mute Sends"], None, "{tracks?, mute?: bool}", has_selection, mute_sends),
cmd!("track.bypass_inserts", "All", ["Track", "Bypass Inserts"], Some("Shift+A"), "{tracks?, bypass?: bool}", has_selection, bypass_inserts),
cmd!(
"track.mute_sends",
"All",
["Track", "Mute Sends"],
Some("Shift+Q"),
"{tracks?, mute?: bool} (toggles when omitted)",
has_selection,
|e, p| super::track_more::mute_sends_where(e, p, 0, 10)
),
cmd!(noundo "track.set_record_to_input_only", "Set Record Tracks to Input Only", ["Track"], Some("Alt+K"), "{}", always, |e, _| {
let s = e.runtime_session_mut();
let mut n = 0;
@@ -292,6 +300,7 @@ fn new_track_row(e: &mut Engine, p: &Value) -> Result<Vec<TrackId>> {
let mut ids = Vec::new();
for _ in 0..count {
let id = s.add_track(kind, format, name.as_deref());
crate::no_input::assign_first_input(s, id);
if let Some(t) = s.track_mut(id) {
if let Some(tb) = ticks {
t.ticks_timebase = tb;
@@ -466,6 +475,7 @@ fn split_mono(e: &mut Engine, p: &Value) -> Result<Value> {
_ => format!("{}", ch + 1),
};
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{}.{suffix}", src.name)));
crate::no_input::assign_first_input(s, id);
let mut clips = src.clips().to_vec();
for c in &mut clips {
c.id = s.new_clip_id();
@@ -952,20 +962,6 @@ fn bypass_inserts(e: &mut Engine, p: &Value) -> Result<Value> {
Ok(json!({"bypass": target}))
}
fn mute_sends(e: &mut Engine, p: &Value) -> Result<Value> {
let tracks = tracks_required(e, "track.mute_sends", p)?;
let s = e.session_mut();
let target = p.get("mute").and_then(Value::as_bool).unwrap_or(true);
for t in &tracks {
if let Some(tr) = s.track_mut(*t) {
for snd in tr.mixer.sends.iter_mut().flatten() {
snd.mute = target;
}
}
}
Ok(json!({"mute": target}))
}
fn create_click(e: &mut Engine, _: &Value) -> Result<Value> {
let s = e.session_mut();
let id = s.add_track(TrackKind::Aux, ChannelFormat::Mono, Some("Click"));
+66 -31
View File
@@ -68,38 +68,56 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
load_preset
),
cmd!("track.bypass_inserts_ae", "Inserts A-E", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |i, _| i < 5)
cmd!(
"track.bypass_inserts_ae",
"Inserts A-E",
["Track", "Bypass Inserts"],
Some("Shift+2"),
"{tracks?, bypass?: bool}",
has_selection,
|e, p| bypass_where(e, p, |i, _| i < 5)
),
cmd!(
"track.bypass_inserts_fj",
"Inserts F-J",
["Track", "Bypass Inserts"],
Some("Shift+3"),
"{tracks?, bypass?: bool}",
has_selection,
|e, p| bypass_where(e, p, |i, _| (5..10).contains(&i))
),
cmd!(
"track.bypass_eq",
"EQ",
["Track", "Bypass Inserts"],
Some("Shift+E"),
"{tracks?, bypass?: bool} — EQ plug-ins only",
has_selection,
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Eq))
),
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], Some("Shift+C"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Dynamics))
}),
cmd!("track.bypass_inserts_fj", "Inserts F-J", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |i, _| (5..10).contains(&i))
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], Some("Shift+V"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Reverb))
}),
cmd!("track.bypass_eq", "EQ", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool} — EQ plug-ins only", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Eq))
}),
cmd!("track.bypass_dynamics", "Dynamics", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
e,
p,
|_, c| c == Some(Category::Dynamics)
)),
cmd!("track.bypass_reverb", "Reverb", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
e,
p,
|_, c| c == Some(Category::Reverb)
)),
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| bypass_where(
e,
p,
|_, c| c == Some(Category::Delay)
)),
cmd!("track.bypass_modulation", "Modulation", ["Track", "Bypass Inserts"], None, "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Modulation))
cmd!("track.bypass_delay", "Delay", ["Track", "Bypass Inserts"], Some("Shift+D"), "{tracks?, bypass?: bool}", has_selection, |e, p| {
bypass_where(e, p, |_, c| c == Some(Category::Delay))
}),
cmd!(
"track.bypass_modulation",
"Modulation",
["Track", "Bypass Inserts"],
Some("Shift+W"),
"{tracks?, bypass?: bool}",
has_selection,
|e, p| bypass_where(e, p, |_, c| c == Some(Category::Modulation))
),
cmd!(
"track.mute_sends_ae",
"Sends A-E",
["Track", "Mute Sends"],
None,
Some("Shift+4"),
"{tracks?, mute?: bool} (toggles when omitted)",
has_selection,
|e, p| mute_sends_where(e, p, 0, 5)
@@ -108,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"track.mute_sends_fj",
"Sends F-J",
["Track", "Mute Sends"],
None,
Some("Shift+5"),
"{tracks?, mute?: bool} (toggles when omitted)",
has_selection,
|e, p| mute_sends_where(e, p, 5, 10)
@@ -335,7 +353,7 @@ fn bypass_where(e: &mut Engine, p: &Value, pick: fn(usize, Option<Category>) ->
Ok(json!({"bypass": target, "inserts": n}))
}
fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
pub(super) fn mute_sends_where(e: &mut Engine, p: &Value, from: usize, to: usize) -> Result<Value> {
let tracks = tracks_required(e, "track.mute_sends", p)?;
let s = e.session_mut();
let all_muted = tracks.iter().filter_map(|t| s.track(*t)).all(|tr| tr.mixer.sends.iter().skip(from).take(to - from).flatten().all(|x| x.mute));
@@ -502,15 +520,22 @@ fn coalesce_vca(e: &mut Engine, p: &Value) -> Result<Value> {
}
fn designate_target(e: &mut Engine, p: &Value) -> Result<Value> {
let tracks = tracks_required(e, "track.designate_target_playlist", p)?;
let idx = p.get("index").and_then(Value::as_u64);
let id = "track.designate_target_playlist";
let tracks = tracks_required(e, id, p)?;
let index = match p.get("index") {
None | Some(Value::Null) => None,
Some(value) => {
let index = value.as_u64().ok_or_else(|| bad(id, "`index` must be a nonnegative integer"))?;
Some(usize::try_from(index).map_err(|_| bad(id, "no such playlist"))?)
}
};
let s = e.session_mut();
let mut out = Vec::new();
for t in &tracks {
let Some(tr) = s.track(*t) else { continue };
let i = idx.map_or(tr.active_playlist, |x| usize::try_from(x).unwrap_or(usize::MAX));
let i = index.unwrap_or(tr.active_playlist);
if i >= tr.playlists.len() {
return Err(bad("track.designate_target_playlist", "no such playlist"));
return Err(bad(id, "no such playlist"));
}
s.edit.values.insert(format!("playlist.target.{}", t.0), i as f64);
out.push(json!({"track": t, "target": i}));
@@ -574,6 +599,8 @@ mod tests {
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
e.execute("track.mute_sends_ae", &json!({})).unwrap();
assert!(e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
e.execute("track.mute_sends", &json!({})).unwrap();
assert!(!e.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().unwrap().mute);
}
#[test]
@@ -726,11 +753,19 @@ mod tests {
e.execute("track.playlist_new", &json!({})).unwrap();
e.execute("track.designate_target_playlist", &json!({})).unwrap();
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
let kick = e.session().track_by_name("Kick").unwrap().id;
for index in [json!(-1), json!("1"), json!(1.5), json!(u64::MAX)] {
assert!(e.execute("track.designate_target_playlist", &json!({"index": index})).is_err(), "{index}");
assert_eq!(target_playlist(e.session(), kick), Some(1), "{index} must leave the target unchanged");
}
e.execute("track.show_target_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 0);
e.execute("track.toggle_recent_playlist", &json!({})).unwrap();
assert_eq!(e.session().track_by_name("Kick").unwrap().active_playlist, 1);
e.execute("track.playlist_select", &json!({"index": 0})).unwrap();
e.execute("track.designate_target_playlist", &json!({"index": null})).unwrap();
assert_eq!(target_playlist(e.session(), kick), Some(0));
}
}
+2 -1
View File
@@ -29,7 +29,8 @@ pub fn specs() -> Vec<CommandSpec> {
always,
offset
),
cmd!(query "video.list", "Movies", [], None, "{} — movies used by Video tracks (path, size, rate, codec, online file, why it is offline)", always, |e, _| {
cmd!(query "video.list", "Movies", [], None, "{} — lists session movies with media details, clip counts, `file_found`, and any recorded `offline` reason. \
The top-level `online` flag reports the Video Track Online setting.", always, |e, _| {
let s = e.session();
let rows: Vec<Value> = s
.videos
+51 -18
View File
@@ -10,7 +10,8 @@
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - The result must lie inside one of the roots of its kind, compared by whole components
//! (`/work2` isn't inside `/work`), without regard to case on Windows.
//! (`/work2` isn't inside `/work`), by the case the disk stores (links are resolved first, so a
//! differently cased spelling of a root still lands inside it).
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
@@ -266,24 +267,12 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
}
}
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
/// Windows, whose file systems ignore it)?
/// Is `path` (resolved) `root` or inside it, component by component? Both come from
/// `canonicalize`, which gives the name's case as the disk stores it, so equal means the same
/// folder; folding case would equate two folders on a case-sensitive Windows directory.
fn inside(path: &Path, root: &Path) -> bool {
let mut path = path.components();
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
}
fn same_component(a: Component, b: Component) -> bool {
if a == b {
return true;
}
if !cfg!(windows) {
return false;
}
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
_ => false,
}
root.components().all(|r| path.next().is_some_and(|p| p == r))
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
@@ -476,7 +465,7 @@ mod tests {
#[cfg(windows)]
#[test]
fn windows_ignores_case_and_refuses_devices() {
fn windows_resolves_case_and_refuses_devices() {
let (base, roots) = folders("case");
let upper = s(base.join("IN/a.scraft"));
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
@@ -488,6 +477,50 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// On a case-sensitive Windows directory `Work` and `work` are two folders: a root on one
/// doesn't grant the other, while a differently cased spelling of a name that is the same
/// folder (the ordinary, case-insensitive directories) is still accepted. Skipped, with a
/// note, where `fsutil` can't switch a directory to case-sensitive (it needs rights and the
/// NTFS volume's support).
#[cfg(windows)]
#[test]
fn windows_case_sensitive_directory_keeps_case_equal_folders_apart() {
let (base, _) = folders("case-sensitive");
let cs = base.join("cs");
std::fs::create_dir_all(&cs).unwrap();
let switched = std::process::Command::new("fsutil")
.args(["file", "setCaseSensitiveInfo"])
.arg(&cs)
.arg("enable")
.output()
.is_ok_and(|o| o.status.success());
if !switched {
eprintln!("skipped: cannot make {} case-sensitive", cs.display());
let _ = std::fs::remove_dir_all(base);
return;
}
for d in ["Work/sub", "work"] {
std::fs::create_dir_all(cs.join(d)).unwrap();
}
std::fs::write(cs.join("Work/a.scraft"), "x").unwrap();
std::fs::write(cs.join("work/secret.scraft"), "x").unwrap();
let roots = AutomationRoots::new(&[&cs.join("Work")], &[&cs.join("Work")]).unwrap().unwrap();
for access in [Access::Read, Access::Write] {
assert_eq!(roots.check(s(cs.join("Work/a.scraft")), access), Ok(()));
assert_eq!(roots.check(s(cs.join("Work/sub/New.scraft")), access), Ok(()));
// The other folder exists, and so does a name no folder has: both are outside.
for outside in ["work/secret.scraft", "work/new.scraft", "WORK/new.scraft"] {
let e = roots.check(s(cs.join(outside)), access).unwrap_err();
assert!(e.contains("outside the"), "{outside}: {e}");
}
}
// A root on the lower-case folder grants that one only.
let lower = AutomationRoots::new(&[&cs.join("work")], &[]).unwrap().unwrap();
assert_eq!(lower.check(s(cs.join("work/secret.scraft")), Access::Read), Ok(()));
assert!(lower.check(s(cs.join("Work/a.scraft")), Access::Read).is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn scopes_nest_and_stay_on_their_thread() {
let (base, roots) = folders("scopes");
+10 -2
View File
@@ -1097,7 +1097,8 @@ fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::colle
}
/// The record-enabled audio tracks, each with the input channels it records (those its input
/// route names, "In 3" → 2, wrapped to the device's `input_channels`) and a new take file
/// route names, "In 3" → 2, wrapped to the device's `input_channels`; with no input,
/// [`NO_INPUT_CHANNEL`](crate::no_input::NO_INPUT_CHANNEL), which records silence) and a new take file
/// `<track>_<NN>.wav` in the `Audio Files` of the session's folder (`unsaved_dir` until it is saved).
pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<(TrackId, Vec<usize>, PathBuf)> {
let dir = e.path.as_deref().and_then(|p| Path::new(p).parent()).unwrap_or(unsaved_dir);
@@ -1113,7 +1114,11 @@ pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec<
}
_ => 0,
};
let inputs = (0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect();
let inputs = if t.mixer.input == soundcraft_model::Route::None {
vec![crate::no_input::NO_INPUT_CHANNEL; t.channels()]
} else {
(0..t.channels()).map(|k| first.saturating_add(k) % input_channels.max(1)).collect()
};
let file = |n: usize| dir.join("Audio Files").join(format!("{}_{n:02}.wav", sanitize_name(&t.name)));
let path = (take_no..take_no + 1_000).map(file).find(|p| !p.exists()).unwrap_or_else(|| file(take_no));
(t.id, inputs, path)
@@ -1241,7 +1246,10 @@ pub(crate) fn read_aaf_plan(_: &str, _: &str, _: Option<&str>) -> Result<Value>
Err(EngineError::Io("AAF import needs the desktop app: its media files are read from a local folder".into()))
}
// Every test here plants a link, so the module and its helper are Unix-only. `cfg(test)` stays an
// attribute of its own: clippy allows `unwrap` in tests only under a plain `#[cfg(test)]`.
#[cfg(test)]
#[cfg(unix)]
mod exclusive_tests {
use super::*;
+9 -1
View File
@@ -176,6 +176,13 @@ fn place_import(
let file_rate = info.sample_rate;
let s = e.session_mut();
let session_rate = s.sample_rate.hz();
// An explicit non-audio target cannot play the clip: refuse it before registering
// the source, like `clip.place_source` does.
if let Some(t) = target
&& !s.track(t).is_some_and(|tr| tr.kind == TrackKind::Audio)
{
return Err(EngineError::BadParams("file.import_audio".into(), "audio files go on audio tracks".into()));
}
let src = add_source_audio(s, name, audio, path, FileFormat::of(info));
if let (Some(bwf), Some(sx)) = (info.bwf.as_ref(), s.sources.last_mut()) {
sx.time_reference = stamp_at_rate(bwf.time_reference, file_rate, session_rate);
@@ -185,7 +192,8 @@ fn place_import(
Some(t) => t,
None => {
let stem = Path::new(name).file_stem().and_then(OsStr::to_str).unwrap_or("Audio").to_string();
s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem))
let t = s.add_track(TrackKind::Audio, ChannelFormat::for_channels(channels), Some(&stem));
crate::no_input::assign_first_input(s, t)
}
};
let cid = s.new_clip_id();
+94 -8
View File
@@ -87,7 +87,7 @@ fn lost_covers(lost: u8, device: u8) -> bool {
}
/// What `track` recorded of `events` over `range`, in ticks from the start of the range. A key
/// already down when the range starts is left out; one still down at its end ends there, and one
/// already down when the range starts sounds from its start, as long as it is held; one still down at its end ends there, and one
/// whose device lost input ends where that happened. Keys are told apart by device, channel and
/// pitch: the same pitch held on two devices gives two notes. A key held while loop recording
/// goes round ([`MidiTakeEvent::WRAP`]) is two notes: to the end of the loop, and from its start;
@@ -108,9 +108,10 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
// The round of the loop being played: it goes up at every `WRAP`.
let mut round = 0u32;
// Keys down: (device, channel, pitch) -> (start tick, velocity, round, the sample the key was
// pressed at). Whether the loop went round between a press and its release is judged by
// their samples: two positions a few samples apart may share a tick, and a press in the
// last samples of the range starts its note a tick earlier so that it plays.
// pressed at, which is before the range only for a key held into it). Whether the loop went
// round between a press and its release is judged by their samples: two positions a few
// samples apart may share a tick, and a press in the last samples of the range starts its
// note a tick earlier so that it plays.
let mut down: HashMap<(u8, u8, u8), (i64, u8, u32, Samples)> = HashMap::new();
let close = |seq: &mut Sequence,
(_, channel, pitch): (u8, u8, u8),
@@ -152,7 +153,16 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
round = round.saturating_add(1);
continue;
}
if e.at < range.start || e.at >= range.end {
if e.at < range.start {
// Before the range (the pre-roll, or before the punch-in): a key pressed there and
// still down when the range starts is recorded from the start of the range, "the
// start of the note is quantized to the punch-in point" (Reference Guide p.822).
// An entry there that ends a note pressed in the range is a late callback, as below.
if round > 0 || held_into_range(s, input, devices, e, &mut down, range.start) {
continue;
}
}
if e.at >= range.end {
continue;
}
let at = tick(e.at);
@@ -175,7 +185,7 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
match e.status & 0xF0 {
0x90 if d2 > 0 => {
// The same key again without a release: the first note ends here.
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at)) {
if let Some(open) = down.insert(key, (at.min(last_start), d2, round, e.at.max(range.start))) {
close(&mut seq, key, open, at, 64, round, e.at);
}
}
@@ -209,6 +219,45 @@ fn midi_take_sequence(s: &Session, input: &MidiInput<'_>, range: Range, pass: Mi
seq
}
/// Follow the keys pressed and released before a record range starts, in `down` (as the take
/// builder keeps them: start tick, velocity, round, the sample the key was pressed at, which for
/// these keys alone is before `start`). A key still down when the range starts goes on from its
/// first tick; one released before it, or whose device lost input, leaves nothing. Returns
/// false when `e` is left to the range: a lost-input entry (for the keys pressed in the range),
/// or an entry for a key pressed in the range, stamped early by a late audio callback.
fn held_into_range(
s: &Session,
input: &MidiInput<'_>,
devices: &[String],
e: &MidiTakeEvent,
down: &mut HashMap<(u8, u8, u8), (i64, u8, u32, Samples)>,
start: Samples,
) -> bool {
if e.status == MidiTakeEvent::LOST {
down.retain(|k, open| open.3 >= start || !lost_covers(e.device, k.0));
return false;
}
let channel = e.status & 0x0F;
if midi_filtered(s, e.status) || !input.accepts(devices.get(usize::from(e.device)).map(String::as_str), channel) {
return true;
}
let key = (e.device, channel, e.data1 & 0x7F);
let note = matches!(e.status & 0xF0, 0x80 | 0x90);
if note && down.get(&key).is_some_and(|open| open.3 >= start) {
return false;
}
match e.status & 0xF0 {
0x90 if e.data2 & 0x7F > 0 => {
down.insert(key, (0, e.data2 & 0x7F, 0, e.at));
}
0x80 | 0x90 => {
down.remove(&key);
}
_ => {}
}
true
}
/// Most events of one MIDI record pass that are kept.
pub const MAX_MIDI_TAKE_EVENTS: usize = 1 << 20;
@@ -310,7 +359,7 @@ mod tests {
assert_eq!(e.session().busses.len(), 0, "a MIDI input is not a bus name");
assert!(records_midi(&e));
let events = [
ev(40_000, 0, 0x90, 59, 80), // before the pass: left out, and so is its release
ev(40_000, 0, 0x90, 59, 80), // before the pass, released inside it: from the pass start
ev(48_000, 0, 0x90, 60, 100), // one beat at 120 bpm, 48 kHz: 24 000 samples = 960 ticks
ev(50_000, 0, 0x80, 59, 0),
ev(60_000, 1, 0x99, 36, 127),
@@ -328,7 +377,7 @@ mod tests {
assert_eq!((before, take.clips.len(), take.gaps), (0, 2, 0), "the track whose device was silent gets no clip");
let keys = sequence(&e, all, range);
let notes: Vec<(u8, u8, i64, i64, u8)> = keys.notes.iter().map(|n| (n.channel, n.pitch, n.start, n.length, n.release_velocity)).collect();
assert_eq!(notes, [(0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
assert_eq!(notes, [(0, 59, 0, 80, 0), (0, 60, 0, 960, 30), (9, 36, 480, 960, 64), (0, 67, 1880, 40, 64)]);
assert_eq!(
keys.ctrls.iter().map(|c| (c.tick, c.kind, c.value)).collect::<Vec<_>>(),
[(960, CtrlKind::PitchBend, 4096), (1680, CtrlKind::Cc(64), 127)]
@@ -345,6 +394,28 @@ mod tests {
assert!(add_midi_recording(&mut e, Range::new(5, 5), &events, &devices, false).clips.is_empty());
}
#[test]
fn a_key_held_into_the_punch_in_is_recorded_from_the_punch_in() {
// Reference Guide p.822: played before the punch-in point, released after it.
let s = Session::default();
let range = Range::new(48_000, 144_000);
let events = [
ev(24_000, 0, 0x90, 60, 100), // held into the range
ev(30_000, 0, 0x90, 62, 100), // pressed and released before it: nothing
ev(36_000, 0, 0x80, 62, 0),
ev(40_000, 0, 0x90, 64, 90), // another one released before it
ev(44_000, 0, 0x80, 64, 0),
ev(72_000, 0, 0x80, 60, 30), // the held key, released one quarter into the range
ev(96_000, 0, 0x90, 67, 100),
ev(120_000, 0, 0x80, 67, 0),
];
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events, &[]));
assert_eq!(got, [(0, 60, 0, 960, 100, 30), (0, 67, 1920, 960, 100, 0)]);
// A key still down at the end of the range covers all of it.
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &events[..1], &[]));
assert_eq!(got, [(0, 60, 0, 3840, 100, 64)]);
}
#[test]
fn the_same_pitch_on_two_devices_is_two_notes_and_lost_input_ends_only_its_device() {
let mut e = Engine::default();
@@ -550,6 +621,21 @@ mod tests {
let marked = [ev(24_000, 0, 0x90, 60, 100), ev(96_000, u8::MAX, MidiTakeEvent::WRAP, 0, 0), ev(48_000, 0, 0x80, 60, 0)];
let got = notes_of(&midi_take_sequence(&s, &MidiInput::default(), range, MidiPass::Linear, &marked, &[]));
assert_eq!(got.iter().map(|n| (n.2, n.3)).collect::<Vec<_>>(), [(960, 960)]);
// A punch range: a key pressed in it whose release is stamped before its start is one
// short note at the press too, and a key pressed and released before it stays out.
let punch = Range::new(48_000, 144_000);
let events = [
ev(30_000, 0, 0x90, 62, 100),
ev(36_000, 0, 0x80, 62, 0),
ev(49_000, 0, 0x90, 60, 100),
ev(47_000, 0, 0x80, 60, 40),
ev(72_000, 0, 0x90, 64, 100),
ev(47_400, 0, 0xB0, 64, 127), // a controller stamped there is still left out
ev(47_500, u8::MAX, MidiTakeEvent::LOST, 0, 0),
];
let seq = midi_take_sequence(&s, &MidiInput::default(), punch, MidiPass::Linear, &events, &[]);
assert_eq!(notes_of(&seq), [(0, 60, 40, 1, 100, 40), (0, 64, 960, 1, 100, 64)]);
assert!(seq.ctrls.is_empty());
}
#[test]
+3 -1
View File
@@ -562,7 +562,9 @@ mod open_tests {
let at = |f: &str| dir.join(f).to_string_lossy().into_owned();
assert_eq!(got[0], (stored_path("Movies/here.mov", &session).unwrap().to_string_lossy().into_owned(), None));
assert_eq!(got[1], (at("near.mov"), None));
assert_eq!(got[2], (at("Video Files/filed.mov"), None));
// Joined part by part, as `relink_videos` does: `join("Video Files/filed.mov")` keeps the `/`,
// which differs from the relinked path on Windows.
assert_eq!(got[2], (dir.join("Video Files").join("filed.mov").to_string_lossy().into_owned(), None));
assert_eq!(got[3], ("Old/gone.mov".into(), Some("file not found".into())));
assert_eq!(got[4].0, stored[4]);
assert!(got[4].1.as_deref().is_some_and(|why| why.starts_with("not opened:")), "{:?}", got[4]);
+7 -3
View File
@@ -18,6 +18,7 @@ pub mod feature_names;
pub mod file_access;
pub mod inspect;
pub mod io;
pub mod no_input;
pub mod score;
use serde_json::{Value, json};
@@ -220,8 +221,9 @@ impl Default for Engine {
}
impl Engine {
pub fn new(session: Session) -> Self {
pub fn new(mut session: Session) -> Self {
install_panic_hook();
no_input::upgrade_legacy_inputs(&mut session);
let doc = Arc::new(session);
Engine {
saved: Arc::clone(&doc),
@@ -296,8 +298,10 @@ impl Engine {
&mut Arc::make_mut(&mut self.doc).edit.zoom
}
/// Replace the whole document (open / new); clears history.
pub fn replace_session(&mut self, s: Session) {
/// Replace the whole document (open / new); clears history. A session saved before "no
/// input" existed is upgraded ([`no_input::upgrade_legacy_inputs`]).
pub fn replace_session(&mut self, mut s: Session) {
no_input::upgrade_legacy_inputs(&mut s);
self.transport = TransportStatus { position: s.edit.selection.start.max(0), ..TransportStatus::default() };
self.transport_requests.clear();
self.transport_requests.push(TransportRequest::ResetSession);
+122
View File
@@ -0,0 +1,122 @@
//! "no input" on an audio track (`Route::None`): the track records and monitors nothing, as
//! Pro Tools' No Input does. A new audio track gets its first input path explicitly instead.
//!
//! Sessions saved before this rule used `Route::None` for an audio track that recorded and
//! monitored hardware input 1 (the selector showed "In 1"). [`upgrade_legacy_inputs`] turns
//! those into the explicit first input when such a session is opened, so it keeps sounding and
//! recording as before. Sessions held by the engine carry [`NO_INPUT_MARKER`], so a "no input"
//! saved by this build stays "no input" when it is opened again.
use soundcraft_model::{ChannelFormat, Route, Session, TrackKind};
/// Set in `edit.flags` of every session the engine holds: its `Route::None` audio inputs mean
/// "no input". A session without it was saved before that, when they meant hardware input 1.
pub const NO_INPUT_MARKER: &str = "io.none_is_no_input";
/// The input channel an audio track with no input records: no device has it, so the take is
/// digital silence.
pub const NO_INPUT_CHANNEL: usize = usize::MAX;
/// The first hardware input path of a track of `format`: "In 1", "In 1-2", "In 1-6"…
pub fn first_input(format: ChannelFormat) -> Route {
match format.channels() {
0 | 1 => Route::Hardware("In 1".into()),
n => Route::Hardware(format!("In 1-{n}")),
}
}
/// Give the new track `id`, if it is an audio track, its first input path (Pro Tools assigns
/// new tracks an input path), and return `id`.
pub(crate) fn assign_first_input(s: &mut Session, id: soundcraft_model::TrackId) -> soundcraft_model::TrackId {
if let Some(t) = s.track_mut(id)
&& t.kind == TrackKind::Audio
&& t.mixer.input == Route::None
{
t.mixer.input = first_input(t.format);
}
id
}
/// A session saved before [`NO_INPUT_MARKER`]: each audio track whose input is `Route::None`
/// recorded and monitored hardware input 1, so it gets that input explicitly. Then the session
/// is marked, and running this again changes nothing.
pub fn upgrade_legacy_inputs(s: &mut Session) {
if s.edit.flag(NO_INPUT_MARKER) {
return;
}
for t in &mut s.tracks {
if t.kind == TrackKind::Audio && t.mixer.input == Route::None {
t.mixer.input = first_input(t.format);
}
}
s.edit.set_flag(NO_INPUT_MARKER, true);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Engine;
use serde_json::json;
use soundcraft_model::TrackId;
fn new_track(e: &mut Engine, format: &str) -> TrackId {
TrackId(e.execute("track.new", &json!({"format": format})).unwrap()["tracks"][0].as_u64().unwrap())
}
fn input(e: &Engine, t: TrackId) -> Route {
e.session().track(t).unwrap().mixer.input.clone()
}
#[test]
fn a_new_audio_track_gets_its_first_input_path() {
let mut e = Engine::default();
let mono = new_track(&mut e, "mono");
let stereo = new_track(&mut e, "stereo");
assert_eq!(input(&e, mono), Route::Hardware("In 1".into()));
assert_eq!(input(&e, stereo), Route::Hardware("In 1-2".into()));
let aux = TrackId(e.execute("track.new", &json!({"kind": "aux"})).unwrap()["tracks"][0].as_u64().unwrap());
assert_eq!(input(&e, aux), Route::None, "only audio tracks take a hardware input by default");
}
#[test]
fn a_track_with_no_input_records_no_device_channel() {
let dir = std::env::temp_dir().join(format!("soundcraft-no-input-{}", std::process::id()));
let mut e = Engine::default();
let vox = new_track(&mut e, "mono");
let gtr = new_track(&mut e, "stereo");
e.execute("track.input", &json!({"tracks": [vox.0, gtr.0], "input": "none"})).unwrap();
e.execute("mix.record_arm", &json!({"tracks": [vox.0, gtr.0], "value": true})).unwrap();
let plan = crate::io::plan_takes(&e, &dir, 30);
assert_eq!(
plan.iter().map(|(t, inputs, _)| (*t, inputs.clone())).collect::<Vec<_>>(),
vec![(vox, vec![NO_INPUT_CHANNEL]), (gtr, vec![NO_INPUT_CHANNEL; 2])]
);
}
#[test]
fn a_session_saved_before_no_input_existed_keeps_recording_input_1() {
let mut old = Session::default();
let vox = old.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Vox"));
let gtr = old.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Gtr"));
let keys = old.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys"));
let text = old.to_json().unwrap();
assert!(!text.contains(NO_INPUT_MARKER));
let mut e = Engine::default();
e.replace_session(Session::from_json(&text).unwrap());
assert_eq!(input(&e, vox), Route::Hardware("In 1".into()));
assert_eq!(input(&e, gtr), Route::Hardware("In 1-2".into()));
assert_eq!(input(&e, keys), Route::None, "a MIDI input is left alone");
assert!(!e.is_dirty(), "opening an old session does not modify it");
}
#[test]
fn no_input_survives_save_and_reopen() {
let mut e = Engine::default();
let vox = new_track(&mut e, "mono");
e.execute("track.input", &json!({"tracks": [vox.0], "input": "no input"})).unwrap();
let text = e.session().to_json().unwrap();
let mut reopened = Engine::default();
reopened.replace_session(Session::from_json(&text).unwrap());
assert_eq!(input(&reopened, vox), Route::None);
}
}
+102
View File
@@ -437,3 +437,105 @@ fn repeated_local_mob_references_fail_before_property_expansion() {
let err = f.preview().unwrap_err().to_string();
assert!(err.contains("duplicate local reference in mobs"), "{err}");
}
/// A FilmCraft-style AAF that references one external mono PCM WAV per channel, written by the
/// shared `craft-aaf` writer around WAVs generated here.
struct MonoWavAaf {
dir: PathBuf,
}
impl MonoWavAaf {
fn new(wav_channels: usize) -> Self {
use craft_aaf::model::{CClip, CItem, CKind, CTrack, Composition, Document, Source};
use craft_aaf::time::{FrameRate, Tick};
static NEXT: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!("soundcraft-aaf-mono-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir(&dir).unwrap();
let frames = 96_000;
let options = EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(BitDepth::Int16);
let mut sources = Vec::new();
let mut tracks = Vec::new();
for (i, name) in ["Dialogue.A1.wav", "Dialogue.A2.wav"].into_iter().enumerate() {
let audio = AudioBuffer { sample_rate: 48000, channels: vec![vec![0.25; frames]; wav_channels] };
let path = dir.join(name);
std::fs::write(&path, craft_audio::encode(&audio, &options).unwrap()).unwrap();
sources.push(Source {
key: "item:1".into(),
name: name.into(),
kind: CKind::Sound,
path: Some(path.display().to_string()),
channel: None,
channels: 1,
file_channels: 1,
width: 0,
height: 0,
frame_rate: FrameRate::FPS_25,
sample_rate: 48000,
bits: 16,
length: Tick::from_units(frames as i64, 48000),
offset: Tick::ZERO,
start_tc: None,
tc_rate: FrameRate::FPS_25,
embedded: None,
markers: Vec::new(),
nested: None,
});
let clip = CClip { len: Tick::from_units(25, 25), source: i, start: Tick::ZERO, gain: None, name: format!("Cut {}", i + 1) };
tracks.push(CTrack {
kind: CKind::Sound,
name: format!("A{}", i + 1),
number: i as u32 + 1,
channels: 1,
items: vec![CItem::Clip(clip)],
});
}
let composition = Composition {
name: "Separate mono".into(),
aaf_mob_id: None,
rate: FrameRate::FPS_25,
sample_rate: 48000,
width: 1920,
height: 1080,
start_tc: 0,
drop: false,
tracks,
markers: Vec::new(),
};
let doc = Document { compositions: vec![composition], sources, ..Document::default() };
let identity =
craft_aaf::Identity { company: "Craft", product: "soundcraft tests", version: "1", platform: "test", product_id: *b"soundcraft-test." };
let bytes =
craft_aaf::aaf::write(&doc, &craft_aaf::aaf::WriteOptions { identity, small_sectors: false }, &mut craft_aaf::Report::default()).unwrap();
std::fs::write(dir.join("Separate mono.aaf"), bytes).unwrap();
Self { dir }
}
fn preview(&self) -> soundcraft_engine::Result<Value> {
Engine::default().execute("file.preview_aaf", &json!({"path": self.dir.join("Separate mono.aaf"), "media_dir": self.dir}))
}
}
impl Drop for MonoWavAaf {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
#[test]
fn separate_mono_pcm_wav_aaf_imports_one_mono_track_per_file() {
let f = MonoWavAaf::new(1);
let preview = f.preview().unwrap();
let plan = &preview["plan"];
let channels: Vec<_> = plan["sources"].as_array().unwrap().iter().map(|s| s["channels"].as_u64().unwrap()).collect();
assert_eq!(channels, [1, 1]);
let mut e = Engine::default();
e.execute("file.import_aaf", &json!({"plan": plan, "media_dir": f.dir, "selected": [0, 1]})).unwrap();
assert_eq!(e.session().tracks.len(), 2);
assert!(e.session().tracks.iter().all(|t| t.channels() == 1 && t.clips().len() == 1));
let sources: Vec<_> = e.session().tracks.iter().map(|t| t.clips()[0].source()).collect();
assert_ne!(sources[0], sources[1], "each channel file is its own source");
}
#[test]
fn a_pcm_descriptor_whose_channel_count_differs_from_its_wav_is_refused() {
let f = MonoWavAaf::new(2);
let err = f.preview().unwrap_err().to_string();
assert!(err.contains("channel counts differ"), "{err}");
}
@@ -18,7 +18,7 @@ fn kick_trim(e: &Engine) -> f32 {
#[test]
fn mix_pan_rejects_a_missing_or_non_numeric_pan_and_keeps_the_pan() {
let mut e = engine_with_kick();
e.execute("mix.pan", &json!({"tracks": ["Kick"], "pan": -1.0})).unwrap();
e.execute("mix.pan", &json!({"tracks": ["Kick"], "pan": -1.0, "index": 0})).unwrap();
assert_eq!(kick_pan(&e)[0], -1.0);
for params in [json!({"tracks": ["Kick"]}), json!({"tracks": ["Kick"], "pan": "left"}), json!({"tracks": ["Kick"], "pan": null})] {
+1 -1
View File
@@ -68,8 +68,8 @@ fn insertion_trims_still_trim_unlocked_clips_beside_both_lock_kinds() {
for clip in &mut session.track_mut(track).unwrap().playlist_mut().unwrap().clips {
clip.start = 0;
}
let before = session.clone();
let mut engine = Engine::new(session);
let before = engine.session().clone();
let result = engine.execute(command, &json!({"tracks": [track.0], "at": 50})).unwrap();
assert_eq!(result["trimmed"], json!(1), "{command}");
let clips = engine.session().track(track).unwrap().clips();
+119
View File
@@ -0,0 +1,119 @@
//! Existing commands/history and saved session PCM for bounded send automation.
use craft_audio::AudioBuffer;
use serde_json::json;
use soundcraft_engine::{Engine, io};
use soundcraft_model::{AutoParam, ChannelFormat, Clip, FileFormat, Route, Session, TrackKind};
use soundcraft_time::Range;
use std::sync::Arc;
fn fixture() -> Engine {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Original"));
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 512]] };
let src = io::add_source(&mut s, "Original synthetic", buffer, None, FileFormat::Wav);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original", src, 0, 0, 512));
s.track_mut(t).unwrap().mixer.output = Route::None;
let mut e = Engine::new(s);
e.execute("mix.new_bus", &json!({"name":"Send","format":"stereo"})).unwrap();
e.execute("mix.send", &json!({"track":"Original","bus":"Send","slot":"A","level_db":0})).unwrap();
e.execute("track.new", &json!({"name":"Return","kind":"aux","format":"stereo"})).unwrap();
let bus = e.session().busses.iter().find(|b| b.name == "Send").unwrap().id;
let aux = e.session().tracks.iter().find(|t| t.kind == TrackKind::Aux).unwrap().id;
e.session_mut().track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
e.mark_clean();
e
}
fn render(e: &Engine) -> Vec<Vec<f32>> {
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 512), 37);
assert_eq!(out.len(), 2);
assert!(out.iter().all(|c| c.len() == 512));
out
}
fn point(e: &mut Engine, param: &str, at: i64, value: f32) {
e.execute("automation.set_point", &json!({"track":"Original","param":param,"at":at,"value":value})).unwrap();
}
#[test]
fn commands_undo_redo_reuse_renderer_and_preserve_render_state() {
let mut e = fixture();
let baseline = render(&e);
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_pan", 173, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let before = render(&e);
point(&mut e, "send_a_mute", 97, 1.0);
let after = render(&e);
assert_ne!(before, after);
assert_ne!(baseline, before);
let arc = e.session_arc();
let serialized = e.session().to_json().unwrap();
let revision = e.revision;
let history = e.undo_history();
let dirty = e.is_dirty();
let mut mix = soundcraft_mix::MixEngine::new(48_000.0, 512);
let mut out = vec![vec![0.0; 512]; 2];
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
mix.render(e.session(), 97, 13, &mut out);
assert!(Arc::ptr_eq(&arc, &e.session_arc()));
assert_eq!(serialized, e.session().to_json().unwrap());
assert_eq!(revision, e.revision);
assert_eq!(history, e.undo_history());
assert_eq!(dirty, e.is_dirty());
assert!(e.undo());
assert_eq!(render(&e), before);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, before);
assert!(e.redo());
assert_eq!(render(&e), after);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
e.execute("mix.automation_mode", &json!({"track":"Original","mode":"off"})).unwrap();
assert_eq!(render(&e), baseline);
}
#[test]
fn lane_commands_survive_folder_and_bundle_save_reopen_with_exact_pcm() {
let mut e = fixture();
e.execute("mix.send_level", &json!({"track":"Original","slot":"A","pan":0.5,"mute":true})).unwrap();
point(&mut e, "send_a_pan", 37, -1.0);
point(&mut e, "send_a_pan", 401, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
e.execute("automation.write_range", &json!({"track":"Original","param":"send_a_mute","start":97,"end":173,"value":1.0})).unwrap();
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let dir = std::env::temp_dir().join(format!("soundcraft-send-automation-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("Original/Send.scraft").to_string_lossy().into_owned();
io::save_session(&mut e, &path).unwrap();
let mut reopened = Engine::default();
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
assert_eq!(render(&reopened), expected);
let tr = reopened.session().tracks.iter().find(|t| t.name == "Original").unwrap();
assert_eq!(tr.lane(&AutoParam::SendPan(0)).unwrap().points.len(), 2);
assert!(!reopened.is_dirty());
assert!(!reopened.can_undo());
let (bundle, _) = io::session_bundle(e.session()).unwrap();
let mut bundled = Engine::default();
io::open_session_bytes(&mut bundled, "Send.scraftz", &bundle).unwrap();
assert_eq!(render(&bundled), expected);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn absent_enabled_field_keeps_legacy_reader_behavior() {
let mut e = fixture();
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let mut json = serde_json::to_value(e.session()).unwrap();
for track in json["tracks"].as_array_mut().unwrap() {
for lane in track["automation"].as_array_mut().unwrap() {
lane.as_object_mut().unwrap().remove("enabled");
}
}
let mut old: Session = serde_json::from_value(json).unwrap();
old.pool = e.session().pool.clone();
let tr = old.tracks.iter().find(|t| t.name == "Original").unwrap();
assert!(tr.automation.iter().all(|l| !l.enabled));
assert_eq!(soundcraft_mix::render_range(&old, Range::new(0, 512), 100), expected);
}
+48 -10
View File
@@ -3,7 +3,7 @@
//! Reads the AAF structured-storage object model directly (properties streams, strong
//! reference vectors/sets and dictionary weak references) for a deliberately small subset:
//! one CompositionMob whose timeline slots hold Sequences of SourceClip and Filler, resolved
//! through MasterMobs to SourceMobs with a WAVEDescriptor and one external NetworkLocator.
//! through MasterMobs to SourceMobs with a WAVE or PCM descriptor and one external NetworkLocator.
//! Anything else in an audio slot aborts instead of producing a misleading montage.
//!
//! No filesystem access happens here: the caller passes the opened AAF and a [`MediaResolver`]
@@ -32,6 +32,7 @@
//! locator resolves under the AAF's folder (see `locator_path`). A file that cannot be found
//! is reported and its edits skipped; it does not abort the import.
use crate::{ImportClip, ImportError, ImportTrack, Media, Plan, Rational, TimecodeRate};
use craft_aaf::aaf::linked_audio::{AudioFileDescriptor, DescriptorFieldError, DescriptorKind, DescriptorProperty};
use craft_aaf::aaf::properties::{Properties, Property, PropertyError};
use std::{
collections::{HashMap, HashSet},
@@ -80,8 +81,6 @@ const PID_CONTENT_ESSENCE: u16 = 0x1902;
const PID_DEF_NAME: u16 = 0x1B02;
const PID_ESSENCE_MOB_ID: u16 = 0x2701;
const PID_DESCRIPTOR_LOCATORS: u16 = 0x2F01;
const PID_FILE_SAMPLE_RATE: u16 = 0x3001;
const PID_FILE_LENGTH: u16 = 0x3002;
const PID_HEADER_CONTENT: u16 = 0x3B03;
const PID_URL_STRING: u16 = 0x4001;
const PID_MOB_ID: u16 = 0x4401;
@@ -230,6 +229,8 @@ impl Q {
struct Obj {
path: String,
class: String,
/// The class AUID in on-disk byte order, as the shared descriptor view classifies it.
auid: [u8; 16],
// Cached objects are cloned along source and dictionary walks; share their property payload.
props: Rc<HashMap<u16, (u16, Vec<u8>)>>,
}
@@ -269,6 +270,16 @@ impl Obj {
fn is(&self, class: &str) -> bool {
self.class == class
}
/// The shared typed view of a WAVE or PCM file descriptor (craft-libs#3180); `None` for any
/// other class.
fn audio_descriptor<'a>(&'a self) -> Option<AudioFileDescriptor<impl Fn(u16) -> DescriptorProperty<'a> + 'a>> {
let kind = DescriptorKind::from_auid_le(self.auid)?;
Some(AudioFileDescriptor::new(kind, move |pid| match self.props.get(&pid) {
None => DescriptorProperty::Missing,
Some((form, data)) if *form == SF_DATA => DescriptorProperty::Data(data),
Some(_) => DescriptorProperty::OtherForm,
}))
}
/// Class name for messages; unknown (extension) classes print their AUID.
fn kind(&self) -> &str {
CLASS_NAMES.iter().find(|(id, _)| *id == self.class).map_or(self.class.as_str(), |(_, n)| n)
@@ -295,6 +306,13 @@ fn property_error(path: &str, e: PropertyError) -> ImportError {
}
}
fn descriptor_error(field: &str, e: DescriptorFieldError) -> ImportError {
match e {
DescriptorFieldError::Missing | DescriptorFieldError::Truncated => fail(format!("missing or short descriptor {field}")),
DescriptorFieldError::OtherForm => fail(format!("descriptor {field} is not a data property")),
}
}
fn property_total(current: usize, additional: usize) -> Result<usize> {
current.checked_add(additional).filter(|total| *total <= MAX_PROPERTY_BYTES).ok_or_else(|| fail("AAF retained property data exceeds 128 MiB"))
}
@@ -391,6 +409,7 @@ impl<F: Read + Seek> Store<F> {
return Err(fail(format!("{path}: not an AAF object")));
}
let class = entry.clsid().to_string();
let auid = entry.clsid().to_bytes_le();
let props_path = if path == "/" { "/properties".to_string() } else { format!("{path}/properties") };
let d = self.stream(&props_path)?.ok_or_else(|| fail(format!("{path}: missing properties")))?;
if d.first() != Some(&0x4c) {
@@ -411,7 +430,7 @@ impl<F: Read + Seek> Store<F> {
let Property { id, form, payload } = record.map_err(|e| property_error(path, e))?;
props.insert(id, (form, payload.to_vec()));
}
let object = Obj { path: path.to_string(), class, props: Rc::new(props) };
let object = Obj { path: path.to_string(), class, auid, props: Rc::new(props) };
self.objects.insert(path.to_string(), object.clone());
Ok(object)
}
@@ -670,7 +689,7 @@ impl<F: Read + Seek> Builder<'_, F> {
}
if mob.is(CLASS_SOURCE_MOB) {
let desc = self.store.opt_strong(&mob, PID_SOURCE_MOB_DESCRIPTOR, "EssenceDescription")?;
if let Some(desc) = desc.filter(|d| d.is(CLASS_WAVE_DESCRIPTOR)) {
if let Some(desc) = desc.filter(|d| d.audio_descriptor().is_some()) {
return self.file_source(&mob, &slot, &desc, key_urn, offset);
}
}
@@ -691,12 +710,20 @@ impl<F: Read + Seek> Builder<'_, F> {
}
fn file_source(&mut self, mob: &Obj, slot: &Obj, desc: &Obj, key: String, offset: Q) -> Result<(String, Q)> {
// Full interleaved WAV only: selecting one physical channel needs a channel map.
if !matches!(slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?, None | Some(0)) {
// Full interleaved WAV only: selecting one physical channel needs a channel map. Track 1
// of a mono file is the whole file (checked once the file is probed).
let physical = slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?;
if !matches!(physical, None | Some(0 | 1)) {
return Err(fail("Physical channel selection / split stereo unsupported"));
}
// Each source file is located, probed and reported once, however many edits use it.
if self.sources.iter().any(|s| s.key == key) || self.missing.iter().any(|m| m.key == key) {
if let Some(source) = self.sources.iter().find(|s| s.key == key) {
if physical == Some(1) && source.channels != 1 {
return Err(fail("Physical channel selection / split stereo unsupported"));
}
return Ok((key, offset));
}
if self.missing.iter().any(|m| m.key == key) {
return Ok((key, offset));
}
let name = mob.string(PID_MOB_NAME);
@@ -721,12 +748,23 @@ impl<F: Read + Seek> Builder<'_, F> {
if !matches!(info.channels, 1 | 2) {
return Err(fail("Only mono/stereo PCM WAV supported"));
}
if desc.rational(PID_FILE_SAMPLE_RATE, "descriptor SampleRate")? != Q::int(i64::from(info.sample_rate)) {
let fields =
desc.audio_descriptor().ok_or_else(|| fail(format!("Unsupported referenced mob/descriptor: {}", name.clone().unwrap_or_default())))?;
let (num, den) = fields.sample_rate().map_err(|e| descriptor_error("SampleRate", e))?;
if Q::new(i128::from(num), i128::from(den))? != Q::int(i64::from(info.sample_rate)) {
return Err(fail(format!("Descriptor/file sample rates differ: {}", name.unwrap_or_default())));
}
if u64::try_from(desc.i64(PID_FILE_LENGTH, "descriptor Length")?).ok() != Some(info.frames) {
if u64::try_from(fields.length().map_err(|e| descriptor_error("Length", e))?).ok() != Some(info.frames) {
return Err(fail(format!("Descriptor/file lengths differ: {}", name.unwrap_or_default())));
}
if let Some(declared) = fields.pcm_channels().map_err(|e| descriptor_error("Channels", e))?
&& declared != u32::from(info.channels)
{
return Err(fail(format!("Descriptor/file channel counts differ: {}", name.unwrap_or_default())));
}
if physical == Some(1) && info.channels != 1 {
return Err(fail("Physical channel selection / split stereo unsupported"));
}
let stem = Path::new(&info.path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
self.sources.push(Media {
key: key.clone(),
+46 -10
View File
@@ -70,6 +70,7 @@ mod midi;
mod offline;
mod pan;
mod routing;
mod send_automation;
mod strip;
mod threads;
@@ -263,12 +264,18 @@ impl MixEngine {
for s in self.strips.values_mut() {
for p in s.plugins.iter_mut().flatten() {
p.plugin.reset();
p.failed = false;
if p.failed && !p.retried {
p.failed = false;
p.retried = true;
}
}
if let Some(i) = &mut s.instrument {
i.plugin.all_notes_off();
i.plugin.reset();
i.failed = false;
if i.failed && !i.retried {
i.failed = false;
i.retried = true;
}
}
s.held.clear();
s.chase = true;
@@ -356,7 +363,7 @@ impl MixEngine {
}
for b in &s.busses {
let n = b.format.channels().clamp(1, MAX_CHANNELS);
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new() });
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new(), age: send_automation::SignalAge::Empty });
bus.fmt = b.format;
if bus.buf.len() != n {
bus.buf = vec![vec![0.0; mb]; n];
@@ -383,7 +390,7 @@ impl MixEngine {
self.begin_block(s, pos, frames);
let blk = Block { pos, frames, any_solo: any_solo(s) };
let order = std::mem::take(&mut self.order);
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
// Phase 1: independent strips (audio, instrument, MIDI), in parallel except on the audio thread.
let mut work = std::mem::take(&mut self.work);
work.clear();
for &i in &order {
@@ -448,6 +455,7 @@ impl MixEngine {
}
self.ensure_synced(s);
for b in self.busses.values_mut() {
b.age = send_automation::SignalAge::Empty;
for c in b.buf.iter_mut() {
c.iter_mut().take(frames).for_each(|x| *x = 0.0);
}
@@ -502,9 +510,11 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(lmax_t.saturating_sub(st.latency), ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
st.align_pre.set(lmax_t.saturating_sub(st.latency), ch);
st.align_pre.process(&mut st.pre, frames);
st.send_pre_age = st.send_pre_age.delayed(st.align_pre.len);
}
let waits = match &t.mixer.output {
Route::Main => true,
@@ -540,6 +550,7 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
st.out_extra.set(0, ch);
self.route_strip(t, &mut st, pos, frames);
self.strips.insert(t.id, st);
@@ -637,22 +648,41 @@ impl MixEngine {
let law = self.pan_law;
for (i, snd) in t.mixer.sends.iter().enumerate() {
let Some(snd) = snd else { continue };
if snd.mute || strip.muted {
if strip.muted {
continue;
}
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let age = if snd.pre_fader { strip.send_pre_age } else { strip.send_post_age };
let clock = age.clock(pos);
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
let ordinary = !src_fmt.is_ambisonic() && !dst.fmt.is_ambisonic();
let mute = ordinary.then(|| send_automation::Reader::for_send(t, AutoParam::SendMute, i, clock.at(0))).flatten();
if mute.is_none() && snd.mute {
continue;
}
let lvl = send_level(t, i, snd.level_db, pos);
let gain = db_to_gain(lvl);
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
if gain <= 0.0 {
continue;
}
dst.age.include(age);
let pan = (ordinary && src.len() == 1 && dst.fmt == ChannelFormat::Stereo)
.then(|| send_automation::Reader::for_send(t, AutoParam::SendPan, i, clock.at(0)))
.flatten();
if let Some(pan) = pan {
send_automation::apply_mono_stereo(src, frames, &mut dst.buf, gain, law, clock, pan, mute);
continue;
}
// Mono sends use the send's own pan; stereo sends go straight to L/R.
let stereo = if src.len() == 1 { [snd.pan, 0.0] } else { [-1.0, 1.0] };
let surround = snd.surround.as_ref().or(if snd.follow_main_pan { t.mixer.surround.as_ref() } else { None });
let m = build_matrix(src_fmt, src.len(), dst.fmt, dst.buf.len(), &PanSpec { stereo, surround }, law);
apply_matrix(src, frames, &mut dst.buf, &m, gain);
if let Some(mute) = mute {
send_automation::apply_gated(src, frames, &mut dst.buf, &m, gain, clock, mute);
} else {
apply_matrix(src, frames, &mut dst.buf, &m, gain);
}
}
let src: &[Vec<f32>] = match &t.mixer.output {
Route::Main | Route::Bus(_) if strip.out_extra.len > 0 => {
@@ -671,7 +701,10 @@ impl MixEngine {
let (dst, dst_fmt) = match &t.mixer.output {
Route::Main => (&mut self.main, self.main_fmt),
Route::Bus(b) => match self.busses.get_mut(b) {
Some(d) => (&mut d.buf, d.fmt),
Some(d) => {
d.age.include(strip.send_post_age.delayed(strip.out_extra.len));
(&mut d.buf, d.fmt)
}
None => return,
},
_ => return,
@@ -705,3 +738,6 @@ mod click;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod send_age_tests;
+1 -1
View File
@@ -1,7 +1,7 @@
use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains};
/// Per-block routing gains: `m[src][dst]`.
type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
pub(crate) type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
/// How a source is panned: the stereo pan pair (mono uses `[0]`) and the optional surround pan.
pub(crate) struct PanSpec<'a> {
+120
View File
@@ -0,0 +1,120 @@
use std::collections::HashMap;
use std::sync::Arc;
use craft_audio::AudioBuffer;
use soundcraft_dsp::Plugin;
use super::send_automation::SignalAge;
use super::strip::{Block, BusBuf, LiveInput, MAX_LATENCY, PluginSlot, Strip, process_strip};
use super::*;
#[test]
fn known_bus_ages_accumulate_and_mixed_ages_keep_the_legacy_clock() {
let mut bus = SignalAge::Empty;
assert_eq!(bus.input(), SignalAge::Known(0));
bus.include(SignalAge::Known(71));
bus.include(SignalAge::Known(71));
assert_eq!(bus, SignalAge::Known(71));
let aux_pre = bus.delayed(23);
let aux_post = aux_pre.delayed(48);
assert_eq!(aux_pre, SignalAge::Known(94));
assert_eq!(aux_post, SignalAge::Known(142));
assert_eq!(aux_pre.clock(300).at(0), 206);
assert_eq!(aux_post.clock(300).at(0), 158);
let nested = aux_post.delayed(71);
assert_eq!(nested, SignalAge::Known(213));
bus.include(SignalAge::Known(142));
assert_eq!(bus, SignalAge::Mixed);
assert_eq!(bus.delayed(71).clock(300).at(0), 300);
}
#[test]
fn age_overflow_preserves_audio_with_the_legacy_clock_fallback() {
let age = SignalAge::Known(u64::MAX).delayed(1);
assert_eq!(age, SignalAge::Mixed);
assert_eq!(age.clock(-7).at(3), -4);
let mut bus = SignalAge::Known(71);
bus.include(SignalAge::Empty);
assert_eq!(bus, SignalAge::Known(71));
}
#[test]
fn processed_insert_age_is_uncapped_while_pdc_stays_capped_and_overflow_falls_back() {
struct DeclaredDelay {
inner: Box<dyn Plugin>,
latency: usize,
}
impl Plugin for DeclaredDelay {
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
self.inner.info()
}
fn prepare(&mut self, rate: f32, block: usize, channels: usize) {
self.inner.prepare(rate, block, channels);
}
fn reset(&mut self) {
self.inner.reset();
}
fn set_param(&mut self, id: &str, value: f32) -> bool {
self.inner.set_param(id, value)
}
fn param(&self, id: &str) -> Option<f32> {
self.inner.param(id)
}
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
self.inner.process(io, frames);
}
fn latency(&self) -> usize {
self.latency
}
}
fn slot(latency: usize) -> PluginSlot {
let mut inner = soundcraft_dsp::create("gain").unwrap();
inner.prepare(48_000.0, 16, 1);
PluginSlot::test_instance("gain".into(), 1, Box::new(DeclaredDelay { inner, latency }))
}
let mut source = Session::default();
source.edit.delay_compensation = false;
let audio = source.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let source_id = soundcraft_model::SourceId(900);
source.pool.insert(source_id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 16]] })));
let clip = source.new_clip_id();
let track = source.track_mut(audio).unwrap();
track.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared-age reference", source_id, 0, 0, 16));
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
track.mixer.inserts[1] = Some(soundcraft_model::Insert::new("gain"));
let mut pre = soundcraft_model::SendSlot::new(Route::None);
pre.pre_fader = true;
track.mixer.sends[0] = Some(pre);
let mut strip = Strip::new();
strip.buf = vec![vec![0.0; 16]];
strip.scratch = vec![0.0; 16];
strip.plugins = vec![Some(slot(MAX_LATENCY + 5)), Some(slot(MAX_LATENCY + 9))];
let busses = HashMap::new();
let live = LiveInput { input: &[], midi: &[], ports: None, midi_lost: 0, monitor_only: false, recording: false };
let blk = Block { pos: 0, frames: 16, any_solo: false };
process_strip(&source, source.track(audio).unwrap(), &mut strip, &busses, &live, blk);
let declared_sum = 2 * MAX_LATENCY as u64 + 14;
assert_eq!(strip.latency, MAX_LATENCY, "the existing PDC cap remains unchanged");
assert_eq!(strip.send_pre_age, SignalAge::Known(declared_sum));
assert_eq!(strip.send_post_age, SignalAge::Known(declared_sum));
assert_eq!(strip.align.len, 0);
assert_eq!(strip.align_pre.len, 0);
assert_eq!(strip.pre, vec![vec![0.25; 16]]);
assert_eq!(strip.buf, strip.pre, "declared age metadata never changes the processed PCM");
let bus = source.add_bus("Overflowing known input", ChannelFormat::Mono);
let aux = source.add_track(TrackKind::Aux, ChannelFormat::Mono, None);
let track = source.track_mut(aux).unwrap();
track.mixer.input = Route::Bus(bus);
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
let busses = HashMap::from([(bus, BusBuf { fmt: ChannelFormat::Mono, buf: vec![vec![0.25; 16]], age: SignalAge::Known(u64::MAX) })]);
let mut aux_strip = Strip::new();
aux_strip.buf = vec![vec![0.0; 16]];
aux_strip.plugins = vec![Some(slot(1))];
process_strip(&source, source.track(aux).unwrap(), &mut aux_strip, &busses, &live, blk);
assert_eq!(aux_strip.latency, 1);
assert_eq!(aux_strip.send_pre_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age.clock(300).at(0), 300);
assert_eq!(aux_strip.buf, vec![vec![0.25; 16]], "overflow preserves the output instead of silencing it");
}
+267
View File
@@ -0,0 +1,267 @@
//! Local send playback: sample-exact mono-to-stereo pan and stepped ordinary-bus mute.
//! No document mutation, allocation, locks or persistent cursor survive a callback/seek.
use super::MAX_CHANNELS;
use super::pan::Matrix;
use soundcraft_dsp::pan::{PanLaw, gains};
use soundcraft_model::{AutoParam, AutomationPoint, Track};
use soundcraft_time::Samples;
/// Source-sample age metadata only; it never changes routing or audio delay compensation.
/// A mixed-age sum has no single source clock, so new send readers retain their legacy clock.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub(crate) enum SignalAge {
#[default]
Empty,
Known(u64),
Mixed,
}
impl SignalAge {
pub(crate) fn input(self) -> Self {
match self {
Self::Empty => Self::Known(0),
other => other,
}
}
pub(crate) fn delayed(self, frames: usize) -> Self {
match self {
Self::Known(age) => u64::try_from(frames).ok().and_then(|frames| age.checked_add(frames)).map_or(Self::Mixed, Self::Known),
other => other,
}
}
pub(crate) fn include(&mut self, contribution: Self) {
*self = match (*self, contribution) {
(Self::Empty, age) | (age, Self::Empty) => age,
(Self::Known(a), Self::Known(b)) if a == b => Self::Known(a),
_ => Self::Mixed,
};
}
pub(crate) fn clock(self, position: Samples) -> Clock {
let age = match self {
Self::Known(age) => age,
Self::Empty | Self::Mixed => 0,
};
Clock::new(position, age)
}
}
/// A forward cursor rebuilt at each callback's absolute position. Like the existing mixer
/// readers, this deliberately ignores lane.enabled; global suspension/migration is separate.
/// Nonfinite or decreasing-time lanes fall back to the static control for the whole callback.
/// Finite values clamp to the control range; duplicate times deterministically use the last knot.
pub(super) struct Reader<'a> {
points: &'a [AutomationPoint],
next: usize,
mute: bool,
}
impl<'a> Reader<'a> {
pub(super) fn for_send(t: &'a Track, param: fn(u8) -> AutoParam, slot: usize, pos: Samples) -> Option<Self> {
if !t.mixer.automation_mode.reads() {
return None;
}
let param = param(u8::try_from(slot).ok()?);
let lane = t.lane(&param)?;
let points = &lane.points;
if points.is_empty() || points.iter().any(|p| !p.value.is_finite()) || points.windows(2).any(|p| p[0].at > p[1].at) {
return None;
}
Some(Self { points, next: points.partition_point(|p| p.at <= pos), mute: matches!(param, AutoParam::SendMute(_)) })
}
pub(super) fn value(&mut self, pos: Samples) -> f32 {
while self.points.get(self.next).is_some_and(|p| p.at <= pos) {
self.next = self.next.saturating_add(1);
}
let Some(a) = self.points.get(self.next.saturating_sub(1)) else { return 0.0 };
let lo = if self.mute { 0.0 } else { -1.0 };
let av = a.value.clamp(lo, 1.0);
if self.next == 0 || self.mute {
return av;
}
let Some(b) = self.points.get(self.next) else { return av };
// Valid timestamps may span i64::MIN..MAX. Widen before subtraction, and interpolate
// bounded values in f64 so neither timestamp nor value arithmetic can overflow.
let width = i128::from(b.at) - i128::from(a.at);
if width <= 0 {
return av;
}
let fraction = ((i128::from(pos) - i128::from(a.at)) as f64 / width as f64).clamp(0.0, 1.0);
(f64::from(av) + (f64::from(b.value.clamp(lo, 1.0)) - f64::from(av)) * fraction) as f32
}
}
/// Timeline position represented by a delayed source tap. Widen the entire expression before
/// clamping, so advancing a frame near MIN/MAX does not lose an earlier delay subtraction.
#[derive(Clone, Copy)]
pub(super) struct Clock {
position: Samples,
age: u64,
}
impl Clock {
pub(super) fn new(position: Samples, age: u64) -> Self {
Self { position, age }
}
pub(super) fn at(self, frame: usize) -> Samples {
let frame = i128::try_from(frame).unwrap_or(i128::MAX);
let at = i128::from(self.position).saturating_add(frame).saturating_sub(i128::from(self.age));
at.clamp(i128::from(Samples::MIN), i128::from(Samples::MAX)) as Samples
}
}
impl From<Samples> for Clock {
fn from(position: Samples) -> Self {
Self::new(position, 0)
}
}
#[cfg(test)]
fn frame_position(pos: Samples, frame: usize) -> Samples {
Clock::from(pos).at(frame)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn apply_mono_stereo(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
gain: f32,
law: PanLaw,
pos: impl Into<Clock>,
mut pan: Reader<'_>,
mut mute: Option<Reader<'_>>,
) {
let clock = pos.into();
let Some(src) = src.first() else { return };
for (i, sample) in src.iter().enumerate().take(frames) {
let at = clock.at(i);
if mute.as_mut().is_some_and(|m| m.value(at) >= 0.5) {
continue;
}
let (left, right) = gains(pan.value(at), law);
for (channel, factor) in [(0, left), (1, right)] {
if let Some(out) = dst.get_mut(channel).and_then(|c| c.get_mut(i)) {
*out += sample * gain * factor;
}
}
}
}
/// Keep the existing static routing matrix (including mono folds and surround positions),
/// applying only the exact mute gate. Sparse taps are prepared on the stack once per block.
pub(super) fn apply_gated(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
matrix: &Matrix,
gain: f32,
pos: impl Into<Clock>,
mut mute: Reader<'_>,
) {
let clock = pos.into();
let mut taps = [[(0usize, 0.0f32); MAX_CHANNELS]; MAX_CHANNELS];
let mut counts = [0usize; MAX_CHANNELS];
for (d, (taps, count)) in taps.iter_mut().zip(counts.iter_mut()).enumerate().take(dst.len()) {
for (s, row) in matrix.iter().enumerate().take(src.len().min(MAX_CHANNELS)) {
let g = row.get(d).copied().unwrap_or(0.0);
if g != 0.0
&& let Some(tap) = taps.get_mut(*count)
{
*tap = (s, g);
*count += 1;
}
}
}
for i in 0..frames {
if mute.value(clock.at(i)) >= 0.5 {
continue;
}
for (d, channel) in dst.iter_mut().enumerate().take(MAX_CHANNELS) {
let Some(out) = channel.get_mut(i) else { continue };
let mut acc = 0.0;
for &(s, g) in taps.get(d).and_then(|t| counts.get(d).and_then(|n| t.get(..*n))).unwrap_or(&[]) {
acc += src.get(s).and_then(|c| c.get(i)).copied().unwrap_or(0.0) * gain * g;
}
*out += acc;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use soundcraft_model::{AutomationLane, ChannelFormat, Session, TrackKind};
fn track(points: &[(i64, f32)], mute: bool) -> Track {
let mut s = Session::default();
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let t = s.track_mut(id).unwrap();
let mut lane = AutomationLane::new(if mute { AutoParam::SendMute(0) } else { AutoParam::SendPan(0) });
lane.points = points.iter().map(|&(at, value)| AutomationPoint { at, value }).collect();
t.automation.push(lane);
t.clone()
}
#[test]
fn wide_interpolation_does_not_overflow() {
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MIN).unwrap();
assert_eq!(r.value(i64::MIN), -1.0);
assert!(r.value(0).abs() < 1e-7);
assert_eq!(r.value(i64::MAX), 1.0);
assert_eq!(frame_position(i64::MAX - 1, 3), i64::MAX);
}
#[test]
fn endpoints_duplicates_and_finite_extremes_are_deterministic() {
let t = track(&[(3, -f32::MAX), (3, 0.25), (7, f32::MAX)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, 0).unwrap();
assert_eq!(r.value(0), -1.0);
assert_eq!(r.value(3), 0.25);
assert_eq!(r.value(5), 0.625);
assert_eq!(r.value(9), 1.0);
let t = track(&[(i64::MIN, -f32::MAX), (i64::MAX, f32::MAX)], true);
let mut r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MIN).unwrap();
assert_eq!(r.value(0), 0.0);
assert_eq!(r.value(i64::MAX), 1.0);
}
#[test]
fn short_buffers_and_saturating_positions_do_not_panic() {
let t = track(&[(i64::MIN, 0.0), (i64::MAX, 1.0)], true);
let r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MAX - 1).unwrap();
let mut dst = vec![vec![0.0; 1]];
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
apply_gated(&[vec![0.25; 2]], 4, &mut dst, &matrix, 1.0, i64::MAX - 1, r);
assert_eq!(dst, vec![vec![0.25]]);
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MAX - 1).unwrap();
apply_mono_stereo(&[vec![0.25; 2]], 4, &mut [], 1.0, PanLaw::Minus3, i64::MAX - 1, r, None);
}
#[test]
fn source_clock_clamps_after_the_composite_delay_expression() {
assert_eq!(Clock::new(i64::MIN + 5, 10).at(8), i64::MIN + 3);
assert_eq!(Clock::new(i64::MAX, 10).at(3), i64::MAX - 7);
assert_eq!(Clock::new(i64::MAX, 10).at(20), i64::MAX);
assert_eq!(Clock::new(-5, 10).at(3), -12);
assert_eq!(Clock::new(i64::MAX, u64::MAX).at(0), i64::MIN);
assert_eq!(Clock::new(i64::MIN, u64::MAX).at(0), i64::MIN);
}
#[test]
fn delayed_reader_seed_and_gate_advancement_use_the_same_clock() {
let t = track(&[(0, 0.0), (30, 1.0), (40, 0.0)], true);
let clock = Clock::new(45, 25);
let reader = Reader::for_send(&t, AutoParam::SendMute, 0, clock.at(0)).unwrap();
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
let mut destination = vec![vec![0.0; 25]];
apply_gated(&[vec![0.25; 25]], 25, &mut destination, &matrix, 1.0, clock, reader);
assert_eq!(destination[0], (0..25).map(|frame| if (10..20).contains(&frame) { 0.0 } else { 0.25 }).collect::<Vec<_>>());
}
}
+42 -9
View File
@@ -5,6 +5,7 @@ use super::live_midi::{LiveMidi, LiveNotes, MidiPorts, midi_thru};
use super::midi::{chase_controllers, schedule_notes};
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
use super::routing::solo_muted;
use super::send_automation::SignalAge;
use super::{
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
db_to_gain,
@@ -16,6 +17,8 @@ use std::sync::Arc;
pub(crate) struct BusBuf {
pub(crate) fmt: ChannelFormat,
pub(crate) buf: Vec<Vec<f32>>,
/// Age shared by the routed contributions in this block, or Mixed when they differ.
pub(crate) age: SignalAge,
}
pub(crate) struct PluginSlot {
@@ -29,6 +32,17 @@ pub(crate) struct PluginSlot {
/// so the audio thread reuses its allocation.
lanes: Vec<usize>,
pub(crate) failed: bool,
/// A failed plugin is retried once on the next reset; a second failure keeps it out for the
/// rest of the session, so a plugin that always fails stops oscillating the track's latency
/// (and the compensation reallocations that go with it) on every stop or seek (#919).
pub(crate) retried: bool,
}
#[cfg(test)]
impl PluginSlot {
pub(crate) fn test_instance(id: String, ch: usize, plugin: Box<dyn Plugin>) -> Self {
Self { id, ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }
}
}
pub(crate) struct Strip {
@@ -55,6 +69,9 @@ pub(crate) struct Strip {
clipbuf: Vec<Vec<f32>>,
/// Total latency of the active inserts (samples).
pub(crate) latency: usize,
/// Sample ages of the selected send taps after their actual applied alignment.
pub(crate) send_pre_age: SignalAge,
pub(crate) send_post_age: SignalAge,
/// Delay compensation: align this strip with the slowest one (post- and pre-fader paths),
/// plus extra delay for direct-to-main outputs so they line up with aux returns.
pub(crate) align: DelayLine,
@@ -153,6 +170,8 @@ impl Strip {
clip_fx: HashMap::new(),
clipbuf: Vec::new(),
latency: 0,
send_pre_age: SignalAge::Known(0),
send_post_age: SignalAge::Known(0),
align: DelayLine::default(),
align_pre: DelayLine::default(),
out_extra: DelayLine::default(),
@@ -203,7 +222,7 @@ impl SlotCtx<'_> {
let state = if third { ins.state_bytes() } else { None };
create_instance_for(&ins.plugin, state.as_deref(), self.sr, self.mb, ch, self.offline).map(|n| n.plugin)
}?;
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false })
Some(PluginSlot { id: ins.plugin.clone(), ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false })
}
}
@@ -234,9 +253,11 @@ fn zero_buf(buf: &mut [Vec<f32>], frames: usize) {
}
}
/// Input monitoring: the track hears its hardware input instead of its clips.
/// Input monitoring: the track hears its hardware input instead of its clips. With no input
/// (`Route::None`) it hears nothing.
fn monitor_input(t: &Track, strip: &mut Strip, live: &LiveInput<'_>, frames: usize) {
let first = match &t.mixer.input {
Route::None => return,
Route::Hardware(h) => {
h.trim_start_matches("In ").split(['-', ' ']).next().and_then(|n| n.parse::<usize>().ok()).map_or(0, |n| n.saturating_sub(1))
}
@@ -283,10 +304,11 @@ fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) {
}
/// An aux or folder reads the bus its input is routed from.
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) {
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) -> SignalAge {
if let Route::Bus(b) = &t.mixer.input
&& let Some(src) = busses.get(b)
{
let input_age = src.age.input();
let (ns, nd) = (src.buf.len(), strip.buf.len());
let dst_fmt = strip_format(t, nd);
let m = if src.fmt == dst_fmt && ns == nd {
@@ -302,7 +324,9 @@ fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, f
build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3)
};
apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0);
return input_age;
}
SignalAge::Known(0)
}
/// Render the track's instrument into the strip.
@@ -387,10 +411,12 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
}
/// Run the active inserts in order; records their latency and the first gain reduction.
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) {
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport, input_age: SignalAge) {
let Block { pos, frames, .. } = blk;
let mut gr = 0.0f32;
let mut latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
let inst_latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
let mut latency = inst_latency;
let mut send_age = input_age.delayed(inst_latency);
for (i, ins) in t.mixer.inserts.iter().enumerate() {
let (Some(ins), Some(Some(slot))) = (ins, strip.plugins.get_mut(i)) else { continue };
if !ins.active || ins.bypass || slot.failed {
@@ -403,13 +429,17 @@ fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport)
strip.failures.record(i);
continue;
}
latency = latency.saturating_add(slot.plugin.latency());
let declared_latency = slot.plugin.latency();
latency = latency.saturating_add(declared_latency);
send_age = send_age.delayed(declared_latency);
if gr == 0.0 {
gr = slot.plugin.gain_reduction_db();
}
}
strip.gr = gr;
strip.latency = latency.min(MAX_LATENCY);
strip.send_pre_age = send_age;
strip.send_post_age = send_age;
}
/// Fader gain (volume, trim and VCA automation), read at every sample of the block.
@@ -460,6 +490,7 @@ fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) {
pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, live: &LiveInput<'_>, blk: Block) {
let Block { pos, frames, any_solo } = blk;
zero_buf(&mut strip.buf, frames);
let mut input_age = SignalAge::Known(0);
let transport = transport_at(s, pos, !live.monitor_only, live.recording);
match t.kind {
TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => {
@@ -470,7 +501,9 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
// doing so, to release its notes).
TrackKind::Instrument | TrackKind::Midi if live.monitor_only && !midi_thru(t) && !strip.live.touched() => {}
TrackKind::Audio => render_audio_clips(s, t, strip, blk),
TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames),
TrackKind::Aux | TrackKind::Folder => {
input_age = read_aux_bus(t, strip, busses, frames);
}
TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, live, blk, &transport),
_ => {}
}
@@ -480,7 +513,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
c.iter_mut().take(frames).for_each(|x| *x *= trim);
}
}
run_inserts(t, strip, blk, &transport);
run_inserts(t, strip, blk, &transport, input_age);
let soloed_out = solo_muted(s, t, any_solo);
strip.muted = t.mixer.mute || soloed_out;
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
@@ -624,7 +657,7 @@ mod apply_params_tests {
fn recorder() -> (PluginSlot, Arc<Mutex<Vec<(String, f32)>>>) {
let sets = Arc::new(Mutex::new(Vec::new()));
let plugin = Box::new(Recorder { inner: soundcraft_dsp::create("gain").unwrap(), sets: Arc::clone(&sets) });
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false }, sets)
(PluginSlot { id: "gain".into(), ch: 2, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }, sets)
}
fn lane(slot: u8, param: &str, point: Option<f32>) -> AutomationLane {
+43
View File
@@ -698,6 +698,31 @@ fn an_insert_that_puts_out_nan_is_taken_out_until_the_next_reset() {
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
}
/// A plugin that fails again after its one reset retry stays failed for the session, instead of
/// oscillating the track's latency (and its delay-line reallocations) on every stop/seek (#919).
#[test]
fn a_repeatedly_failing_insert_gets_only_one_reset_retry() {
let (mut s, a) = session_with_dc(0.5, 48_000);
let _b = add_dc_track(&mut s, 0.5, 48_000);
s.track_mut(a).unwrap().mixer.inserts[2] = Some(Insert::new("clap:test.nan"));
let mut eng = MixEngine::new(48_000.0, 512);
eng.set_external_instances(true);
let both = render_block(&mut eng, &s, 0);
eng.adopt(nan(a, 2, 1));
let only_b = render_block(&mut eng, &s, 512);
assert!((only_b - both / 2.0).abs() < 1e-6, "{only_b} vs {both}");
// While failed it passes the track's audio through, dry.
assert_eq!(render_block(&mut eng, &s, 1024), both);
// The first reset grants the single retry; it fails again.
eng.reset();
assert_eq!(render_block(&mut eng, &s, 1536), only_b);
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
// A later reset does not retry it again: the block stays dry and the count does not move.
eng.reset();
assert_eq!(render_block(&mut eng, &s, 2048), both);
assert_eq!(eng.meters[&a].plugin_failures.count, 2);
}
#[test]
fn nan_from_an_instrument_or_a_master_insert_is_contained() {
let mut s = synth_session(-6.0);
@@ -1118,6 +1143,7 @@ fn a_hosted_instruments_latency_is_compensated() {
#[test]
fn input_monitoring_replaces_clips() {
let (mut s, t) = session_with_dc(0.5, 4800);
s.track_mut(t).unwrap().mixer.input = Route::Hardware("In 1".into());
let mut eng = MixEngine::new(48_000.0, 512);
eng.input = vec![vec![0.25; 512]];
let mut out = vec![vec![0.0; 512]; 2];
@@ -1136,6 +1162,23 @@ fn input_monitoring_replaces_clips() {
assert!(out[0][100].abs() < 1e-6, "stopped, unmonitored: silence");
}
/// A track whose input is "no input" (`Route::None`) hears nothing, not hardware input 1.
#[test]
fn a_track_with_no_input_monitors_nothing() {
let (mut s, t) = session_with_dc(0.0, 4800);
let mut eng = MixEngine::new(48_000.0, 512);
eng.input = vec![vec![0.25; 512], vec![0.5; 512]];
eng.monitor_only = true;
let mut out = vec![vec![0.0; 512]; 2];
s.track_mut(t).unwrap().mixer.input_monitor = true;
s.track_mut(t).unwrap().mixer.input = Route::None;
eng.render(&s, 0, 512, &mut out);
assert!(out.iter().all(|c| c.iter().all(|x| *x == 0.0)), "no input: silence, not In 1");
s.track_mut(t).unwrap().mixer.input = Route::Hardware("In 2".into());
eng.render(&s, 512, 512, &mut out);
assert!((out[0][100] - 0.5 * std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3, "In 2 is heard: {}", out[0][100]);
}
#[test]
fn empty_session_is_silent() {
let s = Session::default();
+8 -5
View File
@@ -1,16 +1,15 @@
use super::AUDIO_THREAD;
/// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks
/// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads
/// count as the audio thread while they render for it. Code that might run there asks
/// do, every call: one thread-local store). [`MixEngine::render`] renders every strip on that
/// thread itself instead of handing strips to worker threads. Code that might run there asks
/// [`on_audio_thread`] before doing anything that blocks; the desktop app's logger does, so a
/// `log::` record from the audio thread never takes a lock or touches a file.
pub fn mark_audio_thread() {
AUDIO_THREAD.set(true);
}
/// True on the thread [`mark_audio_thread`] marked, and on a worker while it renders strips for
/// it. Lock-free and allocation-free.
/// True on the thread [`mark_audio_thread`] marked. Lock-free and allocation-free.
pub fn on_audio_thread() -> bool {
AUDIO_THREAD.get()
}
@@ -29,7 +28,11 @@ fn as_audio_thread(audio: bool, f: impl FnOnce()) {
f();
}
/// Process strips, in parallel on native targets when there are enough of them.
/// Process strips: in parallel on native targets when there are enough of them, except on the
/// realtime audio thread. There they render one after the other on the thread itself: the pool's
/// workers run at normal priority, so under load the callback would wait for starved workers
/// (priority inversion) and miss its deadline, and waiting on them blocks, which the callback
/// never may. Offline renders (bounces) keep the parallelism.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn run_strips<T: Send>(work: &mut [T], f: impl Fn(&mut T) + Sync + Send) {
use rayon::prelude::*;
+435
View File
@@ -0,0 +1,435 @@
//! Independent PCM references for the bounded send consumers, with no hosted plugins/devices.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus, render_range};
use soundcraft_model::{
AutoParam, AutomationLane, AutomationMode, AutomationPoint, BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId,
TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
const LEN: usize = 640;
const PAN: [(i64, f32); 3] = [(37, -1.0), (173, 0.75), (401, 1.0)];
const MUTE: [(i64, f32); 5] = [(37, 0.0), (97, 1.0), (173, 0.0), (257, 1.0), (349, 0.0)];
fn fixture(format: ChannelFormat) -> (Session, TrackId, BusId) {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, format, None);
let src = SourceId(900);
let channels = (0..format.channels()).map(|ch| (0..LEN).map(|n| signal(ch, n)).collect()).collect();
s.pool.insert(src, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels })));
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original synthetic", src, 0, 0, LEN as i64));
let bus = s.add_bus("Send", ChannelFormat::Stereo);
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
let tr = s.track_mut(t).unwrap();
tr.mixer.output = Route::None;
let mut send = SendSlot::new(Route::Bus(bus));
send.level_db = 0.0;
tr.mixer.sends[0] = Some(send);
(s, t, bus)
}
fn signal(ch: usize, n: usize) -> f32 {
if n % 17 < 9 { 0.25 + ch as f32 / 100.0 } else { -0.125 - ch as f32 / 200.0 }
}
fn lane(s: &mut Session, t: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
s.track_mut(t).unwrap().automation.push(lane);
}
fn automated() -> (Session, TrackId, BusId) {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
(s, t, bus)
}
// The expectation never calls AutomationLane::value_at, pan::gains or any mixer helper.
fn expected_pan(at: i64) -> f64 {
if at <= PAN[0].0 {
return f64::from(PAN[0].1);
}
for pair in PAN.windows(2) {
if at < pair[1].0 {
let f = (at - pair[0].0) as f64 / (pair[1].0 - pair[0].0) as f64;
return f64::from(pair[0].1) + f64::from(pair[1].1 - pair[0].1) * f;
}
}
f64::from(PAN[2].1)
}
fn muted(at: i64) -> bool {
MUTE.iter().rev().find(|p| p.0 <= at).unwrap_or(&MUTE[0]).1 >= 0.5
}
fn pan_factors(p: f64, law: PanLaw) -> [f64; 2] {
if law == PanLaw::Zero {
return [(1.0 - p).min(1.0), (1.0 + p).min(1.0)];
}
let depth = match law {
PanLaw::Minus3 => -3.0,
PanLaw::Minus4_5 => -4.5,
PanLaw::Minus6 => -6.0,
PanLaw::Zero => 0.0,
};
let angle = (p + 1.0) * std::f64::consts::PI / 4.0;
[angle.cos().max(0.0).powf(depth / -3.0103), angle.sin().max(0.0).powf(depth / -3.0103)]
}
fn assert_shape(out: &[Vec<f32>], channels: usize, frames: usize) {
assert_eq!(out.len(), channels);
for channel in out {
assert_eq!(channel.len(), frames);
}
}
fn check(out: &[Vec<f32>], start: i64, frames: usize, law: PanLaw, scale: f64) {
assert_shape(out, 2, frames);
for (ch, values) in out.iter().enumerate() {
for (n, &actual) in values.iter().enumerate() {
let at = start + n as i64;
let reference = if muted(at) { 0.0 } else { f64::from(signal(0, at as usize)) * scale * pan_factors(expected_pan(at), law)[ch] };
assert!((f64::from(actual) - reference).abs() < 2e-7, "channel {ch}, at {at}: {actual} vs {reference}");
}
}
}
fn chunks(eng: &mut MixEngine, s: &Session, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut out = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut k = 0;
while offset < length {
let n = sizes[k % sizes.len()].min(length - offset);
let mut block = vec![vec![0.0; n]; 2];
eng.render(s, start + offset as i64, n, &mut block);
for (out, block) in out.iter_mut().zip(block) {
out.extend(block);
}
offset += n;
k += 1;
}
out
}
#[test]
fn pan_and_mute_match_independent_pcm_across_chunks() {
let (s, _, bus) = automated();
for block in [1, 37, 64, 100, 512, 1024] {
let mut e = MixEngine::new(48_000.0, block.max(16));
let out = chunks(&mut e, &s, 0, LEN, &[block]);
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
let mut e = MixEngine::new(48_000.0, 1024);
check(&chunks(&mut e, &s, 0, LEN, &[1, 37, 64, 3, 100, 19]), 0, LEN, PanLaw::Minus3, 1.0);
check(&render_bus(&s, bus, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn all_pan_laws_match_numeric_reference_and_static_calibration() {
let (s, _, _) = automated();
for law in [PanLaw::Minus3, PanLaw::Minus4_5, PanLaw::Minus6, PanLaw::Zero] {
let mut e = MixEngine::new(48_000.0, 1024);
e.pan_law = law;
check(&chunks(&mut e, &s, 0, LEN, &[100]), 0, LEN, law, 1.0);
for at in [0, 77, 173, 349, 401] {
let (mut reference, t, _) = fixture(ChannelFormat::Mono);
reference.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pan = expected_pan(at) as f32;
let mut static_engine = MixEngine::new(48_000.0, 16);
static_engine.pan_law = law;
let static_pcm = chunks(&mut static_engine, &reference, at, 1, &[1]);
let automated_pcm = chunks(&mut e, &s, at, 1, &[1]);
assert_shape(&automated_pcm, 2, 1);
assert_shape(&static_pcm, 2, 1);
assert_eq!(automated_pcm, static_pcm);
}
}
}
#[test]
fn seeking_used_engine_has_no_cursor_history() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
let _ = chunks(&mut e, &s, 0, 520, &[100]);
for at in [31, 77, 97, 98, 173, 256, 257, 301] {
let out = chunks(&mut e, &s, at, 31, &[17, 1, 13]);
check(&out, at, 31, PanLaw::Minus3, 1.0);
let mut fresh = MixEngine::new(48_000.0, 1024);
assert_eq!(out, chunks(&mut fresh, &s, at, 31, &[17, 1, 13]));
}
}
#[test]
fn loop_wrap_and_tiny_final_chunks_use_absolute_knots() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
// Same loop splitting as playback: do not render past the loop end before wrapping.
for _ in 0..3 {
check(&chunks(&mut e, &s, 37, 264, &[100, 63]), 37, 264, PanLaw::Minus3, 1.0);
}
for _ in 0..2 {
check(&chunks(&mut e, &s, 97, 76, &[37]), 97, 76, PanLaw::Minus3, 1.0);
}
}
#[test]
fn modes_and_lane_enabled_preserve_existing_reader_policy() {
for mode in AutomationMode::ALL {
let (mut s, t, _) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.automation_mode = mode;
tr.mixer.sends[0].as_mut().unwrap().mute = true;
for lane in &mut tr.automation {
lane.enabled = false;
}
let out = render_range(&s, Range::new(0, LEN as i64), 37);
assert_shape(&out, 2, LEN);
if mode == AutomationMode::Off {
assert!(out.iter().flatten().all(|v| *v == 0.0));
} else {
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
}
}
#[test]
fn missing_and_empty_lanes_keep_static_pan_and_mute() {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendPan(0), &[]);
lane(&mut s, t, AutoParam::SendMute(0), &[]);
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().mute = true;
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
#[test]
fn static_matrix_mute_steps_and_threshold_match_reference() {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendMute(0), &[(0, 0.49), (97, 0.5), (173, 0.0)]);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, 2, LEN);
assert_shape(&reference, 2, LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if (97..173).contains(&i) { 0.0 } else { r });
}
}
}
#[test]
fn mute_preserves_routing_for_mono_surround_and_sixteen_channels() {
for fmt in [ChannelFormat::Mono, ChannelFormat::Stereo, ChannelFormat::Surround51, ChannelFormat::Atmos714, ChannelFormat::Atmos916] {
let (mut s, t, bus) = fixture(fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, fmt.channels(), LEN);
assert_shape(&reference, fmt.channels(), LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if muted(i as i64) { 0.0 } else { r });
}
}
}
}
#[test]
fn wider_source_and_destination_send_pan_keep_static_routing() {
for (src_fmt, dst_fmt) in [
(ChannelFormat::Stereo, ChannelFormat::Stereo),
(ChannelFormat::Mono, ChannelFormat::Surround51),
(ChannelFormat::Surround51, ChannelFormat::Stereo),
] {
let (mut s, t, bus) = fixture(src_fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = dst_fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
assert_shape(&reference, dst_fmt.channels(), LEN);
let actual = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert_shape(&actual, dst_fmt.channels(), LEN);
assert_eq!(actual, reference);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
}
}
#[test]
fn pre_post_fader_send_level_and_direct_output_are_preserved() {
for pre in [false, true] {
let (mut s, t, bus) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let snd = tr.mixer.sends[0].as_mut().unwrap();
snd.pre_fader = pre;
snd.level_db = -3.0;
let factor = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
check(&render_range(&s, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, factor);
// Keep the direct path isolated from the Aux while comparing source-main PCM.
let aux = s.tracks.iter().find(|tr| tr.kind == TrackKind::Aux).unwrap().id;
s.track_mut(aux).unwrap().inactive = true;
s.track_mut(t).unwrap().mixer.output = Route::Main;
let direct = render_range(&s, Range::new(0, LEN as i64), 37);
s.track_mut(t).unwrap().automation.clear();
s.track_mut(t).unwrap().mixer.sends[0] = None;
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 37), direct);
assert_eq!(s.bus(bus).unwrap().format, ChannelFormat::Stereo);
}
}
#[test]
fn track_solo_and_vca_suppression_cannot_be_unmuted_by_send_lane() {
for suppression in [0, 1, 2] {
let (mut s, t, _) = automated();
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pre_fader = true;
match suppression {
0 => s.track_mut(t).unwrap().mixer.mute = true,
1 => {
let other = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
s.track_mut(other).unwrap().mixer.solo = true;
}
_ => {
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, None);
s.track_mut(vca).unwrap().mixer.mute = true;
s.track_mut(t).unwrap().mixer.vca = Some(vca.0);
}
}
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
}
#[test]
fn slots_a_and_j_and_absent_slots_do_not_drive_each_other() {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let other = s.add_bus("J", ChannelFormat::Stereo);
let mut send = SendSlot::new(Route::Bus(other));
send.level_db = 0.0;
s.track_mut(t).unwrap().mixer.sends[9] = Some(send);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(9), &PAN);
lane(&mut s, t, AutoParam::SendMute(9), &MUTE);
lane(&mut s, t, AutoParam::SendMute(8), &[(0, 1.0)]);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
check(&render_bus(&s, other, Range::new(0, LEN as i64), 100), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn malformed_lanes_fall_back_without_changing_document() {
for points in [
vec![AutomationPoint { at: 3, value: -1.0 }, AutomationPoint { at: 1, value: 1.0 }],
vec![AutomationPoint { at: 0, value: f32::NAN }],
vec![AutomationPoint { at: 0, value: f32::INFINITY }],
] {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut lane = AutomationLane::new(param);
lane.points = points.clone();
s.track_mut(t).unwrap().automation.push(lane);
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
#[test]
fn stereo_sends_keep_legacy_left_right_routing_for_every_static_pan() {
for static_pan in [-1.0, -0.75, 0.0, 0.75, 1.0, f32::NAN, f32::INFINITY] {
for state in ["absent", "empty", "off", "malformed", "active"] {
for pre in [false, true] {
for gated in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = static_pan;
send.pre_fader = pre;
send.level_db = -3.0;
match state {
"absent" => {}
"empty" => lane(&mut s, t, AutoParam::SendPan(0), &[]),
"off" => {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
}
"malformed" => {
let mut pan = AutomationLane::new(AutoParam::SendPan(0));
pan.points = vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: -1.0 }];
s.track_mut(t).unwrap().automation.push(pan);
}
"active" => lane(&mut s, t, AutoParam::SendPan(0), &PAN),
_ => unreachable!(),
}
if gated {
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
}
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
// Existing stereo sends route channels directly to L/R. This reference
// does not call either routing matrices or a pan helper.
let expected = if gated && state != "off" && muted(n as i64) { 0.0 } else { f64::from(signal(ch, n)) * scale };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} gated={gated} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
assert_eq!(s.track(t).unwrap().mixer.sends[0].as_ref().unwrap().pan.to_bits(), static_pan.to_bits());
}
}
}
}
}
#[test]
fn inactive_mono_send_lanes_match_independent_static_controls() {
for state in ["absent", "empty", "off", "unordered", "nan", "infinite"] {
for pre in [false, true] {
for static_mute in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = -0.625;
send.mute = static_mute;
send.pre_fader = pre;
send.level_db = -3.0;
if state == "off" {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
} else if state != "absent" {
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut control = AutomationLane::new(param);
control.points = match state {
"empty" => vec![],
"unordered" => vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: 0.0 }],
"nan" => vec![AutomationPoint { at: 0, value: f32::NAN }],
"infinite" => vec![AutomationPoint { at: 0, value: f32::INFINITY }],
_ => unreachable!(),
};
s.track_mut(t).unwrap().automation.push(control);
}
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
let factors = pan_factors(-0.625, PanLaw::Minus3);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
let expected = if static_mute { 0.0 } else { f64::from(signal(0, n)) * scale * factors[ch] };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} muted={static_mute} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
}
}
+322
View File
@@ -0,0 +1,322 @@
//! Send automation follows the delayed audio at its tap, without changing existing PDC routing.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus};
use soundcraft_model::{
AutoParam, AutomationLane, BusId, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
// The built-in Maximizer uses 1.5 ms of lookahead: 72 samples at 48 kHz, with a declared
// and physical delay of 72 - 1 = 71. Its untouched threshold 0 dB gives unity drive;
// every synthetic level stays below the default -0.3 dB ceiling, so there is no limiting.
// Expected timelines use these declared values, not mixer latency fields or the clock helper.
const LOOKAHEAD: usize = 71;
const SOURCE_FRAMES: usize = 2048;
const MUTE_AT: i64 = 300;
const AMPLITUDE: f32 = 0.25;
struct Graph {
session: Session,
capture: BusId,
receiver: TrackId,
clip_start: i64,
pan_start: i64,
pan_end: i64,
}
fn maximizers(session: &mut Session, track: TrackId, count: usize) {
for slot in session.track_mut(track).unwrap().mixer.inserts.iter_mut().take(count) {
*slot = Some(Insert::new("maximizer"));
}
}
fn source(session: &mut Session, insert_count: usize, clip_start: i64) -> TrackId {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Declared DC"));
let id = SourceId(901);
session.pool.insert(id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![AMPLITUDE; SOURCE_FRAMES]] })));
let clip = session.new_clip_id();
let t = session.track_mut(track).unwrap();
t.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared DC", id, 0, clip_start, SOURCE_FRAMES as i64));
t.mixer.pan = vec![0.0];
t.mixer.output = Route::None;
maximizers(session, track, insert_count);
track
}
fn silent_audio(session: &mut Session, insert_count: usize) {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Unrelated silent lookahead"));
session.track_mut(track).unwrap().mixer.output = Route::None;
maximizers(session, track, insert_count);
}
fn aux(session: &mut Session, input: BusId, format: ChannelFormat, insert_count: usize) -> TrackId {
let track = session.add_track(TrackKind::Aux, format, None);
let t = session.track_mut(track).unwrap();
t.mixer.input = Route::Bus(input);
t.mixer.output = Route::None;
t.mixer.pan = if format == ChannelFormat::Mono { vec![0.0] } else { vec![-1.0, 1.0] };
maximizers(session, track, insert_count);
track
}
fn silent_aux(session: &mut Session, insert_count: usize) {
let input = session.add_bus("Unrelated empty input", ChannelFormat::Mono);
aux(session, input, ChannelFormat::Mono, insert_count);
}
fn return_to_main(session: &mut Session, input: BusId) -> TrackId {
let track = aux(session, input, ChannelFormat::Stereo, 0);
session.track_mut(track).unwrap().mixer.output = Route::Main;
track
}
fn automation(session: &mut Session, track: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
session.track_mut(track).unwrap().automation.push(lane);
}
fn send(session: &mut Session, sender: TrackId, capture: BusId, pre: bool, pan_start: i64, pan_end: i64, automated_pan: bool) {
let mut send = SendSlot::new(Route::Bus(capture));
send.level_db = 0.0;
send.pre_fader = pre;
send.pan = -1.0;
session.track_mut(sender).unwrap().mixer.sends[0] = Some(send);
automation(session, sender, AutoParam::SendMute(0), &[(-512, 0.0), (MUTE_AT, 1.0)]);
if automated_pan {
automation(session, sender, AutoParam::SendPan(0), &[(pan_start, -1.0), (pan_end, 1.0)]);
}
}
fn ordinary(pre: bool, own_inserts: usize, silent_inserts: usize, pdc: bool, clip_start: i64, pan_start: i64, pan_end: i64) -> Graph {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let sender = source(&mut session, own_inserts, clip_start);
if silent_inserts > 0 {
silent_audio(&mut session, silent_inserts);
}
let capture = session.add_bus("Automation capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, pan_start, pan_end, true);
let receiver = return_to_main(&mut session, capture);
Graph { session, capture, receiver, clip_start, pan_start, pan_end }
}
fn make_mix() -> MixEngine {
let mut mix = MixEngine::new(48_000.0, 1024);
mix.pan_law = PanLaw::Zero;
mix
}
fn capture_pcm(mix: &mut MixEngine, graph: &Graph, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut main = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut block = 0;
while offset < length {
let n = sizes[block % sizes.len()].min(length - offset);
let mut main_block = vec![vec![0.0; n]; 2];
mix.render(&graph.session, start + offset as i64, n, &mut main_block);
for (output, samples) in main.iter_mut().zip(main_block) {
assert_eq!(samples.len(), n);
output.extend(samples);
}
offset += n;
block += 1;
}
main
}
fn numeric_pan(at: i64, first: i64, last: i64) -> [f32; 2] {
let pan = if at <= first {
-1.0
} else if at >= last {
1.0
} else {
(-1.0 + 2.0 * (at - first) as f64 / (last - first) as f64) as f32
};
// Independent declared zero-depth pan law; no routing or automation helper is called.
[(1.0 - pan).min(1.0), (1.0 + pan).min(1.0)]
}
fn check_known(output: &[Vec<f32>], graph: &Graph, start: i64, delay: usize, length: usize) {
assert_eq!(output.len(), 2);
for (channel, samples) in output.iter().enumerate() {
assert_eq!(samples.len(), length);
for (offset, &sample) in samples.iter().enumerate() {
let source_time = start + offset as i64 - delay as i64;
let audible =
offset >= delay && source_time >= graph.clip_start && source_time < graph.clip_start + SOURCE_FRAMES as i64 && source_time < MUTE_AT;
let expected = if audible { AMPLITUDE * numeric_pan(source_time, graph.pan_start, graph.pan_end)[channel] } else { 0.0 };
assert!(sample.is_finite());
assert!(
(sample - expected).abs() < 2e-7,
"channel {channel}, emit {}, source {source_time}, delay {delay}: {sample} != {expected}",
start + offset as i64
);
}
}
assert!(output.iter().flatten().any(|sample| sample.abs() > 0.02), "declared capture must be audible");
}
#[test]
fn unrelated_silent_lookahead_keeps_audio_pre_post_pan_and_last_source_sample_299() {
for pre in [false, true] {
let graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 800, &[1, 7, 37, 100, 3, 64]);
assert_eq!(mix.latency, LOOKAHEAD, "the unrelated real Maximizer actually contributes latency");
check_known(&output, &graph, 0, LOOKAHEAD, 800);
let last = output[0].iter().rposition(|sample| sample.abs() > 1e-6).unwrap();
assert_eq!(last, MUTE_AT as usize - 1 + LOOKAHEAD);
// Public render_bus uses its default -3 dB law. This separate mute-only fixture
// holds the static send at its left endpoint, whose factors are exactly1/0.
let mut offline_session = graph.session.clone();
offline_session.tracks[0].automation.retain(|lane| lane.param != AutoParam::SendPan(0));
let offline = render_bus(&offline_session, graph.capture, Range::new(0, 640), 37);
assert_eq!(offline[0].len(), 640);
assert_eq!(offline[0].iter().rposition(|sample| sample.abs() > 1e-6), Some(299));
for (channel, samples) in offline.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let expected = if at < MUTE_AT as usize && channel == 0 { AMPLITUDE } else { 0.0 };
assert!((sample - expected).abs() < 2e-7);
}
}
}
}
#[test]
fn aux_pre_tap_omits_post_alignment_while_both_taps_include_upstream_and_own_delay() {
for pdc in [false, true] {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Own upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let sender = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Aux capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let tap_delay = if pdc && !pre { 3 * LOOKAHEAD } else { 2 * LOOKAHEAD };
let observation_delay = if pdc { 2 * LOOKAHEAD } else { 0 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[100, 17, 1, 37, 64]);
assert_eq!(mix.latency, if pdc { 3 * LOOKAHEAD } else { 0 });
check_known(&output, &graph, 0, tap_delay + observation_delay, 900);
}
}
}
#[test]
fn nested_aux_taps_accumulate_the_actual_upstream_path_instead_of_global_latency() {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
silent_audio(&mut session, 2);
let first_bus = session.add_bus("Nested first", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(first_bus);
let first_aux = aux(&mut session, first_bus, ChannelFormat::Mono, 1);
let second_bus = session.add_bus("Nested second", ChannelFormat::Mono);
session.track_mut(first_aux).unwrap().mixer.output = Route::Bus(second_bus);
let sender = aux(&mut session, second_bus, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Nested capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
// Upstream audio2*71; first Aux own+alignment2*71; target pre adds1*71,
// target post adds2*71. The scalar global mix delay is only4*71.
let tap_delay = if pre { 5 * LOOKAHEAD } else { 6 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 1100, &[37, 3, 100, 64, 1]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
check_known(&output, &graph, 0, tap_delay + observation_delay, 1100);
}
}
#[test]
fn output_extra_downstream_aux_and_master_delay_do_not_shift_the_send_clock() {
for pre in [false, true] {
let mut graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let source = graph.session.tracks[0].id;
graph.session.track_mut(source).unwrap().mixer.output = Route::Main;
maximizers(&mut graph.session, graph.receiver, 1);
silent_aux(&mut graph.session, 2);
let master = graph.session.add_track(TrackKind::Master, ChannelFormat::Stereo, None);
maximizers(&mut graph.session, master, 1);
let mut mix = make_mix();
let main = capture_pcm(&mut mix, &graph, 0, 900, &[100, 37, 1, 64]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
assert!(main.iter().all(|channel| channel[..4 * LOOKAHEAD].iter().all(|sample| *sample == 0.0)));
assert!(main[0][4 * LOOKAHEAD] > 0.4, "main really traverses the excluded output/Aux/Master delays");
for (channel, samples) in main.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let source_time = at as i64 - (4 * LOOKAHEAD) as i64;
let expected = if source_time < 0 {
0.0
} else {
let sent = if source_time < MUTE_AT { AMPLITUDE * numeric_pan(source_time, 0, 600)[channel] } else { 0.0 };
AMPLITUDE + sent
};
assert!((sample - expected).abs() < 2e-7, "exclusion channel {channel}, emit {at}: {sample} != {expected}");
}
}
}
}
#[test]
fn unequal_aux_pre_and_direct_bus_ages_keep_the_documented_raw_clock_fallback() {
for target_pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Mixed upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let contributor = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let mixed_bus = session.add_bus("Unequal actual ages", ChannelFormat::Mono);
session.track_mut(contributor).unwrap().mixer.output = Route::Bus(mixed_bus);
let mut pre_send = SendSlot::new(Route::Bus(mixed_bus));
pre_send.level_db = 0.0;
pre_send.pre_fader = true;
session.track_mut(contributor).unwrap().mixer.sends[0] = Some(pre_send);
let sender = aux(&mut session, mixed_bus, ChannelFormat::Mono, 0);
let capture = session.add_bus("Mixed capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, target_pre, 0, 600, false);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[37, 100, 1, 3, 64]);
let extra = if target_pre { 0 } else { 2 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let delays = [2 * LOOKAHEAD + extra + observation_delay, 3 * LOOKAHEAD + extra + observation_delay];
for (at, (&left, &right)) in output[0].iter().zip(&output[1]).enumerate() {
let contributions = delays.iter().filter(|&&delay| at >= delay).count();
let expected = if at < MUTE_AT as usize + observation_delay { AMPLITUDE * contributions as f32 } else { 0.0 };
assert!((left - expected).abs() < 2e-7, "mixed tap pre={target_pre} emit{at}: {left} != {expected}");
assert_eq!(right, 0.0);
}
assert!(output[0].iter().any(|sample| *sample > 0.02));
}
}
#[test]
fn negative_positions_and_reset_seek_use_the_delayed_source_clock_with_pdc_off() {
let graph = ordinary(false, 1, 0, false, -512, -300, 300);
let mut mix = make_mix();
let negative = capture_pcm(&mut mix, &graph, -128, 256, &[1, 37, 3, 64, 17]);
assert_eq!(mix.latency, 0, "PDC is off while the insert still physically delays its source");
check_known(&negative, &graph, -128, LOOKAHEAD, 256);
mix.reset();
let seek = capture_pcm(&mut mix, &graph, 240, 400, &[100, 1, 37, 3]);
check_known(&seek, &graph, 240, LOOKAHEAD, 400);
assert_eq!(seek[1].iter().rposition(|sample| sample.abs() > 1e-6), Some(130));
}
+74 -5
View File
@@ -1,7 +1,7 @@
use super::{
Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin,
PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId,
itu_stereo_fold, main_channels, midi, record, sync_channel,
Arc, AtomicBool, AtomicU32, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering,
OutputTrouble, Plugin, PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared,
SyncSender, TrackId, devices, itu_stereo_fold, main_channels, midi, record, sync_channel,
};
use soundcraft_mix::{LiveMidi, midi_port_bit, midi_thru};
use soundcraft_model::TrackKind;
@@ -17,6 +17,29 @@ pub(crate) struct Fault {
pub(crate) beats: std::sync::atomic::AtomicU64,
/// The UI has been told.
reported: AtomicBool,
/// Underruns the device reported, callbacks that overran their buffer period, and the worst
/// callback's share of its buffer time (‰), since the stream opened or the last
/// [`Player::take_health`], and the device callbacks in that time.
xruns: std::sync::atomic::AtomicU64,
late_callbacks: std::sync::atomic::AtomicU64,
worst_load: AtomicU32,
callbacks: std::sync::atomic::AtomicU64,
}
/// How the realtime audio path keeps up, for the UI and for stress tests: since the output
/// opened, or since the last [`Player::take_health`].
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub struct AudioHealth {
/// Device callbacks (none for the silent clock).
pub callbacks: u64,
/// Underruns (dropouts) the device reported.
pub xruns: u64,
/// Callbacks that overran their buffer period. Not every one is an audible gap, and the
/// device may report the same overrun as an xrun too (CoreAudio does).
pub late_callbacks: u64,
/// The slowest callback's render time as a share of its buffer period, to 0.001 (1.0 = it
/// overran).
pub worst_load: f64,
}
impl Fault {
@@ -33,6 +56,50 @@ impl Fault {
};
(!self.reported.swap(true, Ordering::Relaxed)).then_some(trouble)
}
/// A device callback rendered `frames` at `rate` in `took`. Lock-free and allocation-free.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn note_callback(&self, took: std::time::Duration, frames: usize, rate: f64) {
self.callbacks.fetch_add(1, Ordering::Relaxed);
if frames == 0 || rate <= 0.0 {
return;
}
let load = took.as_secs_f64() * rate / frames as f64;
if load > 1.0 {
self.late_callbacks.fetch_add(1, Ordering::Relaxed);
}
self.worst_load.fetch_max((load * 1000.0).min(f64::from(u32::MAX)) as u32, Ordering::Relaxed);
}
/// The stream reported an error (on the audio thread or another). A lost stream is recorded
/// as gone; a transient xrun is counted and the stream keeps playing.
pub(crate) fn note_stream_error(&self, e: &cpal::Error) {
if devices::stream_lost(e) {
self.gone.store(true, Ordering::Relaxed);
} else if e.kind() == cpal::ErrorKind::Xrun {
self.xruns.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.load(Ordering::Relaxed),
xruns: self.xruns.load(Ordering::Relaxed),
late_callbacks: self.late_callbacks.load(Ordering::Relaxed),
worst_load: f64::from(self.worst_load.load(Ordering::Relaxed)) / 1000.0,
}
}
/// The health so far, counting afresh from here: each counter is swapped for zero, so an
/// event the callback records meanwhile lands in this reading or the next, never in neither.
pub(crate) fn take_health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.swap(0, Ordering::Relaxed),
xruns: self.xruns.swap(0, Ordering::Relaxed),
late_callbacks: self.late_callbacks.swap(0, Ordering::Relaxed),
worst_load: f64::from(self.worst_load.swap(0, Ordering::Relaxed)) / 1000.0,
}
}
}
/// How long a playing output may go without a block before it counts as stalled.
@@ -981,14 +1048,16 @@ impl Side {
}
}
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) {
/// `false` when no block was rendered since the last take (`out` keeps its readings).
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) -> bool {
if !source.fresh {
// No block since the last take: keep the readings, but not those of deleted tracks.
out.tracks.retain(|id, _| source.tracks.contains_key(id));
return;
return false;
}
copy_meter_snapshot(source, out);
source.reset_levels();
true
}
pub(crate) fn copy_meter_snapshot(source: &MeterSnapshot, out: &mut MeterSnapshot) {
+105
View File
@@ -175,6 +175,62 @@ pub(crate) fn device(host: &cpal::Host, name: Option<&str>, output: bool) -> Opt
if output { host.default_output_device() } else { host.default_input_device() }
}
/// Why the device does not run at the chosen buffer size, when it does not. `running` is the
/// size the open stream reports it runs at, when it reports one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BufferNote {
/// The size is outside the range the driver reports; the device runs at its default buffer.
/// A range of one size (a shared-mode WASAPI device reports only its period) means the device
/// runs only at that size.
OutsideRange { min: u32, max: u32, running: Option<u32> },
/// The driver refused the size although it reports no range, or one that holds the size; the
/// device runs at its default buffer.
Refused { want: u32, running: Option<u32> },
/// The device took the size, but the open stream runs at another one (a host may round a
/// fixed size to one the hardware supports).
Rounded { want: u32, running: u32 },
}
impl BufferNote {
/// The note in English (the reply's `buffer_note`, and the key of the window's translation).
pub fn english(&self) -> String {
match *self {
BufferNote::OutsideRange { min, max, .. } if min == max => format!("The device runs only at {min} samples."),
BufferNote::OutsideRange { min, max, running: Some(n) } => {
format!("The device allows {min}–{max} samples; it runs at its default buffer, {n} samples.")
}
BufferNote::OutsideRange { min, max, running: None } => format!("The device allows {min}–{max} samples; it runs at its default buffer."),
BufferNote::Refused { want, running: Some(n) } => {
format!("The device did not take {want} samples; it runs at its default buffer, {n} samples.")
}
BufferNote::Refused { want, running: None } => format!("The device did not take {want} samples; it runs at its default buffer."),
BufferNote::Rounded { want, running } => format!("The device runs at {running} samples, not {want}."),
}
}
}
/// The note for a chosen buffer (`want`) the device did not take (`used`, `None` for its
/// default), or took but runs at another size, given the range its driver reports and the size
/// the open stream runs at.
pub fn buffer_note(want: Option<u32>, used: Option<u32>, range: Option<(u32, u32)>, running: Option<u32>) -> Option<BufferNote> {
let want = want?;
if used == Some(want) {
return running.filter(|&n| n != want).map(|running| BufferNote::Rounded { want, running });
}
Some(match range {
Some((min, max)) if !(min..=max).contains(&want) => BufferNote::OutsideRange { min, max, running },
_ => BufferNote::Refused { want, running },
})
}
/// The range a driver reports, if it reports one.
pub(crate) fn buffer_range(supported: &cpal::SupportedBufferSize) -> Option<(u32, u32)> {
match supported {
cpal::SupportedBufferSize::Range { min, max } => Some((*min, *max)),
cpal::SupportedBufferSize::Unknown => None,
}
}
/// The buffer to request: the chosen size when the device's range allows it, else the default.
pub(crate) fn buffer_size(want: Option<u32>, supported: &cpal::SupportedBufferSize) -> cpal::BufferSize {
match (want, supported) {
@@ -190,6 +246,55 @@ pub(crate) fn buffer_size(want: Option<u32>, supported: &cpal::SupportedBufferSi
mod tests {
use super::*;
/// A buffer the driver does not take is said, not silently replaced (#1757).
#[test]
fn a_buffer_the_device_did_not_take_gets_a_note() {
// The RME UFX on Core Audio allows 15..=3072 frames (measured); 4096 opens at its default.
assert_eq!(buffer_note(Some(4096), None, Some((15, 3072)), None), Some(BufferNote::OutsideRange { min: 15, max: 3072, running: None }));
assert_eq!(
BufferNote::OutsideRange { min: 15, max: 3072, running: None }.english(),
"The device allows 15–3072 samples; it runs at its default buffer."
);
// The driver gave no range and refused the size.
assert_eq!(buffer_note(Some(100), None, None, None), Some(BufferNote::Refused { want: 100, running: None }));
// A size within the reported range that still failed is refused, not outside the range.
assert_eq!(buffer_note(Some(256), None, Some((15, 3072)), None), Some(BufferNote::Refused { want: 256, running: None }));
// Taken as asked, or nothing asked: no note.
assert_eq!(buffer_note(Some(256), Some(256), Some((15, 3072)), Some(256)), None);
assert_eq!(buffer_note(None, None, Some((15, 3072)), Some(512)), None);
}
/// The note says the size the device runs at, when the stream reports it.
#[test]
fn the_note_says_the_buffer_the_device_runs_at() {
let note = buffer_note(Some(4096), None, Some((15, 3072)), Some(512)).unwrap();
assert_eq!(note, BufferNote::OutsideRange { min: 15, max: 3072, running: Some(512) });
assert_eq!(note.english(), "The device allows 15–3072 samples; it runs at its default buffer, 512 samples.");
let refused = buffer_note(Some(100), None, None, Some(480)).unwrap();
assert_eq!(refused.english(), "The device did not take 100 samples; it runs at its default buffer, 480 samples.");
}
/// A fixed size the device opened with can still run at another size (cpal: "the host may
/// round to hardware-supported values"); the note names the size it runs at.
#[test]
fn a_size_the_device_took_but_runs_differently_gets_a_note() {
let note = buffer_note(Some(100), Some(100), Some((15, 3072)), Some(128)).unwrap();
assert_eq!(note, BufferNote::Rounded { want: 100, running: 128 });
assert_eq!(note.english(), "The device runs at 128 samples, not 100.");
assert_eq!(buffer_note(Some(100), Some(100), Some((15, 3072)), Some(100)), None, "runs as asked");
assert_eq!(buffer_note(Some(100), Some(100), Some((15, 3072)), None), None, "no running size reported");
}
/// A shared-mode WASAPI device reports one size (its period, 480 frames at 48 kHz on the
/// Windows test machine), so the range has a single value.
#[test]
fn a_device_with_one_buffer_size_is_said_to_run_only_at_it() {
let note = buffer_note(Some(256), None, Some((480, 480)), Some(480)).unwrap();
assert_eq!(note, BufferNote::OutsideRange { min: 480, max: 480, running: Some(480) });
assert_eq!(note.english(), "The device runs only at 480 samples.");
assert_eq!(buffer_note(Some(256), None, Some((480, 480)), None).unwrap().english(), "The device runs only at 480 samples.");
}
#[test]
fn config_round_trips_and_tolerates_missing_fields() {
let c = AudioConfig {
+46 -12
View File
@@ -48,8 +48,9 @@ const BLOCK: usize = 512;
/// Room for replaced snapshots on their way back; `update_session` empties it before each send.
const OLD_SESSIONS: usize = 16;
/// The realtime audio thread marker lives in the mix engine, which carries it into the strips it
/// renders on worker threads; the cpal callbacks here set it.
pub use callback::AudioHealth;
/// The realtime audio thread marker lives in the mix engine, which renders every strip on the
/// marked thread itself; the cpal callbacks here set it.
pub use soundcraft_mix::{mark_audio_thread, on_audio_thread};
mod callback;
@@ -62,7 +63,7 @@ use callback::{STALL, copy_meter_snapshot};
use callback::{guarded_block, stalled};
#[cfg(test)]
use stream::pick_output_config;
use stream::{Opened, build_output, first_started, open_device, start_stream};
use stream::{Opened, build_output, first_started, open_device, running_buffer, start_stream};
/// Meter values for the UI: the highest peak (and gain reduction) of every block rendered since
/// the UI last took them with [`Player::take_meters`]. The audio thread renders blocks faster than
@@ -105,6 +106,12 @@ impl MeterSnapshot {
self.fresh = true;
}
/// Zero every level, keeping the entries and their storage: for a reader whose readings went
/// stale because no block has arrived for a while (the device stopped calling back).
pub fn clear_levels(&mut self) {
self.reset_levels();
}
/// Drop the entries of deleted tracks.
fn forget(&mut self, gone: &[TrackId]) {
for id in gone {
@@ -178,6 +185,10 @@ pub struct Player {
pub device_channels: u16,
/// The device buffer in frames when one was chosen (`None`: the device default).
pub device_buffer: Option<u32>,
/// The buffer range the output device's driver reports, when it reports one.
pub device_buffer_range: Option<(u32, u32)>,
/// The buffer the open output stream reports it runs at (`None` when it reports none).
pub device_buffer_running: Option<u32>,
/// True when no audio device could be opened (silent clock).
pub silent: bool,
}
@@ -211,6 +222,19 @@ impl Player {
self.fault.trouble(stalled)
}
/// How the realtime path has kept up since the output opened or the last
/// [`Player::take_health`]: callbacks, device-reported underruns, late callbacks and the
/// worst callback load.
pub fn health(&self) -> AudioHealth {
self.fault.health()
}
/// [`Player::health`] so far, then count afresh (a stress run measures from a take). No
/// event is lost between the reading and the restart.
pub fn take_health(&self) -> AudioHealth {
self.fault.take_health()
}
fn side(&self) -> std::sync::MutexGuard<'_, Side> {
self.side.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -234,7 +258,7 @@ impl Player {
Mutex::new(side)
};
match open_device(want, want_ch, cfg) {
Ok((device, config, format, name)) => {
Ok((device, config, format, name, buffer_range)) => {
// The chosen buffer size first; if the device refuses it, its default.
let mut attempts = vec![config];
if config.buffer_size != cpal::BufferSize::Default {
@@ -266,9 +290,11 @@ impl Player {
cpal::BufferSize::Fixed(n) => Some(n),
cpal::BufferSize::Default => None,
};
let running = running_buffer(&stream);
log::info!(
"audio device: {name} @ {rate} Hz, {channels} ch, {format}, buffer {}",
buffer.map_or("default".to_string(), |n| n.to_string())
"audio device: {name} @ {rate} Hz, {channels} ch, {format}, buffer {}{}",
buffer.map_or("default".to_string(), |n| n.to_string()),
running.map_or(String::new(), |n| format!(" (runs at {n})"))
);
Player {
shared,
@@ -282,6 +308,8 @@ impl Player {
device_rate: rate,
device_channels: config.channels,
device_buffer: buffer,
device_buffer_range: buffer_range,
device_buffer_running: running,
silent: false,
}
}
@@ -359,6 +387,8 @@ impl Player {
device_rate: rate,
device_channels: 0,
device_buffer: None,
device_buffer_range: None,
device_buffer_running: None,
silent: true,
}
}
@@ -382,6 +412,8 @@ impl Player {
device_rate: session.sample_rate.hz(),
device_channels: 0,
device_buffer: None,
device_buffer_range: None,
device_buffer_running: None,
silent: true,
}
}
@@ -539,13 +571,15 @@ impl Player {
/// Take the meters accumulated since the last call into reusable UI storage and start a new
/// period: `out` gets the highest peak of every block rendered in between. If no block was
/// rendered since (a large device buffer renders several blocks per callback), `out` keeps
/// the previous values rather than dropping to silence. Call it from one place only (two
/// readers would split the peaks between them). Once track/channel counts are stable this
/// performs no allocation. The audio thread only ever `try_lock`s, so holding the lock here
/// never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) {
/// the previous values rather than dropping to silence, and the call returns `false`: when
/// that goes on for longer than any device buffer lasts, the device has stopped calling back
/// and the reader should clear the readings ([`MeterSnapshot::clear_levels`]). Call it from
/// one place only (two readers would split the peaks between them). Once track/channel
/// counts are stable this performs no allocation. The audio thread only ever `try_lock`s, so
/// holding the lock here never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) -> bool {
let mut source = self.shared.meters.lock().unwrap_or_else(PoisonError::into_inner);
take_meter_snapshot(&mut source, out);
take_meter_snapshot(&mut source, out)
}
}
+12
View File
@@ -669,6 +669,18 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_channel_the_device_does_not_have_is_recorded_as_digital_silence() {
// A track with no input records `usize::MAX`, a channel no device has.
let dir = std::env::temp_dir().join(format!("soundcraft-silent-take-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut take = TakeWriter::create(TrackId(1), vec![usize::MAX, 0], dir.join("Vox_01.wav"), 48_000, ONE_FILE).unwrap();
take.write(&[0.25; 200], 2);
take.write_header();
assert_eq!(decode(&dir.join("Vox_01.wav")), vec![vec![0.0; 100], vec![0.25; 100]]);
let _ = std::fs::remove_dir_all(&dir);
}
/// Files of 100 stereo or 200 mono frames: blocks that straddle a file's end are split there.
#[test]
fn a_take_that_fills_its_file_goes_on_in_the_next() {
+19 -9
View File
@@ -1,5 +1,5 @@
use super::callback::{AudioState, Fault, guarded_block};
use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
use super::{Arc, AudioConfig, Cmd, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
/// Start a freshly built output stream. `false` when the device refuses to start it, so the caller
/// treats it like a stream that failed to build and tries the next configuration.
@@ -13,6 +13,12 @@ pub(crate) fn start_stream(stream: &impl cpal::traits::StreamTrait) -> bool {
}
}
/// The buffer a started stream reports it runs at: Core Audio's device buffer, WASAPI's period.
/// `None` when the backend cannot say (or says 0).
pub(crate) fn running_buffer(stream: &impl cpal::traits::StreamTrait) -> Option<u32> {
stream.buffer_size().ok().filter(|n| *n > 0)
}
/// A built output stream and the channels and fault flag its callback shares with the player.
pub(crate) struct Opened {
pub(crate) stream: cpal::Stream,
@@ -57,10 +63,14 @@ where
let mut scratch = vec![0.0f32; 8192 * frame];
let chunk = scratch.len();
let (failed, guard, gone) = (Arc::clone(fault), Arc::clone(shared), Arc::clone(fault));
#[cfg(not(target_arch = "wasm32"))]
let rate = f64::from(config.sample_rate);
device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
mark_audio_thread();
#[cfg(not(target_arch = "wasm32"))]
let started = std::time::Instant::now();
for out in data.chunks_mut(chunk) {
let Some(s) = scratch.get_mut(..out.len()) else { return };
guarded_block(&failed, &guard, s, |d| state.fill(d, channels));
@@ -68,6 +78,8 @@ where
*o = T::from_sample(*x);
}
}
#[cfg(not(target_arch = "wasm32"))]
failed.note_callback(started.elapsed(), data.len() / frame, rate);
},
// cpal may call this on the audio thread (on ALSA in a loop while the device stays
// broken): marked, so the logger hands the record off instead of writing it.
@@ -77,9 +89,7 @@ where
// stream that must be rebuilt (`StreamInvalidated`), stops playback until the user
// reconnects; a rerouted default device (`DeviceChanged`) keeps playing on the new
// route, and an xrun is transient, so neither counts as losing the stream.
if devices::stream_lost(&e) {
gone.gone.store(true, Ordering::Relaxed);
}
gone.note_stream_error(&e);
log::warn!("audio stream error: {e}");
},
None,
@@ -94,7 +104,7 @@ pub(crate) fn open_device(
want_rate: u32,
want_ch: u16,
cfg: &AudioConfig,
) -> Result<(cpal::Device, cpal::StreamConfig, cpal::SampleFormat, String), String> {
) -> Result<(cpal::Device, cpal::StreamConfig, cpal::SampleFormat, String, Option<(u32, u32)>), String> {
use cpal::traits::DeviceTrait;
let host = devices::host(cfg);
let device = devices::device(&host, cfg.output.as_deref(), true).ok_or_else(|| "no output device".to_string())?;
@@ -103,10 +113,10 @@ pub(crate) fn open_device(
let want_ch = want_ch.max(2);
let rates: Vec<u32> = cfg.sample_rate.into_iter().chain(Some(want_rate)).collect();
let configs: Vec<cpal::SupportedStreamConfigRange> = device.supported_output_configs().map(|configs| configs.collect()).unwrap_or_default();
let (config, format) = match pick_output_config(&configs, &rates, want_ch) {
let (config, format, range) = match pick_output_config(&configs, &rates, want_ch) {
Some((mut c, buffers, format)) => {
c.buffer_size = devices::buffer_size(cfg.buffer_size, &buffers);
(c, format)
(c, format, devices::buffer_range(&buffers))
}
None => {
let d = device.default_output_config().map_err(|e| e.to_string())?;
@@ -126,10 +136,10 @@ pub(crate) fn open_device(
};
let mut stream_config = c.config();
stream_config.buffer_size = devices::buffer_size(cfg.buffer_size, c.buffer_size());
(stream_config, c.sample_format())
(stream_config, c.sample_format(), devices::buffer_range(c.buffer_size()))
}
};
Ok((device, config, format, name))
Ok((device, config, format, name, range))
}
/// Pick the output configuration for the first requested rate the device offers (the configured
+37 -4
View File
@@ -15,7 +15,8 @@ impl cpal::traits::StreamTrait for Fake {
fn pause(&self) -> Result<(), cpal::Error> {
Ok(())
}
/// The fake stream has no clock and no fixed buffer; neither is used by these tests.
/// The fake stream reports 0 frames, which says nothing about a buffer (see
/// `a_stream_that_reports_no_buffer_size_has_no_running_buffer`).
fn buffer_size(&self) -> Result<cpal::FrameCount, cpal::Error> {
Ok(0)
}
@@ -25,6 +26,12 @@ impl cpal::traits::StreamTrait for Fake {
}
}
#[test]
fn a_stream_that_reports_no_buffer_size_has_no_running_buffer() {
// The fake reports 0 frames, which says nothing about the device.
assert_eq!(stream::running_buffer(&Fake { starts: true }), None);
}
#[test]
fn a_stream_that_will_not_start_is_reported_as_failed() {
assert!(!start_stream(&Fake { starts: false }));
@@ -155,7 +162,7 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
// The last block alone (what the UI used to see) is quiet.
assert!(st.mix.meters[&t].peak[0] < 0.05);
let mut ui = MeterSnapshot::default();
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui), "new blocks arrived");
assert!(ui.tracks[&t].peak[0] > 0.85, "{:?}", ui.tracks[&t]);
assert!(ui.tracks[&t].peaks[0] > 0.85);
assert!(ui.main.peak[0] > 0.5 && ui.main.peaks.iter().all(|p| *p > 0.5), "{:?}", ui.main);
@@ -163,9 +170,12 @@ fn a_spike_in_one_block_among_quiet_ones_reaches_the_ui() {
st.fill(&mut out, 2);
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(ui.tracks[&t].peak[0] < 0.05 && ui.main.peak[0] < 0.05);
// No block since the last take: the reading stays rather than dropping to silence.
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
// No block since the last take: the reading stays rather than dropping to silence, and the
// reader is told, so it can clear readings that stay stale (the device stopped calling back).
assert!(!take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui));
assert!(ui.tracks[&t].peak[0] > 0.005);
ui.clear_levels();
assert!(ui.tracks[&t].peak[0] == 0.0 && ui.main.peak[0] == 0.0 && ui.tracks[&t].peaks.len() == 1, "{:?}", ui.tracks[&t]);
}
#[test]
@@ -279,6 +289,28 @@ fn a_lost_or_stalled_device_is_reported_once() {
assert_eq!((fault.trouble(false), fault.trouble(true)), (Some(OutputTrouble::Gone), None));
}
#[test]
fn underruns_and_late_callbacks_are_counted_until_taken() {
use std::time::Duration;
let f = Fault::default();
let error = |kind| cpal::Error::with_message(kind, "test");
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
// 512 frames at 48 kHz last 10.67 ms.
f.note_callback(Duration::from_millis(4), 512, 48_000.0);
f.note_callback(Duration::from_millis(16), 512, 48_000.0);
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
let h = f.health();
assert_eq!(h, AudioHealth { callbacks: 3, xruns: 2, late_callbacks: 1, worst_load: 1.5 });
assert!(!f.gone.load(Ordering::Relaxed), "an underrun is not a lost device");
assert_eq!(f.take_health(), h);
assert_eq!(f.health(), AudioHealth::default());
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
assert_eq!(f.health().callbacks, 1);
f.note_stream_error(&error(cpal::ErrorKind::DeviceNotAvailable));
assert!(f.gone.load(Ordering::Relaxed));
}
#[test]
fn audio_state_plays_and_stops_at_end() {
let s = Arc::new(soundcraft_model::Session::default());
@@ -696,6 +728,7 @@ fn armed_tracks_are_heard_and_metered_after_playback_stops() {
let mut s = soundcraft_model::Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
s.track_mut(t).unwrap().mixer.record_arm = true;
s.track_mut(t).unwrap().mixer.input = soundcraft_model::Route::Hardware("In 1".into());
let shared = Arc::new(Shared {
position: AtomicI64::new(0),
playing: AtomicBool::new(false),
+5
View File
@@ -10,6 +10,11 @@ repository.workspace = true
[dependencies]
craft-mime.workspace = true
craft-ui.workspace = true
craft-behavior.workspace = true
craft-host.workspace = true
craft-keymap.workspace = true
craft-theme.workspace = true
craft-window.workspace = true
soundcraft-time.workspace = true
craft-audio.workspace = true
soundcraft-midi.workspace = true
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+23
View File
@@ -114,6 +114,8 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
"End" => "Fim",
"Extract" => "Extrair",
"File" => "Arquivo",
"File path" => "Caminho do arquivo",
"Folder path" => "Caminho da pasta",
"Format" => "Formato",
"Grab bag" => "Diversos",
"Grid" => "Grade",
@@ -218,6 +220,7 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
"Renderizações e processos do AudioSuite são concluídos antes de retornar."
}
"Reopen the audio devices with these settings" => "Reabrir os dispositivos de áudio com estas configurações",
"Report a problem" => "Relatar um problema",
"Reset" => "Redefinir",
"Reverse the order" => "Inverter a ordem",
"Revert" => "Reverter",
@@ -288,6 +291,7 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
"Transpose" => "Transpor",
"Unknown label" => "Rótulo desconhecido",
"Update check is not supported in the web browser." => "A verificação de atualizações não é compatível com o navegador.",
"Updated by ArtCraft Launcher." => "Atualizado pelo ArtCraft Launcher.",
"Use" => "Usar",
"User presets need the desktop app." => "As predefinições do usuário exigem o aplicativo para desktop.",
"Uses the edit selection." => "Usa a seleção de edição.",
@@ -321,6 +325,23 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
}
"No engine" => "Sem mecanismo de áudio",
"default buffer" => "buffer padrão",
"The audio settings were changed outside this window; your unapplied changes were replaced." => {
"As configurações de áudio foram alteradas fora desta janela; suas alterações não aplicadas foram substituídas."
}
"The device allows {}–{} samples; it runs at its default buffer." => {
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão."
}
"The device did not take {} samples; it runs at its default buffer." => {
"O dispositivo não aceitou {} amostras; ele funciona com o buffer padrão."
}
"The device runs only at {} samples." => "O dispositivo funciona apenas com {} amostras.",
"The device runs at {} samples, not {}." => "O dispositivo funciona com {} amostras, não {}.",
"The device allows {}–{} samples; it runs at its default buffer, {} samples." => {
"O dispositivo aceita {}–{} amostras; ele funciona com o buffer padrão, {} amostras."
}
"The device did not take {} samples; it runs at its default buffer, {} samples." => {
"O dispositivo não aceitou {} amostras; ele funciona com o buffer padrão, {} amostras."
}
"Bus name: {name}" => "Nome do bus: {name}",
"Model" => "Modelo",
"Version" => "Versão",
@@ -1761,6 +1782,8 @@ fn menu_translate(source: &str) -> Option<&'static str> {
"Enable Track Notes Dialog" => "Ativar o diálogo de notas da pista",
"English" => "Inglês",
"Portuguese (Brazil)" => "Português (Brasil)",
"French" => "Francês",
"Spanish" => "Espanhol",
"key:Space" => "Espaço",
"key:Up" => "Cima",
"key:Down" => "Baixo",
+1 -1
View File
@@ -176,7 +176,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let current=state.compositions.iter().find(|(_,id)|*id==state.composition).map_or("Choose one…".to_string(),|(n,_)|n.clone());
// Locked while analyzing, so a finished analysis always matches the selection.
ui.add_enabled_ui(state.busy.is_none(),|ui|{
craft_ui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
egui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{
for (name,id) in &state.compositions {
if ui.selectable_label(state.composition==*id,format!("{name} ({id})")).clicked() { state.composition=id.clone(); state.preview=None; }
}
+16 -2
View File
@@ -81,6 +81,7 @@ impl SoundApp {
synthetic_batch: None,
synthetic_pointer_active: false,
cancel_synthetic_pointer: false,
injected_acks: VecDeque::new(),
cancel_synthetic_keys: false,
cancel_synthetic_scroll: false,
input_before_scroll: None,
@@ -111,6 +112,9 @@ impl SoundApp {
system_fonts: true,
theme_applied: None,
docking_context: None,
docks: crate::docking::LiveDocks::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: crate::framework::host(),
sim: None,
record_hint: None,
quit_requested: false,
@@ -125,6 +129,7 @@ impl SoundApp {
frame_ms: 0.0,
last_frame: None,
last_meter_poll: f64::NEG_INFINITY,
last_meter_block: f64::NEG_INFINITY,
video: video_track::VideoPool::default(),
bounce: None,
imports: import::Imports::default(),
@@ -151,6 +156,12 @@ impl SoundApp {
let _language = crate::localization::enter(self.ui.language);
self.ui.undo_levels = self.ui.undo_levels.clamp(1, 64);
self.engine.set_history_limit(self.ui.undo_levels);
// A saved state (a hand-edited `ui.json`) can hold more than the menu keeps: keep the newest
// (the list is newest first) and have the host save the corrected list.
if self.ui.recent_sessions.len() > crate::dialogs::recent::MAX_RECENT {
self.ui.recent_sessions.truncate(crate::dialogs::recent::MAX_RECENT);
self.recent_changed = true;
}
// Fonts set now take effect next frame, so draw only from the frame after.
if !self.fonts_ready {
if self.fonts_installed {
@@ -182,7 +193,7 @@ impl SoundApp {
// Frame pacing and the transport simulation use a monotonic host clock instead.
let dt = self.tick_dt();
self.last_frame = Some(self.uptime);
crate::control::expire_gestures(self);
crate::control::expire_gestures(self, ctx);
crate::control::drain(self, ctx);
self.note_recent_session();
self.apply_editor_edits();
@@ -315,7 +326,7 @@ impl SoundApp {
// Input preparation: remember this pass's real pointer/keyboard state, which `logic` (run
// before `ui` in each pass and alone on hidden ticks) uses for gestures and automation.
self.pointer_down = ctx.input(|i| i.pointer.any_down());
self.wants_keyboard = ctx.egui_wants_keyboard_input();
self.wants_keyboard = crate::framework::widget_has_keyboard(&ctx);
// The integration creates this Ui before logic resolves the current frame's palette.
ui.set_style(ctx.global_style());
if !self.fonts_ready {
@@ -356,8 +367,11 @@ impl SoundApp {
dialogs::show(self, &ctx);
aaf_import::show(self, &ctx);
updates_ui::show(self, &ctx);
self.run_framework_dialogs(ui);
// The sampler's drop rects are current now, so route any captured drop in this pass.
self.route_dropped_files();
// A scripted key (`ui.key`) is acknowledged by the framework's idle signal, not by egui's event list.
crate::control::injected_settled(self, &ctx);
// The pass that actually received the injected events has already dispatched their widget
// side effects, even when it then asks for another layout pass. `received_synthetic` was
// captured before menus and widgets, so a widget that consumed the event from InputState
+186 -3
View File
@@ -27,7 +27,7 @@ impl SoundApp {
// The input reopens on the next record or monitor with the new choice.
self.recorder = None;
self.recorder_failed = false;
let player = soundcraft_playback::Player::with_config(self.engine.session_arc(), &self.ui.audio);
let player = reopen(&mut self.player, &self.ui.audio, || soundcraft_playback::Player::with_config(self.engine.session_arc(), &self.ui.audio));
self.attach_midi(&player);
player.locate(at);
self.player = Some(player);
@@ -127,12 +127,52 @@ impl SoundApp {
}
self.recorder = None;
self.recorder_failed = false;
let player = Player::with_config(self.engine.session_arc(), &self.ui.audio);
let player = reopen(&mut self.player, &self.ui.audio, || Player::with_config(self.engine.session_arc(), &self.ui.audio));
self.attach_midi(&player);
self.player = Some(player);
}
}
/// How long the meters keep the last readings while no audio block arrives. Longer than the
/// longest device buffer (8192 frames at 44.1 kHz, 186 ms) plus the slowest meter poll (50 ms), so
/// a large buffer never reads as silence between its callbacks; once it has passed, the device has
/// stopped calling back (switched off, unplugged, stalled) and the meters fall to silence.
pub(super) const METER_STALE_SECS: f64 = 0.5;
/// After a meter take that `fresh`ly brought new blocks or not, at `now` (uptime, seconds): note
/// when the last block came in `last_block`, and clear `snap`'s readings once none has come for
/// [`METER_STALE_SECS`]. Otherwise the last block's levels would be fed to the meters every frame
/// and never fall.
pub(super) fn age_meters(snap: &mut soundcraft_playback::MeterSnapshot, fresh: bool, now: f64, last_block: &mut f64) {
if fresh {
*last_block = now;
} else if now - *last_block >= METER_STALE_SECS {
snap.clear_levels();
}
}
/// Open the new device of `cfg` with `open` in place of the one in `slot`, and return it; the caller
/// stores it, which closes the old one if it is still there.
///
/// On ASIO the old device closes first: in cpal 0.18.2 a process holds one ASIO driver, and while
/// the old stream keeps it loaded the device list stops at the first other driver, so the new device
/// (even the same driver again) is often not found and the player falls back to the silent clock
/// (#1864). Elsewhere (Core Audio, WASAPI, ALSA, JACK) a device opens whatever else is open, and the
/// old one stays open until the new one is there, as before: closing first there would only make the
/// new device start cold, which on Core Audio holds Apply on the UI thread for about half a second.
fn reopen<T>(slot: &mut Option<T>, cfg: &soundcraft_playback::AudioConfig, open: impl FnOnce() -> T) -> T {
if one_driver_per_process(cfg) {
drop(slot.take());
}
open()
}
/// Whether `cfg`'s audio system opens one driver per process (ASIO in cpal 0.18.2), so the device in
/// use must close before another (or the same one again) can be found.
fn one_driver_per_process(cfg: &soundcraft_playback::AudioConfig) -> bool {
cfg.system.as_deref().is_some_and(|s| s.eq_ignore_ascii_case("ASIO"))
}
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);
@@ -143,7 +183,9 @@ pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], gr: f32, dt: f32)
if let Some(x) = d.level.get_mut(c) {
*x = if nv < 1e-5 { 0.0 } else { nv };
}
if v >= d.hold.get(c).copied().unwrap_or(0.0) {
// 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;
}
@@ -167,6 +209,84 @@ pub(super) fn wants_audio_input(s: &soundcraft_model::Session) -> bool {
s.tracks.iter().any(|t| !t.kind.is_midi() && (t.mixer.input_monitor || t.mixer.record_arm))
}
#[cfg(test)]
mod reopen_tests {
use super::reopen;
use soundcraft_playback::AudioConfig;
use std::cell::Cell;
use std::rc::Rc;
/// A fake audio system. `one_driver` models ASIO in cpal 0.18.2: while a stream holds the
/// driver, looking a device up by name finds nothing. Without it, any device opens.
#[derive(Default)]
struct FakeHost {
one_driver: bool,
open_streams: Rc<Cell<u32>>,
opened_while_another_was_open: Cell<u32>,
}
/// An open stream; dropping it closes it (and releases an ASIO driver).
struct Stream(Rc<Cell<u32>>);
impl Drop for Stream {
fn drop(&mut self) {
self.0.set(self.0.get() - 1);
}
}
/// A player: its stream when the device was found, else the silent clock (no stream).
struct FakePlayer {
stream: Option<Stream>,
}
impl FakeHost {
fn open(&self) -> FakePlayer {
if self.open_streams.get() > 0 {
self.opened_while_another_was_open.set(self.opened_while_another_was_open.get() + 1);
if self.one_driver {
return FakePlayer { stream: None };
}
}
self.open_streams.set(self.open_streams.get() + 1);
FakePlayer { stream: Some(Stream(Rc::clone(&self.open_streams))) }
}
}
fn config(system: &str) -> AudioConfig {
AudioConfig { system: Some(system.into()), output: Some("ASIO4ALL v2".into()), ..AudioConfig::default() }
}
/// Apply, Apply, Reconnect: each step opens the device of `cfg` in place of the open one, as
/// `apply_audio_config` and `reconnect_audio` do. Returns whether each step found the device.
fn apply_apply_reconnect(host: &FakeHost, cfg: &AudioConfig) -> Vec<bool> {
let mut player = Some(host.open());
assert!(player.as_ref().is_some_and(|p| p.stream.is_some()), "the first open finds the device");
let mut found = Vec::new();
for _ in ["first Apply", "second Apply", "Reconnect"] {
let new = reopen(&mut player, cfg, || host.open());
found.push(new.stream.is_some());
player = Some(new);
}
found
}
#[test]
fn on_asio_every_apply_and_reconnect_finds_the_device() {
let host = FakeHost { one_driver: true, ..FakeHost::default() };
assert_eq!(apply_apply_reconnect(&host, &config("ASIO")), [true, true, true], "no step falls back to the silent clock");
assert_eq!(host.opened_while_another_was_open.get(), 0, "the old stream released the driver before each lookup");
}
#[test]
fn elsewhere_the_old_device_stays_open_until_the_new_one_is_there() {
for system in ["CoreAudio", "WASAPI"] {
let host = FakeHost::default();
assert_eq!(apply_apply_reconnect(&host, &config(system)), [true, true, true]);
assert_eq!(host.opened_while_another_was_open.get(), 3, "{system}: each new device opened before the old one closed, as before");
}
}
}
#[cfg(test)]
mod audio_input_tests {
use super::wants_audio_input;
@@ -189,3 +309,66 @@ mod audio_input_tests {
assert!(wants_audio_input(&s));
}
}
#[cfg(test)]
mod meter_tests {
use super::{METER_STALE_SECS, MeterDisplay, age_meters, feed_meter};
use soundcraft_mix::StripMeter;
use soundcraft_model::TrackId;
use soundcraft_playback::MeterSnapshot;
/// Runs the UI's meter loop for `secs` at 60 frames a second, polling at 20 Hz as the Edit
/// window does; `blocks(prev, now)` says whether a block (with `peak`) arrived since the
/// previous poll.
fn run(secs: f64, peak: [f32; 2], blocks: impl Fn(f64, f64) -> bool) -> (MeterDisplay, f32) {
let t = TrackId(1);
let mut snap = MeterSnapshot::default();
let mut d = MeterDisplay::default();
let (mut last_block, mut last_poll, mut lowest) = (f64::NEG_INFINITY, f64::NEG_INFINITY, f32::INFINITY);
let dt = 1.0 / 60.0;
let mut now = 0.0;
while now < secs {
if now - last_poll >= 1.0 / 20.0 {
let fresh = blocks(last_poll.max(-1e-9), now);
if fresh {
let m = snap.tracks.entry(t).or_insert_with(StripMeter::default);
m.peak = peak;
m.peaks = peak.to_vec();
}
age_meters(&mut snap, fresh, now, &mut last_block);
last_poll = now;
}
let m = snap.tracks.get(&t).map_or([0.0; 2], |m| m.peak);
feed_meter(&mut d, m, 0.0, dt as f32);
if now > 0.0 {
lowest = lowest.min(d.level[0]);
}
now += dt;
}
(d, lowest)
}
#[test]
fn meters_fall_to_silence_when_the_device_stops_calling_back() {
// Blocks come for a second, then the device is switched off: no callback ever again.
let (d, _) = run(6.0, [0.4; 2], |_, now| now < 1.0);
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
}
/// A silent channel does not keep the other channel's peak hold up: 0.0 meets a hold of 0.0
/// every frame, which must not restart the shared hold time.
#[test]
fn a_silent_channel_does_not_keep_the_other_channels_peak_hold() {
let (d, _) = run(6.0, [0.4, 0.0], |_, now| now < 1.0);
assert!(d.level == [0.0; 2] && d.hold == [0.0; 2], "the meter still reads {d:?}");
}
#[test]
fn a_large_device_buffer_keeps_the_meters_up_between_callbacks() {
// 8192 frames at 44.1 kHz: one block every 186 ms, several polls without one.
let period = 8192.0 / 44_100.0;
assert!(period + 1.0 / 20.0 < METER_STALE_SECS);
let (d, lowest) = run(3.0, [0.4; 2], |prev, now| (now / period).floor() > (prev / period).floor());
assert!(lowest >= 0.4 && d.level[0] >= 0.4, "the meter dropped to {lowest} between callbacks");
}
}

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