Compare commits

...
Author SHA1 Message Date
dependabot[bot] e3ba790c40 ci(deps): bump step-security/harden-runner
Bumps the actions group with 1 update in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner).


Updates `step-security/harden-runner` from 2.22.4 to 2.23.0
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/1d88384fd173af6ecb012dfd0264a306b711241a...aebdcf6156ab6691adf63218240e476564a1ed4c)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 21:09:20 +00: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
78 changed files with 2462 additions and 324 deletions
+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1408486424,
"producer_workflow_id": 429730684,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"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": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+4 -4
View File
@@ -36,7 +36,7 @@ jobs:
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -118,7 +118,7 @@ jobs:
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -207,14 +207,14 @@ jobs:
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
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@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/rust-channel@main
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
+16 -2
View File
@@ -34,12 +34,26 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
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.
+3 -2
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
app-name: soundcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
@@ -32,3 +32,4 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+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 }}
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -61,7 +61,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+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
+9 -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)
+8
View File
@@ -22,6 +22,8 @@ fn is_control_method(method: &str) -> bool {
| "ui.move"
| "ui.click"
| "ui.drag"
| "ui.scroll"
| "ui.zoom"
| "ui.key"
| "ui.text"
| "ui.screenshot"
@@ -68,5 +70,11 @@ mod tests {
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
assert_eq!(app_request(method, json!({})).0, method);
}
for (method, params) in [
("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() {
+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();
+4 -1
View File
@@ -67,7 +67,10 @@ fn main() {
}
if let Err(e) = res.compile() {
if std::env::var_os("SOUNDCRAFT_REQUIRE_WINRES").is_some() {
panic!("embedding Windows resources failed: {e}");
// 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);
}
println!("cargo:warning=soundcraft.exe built without icon/version resources: {e}");
}
+7 -1
View File
@@ -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]
+79 -1
View File
@@ -149,6 +149,12 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
@@ -162,11 +168,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
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 {
@@ -252,6 +303,8 @@ fn validate_for(
Ok(confirmed)
}
const PROFILE_FOLDERS: [&str; 3] = ["Autosave", "Presets", "logs"];
#[cfg(test)]
mod tests {
use super::*;
@@ -428,6 +481,31 @@ mod tests {
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
+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();
+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());
+5 -1
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 };
+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)]);
+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 {
+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"));
+47 -27
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));
@@ -581,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]
+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::*;
+2 -1
View File
@@ -192,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);
}
}
@@ -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();
+3 -1
View File
@@ -238,9 +238,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))
}
+18
View File
@@ -1143,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];
@@ -1161,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();
+4 -2
View File
@@ -981,14 +981,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 {
+30 -10
View File
@@ -62,7 +62,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 +105,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 +184,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,
}
@@ -234,7 +244,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 +276,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 +294,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 +373,8 @@ impl Player {
device_rate: rate,
device_channels: 0,
device_buffer: None,
device_buffer_range: None,
device_buffer_running: None,
silent: true,
}
}
@@ -382,6 +398,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 +557,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() {
+11 -5
View File
@@ -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,
@@ -94,7 +100,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 +109,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 +132,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
+15 -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]
@@ -696,6 +706,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),
+19
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",
@@ -323,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",
+7
View File
@@ -129,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(),
@@ -155,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 {
+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");
}
}
+79 -7
View File
@@ -1,4 +1,4 @@
use super::audio::feed_meter;
use super::audio::{age_meters, feed_meter};
use super::plugins::failed_plugin_status;
use super::{Gesture, MainWindow, MeterDisplay, Range, Samples, SoundApp, TrackId, TransportRequest, json};
@@ -234,6 +234,8 @@ impl SoundApp {
Ok(dir)
}
/// Ends recording, clears the punch state and places the recorded takes
/// (from the recorder or the take plan when the recorder is already gone).
fn finish_recording(&mut self) {
self.engine.transport.recording = false;
let midi_pass = self.end_midi_pass();
@@ -246,13 +248,21 @@ impl SoundApp {
// The audio input stops taking in first: waiting for the MIDI below would otherwise add
// what the input hears meanwhile to the audio takes. No input device is open when the
// pass was MIDI only.
let (takes, problem) = self.recorder.as_mut().map_or_else(|| (Vec::new(), None), |r| r.finish());
// The audio thread writes down what was played up to the stop; the clips wait for that.
let plan = self.take_plan.take();
self.punch = None;
self.autosaved_rev = 0;
// The recorder can already be gone (tests run headless): the plan still names the takes,
// so place what it holds; with neither, there is nothing to place.
let (takes, problem) = match (&mut self.recorder, &plan) {
(Some(r), _) => r.finish(),
(None, Some(plan)) => (plan.takes.iter().map(|t| (t.track, t.path.clone())).collect(), None),
(None, None) => (Vec::new(), None),
};
let midi_confirmed = self.await_midi_capture(midi_pass);
// Where the pass ended: the audio engine's own position is the freshest.
let engine_at = self.player.as_ref().map(|p| p.position());
let stopped_at = super::midi::pass_stop(engine_at, self.engine.transport.position);
let plan = self.take_plan.take();
let tracks = takes.len().max(1);
let plan = plan.unwrap_or_else(|| soundcraft_engine::io::Recording {
start: self.record_start,
@@ -261,8 +271,6 @@ impl SoundApp {
rate: 0,
takes: Vec::new(),
});
self.punch = None;
self.autosaved_rev = 0;
let ids = soundcraft_engine::io::place_recording(&mut self.engine, &plan, takes);
// The audio engine may have confirmed the pass while the audio takes were finished: the
// stop position and what the user is told go by one answer.
@@ -463,7 +471,14 @@ impl SoundApp {
}
TransportRequest::Record => {
if self.engine.transport.recording {
self.stop_play();
// Punching out ends the take; while playing, the transport keeps
// running, like QuickPunch. `finish_recording` places the take
// without touching playback.
if self.is_playing() {
self.finish_recording();
} else {
self.stop_play();
}
} else {
self.start_recording();
}
@@ -507,7 +522,8 @@ impl SoundApp {
let now = self.uptime;
let meter_interval = if self.ui.window == MainWindow::Mix { 1.0 / 60.0 } else { 1.0 / 20.0 };
if now - self.last_meter_poll >= meter_interval {
p.take_meters(&mut self.meter_snapshot);
let fresh = p.take_meters(&mut self.meter_snapshot);
age_meters(&mut self.meter_snapshot, fresh, now, &mut self.last_meter_block);
self.last_meter_poll = now;
}
let snap = &self.meter_snapshot;
@@ -562,4 +578,60 @@ mod tests {
assert_eq!(app.fallback_take_dir().unwrap(), a, "the same folder for the rest of the run");
let _ = std::fs::remove_dir_all(&a);
}
/// Punching out (Record pressed again mid-take) ends the take and leaves the transport
/// running, like QuickPunch: the punch clears, the take is placed inside the punch range,
/// and playback continues from where it was.
#[test]
fn punching_out_while_playing_keeps_the_transport_running() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.run("track.new", json!({"count": 1, "format": "mono"})).unwrap();
let track = app.engine.session().tracks[0].id;
// A take already recorded over the punch range, so the punch-out has something to place.
let take = std::env::temp_dir().join(format!("soundcraft-punch-out-take-{}.wav", std::process::id()));
let opts = craft_audio::EncodeOptions::new(craft_audio::EncodeFormat::Wav);
std::fs::write(
&take,
craft_audio::encode(&craft_audio::AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 96_000]] }, &opts).unwrap(),
)
.unwrap();
app.record_start = 0;
app.punch = Some(Range { start: 48_000, end: 96_000 });
app.take_plan = Some(soundcraft_engine::io::Recording {
start: 0,
pass: None,
punch: app.punch,
rate: 48_000,
takes: vec![soundcraft_engine::io::Take { track, path: take.clone(), channels: 1 }],
});
// Punch out two seconds in: the playhead must keep its place, not restart from the top.
app.start_play(96_000, None, None);
app.engine.transport.recording = true;
app.engine.transport_requests.push(TransportRequest::Record);
app.handle_transport(1.0 / 60.0);
assert!(!app.engine.transport.recording, "the take ends");
assert!(app.punch.is_none(), "the punch clears");
assert!(app.is_playing(), "playback continues after the punch-out");
assert!(app.engine.transport.position >= 96_000, "the playhead keeps its place instead of restarting");
let clips = app.engine.session().track(track).unwrap().clips().to_vec();
assert_eq!(clips.len(), 1, "the take is placed");
assert_eq!(clips[0].start, 48_000, "the take is trimmed to the punch");
assert_eq!(clips[0].end(), 96_000, "the take covers the punch");
let _ = std::fs::remove_file(&take);
}
/// A Record press while recording but not playing (a player that died mid-take, say)
/// still stops everything, from where it was.
#[test]
fn a_record_press_while_recording_but_stopped_still_stops() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.start_play(96_000, None, None);
app.engine.transport.playing = false;
app.engine.transport.recording = true;
app.engine.transport_requests.push(TransportRequest::Record);
app.handle_transport(1.0 / 60.0);
assert!(!app.engine.transport.recording);
assert!(!app.is_playing());
assert_eq!(app.engine.transport.position, 96_000, "the playhead stays where it stopped");
}
}
+5 -2
View File
@@ -342,7 +342,8 @@ fn bounce_file_row(app: &mut SoundApp, ui: &mut egui::Ui, path: &mut String, for
/// The path prompt's form; the command to run once it is confirmed.
fn path_prompt_form(app: &mut SoundApp, ui: &mut egui::Ui, cmd: &str, path: &mut String, key: &str, enter: bool) -> Option<(String, Value)> {
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), crate::localization::text("Path"));
let label = if key == "dir" { crate::localization::text("Folder path") } else { crate::localization::text("File path") };
crate::widgets::named_text_field(ui.add(egui::TextEdit::singleline(path).desired_width(420.0)), label);
let mut picked = None;
// Import Audio picks several files at once; every other open dialog takes one.
let multi = cmd == "file.import_audio" && app.services.pick_open_many.is_some();
@@ -444,7 +445,9 @@ fn strip_silence_form(
mode = Some("separate");
}
// Enter on a focused Extract or Separate clicks that button, so Enter presses Strip only when neither was clicked.
if buttons(ui, "Strip", enter) && mode.is_none() {
// The button is its own string ("Strip Silence"), not the Channel Strip plug-in's
// short name "Strip", so translations can give them different words (#1610).
if buttons(ui, "Strip Silence", enter) && mode.is_none() {
mode = Some("strip");
}
// Enter on a focused Rename… also presses Strip, so Rename… goes first.
+15
View File
@@ -159,4 +159,19 @@ mod tests {
let ui: crate::UiState = serde_json::from_str("{}").unwrap();
assert!(ui.recent_sessions.is_empty());
}
/// A saved state with more entries than the menu keeps (a hand-edited `ui.json`) is cut to
/// the newest [`MAX_RECENT`] on the first frame, and a list within the limit is left alone.
/// Cutting it tells the host to save, so the file is corrected without waiting for a clean exit.
#[test]
fn an_oversized_saved_list_is_capped_on_the_first_frame() {
let paths = |count: usize| (0..count).map(|i| format!("{i}.scraft")).collect::<Vec<_>>();
for (saved, kept) in [(1000, MAX_RECENT), (MAX_RECENT + 1, MAX_RECENT), (MAX_RECENT, MAX_RECENT), (3, 3), (0, 0)] {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default());
app.ui = serde_json::from_value(json!({"recent_sessions": paths(saved)})).unwrap();
let mut harness = egui_kittest::Harness::builder().build_ui_state(|ui, app: &mut SoundApp| app.logic(&ui.ctx().clone()), app);
assert_eq!(harness.state().ui.recent_sessions, paths(kept), "{saved} saved entries");
assert_eq!(harness.state_mut().take_recent_changed(), saved > kept, "{saved} saved entries: save only when entries were cut");
}
}
}
+5
View File
@@ -149,6 +149,8 @@ pub struct UiState {
pub preferences_window_pos: Option<[f32; 2]>,
pub reduce_visual_effects: preferences::ReduceVisualEffects,
pub undo_levels: usize,
/// The level a send made in the Mix window starts at (Preferences › Mixing).
pub sends_default: preferences::SendsDefault,
/// The audio device choice (Setup › Playback Engine), kept with the preferences: per machine.
pub audio: soundcraft_playback::AudioConfig,
/// The Mix window lives in its own native window (Window › Mix in Separate Window); the main
@@ -227,6 +229,7 @@ impl Default for UiState {
preferences_window_pos: None,
reduce_visual_effects: preferences::ReduceVisualEffects::default(),
undo_levels: 64,
sends_default: preferences::SendsDefault::default(),
audio: soundcraft_playback::AudioConfig::default(),
mix_separate: false,
show_io_setup: false,
@@ -481,6 +484,8 @@ pub struct SoundApp {
pub frame_ms: f32,
last_frame: Option<f64>,
last_meter_poll: f64,
/// When a meter take last brought new audio blocks (uptime, seconds).
last_meter_block: f64,
/// Movies for the Video window and Video track (decoded in the background).
pub video: video_track::VideoPool,
/// The Bounce Mix in progress, rendered a slice per frame.
+10
View File
@@ -512,6 +512,16 @@ mod tests {
}
}
/// The Strip Silence dialog's action button and the Channel Strip plug-in's short name are
/// different strings ("remove" vs a channel strip): the button keeps the dialog's own key,
/// so a translation gives each its word (#1610).
#[test]
fn strip_button_translates_as_its_own_key() {
let pt = Language::PortugueseBrazil;
assert_eq!(pt.text("Strip Silence"), "Remover silêncio", "the dialog's action button");
assert_eq!(pt.text("Strip"), "Canal", "the Channel Strip plug-in's short name keeps its own key");
}
#[test]
fn every_localized_source_string_has_a_catalog_entry() {
fn visit(dir: &std::path::Path, missing: &mut Vec<String>) {
+114
View File
@@ -82,6 +82,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
("ui.theme", "Appearance", "", None),
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
("ui.undo_levels", "Levels of Undo", "", None),
("ui.sends_default", "Sends Default to", "", None),
];
/// Extra catalog mappings handled by the UI layer.
@@ -849,6 +850,20 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
}
json!({"levels": app.ui.undo_levels})
}
"ui.sends_default" => {
// No `level` reads the value back; a `level` that is not a string is an error, so
// `{"level": 0}` cannot look like it set 0 dB while changing nothing.
let level = match p.get("level") {
None => return Some(Ok(json!({"level": app.ui.sends_default.id()}))),
Some(Value::String(level)) => level.as_str(),
Some(other) => return Some(Err(format!("send default must be the string \"-inf\" or \"0\", not {other}"))),
};
let Some(level) = crate::preferences::SendsDefault::parse(level) else {
return Some(Err(format!("unknown send default `{level}` (-inf or 0)")));
};
app.ui.sends_default = level;
json!({"level": level.id()})
}
"ui.set" => match serde_json::to_value(&app.ui) {
Ok(mut cur) => {
if let (Some(obj), Some(patch)) = (cur.as_object_mut(), p.as_object()) {
@@ -866,6 +881,8 @@ pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<
app.ui = ns;
app.ui.undo_levels = app.ui.undo_levels.clamp(1, 64);
app.engine.set_history_limit(app.ui.undo_levels);
// The list is newest first, so this keeps the newest, as `recent::note` does.
app.ui.recent_sessions.truncate(crate::dialogs::recent::MAX_RECENT);
if closed_preferences {
app.preferences.discard_draft();
}
@@ -951,6 +968,103 @@ mod tests {
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (64, 64));
}
/// The Sends Default to preference reads back, takes -inf or 0, and rejects anything else.
#[test]
fn sends_default_sets_reads_and_rejects_unknown_levels() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
assert_eq!(app.run("ui.sends_default", json!({})).unwrap(), json!({"level": "-inf"}));
assert_eq!(app.run("ui.sends_default", json!({"level": "0"})).unwrap(), json!({"level": "0"}));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(app.run("ui.sends_default", json!({"level": "-6"})).is_err());
assert_eq!(app.ui.sends_default, SendsDefault::Unity, "a rejected level changes nothing");
assert_eq!(app.run("ui.sends_default", json!({"level": "-inf"})).unwrap(), json!({"level": "-inf"}));
assert_eq!(app.ui.sends_default, SendsDefault::NegativeInfinity, "switching back to −∞ dB works");
assert!(!app.engine.is_dirty(), "a preference is not a document edit");
}
/// A `level` that is present but not a string is an error, not a read-back: `{"level": 0}` must
/// not look like it set 0 dB while changing nothing.
#[test]
fn sends_default_rejects_a_non_string_level() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for bad in [json!(0), json!(null), json!(false), json!(["0"])] {
assert!(app.run("ui.sends_default", json!({"level": bad})).is_err(), "{bad} accepted");
assert_eq!(app.ui.sends_default, SendsDefault::NegativeInfinity, "{bad} changed the setting");
}
}
/// `ui.set` takes the same `-inf` and `0` as `ui.sends_default`, and a bad value changes nothing.
#[test]
fn ui_set_takes_the_same_sends_default_levels() {
use crate::preferences::SendsDefault;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let result = app.run("ui.set", json!({"sends_default": "0"})).unwrap();
assert_eq!((result["ui"]["sends_default"].clone(), app.ui.sends_default), (json!("0"), SendsDefault::Unity));
let result = app.run("ui.set", json!({"sends_default": "-inf"})).unwrap();
assert_eq!((result["ui"]["sends_default"].clone(), app.ui.sends_default), (json!("-inf"), SendsDefault::NegativeInfinity));
app.run("ui.set", json!({"sends_default": "0"})).unwrap();
for bad in [json!("unity"), json!("-6"), json!(0)] {
assert!(app.run("ui.set", json!({"sends_default": bad})).is_err(), "{bad} accepted");
assert_eq!(app.ui.sends_default, SendsDefault::Unity, "{bad} changed the setting");
}
}
fn recent_paths(count: usize) -> Vec<String> {
(0..count).map(|i| format!("{i}.scraft")).collect()
}
/// `ui.set` keeps the newest `MAX_RECENT` recent sessions, in order, and answers with that list.
#[test]
fn ui_set_keeps_at_most_ten_recent_sessions() {
use crate::dialogs::recent::MAX_RECENT;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for count in [MAX_RECENT + 1, 1000] {
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(count)})).unwrap();
assert_eq!(app.ui.recent_sessions, recent_paths(MAX_RECENT), "{count} entries: the first ten, in order");
assert_eq!(result["ui"]["recent_sessions"], json!(recent_paths(MAX_RECENT)), "{count} entries: the answer shows the kept list");
}
}
/// A list within the limit, an empty one included, is stored as given.
#[test]
fn ui_set_leaves_a_recent_list_within_the_limit_alone() {
use crate::dialogs::recent::MAX_RECENT;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for count in [MAX_RECENT, MAX_RECENT - 1, 1, 0] {
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(count)})).unwrap();
assert_eq!(app.ui.recent_sessions, recent_paths(count), "{count} entries");
assert_eq!(result["ui"]["recent_sessions"], json!(recent_paths(count)), "{count} entries");
}
}
/// Capping the list does not drop the other fields of the same call.
#[test]
fn ui_set_applies_other_fields_beside_a_capped_recent_list() {
use crate::dialogs::recent::MAX_RECENT;
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
let result = app.run("ui.set", json!({"recent_sessions": recent_paths(25), "undo_levels": 7})).unwrap();
assert_eq!((app.ui.recent_sessions.len(), app.ui.undo_levels, app.engine.history_limit), (MAX_RECENT, 7, 7));
assert_eq!(result["ui"]["undo_levels"], 7);
// A call that does not name the list leaves it as it was.
app.run("ui.set", json!({"undo_levels": 9})).unwrap();
assert_eq!(app.ui.recent_sessions, recent_paths(MAX_RECENT));
}
/// A list that is not an array of strings is refused, however long, and nothing changes.
#[test]
fn ui_set_refuses_a_recent_list_of_the_wrong_type() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.run("ui.set", json!({"recent_sessions": recent_paths(3), "undo_levels": 7})).unwrap();
let numbers: Vec<u32> = (0..25).collect();
for bad in [json!("a.scraft"), json!(5), json!(null), json!({"0": "a.scraft"}), json!(["a.scraft", 5]), json!(numbers)] {
let error = app.run("ui.set", json!({"recent_sessions": bad, "undo_levels": 20})).unwrap_err();
assert!(error.starts_with("bad ui state"), "{bad}: {error}");
assert_eq!((app.ui.recent_sessions.clone(), app.ui.undo_levels), (recent_paths(3), 7), "{bad} changed the state");
}
}
#[test]
fn mix_view_aliases_are_allocated_once() {
let first = ui_aliases();
+21 -3
View File
@@ -71,9 +71,8 @@ pub(crate) fn midi_input_menu(app: &mut SoundApp, ui: &mut Ui, id: TrackId) {
pub(crate) fn input_name(app: &SoundApp, track: &Track) -> String {
if track.kind.is_midi() {
midi_input_name(track)
} else if track.kind.has_playlist() && track.mixer.input == Route::None {
let channels = track.format.channels();
if channels == 1 { crate::localized_format!("In {}", 1) } else { crate::localized_format!("In 1-{}", channels) }
} else if track.mixer.input == Route::None {
crate::localization::text("no input").to_string()
} else {
route_name(app, &track.mixer.input)
}
@@ -180,3 +179,22 @@ mod midi_input_tests {
assert_eq!(shown(&app, audio), "In 1", "an audio track still shows its audio input");
}
}
#[cfg(test)]
mod no_input_tests {
use super::input_name;
use crate::{Services, SoundApp};
use serde_json::json;
/// An audio or aux track set to no input says so (it showed "In 1", or "no output" on an aux).
#[test]
fn no_input_reads_no_input_on_the_selector() {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.run("track.new", json!({"format": "mono"})).unwrap();
app.run("track.new", json!({"kind": "aux"})).unwrap();
app.run("track.input", json!({"tracks": [app.engine.session().tracks[0].id.0], "input": "none"})).unwrap();
for track in &app.engine.session().tracks {
assert_eq!(input_name(&app, track), "no input", "{}", track.name);
}
}
}
+45 -2
View File
@@ -464,8 +464,16 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
app.ui.send_window = Some((id, slot));
}
};
// A new send starts at the Sends Default to preference; re-targeting keeps the send's level.
let send_params = |app: &SoundApp, bus: &str| {
let mut p = json!({"track": id.0, "slot": slot, "bus": bus});
if !has_send {
p["level_db"] = json!(app.ui.sends_default.level_db());
}
p
};
if let Some(bus) = picked
&& app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": bus})).is_ok()
&& app.run("mix.send", send_params(app, &bus)).is_ok()
{
show_new_send(app);
}
@@ -479,7 +487,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
n += 1;
}
if app.run("mix.new_bus", json!({"name": format!("Bus {n}")})).is_ok()
&& app.run("mix.send", json!({"track": id.0, "slot": slot, "bus": format!("Bus {n}")})).is_ok()
&& app.run("mix.send", send_params(app, &format!("Bus {n}"))).is_ok()
{
show_new_send(app);
}
@@ -495,6 +503,7 @@ fn send_route_menu(app: &mut SoundApp, ui: &Ui, field: &egui::Response, id: Trac
mod tests {
use super::*;
use crate::Services;
use crate::preferences::SendsDefault;
use egui_kittest::{Harness, kittest::Queryable};
/// Filtering the destination list to nothing shrinks the menu; clearing the filter grows it
@@ -620,4 +629,38 @@ mod tests {
assert_eq!(target.as_deref(), Some("Aux"), "the send moved");
assert_eq!(app.ui.send_window, None, "no window opened");
}
/// Picks `item` from Kick's send A menu with the Sends Default to preference set to `default`,
/// and returns the send's level.
fn level_after_picking(existing_send: bool, default: SendsDefault, item: &str) -> Option<f32> {
let (mut h, kick) = kick_send_harness(existing_send);
h.state_mut().0.ui.sends_default = default;
if existing_send {
h.state_mut().0.run("mix.send_level", json!({"track": kick.0, "slot": 0, "db": -9.0})).unwrap();
}
h.run();
h.get_by_label("Send A for Kick").click();
h.run();
h.get_by_label(item).click();
h.run();
let (app, _) = h.state();
app.engine.session().track(kick).and_then(|t| t.mixer.sends.first().cloned().flatten()).map(|s| s.level_db)
}
/// A new send starts at the level set in Preferences › Mixing › Sends Default to (#1423).
#[test]
fn a_new_send_starts_at_the_sends_default_preference() {
let _palette = crate::theme::lock_test_palette();
assert_eq!(level_after_picking(false, SendsDefault::NegativeInfinity, "Aux"), Some(-144.0));
assert_eq!(level_after_picking(false, SendsDefault::Unity, "Aux"), Some(0.0));
assert_eq!(level_after_picking(false, SendsDefault::Unity, "new bus..."), Some(0.0));
}
/// Moving an existing send to another bus keeps its level, whatever the preference says.
#[test]
fn changing_a_sends_destination_keeps_its_level() {
let _palette = crate::theme::lock_test_palette();
assert_eq!(level_after_picking(true, SendsDefault::Unity, "Aux"), Some(-9.0));
assert_eq!(level_after_picking(true, SendsDefault::NegativeInfinity, "Aux"), Some(-9.0));
}
}
+97 -9
View File
@@ -447,6 +447,7 @@ pub fn recall_configuration(app: &mut SoundApp, saved: &Value) -> Result<(), Str
st.preferences_window_pos = app.ui.preferences_window_pos;
st.reduce_visual_effects = app.ui.reduce_visual_effects;
st.undo_levels = app.ui.undo_levels.clamp(1, 64);
st.sends_default = app.ui.sends_default;
st.show_configurations = true;
crate::docking::cancel_replaced_state(app, &st);
app.engine.set_history_limit(st.undo_levels);
@@ -592,14 +593,50 @@ fn midi_inputs(app: &mut SoundApp, ui: &mut egui::Ui) {
ui.data_mut(|d| d.insert_temp(debug_id, debug));
}
/// What the Playback Engine says when a change made elsewhere replaced its unapplied edits.
const REPLACED_EDITS: &str = "The audio settings were changed outside this window; your unapplied changes were replaced.";
/// Drop the replacement notice from the status line when it is still this notice, so a later edit
/// or closing the window does not leave it there. Leave any other status message alone.
fn clear_replaced_edits_status(app: &mut SoundApp) {
if app.ui.status == crate::localization::text(REPLACED_EDITS) {
app.ui.status.clear();
}
}
/// Setup › Playback Engine / Hardware: choose the audio system, devices, rate and buffer size.
pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
let mut open = app.ui.show_playback_engine;
// The window's unapplied edits, with the choice they started from. A choice changed elsewhere
// (`ui.audio_device`, `setup.playback_engine`) replaces them, so the window never shows, or
// applies, an earlier choice. A reconnect reopens the same choice and leaves them alone.
let draft_id = egui::Id::unique("audio_draft");
// Set while the window shows a choice made elsewhere that replaced its unapplied edits.
let replaced_id = egui::Id::unique("audio_draft_replaced");
if !open {
// Closed from the menu or by command: unapplied edits go, as with the close button.
clear_replaced_edits_status(app);
ctx.data_mut(|d| {
d.remove_temp::<(AudioConfig, AudioConfig)>(draft_id);
d.remove_temp::<bool>(replaced_id);
});
return;
}
let draft_id = egui::Id::unique("audio_draft");
let mut draft = ctx.data(|d| d.get_temp::<AudioConfig>(draft_id)).unwrap_or_else(|| app.ui.audio.clone());
// Pro Tools' Playback Engine is modal, so nothing else changes the device under its edits
// (Reference Guide p. 109). This window is not: a change made elsewhere wins, and when it
// replaces unapplied edits the window and the status line say so.
let mut draft = match ctx.data(|d| d.get_temp::<(AudioConfig, AudioConfig)>(draft_id)) {
Some((from, draft)) if from == app.ui.audio => draft,
Some((from, draft)) => {
if draft != from && draft != app.ui.audio {
let note = crate::localization::text(REPLACED_EDITS);
app.ui.status = note.to_string();
ctx.data_mut(|d| d.insert_temp(replaced_id, true));
}
app.ui.audio.clone()
}
None => app.ui.audio.clone(),
};
let mut refresh = false;
let mut apply = false;
let systems = audio_systems(ctx, false);
@@ -658,6 +695,13 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
draft = app.ui.audio.clone();
}
});
if draft != app.ui.audio {
// A new edit: the replaced ones are no longer the news.
ui.ctx().data_mut(|d| d.remove_temp::<bool>(replaced_id));
clear_replaced_edits_status(app);
} else if ui.ctx().data(|d| d.get_temp::<bool>(replaced_id)).unwrap_or(false) {
ui.label(egui::RichText::new(crate::localization::text(REPLACED_EDITS)).color(ui.visuals().warn_fg_color));
}
ui.separator();
egui::Grid::new("pe-state").num_columns(2).show(ui, |ui| {
ui.label(crate::localization::text("Output"));
@@ -672,6 +716,11 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
}
}));
ui.end_row();
if let Some(note) = buffer_note(app) {
ui.label("");
ui.label(egui::RichText::new(buffer_note_text(note)).color(ui.visuals().warn_fg_color));
ui.end_row();
}
ui.label(crate::localization::text("Input"));
ui.label(app.recorder.as_ref().map_or(crate::localization::text("opened on first record or monitor").to_string(), |r| {
crate::localized_format!("{} · {} Hz · {} ch", r.device_name, r.sample_rate, r.channels)
@@ -709,11 +758,13 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
app.ui.status = e;
}
if open {
ctx.data_mut(|d| d.insert_temp(draft_id, draft));
ctx.data_mut(|d| d.insert_temp(draft_id, (app.ui.audio.clone(), draft)));
} else {
// Closing discards unapplied edits and the device list (re-read on the next open).
clear_replaced_edits_status(app);
ctx.data_mut(|d| {
d.remove_temp::<AudioConfig>(draft_id);
d.remove_temp::<(AudioConfig, AudioConfig)>(draft_id);
d.remove_temp::<bool>(replaced_id);
d.remove_temp::<Arc<Vec<AudioSystem>>>(egui::Id::unique("audio_systems"));
});
}
@@ -722,7 +773,9 @@ pub fn playback_engine(app: &mut SoundApp, ctx: &egui::Context) {
/// `ui.audio_device`: `{list?: bool}` returns the audio systems and their devices;
/// `{system?, output?, input?, sample_rate?, buffer_size?}` (a `null` value means "default") sets
/// the choice and reopens the devices. Always returns the choice and the open device.
/// the choice and reopens the devices. Always returns the choice, the open device (with the
/// driver's `buffer_range`, null when it reports none, and `buffer_running`, the size the stream
/// reports it runs at) and a `buffer_note` when the device does not run at the chosen buffer size.
pub fn audio_device_command(app: &mut SoundApp, p: &serde_json::Value) -> Result<serde_json::Value, String> {
use serde_json::Value;
let mut changed = false;
@@ -746,21 +799,55 @@ pub fn audio_device_command(app: &mut SoundApp, p: &serde_json::Value) -> Result
app.apply_audio_config(cfg)?;
}
let device = app.player.as_ref().map(|pl| {
json!({"name": pl.device_name, "sample_rate": pl.device_rate, "channels": pl.device_channels, "buffer_size": pl.device_buffer, "silent": pl.silent})
let range = pl.device_buffer_range.map(|(min, max)| json!({"min": min, "max": max}));
json!({"name": pl.device_name, "sample_rate": pl.device_rate, "channels": pl.device_channels, "buffer_size": pl.device_buffer, "buffer_range": range, "buffer_running": pl.device_buffer_running, "silent": pl.silent})
});
let mut out = json!({"config": app.ui.audio, "device": device});
let mut out = json!({"config": app.ui.audio, "device": device, "buffer_note": buffer_note(app).map(|n| n.english())});
if p.get("list").and_then(Value::as_bool).unwrap_or(false) {
out["systems"] = json!(soundcraft_playback::devices::audio_systems());
}
Ok(out)
}
/// Why the open output does not run at the chosen buffer, when it does not (#1757).
fn buffer_note(app: &SoundApp) -> Option<soundcraft_playback::devices::BufferNote> {
let player = app.player.as_ref().filter(|p| !p.silent)?;
soundcraft_playback::devices::buffer_note(
app.ui.audio.buffer_size,
player.device_buffer,
player.device_buffer_range,
player.device_buffer_running,
)
}
/// The window's wording of a [`soundcraft_playback::devices::BufferNote`].
fn buffer_note_text(note: soundcraft_playback::devices::BufferNote) -> String {
use soundcraft_playback::devices::BufferNote;
match note {
BufferNote::OutsideRange { min, max, .. } if min == max => crate::localized_format!("The device runs only at {} samples.", min),
BufferNote::OutsideRange { min, max, running: Some(n) } => {
crate::localized_format!("The device allows {}–{} samples; it runs at its default buffer, {} samples.", min, max, n)
}
BufferNote::OutsideRange { min, max, running: None } => {
crate::localized_format!("The device allows {}–{} samples; it runs at its default buffer.", min, max)
}
BufferNote::Refused { want, running: Some(n) } => {
crate::localized_format!("The device did not take {} samples; it runs at its default buffer, {} samples.", want, n)
}
BufferNote::Refused { want, running: None } => {
crate::localized_format!("The device did not take {} samples; it runs at its default buffer.", want)
}
BufferNote::Rounded { want, running } => crate::localized_format!("The device runs at {} samples, not {}.", running, want),
}
}
/// Programmatic `setup.playback_engine` / `setup.hardware`. `device` is the output name and
/// `buffer_size` is any integer 16..=8192 or null (not rounded to the window's power-of-two list);
/// both go through [`audio_device_command`]. Delay compensation still goes through the engine
/// command, and only after the device change has been accepted. The result is the open device:
/// its name, the buffer actually in use (`device_buffer`, null for the device default), its sample
/// rate, and delay compensation. `applied` is true only when an audio device is open.
/// its name, the buffer actually in use (`buffer_size`, null for the device default), a
/// `buffer_note` when that is not the chosen size, its sample rate, and delay compensation.
/// `applied` is true only when an audio device is open.
pub fn setup_audio_command(app: &mut SoundApp, id: &str, p: &serde_json::Value) -> Result<serde_json::Value, String> {
use serde_json::Value;
let mut audio = serde_json::Map::new();
@@ -796,6 +883,7 @@ pub fn setup_audio_command(app: &mut SoundApp, id: &str, p: &serde_json::Value)
"applied": applied,
"device": device,
"buffer_size": buffer_size,
"buffer_note": buffer_note(app).map(|n| n.english()),
"sample_rate": sample_rate,
"bit_depth": app.engine.session().bit_depth,
"delay_compensation": app.engine.session().edit.delay_compensation,
+109 -1
View File
@@ -71,6 +71,54 @@ impl ReduceVisualEffects {
}
}
/// The level a send made in the Mix window starts at (Mixing › Sends Default to).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SendsDefault {
// Stored and set (`ui.set`) with the same ids as `ui.sends_default` takes.
#[default]
#[serde(rename = "-inf")]
NegativeInfinity,
#[serde(rename = "0")]
Unity,
}
impl SendsDefault {
pub const ALL: [Self; 2] = [Self::NegativeInfinity, Self::Unity];
/// Returns the text shown for this level in the preference selector.
pub const fn label(self) -> &'static str {
match self {
Self::NegativeInfinity => "−∞ dB",
Self::Unity => "0 dB",
}
}
/// Returns the stable command and persistence identifier for this level.
pub const fn id(self) -> &'static str {
match self {
Self::NegativeInfinity => "-inf",
Self::Unity => "0",
}
}
/// Parses a command or persistence identifier into a default send level.
pub fn parse(id: &str) -> Option<Self> {
match id {
"-inf" => Some(Self::NegativeInfinity),
"0" => Some(Self::Unity),
_ => None,
}
}
/// The send level in dB; −∞ is the mixer's -144 dB floor.
pub const fn level_db(self) -> f32 {
match self {
Self::NegativeInfinity => -144.0,
Self::Unity => 0.0,
}
}
}
impl PreferencesPage {
pub const ALL: [Self; 9] = [
Self::Display,
@@ -121,9 +169,11 @@ struct PreferencesDraft {
theme: ThemeMode,
reduce_visual_effects: ReduceVisualEffects,
undo_levels: usize,
sends_default: SendsDefault,
theme_edited: bool,
reduce_visual_effects_edited: bool,
undo_levels_edited: bool,
sends_default_edited: bool,
}
impl PreferencesDraft {
@@ -133,9 +183,11 @@ impl PreferencesDraft {
theme: app.ui.theme,
reduce_visual_effects: app.ui.reduce_visual_effects,
undo_levels: app.ui.undo_levels,
sends_default: app.ui.sends_default,
theme_edited: false,
reduce_visual_effects_edited: false,
undo_levels_edited: false,
sends_default_edited: false,
}
}
@@ -150,6 +202,9 @@ impl PreferencesDraft {
if !self.undo_levels_edited {
self.undo_levels = app.ui.undo_levels;
}
if !self.sends_default_edited {
self.sends_default = app.ui.sends_default;
}
}
/// Remembers which values the user changed during the current UI frame.
@@ -157,6 +212,7 @@ impl PreferencesDraft {
self.theme_edited |= self.theme != before.theme;
self.reduce_visual_effects_edited |= self.reduce_visual_effects != before.reduce_visual_effects;
self.undo_levels_edited |= self.undo_levels != before.undo_levels;
self.sends_default_edited |= self.sends_default != before.sends_default;
}
}
@@ -189,6 +245,7 @@ enum Control {
Theme,
ReduceVisualEffects,
UndoLevels,
SendsDefault,
}
impl Control {
@@ -204,6 +261,7 @@ impl Control {
Self::Theme => "UI Theme",
Self::ReduceVisualEffects => "Reduce Visual Effects",
Self::UndoLevels => "Levels of Undo",
Self::SendsDefault => "Sends Default to",
}
}
@@ -220,6 +278,10 @@ impl Control {
let modes = ReduceVisualEffects::ALL.map(|mode| both(mode.label())).join(" ");
format!("{} {modes}", both(self.label()))
}
Self::SendsDefault => {
let levels = SendsDefault::ALL.map(|level| both(level.label())).join(" ");
format!("{} {levels}", both(self.label()))
}
_ => both(self.label()),
}
}
@@ -432,7 +494,7 @@ const MIXING: &[Section] = &[
Section {
title: "Setup",
controls: &[
Control::Value("Sends Default to", "−∞ dB"),
Control::SendsDefault,
Control::Check("Send Pans Default to Follow Main Pan"),
Control::Check("Use Absolute Pan Linking"),
Control::Check("Allow Sends to Persist During Low-Latency Monitoring"),
@@ -814,6 +876,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
let _ = app.run("ui.theme", json!({"mode": draft.theme.id()}));
let _ = app.run("ui.reduce_visual_effects", json!({"mode": draft.reduce_visual_effects.id()}));
let _ = app.run("ui.undo_levels", json!({"levels": draft.undo_levels}));
let _ = app.run("ui.sends_default", json!({"level": draft.sends_default.id()}));
open = false;
app.preferences.discard_draft();
}
@@ -962,6 +1025,16 @@ fn control_ui(ui: &mut egui::Ui, page: PreferencesPage, section: &str, index: us
ui.add(egui::DragValue::new(&mut draft.undo_levels).range(1..=64));
});
}
Control::SendsDefault => {
egui::ComboBox::new(id, label("Sends Default to")).selected_text(crate::localization::text(draft.sends_default.label())).show_ui(
ui,
|ui| {
for level in SendsDefault::ALL {
ui.selectable_value(&mut draft.sends_default, level, crate::localization::text(level.label()));
}
},
);
}
Control::Check(text) => {
let mut value = false;
ui.add_enabled(false, egui::Checkbox::new(&mut value, label(text)))
@@ -1103,6 +1176,16 @@ mod tests {
assert!(!text_matches(&control.search_text(), "mixagem"));
}
#[test]
fn sends_default_is_found_by_its_label_and_levels_in_both_languages() {
let _scope = crate::localization::enter(crate::localization::Language::PortugueseBrazil);
let text = Control::SendsDefault.search_text();
assert!(text_matches(&text, "sends default"), "English label");
assert!(text_matches(&text, crate::localization::Language::PortugueseBrazil.text("Sends Default to")), "pt-BR label");
assert!(text_matches(&text, "0 dB"), "a level");
assert!(!text_matches(&text, "mixagem"));
}
/// Creates a complete application harness with Preferences already open.
fn preferences_harness(size: egui::Vec2) -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(Engine::default(), None, crate::Services::default());
@@ -1134,9 +1217,11 @@ mod tests {
assert!(app.run("ui.theme", json!({"mode": ThemeMode::Light.id()})).is_ok());
assert!(app.run("ui.reduce_visual_effects", json!({"mode": "playback"})).is_ok());
assert!(app.run("ui.undo_levels", json!({"levels": 32})).is_ok());
assert!(app.run("ui.sends_default", json!({"level": "0"})).is_ok());
assert_eq!(app.ui.theme, ThemeMode::Light);
assert_eq!(app.ui.reduce_visual_effects, ReduceVisualEffects::Playback);
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (32, 32));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(!app.engine.is_dirty());
}
@@ -1150,6 +1235,7 @@ mod tests {
assert!(app.run("ui.theme", json!({"mode": ThemeMode::Light.id()})).is_ok());
assert!(app.run("ui.reduce_visual_effects", json!({"mode": "always"})).is_ok());
assert!(app.run("ui.undo_levels", json!({"levels": 17})).is_ok());
assert!(app.run("ui.sends_default", json!({"level": "0"})).is_ok());
}
harness.run_steps(2);
harness.get_by_label("OK").click();
@@ -1159,6 +1245,7 @@ mod tests {
assert_eq!(app.ui.theme, ThemeMode::Light);
assert_eq!(app.ui.reduce_visual_effects, ReduceVisualEffects::Always);
assert_eq!((app.ui.undo_levels, app.engine.history_limit), (17, 17));
assert_eq!(app.ui.sends_default, SendsDefault::Unity);
assert!(!app.ui.show_preferences);
}
@@ -1174,11 +1261,13 @@ mod tests {
app.ui.theme = ThemeMode::System;
app.ui.reduce_visual_effects = ReduceVisualEffects::Always;
app.ui.undo_levels = 17;
app.ui.sends_default = SendsDefault::Unity;
draft.sync_unedited_from_live(&app);
assert_eq!(draft.theme, ThemeMode::Light);
assert_eq!(draft.reduce_visual_effects, ReduceVisualEffects::Always);
assert_eq!(draft.undo_levels, 17);
assert_eq!(draft.sends_default, SendsDefault::Unity);
}
/// Command inputs reject unknown modes and bound undo depth safely.
@@ -1361,6 +1450,25 @@ mod tests {
assert_eq!(harness.state().ui.theme, ThemeMode::Dark);
}
/// Choosing 0 dB for Sends Default to applies on OK and is discarded on Cancel (#1423).
#[test]
fn sends_default_choice_applies_on_ok_and_not_on_cancel() {
for (button, expected) in [("OK", SendsDefault::Unity), ("Cancel", SendsDefault::NegativeInfinity)] {
let mut harness = preferences_harness(egui::vec2(1280.0, 1000.0));
harness.state_mut().ui.preferences_page = PreferencesPage::Mixing;
harness.run_steps(4);
harness.get_by_value("−∞ dB").click();
harness.run_steps(2);
harness.get_by_label("0 dB").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.sends_default, SendsDefault::NegativeInfinity, "staged until {button}");
harness.get_by_label(button).click();
harness.run_steps(2);
assert_eq!(harness.state().ui.sends_default, expected, "after {button}");
assert!(!harness.state().ui.show_preferences);
}
}
/// Escape closes an open choice popup before it can cancel the complete window.
#[test]
fn escape_closes_a_choice_popup_before_preferences() {
+63 -12
View File
@@ -83,19 +83,21 @@ pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
// an event's `repeat` flag from the physical key state, which says nothing about whether that
// particular event was injected.
let scripted = app.scripted_key_press_indices();
let events: Vec<(Key, Modifiers, bool)> = ctx.input(|i| {
let events: Vec<(Key, Option<Key>, Modifiers, bool)> = ctx.input(|i| {
i.events
.iter()
.enumerate()
.filter_map(|(index, e)| match e {
egui::Event::Key { key, pressed: true, repeat, modifiers, .. } => Some((*key, *modifiers, *repeat && !scripted.contains(&index))),
egui::Event::Key { key, physical_key, pressed: true, repeat, modifiers } => {
Some((*key, *physical_key, *modifiers, *repeat && !scripted.contains(&index)))
}
_ => None,
})
.collect()
});
// Cmd and Ctrl are separate keys only on macOS (asked at runtime so the web build in a Mac browser agrees).
let mac = ctx.os() == egui::os::OperatingSystem::Mac;
for (key, mods, repeat) in events {
for (key, physical, mods, repeat) in events {
if repeat {
if let Some((id, params)) = repeating_command(key, mods, mac) {
let _ = app.run(id, params);
@@ -105,19 +107,57 @@ pub fn handle(app: &mut SoundApp, ctx: &egui::Context) {
if fixed(app, key, mods, mac) {
continue;
}
if let Some(id) = command_for(key, mods, mac) {
if crate::menus::invoke_shortcut_dialog(app, id) {
continue;
}
let _ = app.run(id, json!({}));
} else if let Some(c) =
crate::menus::UI_COMMANDS.iter().find(|c| c.3.and_then(parse).is_some_and(|(m, k)| k == key && mods_match(m, mods, mac)))
if !registered(app, key, mods, mac)
&& let Some(base) = shifted_symbol_base(key, physical, mods)
{
let _ = app.run(c.0, json!({}));
registered(app, base, mods, mac);
}
}
}
/// Run the registry or UI command whose shortcut is this chord. Returns whether one matched.
fn registered(app: &mut SoundApp, key: Key, mods: Modifiers, mac: bool) -> bool {
if let Some(id) = command_for(key, mods, mac) {
if !crate::menus::invoke_shortcut_dialog(app, id) {
let _ = app.run(id, json!({}));
}
true
} else if let Some(c) = crate::menus::UI_COMMANDS.iter().find(|c| c.3.and_then(parse).is_some_and(|(m, k)| k == key && mods_match(m, mods, mac)))
{
let _ = app.run(c.0, json!({}));
true
} else {
false
}
}
/// The key a shortcut names for a Shift chord the layout reports by its shifted character. With
/// Shift held the platform reports the `/` key as `?` (and `\` as `|`, `[` as `{`, ...), so
/// "Shift+/" never matched a real press, only a scripted one built from the shortcut string. The key's
/// position (`physical_key`, named after the US layout) gives the key back. Only punctuation: a letter
/// or digit position must not stand in for a symbol another layout types there.
fn shifted_symbol_base(key: Key, physical: Option<Key>, mods: Modifiers) -> Option<Key> {
let shifted = matches!(key, Key::Questionmark | Key::Pipe | Key::OpenCurlyBracket | Key::CloseCurlyBracket | Key::Colon | Key::Plus);
physical.filter(|p| {
mods.shift
&& shifted
&& matches!(
p,
Key::Slash
| Key::Backslash
| Key::OpenBracket
| Key::CloseBracket
| Key::Semicolon
| Key::Equals
| Key::Comma
| Key::Period
| Key::Quote
| Key::Minus
| Key::Backtick
)
})
}
/// The command a host auto-repeat of this chord runs, if it is one of [`REPEATING`]. A repeat
/// resolves its chord the way a press falls through to these zooms ([`zoom_key`], then the
/// registry) without the earlier [`fixed`] / [`fixed_more`] arms, so an arm added there for one of
@@ -166,7 +206,7 @@ fn fixed(app: &mut SoundApp, key: Key, m: Modifiers, mac: bool) -> bool {
// No MIDI target can consume the notes any more: drop the stale selection.
app.midi.selected.clear();
}
if app.ui.show_midi_editor && !app.midi.selected.is_empty() {
if midi_editor_drawn(app) && !app.midi.selected.is_empty() {
return false;
}
let _ = app.run("edit.clear", json!({}));
@@ -471,6 +511,17 @@ fn centre_on_selection(app: &mut SoundApp, end: bool) -> bool {
true
}
/// Whether the MIDI editor's body was drawn on the last frame, and is still in front: docking
/// records its rect only when it draws the body (shortcuts run before the panels draw), and a
/// layout change since, such as a tab moved over it, has not redrawn the dock yet. Open behind
/// another tab, its notes aren't on screen and its keys aren't read, so Delete is the Edit
/// window's Clear there (#1627).
fn midi_editor_drawn(app: &SoundApp) -> bool {
app.ui.show_midi_editor
&& app.ui.docking.layout().panel_state(&crate::docking::Panel::Midi) == craft_behavior::dock::PanelState::Front
&& app.docking_context.as_ref().is_some_and(|c| c.data(|d| d.get_temp::<egui::Rect>(egui::Id::unique("soundcraft-midi-body"))).is_some())
}
/// Whether the pointer is over the MIDI editor, whose piano roll moves the selected notes with the arrow keys.
fn piano_roll_has_pointer(app: &SoundApp) -> bool {
app.ui.show_midi_editor
+1
View File
@@ -459,6 +459,7 @@ fn preferences_saved_before_the_window_was_remembered_keep_full_scale() {
assert_eq!((ui.window_size, ui.window_maximized, ui.ui_scale), ([1600.0, 1000.0], false, 1.0));
assert_eq!(ui.reduce_visual_effects, crate::preferences::ReduceVisualEffects::Never);
assert_eq!(ui.undo_levels, 64);
assert_eq!(ui.sends_default, crate::preferences::SendsDefault::NegativeInfinity);
}
#[test]
+109
View File
@@ -1,4 +1,6 @@
//! `ui.audio_device`: the audio device choice is kept only once the devices reopen with it.
use egui::vec2;
use egui_kittest::{Harness, kittest::Queryable};
use serde_json::json;
use soundcraft_ui_egui::{Services, SoundApp};
@@ -30,6 +32,16 @@ fn new_app() -> SoundApp {
SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default())
}
#[test]
fn the_reply_says_when_the_device_does_not_run_at_the_chosen_buffer() {
// Nothing open: there is no device buffer to explain, so the note is null, never a guess (#1757).
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
for command in ["ui.audio_device", "setup.playback_engine"] {
let r = app.run(command, json!({})).unwrap();
assert!(r.get("buffer_note").is_some_and(serde_json::Value::is_null), "{command}: {r}");
}
}
#[test]
fn playback_engine_refuses_an_invalid_or_untimely_device_choice_without_side_effects() {
let mut app = new_app();
@@ -101,3 +113,100 @@ fn playback_engine_applies_the_same_device_choice_as_the_audio_command() {
assert!(app.ui.show_playback_engine, "the menu still opens the Playback Engine window");
assert_eq!(app.ui.audio, cfg, "opening the window does not change the device");
}
/// The Playback Engine window, rendered, with the app's audio choice set to `buffer` samples.
fn playback_engine_harness(buffer: u32) -> Harness<'static, SoundApp> {
let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default());
app.ui.audio.buffer_size = Some(buffer);
app.ui.show_playback_engine = true;
let mut h =
Harness::builder().with_context_setup(soundcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut SoundApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
/// Whether the Buffer size selector shows `text`.
fn shows(h: &Harness<'_, SoundApp>, text: &str) -> bool {
h.query_all_by_label("Buffer size").any(|n| n.value().is_some_and(|v| v == text))
}
/// A command (or another window) changes the audio choice while the Playback Engine is closed or
/// open: the window then shows the current choice, and Apply has nothing to apply, so it never
/// puts an earlier choice back.
#[test]
fn the_playback_engine_shows_the_current_choice_after_a_command_changes_it() {
let mut h = playback_engine_harness(256);
assert!(shows(&h, "256 samples"), "the window opens on the current choice");
// Closed from the menu (not its close button), then the choice changes by command.
h.state_mut().ui.show_playback_engine = false;
h.run_steps(2);
h.state_mut().ui.audio.buffer_size = Some(512);
h.state_mut().ui.show_playback_engine = true;
h.run_steps(3);
assert!(shows(&h, "512 samples"), "reopened on the choice the command made");
assert!(!shows(&h, "256 samples"), "not on the earlier one");
// Changed while the window is open.
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(shows(&h, "1024 samples"), "an open window follows a change made elsewhere");
assert!(h.query_by_label("Revert").is_none(), "nothing to revert: no edit differs from the current choice");
}
/// Make an unapplied edit in the window: its buffer size set to `buffer`, as if chosen in its
/// Buffer size selector (the window keeps its edits with the choice they started from).
fn edit_buffer(h: &mut Harness<'_, SoundApp>, buffer: u32) {
let from = h.state().ui.audio.clone();
let draft = soundcraft_playback::AudioConfig { buffer_size: Some(buffer), ..from.clone() };
h.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("audio_draft"), (from, draft)));
h.run_steps(2);
}
/// Pro Tools' Playback Engine is a modal dialog, so nothing else changes the device while it has
/// unapplied edits (Reference Guide p. 109). This window is not modal: when a command changes the
/// choice under unapplied edits, the window takes the new choice and says the edits were replaced.
#[test]
fn the_playback_engine_says_when_a_command_replaces_its_unapplied_edits() {
const NOTE: &str = "The audio settings were changed outside this window; your unapplied changes were replaced.";
let mut h = playback_engine_harness(256);
edit_buffer(&mut h, 128);
h.run_steps(2);
assert!(shows(&h, "128 samples"), "the edit is in the window");
assert!(h.query_by_label("Revert").is_some(), "an unapplied edit");
// A command changes the buffer to 1024 while the edit is unapplied.
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(shows(&h, "1024 samples"), "the window takes the current choice");
assert!(h.query_by_label(NOTE).is_some(), "and says the unapplied edit was replaced");
assert!(h.state().ui.status.contains(NOTE), "the status line says it too: {}", h.state().ui.status);
// The next edit takes the note away.
edit_buffer(&mut h, 512);
h.run_steps(2);
assert!(h.query_by_label(NOTE).is_none(), "a new edit: the note goes");
assert!(!h.state().ui.status.contains(NOTE), "and the status line too: {}", h.state().ui.status);
// Closing also clears the status line.
let mut h = playback_engine_harness(256);
edit_buffer(&mut h, 128);
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(h.state().ui.status.contains(NOTE), "the status line says it: {}", h.state().ui.status);
h.state_mut().ui.show_playback_engine = false;
h.run_steps(2);
assert!(!h.state().ui.status.contains(NOTE), "closing clears the status line: {}", h.state().ui.status);
// A change made elsewhere with no unapplied edit replaces nothing, so nothing is said.
let mut h = playback_engine_harness(256);
h.state_mut().ui.audio.buffer_size = Some(1024);
h.run_steps(3);
assert!(h.query_by_label(NOTE).is_none(), "no edit was replaced");
}
+17 -2
View File
@@ -23,6 +23,21 @@ fn harness() -> Harness<'static, SoundApp> {
h
}
/// How many frames a bounce may take before a test calls it stuck. A frame renders for a slice of
/// wall-clock time, so a slow CPU needs many more frames than the harness's `max_steps`.
const MAX_FRAMES: usize = 100_000;
/// Steps frames until the bounce ends, then lets the app settle.
fn finish_bounce(h: &mut Harness<'_, SoundApp>) {
let mut frames = 0;
while h.state().bounce.is_some() {
h.step();
frames += 1;
assert!(frames < MAX_FRAMES, "the bounce did not finish within {MAX_FRAMES} frames");
}
h.run();
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("soundcraft-ui-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -77,7 +92,7 @@ fn a_bounce_renders_across_frames_with_progress_until_its_file_is_written() {
h.step();
}
assert!(progress.is_sorted() && progress[0] < progress[3] && progress[3] < 1.0, "{progress:?}");
h.run();
finish_bounce(&mut h);
assert!(h.state().bounce.is_none());
assert!(h.state().ui.status.starts_with("Bounced Mix.wav (peak"), "{}", h.state().ui.status);
let (_, file) = craft_audio::decode(&std::fs::read(dir.join("Mix.wav")).unwrap(), None).unwrap();
@@ -97,7 +112,7 @@ fn a_bounce_keeps_going_while_the_window_is_hidden() {
let _ = ctx.run_logic(&egui::RawInput::default(), |ctx| h.state_mut().logic(ctx));
assert!(h.state().bounce.is_none() || ctx.has_requested_repaint());
calls += 1;
assert!(calls < 10_000);
assert!(calls < MAX_FRAMES);
}
assert!(calls > 3, "{calls}");
assert!(h.state().ui.status.starts_with("Bounced Hidden.wav"), "{}", h.state().ui.status);
+54
View File
@@ -317,3 +317,57 @@ fn cmd_6_and_7_choose_the_pencil_and_the_smart_tool() {
assert_eq!(app.engine.session().edit.tool.id(), "smart", "{os:?}");
}
}
/// What egui-winit sends for a real press of the `key` key with Shift and Cmd (Ctrl off macOS) held: the
/// modifier keys first, each with its own `ModifiersChanged`, then the key by the name the layout gives
/// it, with its US-layout position as `physical_key`, and no `Text` while Cmd or Ctrl is down.
fn host_chord(os: OperatingSystem, cmd: Modifiers, logical: Key, physical: Key) -> Vec<Event> {
let command_key = if os == OperatingSystem::Mac { Key::SuperLeft } else { Key::ControlLeft };
let shift_held = Modifiers { shift: true, ..cmd };
let key = |key, physical_key, pressed, modifiers| Event::Key { key, physical_key, pressed, repeat: false, modifiers };
vec![
key(command_key, Some(command_key), true, Modifiers::NONE),
Event::ModifiersChanged(cmd),
key(Key::ShiftLeft, Some(Key::ShiftLeft), true, cmd),
Event::ModifiersChanged(shift_held),
key(logical, Some(physical), true, shift_held),
key(logical, Some(physical), false, shift_held),
]
}
fn host_pass(ctx: &egui::Context, app: &mut SoundApp, events: Vec<Event>) {
ctx.run_ui(RawInput { events, ..Default::default() }, |ui| shortcuts::handle(app, ui.ctx())).textures_delta.clear();
}
/// Cmd+Shift+. is All MIDI Notes Off (Pro Tools p.1061), also under Commands Keyboard Focus, where a
/// bare `.` nudges. macOS reports the key from the layout's Cmd table as `.`; Windows and Linux report
/// `>`, which egui has no key for, so the key arrives by its position.
#[test]
fn a_host_cmd_shift_period_turns_all_notes_off_and_does_not_nudge() {
for (os, cmd) in OSES {
let (ctx, mut app) = rig(os);
app.run("options.keyboard_focus", json!({"focus": "commands"})).unwrap();
app.run("edit.select", json!({"tracks": ["Kick"], "start": 48_000, "end": 96_000})).unwrap();
app.engine.transport_requests.clear();
host_pass(&ctx, &mut app, host_chord(os, cmd, Key::Period, Key::Period));
assert_eq!(app.engine.transport_requests, [TransportRequest::AllNotesOff], "{os:?}");
assert_eq!(start(&app), 48_000, "{os:?}: the chord nudged the selection");
}
}
/// Shift+/ is Link Timeline and Edit Selection. Every platform reports that press as `?`.
#[test]
fn a_host_shift_slash_toggles_link_timeline_and_edit_selection() {
for (os, _) in OSES {
let (ctx, mut app) = rig(os);
let linked = app.engine.session().edit.link_timeline_edit;
let shift = Modifiers::SHIFT;
let key = |key, physical_key, pressed| Event::Key { key, physical_key, pressed, repeat: false, modifiers: shift };
host_pass(
&ctx,
&mut app,
vec![Event::ModifiersChanged(shift), key(Key::Questionmark, Some(Key::Slash), true), key(Key::Questionmark, Some(Key::Slash), false)],
);
assert_ne!(app.engine.session().edit.link_timeline_edit, linked, "{os:?}");
}
}
+108
View File
@@ -225,3 +225,111 @@ fn a_midi_editor_behind_another_tab_leaves_the_arrows_to_the_edit_window() {
let (x, middle) = x_and_middle(&app, clip.start);
assert!((x - middle).abs() < 1.0, "Left: the clip start at {x}, the middle at {middle}");
}
/// #1627: the MIDI editor open behind another tab isn't drawn, so its key handler doesn't run and
/// its notes aren't on screen. Delete there clears the Edit selection, as it does elsewhere in the
/// Edit window, instead of doing nothing; in front, the editor still takes the key for its notes.
#[test]
fn delete_with_the_midi_editor_behind_another_tab_clears_the_edit_selection() {
let clips = |app: &SoundApp| app.engine.session().track_by_name("Keys").and_then(|t| t.playlist()).map_or(0, |p| p.clips.len());
let clip_ids = |app: &SoundApp| -> Vec<_> {
app.engine.session().track_by_name("Keys").and_then(|t| t.playlist()).map(|p| p.clips.iter().map(|c| c.id).collect()).unwrap_or_default()
};
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.ui.show_midi_editor = true;
let end: i64 = 48_000 * 600;
app.run("edit.select", json!({"tracks": ["Keys"], "start": 0, "end": end})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
app_frame(&ctx, &mut app, vec![]);
}
app.run("ui.dock", json!({"operation": "open", "panel": "history"})).unwrap();
app.run("ui.dock", json!({"operation": "move", "panel": "history", "target": "midi", "zone": "tab"})).unwrap();
for _ in 0..3 {
app_frame(&ctx, &mut app, vec![]);
}
assert!(app.ui.show_midi_editor, "the MIDI editor is still open");
assert_ne!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
let before = clip_ids(&app);
assert!(!before.is_empty());
app.midi.selected = vec![0, 1];
app_frame(&ctx, &mut app, arrow(Key::Delete));
assert_eq!(clips(&app), 0, "Delete cleared the Edit selection");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(clip_ids(&app), before, "one Undo brings every clip back");
}
/// #1627: a layout change between frames that puts another tab over the MIDI Editor counts at
/// once. The editor's body rect from the frame before is stale, and Delete clears the Edit
/// selection on the very next key, not after the dock redraws.
#[test]
fn delete_right_after_a_tab_covers_the_midi_editor_clears_the_edit_selection() {
let clips = |app: &SoundApp| app.engine.session().track_by_name("Keys").and_then(|t| t.playlist()).map_or(0, |p| p.clips.len());
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.ui.show_midi_editor = true;
let end: i64 = 48_000 * 600;
app.run("edit.select", json!({"tracks": ["Keys"], "start": 0, "end": end})).unwrap();
let ctx = egui::Context::default();
soundcraft_ui_egui::framework::install_headless(&ctx);
for _ in 0..6 {
app_frame(&ctx, &mut app, vec![]);
}
assert_eq!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
app.run("ui.dock", json!({"operation": "open", "panel": "history"})).unwrap();
app.run("ui.dock", json!({"operation": "move", "panel": "history", "target": "midi", "zone": "tab"})).unwrap();
assert_ne!(app.ui.docking.layout().panel_state(&soundcraft_ui_egui::docking::Panel::Midi), craft_behavior::dock::PanelState::Front);
assert!(clips(&app) > 0);
app.midi.selected = vec![0, 1];
app_frame(&ctx, &mut app, arrow(Key::Delete));
assert_eq!(clips(&app), 0, "Delete cleared the Edit selection");
}
#[test]
fn pro_tools_shift_keys_bypass_inserts_and_mute_sends() {
for os in [OperatingSystem::Mac, OperatingSystem::Windows, OperatingSystem::Nix] {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default());
app.engine.execute("edit.select", &json!({"tracks": ["Snare"]})).unwrap();
let ctx = egui::Context::default();
ctx.set_os(os);
for (key, id) in [
(Key::A, "track.bypass_inserts"),
(Key::Num2, "track.bypass_inserts_ae"),
(Key::Num3, "track.bypass_inserts_fj"),
(Key::E, "track.bypass_eq"),
(Key::C, "track.bypass_dynamics"),
(Key::V, "track.bypass_reverb"),
(Key::D, "track.bypass_delay"),
(Key::W, "track.bypass_modulation"),
(Key::Q, "track.mute_sends"),
(Key::Num4, "track.mute_sends_ae"),
(Key::Num5, "track.mute_sends_fj"),
] {
let before = app.engine.journal.len();
press(&ctx, &mut app, key, Modifiers::SHIFT);
assert_eq!(app.engine.journal.len(), before + 1, "{os:?} Shift+{key:?}: {}", app.ui.status);
assert_eq!(app.engine.journal.back().unwrap().0, id, "{os:?} Shift+{key:?}");
}
let muted = |app: &SoundApp| app.engine.session().track_by_name("Snare").unwrap().mixer.sends[0].as_ref().is_some_and(|s| s.mute);
let was = muted(&app);
press(&ctx, &mut app, Key::Q, Modifiers::SHIFT);
assert_ne!(muted(&app), was, "{os:?}");
press(&ctx, &mut app, Key::Q, Modifiers::SHIFT);
assert_eq!(muted(&app), was, "{os:?}: a second Shift+Q unmutes");
// The keys reach the right inserts, not just the right command ids: Kick has an EQ then a compressor.
app.engine.execute("edit.select", &json!({"tracks": ["Kick"]})).unwrap();
let bypassed = |app: &SoundApp| -> Vec<bool> {
app.engine.session().track_by_name("Kick").unwrap().mixer.inserts.iter().take(2).map(|i| i.as_ref().unwrap().bypass).collect()
};
let before = bypassed(&app);
press(&ctx, &mut app, Key::E, Modifiers::SHIFT);
let after_eq = bypassed(&app);
assert_ne!(after_eq[0], before[0], "{os:?}: Shift+E flips the EQ");
assert_eq!(after_eq[1], before[1], "{os:?}: Shift+E leaves the compressor");
press(&ctx, &mut app, Key::C, Modifiers::SHIFT);
let after_dyn = bypassed(&app);
assert_ne!(after_dyn[1], before[1], "{os:?}: Shift+C flips the compressor");
assert_eq!(after_dyn[0], after_eq[0], "{os:?}: Shift+C leaves the EQ");
}
}
@@ -123,7 +123,7 @@ fn enter_right_after_switching_between_strip_silence_and_rename_presses_the_new_
#[test]
fn strip_silence_strip_removes_the_silence() {
let (mut h, track, before) = strip_silence_dialog();
h.get_by_role_and_label(Role::Button, "Strip").click();
h.get_by_role_and_label(Role::Button, "Strip Silence").click();
h.run_steps(2);
assert_eq!(h.state().dialogs.open_name(), None);
let strip = clips(&h, track);
@@ -167,7 +167,7 @@ fn strip_silence_opens_with_the_values_escape_closed_it_with() {
fn strip_silence_opens_with_the_values_strip_used() {
let (mut h, _, _) = strip_silence_dialog();
set_values(&mut h, CHANGED);
h.get_by_role_and_label(Role::Button, "Strip").click();
h.get_by_role_and_label(Role::Button, "Strip Silence").click();
h.run_steps(2);
assert_eq!(reopen(&mut h), CHANGED);
}
@@ -54,7 +54,7 @@ fn rename_names_the_clips_strip_silence_leaves() {
click(&mut h, "OK");
assert_eq!(h.state().dialogs.open_name(), Some("strip_silence"), "OK goes back to Strip Silence");
assert_eq!(h.state().dialogs.strip_names, sfx());
click(&mut h, "Strip");
click(&mut h, "Strip Silence");
assert_eq!(h.state().dialogs.open_name(), None);
let names: Vec<String> = h.state().engine.session().track(track).unwrap().clips().iter().map(|c| c.name.clone()).collect();
assert!(names.len() > 1);
+17 -2
View File
@@ -1,6 +1,6 @@
# Where SoundCraft falls short of Pro Tools
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-23 · **Change:** trivial (G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-25 · **Change:** minor (G-01: the Playback Engine shows the current device choice after a command changes it, and a buffer size the driver does not take is reported; previously trivial: G-04: Number of Loops accepts up to 1,000; crossfade remains open; previously minor: G-06: recording to disk is done (#84, long takes #888); streaming sources remain; previously minor: G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1
Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing
real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker**
@@ -52,10 +52,24 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t
not rounded onto the window's power-of-two list. Headless (CLI, no app) still stores the request
and returns `applied: false`, with `buffer_size` null when unset; playback does not read those
session values.
- **Done (2026-11-25):** the Playback Engine shows the current choice when `ui.audio_device` or
`setup.playback_engine` changed it while the window was closed or open, and Apply no longer puts
an earlier choice back. Closing the window from the menu discards unapplied edits, as its close
button does. A change made elsewhere that replaces unapplied edits is said in the window and the
status line (Pro Tools' dialog is modal, so it never meets this case). Checked on macOS (Core
Audio, RME UFX and a second input device).
- **Done (2026-11-25):** a buffer size the driver does not take is reported: `ui.audio_device`,
`setup.playback_engine` and `setup.hardware` return a `buffer_note`, `ui.audio_device` also
returns the driver's range as `device.buffer_range`, and the Playback Engine shows the note under
Output (#1757). On macOS an RME UFX's driver allows 15–3072 frames; 4096 opens at its default
buffer. The note says the size the device runs at (`device.buffer_running`, from the open
stream), and a device that reports one size (shared-mode WASAPI reports its period, 480 frames at
48 kHz) is said to run only at that size. A size the driver takes while the stream runs at
another (a host may round it) is said too.
- **Missing:** routing to physical channels (I/O Setup), one duplex stream on one clock (input and
output are still separate cpal streams), latency reporting and record-offset compensation, ASIO
in official builds (owner decision: Steinberg's SDK is proprietary or GPLv3), JACK, and
verification on macOS and Linux. The mix still runs in fixed 512-sample blocks.
verification on Linux. The mix still runs in fixed 512-sample blocks.
- **Evidence:** code above; Playback Engine window says "Mix block size: 512 samples"; issue #42
(no input device selection, forced monitoring feedback with virtual routing).
- **Impact:** blocks tracking with any multichannel interface; latency makes overdubs hard.
@@ -252,6 +266,7 @@ missing. Out of scope unless the owner decides otherwise.
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | minor | G-01: the Playback Engine shows the current device choice after a command changes it, and Apply keeps it; a buffer size the driver does not take is reported, with the driver's range (#1757); estimates unchanged |
| 2026-11-23 | trivial | G-04: Clip Looping Number of Loops accepts up to 1,000; crossfade remains open; estimates unchanged |
| 2026-11-14 | minor | G-03: strict external-WAV AAF import with bounded property caching; AAF/OMF export, OMF import and `.ptx` remain; estimates unchanged |
| 2026-11-13 | trivial | G-09: the pt-BR catalog now covers tooltips localized inside buttons and toggles, the Edit-window status bar, the remove-session question, the send help text and engine errors shown in the status line; estimates unchanged |
+5 -4
View File
@@ -1,6 +1,6 @@
# Hardware parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (record to disk: done, #84 and #888, previously trivial: bounces of a bus fed by an aux compensate its latency, #246; previously minor: MIDI input devices, live play-through with controllers, and MIDI recording) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (the Playback Engine shows the current device choice after a command changes it; buffer sizes verified on Core Audio; one the driver does not take is reported; previously minor: record to disk: done, #84 and #888, previously trivial: bounces of a bus fed by an aux compensate its latency, #246; previously minor: MIDI input devices, live play-through with controllers, and MIDI recording) · **Target:** Avid Pro Tools Ultimate 2026.4.1
A DAW is judged by how it drives audio interfaces, MIDI gear, control surfaces and sync. This is
SoundCraft's weakest dimension. Ours is measured from `crates/playback` (cpal) and the absence of
@@ -16,9 +16,9 @@ Legend: ✅ works · 🟡 partial · ❌ missing.
| Feature | Pro Tools (macOS / Windows) | SoundCraft macOS | Windows | Linux | FreeBSD | Web |
|---|---|---|---|---|---|---|
| Driver API | Core Audio / ASIO | 🟡 Core Audio via cpal | 🟡 WASAPI shared via cpal; ASIO with the opt-in `asio` build feature (verified with an SSL 2+) | 🟡 ALSA/Pulse via cpal; no JACK | 🟡 cpal (ALSA layer) | 🟡 Web Audio |
| Choose playback device | ✅ Playback Engine | 🟡 Setup › Playback Engine (not yet verified on macOS) | ✅ Setup › Playback Engine (WASAPI, ASIO) | 🟡 (not yet verified) | 🟡 (not yet verified) | ❌ |
| Choose input device | ✅ | 🟡 Setup › Playback Engine (not yet verified on macOS) | ✅ (WASAPI, ASIO) | 🟡 (not yet verified) | ❌ no recording | ❌ |
| Buffer size (32–2048) | ✅ | 🟡 device buffer when the driver allows it (not yet verified); mix in 512-sample blocks | 🟡 device buffer 16–8192 (verified 128 on ASIO, 256 on WASAPI); mix in 512-sample blocks | 🟡 (not yet verified) | 🟡 | ❌ |
| Choose playback device | ✅ Playback Engine | ✅ Setup › Playback Engine and `ui.audio_device` (verified with an RME UFX and the built-in speakers; the window shows a choice made by command) | ✅ Setup › Playback Engine (WASAPI, ASIO) | 🟡 (not yet verified) | 🟡 (not yet verified) | ❌ |
| Choose input device | ✅ | ✅ Setup › Playback Engine and `ui.audio_device` (verified with an RME UFX and a second input device) | ✅ (WASAPI, ASIO) | 🟡 (not yet verified) | ❌ no recording | ❌ |
| Buffer size (32–2048) | ✅ | 🟡 device buffer when the driver allows it (16–2048 verified on an RME UFX, whose driver allows 15–3072); outside the driver's range the default buffer, and the Playback Engine says so; mix in 512-sample blocks | 🟡 device buffer 16–8192 (verified 128 on ASIO, 256 on WASAPI); mix in 512-sample blocks | 🟡 (not yet verified) | 🟡 | ❌ |
| Duplex stream on one clock | ✅ | ❌ separate input/output streams | ❌ | ❌ | ❌ | ❌ |
| Hardware I/O mapping (I/O Setup to physical channels) | ✅ | 🟡 multichannel output in order; no per-channel map | 🟡 | 🟡 | 🟡 | ❌ |
| Low-latency monitoring | ✅ | ❌ (`options.low_latency_monitoring` is a stored flag) | ❌ | ❌ | ❌ | ❌ |
@@ -72,6 +72,7 @@ Legend: ✅ works · 🟡 partial · ❌ missing.
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | minor | Choosing the playback and input device verified on macOS; the Playback Engine shows a choice made by command; buffer sizes 16–2048 verified on Core Audio; a size the driver does not take is reported with its range (#1757) |
| 2026-11-18 | minor | MIDI input devices (`midir`): live play-through to record-enabled MIDI and instrument tracks (notes, pedal, controllers, pitch bend, aftertouch), MIDI recording into clips, per-track device and channel, device switches in Playback Engine; guide in `midi-input.md` |
| 2026-10-30 | minor | Record to disk: takes are written to disk as they record (#84) and long takes continue in a new file (#888) |
| 2026-10-13 | trivial | bounces of a bus fed by an aux compensate its latency (#246) |
+3 -1
View File
@@ -75,7 +75,9 @@ When the pass stops, each track that was record-enabled and active when it start
clip with what its input received: notes with their velocities, controllers, pitch bend, aftertouch and
program changes. What a pass records is settled when it starts: a track put in record while it
runs is recorded from the next pass, and one taken out of record keeps what it recorded. A track
that received nothing gets no clip. The clip covers the pass, the punch range, or the loop.
that received nothing gets no clip. The clip covers the pass, the punch range, or the loop. A key
pressed before a punch range (during the pre-roll) and still held when it starts is recorded
from the start of the range.
One **Undo** removes the take.
**Setup › MIDI › MIDI Input Filter…** keeps kinds of messages (for example aftertouch) out of
+118 -115
View File
@@ -19,120 +19,123 @@ UI-layer commands (windows, AudioSuite) are counted by the app's own report (`en
| View | 92 | 112 |
| Window | 1 | 52 |
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 397 yes, 115 no (window 68, os 9, engine-gap 38), 0 partial, 0 unknown.**
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`.
## Not yet implemented
- File > Open > Project...
- File > Open > Sketch...
- File > Dashboard...
- File > Start Collaboration...
- File > Import > VENUE Channel Names as Track Names
- File > Export > Selected Tracks as New AAF/OMF...
- File > Export > Selected Tracks as New Media Composer Compatible Session...
- File > Sign In
- Edit > Automation > Duplicate Dolby Atmos Plugin Automation to Pan Automation
- Edit > Automation > Duplicate Pan Automation to Dolby Atmos Plugin Automation
- Edit > Automation > Coalesce Pan Guide Automation
- View > Mix Window Views > Mic Preamps
- View > Mix Window Views > Instruments
- View > Mix Window Views > HEAT
- View > Mix Window Views > Inserts A-E
- View > Mix Window Views > Inserts F-J
- View > Mix Window Views > Sends A-E
- View > Mix Window Views > Sends F-J
- View > Mix Window Views > EQ Curve
- View > Mix Window Views > I/O
- View > Mix Window Views > Object
- View > Mix Window Views > Meters and Faders
- View > Mix Window Views > Delay Compensation
- View > Mix Window Views > Track Color
- View > Mix Window Views > Comments
- View > Mix Window Views > All
- View > Mix Window Views > Minimal
- View > Narrow Mix
- View > Other Displays > Universe
- View > Other Displays > Track List
- View > Other Displays > Clip List
- Track > Change Track Width > Show / Hide...
- Track > ARA Plugins > Melodyne
- Clip > ARA Plugins > Melodyne
- AudioSuite > EQ > Channel Strip
- AudioSuite > EQ > EQ3 1-Band
- AudioSuite > EQ > EQ3 7-Band
- AudioSuite > Dynamics > BF-76
- AudioSuite > Dynamics > Channel Strip
- AudioSuite > Dynamics > Dyn3 Compressor/Limiter
- AudioSuite > Dynamics > Dyn3 De-Esser
- AudioSuite > Dynamics > Dyn3 Expander/Gate
- AudioSuite > Dynamics > Maxim
- AudioSuite > Pitch Shift > Pitch II
- AudioSuite > Pitch Shift > Pitch Shift Legacy
- AudioSuite > Pitch Shift > Time Shift
- AudioSuite > Pitch Shift > Vari-Fi
- AudioSuite > Reverb > D-Verb
- AudioSuite > Delay > Mod Delay III
- AudioSuite > Modulation > Sci-Fi
- AudioSuite > Harmonic > Eleven Lite
- AudioSuite > Harmonic > Lo-Fi
- AudioSuite > Harmonic > Recti-Fi
- AudioSuite > Harmonic > SansAmp PSA-1
- AudioSuite > Other > DC Offset Removal
- AudioSuite > Other > Duplicate
- AudioSuite > Other > Gain
- AudioSuite > Other > Invert
- AudioSuite > Other > Normalize
- AudioSuite > Other > Reverse
- AudioSuite > Other > Signal Generator
- AudioSuite > Other > Time Compression Expansion
- Options > Activate HEAT
- Setup > Machine Track Arming Profiles...
- Window > Configurations > Window Configuration List
- Window > Configurations > New Configuration...
- Window > Configurations > Update Active Configuration
- Window > Configurations > Auto-Update Active Configuration
- Window > Arrange > Tile
- Window > Arrange > Tile Horizontal
- Window > Arrange > Tile Vertical
- Window > Arrange > Cascade
- Window > Hide All Floating Windows
- Window > Close Window
- Window > Mix
- Window > Edit
- Window > Sketch to Front
- Window > MIDI Editor
- Window > Score Editor
- Window > MIDI Event List
- Window > MIDI Editors > Bring to Front
- Window > MIDI Editors > Send to Back
- Window > MIDI Keyboard
- Window > Clip List
- Window > Clip Effects
- Window > ARA Plugins
- Window > Splice
- Window > Learn
- Window > SoundFlow
- Window > Task Manager
- Window > New Workspace > Default
- Window > New Workspace > Soundbase
- Window > New Workspace > Track Presets
- Window > Workspaces > Bring to Front
- Window > Workspaces > Send to Back
- Window > Workspaces > Close All Workspaces
- Window > Transport
- Window > Big Counter
- Window > Automation
- Window > Memory Locations
- Window > Machine Track Arming
- Window > Video Universe
- Window > Video
- Window > Color Palette
- Window > UI Customization
- Window > Metadata Inspector
- Window > Transcript
- Window > Pro Tools Search
- Window > Renderer
- Window > Trim and Downmix
- Window > Collaboration > Pro Tools Projects
- Window > Collaboration > Find Talent
- Window > Collaboration > Messages
- Window > Disk Usage
- Window > System Usage
- File > Open > Project...: headless: no, reach: os (online project service)
- File > Open > Sketch...: headless: no, reach: engine-gap (sketch files could be opened by a command)
- File > Dashboard...: headless: no, reach: window (the start dialog)
- File > Start Collaboration...: headless: no, reach: os (online collaboration service)
- File > Import > VENUE Channel Names as Track Names: headless: no, reach: engine-gap (the import could be a command)
- File > Export > Selected Tracks as New AAF/OMF...: headless: no, reach: engine-gap (the export could be a command)
- File > Export > Selected Tracks as New Media Composer Compatible Session...: headless: no, reach: engine-gap (the export could be a command)
- File > Sign In: headless: no, reach: os (online account service)
- Edit > Automation > Duplicate Dolby Atmos Plugin Automation to Pan Automation: headless: no, reach: engine-gap (automation copies could be commands)
- Edit > Automation > Duplicate Pan Automation to Dolby Atmos Plugin Automation: headless: no, reach: engine-gap (automation copies could be commands)
- Edit > Automation > Coalesce Pan Guide Automation: headless: no, reach: engine-gap (automation copies could be commands)
- View > Mix Window Views > Mic Preamps: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Instruments: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > HEAT: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Inserts A-E: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Inserts F-J: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Sends A-E: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Sends F-J: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > EQ Curve: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > I/O: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Object: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Meters and Faders: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Delay Compensation: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Track Color: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Comments: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > All: headless: no, reach: window (shows or hides part of a desktop window)
- View > Mix Window Views > Minimal: headless: no, reach: window (shows or hides part of a desktop window)
- View > Narrow Mix: headless: no, reach: window (shows or hides part of a desktop window)
- View > Other Displays > Universe: headless: no, reach: window (shows or hides part of a desktop window)
- View > Other Displays > Track List: headless: no, reach: window (shows or hides part of a desktop window)
- View > Other Displays > Clip List: headless: no, reach: window (shows or hides part of a desktop window)
- Track > Change Track Width > Show / Hide...: headless: no, reach: window (a desktop dialog)
- Track > ARA Plugins > Melodyne: headless: no, reach: engine-gap (no plug-in extension host in the engine yet)
- Clip > ARA Plugins > Melodyne: headless: no, reach: engine-gap (no plug-in extension host in the engine yet)
- AudioSuite > EQ > Channel Strip: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > EQ > EQ3 1-Band: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > EQ > EQ3 7-Band: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Dynamics > BF-76: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Dynamics > Channel Strip: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Dynamics > Dyn3 Compressor/Limiter: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Dynamics > Dyn3 De-Esser: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Dynamics > Dyn3 Expander/Gate: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Dynamics > Maxim: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Pitch Shift > Pitch II: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Pitch Shift > Pitch Shift Legacy: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Pitch Shift > Time Shift: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Pitch Shift > Vari-Fi: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Reverb > D-Verb: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Delay > Mod Delay III: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Modulation > Sci-Fi: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Harmonic > Eleven Lite: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Harmonic > Lo-Fi: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Harmonic > Recti-Fi: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Harmonic > SansAmp PSA-1: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > DC Offset Removal: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Duplicate: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Gain: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Invert: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Normalize: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Reverse: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Signal Generator: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- AudioSuite > Other > Time Compression Expansion: headless: no, reach: engine-gap (offline processing over the crates/dsp plug-ins could be commands)
- Options > Activate HEAT: headless: no, reach: engine-gap (the processor could be an engine option)
- Setup > Machine Track Arming Profiles...: headless: no, reach: os (external machine control hardware)
- Window > Configurations > Window Configuration List: headless: no, reach: window (opens or arranges a desktop window)
- Window > Configurations > New Configuration...: headless: no, reach: window (opens or arranges a desktop window)
- Window > Configurations > Update Active Configuration: headless: no, reach: window (opens or arranges a desktop window)
- Window > Configurations > Auto-Update Active Configuration: headless: no, reach: window (opens or arranges a desktop window)
- Window > Arrange > Tile: headless: no, reach: window (opens or arranges a desktop window)
- Window > Arrange > Tile Horizontal: headless: no, reach: window (opens or arranges a desktop window)
- Window > Arrange > Tile Vertical: headless: no, reach: window (opens or arranges a desktop window)
- Window > Arrange > Cascade: headless: no, reach: window (opens or arranges a desktop window)
- Window > Hide All Floating Windows: headless: no, reach: window (opens or arranges a desktop window)
- Window > Close Window: headless: no, reach: window (opens or arranges a desktop window)
- Window > Mix: headless: no, reach: window (opens or arranges a desktop window)
- Window > Edit: headless: no, reach: window (opens or arranges a desktop window)
- Window > Sketch to Front: headless: no, reach: window (opens or arranges a desktop window)
- Window > MIDI Editor: headless: no, reach: window (opens or arranges a desktop window)
- Window > Score Editor: headless: no, reach: window (opens or arranges a desktop window)
- Window > MIDI Event List: headless: no, reach: window (opens or arranges a desktop window)
- Window > MIDI Editors > Bring to Front: headless: no, reach: window (opens or arranges a desktop window)
- Window > MIDI Editors > Send to Back: headless: no, reach: window (opens or arranges a desktop window)
- Window > MIDI Keyboard: headless: no, reach: window (opens or arranges a desktop window)
- Window > Clip List: headless: no, reach: window (opens or arranges a desktop window)
- Window > Clip Effects: headless: no, reach: window (opens or arranges a desktop window)
- Window > ARA Plugins: headless: no, reach: window (opens or arranges a desktop window)
- Window > Splice: headless: no, reach: os (online sample service)
- Window > Learn: headless: no, reach: window (opens or arranges a desktop window)
- Window > SoundFlow: headless: no, reach: os (third-party automation service)
- Window > Task Manager: headless: no, reach: window (opens or arranges a desktop window)
- Window > New Workspace > Default: headless: no, reach: window (opens or arranges a desktop window)
- Window > New Workspace > Soundbase: headless: no, reach: window (opens or arranges a desktop window)
- Window > New Workspace > Track Presets: headless: no, reach: window (opens or arranges a desktop window)
- Window > Workspaces > Bring to Front: headless: no, reach: window (opens or arranges a desktop window)
- Window > Workspaces > Send to Back: headless: no, reach: window (opens or arranges a desktop window)
- Window > Workspaces > Close All Workspaces: headless: no, reach: window (opens or arranges a desktop window)
- Window > Transport: headless: no, reach: window (opens or arranges a desktop window)
- Window > Big Counter: headless: no, reach: window (opens or arranges a desktop window)
- Window > Automation: headless: no, reach: window (opens or arranges a desktop window)
- Window > Memory Locations: headless: no, reach: window (opens or arranges a desktop window)
- Window > Machine Track Arming: headless: no, reach: window (opens or arranges a desktop window)
- Window > Video Universe: headless: no, reach: window (opens or arranges a desktop window)
- Window > Video: headless: no, reach: window (opens or arranges a desktop window)
- Window > Color Palette: headless: no, reach: window (opens or arranges a desktop window)
- Window > UI Customization: headless: no, reach: window (opens or arranges a desktop window)
- Window > Metadata Inspector: headless: no, reach: window (opens or arranges a desktop window)
- Window > Transcript: headless: no, reach: window (opens or arranges a desktop window)
- Window > Pro Tools Search: headless: no, reach: window (opens or arranges a desktop window)
- Window > Renderer: headless: no, reach: window (opens or arranges a desktop window)
- Window > Trim and Downmix: headless: no, reach: window (opens or arranges a desktop window)
- Window > Collaboration > Pro Tools Projects: headless: no, reach: os (online collaboration service)
- Window > Collaboration > Find Talent: headless: no, reach: os (online collaboration service)
- Window > Collaboration > Messages: headless: no, reach: os (online collaboration service)
- Window > Disk Usage: headless: no, reach: window (opens or arranges a desktop window)
- Window > System Usage: headless: no, reach: window (opens or arranges a desktop window)
+6
View File
@@ -53,6 +53,12 @@ done
echo "==> SoundCraft $VERSION Flatpak bundle for $ARCH from $(basename "$TARBALL")"
# The packaged app unpacks to tens of MB; an archive that lists far more would fill the build
# host's disk before anything here could check it.
MAX_UNPACKED_BYTES=$((2 * 1024 * 1024 * 1024))
UNPACKED="$(tar --numeric-owner -tzvf "$TARBALL" | awk '{ s += $3 } END { print s + 0 }')"
[ "$UNPACKED" -le "$MAX_UNPACKED_BYTES" ] || { echo "error: $TARBALL unpacks to $UNPACKED bytes, more than $MAX_UNPACKED_BYTES" >&2; exit 1; }
WORK="$CARGO_TARGET_DIR/flatpak-bundle"
rm -rf "$WORK"
mkdir -p "$WORK/stage"
+5 -2
View File
@@ -19,10 +19,13 @@ fi
TMP="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"
KEYCHAIN="$TMP/soundcraft-signing.keychain-db"
CERT="$TMP/soundcraft-signing.p12"
# The decoded certificate goes in a folder of this run's own (mktemp creates it, owner-only):
# a name another account could plant in the shared folder must not receive or redirect it.
CERT_DIR="$(mktemp -d "$TMP/soundcraft-signing.XXXXXX")"
CERT="$CERT_DIR/soundcraft-signing.p12"
KC_PASS="${KEYCHAIN_PASSWORD:-$(openssl rand -hex 24)}"
trap 'rm -f "$CERT"' EXIT
trap 'rm -rf "$CERT_DIR"' EXIT
printf '%s' "$APPLE_CERTIFICATE" | base64 --decode >"$CERT"
security create-keychain -p "$KC_PASS" "$KEYCHAIN"
security set-keychain-settings -lut 21600 "$KEYCHAIN"
+3 -2
View File
@@ -33,11 +33,12 @@ OUTPUT="$DIST/soundcraft-$VERSION-macos-aarch64-nightly.zip"
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/SoundCraft"
chmod 755 "$APP/Contents/MacOS/SoundCraft"
cp "$ROOT/assets/app-icon/soundcraft-nightly.icns" "$APP/Contents/Resources/soundcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# Launcher admits notices under Resources/docs, not beside the icon.
nightly_copy_notices "$APP/Contents/Resources/docs"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
+74 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
import base64
import importlib.util
import json
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"soundcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "SoundCraft Nightly.app"
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
@@ -183,6 +185,44 @@ class Fixture:
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def package(self):
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
source = HERE.parents[1]
checkout = self.root / "source"
checkout.mkdir()
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
"assets/app-icon/soundcraft-nightly.icns"):
target = checkout / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / relative, target)
env = self.env(**dict.fromkeys(SECRETS))
def git(*args):
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
git("init", "-q")
git("add", "--", ".")
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
commit = git("rev-parse", "HEAD").strip()
version = VERSION[:-12] + commit[:12]
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
(self.bin / "cargo").write_text(
'#!/bin/sh\nset -eu\n'
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/soundcraft"\n'
'mkdir -p "$(dirname "$gui")"\n'
"printf \"#!/bin/sh\\necho 'SoundCraft %s (nightly-v1)'\\n\" \"$SOUNDCRAFT_VERSION\" >\"$gui\"\n",
)
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"),
SOUNDCRAFT_BUILD_CHANNEL="nightly-v1", SOUNDCRAFT_VERSION=version,
SOUNDCRAFT_BUILD_SHA=commit, SOUNDCRAFT_BUILD_DATE="2026-11-23")
assert result.returncode == 0, result.stdout
return self.dist / ASSET.replace(VERSION, version)
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
@@ -410,6 +450,38 @@ class Verify(unittest.TestCase):
class Build(unittest.TestCase):
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
f = Fixture(self)
archive = f.package()
source = HERE.parents[1]
resources = f"{APP}/Contents/Resources"
icon = "soundcraft-nightly.icns"
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
contents = f"{APP}/Contents"
gui = f"{contents}/MacOS/SoundCraft"
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = {entry.filename for entry in entries}
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
for path, data in expected_files.items():
with self.subTest(path=path):
self.assertEqual(zipped.read(path), data)
mode = zipped.getinfo(path).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode))
self.assertFalse(mode & 0o111)
mode = zipped.getinfo(gui).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
self.assertEqual(result.returncode, 0, result.stdout)
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
+96 -6
View File
@@ -10,6 +10,12 @@ ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# The pinned shared registry enables Windows, Linux and macOS for SoundCraft.
SIGNER_SECRETS = {
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
}
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
@@ -43,6 +49,49 @@ def assert_nightly_serialization(source):
raise ValueError("nightly serialization must use its stable group and no cancellation")
def caller_entries(lines, indent):
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
entries = {}
children = None
for line in lines:
if children is not None and line.startswith(" " * (indent + 1)):
children.append(line)
continue
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
if row is None or row[1] in entries:
raise ValueError("malformed or duplicate caller mapping entry")
children = []
entries[row[1]] = row[2], children
return entries
def assert_caller_secrets(source, job_name, names):
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
root = caller_entries(lines, 0)
job_marker, job_lines = root.pop("jobs", (None, []))
jobs = caller_entries(job_lines, 2)
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
raise ValueError("the caller must have one plain job block")
job = caller_entries(jobs[job_name][1], 4)
if "environment" in job or "environment" in root or "secrets" in root:
raise ValueError("only the native callee may bind the environment")
if names:
if "secrets" not in job:
raise ValueError("signer requires an explicit target-specific secret map")
mode, secret_lines = job.pop("secrets")
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
if mode is not None or caller_entries(secret_lines, 6) != expected:
raise ValueError("signer must forward exactly the reviewed same-name secret references")
elif "secrets" in job:
raise ValueError("unsigned caller must not pass secrets")
for value, children in (*root.values(), *job.values()):
outside_map = "\n".join([value or "", *children])
# Scan all remaining text: quoted braces can appear before a secret reference.
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
raise ValueError("secret bindings belong only in the signer map")
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
lines = jobs.splitlines()
@@ -99,7 +148,7 @@ def reviewed_manual_actors(caller_source, policy):
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$",
return re.findall(r"(?m)^ tooling-revision: (\S+)$",
(ROOT / ".github/workflows" / name).read_text())[0]
@@ -179,8 +228,49 @@ class TrustedSourcePreparation(unittest.TestCase):
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
header = " secrets:\n"
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
self.assertIn(linux, signer)
mutations = {
"missing name": signer.replace(linux, ""),
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
"duplicate name": signer.replace(linux, linux + linux),
"duplicate map": signer + header + linux,
"quoted duplicate map": signer + ' "secrets": inherit\n',
"inherit": signer.split(header)[0] + " secrets: inherit\n",
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
"yaml merge": signer + " <<: *other\n",
"environment": signer + " environment: release\n",
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
}
for change, source in mutations.items():
with self.subTest(change=change), self.assertRaises(ValueError):
assert_caller_secrets(source, "release", SIGNER_SECRETS)
def test_unsigned_caller_has_no_secrets(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
assert_caller_secrets(producer, "unsigned", set())
for suffix in (" secrets: {}\n", " secrets: inherit\n",
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
assert_caller_secrets(producer + suffix, "unsigned", set())
def test_unsigned_caller_refuses_secret_after_format_brace(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
# This inert fixture is never dispatched; the brace is part of the format string.
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
assert_caller_secrets(source, "unsigned", set())
class NightlyTrustAnchors(unittest.TestCase):
@@ -217,7 +307,7 @@ class NightlyTrustAnchors(unittest.TestCase):
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
class NightlyEnabledCallers(unittest.TestCase):
@@ -629,7 +719,7 @@ def trust_closure_problems(workflows):
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
if name != "nightly-sign.yml" or ref != "main":
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
@@ -679,7 +769,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}