Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor b5bcd710d7 Docs: state FreeBSD 15.1 requirement for prebuilt packages 2026-12-04 09:09:39 -05:00
.CooCooandFredApps be4d197b5f Clip > Unloop... opens the Unloop dialog: Remove or Flatten (#1036)
* Clip > Unloop... opens the Unloop dialog: Remove or Flatten

Clip > Unloop... removed the loop iterations of the selected clips at
once. It now opens the Unloop dialog. Remove deletes the loop iterations
and keeps the source clip, as the menu item did before, and Flatten
keeps each loop iteration as its own clip. Enter presses Remove. The
dialog opens for the clips clip.unloop would take and runs clip.unloop
on those clips with the chosen mode. With no clip to take, the menu runs
the command as before. Running clip.unloop as a command still unloops at
once without opening the dialog.

Enter in a dialog now presses the default button only when no widget
has the keyboard focus or a text field has it. Before, Enter on a
focused button, checkbox, radio button or combo box acted on that widget
and pressed the default button too: Enter on a focused Cancel ran the
dialog's OK action, Enter on Don't Save saved the session first (or
opened Save As when it had never been saved), Enter on Browse... opened
the picker and then pressed OK or Bounce, and Enter on a checkbox, radio
button or combo box toggled, picked or opened it and then pressed the
dialog's default button.

* Clip > Unloop... runs the command when no selected clip is looped

The dialog opened for any selected clip, so an ordinary clip showed
Remove and Flatten, and either choice only gave "the selection is not
a looped clip". The menu now opens the dialog only when a clip it
takes belongs to a loop (`cmd::is_looped`, the loop check
`clip.unloop` uses); otherwise it runs the command, and the status
line shows that error.

* Tests: follow main's PathBuf pickers and FileFormat in the focused-button tests

* Dialogs: Enter presses the default button after the dialog opens

A dialog clears the keyboard focus on the first frame it is drawn, so a
button in the main window that still had the focus no longer takes the
Enter meant for the dialog. Enter in that first frame, which opened the
dialog from a menu item or the command palette, no longer presses its
default button. In the Unloop dialog, a Flatten click in the same frame
as Enter flattens instead of removing.

* Dialogs: a replaced dialog skips the opening Enter, and a held Enter does not press the default

A dialog opened in place of another one, or the save prompt opened from a
dialog, now gets the same first frame as a dialog opened when none was
open: the keyboard focus is cleared and that frame's Enter is ignored.
Enter presses the default button only on a new key press, so the repeats
of an Enter held down from the menu or palette do not press it.

* Dialogs: rename and Modify Group dialogs that replace an open dialog skip the opening Enter

Rename Track, Rename Clip, Rename Marker and Modify Group now open through
the same path as the other dialogs, so when one replaces a dialog that is
already open, its first frame clears the keyboard focus and ignores Enter.

* Unloop: leave the dialog-wide Enter handling to its own pull request

The changes to Enter and the keyboard focus in every dialog, and their
tests in focused_dialog_buttons.rs, are removed from this branch. The
Unloop dialog keeps its Flatten and Remove buttons, Enter on Remove, and
a Flatten click winning over an Enter in the same frame.

* Unloop dialog: test Enter with no button focused and on a focused Cancel

Enter with no button focused presses Remove, and Enter on a focused
Cancel closes the dialog without unlooping.

* Tests: Unloop over another dialog and a held Enter do not press Remove

An Unloop dialog that replaces an open dialog ignores the Enter of its first frame, and a held Enter's repeats do not press Remove until Enter is released and pressed again. The frame helper is shared with the Flatten click test.

* Unloop dialog: show its title, text and Flatten button in Brazilian Portuguese

The explanation and the Flatten button now go through crate::localization::text, and the pt-BR catalog has rows for the Unloop title, Flatten and the explanation. Remove already had one.

* Unloop dialog tests: install the headless runtime in each harness

main's UI harnesses install the craft-ui runtime before the first
frame (55078b0f). Without it every Unloop dialog test panics on
`dock.float_panel` in the command board.

* Localization: add zh-Hans rows for the Unloop dialog

main's every_localized_source_string_has_a_zh_hans_entry test requires a
zh-Hans row for every string passed to localization::text, and the merge
of main into this branch brought that test in while the Unloop dialog's
"Flatten" button had only a pt-BR row, so the gate failed. Add "Flatten",
"Unloop" and the dialog's explanation to zh-hans.tsv and regenerate the
locale module with docs/i18n/tools/gen_zh_hans_locale.py.

* Unloop: keep the pending save action and close id dialogs on session change

An Unloop with no looped clip in the selection opened no dialog but still
cleared the action waiting on Save Session As, so a Save-then-close never
closed. The check now runs before that action is cleared.

Replacing the session left open dialogs that hold the old session's track,
clip, source, marker or group ids (Unloop, Clear, the rename dialogs, Auto
Rename, Spot, Group), and the new session can reuse those ids, so OK could
edit objects the user never chose. document_replaced now closes them.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 10:35:36 +01:00
FredApps efbcb74c3d Merge pull request #970 from lucasegen/fix/toolbar-overflow
Fit the Edit toolbar in a 13-inch MacBook window and keep its scroll bar off the controls
2026-12-04 08:11:33 +01:00
FredApps 2930c40002 Format toolbar test harness 2026-12-04 07:55:56 +01:00
FredApps 15e189b7fb Initialize framework in toolbar fit harness 2026-12-04 07:53:51 +01:00
FredApps ce8cd8f897 Merge branch 'main' into fix/toolbar-overflow 2026-12-04 07:43:27 +01:00
FredApps 5e090423b9 Merge pull request #1400 from TheGeekyM/feat-add-a-semantic-session-diff-so
docs(readme): say what session.inspect actually returns
2026-12-04 07:17:04 +01:00
FredApps ce744fb9ab Merge pull request #1699 from istefp/feat/win-editor-timers
vst3, clap: pump hosted editors' Win32 timers and paints while the transport plays
2026-12-04 07:15:08 +01:00
FredApps e21c406016 Merge pull request #1618 from mtlcl410/fix/preserve-imported-sysex
M7: imported SMF SysEx packets survive session saves and MIDI export (file-format-parity.md)
2026-12-04 07:14:50 +01:00
FredApps fb11e9268d Merge pull request #1580 from gmrmad1/fix/new-track-instrument-id
track: validate the instrument id in track.new
2026-12-04 07:14:33 +01:00
FredApps 9f0cc38b02 Format session inspection regression 2026-12-04 07:04:33 +01:00
FredApps 7e5a8d69e3 Merge branch 'main' into feat/win-editor-timers 2026-12-04 07:03:38 +01:00
FredApps fc09513bc6 Merge branch 'main' into fix/preserve-imported-sysex 2026-12-04 07:03:36 +01:00
FredApps 337f4db5cb Merge branch 'main' into fix/new-track-instrument-id 2026-12-04 07:03:34 +01:00
FredApps 5584e00693 Merge branch 'main' into feat-add-a-semantic-session-diff-so 2026-12-04 07:03:32 +01:00
FredApps a4193ccba5 Merge pull request #1098 from dotCooCoo/feat/send-fine-adjustment
Sends: Ctrl or Command gives fine adjustment on a send's level, its sliders and the pan knobs
2026-12-04 06:36:33 +01:00
FredApps 1a4dbc3b10 Merge pull request #734 from MarekSpodBiedry/issue-717
Bounce: report the levels of the clipped samples that are written (#717)
2026-12-04 06:35:57 +01:00
FredApps 671a0ceb2a Merge pull request #1225 from justinjohn0306/automation/issue-1224
Fix #1224: Confined MCP: setup.disk_allocation accepts a record folder outside the automation roots
2026-12-04 06:35:26 +01:00
FredApps 46c86c5033 Merge branch 'main' into automation/issue-1224 2026-12-04 06:01:22 +01:00
FredApps dc1cdc6c59 Merge branch 'main' into feat/send-fine-adjustment 2026-12-04 06:01:17 +01:00
FredApps 6ba76e46ff Merge branch 'main' into issue-717 2026-12-04 06:01:12 +01:00
344d732f77 Edit window: one header meter bar per channel (#1321)
* Edit window: one header meter bar per channel

Track-header meters now draw one bar per channel, as Pro Tools does:
mono one, stereo two, 5.1 six, 7.1 eight, up to MAX_CHANNELS. The
master fader meters the main output's channels. Mono and stereo keep
the 8 pt meter they had.

The track-header column widens to fit the widest meter among the
tracks shown, so every meter starts at the same x; hiding the widest
track narrows it again. Ruler labels and column titles follow.

MeterDisplay now keeps a level and peak hold for every channel, fed
from StripMeter::peaks. The Mix window's surround meters read it too,
gaining peak hold, which replaces their separate per-frame ballistics
and the per-frame meter snapshot clone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ddan1HaNGYU3ZEJ5J5ktUj

* Meters: let only a reading refresh the shared peak-hold timer

With one level per channel, a strip's unused channels read 0 against a
zero hold on every update, so `v >= hold` reset `hold_age` each time and
the peak holds of the live channels never expired. Only a non-zero
reading now refreshes the timer; a test feeds 2.5 s of silence after a
peak on a stereo strip and checks the holds fall back to the level.

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

* Meters: time each channel's peak hold on its own

A strip's channels shared one `hold_age`, so a steady reading on C kept
resetting it and an L peak stayed held well past 2 s after L went
silent. `MeterDisplay::hold_age` is now per channel, which also makes
the earlier non-zero-reading guard unnecessary: a silent channel only
resets its own (zero) hold. A test keeps C playing after an L peak and
checks the L hold expires while C's stays.

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

* Meters: fall when the output stops rendering while monitoring

Input monitoring and record-arm keep the meters live while stopped, where
no stall is reported. If the output then stalls, goes away or fails, no
block arrives and the UI kept feeding the last reading, so meters froze
on it. `Player::take_meters` now says whether a block arrived since the
last take; once none has for 0.5 s (well past the longest device
buffer's burst), the UI feeds silence and the meters fall and their
holds expire. Takes without a new block still keep the reading, so a
large buffer does not make meters dip between bursts.

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

* Meters: keep repainting while any channel or hold is still falling

After playback stops, the idle repaint schedule checked only channel 0 of
the track meters, so a surround strip with signal on C alone (or a
quiet strip whose peak hold had not expired yet, or the main meter)
fell in steps on the slower idle schedule. `MeterDisplay::is_moving`
checks every channel's level and hold, for the tracks and the main
meter.

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

* Meter tests: cover the master special case, fallback width and non-finite pairs

From review: the master test now sets a 5.1 main output with a stereo
master track, so it fails without the main-output special case; the
header width test has 5.1 and 7.1 tracks and checks that hiding the 7.1
falls back to the 5.1 width; the non-finite test puts NaN and infinity on
the stereo pair as well and checks the next good reading shows; the
width test uses MAX_CHANNELS instead of 16.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 05:53:16 +01:00
7f9e5e71ea Edit › Room Tone: fill gaps with recorded room tone (#1516)
* Edit › Room Tone: fill gaps with recorded room tone

Narrators and dialogue editors fill gaps left by edits with the room's
own background noise, since digital silence is audible. This adds:

- edit.room_tone_set: the selected clip (or the selected part of it)
  becomes the session's room tone, saved with the session.
- edit.room_tone_fill: fills every empty stretch of the selection on
  the selected audio tracks with ordinary clips of that tone. Gaps
  longer than the tone are tiled with equal-power crossfades
  (fade_ms, default 10 ms); each gap's edges get a short de-click
  fade (edge_fade_ms, default 2 ms) so the background does not dip
  next to speech. A fill is capped at 20,000 clips and is planned
  before anything changes.
- edit.room_tone_clear and the edit.room_tone query.

The tone is dropped when its file is removed from the Clip List, when
a template is saved, and when a loaded session's tone points at a
missing source; it counts towards the unsaved-changes state. The
commands sit in Edit › Room Tone, under Strip Silence.

* Room Tone: check the window against the decoded audio

A session's stored source frame count is not refreshed when it is
reopened, so a room tone sanitized against it can outlast a shorter
replacement file. Fill now clamps the tone to the decoded frames and
refuses when less than the minimum is left; Set measures the window
against the decoded audio when the source is loaded.

* Room Tone: take audio types from craft-audio after the merge

main removed crates/audio-io (#1506); the room tone tests now use
craft_audio::AudioBuffer and soundcraft_model::FileFormat.

* Room Tone: keep a tone past a stale stored length on reload

Set Room Tone sizes the window from the decoded audio, but reopening a
session cuts it to the source's stored frame count, which is not
refreshed on load. Record the decoded count when it is longer, so the
saved tone reopens unchanged.

* Translate room tone menu labels into Brazilian Portuguese

---------

Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-03 15:40:17 +01:00
FredApps bf69b6aa25 Merge pull request #1288 from JonRC/fix/1287-hosted-latency-in-bounces
Offline renders follow a latency hosted plugins report once they run (LSP Limiter was 240 samples late)
2026-12-02 21:26:48 +01:00
FredApps 75b87c1394 Merge branch 'main' into fix/preserve-imported-sysex 2026-12-02 15:18:16 +01:00
FredApps 2c187ba304 Merge branch 'main' into feat/win-editor-timers 2026-12-02 15:18:08 +01:00
Madhav Agarwal 39e09f8b1e track: reject a malformed instrument id in track.new
A present non-string instrument was read as absent and silently created the default synth. Only a missing instrument asks for the default now; an explicit value must be a plugin id string. Cover the single-row case, a mixed batch where the malformed second row rolls back the first, and the unchanged default when omitted.
2026-12-02 17:30:03 +05:30
FredApps f9a110751d Merge branch 'main' into automation/issue-1224 2026-12-02 09:09:11 +01:00
FredApps bc7e94a98b Merge branch 'main' into feat/send-fine-adjustment 2026-12-02 09:09:03 +01:00
FredApps 1010b23770 Merge branch 'main' into fix/toolbar-overflow 2026-12-02 09:08:45 +01:00
FredApps 841c4a37c9 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	contributors/people.toml
#	docs/plugin-parity.md
2026-12-02 12:23:56 +07:00
FredApps 9c1f7b9fa0 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/control-protocol.md
2026-12-02 12:23:52 +07:00
FredApps 7d6cbb1997 Merge branch 'main' into issue-717 2026-12-02 06:05:12 +01:00
a67a063280 docs: bring ROADMAP.md current through 2026-11-15 (#1574)
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-01 11:39:13 +01:00
a3e10d89d7 Send menu: a new bus asks mono or stereo (#1547)
* Send menu: new bus asks mono or stereo (#1388)

Co-Authored-By: Patrick Istefanidis <smallroomproductionsfl@gmail.com>

* send menu: complete new-bus labels

---------

Co-authored-by: Patrick Istefanidis <smallroomproductionsfl@gmail.com>
Co-authored-by: Stefan Pantic <stefpantic@gmail.com>
2026-12-01 11:15:09 +01:00
Justin JohnandClaude Opus 5.5 15267be73b Test the record folder in a folder of its own, removing only what it made
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:58:01 +05:30
Stefan Pantic 0a37c171e8 vst3,clap: document timer test FFI safety 2026-11-30 01:08:51 -05:00
Dylan M. Taylor bb486228cd Enable automated nightly schedule and Stage 2 signer dispatch (#1882) 2026-11-29 16:16:21 -05:00
Dylan M. Taylor 3b06aea7d0 ci(sonarcloud): give each main commit its own concurrency group (#1951) 2026-11-29 15:43:36 -05:00
Dylan M. Taylor 7b4905c00e test(nightly): preserve startup and saved session coverage (#1950) 2026-11-29 15:12:24 -05:00
Dylan M. Taylor 40497d7eca Adopt craft-nightly for self-isolated nightly builds (#1943) 2026-11-29 13:48:49 -05:00
FredAppsandFredrik Hallin 35dcf1d412 Release: SoundCraft v0.21.0 (#1914)
Co-authored-by: Fredrik Hallin <fredrik.hallin@guidelinegeo.com>
2026-11-29 07:57:37 +01:00
FredAppsandFredrik Hallin f155bba583 ci: use the standard macOS runner for releases (#1915)
Co-authored-by: Fredrik Hallin <fredrik.hallin@guidelinegeo.com>
2026-11-29 07:55:42 +01:00
Dylan M. Taylor 896de30146 chore(sonar): classify apps/soundcraft-web/tests/** as test code (#1913) 2026-11-29 01:20:29 -05:00
Dylan M. Taylor 681f40f566 fix(web-tests): constrain page-api.mjs site folder root to cwd or tmpdir (#1908) 2026-11-29 01:01:10 -05:00
Dylan M. Taylor a3c7f4edc7 fix(sonar): resolve 7 new-code SonarCloud issues (#1907) 2026-11-29 00:39:54 -05:00
Dylan M. Taylor 7fe79e21ed fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#1906) 2026-11-28 22:41:10 -05:00
Dylan M. Taylor d42ade0951 fix(packaging): resize soundcraft-nightly.png to 256x256 for Flatpak export (#1905) 2026-11-28 22:05:05 -05:00
Dylan M. Taylor 025cf1e0ba fix(packaging): exclude embedded nightly icon from staged hicolor tree and re-enable arch (#1904) 2026-11-28 22:01:23 -05:00
Dylan M. Taylor 31dfc36766 ci(nightly): omit arch format while fixing Arch side-by-side fixture (#1903) 2026-11-28 21:41:46 -05:00
7a563aca6e Chase held MIDI notes after a seek (#1563)
* Chase held MIDI notes after a seek

Problem: the mixer sent all-notes-off on a seek and only struck note-ons
that start inside a block, so a chord that began before the new position
stayed silent until the next chord (also when playback started mid-chord).

Change: schedule_notes takes chase (the first block after a start or seek,
from the existing Strip::chase) and strikes notes sounding at the block
start, with real-time properties and MIDI track offset applied as for
normal notes.

Validation (Linux host): new soundcraft-mix test
notes_held_across_a_seek_are_struck_again passes; soundcraft-mix lib tests
pass with the change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Keep the controller restore after live input lets go separate from the note chase, so it does not re-strike sounding notes

---------

Co-authored-by: Your Name <you@example.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-29 00:07:43 +01:00
af7c16b570 Release MIDI notes whose note-off lands on the clip end (#1562)
Co-authored-by: Your Name <you@example.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 23:50:40 +01:00
SuperiorandFredApps 60950ba884 Localization: Simplified Chinese catalogs on the shared localization module (#783)
* Add the Simplified Chinese catalog to the shared localization module

English source text stays the key: crates/ui-egui/locales/zh-Hans/mod.rs is generated from
crates/ui-egui/src/i18n/zh-hans.tsv (1,383 strings) by docs/i18n/tools/gen_zh_hans_locale.py, so a
translator edits one TSV row per string and the module follows. The TSV is also the file
storytold/craft-i18n's sync script reads, so the catalog can move there when SoundCraft cuts over.

The catalog covers every string passed to localization::text / localized_format! in the crate and
every reference menu label (crates/engine/catalog/menus.txt). Tests compare placeholders against the
English source, reject duplicate keys and name any untranslated string by file. Engine diagnostics
stay English by design: a half-translated error reads worse than a whole one.

Language::SimplifiedChinese ("zh-Hans") joins the enum, the Appearance menu and the ui.language
command, and the choice is saved with the UI state like the theme. AI-authored from the English
source; native-speaker review is still pending.

* Add a Han font fallback for Chinese on the desktop and the web

egui's bundled faces carry no Han glyphs, so a Chinese interface and Chinese session, track and clip
names would draw boxes. fonts.rs now appends a Han fallback to every family:

- desktop: the operating system's own face, resolved through fontconfig with lang=zh-cn plus a list
  of per-platform candidates (PingFang, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi,
  ...). Nothing is redistributed.
- web: the browser cannot reach system fonts, so the build embeds assets/fonts/NotoSansSC-SoundCraftSubset.ttf,
  a 1.1 MiB Open Font License subset of Noto Sans SC pinned at weight 400.

Han is ordered before the Hangul fallback for every interface language except Korean: the first face
with a glyph wins, and on Linux fontconfig often resolves Noto Sans CJK's Korean face, whose Han
glyphs are Korean-styled. Tests check the ordering, that every family draws Han when a system font
is present, that the bundled face draws the whole zh-Hans catalog in every family, and that it stays
inside its 2 MiB budget. ATTRIBUTION.md records the font and its OFL text; cargo xtask assets
enforces that.

* Document the zh-Hans catalog and refresh the localization numbers

docs/localization.md now describes what ships today (the Language enum, locales/<tag>/mod.rs,
text / localized_format! / error_text, the TSV-to-module step, the Han fallback, the tests) instead
of the packed-catalog design the branch carried before upstream landed the shared localization
module. docs/localization-zh-hans.md is the translator workflow; docs/i18n/glossary.md records the
wording decisions without citing another product's catalogs, and the earlier cross-corpus research
files are gone: the repository's clean-room rule forbids reading GPL translation sources, so the
terminology stands on its own reasoning.

ROADMAP.md, docs/roadmap.md, docs/localization-parity.md and docs/gaps.md move zh-Hans from "none"
to shipped-for-fixed-strings with native review pending, note the CJK fallback, and lower the
localization estimate from 70-110 h to 55-90 h.

* Align the localization numbers and the catalog-editing guidance

The localization row in docs/target-app-parity.md still listed pt-BR only, ~12 % and 70-110 h; the
G-09 row kept the old 20-40 h. Both now match ROADMAP.md, docs/roadmap.md and
docs/localization-parity.md: two shipped catalogs, ~19 %, 55-90 h to the target's eight languages.

Also, docs/localization-parity.md no longer tells a reader to add a Rust arm for every catalog: pt-BR
is hand-written, zh-Hans is generated from its TSV, and the two are now described separately. The
font regeneration commands in docs/localization.md and docs/localization-zh-hans.md name the input
the subset script requires (a Noto Sans SC variable font) instead of implying it runs with no
argument.

* zh-Hans: keep the slot and track order in "Insert {} for {}"

---------

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

Co-authored-by: IfritisZ <44840600+IfritisZ@users.noreply.github.com>
Co-authored-by: timlehmann1234567890-cell <346860803+timlehmann1234567890-cell@users.noreply.github.com>
2026-11-28 23:22:25 +01:00
Billy Coleman IIIandFredApps 0f26696507 Read bus-send pan and mute automation (#543)
* Read bus-send automation at the delayed source timeline

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

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

* style: group the send-automation imports

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

* style: rustfmt the send-automation merge port

---------

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

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

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

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

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

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

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

* style: rustfmt the audio.health port

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

* Complete the Spanish (es-ES) UI catalog

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

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

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

* Test that the Spanish catalog covers every menu label

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

* docs: Spanish catalog complete in the language tables

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

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

---------

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

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

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

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

---------

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

* docs: bring comments in line with the code

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

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

---------

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-28 12:40:09 +01:00
dotCooCoo c876aa0de3 Sends: install the headless UI runtime in the fine adjustment tests
The send fine adjustment tests built their harness without the context setup the other UI integration tests use, so each press with a modifier held reached an app-scope command with no state and panicked.
2026-11-25 22:55:55 -08:00
dotCooCoo c8242560d7 Merge main into feat/send-fine-adjustment 2026-11-25 22:51:30 -08:00
dotCooCoo 3dcfa69e35 Merge main into feat/send-fine-adjustment 2026-11-25 21:13:27 -08:00
mtlcl410 c5d9c72707 docs: bring comments in line with the code 2026-11-26 09:43:43 +08:00
dotCooCoo c4bb7d12ac Sends: a Ctrl press on a fine slider without a move keeps the value unrounded
A Ctrl or Command press and release on a fine slider's rail, with the
pointer kept still, rounded the value to the decimals of the value box,
so the send options menu stored a new level or pan. The value now stays
at the anchor until the pointer moves.
2026-11-24 18:05:45 -08:00
Stefan Pantic 94bbac0711 vst3,clap: the timer pump reposts WM_QUIT with its exit code and stops 2026-11-24 19:26:13 -05:00
mtlcl410 d88b9dd19e Merge current main into fix/preserve-imported-sysex
Main now pins craft-libs a3fca170, which contains craft-libs#2077 (38b40018),
so this branch uses main's pins and lockfile unchanged. Conflicts: main's
explicit Sequence fields in the note-split and its room_tone binding are kept;
the MAX_SYSEX_BYTES re-export and the shorter test constructors stay.
2026-11-24 14:19:11 +08:00
Stefan Pantic 1111864d20 vst3,clap: pump editor WM_TIMERs and their paints while the transport plays
Hosted VST3 and CLAP editors on Windows animate from Win32 timers. Win32
only synthesizes WM_TIMER and WM_PAINT when the thread's message queue
runs dry, but during transport playback eframe repaints continuously and
the queue never empties — so a timer-driven editor freezes until Pause.

Each host window now has a per-frame service() called from the existing
per-frame idle path (main thread only): it dispatches up to 32 pending
WM_TIMERs with PeekMessageW/PM_REMOVE + DispatchMessageW — a TIMERPROC
only runs through dispatch — then flushes the paint they invalidated
with RedrawWindow(RDW_UPDATENOW | RDW_ALLCHILDREN) so children repaint
too. Non-Windows hosts get a no-op service().

Each host gains a regression test that proves both halves: a real Win32
timer does not fire while nobody pumps, and after service() it has both
fired and had its invalidated paint flushed (GetUpdateRect is clear).

Fixes #1447
2026-11-21 14:59:00 -05:00
mtlcl410 a66c29502b Preserve copied MIDI duration when merging at a slower destination tempo 2026-11-20 20:20:51 +08:00
mtlcl410 871f6f9fa7 Respect copied MIDI bounds during merge and report the SysEx import budget 2026-11-20 20:08:56 +08:00
mtlcl410 faac329f43 Merge remote-tracking branch 'canonical/main' into fix/preserve-imported-sysex
# Conflicts:
#	docs/file-format-parity.md
2026-11-20 16:19:34 +08:00
mtlcl410 308447df97 Use canonical craft-libs for SysEx and distinguish truncation from a complete oversized packet 2026-11-20 16:19:20 +08:00
mtlcl410 f741e775ef Use the reviewed SysEx writer ordering dependency 2026-11-18 06:27:34 +08:00
mtlcl410 a58e54a93c Keep imported SMF SysEx packets through session saves and MIDI export 2026-11-18 02:07:12 +08:00
JonRC aa7c4436c7 Merge remote-tracking branch 'upstream/main' into fix/1287-hosted-latency-in-bounces 2026-11-16 07:11:28 -03:00
dotCooCoo 6b8eeb6f67 Merge main into feat/send-fine-adjustment 2026-11-15 13:25:43 -08:00
Madhav Agarwal 50810053fa track: validate the instrument id in track.new 2026-11-15 18:50:29 +05:30
MarekSpodBiedry 51415ca71d Use the channel count as usize in the bounce clipping test (#717) 2026-11-13 22:21:10 +01:00
MarekSpodBiedry 0f1064a4c0 Merge main into #734 (#717) 2026-11-13 22:19:43 +01:00
Mohamed Emad 774c07bd85 Address review feedback 2026-11-13 16:25:55 +02:00
dotCooCoo d574a079ff Merge main into feat/send-fine-adjustment 2026-11-13 04:10:19 -08:00
JonRC 87d89ae302 CLAP idle: run every callback a plugin asks for, up to eight
A plugin may ask for another on_main_thread from on_main_thread before it
asks for the restart. idle ran one callback per call, so the restart and
the new latency came an idle later, after the bounce had fixed its head
trim. idle now runs callbacks until none is pending, at most eight, before
it checks for a restart. The CLAP fixture now asks for a second callback
before the restart, so its restart test covers this.
2026-11-12 21:40:48 -03:00
JonRC 7f8a5b39fc Merge remote-tracking branch 'upstream/main' into fix/1287-hosted-latency-in-bounces
# Conflicts:
#	crates/mix/src/tests.rs
2026-11-12 21:17:46 -03:00
Mohamed Emad 2c1d83e616 Address review feedback 2026-11-12 17:48:17 +02:00
Mohamed Emad 32ab49522f Address review feedback 2026-11-12 17:43:38 +02:00
dotCooCoo 49af7e3857 Merge feat/plugin-parameter-default-reset into feat/send-fine-adjustment
An Alt-click on the Clip Effects gain after typing in its value box is its own undo step, as on the other Clip Effects parameters. The tests that relied on a Ctrl press setting the value now start from a set value or a fresh dialog.
2026-11-09 16:41:01 -08:00
dotCooCoo a852af5495 Merge feat/plugin-parameter-fine-sliders into feat/plugin-parameter-default-reset 2026-11-09 15:05:50 -08:00
dotCooCoo 39ff7fd004 Tests: plugin sliders with Control alone and with Ctrl toggled during a drag
The plugin window's logarithmic and whole-number sliders keep their value
when Ctrl is pressed or released during a drag, and a drag with Control
alone is fine. The tenth-as-far test names the parameters it drags and
checks the others do not change, and the low-end test checks the value
after the release.
2026-11-09 15:00:46 -08:00
dotCooCoo 8bd195f8eb Merge feat/strip-silence-fine-sliders into feat/plugin-parameter-fine-sliders 2026-11-09 15:00:46 -08:00
dotCooCoo 7c5d5434b7 Strip Silence: the fine slider's response reports each change of a drag
The value moved by a drag that the key has touched is set before the
slider reads it, so the Response's changed() stayed false on those
passes. fine_slider now marks the response when the value changed.

Tests: a Control-only drag, and changed() on every pass of a Ctrl-drag.
The value box test releases the button once and checks the value after.
2026-11-09 14:46:57 -08:00
dotCooCoo ec7bd5d0bb Plugins: a short Ctrl-drag at the low end of a log slider with a value box moves the value
A fine drag rounded to at most three decimal places, so a one-point
drag near the bottom of a range such as Attack at 0.01 ms rounded back
to where it started. The rounding now allows up to six places.
2026-11-09 13:23:55 -08:00
dotCooCoo 4eed24d4d0 Plugins: tests cover Alt reset and Ctrl fine adjustment on more slider kinds
Tests now cover Ctrl without Command, Alt pressed during a drag, one
undo step for a choice-list reset, whole-number and logarithmic sliders,
Alt-click and Ctrl-drag on the AudioSuite and Clip Effects value boxes,
and Alt on a Strip Silence slider, which behaves like a plain click or
drag.

The ROADMAP entry limits the choice-list reset to the plugin window, and
the docs/ui-parity.md fine-adjustment row names the Clip Effects and
AudioSuite sliders.
2026-11-09 13:13:46 -08:00
JonRC aadf0b4da6 Render the first block again until plugin latency settles
A plugin can settle its latency in more than one step, and the result of
idle after the first block was rendered again was dropped, so a second
change left the head trim short. The render now starts over until no
insert's latency changes, four times at most, with a warning if it never
settles. Instrument latency still does not count: it is not part of
delay compensation, and the doc on idle_plugins now says so. Plugin::idle
also gets a contract for implementors, and the plugin-parity row ends
its sentence.
2026-11-09 16:39:37 -03:00
dotCooCoo 01379a61b3 Merge main into feat/send-fine-adjustment 2026-11-07 08:15:02 -08:00
dotCooCoo 8f5d5ec0ec Merge main into feat/plugin-parameter-default-reset 2026-11-07 08:14:39 -08:00
dotCooCoo 70bdc7f046 Merge main into feat/plugin-parameter-fine-sliders
# Conflicts:
#	crates/ui-egui/tests/it/main.rs
2026-11-07 08:07:43 -08:00
dotCooCoo 4baaf8af30 Merge main into feat/strip-silence-fine-sliders 2026-11-07 08:07:18 -08:00
lucasegen 64ef487e21 Merge remote-tracking branch 'upstream/main' into fix/toolbar-overflow
# Conflicts:
#	crates/ui-egui/tests/it/main.rs
2026-11-07 15:43:37 +01:00
dotCooCoo 234990eb2a Clip Effects: an Alt-click reset during an automation pass joins the pass's undo step
The reset ends the open merge only when it continues the same slider's typed
edit. While a Write, Touch or Latch pass plays, the merge holds the pass's
key, so ending it split the pass into two undo steps.
2026-11-07 03:15:17 -08:00
dotCooCoo 99810a6666 Merge main into feat/send-fine-adjustment 2026-11-06 03:42:02 -08:00
dotCooCoo 48fec6e40d Merge main into feat/plugin-parameter-default-reset 2026-11-06 03:39:16 -08:00
dotCooCoo cbadb1bcd6 Merge main into feat/plugin-parameter-fine-sliders 2026-11-06 03:36:25 -08:00
dotCooCoo cf6ea93d8e Merge main into feat/strip-silence-fine-sliders 2026-11-06 03:29:04 -08:00
Mohamed Emad 6bcb14b3bd Address review feedback 2026-11-06 08:57:48 +02:00
Mohamed Emad 170c329242 docs(readme): say what session.inspect actually returns
This fixes one sentence in the README's "For agents and scripts" section. It used to say `session.inspect` "reports exactly what changed". It now says what the command returns: the session's current state and the labels of the last undo and redo steps. Agents check their work by comparing an inspection from before an edit with one from after it. I also added integration tests in the engine crate that check both the corrected sentence and the before/after workflow it describes.
2026-11-06 03:56:10 +02:00
Justin JohnandClaude Opus 5.5 669a0ebcb6 Use str::repeat for the record-folder test pad
clippy -D warnings rejects repeat().take() on Unix, where this block compiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:16:00 +05:30
Justin JohnandClaude Opus 5.5 0dd9f8f535 Merge justinjohn0306/soundcraft#1: trim again after the disk_allocation path is cut
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:14:58 +05:30
MarekSpodBiedry 07bbb27289 Bounce: meter the clipped samples only for integer files; move test to tests/it (#717) 2026-11-04 08:48:14 +01:00
MarekSpodBiedry 2959d8d173 Merge main into #734 2026-11-04 08:48:01 +01:00
XI-AdithyaShankaranandCursor bbcb826f38 Trim again after the disk_allocation path is cut to 200 characters.
A space at the cut was checked, then removed when the path was stored. The outside-folder test now uses the working directory's parent.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 00:27:23 +05:30
JonRC b56703843b Clear hosted plugins' audio before the first block is rendered again
Vst3Plugin::reset only flushes notes, so a VST3 insert on any track kept
what the discarded first pass left in it, a reverb or echo tail for
example. The second pass now prepares the hosted plugins again after the
reset, which deactivates and reactivates them. The comment also says
that the head trim is the first block's: a later latency change moves
the alignment from that block on, as in playback.
2026-11-02 13:23:28 -03:00
JonRC a5906ce9c7 Offline renders follow a latency hosted plugins report once they run
LSP Limiter reports 0 samples at activate and its 5 ms lookahead once it
has processed, so bounces came out exactly 240 samples late. Offline
renders now give plugins main-thread time between blocks (Plugin::idle):
CLAP plugins get the on_main_thread and the restart they ask for, VST3
plugins are asked for their latency instead of waiting for
restartComponent. When a latency changes on the first block, the render
starts over from the range start, as a locate does.

Fixes #1287.
2026-11-02 12:19:37 -03:00
JonRC 8305f68827 Contributors: add JonRC to people.toml 2026-11-02 12:02:39 -03:00
dotCooCoo cb6fbac081 Merge main into feat/strip-silence-fine-sliders 2026-11-01 23:32:19 -08:00
dotCooCoo 7b7f0ca22b Merge commit 'refs/check/merge-soundcraft-1098-main' into feat/send-fine-adjustment
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-11-01 18:46:06 -08:00
dotCooCoo 751ff25d5f Merge main into feat/plugin-parameter-default-reset 2026-11-01 18:33:37 -08:00
dotCooCoo 30ee5b5b22 Merge commit 'refs/check/gf-dialog-enter-main' into feat/plugin-parameter-fine-sliders
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-11-01 13:55:24 -08:00
dotCooCoo 052d8573bf Dialogs: leave Enter on a focused Cancel or Don't Save to its own pull request
The dialog changes for Enter on a focused Cancel or Don't Save, the
Bounce Mix change that started the bounce after the Cancel check, and
their tests in save_changes.rs, strip_silence_dialog.rs and bounce.rs
are removed from this branch. The fine adjustment on the sliders stays.
2026-11-01 13:54:59 -08:00
Justin JohnandClaude Opus 5.5 2ef1a73ba6 Check the disk_allocation path as it is stored
set_text trims the value and cuts it to 200 characters, so the raw path
that was checked could differ from the one kept (" /tmp/esc" passed as
"<cwd>/ /tmp/esc" but was stored as "/tmp/esc"). Normalise once with
text_value, then check and store that same string. An empty path still
clears the setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 07:50:14 +05:30
Justin JohnandClaude Opus 5.5 aa1a6d3cbd Check the disk_allocation path before touching the session
A refused path no longer bumps the revision or marks the session dirty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:30:57 +05:30
justinjohn0306 1b99bf0e4f Fix #1224: Confined MCP: setup.disk_allocation accepts a record folder outside the automation roots 2026-10-31 13:41:03 +05:30
dotCooCoo 7dcb8daa22 Sends: a Ctrl press keeps a fine slider's value; an Alt-click reset is its own undo step
A press on a fine slider's rail with Ctrl or Command held set the value
under the pointer before the fine drag began, so the drag went on from
there. The press now leaves the value where it was.

An Alt-click on a clip effects value box right after typing in it joined
the typed edit's undo step, so one undo went back past the typed value.
The reset now starts its own undo step.
2026-10-28 20:42:44 -07:00
dotCooCoo 72d4d9d638 Clip Effects: log-taper parameter sliders use a logarithmic rail
The EQ and Dynamics sliders in the Clip Effects window now follow the
parameter's taper, as the plug-in window does, so a frequency, Q, ratio,
attack or release slider moves along a logarithmic rail.
2026-10-28 20:36:19 -07:00
dotCooCoo a64f8f22e6 Merge main into feat/plugin-parameter-default-reset 2026-10-28 16:58:06 -07:00
dotCooCoo 3d52c606ca Merge main into feat/send-fine-adjustment 2026-10-28 16:35:33 -07:00
dotCooCoo 7810959b59 Merge main into feat/plugin-parameter-fine-sliders
# Conflicts:
#	crates/ui-egui/src/dialogs.rs
2026-10-28 16:33:59 -07:00
dotCooCoo 69d336b021 Merge commit 'refs/check/bf-sc-main' into feat/strip-silence-fine-sliders
# Conflicts:
#	crates/ui-egui/src/dialogs.rs
2026-10-28 14:12:40 -07:00
lucasegenandClaude Opus 5.5 55d4a89b98 Merge upstream main into fix/toolbar-overflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:13:39 +01:00
dotCooCoo 30058888c7 Tests: give the Enter-on-Cancel bounce test its own scratch folder
It shared bounce-cancel with cancel_or_escape_stops_a_bounce_and_leaves_no_file,
so the two tests removed each other's folder when run in parallel.
2026-10-28 07:31:19 -07:00
dotCooCoo 245523a866 Bounce Mix: Cancel starts no bounce; fine adjust on more AudioSuite sliders
Enter on a focused Cancel also pressed Bounce, which started the bounce
before the Cancel check ran. The bounce now starts after that check.

The Normalize, Time Shift and Pitch Shift sliders in the AudioSuite
window move a tenth as far while Ctrl or Command is held.
2026-10-28 03:38:41 -07:00
dotCooCoo 38694924aa Tests: pressing Ctrl during a value-box drag keeps the value
The rest of the drag on the Threshold value box moves as far as a drag
with Ctrl held from the start.
2026-10-28 03:38:39 -07:00
dotCooCoo f554274864 Merge main into feat/plugin-parameter-fine-sliders 2026-10-28 01:32:16 -07:00
dotCooCoo 1480399413 Merge main into feat/strip-silence-fine-sliders 2026-10-28 01:20:19 -07:00
dotCooCoo 87345598ca Read send destinations only while the menu is open 2026-10-27 08:13:21 -07:00
dotCooCoo 1125a5f0a1 Add fine dragging and default reset to all AudioSuite sliders 2026-10-27 08:11:52 -07:00
dotCooCoo 817623090a Read send destinations only while the menu is open 2026-10-27 08:10:01 -07:00
dotCooCoo 5b604a5884 Merge main and add default reset and fine adjustment to Clip Effects gain 2026-10-27 05:35:52 -07:00
dotCooCoo cf4fe7a29b Merge main into feat/send-fine-adjustment 2026-10-26 02:27:34 -07:00
dotCooCoo 6c7491e239 Merge main into feat/send-fine-adjustment 2026-10-26 02:26:23 -07:00
lucasegenandClaude Opus 5.5 b301c7f1d2 Merge upstream main into fix/toolbar-overflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:15:48 +01:00
dotCooCoo cb8014ff9c Merge main into feat/plugin-parameter-fine-sliders 2026-10-25 21:06:43 -07:00
dotCooCoo 5f1335bf8f Merge main into feat/plugin-parameter-default-reset 2026-10-25 16:25:11 -07:00
dotCooCoo bf62aa6db7 Sends: Ctrl or Command gives fine adjustment on a send's level, its sliders and the pan knobs
A vertical drag on a send's level moved it finely only with Shift held,
and the Level and Pan sliders of a send's options menu and the pan knobs
had no fine adjustment. Ctrl (Command on a Mac) now gives the send level
drag the same fine step as Shift, and Shift keeps working. The options
menu's Level and Pan sliders use widgets::FineSlider, so they move a
tenth as far while Ctrl or Command is held. FineSlider gains a suffix
option so the Level box keeps its " dB". widgets::pan_knob turns a tenth
as far while Ctrl or Command is held, in the Send window and on the
tracks.
2026-10-25 16:17:17 -07:00
dotCooCoo 92a5ce9a29 Dialogs: Enter on a focused Cancel or Don't Save no longer runs OK
Enter on a focused button clicks it and also presses the dialog's OK.
In Strip Silence, Enter on Cancel closed the dialog and still stripped
the selected clips. Cancel and Escape now drop the command and the save
that OK asked for, in every dialog. In Unsaved Changes, Enter on a
focused Don't Save closes without saving instead of opening Save.
2026-10-25 13:19:11 -07:00
dotCooCoo 8cec3da577 Merge main into feat/plugin-parameter-fine-sliders 2026-10-25 13:12:59 -07:00
dotCooCoo df1d064e5a Merge main into feat/plugin-parameter-fine-sliders 2026-10-25 09:43:29 -07:00
dotCooCoo eaf0634689 Merge commit '9774947' into feat/plugin-parameter-fine-sliders
# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/widgets.rs
2026-10-25 09:43:11 -07:00
lucasegenandClaude Opus 5.5 5787f4dc3b Merge upstream main into fix/toolbar-overflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:38:17 +01:00
dotCooCoo 9774947acf Merge main into feat/strip-silence-fine-sliders
ROADMAP.md keeps both the Strip Silence fine adjustment entry and the
Auto Pan stereo balance entry.
2026-10-25 09:09:44 -07:00
dotCooCoo 82e3ce059b Merge main into feat/strip-silence-fine-sliders
ROADMAP.md: the header, the progress log and the revision table keep
both the Strip Silence fine adjustment entry and main's entries.

widgets::fine_slider calls Ui::scope_id, which egui 0.37 uses in
place of the deprecated Ui::id, as #1063 does elsewhere.
2026-10-25 08:49:50 -07:00
dotCooCoo 6287acf019 Plugins: FineSlider::default_value describes what a held Alt does
While Alt is held, a drag leaves the value where it is, and an Alt-click
on the value box does not open it for typing. An Alt-click on the rail
sets the default.
2026-10-25 08:43:08 -07:00
dotCooCoo a90f96867e Merge main into feat/plugin-parameter-default-reset
ROADMAP.md keeps both sides' progress log lines and revision rows. For egui
0.37, FineSlider takes its id from Ui::scope_id, and the plugin slider tests
look up the plugin window and the AudioSuite parameters with Id::unique, as
main's own code does.
2026-10-25 08:34:06 -07:00
dotCooCoo 5c42c6c2f7 Plugins: Alt-click returns a parameter to its default value
An Alt-click (Option-click on a Mac) on a parameter in the plugin window,
the Clip Effects window or an AudioSuite plugin's window sets the
parameter's default value, as an Alt-click sets a fader to 0 dB. It works
on a slider, on a slider's value box and on a choice list. The click on a
value box does not open it for typing, and the click on a choice list does
not open the list. In the plugin window and the Clip Effects window the
reset runs the same command as a drag, so it is one undo step. While Alt
is held, a drag on one of these sliders leaves the value where it is.

widgets::FineSlider has a new default_value option for this.
2026-10-24 21:12:23 -07:00
dotCooCoo a9ef108e61 Plugins: parameter sliders move a tenth as far while Ctrl or Command is held
While Ctrl (Command on a Mac) is held, a drag on a parameter slider in
the plugin window, the Clip Effects window or an AudioSuite plugin's
window moves the value a tenth as far as the same drag without the key,
as the Strip Silence sliders do. A logarithmic slider moves a tenth as
far along the slider, and a whole-number slider, such as the Sampler's
Root Note, stays on whole numbers. A drag without the key works as
before.

widgets::FineSlider is a new builder with the slider options these
windows use (no value box, logarithmic, whole numbers, a salt for
unlabeled sliders); widgets::fine_slider keeps its signature and calls
it.
2026-10-24 20:46:54 -07:00
dotCooCoo afc93c151b Strip Silence: the sliders move a tenth as far while Ctrl or Command is held
While Ctrl (Command on a Mac) is held, a drag on one of the four Strip
Silence sliders moves the value a tenth as far as the same drag
without the key, on the slider and on its value box. Pressing or
releasing the key during a drag leaves the value where it is, and the
drag goes on from there. Releasing the mouse button leaves the value
too. A drag without the key works as before.

The new widgets::fine_slider uses the modifier test and the tenth of
widgets::fader. Threshold and Clip Start Pad show one decimal place,
and a drag on the slider during which the key was held rounds the
value to the places the box shows.
2026-10-24 19:28:33 -07:00
lucasegenandClaude Opus 5.5 2f34f0f501 Allow the toolbar fit test's panel field to go unread off macOS
Only the macOS-only fit test reads it, so clippy failed on Linux with dead_code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 00:06:45 +02:00
lucasegenandClaude Opus 5.5 0a0b451db0 Check the 1470-point toolbar fit on macOS only
The window of #704 is a Mac's, drawn in the Mac's UI font. Linux draws the
toolbar in DejaVu Sans, which is wider, and there it scrolls at 1470 points:
CI failed on that. The narrow-window scroll bar test still runs everywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 00:01:12 +02:00
lucasegenandClaude Opus 5.5 5f56c9f103 Merge upstream main into fix/toolbar-overflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:50:38 +02:00
lucasegenandClaude Opus 5.5 f2dfd76781 Check the toolbar scroll bar against all its content, not only the groups
The output meter is not a group, so the narrow-window test never checked that
the scroll bar keeps clear of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 07:16:32 +02:00
lucasegenandClaude Opus 5.5 9b3b70ba57 Merge upstream main into fix/toolbar-overflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 07:02:56 +02:00
lucasegenandClaude Opus 5.5 c4037f27ab Count a full-width scroll bar track in the toolbar fit test
Review feedback: the test skipped every shape as wide as the toolbar,
so a full-width scroll bar track could be painted without being counted.
It now skips only full-width shapes as tall as the toolbar (the panel),
and leaves full-width shapes out of the content's right edge, which a
border's half-pixel stroke would otherwise push past the window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 00:36:09 +02:00
lucasegenandClaude Sonnet 5.5 8b6d9c71fb Move the new tests into the crate's single test binary
Upstream now builds each crate's integration tests as one binary (tests/it/main.rs, one module per file). The tests this branch adds move there too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:21:57 +02:00
lucasegen f804014297 Merge upstream main into fix/toolbar-overflow 2026-10-23 22:20:55 +02:00
lucasegenandClaude Opus 5.5 3d06c6e5b8 Fit the Edit toolbar in a 13-inch MacBook window and keep its scroll bar off the controls
At 1470 x 956 pt and 100 % scale the toolbar was about 20 pt wider than the
window, so it scrolled sideways and its floating scroll bar covered the
bottom row of the counter and transport groups (#704).

- Drop the 32 pt of dead space at the right of the tool group and the 5 pt
  left over in the transport group: every section now fits in 1470 pt.
- Use a solid scroll bar so a narrower window gets a strip of its own under
  the groups (the panel height already leaves room) instead of an overlay.
- Add a regression test: no scroll bar at 1470 pt, and at 1280 pt the bar
  does not intersect any group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:08:14 +02:00
MarekSpodBiedry 222f1aef35 Bounce: report the levels of the clipped samples that are written (#717) 2026-10-18 01:03:42 +02:00
154 changed files with 14047 additions and 1290 deletions
+15 -5
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",
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -95,7 +97,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+1 -1
View File
@@ -214,7 +214,7 @@ jobs:
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
+71
View File
@@ -0,0 +1,71 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [SoundCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
if: >-
github.repository == 'storytold/soundcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/soundcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/soundcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/soundcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/soundcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'soundcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+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.
+7 -4
View File
@@ -1,8 +1,10 @@
name: SoundCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
# A later explicit opt-in may add a cadence (and a reviewed dispatcher with it).
# Runs automatically on the reviewed nightly schedule and for supervised manual runs
# by the reviewed manual actors.
on:
schedule:
- cron: '30 5 * * *'
workflow_dispatch:
permissions:
@@ -22,9 +24,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 +34,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"]'
+1
View File
@@ -37,6 +37,7 @@ jobs:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: soundcraft
app-title: SoundCraft
macos-runner: macos-15
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+14 -3
View File
@@ -21,9 +21,18 @@ are bundled.
## Fonts
SoundCraft bundles no font files. It uses the default fonts shipped inside the `egui` crate
(Ubuntu-Light: Ubuntu Font Licence 1.0; Hack: MIT; Noto Emoji: OFL-1.1; emoji-icon-font: MIT)
and, at runtime, the operating system's own UI fonts when available (never redistributed).
SoundCraft ships one font file, for the web build only. Everything else is the default fonts
shipped inside the `egui` crate (Ubuntu-Light: Ubuntu Font Licence 1.0; Hack: MIT; Noto Emoji:
OFL-1.1; emoji-icon-font: MIT) and, at runtime, the operating system's own UI fonts when available
(never redistributed).
The browser cannot reach the operating system's fonts, and egui's bundled faces carry no Han
glyphs, so a Simplified Chinese interface would draw boxes. `assets/fonts/NotoSansSC-SoundCraftSubset.ttf`
is therefore compiled into the web build alone (`crates/ui-egui/src/fonts.rs`): a subset of the
Noto Sans SC variable font, pinned at weight 400 and reduced with fontTools to the UI glyph set
(the zh-Hans catalog, GB 2312 level-1 common characters, ASCII, Latin-1 letters and the UI's
punctuation, arrows and triangles; about 1.1 MiB). It is SIL Open Font License 1.1 — see
`assets/fonts/OFL.txt`. Native builds never embed it and keep drawing with system fonts.
## Bundled egui font icons
@@ -47,6 +56,8 @@ here. The subset uses default_fonts; the parent face uses monochrome_emoji_fonts
| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand assets | ArtCraft brand terms |
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand assets | ArtCraft brand terms |
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand assets | ArtCraft brand terms |
| `assets/fonts/NotoSansSC-SoundCraftSubset.ttf` | Google LLC / Noto Project Authors | Noto Sans SC variable font, subset to the UI glyph set and pinned at weight 400 (generated with fontTools by `docs/i18n/tools/subset_web_font.py`) | SIL Open Font License 1.1 (`assets/fonts/OFL.txt`) |
| `assets/fonts/OFL.txt` | Noto Project Authors / SIL | SIL Open Font License 1.1 text | OFL-1.1 |
| `assets/app-icon/icon.svg` | SoundCraft contributors | original (hand-placed SVG paths; placeholder app icon) | MIT OR Apache-2.0 |
| `packaging/macos/dmg/` (all files) | @XusBadia | original (macOS DMG window background and layout, from the app icon; see `packaging/macos/dmg/README.md`) | MIT OR Apache-2.0 |
| `assets/app-icon/soundcraft-1024.png` | SoundCraft contributors | original, rendered from `icon.svg` | MIT OR Apache-2.0 |
Generated
+39 -18
View File
@@ -1478,6 +1478,14 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -1822,6 +1830,17 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2bfc45c49378effb801c6433758fb5aaa5d7808e#2bfc45c49378effb801c6433758fb5aaa5d7808e"
dependencies = [
"js-sys",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
]
[[package]]
name = "craft-win32"
version = "0.1.0"
@@ -5960,11 +5979,12 @@ dependencies = [
[[package]]
name = "soundcraft"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"chrono",
"clap",
"craft-audio",
"craft-nightly",
"craft-update",
"eframe",
"egui",
@@ -5985,7 +6005,7 @@ dependencies = [
[[package]]
name = "soundcraft-au-host"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"log",
"serde",
@@ -5995,7 +6015,7 @@ dependencies = [
[[package]]
name = "soundcraft-automation"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"clap",
"craft-audio",
@@ -6009,7 +6029,7 @@ dependencies = [
[[package]]
name = "soundcraft-clap-host"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"clap-sys",
"libc",
@@ -6024,7 +6044,7 @@ dependencies = [
[[package]]
name = "soundcraft-cli"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"clap",
"clap_complete",
@@ -6042,7 +6062,7 @@ dependencies = [
[[package]]
name = "soundcraft-dsp"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"log",
"proptest",
@@ -6053,7 +6073,7 @@ dependencies = [
[[package]]
name = "soundcraft-engine"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"cfb",
"craft-aaf",
@@ -6083,7 +6103,7 @@ dependencies = [
[[package]]
name = "soundcraft-interchange"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"cfb",
"craft-aaf",
@@ -6096,7 +6116,7 @@ dependencies = [
[[package]]
name = "soundcraft-midi"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-midi",
"proptest",
@@ -6104,7 +6124,7 @@ dependencies = [
[[package]]
name = "soundcraft-mix"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-audio",
"log",
@@ -6120,14 +6140,14 @@ dependencies = [
[[package]]
name = "soundcraft-model"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-scraft-format",
]
[[package]]
name = "soundcraft-playback"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"cpal",
"craft-audio",
@@ -6143,14 +6163,14 @@ dependencies = [
[[package]]
name = "soundcraft-time"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-time",
]
[[package]]
name = "soundcraft-ui-egui"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-audio",
"craft-behavior",
@@ -6186,7 +6206,7 @@ dependencies = [
[[package]]
name = "soundcraft-video"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-media",
"craft-video",
@@ -6197,7 +6217,7 @@ dependencies = [
[[package]]
name = "soundcraft-vst3-host"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"libc",
"libloading 0.9.0",
@@ -6215,9 +6235,10 @@ dependencies = [
[[package]]
name = "soundcraft-web"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-audio",
"craft-web-api",
"eframe",
"egui",
"js-sys",
@@ -8138,7 +8159,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"serde_json",
]
+2 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.20.1"
version = "0.21.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -79,6 +79,7 @@ craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/c
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
+5 -1
View File
@@ -216,7 +216,9 @@ The realtime audio thread never writes a record itself: the logger keeps the fir
Everything you can click is also a command with an id and JSON parameters, and the same commands
are reachable from the menus, the keyboard, the command line, a JSON control channel and an
[MCP](https://modelcontextprotocol.io) server. Programmatic calls never open dialogs, and
`session.inspect` reports exactly what changed, so an agent can check its own work.
`session.inspect` returns the session's current state (tracks, clips, mixer, markers) and the
last undo and redo step labels, so an agent can check its own work by comparing inspections from
before and after.
```sh
# Headless: load the demo, turn the kick down, add an EQ, bounce.
@@ -351,6 +353,8 @@ RISC-V (riscv64) packages are `soundcraft-<ver>-linux-riscv64.deb`,
### FreeBSD
Current prebuilt FreeBSD release packages require FreeBSD 15.1 or later. They are built using the shared FreeBSD 15.1-STABLE release target; older FreeBSD releases are not supported by these binaries.
| Build | File |
|---|---|
| x86_64 | `soundcraft-<ver>-freebsd-x86_64.tar.gz` |
+15 -6
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows)
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (long takes kept whole; previously minor: strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-27 · **Change:** trivial (Languages table: Spanish full; previously trivial: French and Spanish partial; previously minor: long takes kept whole; previously minor: room tone fill, strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1
SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with
Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is
@@ -52,7 +52,7 @@ measures readiness and adds hardware, localization and field bug reports.
| UI/UX fidelity | ~55 % | 60–100 | [ui-parity.md](docs/ui-parity.md) |
| File formats | ~40 % | 70–120 | [file-format-parity.md](docs/file-format-parity.md) |
| Hardware (interfaces, MIDI, surfaces, sync) | ~12 % | 110–180 | [hardware-parity.md](docs/hardware-parity.md) |
| Localization | ~12 % (1 of Pro Tools' 8 languages; English and pt-BR fixed UI strings, no CJK/RTL font fallback or native review) | 70–110 | [localization-parity.md](docs/localization-parity.md) |
| Localization | ~19 % (2 of Pro Tools' 8 languages; English, pt-BR and zh-Hans fixed UI strings, with a CJK fallback and a web Han font; no RTL or complex-script shaping, no native review) | 55–90 | [localization-parity.md](docs/localization-parity.md) |
| Performance | ~35 % (unmeasured) | 40–70 | [hardware-parity.md](docs/hardware-parity.md#performance) |
| Stability | ~45 % | 50–80 | [gaps.md](docs/gaps.md) |
| Platforms | ~65 % (5 platforms built, macOS exercised) | 20–40 | [gaps.md](docs/gaps.md) |
@@ -86,11 +86,11 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
| Language | Code | Status | Translated |
|---|---|---|---:|
| English | en | full | 100 % |
| Simplified Chinese | zh-Hans | none | 0 % |
| Spanish | es | none (PR #143 open) | 0 % |
| Simplified Chinese | zh-Hans | full — 100 % of fixed UI strings; CJK fallback, web Han font, tests pass | 100 % (native-speaker review pending) |
| Spanish | es | full — 100 % of fixed UI strings and engine errors; tests pass | 100 % (native-speaker review done) |
| Hindi | hi | none | 0 % |
| Arabic | ar | none | 0 % |
| French | fr | none (PR #143 open) | 0 % |
| French | fr | partial — catalog of 1,368 strings, the rest in English | ≈ 62 % |
| Portuguese (Brazil) | pt-BR | full — 100 % of fixed UI strings; tests pass | 100 % (native-speaker review pending) |
| Indonesian | id | none | 0 % |
| Japanese | ja | none | 0 % |
@@ -98,7 +98,7 @@ Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#f
| Korean | ko | none | 0 % |
| Vietnamese | vi | none | 0 % |
Other languages shipped: 0 complete. Brazilian Portuguese covers the fixed UI strings (100 %), with native-speaker review, CJK/RTL font fallbacks and script shaping still pending. Detail: [localization-parity.md](docs/localization-parity.md).
Other languages shipped: Spanish complete (fixed UI strings and engine errors, native-speaker review). French is partial (≈ 62 %). Brazilian Portuguese and Simplified Chinese cover the fixed UI strings (100 %); both still need native-speaker review. CJK fallbacks ship for Chinese, while RTL and complex-script shaping are still missing. Detail: [localization-parity.md](docs/localization-parity.md).
## Upcoming
@@ -125,7 +125,9 @@ mutated and truncated movies. Field reports from the first public week are track
## Progress log
- **2026-11-18 (MIDI input):** MIDI input devices: keyboards play record-enabled and input-monitored MIDI and instrument tracks live and are recorded into MIDI clips, with a device and channel choice per track. The device switches are in the MIDI inputs section of Setup › Playback Engine (Setup › MIDI › MIDI Input Devices opens the same window) and are kept in the app preferences, per computer, not in the session. Controllers, pitch bend and aftertouch reach the instrument live; a pitch held on two devices or channels sounds until both release it; a full input queue releases the notes of its device and marks the take incomplete. On Linux, live play was checked with a hardware keyboard (Akai MPK mini 3) and recording with a virtual one; macOS and Windows are type-checked only, and there is no MIDI input on FreeBSD or the web. Guide: `docs/midi-input.md`. No readiness percentage change until that is measured.
- **2026-11-15 (27 October–15 November recap):** Releases v0.14.0 through v0.20.1; clips draw as a small name pill with shared cut seams, alternate playlist lanes draw on screen and rating stars follow their own switch; the Edit window's I/O column sets volume and pan; edit modes, playback and record colours; Grid and Nudge time scales; a new-tracks workflow; Smart Tool/Pencil shortcuts, held zoom keys, track-colour Color Palette, Sub-counter format menu, searchable I/O menus, scrolling menus, distinct link icons and Insertion Follows Playback; folder-track indentation, stereo input pairs, sends that open their Send window, Alt-click marker deletion and selection-aware Clip menus; the playback engine applies the chosen device and buffer (#1077) and volume automation is read at every sample (#1355); a 256 MiB session cap with a tree-free parser (#892), overflow and bounds hardening across H.264, FLAC, WAV, CAF, tempo, grid, automation and timecode, MIDI tempo/track-flood limits (#890), bounded command journal and score output (#995, #993), clip-FX gain and send-level clamps (#884), clip-group path-traversal rejection and VST3 multi-out instruments with up to 64 buses; MIDI export keeps only the notes a trimmed clip plays, key signatures follow Insert/Cut Time, score export keeps short-bar notes and strips XML-forbidden characters, and WAV bounces carry BWF timecode; Enter presses the default button only without button focus (#1243), the 1/4t quantize grid (#1453), VST3 scan paths (#1450) and portable.txt (#1341) are fixed, CLAP resets keep note-offs (#1464, #1470) and hosted plugins learn when they render offline; the #1144 demo benchmark recorded about a 20 % faster mix bounce on its stated setup; shared craft-update with Flatpak self-update and Linux signing fixes, and a nightly release dry run (#1508); session format and H.264/ProRes codecs move to craft-libs, and audio formats to craft-audio; commands --json (#744), malformed control requests close the connection and Import Audio Browse selects several files (#1089). This is a historical summary, not a new measurement of readiness.
- **2026-11-14:** AAF import supports a strict CompositionMob SourceClip/Filler subset with external mono/stereo PCM WAV media, editable clips and handles, relink and absolute or relative timecode mapping. The reader shares cached object properties, caps retained property data at 128 MiB and rejects duplicate local references before expansion. AAF export, OMF and `.ptx` remain missing. No readiness percentage change.
- **2026-11-12:** Edit › Room Tone fills gaps with recorded silence instead of digital silence, beyond Pro Tools' own menus. Set Room Tone (`edit.room_tone_set`) takes the selected clip, or the selected part of it, as the session's room tone, and the session file keeps it. Fill Gaps with Room Tone (`edit.room_tone_fill`) puts ordinary, editable clips of that tone in every empty stretch of the selection on the selected audio tracks. When a gap is longer than the tone, the clips overlap with equal-power crossfades (10 ms by default) so the background keeps its level, and each gap's edges get a 2 ms fade so it doesn't click. Clear Room Tone forgets the tone and keeps the clips. A synthesised tone that doesn't repeat comes later. No readiness percentage change.
- **2026-11-09:** A built-in Frequency Shifter (`freq_shifter`) moves every frequency in the signal by the same number of hertz, from 0.01 Hz to 5 kHz: up, down, both ways at once, or down on the left and up on the right of a stereo track. The unwanted sideband stays at least 100 dB down from 20 Hz to 20 Hz below Nyquist at 44.1 to 96 kHz. Feedback sends the output round again for a trail of further shifts, Mix blends in the dry signal, and every change glides without a click. No readiness percentage change.
- **2026-11-08:** Command-click near an existing automation breakpoint keeps that point as the click target with every active tool, and existing fade and clip-gain controls retain their normal priority. Empty automation space shows a crosshair and an insertion hint while Command is held. The active tool's drag gestures stay unchanged. No readiness percentage change.
- **2026-11-05:** Command-click in an automation lane adds a point at the clicked time and value with the current editing tool (#1394), using the existing Pencil mapping. Command-click preserves the existing selection and also works on the fallback volume lanes of Master, Aux and VCA tracks. Plain clicks and clip contents stay unchanged, and one Undo removes the new point. No readiness percentage change.
@@ -133,10 +135,12 @@ mutated and truncated movies. Field reports from the first public week are track
- **2026-10-27 (plugin editors on Linux):** VST3 editors and embedded CLAP editors open in a SoundCraft X11 host window on Linux and the BSDs (XWayland on Wayland desktops), resized on request and closed from its title bar; the host run loop (VST3 `Linux::IRunLoop`, CLAP `timer-support` and `posix-fd-support`) lets X11 editors read their display connection and repaint. Verified with Graillon 3 and Surge XT Effects (JUCE) in both formats (#527). No readiness percentage change.
- **2026-10-25:** Alt+Shift+E (`view.zoom_toggle_cancel`) and an Alt-click on the Zoom Toggle button cancel Zoom Toggle and keep the current view: the zoom, the scroll and the track heights stay as they are, and the button is no longer lit. The next Zoom Toggle zooms in from that view and goes back to it. No readiness percentage change.
- **2026-10-25:** Tracks and Groups and the Clip List sit in dock columns that run the Edit window's full height at its left and right edges, with the MIDI Editor under the session view between them; Mix docks Tracks and Groups at its left edge. A panel dragged onto a dock group joins it as a tab, stacks above or below it, or makes a new column; one dragged to an empty window edge makes a dock there. A list with no saved place reopens in its dock, and makes the dock again when it is gone. Preferences and window configurations saved with the earlier split-frame layouts load with the new default layouts and keep their other settings. No readiness percentage change.
- **2026-10-25:** A vertical drag on a send's level moves it as finely with Ctrl (Command on a Mac) held as with Shift, as a fader's Ctrl-drag does. The Level and Pan sliders of a send's options menu, the Send window's pan knob and the tracks' pan knobs move a tenth as far for the same drag while Ctrl (Command on a Mac) is held. No readiness percentage change.
- **2026-10-25:** Auto Pan moves the balance of a stereo track: the left channel's level falls as the position moves right and the right channel's as it moves left, at constant power, and each channel stays on its own side. At the center the track passes unchanged, so a wide or out-of-phase stereo image keeps its width, and the envelope follower follows the louder channel. No readiness percentage change.
- **2026-10-24:** An Alt-click (Option-click on a Mac) on a parameter in the plugin window, the Clip Effects window or an AudioSuite plugin's window returns it to its default value, on a slider or a slider's value box, and in the plugin window on a choice list too, as an Alt-click returns a fader to 0 dB. In the plugin window and the Clip Effects window the reset is one undo step. While Alt is held, a drag on a slider leaves the value where it is. No readiness percentage change.
- **2026-10-24:** The parameter sliders of the plugin window, the Clip Effects window and AudioSuite plugins move a tenth as far for the same drag while Ctrl (Command on a Mac) is held, as the Strip Silence sliders do. Logarithmic sliders move a tenth as far along the slider, and whole-number sliders stay on whole numbers. No readiness percentage change.
- **2026-10-24:** The Strip Silence window's four sliders move a tenth as far for the same drag while Ctrl (Command on a Mac) is held, on the slider and on its value box. Pressing or releasing the key during a drag leaves the value where it is. The Threshold and Clip Start Pad boxes show one decimal place. No readiness percentage change.
- **2026-10-24:** Clip › Unloop… opens the Unloop dialog. Remove deletes the loop iterations and keeps the source clip, and Flatten keeps each loop iteration as its own clip. No readiness percentage change.
- **2026-10-24:** Clip List › Auto Rename (`clip.auto_rename`) sets the names that editing gives the clips it separates from the selected clips: a name, a starting number, a number of places (zeros before the number) and a suffix. The piece after each cut takes the next name, the piece before it keeps its name, and all the pieces count up one number sequence. Pieces that Strip Silence names with its own Rename fields, or removes, take no Auto Rename name. Copied clips keep their scheme when they are pasted, saved sessions hold the schemes, and Import Session Data brings them along. No readiness percentage change.
- **2026-10-24:** While the Strip Silence window is open, the Edit window draws a rectangle around each range that Strip would keep on the selected tracks, padded by Clip Start Pad and Clip End Pad, and the rectangles follow the sliders as they move. They are removed when the window closes. `edit.strip_silence_preview` returns the same ranges without changing the session. No readiness percentage change.
- **2026-10-24:** The Strip Silence window has a Rename button. It opens Rename Selected Clips, where a name, a starting number, a count of zeros and a suffix set the names of the clips that Strip, Extract and Separate leave in the selection (for example SFX023.Reel1, SFX024.Reel1). The app keeps the scheme for later uses of Strip Silence until the app quits, or until Clear and then OK empty it. No readiness percentage change.
@@ -189,7 +193,12 @@ mutated and truncated movies. Field reports from the first public week are track
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | trivial | Languages table: Spanish catalog complete with native-speaker review. Estimates unchanged |
| 2026-11-24 | trivial | Languages table: French and Spanish catalogs, partial (≈ 62 %), PR #143. Estimates unchanged |
| 2026-11-22 | minor | Languages table: Simplified Chinese (zh-Hans) covers the fixed UI strings through the `locales/zh-Hans` catalog, with a Han system-font fallback and an OFL web subset; needs native review. Localization estimate 70–110 → 55–90 h |
| 2026-11-15 | minor | Historical 27 October–15 November progress recap through v0.20.1; menu breadth, readiness and effort were not re-measured |
| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged |
| 2026-11-12 | trivial | Progress log: room tone fill; readiness estimates unchanged |
| 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged |
| 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged |
| 2026-11-05 | trivial | Progress log: Command-click adds an undoable automation point (#1394); readiness estimates unchanged |
+2 -1
View File
@@ -27,6 +27,7 @@ fn is_control_method(method: &str) -> bool {
| "ui.key"
| "ui.text"
| "ui.screenshot"
| "audio.health"
| "app.quit"
)
}
@@ -67,7 +68,7 @@ mod tests {
assert_eq!(m, "engine.execute");
let (m, _) = app_request("track.new", json!({}));
assert_eq!(m, "engine.execute");
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "audio.health", "app.quit"] {
assert_eq!(app_request(method, json!({})).0, method);
}
for (method, params) in [
+2
View File
@@ -17,6 +17,8 @@ path = "src/main.rs"
soundcraft-engine = { workspace = true }
craft-audio.workspace = true
soundcraft-ui-egui.workspace = true
# The page command API (storytold/craft-libs#413): window.soundcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2bfc45c49378effb801c6433758fb5aaa5d7808e", version = "0.1.0" }
soundcraft-playback = { workspace = true }
soundcraft-model = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
+79
View File
@@ -0,0 +1,79 @@
//! `window.soundcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
//!
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
//! `screenshot`, as promises with a timeout). This module is SoundCraft's part: a [`Request`] that
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
//! reply. SoundCraft's control request has no abandon state, so a call the page gave up on still runs
//! when the app reaches it, as it does for a desktop client that timed out.
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError, TrySendError, sync_channel};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use serde_json::{Value, json};
use soundcraft_ui_egui::ControlRequest;
use wasm_bindgen_futures::JsFuture;
/// The app id in `window.<app>`.
const APP: &str = "soundcraft";
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
/// How many control requests may wait for the app at once. `craft-web-api` already refuses calls past its own
/// in-flight limit; this bounds the app's queue too, so a flood of calls can't grow it without limit.
const QUEUE: usize = 64;
/// Put `window.soundcraft` on the page and return the queue the app drains each frame (hand it to
/// `SoundApp::with_control`). An existing `window.soundcraft` keeps the functions it already has.
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = sync_channel::<ControlRequest>(QUEUE);
let request: Request = Rc::new(move |method, params| {
let (control, reply) = ControlRequest::new(method, params);
if let Err(refused) = queue.try_send(control) {
let error = match refused {
TrySendError::Full(_) => format!("soundcraft is busy: {QUEUE} requests are already waiting for the app"),
TrySendError::Disconnected(_) => "the app is not running".to_string(),
};
return Box::pin(async move { json!({"ok": false, "error": error}) });
}
ctx.request_repaint();
Box::pin(wait(reply))
});
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
log::warn!("couldn't install window.{APP}: {e:?}");
}
requests
}
/// The app's reply, polled about once a frame.
async fn wait(reply: Receiver<Value>) -> Value {
loop {
match reply.try_recv() {
Ok(reply) => return reply,
Err(TryRecvError::Empty) => {
if !sleep(POLL_MS).await {
return json!({"ok": false, "error": "this page has no timer to wait for the app with"});
}
}
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
}
}
}
async fn sleep(ms: i32) -> bool {
// `false` when this page has no timer to wait with (no window, or the timer is refused): the caller ends the
// call with an error instead of going round again at once.
let timer = std::cell::Cell::new(false);
let promise = js_sys::Promise::new(&mut |resolve, _| {
let set = web_sys::window().is_some_and(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms).is_ok());
timer.set(set);
if !set {
let _ = resolve.call0(&wasm_bindgen::JsValue::UNDEFINED);
}
});
let _ = JsFuture::from(promise).await;
timer.get()
}
+4 -1
View File
@@ -6,7 +6,8 @@
//! from this directory (output in `dist/web`).
//!
//! Differences from the desktop app:
//! - no TCP control channel (browsers can't listen on sockets);
//! - no TCP control channel (browsers can't listen on sockets); `window.soundcraft` (`api`) drives the
//! same control channel from the page instead;
//! - no file system: File > Open Session…, Import > Audio…/MIDI… and files dropped on the page are
//! read as bytes through the browser's file picker; a session is saved as ONE bundle file
//! (`<name>.scraftz`: the `.scraft` and its `Audio Files/`), and every save or export arrives as a
@@ -18,6 +19,8 @@
//! empty session instead of the demo.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(target_arch = "wasm32")]
mod web;
+1 -1
View File
@@ -52,7 +52,7 @@ pub fn start() {
soundcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let engine = if query().contains("empty") { Engine::default() } else { soundcraft_engine::demo::demo_engine() };
let player = soundcraft_playback::Player::new(Arc::new(engine.session().clone()));
let app = SoundApp::new(engine, Some(player), Services::default());
let app = SoundApp::new(engine, Some(player), Services::default()).with_control(crate::api::install(cc.egui_ctx.clone()));
Ok(Box::new(WebShell { app, inbox: Rc::default(), samples: Rc::default() }))
}),
)
+129
View File
@@ -0,0 +1,129 @@
// Real-browser check of window.soundcraft (the page command API from craft-web-api): serve a built
// copy of the web app, load it in headless Chromium and drive every function the crate installs.
//
// Usage, from a folder where Playwright is installed (`npm i playwright`, then `npx playwright install chromium`):
// node <repo>/apps/soundcraft-web/tests/page-api.mjs <site folder>
// The site folder is a built copy of the web app: `trunk build --release` in apps/soundcraft-web
// (dist/web), or the unpacked `packaging/web/package.sh` zip. Exits non-zero on the first failed check.
//
// Not repeated here: the 30 s request timeout belongs to craft-web-api and is covered by that crate's own
// tests. The limit on calls waiting for the app (64) is exercised below: it needs a craft-web-api that has it
// (craft-libs#733) and the app's own bounded queue.
import { createRequire } from 'node:module'
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import assert from 'node:assert/strict'
const dir = process.argv[2]
if (!dir) { console.error('usage: node page-api.mjs <site folder>'); process.exit(2) }
const cwd = path.resolve(process.cwd())
const tmp = path.resolve(os.tmpdir())
const rootDir = path.resolve(cwd, dir)
const inAllowedRoot =
rootDir === cwd ||
rootDir.startsWith(cwd + path.sep) ||
rootDir === tmp ||
rootDir.startsWith(tmp + path.sep)
if (!inAllowedRoot) {
console.error('site folder must be inside the current working directory or system temp directory')
process.exit(2)
}
const rootPrefix = rootDir.endsWith(path.sep) ? rootDir : rootDir + path.sep
const require = createRequire(path.join(process.cwd(), 'noop.js'))
const { chromium } = (() => { try { return require('playwright') } catch { return require('@playwright/test') } })()
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png' }
const server = http.createServer(async (req, res) => {
const route = decodeURIComponent(req.url.split('?')[0])
const relPath = (route === '/' ? 'index.html' : route).replace(/^\/+/, '')
const file = path.resolve(rootDir, relPath)
if (!file.startsWith(rootPrefix)) {
res.writeHead(403)
res.end()
return
}
try {
const body = await readFile(file)
res.writeHead(200, { 'content-type': types[path.extname(file)] || 'application/octet-stream' })
res.end(body)
} catch { res.writeHead(404); res.end() }
})
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
const origin = `http://127.0.0.1:${server.address().port}`
const browser = await chromium.launch({ headless: true, args: ['--disable-gpu'] })
try {
const page = await (await browser.newContext({ viewport: { width: 1280, height: 900 } })).newPage()
const errors = []
page.on('pageerror', (e) => errors.push(e.message))
// ?webgl forces the WebGL2 backend: headless Chromium has no WebGPU adapter.
await page.goto(`${origin}/?webgl`)
await page.locator('canvas').first().waitFor({ timeout: 180_000 })
await page.waitForFunction(() => window.soundcraft && typeof window.soundcraft.request === 'function', null, { timeout: 180_000 })
const names = await page.evaluate(() => Object.keys(window.soundcraft).sort((a, b) => a.localeCompare(b)))
for (const f of ['request', 'execute', 'commands', 'docInspect', 'uiInspect', 'screenshot']) {
assert(names.includes(f), `window.soundcraft.${f} is installed (found: ${names.join(' ')})`)
}
// A call that rejects is reported, not thrown, so each check can look at the error.
const call = (fn, ...args) => page.evaluate(async ([fn, args]) => {
try { return { ok: true, value: await window.soundcraft[fn](...args) } }
catch (e) { return { ok: false, error: String((e && e.message) || e), isError: e instanceof Error } }
}, [fn, args])
const commands = await call('commands')
assert(commands.ok && Array.isArray(commands.value) && commands.value.length > 0, `commands() lists the commands: ${JSON.stringify(commands).slice(0, 200)}`)
assert(commands.value.some((c) => c.id === 'track.new'), 'commands() includes track.new')
const doc = await call('docInspect')
assert(doc.ok && typeof doc.value === 'object', `docInspect() resolves with an object: ${JSON.stringify(doc).slice(0, 200)}`)
const ui = await call('uiInspect')
assert(ui.ok && typeof ui.value === 'object', `uiInspect() resolves with an object: ${JSON.stringify(ui).slice(0, 200)}`)
// execute changes the session, and docInspect shows it.
const docBefore = await call('docInspect')
assert(docBefore.ok, `docInspect() resolves before execute: ${JSON.stringify(docBefore).slice(0, 200)}`)
const ran = await call('execute', 'track.new', {})
assert(ran.ok, `execute('track.new') resolves: ${JSON.stringify(ran).slice(0, 300)}`)
const docAfter = await call('docInspect')
assert(docAfter.ok, `docInspect() resolves after execute: ${JSON.stringify(docAfter).slice(0, 200)}`)
assert.notEqual(JSON.stringify(docBefore.value), JSON.stringify(docAfter.value), 'docInspect() changes after execute(track.new)')
// Failures reject with an Error that names what went wrong.
const unknownCommand = await call('execute', 'no.such.command', {})
assert(!unknownCommand.ok && unknownCommand.isError && unknownCommand.error.includes('no.such.command'), `execute of an unknown command rejects with an Error naming it: ${JSON.stringify(unknownCommand)}`)
const unknownMethod = await call('request', 'no.such.method', {})
assert(!unknownMethod.ok && unknownMethod.isError && unknownMethod.error.includes('no.such.method'), `an unknown method rejects with an Error naming it: ${JSON.stringify(unknownMethod)}`)
const shot = await call('screenshot')
assert(shot.ok, `screenshot() resolves: ${JSON.stringify(shot).slice(0, 200)}`)
const data = shot.value && shot.value.data
assert(typeof data === 'string' && data.length > 1000, 'screenshot() carries base64 data')
assert.equal(Buffer.from(data, 'base64').subarray(1, 4).toString(), 'PNG', 'the screenshot is a PNG')
// Several calls at once all settle.
const settled = await page.evaluate(() => Promise.all([1, 2, 3, 4, 5].map(() => window.soundcraft.uiInspect())).then((r) => r.length))
assert.equal(settled, 5, 'five concurrent calls all settle')
// Overload: far more calls than may wait at once. The ones over the limit are refused at once as busy, the
// ones within it are answered, and the page can call again afterwards (the slots came back).
const burst = await page.evaluate(() => Promise.all(
Array.from({ length: 300 }, () => window.soundcraft.uiInspect().then(() => 'ok', (e) => String((e && e.message) || e))),
))
const refused = burst.filter((r) => r !== 'ok')
console.log(`burst of ${burst.length}: ${burst.length - refused.length} answered, ${refused.length} refused (${refused[0]})`)
assert(refused.length > 0, 'calls beyond the limit are refused')
assert(refused.every((r) => /busy/i.test(r)), `every refusal says busy: ${refused.find((r) => !/busy/i.test(r))}`)
assert(burst.includes('ok'), 'the calls within the limit are answered')
assert.equal(burst.length, 300, 'every call settled, none was left waiting')
const afterBurst = await call('uiInspect')
assert(afterBurst.ok, `a call after the burst is accepted again: ${JSON.stringify(afterBurst).slice(0, 200)}`)
assert.deepEqual(errors, [], 'no uncaught page errors')
console.log('PASS window.soundcraft: all six functions, the failure paths and concurrent calls work against the real app')
} finally {
await browser.close()
server.close()
}
+1
View File
@@ -17,6 +17,7 @@ asio = ["soundcraft-playback/asio"]
[dependencies]
soundcraft-engine.workspace = true
craft-audio.workspace = true
craft-nightly.workspace = true
soundcraft-ui-egui.workspace = true
soundcraft-playback.workspace = true
soundcraft-automation.workspace = true
+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}");
}
+3 -29
View File
@@ -1,23 +1,10 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
pub use craft_nightly::BuildFlavor;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(soundcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open SoundCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable SoundCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -36,6 +23,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -44,20 +32,6 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.20.1"), "0.20.1");
+1 -7
View File
@@ -10,12 +10,6 @@ use soundcraft_ui_egui::docking;
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
/// The portable marker in `dir`, if it is a regular file (never a link or a directory).
pub(crate) fn portable_marker(dir: &std::path::Path) -> Option<std::path::PathBuf> {
let marker = dir.join(PORTABLE_MARKER);
std::fs::symlink_metadata(&marker).ok().filter(|m| m.file_type().is_file()).map(|_| marker)
}
#[derive(Clone, Copy)]
enum Platform {
Mac,
@@ -44,7 +38,7 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<Path
}
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option<PathBuf> {
// The compiled Nightly flavor cannot run without a profile (`build_flavor::require_profile`),
// The compiled Nightly flavor always selects an isolated profile (`launch_profile::prepare`),
// so this is the complete settings folder and never falls back to Stable data.
if let Some(root) = nightly {
return Some(root.to_path_buf());
+243 -168
View File
@@ -1,214 +1,289 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
//! Nightly-v1 bootstrap and profile fencing via `craft-nightly`.
//!
//! Selected before logging, updates, fonts or saved state. Direct launches of a nightly build
//! self-isolate into `craft_nightly::canonical_profile_root("soundcraft")`; launcher launches
//! pass `--launch-profile nightly-v1 --profile-root <dir> -- <args...>`. Stable builds keep
//! their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
use std::path::PathBuf;
pub const VERSION: &str = "nightly-v1";
use craft_nightly::{AppProfileSpec, Launch, Profile, ProfileError, StartupOptions};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
use crate::build_flavor;
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
const APP_ID: &str = "soundcraft";
const DISPLAY_NAME: &str = "SoundCraft";
const STABLE_DIR_NAMES: &[&str] = &["soundcraft", "SoundCraft"];
const STABLE_PACKAGE_ID: &str = "ai.storyteller.soundcraft";
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.soundcraft.nightly";
const FORBIDDEN_ENV_VARS: &[&str] = &[crate::env::CONFIG_DIR];
const PORTABLE_MARKERS: &[&str] = &[crate::config::PORTABLE_MARKER];
const FOLDER_ONLY_ENTRIES: &[&str] = &["Autosave", "Presets", "logs"];
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
static STABLE: Profile = Profile::Stable;
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&STABLE)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
fn non_empty_abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// The MSI's default per-user and per-machine folders (install-policy.wxi).
if let Some(local) = non_empty_abs_env(&env, "LOCALAPPDATA") {
roots.push(local.join("Programs").join("ArtCraft").join("SoundCraft"));
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
if let Some(profile) = non_empty_abs_env(&env, "USERPROFILE") {
roots.push(profile.join("AppData").join("Local").join("Programs").join("ArtCraft").join("SoundCraft"));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs_env(&env, key) {
roots.push(base.join("ArtCraft").join("SoundCraft"));
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
#[cfg(all(unix, not(target_os = "macos")))]
{
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs_env(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.soundcraft"));
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
#[cfg(target_os = "macos")]
{
roots.push(PathBuf::from("/Applications/SoundCraft.app"));
if let Some(home) = non_empty_abs_env(&env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.soundcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.soundcraft.savedState"));
roots.push(home.join("Applications/SoundCraft.app"));
}
}
#[cfg(not(any(unix, target_os = "windows")))]
let _ = env;
roots
}
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: DISPLAY_NAME,
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: PORTABLE_MARKERS,
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots_with(env),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
pub fn spec() -> AppProfileSpec {
spec_with(|key| std::env::var_os(key))
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
// SoundCraft keeps no Documents agent folder and has no craft-settings data/cache roots: one
// settings folder holds ui.json, Autosave/, Presets/ and logs/, and `config::writable` is the
// app's existing exclusive write probe.
crate::profile_root::validate(root, env, exe, crate::config::writable)
pub fn prepare(args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
craft_nightly::prepare_launch(build_flavor::COMPILED, &spec(), args, &StartupOptions::new())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, canonical_profile_root, launch_arguments, parse_startup, validate_and_prepare_root};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\soundcraft" } else { "/nightly-data/profiles/soundcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
struct TempDir(PathBuf);
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "image with spaces.psd"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
impl TempDir {
fn new(prefix: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
loop {
let candidate = base.join(format!("{prefix}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => return Self(candidate),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create temp dir: {error}"),
}
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
fn soundcraft_spec_preserves_stable_fences_and_folder_entries() {
let spec = spec();
assert_eq!(spec.app_id, "soundcraft");
assert_eq!(spec.display_name, "SoundCraft");
assert_eq!(spec.stable_dir_names, &["soundcraft", "SoundCraft"]);
assert_eq!(spec.stable_package_id, "ai.storyteller.soundcraft");
assert_eq!(spec.nightly_package_id, "ai.storyteller.soundcraft.nightly");
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, &["SOUNDCRAFT_CONFIG_DIR"]);
assert_eq!(spec.portable_markers, &["portable.txt"]);
assert_eq!(spec.folder_only_entries, &["Autosave", "Presets", "logs"]);
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
let spec = spec();
let expected_root = canonical_profile_root("soundcraft").unwrap();
let argv = args(&["--demo", "song.scraft"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(launch.passthrough_args, argv);
assert!(launch.leading_flags.is_empty());
}
#[test]
fn explicit_launcher_invocation_round_trips_and_preserves_file_arguments() {
let spec = spec();
let root = PathBuf::from(absolute());
let user_args = args(&["--profile-root", "session with spaces.scraft"]);
let argv = launch_arguments(&root, &user_args);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(root));
assert_eq!(launch.passthrough_args, user_args);
}
#[test]
fn stable_build_keeps_arguments_and_refuses_nightly_flags() {
let spec = spec();
for argv in [args(&[]), args(&["--demo", "a.scraft"]), args(&["--", "--launch-profile", "file.scraft"])] {
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
}
let nightly = launch_arguments(Path::new(absolute()), &[]);
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec, nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn version_queries_are_recognized_for_plain_and_launcher_invocations() {
let spec = spec();
for flag in ["--version", "-V"] {
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(plain.is_version_query());
for header in [
["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()],
["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT],
] {
let mut query = args(&header);
query.push(flag.into());
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, query.clone(), &StartupOptions::new()).unwrap().is_version_query());
query.push("recording with spaces.wav".into());
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, query, &StartupOptions::new()).unwrap();
assert!(!launch.is_version_query());
assert_eq!(launch.passthrough_args, args(&[flag, "recording with spaces.wav"]));
}
}
}
#[test]
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
let dir = TempDir::new("soundcraft-nightly-reopen");
let root = dir.path().join("profile");
let spec = spec();
let prepared = validate_and_prepare_root(&root, &spec).unwrap();
assert_eq!(prepared, root);
for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(prepared.join(file), b"saved profile data").unwrap();
}
for folder in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(prepared.join(folder)).unwrap();
}
assert_eq!(validate_and_prepare_root(&root, &spec).unwrap(), prepared);
for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(prepared.join(file)).unwrap(), b"saved profile data", "{file} remains intact after reopen");
}
for folder in FOLDER_ONLY_ENTRIES {
let path = prepared.join(folder);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(
matches!(validate_and_prepare_root(&root, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
"{folder} must remain a directory"
);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn extra_forbidden_roots_fence_soundcraft_install_locations() {
let dir = TempDir::new("soundcraft-extra-fence");
let custom_forbidden = dir.path().join("forbidden-install");
let mut spec = spec();
spec.extra_forbidden_roots.push(custom_forbidden.clone());
assert!(matches!(validate_and_prepare_root(&custom_forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
}
#[test]
fn platform_extra_forbidden_roots_include_expected_paths() {
let home = if cfg!(windows) { r"C:\Users\tester" } else { "/Users/tester" };
let local = if cfg!(windows) { r"C:\Users\tester\AppData\Local" } else { "/unused" };
let program_files = if cfg!(windows) { r"C:\Program Files" } else { "/unused" };
let spec = spec_with(|key| match key {
"HOME" | "USERPROFILE" => Some(OsString::from(home)),
"LOCALAPPDATA" => Some(OsString::from(local)),
"ProgramFiles" => Some(OsString::from(program_files)),
_ => None,
});
#[cfg(target_os = "windows")]
{
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(local).join("Programs").join("ArtCraft").join("SoundCraft")));
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(program_files).join("ArtCraft").join("SoundCraft")));
}
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/soundcraft")));
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join(".var/app/ai.storyteller.soundcraft")));
}
#[cfg(target_os = "macos")]
{
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/Applications/SoundCraft.app")));
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join("Library/Preferences/ai.storyteller.soundcraft.plist")));
}
let _ = (home, local, program_files, &spec);
}
}
+2 -2
View File
@@ -22,8 +22,8 @@
//! callback must never do. Code that runs on the audio thread logs anyway (the cpal error callback,
//! the synth's full event queue, a hosted plugin's failed `process`, a CLAP plugin calling the
//! host's `log` from its audio thread, the panic hook). So the cpal callbacks mark their thread
//! (`soundcraft_playback::mark_audio_thread`; the mix engine carries the mark into the worker
//! threads that render strips for it), and a record from a marked thread is not written
//! (`soundcraft_playback::mark_audio_thread`; the mix engine renders every strip on the marked
//! thread itself), and a record from a marked thread is not written
//! there: the first one is kept in a fixed buffer (`try_lock`, no allocation, never waits) and the
//! rest are only counted (an atomic). Another thread writes them out: the UI thread every frame
//! ([`AppLogger::report_audio_thread`]) and any other thread before its own next record.
+20 -23
View File
@@ -26,7 +26,6 @@ mod logging;
mod native_menu;
mod nightly_session;
mod process_identity;
mod profile_root;
mod switch;
use env::Env;
@@ -251,36 +250,34 @@ fn report_launch_profile_error(error: &str) {
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before the logger, updates, fonts or saved state.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window, as
// `SoundCraft <version> (nightly-v1)` on standard output with nothing on standard error.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
// Plain `--version` / `-V` on Nightly: answered before canonical root resolution, validation,
// process identity, IPC or any window, even in environments without HOME/LOCALAPPDATA.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let early = launch_profile::prepare(argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
// `craft_nightly::prepare_launch` skips root validation and profile installation for version queries.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION")));
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
if let Err(error) = os_window::select_identity(identity) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(early.passthrough_args)
}
fn main() -> eframe::Result {
-627
View File
@@ -1,627 +0,0 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use crate::config::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
/// The Nightly Flatpak's own app id (packaging/linux/flatpak-bundle.sh). Inside that instance the
/// sandbox is the isolation, so it is the one Flatpak whose environment a Nightly launch accepts.
const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.soundcraft.nightly";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("SoundCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
// install folder is not known here; the executable's own folder is fenced below.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("SoundCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("SoundCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("soundcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.soundcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/SoundCraft"),
library.join("Caches/SoundCraft"),
library.join("Caches/ai.storyteller.soundcraft"),
library.join("Preferences/SoundCraft"),
library.join("Preferences/ai.storyteller.soundcraft.plist"),
library.join("Saved Application State/ai.storyteller.soundcraft.savedState"),
home.join("Applications/SoundCraft.app"),
PathBuf::from("/Applications/SoundCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve
/// inside it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a SoundCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["soundcraft.exe", "soundcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
/// boundary tests exercise the real policy without starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if env("SOUNDCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
// The Launcher protocol is the one root the app validates. A wrapper that isolates with
// the stable override variable instead passes the profile explicitly; the message names
// that, because this is what a Linux nightly launcher hits when it exports the variable.
return Err(
"nightly-v1 cannot be combined with SOUNDCRAFT_CONFIG_DIR; pass --launch-profile nightly-v1 --profile-root <dir> -- instead".into()
);
}
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its
// runtime socket namespace could point another profile at the stable app's socket. The
// Nightly Flatpak is the exception: its own app id is the sandbox, so $HOME and the XDG
// folders in there are already this package's own.
if platform != Platform::Windows
&& let Some(instance) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& instance.to_string_lossy() != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable SoundCraft installation or its SoundCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Autosave is swept and rewritten on start and Presets are written in place: never let either
// alias leave this private profile, including toward a Stable portable directory we cannot know.
private_subdirectory(&chosen, "Autosave", "autosave folder")?;
private_subdirectory(&chosen, "Presets", "presets folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "Autosave", "autosave folder")?;
private_subdirectory(&confirmed, "Presets", "presets folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("soundcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/soundcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("SoundCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn autosave_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/soundcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("Autosave")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "Autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join("Autosave")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "Autosave cannot treat all profile settings as autosaves");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn autosave_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let autosave = private.join("private-recovery");
std::fs::create_dir_all(&autosave).unwrap();
std::os::unix::fs::symlink(&autosave, private.join("Autosave")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("Autosave")).unwrap(), autosave);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/soundcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Autosave"), platform));
assert!(overlaps(&root.join("Autosave"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("soundcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("soundcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/soundcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/SoundCraft Nightly.app/Contents/MacOS/SoundCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/SoundCraft",
"Caches/SoundCraft",
"Caches/ai.storyteller.soundcraft",
"Preferences/SoundCraft",
"Saved Application State/ai.storyteller.soundcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/soundcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_and_install_fences_remain_active() {
let fixture = Fixture::new();
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("SoundCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/soundcraft")).is_ok());
}
#[test]
fn windows_default_msi_install_folders_are_fenced() {
let mut fixture = Fixture::new();
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("SoundCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("SoundCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("soundcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not SoundCraft's install");
}
#[test]
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
let fixture = Fixture::new();
let portable = fixture.root.join("D/PC");
std::fs::create_dir_all(&portable).unwrap();
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
std::fs::write(portable.join("soundcraft.exe"), b"stable portable executable, never run").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.unwrap_err().contains("portable"));
assert!(!probed.get());
assert!(!candidate.exists());
}
}
// A portable.txt that no SoundCraft executable sits beside is someone else's file.
let unrelated = fixture.root.join("user folder");
std::fs::create_dir_all(&unrelated).unwrap();
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/soundcraft")).is_ok());
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.soundcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
}
#[cfg(unix)]
#[test]
fn any_profile_entry_alias_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/soundcraft/Presets");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap();
for name in ["Presets", "logs", "settings.json"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-presets")).unwrap();
std::fs::write(private.join("settings.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/soundcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("SOUNDCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("SOUNDCRAFT_CONFIG_DIR"));
fixture.env.remove("SOUNDCRAFT_CONFIG_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
// The Nightly Flatpak is its own instance: the profile inside it is a sandbox-local folder.
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft.nightly".into());
let sandboxed = fixture.home().join(".var/app/ai.storyteller.soundcraft.nightly/config/soundcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &sandboxed).unwrap(), sandboxed);
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/soundcraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/soundcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright © 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+4
View File
@@ -70,6 +70,10 @@ sync_github_name = true
real_name = "Kushagra Kumar"
sync_github_name = true
[people.JonRC]
real_name = "Jonathan Cardoso"
display_name = "Jonathan Cardoso"
# Display name explicitly chosen by the contributor on 2026-10-19.
[people.vhhr7]
display_name = "Vic Herrera (@vhhr)"
@@ -182,6 +182,7 @@ fn writes(dir: &Path) -> Vec<(&'static str, Value)> {
("file.print_score", json!({"path": p("k.svg")})),
("file.export_clip_groups", json!({"path": p("l.scgrp"), "clips": [clip]})),
("track.save_preset", json!({"path": p("m.json"), "tracks": ["Kick"]})),
("setup.disk_allocation", json!({"path": p("recordings")})),
]
}
@@ -301,6 +302,7 @@ fn links_out_of_the_roots_are_refused() {
refused(&mut srv, "file.bounce_mix", json!({"path": s(f.write.join("away/x.wav"))}), "outside the write root");
refused(&mut srv, "file.bounce_stems", json!({"dir": s(f.write.join("away/stems"))}), "outside the write root");
refused(&mut srv, "session.save_as", json!({"path": s(f.write.join("away/x.scraft"))}), "outside the write root");
refused(&mut srv, "setup.disk_allocation", json!({"path": s(f.write.join("away/rec"))}), "outside the write root");
refused(&mut srv, "file.bounce_mix", json!({"path": s(f.write.join("dangling.wav"))}), "a link that leads nowhere");
assert_eq!(listing(&f.outside), before, "nothing was written through a link");
assert!(!f.outside.join("not-yet.wav").exists());
@@ -371,6 +373,56 @@ fn media_a_session_names_outside_the_read_root_is_not_loaded() {
assert!(inspect(&mut free)["sources"].as_array().unwrap().iter().all(|x| x["loaded"] == true));
}
/// `setup.disk_allocation` stores its path trimmed and cut to 200 characters, so that string is
/// what gets checked. With the working folder as the write root, `" /abs/outside"` read as given
/// would be `<cwd>/ /abs/outside` and pass, yet `/abs/outside` would be kept. The outside folder
/// is the working directory's parent, so this does not depend on `TMPDIR`. A space at character
/// 200 would be checked and then trimmed off again: `<pad>/link ` can sit inside the root while
/// `<pad>/link` is a symlink out of it. An empty path still clears the setting.
#[test]
fn the_record_folder_is_checked_as_it_is_stored() {
let cwd = std::env::current_dir().unwrap();
let outside = cwd.parent().expect("the working directory has a parent");
let mut srv = demo_server(None, Some(&cwd));
let spaced = format!(" {}", s(outside.join("rec")));
refused(&mut srv, "setup.disk_allocation", json!({"path": spaced}), "outside the write root");
refused(&mut srv, "setup.disk_allocation", json!({"track": "Kick", "path": spaced}), "outside the write root");
ok(&mut srv, "setup.disk_allocation", json!({"path": " rec "}));
ok(&mut srv, "setup.disk_allocation", json!({"path": ""}));
ok(&mut srv, "setup.disk_allocation", json!({"path": " "}));
// Character 200 is a space, and more follows so the first trim leaves it. The cut used to
// keep that space for the check and drop it when the same string was stored.
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
// A folder of our own in the working folder: `create_dir` fails rather than reuse one that
// is already there, so only what this run made is removed, and parallel runs don't meet.
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let own = format!("sc-record-{}-{nanos}", std::process::id());
std::fs::create_dir(cwd.join(&own)).unwrap();
struct RemoveDir(PathBuf);
impl Drop for RemoveDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let _cleanup = RemoveDir(cwd.join(&own));
let tail = "/link";
let pad = "d".repeat(199 - own.len() - 1 - tail.len());
let rel = format!("{own}/{pad}{tail}");
assert_eq!(rel.chars().count(), 199, "the stored path is 199 characters");
let dir = cwd.join(&own).join(&pad);
std::fs::create_dir(&dir).unwrap();
symlink(outside, dir.join("link")).unwrap();
let input = format!("{rel} x");
assert_eq!(input.chars().nth(199), Some(' '), "character 200 is a space");
refused(&mut srv, "setup.disk_allocation", json!({"path": input}), "outside the write root");
let reported = ok(&mut srv, "setup.disk_allocation", json!({}));
assert!(!reported.contains(&pad), "a refused record folder was stored: {reported}");
}
}
#[test]
fn without_roots_nothing_is_confined() {
let f = fixture("free");
+5
View File
@@ -287,6 +287,11 @@ impl GuiLink {
#[cfg(all(unix, not(target_os = "macos")))]
self.dispatch(&g);
if g.created {
// a timer-driven editor's WM_TIMERs and the paints they invalidate are starved while
// the transport keeps the queue busy (#1447)
if let Some(w) = &g.window {
w.service();
}
let resize = self.host.gui_resize.swap(0, Ordering::Relaxed);
if resize != 0
&& let Some(win) = &g.window
@@ -16,6 +16,9 @@ impl HostWindow {
clap_window_handle { ptr: std::ptr::null_mut() }
}
pub fn raise(&self) {}
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
pub fn service(&self) {}
pub fn is_visible(&self) -> bool {
false
}
+108 -3
View File
@@ -2,12 +2,14 @@ use clap_sys::ext::gui::clap_window_handle;
use std::ffi::c_void;
use std::sync::OnceLock;
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows_sys::Win32::Graphics::Gdi::{RDW_ALLCHILDREN, RDW_UPDATENOW, RedrawWindow};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
use windows_sys::Win32::UI::WindowsAndMessaging::{
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, GWL_EXSTYLE, GWL_STYLE,
GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, RegisterClassExW, SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE,
SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GWL_EXSTYLE,
GWL_STYLE, GetWindowLongPtrW, IDC_ARROW, IsWindow, IsWindowVisible, LoadCursorW, MSG, PM_REMOVE, PeekMessageW, PostQuitMessage, RegisterClassExW,
SW_HIDE, SW_SHOW, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE, WM_QUIT, WM_TIMER,
WNDCLASSEXW, WS_CAPTION, WS_CLIPCHILDREN, WS_OVERLAPPED, WS_SYSMENU,
};
pub const SUPPORTED: bool = true;
@@ -148,6 +150,18 @@ impl HostWindow {
self.live().is_some_and(|h| unsafe { IsWindowVisible(h) } != 0)
}
/// Per-frame service on the main thread (#1447): while the transport plays eframe always keeps a
/// repaint pending, and Win32 only synthesizes `WM_TIMER` and `WM_PAINT` when the queue runs dry —
/// so a timer-driven editor is starved until playback pauses. Dispatches the thread's pending
/// timers (thread-wide on purpose: nothing else on this thread uses Win32 timers, and a timer
/// with a `TIMERPROC` only runs through dispatch) and flushes the paint they invalidate.
pub fn service(&self) {
let Some(hwnd) = self.live() else { return };
pump_timers();
// SAFETY: a live window of this thread; ALLCHILDREN reaches the plugin's child windows.
unsafe { RedrawWindow(hwnd, std::ptr::null(), std::ptr::null_mut(), RDW_UPDATENOW | RDW_ALLCHILDREN) };
}
pub fn close(self) {
if let Some(h) = self.live() {
// SAFETY: our own live window; the plugin's GUI was destroyed first.
@@ -168,3 +182,94 @@ pub fn resize(window: *mut c_void, w: f64, h: f64) {
// SAFETY: as above; only the size changes.
unsafe { SetWindowPos(window, std::ptr::null_mut(), 0, 0, ow, oh, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE) };
}
/// Dispatches up to 32 `WM_TIMER`s pending on this thread (main thread only). The cap keeps a timer
/// that re-arms on every dispatch from starving the frame; leftovers are served next tick.
fn pump_timers() {
// SAFETY: `PeekMessageW`/`DispatchMessageW`/`PostQuitMessage` on this thread's own queue;
// `msg` outlives them all.
unsafe {
let mut msg: MSG = std::mem::zeroed();
for _ in 0..32 {
if PeekMessageW(&mut msg, std::ptr::null_mut(), WM_TIMER, WM_TIMER, PM_REMOVE) == 0 {
break;
}
if msg.message == WM_QUIT {
// PeekMessageW returns WM_QUIT regardless of the filter — repost it with its
// exit code so the app's own message loop still sees the quit, and stop here.
PostQuitMessage(msg.wParam as i32);
break;
}
DispatchMessageW(&msg);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use windows_sys::Win32::Graphics::Gdi::{GetUpdateRect, InvalidateRect};
use windows_sys::Win32::UI::WindowsAndMessaging::{KillTimer, SetTimer};
static FIRED: AtomicUsize = AtomicUsize::new(0);
unsafe extern "system" fn on_timer(hwnd: HWND, _msg: u32, _id: usize, _time: u32) {
FIRED.fetch_add(1, Ordering::Relaxed);
// SAFETY: a live window of this thread.
unsafe { InvalidateRect(hwnd, std::ptr::null(), 1) };
}
/// #1447: while the transport plays eframe always has a repaint pending, and Win32 only
/// synthesizes `WM_TIMER`/`WM_PAINT` when the queue runs dry — an editor that animates from a
/// timer freezes until Pause. `service` must dispatch the timer and its paint without a
/// message loop ever waiting.
#[test]
fn an_editors_timer_and_paint_run_while_the_thread_never_waits_for_messages() {
// windows are created and served on the app's UI thread — named "main" here.
std::thread::Builder::new()
.name("main".into())
.spawn(|| {
let window = HostWindow::new("timer test", 120.0, 80.0).expect("host window");
let h = window.raw() as HWND;
FIRED.store(0, Ordering::Relaxed);
// SAFETY: live window of this thread; proc outlives the timer (killed below).
unsafe { SetTimer(h, 1, 10, Some(on_timer)) };
std::thread::sleep(std::time::Duration::from_millis(100));
assert_eq!(FIRED.load(Ordering::Relaxed), 0, "the timer fired without anyone pumping");
window.service();
assert!(FIRED.load(Ordering::Relaxed) > 0, "service() did not dispatch WM_TIMER");
// SAFETY: `GetUpdateRect` accepts any window; false means the paint was flushed.
assert_eq!(unsafe { GetUpdateRect(h, std::ptr::null_mut(), 0) }, 0, "the timer's paint is still pending");
unsafe { KillTimer(h, 1) };
window.close();
})
.expect("spawn")
.join()
.expect("join");
}
/// `PeekMessageW` returns `WM_QUIT` regardless of the filter range, so the pump can swallow
/// the quit the app's own loop is waiting for. It must repost it — with its exit code — and
/// stop, leaving the signal for the owning loop.
#[test]
fn the_pump_leaves_a_quit_and_its_exit_code_for_the_owning_loop() {
std::thread::Builder::new()
.name("main".into())
.spawn(|| {
// SAFETY: this thread owns the queue it posts to and peeks.
unsafe { PostQuitMessage(7) };
pump_timers();
// SAFETY: `MSG` is a plain Win32 data struct made of integer and pointer fields,
// so an all-zero value is valid initialized storage.
let mut msg: MSG = unsafe { std::mem::zeroed() };
// SAFETY: `msg` is live owned storage, so `&mut msg` remains valid and writable
// for the duration of the call.
assert_ne!(unsafe { PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) }, 0, "the pump swallowed the quit");
assert_eq!((msg.message, msg.wParam), (WM_QUIT, 7), "the quit signal or its exit code changed");
})
.expect("spawn")
.join()
.expect("join");
}
}
+3
View File
@@ -142,6 +142,9 @@ impl HostWindow {
self.shown.store(true, Ordering::Relaxed);
}
/// Per-frame service (#1447): only Windows starves editor timers/paints while repaints run.
pub fn service(&self) {}
pub fn is_visible(&self) -> bool {
let Some(x) = x().filter(|_| on_main_thread()) else { return false };
x.pump();
+25
View File
@@ -8,6 +8,8 @@ use std::sync::atomic::Ordering;
/// Largest block we activate a plugin for.
const MAX_BLOCK: usize = 1 << 16;
/// Most `on_main_thread` calls one `idle` runs for a plugin that keeps asking for more.
const MAX_CALLBACKS_PER_IDLE: usize = 8;
/// Most channels a host strip may ask for.
const MAX_CHANNELS: usize = 64;
/// Queue slots that only releases from `note_off` may take: one per key, so a queue that
@@ -43,6 +45,8 @@ pub struct ClapPlugin {
channels: usize,
max_block: usize,
latency: usize,
/// What the last `prepare` was asked for, to restart the plugin the same way.
prepared: Option<(f32, usize, usize)>,
steady: i64,
transport: Option<Transport>,
}
@@ -67,6 +71,7 @@ impl ClapPlugin {
channels: 2,
max_block: 0,
latency: 0,
prepared: None,
steady: 0,
transport: None,
}
@@ -231,6 +236,7 @@ impl Plugin for ClapPlugin {
}
fn prepare(&mut self, sample_rate: f32, max_block: usize, channels: usize) {
self.prepared = Some((sample_rate, max_block, channels));
let sr = if sample_rate.is_finite() && sample_rate > 0.0 { f64::from(sample_rate) } else { 48_000.0 };
let mb = max_block.clamp(1, MAX_BLOCK);
self.channels = channels.clamp(1, MAX_CHANNELS);
@@ -358,6 +364,25 @@ impl Plugin for ClapPlugin {
self.latency
}
fn idle(&mut self) {
// A plugin that finds a new latency while processing asks for `on_main_thread`, and from
// there for a restart (maybe after more callbacks): the new value only counts once it is
// activated again. Run every callback it asks for here, a bounded number of them.
for _ in 0..MAX_CALLBACKS_PER_IDLE {
if !self.inst.state().callback.load(Ordering::Relaxed) {
break;
}
self.inst.service_callback();
}
if self.inst.state().restart.swap(false, Ordering::Relaxed) {
if let Some((sr, mb, ch)) = self.prepared {
self.prepare(sr, mb, ch);
}
} else if self.inst.is_active() && self.inst.state().latency_changed.swap(false, Ordering::Relaxed) {
self.latency = self.inst.latency() as usize;
}
}
fn set_transport(&mut self, transport: &Transport) {
self.transport = Some(*transport);
}
+37 -4
View File
@@ -1,7 +1,9 @@
//! Test-only CLAP plugins for soundcraft-clap-host: a gain effect and a "DC synth".
//!
//! - `org.soundcraft.test.gain`: stereo in/out, param 7 "Gain" (0..2, default 1), param 3 "Mode"
//! (stepped enum A/B/C), hidden param 9, latency 3 samples.
//! (stepped enum A/B/C), hidden param 9, latency 3 samples. Mode C needs 16: like LSP, the
//! plugin finds that out in `process`, asks for `on_main_thread`, from there for a second
//! `on_main_thread`, and from that one for a restart; it reports 16 once activated again.
//! - `org.soundcraft.test.synth`: instrument, stereo out, CLAP note port; outputs a constant equal
//! to the velocity of the held note (0 when none), switching at the event's sample offset. A
//! MIDI CC 7 (volume) sets the constant to its value / 127. `reset` leaves the note sounding.
@@ -99,6 +101,11 @@ struct Fx {
gain: f64,
mode: f64,
level: f64,
/// The latency the plugin was activated with, and whether it asked for a restart to change it.
latency: u32,
restart_wanted: bool,
/// The first `on_main_thread` after a latency change only asks for another one.
second_callback_asked: bool,
active: bool,
processing: bool,
gui_created: bool,
@@ -146,9 +153,14 @@ unsafe extern "C" fn activate(p: *const clap_plugin, sr: f64, min: u32, max: u32
return false;
}
f.active = true;
f.latency = latency_for(f.mode);
true
}
fn latency_for(mode: f64) -> u32 {
if mode >= 2.0 { 16 } else { 3 }
}
unsafe extern "C" fn deactivate(p: *const clap_plugin) {
let f = unsafe { fx(p) };
assert!(!f.processing, "deactivate while processing");
@@ -310,6 +322,11 @@ unsafe extern "C" fn process(p: *const clap_plugin, pr: *const clap_process) ->
unsafe { *o.add(i) = v };
}
}
if latency_for(f.mode) != f.latency && !f.restart_wanted {
f.restart_wanted = true;
let host = unsafe { &*f.host };
unsafe { (host.request_callback.unwrap())(f.host) };
}
CLAP_PROCESS_CONTINUE
}
@@ -422,8 +439,8 @@ unsafe extern "C" fn ports_get(p: *const clap_plugin, index: u32, is_input: bool
static PORTS: clap_plugin_audio_ports = clap_plugin_audio_ports { count: Some(ports_count), get: Some(ports_get) };
unsafe extern "C" fn latency_get(_p: *const clap_plugin) -> u32 {
3
unsafe extern "C" fn latency_get(p: *const clap_plugin) -> u32 {
unsafe { fx(p) }.latency
}
static LATENCY: clap_plugin_latency = clap_plugin_latency { get: Some(latency_get) };
@@ -586,7 +603,20 @@ unsafe extern "C" fn get_extension(p: *const clap_plugin, id: *const c_char) ->
}
}
unsafe extern "C" fn on_main_thread(_p: *const clap_plugin) {}
unsafe extern "C" fn on_main_thread(p: *const clap_plugin) {
let f = unsafe { fx(p) };
if !f.restart_wanted {
return;
}
let host = unsafe { &*f.host };
if std::mem::replace(&mut f.second_callback_asked, true) {
f.restart_wanted = false;
f.second_callback_asked = false;
unsafe { (host.request_restart.unwrap())(f.host) };
} else {
unsafe { (host.request_callback.unwrap())(f.host) };
}
}
// ---- factory + entry ----
@@ -641,6 +671,9 @@ unsafe extern "C" fn factory_create(_f: *const clap_plugin_factory, host: *const
gain: 1.0,
mode: 0.0,
level: 0.0,
latency: 3,
restart_wanted: false,
second_callback_asked: false,
active: false,
processing: false,
gui_created: false,
+21
View File
@@ -80,6 +80,27 @@ fn gain_processes_audio_and_follows_params() {
p.process(&mut io, 8);
}
#[test]
fn a_new_latency_counts_after_the_restart_the_plugin_asks_for() {
fixture_dir();
let mut p = soundcraft_clap_host::create(GAIN).unwrap();
p.prepare(48_000.0, 64, 2);
assert_eq!(p.latency(), 3);
assert!(p.set_param("3", 2.0), "mode C takes 16 samples");
let mut io = vec![vec![0.5f32; 64]; 2];
p.process(&mut io, 64);
assert_eq!(p.latency(), 3, "so far the plugin only asked for on_main_thread");
// One idle runs both callbacks the plugin asks for (the second one asks for the restart).
p.idle();
assert_eq!(p.latency(), 16, "restarted with its new latency");
assert_eq!(p.param("3"), Some(2.0));
let mut io = vec![vec![0.5f32; 64]; 2];
p.process(&mut io, 64);
assert!(io[0].iter().all(|&x| (x - 0.5).abs() < 1e-6), "still processing after the restart: {:?}", &io[0][..4]);
p.idle();
assert_eq!(p.latency(), 16);
}
#[test]
fn synth_plays_notes_at_their_offsets() {
fixture_dir();
+9
View File
@@ -210,6 +210,15 @@ pub trait Plugin: Send {
fn latency(&self) -> usize {
0
}
/// Main-thread time between blocks, for hosted plugins: runs the callbacks the plugin asked
/// for, restarts it when it asked to, and reads its latency again (some plugins only know it
/// once they have processed). Offline renders call it after every block; the realtime audio
/// thread never does.
///
/// For implementors: it runs between two `process` calls, on the thread that owns the instance,
/// so it may allocate, block and re-activate the plugin, and it may change what `latency()`
/// reports; callers read `latency()` again afterwards.
fn idle(&mut self) {}
/// How long the output keeps ringing after the input stops, in samples.
fn tail_samples(&self) -> usize {
0
+3
View File
@@ -27,6 +27,7 @@ mod more_util;
mod options;
mod plugin_state;
mod query;
mod room_tone;
pub(crate) mod sampler;
mod setup_more;
mod strip_silence;
@@ -62,6 +63,7 @@ mod panic_probe {
}
}
pub use clip_more::is_looped;
pub use file::bounce_job;
pub(crate) use edit::remember_selection;
@@ -165,6 +167,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(video::specs());
v.extend(zoom_toggle::specs());
v.extend(strip_silence::specs());
v.extend(room_tone::specs());
#[cfg(test)]
v.extend(panic_probe::specs());
v
+3 -1
View File
@@ -40,7 +40,9 @@ fn audio_as_midi(e: &mut Engine, p: &Value) -> Result<Value> {
seq.sort();
let count = seq.notes.len();
let clip = Clip::midi(ClipId(0), "Audio as MIDI", 0, r.len(), seq);
e.clipboard = Clipboard { tracks: vec![vec![clip]], automation: vec![Vec::new()], ..Clipboard::of_range(e.session(), r) };
let mut clipboard = Clipboard { automation: vec![Vec::new()], ..Clipboard::of_range(s, r) };
clipboard.push_clips(s, r.start, vec![clip]);
e.clipboard = clipboard;
Ok(json!({"notes": count, "length": r.len()}))
}
+16
View File
@@ -55,6 +55,10 @@ fn clear(e: &mut Engine, p: &Value) -> Result<Value> {
pl.clips.retain(|c| !gone.contains(&c.id));
}
s.sources.retain(|f| !sources.contains(&f.id));
// The room tone plays one of the removed files: nothing is left for it to play.
if s.room_tone.is_some_and(|t| sources.contains(&t.source)) {
s.room_tone = None;
}
for f in &sources {
s.pool.remove(*f);
}
@@ -106,6 +110,18 @@ mod tests {
assert_eq!(e.session().clips_using(f).count(), 6);
}
#[test]
fn removing_the_room_tones_file_forgets_the_room_tone() {
let mut e = crate::demo::demo_engine();
let (f, clips) = kick(&e);
e.execute("edit.room_tone_set", &json!({"clip": clips[0]})).unwrap();
assert_eq!(e.session().room_tone.map(|t| t.source), Some(f));
e.execute("clip.clear", &json!({"sources": [f], "with_clips": true})).unwrap();
assert_eq!(e.session().room_tone, None);
assert!(e.undo());
assert_eq!(e.session().room_tone.map(|t| t.source), Some(f), "undo brings it back with the file");
}
#[test]
fn listing_a_files_clips_too_is_enough() {
let mut e = crate::demo::demo_engine();
+5
View File
@@ -150,6 +150,11 @@ fn loop_chain(s: &Session, t: TrackId, id: ClipId) -> Vec<ClipId> {
chain
}
/// Whether a clip belongs to a loop that `clip.unloop` changes: two or more back-to-back copies.
pub fn is_looped(s: &Session, id: ClipId) -> bool {
s.find_clip(id).is_some_and(|(t, _)| loop_chain(s, t, id).len() >= 2)
}
fn unloop(e: &mut Engine, p: &Value) -> Result<Value> {
let id = "clip.unloop";
let remove = match str_param(p, "mode") {
+6 -4
View File
@@ -259,7 +259,9 @@ fn cut_copy(e: &mut Engine, p: &Value, cut: bool, id: &str) -> Result<Value> {
let follow = e.session().edit.automation_follows_edit;
for t in &tracks {
// Cut carries only what it removes; a locked clip stays where it is (see `ops::take_range`).
cb.tracks.push(if cut { ops::take_range(e.session(), *t, range) } else { ops::copy_range(e.session(), *t, range) });
let s = e.session();
let clips = if cut { ops::take_range(s, *t, range) } else { ops::copy_range(s, *t, range) };
cb.push_clips(s, range.start, clips);
let lanes = e
.session()
.track(*t)
@@ -1217,9 +1219,9 @@ mod tests {
let (mut e, t, at) = keys();
let s = e.session_mut();
let cc = soundcraft_midi::CtrlEvent { tick: 0, channel: 0, kind: soundcraft_midi::CtrlKind::Cc(1), value: 64 };
let a = soundcraft_midi::Sequence { notes: vec![note(0, 1, 60), note(3, 2, 62), note(5, 1, 63)], ctrls: vec![], sysex: vec![] };
let b = soundcraft_midi::Sequence { notes: vec![note(0, 1, 64)], ctrls: vec![], sysex: vec![] };
let c = soundcraft_midi::Sequence { notes: vec![note(1, 1, 65)], ctrls: vec![cc], sysex: vec![] };
let a = soundcraft_midi::Sequence { notes: vec![note(0, 1, 60), note(3, 2, 62), note(5, 1, 63)], ..Default::default() };
let b = soundcraft_midi::Sequence { notes: vec![note(0, 1, 64)], ..Default::default() };
let c = soundcraft_midi::Sequence { notes: vec![note(1, 1, 65)], ctrls: vec![cc], ..Default::default() };
for (start, end, seq, muted) in [(0, 4, a, false), (6, 8, b, true), (8, 12, c, false)] {
let id = s.new_clip_id();
let mut clip = Clip::midi(id, "Keys", at(start), at(end) - at(start), seq);
+44 -17
View File
@@ -448,6 +448,19 @@ fn paste_clip_effects(e: &mut Engine, p: &Value) -> Result<Value> {
Ok(json!({"clips": ids.len()}))
}
fn retain_midi_window(sequence: &mut soundcraft_midi::Sequence, end: i64) {
let window = 0..end;
sequence.notes.retain_mut(|note| {
if !window.contains(&note.start) {
return false;
}
note.length = note.length.min(end - note.start);
true
});
sequence.ctrls.retain(|event| window.contains(&event.tick));
sequence.sysex.retain(|event| window.contains(&event.tick));
}
fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
let id = "edit.paste_merge_midi";
let tracks = tracks_required(e, id, p)?;
@@ -460,16 +473,22 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
let mut placed = 0;
for (i, t) in tracks.iter().enumerate() {
let Some(clips) = cb.tracks.get(i % cb.tracks.len().max(1)) else { continue };
for c in clips {
for source in clips {
let mut c = source.clone();
let pos = at.saturating_add(c.start);
let ClipContent::Midi { sequence } = &c.content else {
let mut nc = c.clone();
nc.id = s.new_clip_id();
nc.start = pos;
ops::place_clip(s, *t, nc);
let ClipContent::Midi { sequence } = &mut c.content else {
c.id = s.new_clip_id();
c.start = pos;
ops::place_clip(s, *t, c);
placed += 1;
continue;
};
let paste_tick = tempo.samples_to_ticks(pos, sr);
let sample_end = pos.saturating_add(c.length);
let ticks = cb.midi_tick_lengths.get(&c.id).copied().unwrap_or_else(|| tempo.samples_to_ticks(sample_end, sr).saturating_sub(paste_tick));
retain_midi_window(sequence, ticks);
// At a slower destination tempo the same musical window needs more samples.
let want_end = sample_end.max(tempo.tick_to_samples(paste_tick.saturating_add(ticks), sr));
let target = s.track(*t).and_then(|tr| {
let host = tr.clips().iter().find(|x| matches!(x.content, ClipContent::Midi { .. }) && x.range().contains(pos))?;
let next_start = tr.clips().iter().filter(|x| x.start > host.start && x.id != host.id).map(|x| x.start).min();
@@ -477,22 +496,23 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
});
match target {
Some((hid, hstart, next_start)) => {
let diff = tempo.samples_to_ticks(pos, sr) - tempo.samples_to_ticks(hstart, sr);
let want_end = pos.saturating_add(c.length);
let diff = paste_tick - tempo.samples_to_ticks(hstart, sr);
let limit = next_start.unwrap_or(Samples::MAX);
if let Some(h) = s.find_clip_mut(hid)
&& let ClipContent::Midi { sequence: hs } = &mut h.content
{
for n in &sequence.notes {
let mut n = *n;
for mut n in sequence.notes.drain(..) {
n.start = n.start.saturating_add(diff);
hs.notes.push(n);
}
for cc in &sequence.ctrls {
let mut cc = *cc;
for mut cc in sequence.ctrls.drain(..) {
cc.tick = cc.tick.saturating_add(diff);
hs.ctrls.push(cc);
}
for mut event in sequence.sysex.drain(..) {
event.tick = event.tick.saturating_add(diff);
hs.sysex.push(event);
}
hs.sort();
if want_end > h.end() {
h.trim_end_to(want_end.min(limit));
@@ -501,10 +521,17 @@ fn paste_merge_midi(e: &mut Engine, p: &Value) -> Result<Value> {
}
}
None => {
let mut nc = c.clone();
nc.id = s.new_clip_id();
nc.start = pos;
ops::place_clip(s, *t, nc);
// Only extend through empty space. Keep the existing placement behavior
// inside the original sample range and preserve material beyond it.
if want_end > sample_end
&& let Some(track) = s.track(*t)
{
let limit = track.clips().iter().filter(|other| other.end() > sample_end).map(|other| other.start.max(sample_end)).min();
c.length = want_end.min(limit.unwrap_or(Samples::MAX)).saturating_sub(pos);
}
c.id = s.new_clip_id();
c.start = pos;
ops::place_clip(s, *t, c);
placed += 1;
}
}
@@ -1143,7 +1170,7 @@ mod tests {
e.execute("edit.select", &json!({"tracks": [keys.0], "start": r.start, "end": r.end})).unwrap();
e.execute("edit.copy", &json!({})).unwrap();
let copied = match &e.clipboard.tracks[0][0].content {
ClipContent::Midi { sequence } => sequence.notes.len(),
ClipContent::Midi { sequence } => sequence.notes_in(0, e.clipboard.midi_tick_lengths[&clip.id]).count(),
_ => 0,
};
e.execute("edit.paste_merge_midi", &json!({"at": clip.start + 96_000})).unwrap();
+4 -4
View File
@@ -349,9 +349,9 @@ fn select_split(e: &mut Engine, p: &Value) -> Result<Value> {
};
let mut nc = c.clone();
nc.id = s.new_clip_id();
// Note-split has always copied only the matching notes, not controllers. SysEx is the same
// default now that Sequence has that field: packets stay on the source clip. Full SysEx
// split/trim/heal is storytold/soundcraft#1618.
// Note-split copies only the matching notes, not controllers or SysEx: packets stay on the
// source clip. (Split, trim, Merge MIDI and consolidate re-anchor packets to the new clip
// start.)
nc.content = ClipContent::Midi { sequence: soundcraft_midi::Sequence { notes: hit, ctrls: Vec::new(), sysex: Vec::new() } };
crate::edit::place_clip(s, nt, nc);
}
@@ -965,7 +965,7 @@ mod tests {
}
/// Note-split copies only the notes in the pitch range. SysEx already on the clip stays there;
/// the new clip's sysex list is empty (storytold/soundcraft#1618 owns split/trim of packets).
/// the new clip's sysex list is empty.
#[test]
fn note_split_leaves_sysex_on_the_source_clip() {
let (mut e, t) = midi_engine();
+16 -1
View File
@@ -44,6 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
for t in &mut s.tracks { for pl in &mut t.playlists { pl.clips.clear() } }
s.sources.clear();
s.videos.clear();
s.room_tone = None;
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
// A template too large to open is not saved (#892).
crate::io::session_size(file.display(), text.len() as u64, true)?;
@@ -73,7 +74,21 @@ pub fn specs() -> Vec<CommandSpec> {
let at = position_param(e, "file.import_midi", p, "at")?.unwrap_or(0);
let bytes = crate::io::read_file(&path)?;
let tracks = crate::io::import_midi_bytes(e, &bytes, at, bool_or(p, "tempo_map", true))?;
Ok(json!({"tracks": tracks}))
let sysex_packets: usize = tracks
.iter()
.filter_map(|id| e.session().track(*id))
.flat_map(|t| t.clips())
.map(|c| match &c.content {
soundcraft_model::ClipContent::Midi { sequence } => sequence.sysex.len(),
_ => 0,
})
.sum();
let mut result = json!({"tracks": tracks});
if sysex_packets > 0 {
result["sysex_packets"] = json!(sysex_packets);
result["warnings"] = json!(["SysEx packets are retained for session saves and MIDI export; SysEx playback is not supported."]);
}
Ok(result)
}),
cmd!(
"file.import_video",
+7 -2
View File
@@ -36,12 +36,17 @@ pub fn set_flags(e: &mut Engine, ids: &[&str], on: bool) -> Value {
json!({"flags": ids, "value": on})
}
/// A string setting as [`set_text`] stores it: trimmed, cut to 200 characters, then trimmed again.
/// The second trim drops a space at the cut, so a later call returns the same string. Empty clears it.
pub fn text_value(value: &str) -> String {
value.trim().chars().take(200).collect::<String>().trim_end().to_string()
}
/// String settings live in `edit.flags` as `key=value` (one per key).
pub fn set_text(edit: &mut EditState, key: &str, value: Option<&str>) {
let prefix = format!("{key}=");
edit.flags.retain(|f| !f.starts_with(&prefix));
if let Some(v) = value.map(str::trim).filter(|v| !v.is_empty()) {
let v: String = v.chars().take(200).collect();
if let Some(v) = value.map(text_value).filter(|v| !v.is_empty()) {
edit.flags.insert(format!("{prefix}{v}"));
}
}
+489
View File
@@ -0,0 +1,489 @@
//! Room tone: choose a stretch of recorded silence and fill gaps with it instead of digital silence.
//!
//! The fill is made of ordinary audio clips that play the chosen window, overlapped and
//! crossfaded where the gap is longer than the tone, so it can be edited like any other clip.
use super::{CommandSpec, always, bad, clip_ids_param, f64_or, has_range, range_param, tracks_required};
use crate::{Engine, Result, cmd};
use serde_json::{Value, json};
use soundcraft_model::{Clip, ClipContent, Fade, FadeShape, RoomTone, Session, TrackId, TrackKind};
use soundcraft_time::{Range, Samples};
const SET: &str = "edit.room_tone_set";
const FILL: &str = "edit.room_tone_fill";
/// The shortest room tone accepted, in seconds: shorter windows tile into a buzz and many clips.
const MIN_TONE_SECONDS: f64 = 0.1;
/// The most clips one fill makes, so a huge range can't flood the playlist.
const MAX_FILL_CLIPS: usize = 20_000;
/// The name the fill clips get.
const CLIP_NAME: &str = "Room Tone";
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"edit.room_tone_set",
"Set Room Tone",
["Edit", "Room Tone"],
None,
"{clip?} — the clip (default: the selected clip) becomes the session's room tone; with no `clip`, an edit selection inside the clip picks just that part. At least 0.1 s, not elastic. Returns the window",
always,
set
),
cmd!(
"edit.room_tone_fill",
"Fill Gaps with Room Tone",
["Edit", "Room Tone"],
None,
"{tracks?, start?, end?, fade_ms?: 10, edge_fade_ms?: 2, min_gap_ms?: 0} — fills every empty stretch of the range on each audio track with clips of the room tone, tiled with crossfades of `fade_ms` where the gap is longer than the tone, and faded in and out over `edge_fade_ms` at the edges of each gap (short, so the background does not dip next to speech); gaps shorter than `min_gap_ms` are left alone. Returns {clips, gaps}",
fillable,
fill
),
cmd!(
"edit.room_tone_clear",
"Clear Room Tone",
["Edit", "Room Tone"],
None,
"{} — forgets the room tone; clips already filled stay",
has_tone,
|e, _| {
let was = e.session_mut().room_tone.take();
Ok(json!({"cleared": was.is_some()}))
}
),
cmd!(query "edit.room_tone", "Room Tone", [], None, "{} — the room tone window {source, offset, length, gain_db}, or null", always, |e, _| {
Ok(e.session().room_tone.map_or(Value::Null, |t| describe(e.session(), t)))
}),
]
}
fn has_tone(e: &Engine) -> std::result::Result<(), String> {
if e.session().room_tone.is_some() { Ok(()) } else { Err("set a room tone first (Edit › Room Tone › Set Room Tone)".into()) }
}
fn fillable(e: &Engine) -> std::result::Result<(), String> {
has_tone(e)?;
has_range(e)
}
fn describe(s: &Session, t: RoomTone) -> Value {
let name = s.source(t.source).map(|f| f.name.clone());
json!({"source": t.source.0, "source_name": name, "offset": t.offset, "length": t.length, "gain_db": t.gain_db})
}
fn set(e: &mut Engine, p: &Value) -> Result<Value> {
let explicit = p.get("clip").is_some() || p.get("clips").is_some();
let ids = clip_ids_param(e, p);
let s = e.session();
let id = match ids.as_slice() {
[id] => *id,
[] => return Err(bad(SET, "select the clip of room tone, or pass `clip`")),
_ => return Err(bad(SET, "select one clip of room tone, not several")),
};
let (_, clip) = s.find_clip(id).ok_or_else(|| bad(SET, format!("no clip with id {}", id.0)))?;
let ClipContent::Audio { source, .. } = clip.content else {
return Err(bad(SET, format!("“{}” is not an audio clip", clip.name)));
};
if (clip.stretch - 1.0).abs() > f64::EPSILON {
return Err(bad(SET, format!("“{}” is time-stretched; render it first", clip.name)));
}
// An edit selection inside the clip picks part of it.
let sel = s.edit.selection;
let window = if explicit || sel.is_empty() {
clip.range()
} else {
sel.intersect(&clip.range()).ok_or_else(|| bad(SET, "the edit selection is outside the clip"))?
};
let offset = clip.source_offset().saturating_add(window.start - clip.start);
let stored = s.source(source).map(|f| f.frames).ok_or_else(|| bad(SET, format!("the audio file of “{}” is missing", clip.name)))?;
// The stored count isn't refreshed when a session reopens; the decoded audio is what plays.
let frames = s.pool.get(source).map_or(stored, |a| a.frames() as u64);
let tone = RoomTone { source, offset, length: window.len(), gain_db: clip.gain_db }
.sanitized(frames)
.ok_or_else(|| bad(SET, format!("“{}” plays no audio from its file", clip.name)))?;
if tone.length < s.sample_rate.samples(MIN_TONE_SECONDS) {
return Err(bad(SET, format!("room tone must be at least {MIN_TONE_SECONDS} s long")));
}
let s = e.session_mut();
// A session reopens with the room tone cut to the stored count, so record the decoded one.
if let Some(f) = s.sources.iter_mut().find(|f| f.id == source && f.frames < frames) {
f.frames = frames;
}
s.room_tone = Some(tone);
Ok(describe(e.session(), tone))
}
/// The empty stretches of `range` on `track`'s active playlist, at least `min` samples long.
fn gaps(s: &Session, track: TrackId, range: Range, min: Samples) -> Vec<Range> {
let Some(t) = s.track(track) else { return Vec::new() };
let mut out = Vec::new();
let mut at = range.start;
let mut clips: Vec<Range> = t.clips().iter().map(Clip::range).filter(|r| r.end > range.start && r.start < range.end).collect();
clips.sort_by_key(|r| r.start);
for c in clips {
if c.start > at {
out.push(Range::new(at, c.start));
}
at = at.max(c.end);
}
if at < range.end {
out.push(Range::new(at, range.end));
}
out.retain(|g| g.len() >= min.max(1));
out
}
/// The clips that fill `gap` with `tone`: whole tone windows, each overlapping the one before by
/// `fade` samples with a crossfade, the last cut to the gap's end; the first fades in and the last
/// fades out over `edge` (or less, in a short gap). `None` when that takes more than `budget` clips.
fn tiles(tone: RoomTone, gap: Range, fade: Samples, edge: Samples, budget: usize) -> Option<Vec<Clip>> {
let edge = edge.max(0);
// The overlap must leave each tile moving forward.
let fade = fade.clamp(0, tone.length / 2);
let step = tone.length - fade;
if step <= 0 {
return Some(Vec::new());
}
// Count before allocating: a long gap and a short tone could otherwise make millions.
let needed = gap.len().saturating_sub(fade).max(1).saturating_add(step - 1) / step;
if usize::try_from(needed).map_or(true, |n| n > budget) {
return None;
}
let mut out: Vec<Clip> = Vec::new();
let mut at = gap.start;
while at < gap.end && out.len() <= budget {
let length = tone.length.min(gap.end - at);
let mut c = Clip::audio(soundcraft_model::ClipId(0), CLIP_NAME, tone.source, tone.offset, at, length);
c.gain_db = tone.gain_db;
let crossfade = Fade { len: fade.min(length), shape: FadeShape::EqualPower, curvature: 0.0 };
if let Some(prev) = out.last_mut() {
prev.fade_out = crossfade;
c.fade_in = crossfade;
} else {
c.fade_in = Fade { len: edge.min(length / 2), ..crossfade };
}
if at + length >= gap.end {
// The last tile also fades out to the gap's edge, leaving room for its fade in.
c.fade_out = Fade { len: edge.min(length - c.fade_in.len).max(0), ..crossfade };
out.push(c);
break;
}
out.push(c);
at = at.saturating_add(step);
}
(out.len() <= budget).then_some(out)
}
fn fill(e: &mut Engine, p: &Value) -> Result<Value> {
let tone = e.session().room_tone.ok_or_else(|| bad(FILL, "set a room tone first"))?;
let tracks = tracks_required(e, FILL, p)?;
let range = range_param(e, FILL, p)?;
if range.is_empty() {
return Err(bad(FILL, "select a range to fill"));
}
let s = e.session();
let name = s.source(tone.source).map_or_else(|| "the room tone's audio file".to_string(), |f| format!("`{}`", f.name));
let Some(audio) = s.pool.get(tone.source) else {
return Err(bad(FILL, format!("{name} is not loaded; relink it before filling")));
};
// The window was checked against the session file's frame count, which can be stale when the
// file was replaced by a shorter one: tile only audio that decoded.
let tone = tone
.sanitized(audio.frames() as u64)
.filter(|t| t.length >= s.sample_rate.samples(MIN_TONE_SECONDS))
.ok_or_else(|| bad(FILL, format!("{name} is now shorter than the room tone; set the room tone again")))?;
let ms = |k: &str, d: f64| s.sample_rate.samples(f64_or(p, k, d).clamp(0.0, 10_000.0) / 1000.0);
let (fade, edge, min_gap) = (ms("fade_ms", 10.0), ms("edge_fade_ms", 2.0), ms("min_gap_ms", 0.0));
// Plan every track first, so a fill that would be too big changes nothing.
let mut plan: Vec<(TrackId, Vec<Clip>)> = Vec::new();
let (mut count, mut gap_count) = (0usize, 0usize);
for t in tracks {
if s.track(t).is_none_or(|tr| tr.kind != TrackKind::Audio) {
continue;
}
let mut clips = Vec::new();
for gap in gaps(s, t, range, min_gap) {
let budget = MAX_FILL_CLIPS.saturating_sub(count.saturating_add(clips.len()));
let made = tiles(tone, gap, fade, edge, budget).ok_or_else(|| {
bad(FILL, format!("that would make more than {MAX_FILL_CLIPS} clips; fill a shorter range or use a longer room tone"))
})?;
clips.extend(made);
gap_count += 1;
}
count += clips.len();
plan.push((t, clips));
}
if gap_count == 0 {
return Err(bad(FILL, "no empty space to fill on the audio tracks in that range"));
}
let s = e.session_mut();
for (t, mut clips) in plan {
for c in &mut clips {
c.id = s.new_clip_id();
}
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
pl.clips.extend(clips);
pl.sort();
}
}
Ok(json!({"clips": count, "gaps": gap_count}))
}
#[cfg(test)]
mod tests {
use super::*;
use craft_audio::AudioBuffer;
use soundcraft_model::{ChannelFormat, ClipId, FileFormat, SourceAudio, SourceId};
use std::sync::Arc;
const RATE: Samples = 48_000;
/// A session with one mono track holding `clips` (start, length) of a 10 s source, the first
/// of which plays 1 s of room tone from the start of the file.
fn engine(clips: &[(Samples, Samples)]) -> (Engine, TrackId, Vec<ClipId>) {
let mut e = Engine::default();
let s = e.session_mut();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Narration"));
let src = SourceId(s.alloc());
let frames = 10 * RATE as usize;
s.sources.push(soundcraft_model::Source {
id: src,
name: "Take".into(),
path: "Take.wav".into(),
channels: 1,
frames: frames as u64,
sample_rate: 48_000,
format: FileFormat::Wav,
time_reference: 0,
unsaved: false,
});
// Quiet white noise, like a room: uncorrelated from one moment to the next.
let mut seed = 0x2545_f491_u32;
let noise: Vec<f32> = (0..frames)
.map(|_| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
(seed as f32 / u32::MAX as f32 - 0.5) * 0.02
})
.collect();
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![noise] };
s.pool.insert(src, Arc::new(SourceAudio::new(buffer)));
let mut ids = Vec::new();
for (i, (start, length)) in clips.iter().enumerate() {
let id = s.new_clip_id();
let offset = if i == 0 { 0 } else { RATE * 2 };
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
pl.clips.push(Clip::audio(id, format!("Clip {i}"), src, offset, *start, *length));
pl.sort();
}
ids.push(id);
}
s.edit.selected_tracks = vec![t];
(e, t, ids)
}
fn clips(e: &Engine, t: TrackId) -> Vec<Clip> {
e.session().track(t).map(|tr| tr.clips().to_vec()).unwrap_or_default()
}
#[test]
fn set_takes_the_selected_clip_or_the_selected_part_of_it() {
let (mut e, _, ids) = engine(&[(0, RATE)]);
e.session_mut().edit.selected_clips = vec![ids[0]];
let r = e.execute(SET, &json!({})).unwrap();
assert_eq!((r["offset"].as_i64(), r["length"].as_i64()), (Some(0), Some(RATE)));
e.session_mut().edit.selected_clips.clear();
e.session_mut().edit.selection = Range::new(RATE / 4, RATE / 2);
let r = e.execute(SET, &json!({})).unwrap();
assert_eq!((r["offset"].as_i64(), r["length"].as_i64()), (Some(RATE / 4), Some(RATE / 4)));
e.execute("edit.undo", &json!({})).unwrap();
assert_eq!(e.session().room_tone.map(|t| t.length), Some(RATE), "undo restores the previous tone");
}
#[test]
fn a_tone_past_a_stale_stored_length_survives_a_reload() {
// The session file says 3 s, but 10 s decoded: the tone at 4..5 s plays.
let (mut e, t, _) = engine(&[]);
let s = e.session_mut();
let src = s.sources.first().map(|f| f.id).unwrap();
s.sources.iter_mut().for_each(|f| f.frames = 3 * RATE as u64);
let id = s.new_clip_id();
if let Some(pl) = s.track_mut(t).and_then(|tr| tr.playlist_mut()) {
pl.clips.push(Clip::audio(id, "Late", src, 4 * RATE, 0, RATE));
}
e.execute(SET, &json!({"clip": id.0})).unwrap();
let tone = e.session().room_tone;
assert_eq!(tone.map(|t| (t.offset, t.length)), Some((4 * RATE, RATE)));
let loaded = Session::from_json(&e.session().to_json().unwrap()).unwrap();
assert_eq!(loaded.room_tone, tone, "reopening keeps the tone that was set");
}
#[test]
fn set_refuses_what_cannot_be_a_room_tone() {
let (mut e, t, ids) = engine(&[(0, RATE / 20)]);
assert!(e.execute(SET, &json!({"clip": ids[0].0})).is_err(), "50 ms is too short");
assert!(e.execute(SET, &json!({"clip": 9999})).is_err(), "unknown clip");
e.session_mut().edit.selected_tracks = vec![t];
e.session_mut().edit.selection = Range::new(RATE * 5, RATE * 6);
assert!(e.execute(SET, &json!({})).is_err(), "nothing selected");
assert_eq!(e.session().room_tone, None);
assert!(e.execute(FILL, &json!({"start": 0, "end": RATE})).is_err(), "no tone to fill with");
}
#[test]
fn fill_puts_crossfaded_tone_clips_in_every_gap_and_nowhere_else() {
// Tone 0..1 s, speech 3..4 s; fill 0..6 s: gaps 1..3 s (2 s) and 4..6 s (2 s).
let (mut e, t, ids) = engine(&[(0, RATE), (3 * RATE, RATE)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
let fade = RATE / 100;
let r = e.execute(FILL, &json!({"start": 0, "end": 6 * RATE})).unwrap();
assert_eq!(r["gaps"], 2);
let fills: Vec<Clip> = clips(&e, t).into_iter().filter(|c| !ids.contains(&c.id)).collect();
assert_eq!(r["clips"].as_u64(), Some(fills.len() as u64));
for gap in [Range::new(RATE, 3 * RATE), Range::new(4 * RATE, 6 * RATE)] {
let mut in_gap: Vec<&Clip> = fills.iter().filter(|c| gap.contains(c.start)).collect();
in_gap.sort_by_key(|c| c.start);
// 2 s of a 1 s tone with 10 ms overlaps: three tiles, the last cut short.
assert_eq!(in_gap.len(), 3, "{gap:?}");
assert_eq!(in_gap.first().map(|c| c.start), Some(gap.start));
assert_eq!(in_gap.last().map(|c| c.end()), Some(gap.end), "the fill ends at the gap's edge");
for pair in in_gap.windows(2) {
assert_eq!(pair[0].end() - pair[1].start, fade, "neighbours overlap by the crossfade");
assert_eq!((pair[0].fade_out.len, pair[1].fade_in.len), (fade, fade));
}
let edge = RATE / 500;
assert_eq!(in_gap[0].fade_in.len, edge, "a short de-click fade at the gap's edges");
assert!(in_gap.last().is_some_and(|c| c.fade_out.len == edge));
for c in &in_gap {
assert_eq!(c.name, CLIP_NAME);
assert_eq!(c.source_offset(), 0);
assert!(c.length <= RATE);
}
}
// The original clips are untouched and nothing covers them.
let all = clips(&e, t);
for id in &ids {
let c = all.iter().find(|c| c.id == *id).unwrap();
assert!(fills.iter().all(|f| !f.range().overlaps(&c.range())), "fill over {}", c.name);
}
e.execute("edit.undo", &json!({})).unwrap();
assert_eq!(clips(&e, t).len(), 2, "undo removes the whole fill");
}
#[test]
fn the_fill_plays_at_the_tones_level_through_every_crossfade() {
let (mut e, t, ids) = engine(&[(0, RATE)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
e.execute(FILL, &json!({"tracks": [t.0], "start": 0, "end": 5 * RATE, "fade_ms": 50})).unwrap();
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 5 * RATE), 512);
let left = &out[0];
let rms = |a: usize, b: usize| (left[a..b].iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / (b - a) as f64).sqrt();
let tone = rms(0, RATE as usize);
assert!(tone > 0.0);
// 20 ms windows from where the tone clip ends to the end of the fill: the edge fades are
// too short to dip a window, and the crossfades keep the power.
let win = (RATE / 50) as usize;
for w in (RATE as usize..(5 * RATE) as usize - win).step_by(win) {
let db = 20.0 * (rms(w, w + win) / tone).log10();
assert!(db.abs() < 1.5, "level {db:.2} dB off the tone at {} s", w as f64 / RATE as f64);
}
}
#[test]
fn fill_skips_short_gaps_and_refuses_when_nothing_is_empty() {
let (mut e, t, ids) = engine(&[(0, RATE), (RATE + 100, RATE)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
assert!(e.execute(FILL, &json!({"start": 0, "end": 2 * RATE + 100, "min_gap_ms": 5})).is_err(), "the 100-sample gap is under 5 ms");
let r = e.execute(FILL, &json!({"start": 0, "end": 2 * RATE + 100})).unwrap();
assert_eq!((r["gaps"].as_u64(), r["clips"].as_u64()), (Some(1), Some(1)));
let short = clips(&e, t).into_iter().find(|c| !ids.contains(&c.id)).unwrap();
assert_eq!((short.start, short.length), (RATE, 100));
assert!(short.fade_in.len + short.fade_out.len <= short.length, "fades fit a short gap");
assert_eq!((short.fade_in.len, short.fade_out.len), (50, 50));
}
#[test]
fn a_fill_too_big_changes_nothing() {
let (mut e, t, ids) = engine(&[(0, RATE / 5)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
// 200 ms tiles over 4 hours is far more than the cap.
let r = e.execute(FILL, &json!({"start": 0, "end": RATE * 4 * 3600}));
assert!(r.is_err());
assert_eq!(clips(&e, t).len(), 1);
}
#[test]
fn fill_ignores_non_audio_tracks_and_needs_loaded_audio() {
let (mut e, t, ids) = engine(&[(0, RATE)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
let aux = e.session_mut().add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
let r = e.execute(FILL, &json!({"tracks": [t.0, aux.0], "start": 0, "end": 2 * RATE})).unwrap();
assert_eq!(r["gaps"], 1);
let tone = e.session().room_tone.unwrap();
e.session_mut().pool.remove(tone.source);
assert!(e.execute(FILL, &json!({"start": 0, "end": 3 * RATE})).is_err(), "unloaded audio is not filled with");
}
/// Replaces the tone's pooled audio with `frames` frames of silence, as when its file was
/// swapped for a shorter one: the stored `Source.frames` keeps the old length.
fn shorten_audio(e: &mut Engine, frames: usize) {
let src = e.session().sources.first().map(|f| f.id).unwrap();
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; frames]] };
e.session_mut().pool.insert(src, Arc::new(SourceAudio::new(buffer)));
}
#[test]
fn fill_reads_only_the_audio_that_decoded() {
// Tone 0..1 s; the file now decodes to 0.5 s.
let (mut e, t, ids) = engine(&[(0, RATE)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
shorten_audio(&mut e, (RATE / 2) as usize);
e.execute(FILL, &json!({"start": 0, "end": 3 * RATE})).unwrap();
let fills: Vec<Clip> = clips(&e, t).into_iter().filter(|c| !ids.contains(&c.id)).collect();
assert!(!fills.is_empty());
for c in &fills {
assert!(c.source_offset() + c.length <= RATE / 2, "a fill clip reads past the decoded audio: {c:?}");
}
// Less than the minimum left: refused, nothing placed.
shorten_audio(&mut e, (RATE / 20) as usize);
let before = clips(&e, t).len();
assert!(e.execute(FILL, &json!({"start": 0, "end": 6 * RATE})).is_err());
assert_eq!(clips(&e, t).len(), before);
}
#[test]
fn set_measures_the_window_against_the_decoded_audio() {
let (mut e, _, ids) = engine(&[(0, RATE)]);
shorten_audio(&mut e, (RATE / 2) as usize);
let r = e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
assert_eq!(r["length"].as_i64(), Some(RATE / 2));
shorten_audio(&mut e, (RATE / 20) as usize);
assert!(e.execute(SET, &json!({"clip": ids[0].0})).is_err(), "only 50 ms decoded");
}
#[test]
fn clear_forgets_the_tone_but_keeps_the_fill() {
let (mut e, t, ids) = engine(&[(0, RATE)]);
e.execute(SET, &json!({"clip": ids[0].0})).unwrap();
e.execute(FILL, &json!({"start": 0, "end": 2 * RATE})).unwrap();
e.execute("edit.room_tone_clear", &json!({})).unwrap();
assert_eq!(e.session().room_tone, None);
assert_eq!(e.execute("edit.room_tone", &json!({})).unwrap(), Value::Null);
assert_eq!(clips(&e, t).len(), 2);
}
#[test]
fn tiles_never_stall_or_overrun_on_odd_lengths() {
let tone = RoomTone { source: SourceId(1), offset: 0, length: 3, gain_db: 0.0 };
for (gap, fade) in [(Range::new(0, 1), 10), (Range::new(5, 17), 2), (Range::new(0, 1000), 0), (Range::new(0, 7), 1000)] {
let t = tiles(tone, gap, fade, fade, MAX_FILL_CLIPS).unwrap();
assert_eq!(t.first().map(|c| c.start), Some(gap.start));
assert_eq!(t.last().map(Clip::end), Some(gap.end));
assert!(t.iter().all(|c| c.length > 0 && c.fade_in.len + c.fade_out.len <= c.length), "{gap:?} {fade}");
}
let huge = Range::new(0, soundcraft_time::MAX_POSITION);
assert!(tiles(tone, huge, 0, 0, MAX_FILL_CLIPS).is_none(), "refused before allocating");
assert_eq!(tiles(tone, Range::new(0, 9), 0, 0, 3).map(|t| t.len()), Some(3), "exactly the budget is fine");
}
}
+10 -2
View File
@@ -2,7 +2,7 @@
//! shortcuts, MIDI setup) and File › Import › Session Data.
use super::{CommandSpec, always, bad, command_specs, i64_or, str_param, track_param, tracks_param};
use super::more_util::{set_text, store_value, text, toggle_flag, values_with_prefix};
use super::more_util::{set_text, store_value, text, text_value, toggle_flag, values_with_prefix};
use crate::{Engine, EngineError, Result, cmd};
use serde_json::{Value, json};
use soundcraft_model::{BusId, ChannelFormat, ClipContent, OutputPath, Route, Session, SourceId, TrackId, TrackKind};
@@ -242,8 +242,16 @@ fn engine_settings(e: &mut Engine, p: &Value, id: &str) -> Result<Value> {
fn disk_allocation(e: &mut Engine, p: &Value) -> Result<Value> {
let id = "setup.disk_allocation";
let t = track_param(e, id, p, "track")?;
// The path that is checked is the path that is stored. `text_value` trims, cuts to 200
// characters, and trims again, which is what `set_text` keeps.
// An empty one clears the setting and names no folder, so it isn't checked.
let path = str_param(p, "path").map(text_value);
// Checked before `session_mut` so a refused path leaves the session untouched.
if let Some(path) = path.as_deref().filter(|v| !v.is_empty()) {
crate::file_access::check_write(path).map_err(EngineError::Io)?;
}
let s = e.session_mut();
if let Some(path) = str_param(p, "path") {
if let Some(path) = path.as_deref() {
let key = t.map_or_else(|| "disk.root".to_string(), |t| format!("disk.track.{}", t.0));
set_text(&mut s.edit, &key, Some(path));
}
+43 -1
View File
@@ -295,7 +295,23 @@ fn new_track_row(e: &mut Engine, p: &Value) -> Result<Vec<TrackId>> {
};
let name = str_param(p, "name").map(str::to_string);
let ticks = str_param(p, "timebase").map(|t| t == "ticks");
let instrument = str_param(p, "instrument").map(str::to_string);
// A missing instrument asks for the default; an explicit value must be a string plugin id,
// even before a non-instrument row ignores it, so a number is not silently treated as absent.
let instrument = match p.get("instrument") {
None => None,
Some(value) => {
let id = value.as_str().ok_or_else(|| bad("track.new", "`instrument` must be a plugin id string"))?;
if kind == TrackKind::Instrument {
let info = super::clap::plugin_info(id).ok_or_else(|| bad("track.new", format!("unknown plugin `{id}`")))?;
if !info.is_instrument {
return Err(bad("track.new", format!("`{id}` is not an instrument")));
}
Some(info.id.to_string())
} else {
None
}
}
};
let s = e.session_mut();
let mut ids = Vec::new();
for _ in 0..count {
@@ -1281,4 +1297,30 @@ mod tests {
assert!(e.undo());
assert_eq!(vca(&e), Some(master.0));
}
#[test]
fn new_instrument_track_validates_the_instrument_id() {
let mut e = Engine::default();
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": "no.such.plugin"})).is_err());
assert_eq!(e.session().tracks.len(), 0);
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": "eq_7band"})).is_err());
assert_eq!(e.session().tracks.len(), 0);
// An explicit non-string is malformed, not a request for the default.
assert!(e.execute("track.new", &json!({"kind": "instrument", "instrument": 42})).is_err());
assert_eq!(e.session().tracks.len(), 0);
// In a batch, a malformed second row rolls the first row back too.
let batch = json!({"rows": [
{"kind": "instrument", "instrument": "drum_synth"},
{"kind": "instrument", "instrument": 42},
]});
assert!(e.execute("track.new", &batch).is_err());
assert_eq!(e.session().tracks.len(), 0);
// Omitted still asks for the default instrument.
let r = e.execute("track.new", &json!({"kind": "instrument"})).unwrap();
let id = TrackId(r["tracks"][0].as_u64().unwrap());
assert_eq!(e.session().track(id).unwrap().instrument.as_ref().unwrap().plugin, "subtractive_synth");
let r = e.execute("track.new", &json!({"kind": "instrument", "instrument": "drum_synth"})).unwrap();
let id = TrackId(r["tracks"][0].as_u64().unwrap());
assert_eq!(e.session().track(id).unwrap().instrument.as_ref().unwrap().plugin, "drum_synth");
}
}
+3
View File
@@ -325,6 +325,9 @@ mod tests {
doc.pool.remove(SourceId(900));
check(&saved, &doc, false, "decoded audio removed");
let mut doc = saved.clone();
doc.room_tone = Some(soundcraft_model::RoomTone { source: SourceId(900), offset: 0, length: 10, gain_db: 0.0 });
check(&saved, &doc, false, "session room tone");
let mut doc = saved.clone();
doc.folder = Some(std::path::PathBuf::from("session"));
check(&saved, &doc, false, "session folder");
let mut doc = saved.clone();
+13
View File
@@ -48,14 +48,19 @@ pub fn split_clip(clip: &Clip, at: Samples, new_id: ClipId, t: TimeCtx<'_>) -> O
let boundary = t.ticks(at) - t.ticks(clip.start);
ls.notes.retain(|n| n.start < boundary);
ls.ctrls.retain(|c| c.tick < boundary);
ls.sysex.retain(|e| e.tick < boundary);
rs.notes.retain(|n| n.start >= boundary);
rs.ctrls.retain(|c| c.tick >= boundary);
rs.sysex.retain(|e| e.tick >= boundary);
for n in &mut rs.notes {
n.start -= boundary;
}
for c in &mut rs.ctrls {
c.tick -= boundary;
}
for e in &mut rs.sysex {
e.tick -= boundary;
}
}
Some((left, right))
}
@@ -69,12 +74,16 @@ fn rebase_midi_start(clip: &mut Clip, old_start: Samples, t: TimeCtx<'_>) {
}
sequence.notes.retain(|n| n.start >= delta);
sequence.ctrls.retain(|c| c.tick >= delta);
sequence.sysex.retain(|e| e.tick >= delta);
for n in &mut sequence.notes {
n.start -= delta;
}
for c in &mut sequence.ctrls {
c.tick -= delta;
}
for e in &mut sequence.sysex {
e.tick -= delta;
}
}
}
@@ -323,6 +332,10 @@ pub fn consolidate_midi(s: &mut Session, track: TrackId, range: Range) -> bool {
c.tick += at;
merged.ctrls.push(c);
}
for mut e in sequence.sysex.into_iter().filter(|e| (0..len).contains(&e.tick)) {
e.tick += at;
merged.sysex.push(e);
}
}
}
merged.sort();
+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");
+16
View File
@@ -335,6 +335,8 @@ pub struct Bounce {
gain: f32,
peak: f32,
meter: soundcraft_dsp::meter::LoudnessMeter,
/// The file has an integer bit depth, so the encoder clips to full scale (a float file keeps its headroom).
integer: bool,
enc: Option<craft_audio::FileEncoder<Out>>,
}
@@ -409,6 +411,7 @@ impl Bounce {
peak: 0.0,
meter,
enc: Some(enc),
integer: opts.bit_depth != craft_audio::BitDepth::Float32,
})
}
@@ -438,6 +441,19 @@ impl Bounce {
Some((chunk, n)) => {
fill(&mut self.block, chunk, n, self.fold, self.gain);
self.done += n;
if !self.measuring {
// The encoder clips an integer file to full scale and maps a float file's NaN to 0 and
// infinities to +-1, so the report must describe what it writes.
for v in self.block.iter_mut().flatten() {
*v = if v.is_nan() {
0.0
} else if self.integer || v.is_infinite() {
v.clamp(-1.0, 1.0)
} else {
*v
};
}
}
self.peak = self.peak.max(soundcraft_dsp::offline::peak(&self.block));
if !self.measuring {
self.meter.process(&self.block, n);
+20 -7
View File
@@ -22,7 +22,11 @@ pub(super) const MAX_MIDI_TRACKS: usize = 512;
pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: bool) -> Result<Vec<TrackId>> {
let smf = match soundcraft_midi::read_smf(bytes) {
Ok(smf) => smf,
Err(err @ (soundcraft_midi::MidiError::TooManyEvents(_) | soundcraft_midi::MidiError::TooManyTracks(_))) => {
Err(
err @ (soundcraft_midi::MidiError::TooManyEvents(_)
| soundcraft_midi::MidiError::TooManyTracks(_)
| soundcraft_midi::MidiError::SysExTooLarge(_)),
) => {
return Err(EngineError::Io(err.to_string()));
}
Err(_) => {
@@ -30,9 +34,10 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
// The strict reader stops at the first damage, so a limit further on shows only here.
if read.over_limit {
return Err(EngineError::Io(format!(
"MIDI file: more than {} events or {} tracks",
"MIDI file exceeds a limit of {} events, {} tracks, or {} bytes of SysEx payload",
soundcraft_midi::MAX_EVENTS,
soundcraft_midi::MAX_TRACKS
soundcraft_midi::MAX_TRACKS,
soundcraft_midi::MAX_SYSEX_BYTES
)));
}
for warning in &read.warnings {
@@ -50,7 +55,8 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TEMPOS} tempo changes")));
}
}
let tracks_to_import = smf.tracks.iter().filter(|tr| !tr.sequence.notes.is_empty() || !tr.sequence.ctrls.is_empty()).count();
let tracks_to_import =
smf.tracks.iter().filter(|tr| !tr.sequence.notes.is_empty() || !tr.sequence.ctrls.is_empty() || !tr.sequence.sysex.is_empty()).count();
if tracks_to_import > MAX_MIDI_TRACKS {
return Err(EngineError::Io(format!("MIDI file: more than {MAX_MIDI_TRACKS} tracks")));
}
@@ -72,12 +78,13 @@ pub fn import_midi_bytes(e: &mut Engine, bytes: &[u8], at: Samples, tempo_map: b
let base_tick = tempo.samples_to_ticks(at, s.sample_rate);
let mut clips = Vec::new();
for (i, tr) in smf.tracks.iter().enumerate() {
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.is_empty() {
if tr.sequence.notes.is_empty() && tr.sequence.ctrls.is_empty() && tr.sequence.sysex.is_empty() {
continue;
}
// A controller on the clip's last tick would not play, so the clip runs one tick past the last one.
let past_ctrls = tr.sequence.ctrls.iter().map(|c| c.tick.saturating_add(1)).max().unwrap_or(0);
let end_tick = base_tick.saturating_add(tr.sequence.end_tick().max(past_ctrls).max(1));
let past_sysex = tr.sequence.sysex.iter().map(|e| e.tick.saturating_add(1)).max().unwrap_or(0);
let end_tick = base_tick.saturating_add(tr.sequence.end_tick().max(past_ctrls).max(past_sysex).max(1));
let len = tempo.tick_to_samples(end_tick, s.sample_rate).saturating_sub(at);
if len > s.sample_rate.samples(86_400.0) {
return Err(EngineError::Io(format!("MIDI track {}: longer than 24 hours", i + 1)));
@@ -125,8 +132,14 @@ pub fn export_midi(e: &Engine, only: Option<&[TrackId]>) -> Result<Vec<u8>> {
for c in t.clips() {
if let ClipContent::Midi { sequence } = &c.content {
let base = s.tempo.samples_to_ticks(c.start, s.sample_rate);
// Only what plays: notes starting inside the clip, cut at its end.
// Only what plays: notes starting inside the clip (cut at its end), and the
// controllers and SysEx inside it.
let clip_end = s.tempo.samples_to_ticks(c.end(), s.sample_rate);
for event in sequence.sysex.iter().filter(|event| event.tick.saturating_add(base) < clip_end) {
let mut event = event.clone();
event.tick = event.tick.saturating_add(base);
seq.sysex.push(event);
}
for n in sequence.notes.iter().filter(|n| n.start.saturating_add(base) < clip_end) {
let mut n = *n;
n.start = n.start.saturating_add(base);
+16
View File
@@ -113,6 +113,9 @@ pub struct TransportStatus {
pub struct Clipboard {
pub length: Samples,
pub tracks: Vec<Vec<Clip>>,
/// Visible duration at copy time. An ordinary paste keeps the underlying clip's trim handles,
/// whereas merging materializes only its selected MIDI events, even after a tempo change.
pub midi_tick_lengths: std::collections::BTreeMap<soundcraft_model::ClipId, i64>,
pub automation: Vec<Vec<soundcraft_model::AutomationLane>>,
/// Copy Special › Clip Gain: per track, (offset from the copied range start, dB) breakpoints.
pub clip_gain: Vec<Vec<(Samples, f32)>>,
@@ -131,6 +134,19 @@ pub struct Clipboard {
}
impl Clipboard {
/// Store one track of range-relative clips and capture the source tempo before a paste.
pub(crate) fn push_clips(&mut self, session: &Session, range_start: Samples, clips: Vec<Clip>) {
for clip in &clips {
if matches!(clip.content, soundcraft_model::ClipContent::Midi { .. }) {
let start = range_start.saturating_add(clip.start);
let end = start.saturating_add(clip.length);
let ticks = |at| session.tempo.samples_to_ticks(at, session.sample_rate);
self.midi_tick_lengths.insert(clip.id, ticks(end).saturating_sub(ticks(start)));
}
}
self.tracks.push(clips);
}
/// An empty clipboard for material copied from `range`.
pub fn of_range(s: &Session, range: soundcraft_time::Range) -> Clipboard {
let line = s.grid_line_at_or_before(range.start);
+33
View File
@@ -66,6 +66,39 @@ fn scratch(name: &str) -> PathBuf {
dir
}
#[test]
fn an_integer_bounce_reports_the_levels_of_the_clipped_file() {
let mut e = soundcraft_engine::Engine::default();
let sr = e.session().sample_rate.hz();
let frames = sr as usize;
let samples: Vec<f32> = (0..frames).map(|i| 1.5 * (std::f32::consts::TAU * 440.0 * i as f32 / sr as f32).sin()).collect();
let audio = craft_audio::AudioBuffer { sample_rate: sr, channels: vec![samples.clone(), samples] };
let s = e.session_mut();
let track = s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::Stereo, Some("Hot"));
let source = soundcraft_engine::io::add_source(s, "hot", audio, None, FileFormat::Wav);
let clip = soundcraft_model::Clip::audio(s.new_clip_id(), "hot", source, 0, 0, frames as i64);
soundcraft_engine::edit::place_clip(s, track, clip);
let mix = soundcraft_mix::render_range(e.session(), Range::new(0, frames as i64), 1024);
assert!(soundcraft_dsp::offline::peak(&mix) > 1.0);
let dir = scratch("bounce-int-clipped");
let path = dir.join("Mix.wav");
let r = e.execute("file.bounce_mix", &serde_json::json!({"path": path, "bit_depth": 16, "dither": false, "start": 0, "end": frames})).unwrap();
let (_, file) = craft_audio::decode(&std::fs::read(&path).unwrap(), None).unwrap();
assert!(file.peak() <= 1.0);
let mut meter = soundcraft_dsp::meter::LoudnessMeter::new(sr as f32, file.channels.len());
meter.process(&file.channels, file.frames());
for (key, value, tolerance) in [
("peak_db", soundcraft_dsp::offline::peak_db(&file.channels), 0.01),
("lufs", meter.integrated_lufs(), 0.05),
("true_peak_db", meter.true_peak_db(), 0.05),
] {
let reported = r[key].as_f64().unwrap();
assert!((reported - f64::from(value)).abs() < tolerance, "{key}: reported {reported}, file {value}");
}
assert!(r["peak_db"].as_f64().unwrap() <= 0.0);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn bounces_write_exactly_the_mix_and_report_its_levels() {
let e = soundcraft_engine::demo::demo_engine();
+2
View File
@@ -17,8 +17,10 @@ mod new_track_rows;
mod processing_keeps_crossfades;
mod random_edits;
mod recording;
mod session_inspect;
mod session_transport;
mod split_into_mono;
mod sysex_import;
mod time_key_signatures;
mod track_name_collisions;
mod trim_to_selection;
+185
View File
@@ -0,0 +1,185 @@
//! `session.inspect` reports what the README promises: tracks, clips, mixer, markers and the last
//! undo and redo labels, so two inspections taken around an edit show what the edit changed.
use serde_json::{Value, json};
use soundcraft_engine::Engine;
/// The engine's current `session.inspect` reply, with default (summary) detail.
fn inspect(e: &mut Engine) -> Value {
e.execute("session.inspect", &json!({})).expect("session.inspect")
}
/// The engine's current `session.inspect` reply with `{"detail": "full"}`.
fn inspect_full(e: &mut Engine) -> Value {
e.execute("session.inspect", &json!({"detail": "full"})).expect("session.inspect full")
}
/// Asserts the README's promise on one reply: typed mixer fields and clips on every track, typed
/// markers, and history labels that are each a string or null.
fn assert_reports_session_state(v: &Value) {
let tracks = v["tracks"].as_array().expect("tracks");
assert!(!tracks.is_empty());
for t in tracks {
assert!(t["clips"].is_array(), "{t}");
assert!(t["volume_db"].is_number(), "volume_db in {t}");
let pan = t["pan"].as_array().expect("pan is one value per channel");
assert!(!pan.is_empty() && pan.iter().all(Value::is_number), "pan in {t}");
assert!(t["mute"].is_boolean(), "mute in {t}");
assert!(t["solo"].is_boolean(), "solo in {t}");
assert!(t["inserts"].is_array(), "inserts in {t}");
assert!(t["sends"].is_array(), "sends in {t}");
}
assert!(tracks.iter().any(|t| !t["clips"].as_array().unwrap().is_empty()), "the demo has clips");
let markers = v["markers"].as_array().expect("markers");
assert!(!markers.is_empty(), "the demo has markers");
for m in markers {
assert!(m["id"].is_u64(), "id in {m}");
assert!(m["number"].is_u64(), "number in {m}");
assert!(m["name"].is_string(), "name in {m}");
assert!(m["start"].is_u64(), "start in {m}");
assert!(m["end"].is_u64(), "end in {m}");
}
for key in ["undo", "redo"] {
let label = v.get(key).unwrap_or_else(|| panic!("{key} missing from {v}"));
assert!(label.is_string() || label.is_null(), "{key} in {v}");
}
}
/// The README text with line breaks and indentation folded to single spaces.
fn readme() -> String {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../README.md");
std::fs::read_to_string(path).expect("README.md").split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Adds one track with default parameters and returns its id.
fn new_track(e: &mut Engine) -> Value {
e.execute("track.new", &json!({})).expect("track.new")["tracks"][0].clone()
}
/// The track with this id in an inspection; panics with the whole reply when it is absent.
fn track<'a>(v: &'a Value, id: &Value) -> &'a Value {
v["tracks"].as_array().and_then(|ts| ts.iter().find(|t| &t["id"] == id)).unwrap_or_else(|| panic!("track {id} in {v}"))
}
/// The README describes `session.inspect` as current state plus history labels, not a change report.
#[test]
fn readme_describes_inspect_as_current_state() {
let text = readme();
let sentence =
["`session.inspect` returns the session's current state (tracks, clips, mixer, markers)", "and the last undo and redo step labels"];
assert!(text.contains(&sentence.join(" ")), "README sentence about session.inspect");
assert!(!text.contains("reports exactly what changed"), "the old change-report wording is back");
}
/// Every track carries its clips and mixer fields, and the session lists its markers.
#[test]
fn inspect_reports_tracks_clips_mixer_and_markers() {
let mut e = soundcraft_engine::demo::demo_engine();
assert_reports_session_state(&inspect(&mut e));
}
/// Full detail reports the same state, and adds each insert's parameters.
#[test]
fn full_detail_reports_the_same_state_with_insert_params() {
let mut e = soundcraft_engine::demo::demo_engine();
e.execute("mix.volume", &json!({"track": "Kick", "db": -6.0})).unwrap();
let summary = inspect(&mut e);
let full = inspect_full(&mut e);
assert_reports_session_state(&full);
assert_eq!(full["undo"], json!("Set Volume"), "{full}");
assert_eq!(full["undo"], summary["undo"]);
assert_eq!(full["redo"], summary["redo"]);
assert_eq!(full["markers"], summary["markers"]);
let inserts = |v: &Value| v["tracks"].as_array().unwrap().iter().flat_map(|t| t["inserts"].as_array().unwrap().clone()).collect::<Vec<_>>();
let (s, f) = (inserts(&summary), inserts(&full));
assert!(!f.is_empty(), "the demo has inserts");
assert_eq!(s.len(), f.len());
assert!(s.iter().all(|i| i["params"].is_null()), "summary leaves params out");
assert!(f.iter().all(|i| !i["params"].is_null()), "full includes params");
}
/// With no edits yet, both history labels are null.
#[test]
fn a_fresh_session_has_no_undo_or_redo_step() {
let mut e = Engine::default();
let v = inspect(&mut e);
assert_eq!(v.get("undo"), Some(&Value::Null), "{v}");
assert_eq!(v.get("redo"), Some(&Value::Null), "{v}");
}
/// The undo label is the label of the command that ran last.
#[test]
fn undo_names_the_last_edit() {
let mut e = Engine::default();
let t = new_track(&mut e);
e.execute("mix.volume", &json!({"track": t, "db": -6.0})).unwrap();
let v = inspect(&mut e);
assert_eq!(v["undo"], json!("Set Volume"), "{v}");
assert_eq!(v["redo"], Value::Null, "{v}");
}
/// Undo moves the step's label to redo, and redo moves it back.
#[test]
fn undo_moves_the_step_label_to_redo() {
let mut e = Engine::default();
let t = new_track(&mut e);
e.execute("mix.volume", &json!({"track": t, "db": -6.0})).unwrap();
let before = inspect(&mut e);
assert!(e.undo());
let after = inspect(&mut e);
assert_eq!(after["redo"], before["undo"], "{after}");
assert_ne!(after["undo"], before["undo"], "{after}");
assert!(e.redo());
let again = inspect(&mut e);
assert_eq!(again["undo"], before["undo"], "{again}");
assert_eq!(again["redo"], Value::Null, "{again}");
}
/// Inspecting is read-only: two calls in a row agree and add no undo step.
#[test]
fn inspecting_does_not_change_the_session_or_history() {
let mut e = soundcraft_engine::demo::demo_engine();
let history = e.undo_history().len();
let first = inspect(&mut e);
let second = inspect(&mut e);
assert_eq!(first, second);
assert_eq!(e.undo_history().len(), history, "an inspection is not an undo step");
}
/// A volume change shows up in that track's `volume_db` and leaves its other fields alone.
#[test]
fn comparing_inspections_shows_a_mixer_change() {
let mut e = Engine::default();
let t = new_track(&mut e);
let before = inspect(&mut e);
e.execute("mix.volume", &json!({"track": t, "db": -6.0})).unwrap();
let after = inspect(&mut e);
assert_ne!(track(&before, &t)["volume_db"], track(&after, &t)["volume_db"]);
assert_eq!(track(&after, &t)["volume_db"].as_f64(), Some(-6.0));
assert_eq!(track(&before, &t)["pan"], track(&after, &t)["pan"], "untouched fields stay equal");
}
/// An added marker appears with its name and start, and becomes the last undo step.
#[test]
fn comparing_inspections_shows_a_new_marker() {
let mut e = Engine::default();
let before = inspect(&mut e);
e.execute("markers.add", &json!({"name": "Verse", "at": 48_000})).unwrap();
let after = inspect(&mut e);
let count = |v: &Value| v["markers"].as_array().map_or(0, Vec::len);
assert_eq!(count(&after), count(&before) + 1, "{after}");
let m = after["markers"].as_array().unwrap().iter().find(|m| m["name"] == "Verse").expect("the new marker");
assert_eq!(m["start"], json!(48_000), "{m}");
assert_ne!(after["undo"], before["undo"], "the marker is the last undo step");
}
/// A new track appears in the list, with no clips.
#[test]
fn comparing_inspections_shows_a_new_track() {
let mut e = Engine::default();
let before = inspect(&mut e);
let t = new_track(&mut e);
let after = inspect(&mut e);
assert_eq!(after["tracks"].as_array().unwrap().len(), before["tracks"].as_array().unwrap().len() + 1);
assert!(track(&after, &t)["clips"].as_array().unwrap().is_empty(), "a new track has no clips");
}
+224
View File
@@ -0,0 +1,224 @@
use soundcraft_engine::{Engine, edit, io};
use soundcraft_model::ClipContent;
use soundcraft_time::Range;
fn fixture() -> Vec<u8> {
let body = [0, 0xF0, 8, 0x43, 0x10, 0x4C, 0, 0, 0x7E, 0, 0xF7, 0x83, 0x60, 0xF7, 1, 0xF8, 0x83, 0x60, 0xF0, 2, 0x43, 0xF7, 0, 0xFF, 0x2F, 0];
smf_track(&body)
}
fn smf_track(body: &[u8]) -> Vec<u8> {
let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\x03\xC0MTrk".to_vec();
bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
bytes.extend_from_slice(body);
bytes
}
fn exported(engine: &Engine) -> Vec<soundcraft_midi::SysExEvent> {
soundcraft_midi::read_smf(&io::export_midi(engine, None).unwrap()).unwrap().tracks.into_iter().flat_map(|t| t.sequence.sysex).collect()
}
#[test]
fn sysex_only_track_is_imported_at_the_requested_offset_and_exported() {
let mut e = Engine::default();
let tracks = io::import_midi_bytes(&mut e, &fixture(), 48_000, false).unwrap();
assert_eq!(tracks.len(), 1, "a SysEx-only setup track must not disappear");
let clip = &e.session().track(tracks[0]).unwrap().clips()[0];
assert_eq!(clip.start, 48_000);
assert!(clip.end() > 72_000, "the final packet must lie inside the clip");
let packets = exported(&e);
assert_eq!(packets.iter().map(|e| e.tick).collect::<Vec<_>>(), [1920, 2400, 2880]);
assert_eq!(packets[0].data, [0x43, 0x10, 0x4C, 0, 0, 0x7E, 0, 0xF7]);
assert_eq!(packets[1].status, 0xF7);
assert_eq!(packets[1].data, [0xF8]);
}
#[test]
fn import_command_reports_retention_and_the_remaining_playback_limit() {
let path = std::env::temp_dir().join(format!("soundcraft-sysex-command-{}.mid", std::process::id()));
std::fs::write(&path, fixture()).unwrap();
let mut e = Engine::default();
let result = e.execute("file.import_midi", &serde_json::json!({"path":path})).unwrap();
assert_eq!(result["sysex_packets"], 3);
assert!(result["warnings"][0].as_str().unwrap().contains("playback is not supported"));
std::fs::remove_file(path).unwrap();
}
// Delta 0, F0, then a four-byte VLQ declaring 16 MiB + 1 payload bytes.
const LARGE_SYSEX_HEADER: [u8; 6] = [0, 0xF0, 0x88, 0x80, 0x80, 1];
#[test]
fn truncated_sysex_is_salvaged_without_hitting_the_size_limit() {
let bytes = smf_track(&LARGE_SYSEX_HEADER);
assert!(matches!(soundcraft_midi::read_smf(&bytes), Err(soundcraft_midi::MidiError::Truncated(_))));
let read = soundcraft_midi::read_smf_lenient(&bytes).unwrap();
assert!(!read.warnings.is_empty());
assert!(!read.over_limit);
let mut e = Engine::default();
assert!(io::import_midi_bytes(&mut e, &bytes, 0, true).unwrap().is_empty());
}
#[test]
fn oversized_sysex_is_refused_without_changing_the_session() {
let limit = soundcraft_midi::MAX_SYSEX_BYTES;
let mut body = LARGE_SYSEX_HEADER.to_vec();
body.resize(body.len() + limit, 0);
body.push(0xF7);
body.extend_from_slice(&[0, 0xFF, 0x2F, 0]);
let bytes = smf_track(&body);
let expected = soundcraft_midi::MidiError::SysExTooLarge(limit);
assert_eq!(soundcraft_midi::read_smf(&bytes).unwrap_err(), expected);
assert!(soundcraft_midi::read_smf_lenient(&bytes).unwrap().over_limit);
let mut e = Engine::default();
let before = serde_json::to_value(e.session()).unwrap();
let error = io::import_midi_bytes(&mut e, &bytes, 0, true).unwrap_err();
assert!(error.to_string().contains(&expected.to_string()), "{error}");
assert_eq!(serde_json::to_value(e.session()).unwrap(), before);
}
#[test]
fn sysex_survives_a_real_session_save_reopen_and_midi_export() {
let mut e = Engine::default();
io::import_midi_bytes(&mut e, &fixture(), 0, false).unwrap();
let before = exported(&e);
let path = std::env::temp_dir().join(format!("soundcraft-sysex-roundtrip-{}.scraft", std::process::id()));
io::save_session(&mut e, &path.to_string_lossy()).unwrap();
let mut reopened = Engine::default();
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
assert_eq!(exported(&reopened), before);
std::fs::remove_file(path).unwrap();
}
#[test]
fn splitting_and_consolidating_keep_packet_times_and_order() {
let mut e = Engine::default();
let track = io::import_midi_bytes(&mut e, &fixture(), 0, false).unwrap()[0];
let before = exported(&e);
let clip = e.session().track(track).unwrap().clips()[0].clone();
let new_id = e.session_mut().new_clip_id();
let (left, right) = edit::split_clip(&clip, 12_000, new_id, edit::TimeCtx::of(e.session())).unwrap();
match (&left.content, &right.content) {
(ClipContent::Midi { sequence: a }, ClipContent::Midi { sequence: b }) => {
assert_eq!(a.sysex.len(), 1);
assert_eq!(b.sysex.iter().map(|e| e.tick).collect::<Vec<_>>(), [0, 480]);
}
_ => panic!("expected MIDI"),
}
e.session_mut().track_mut(track).unwrap().playlist_mut().unwrap().clips = vec![left, right];
assert_eq!(exported(&e), before);
assert!(edit::consolidate_midi(e.session_mut(), track, Range::new(0, clip.end())));
assert_eq!(exported(&e), before);
}
#[test]
fn trimming_drops_packets_before_the_new_start_and_reanchors_the_rest() {
let mut e = Engine::default();
let track = io::import_midi_bytes(&mut e, &fixture(), 0, false).unwrap()[0];
assert_eq!(edit::trim_start_to(e.session_mut(), track, 12_000), 1);
let packets = exported(&e);
assert_eq!(packets.iter().map(|e| e.tick).collect::<Vec<_>>(), [480, 960]);
assert_eq!(packets[0].status, 0xF7);
}
#[test]
fn partial_copy_merge_exports_only_the_selected_midi_events() {
use serde_json::json;
use soundcraft_midi::{CtrlEvent, CtrlKind, Note, Sequence, SysExEvent};
use soundcraft_model::{ChannelFormat, Clip, TrackKind};
let mut e = Engine::default();
let s = e.session_mut();
let source = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
let host = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
let mut sequence = Sequence::default();
for (tick, key) in [(119, 60), (120, 61), (240, 62), (360, 63), (480, 64)] {
sequence.notes.push(Note { start: tick, length: 180, pitch: key, velocity: 100, release_velocity: 64, channel: 0 });
sequence.ctrls.push(CtrlEvent { tick, channel: 0, kind: CtrlKind::Cc(11), value: i32::from(key) });
sequence.sysex.push(SysExEvent { tick, status: 0xf0, data: vec![0x7d, key, 0xf7] });
}
let source_id = s.new_clip_id();
let host_id = s.new_clip_id();
edit::place_clip(s, source, Clip::midi(source_id, "source", 0, 24_000, sequence));
edit::place_clip(s, host, Clip::midi(host_id, "destination", 12_000, 96_000, Sequence::default()));
// At 120 BPM and 48 kHz, [3000, 9000) samples selects source ticks [120, 360).
e.execute("edit.copy", &json!({"tracks":[source.0], "start":3000, "end":9000})).unwrap();
let result = e.execute("edit.paste_merge_midi", &json!({"tracks":[host.0], "at":24_000})).unwrap();
assert_eq!(result["merged"], 1);
let smf = soundcraft_midi::read_smf(&io::export_midi(&e, Some(&[host])).unwrap()).unwrap();
let exported = &smf.tracks.iter().find(|t| !t.sequence.notes.is_empty()).unwrap().sequence;
let ClipContent::Midi { sequence: merged } = &e.session().find_clip(host_id).unwrap().1.content else { panic!("expected MIDI") };
// Host-relative ticks and the decoded SMF both retain inclusive start and exclusive end.
for (seq, base) in [(exported, 960), (merged, 480)] {
let notes: Vec<_> = seq.notes.iter().map(|n| (n.start, n.pitch, n.length)).collect();
let ctrls: Vec<_> = seq.ctrls.iter().map(|c| (c.tick, c.kind, c.value)).collect();
let packets: Vec<_> = seq.sysex.iter().map(|s| (s.tick, s.status, s.data.as_slice())).collect();
assert_eq!(
(notes, ctrls, packets),
(
vec![(base, 61, 180), (base + 120, 62, 120)],
vec![(base, CtrlKind::Cc(11), 61), (base + 120, CtrlKind::Cc(11), 62)],
vec![(base, 0xf0, &[0x7d, 61, 0xf7][..]), (base + 120, 0xf0, &[0x7d, 62, 0xf7][..])],
)
);
}
// At the faster destination tempo the same sample length spans twice as many ticks.
// A repeated paste on an empty track must still use the source window.
e.session_mut().tempo.set_tempo(0, 240.).unwrap();
let empty = e.session_mut().add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
let result = e.execute("edit.paste_merge_midi", &json!({"tracks":[empty.0], "at":24_000})).unwrap();
assert_eq!(result["placed"], 1);
let smf = soundcraft_midi::read_smf(&io::export_midi(&e, Some(&[empty])).unwrap()).unwrap();
let seq = &smf.tracks.iter().find(|t| !t.sequence.notes.is_empty()).unwrap().sequence;
assert_eq!(seq.notes.iter().map(|n| (n.start, n.length)).collect::<Vec<_>>(), [(1920, 180), (2040, 120)]);
assert_eq!(seq.ctrls.iter().map(|c| c.tick).collect::<Vec<_>>(), [1920, 2040]);
assert_eq!(seq.sysex.iter().map(|s| s.tick).collect::<Vec<_>>(), [1920, 2040]);
// At half tempo the original sample duration would end at the second retained event.
// Both placement and extension of a short host must cover the full source-tick window.
e.session_mut().tempo.set_tempo(0, 60.).unwrap();
let s = e.session_mut();
let short = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
let short_id = s.new_clip_id();
edit::place_clip(s, short, Clip::midi(short_id, "short host", 23_000, 2_000, Sequence::default()));
let blank = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
for (track, action) in [(blank, "placed"), (short, "merged")] {
let result = e.execute("edit.paste_merge_midi", &json!({"tracks":[track.0], "at":24_000})).unwrap();
assert_eq!(result[action], 1);
let smf = soundcraft_midi::read_smf(&io::export_midi(&e, Some(&[track])).unwrap()).unwrap();
let seq = &smf.tracks.iter().find(|t| !t.sequence.notes.is_empty()).unwrap().sequence;
assert_eq!(seq.notes.iter().map(|n| (n.start, n.length)).collect::<Vec<_>>(), [(480, 180), (600, 120)]);
assert_eq!(seq.ctrls.iter().map(|c| c.tick).collect::<Vec<_>>(), [480, 600]);
assert_eq!(seq.sysex.iter().map(|s| s.tick).collect::<Vec<_>>(), [480, 600]);
}
let s = e.session_mut();
let adjacent = s.add_track(TrackKind::Midi, ChannelFormat::Stereo, None);
let neighbor_id = s.new_clip_id();
edit::place_clip(s, adjacent, Clip::midi(neighbor_id, "neighbor", 32_000, 4_000, Sequence::default()));
e.execute("edit.paste_merge_midi", &json!({"tracks":[adjacent.0], "at":24_000})).unwrap();
let clips = e.session().track(adjacent).unwrap().clips();
assert_eq!(clips.len(), 2);
assert_eq!((clips[0].end(), clips[1].id, clips[1].start, clips[1].length), (32_000, neighbor_id, 32_000, 4_000));
}
#[test]
fn recovered_track_over_the_sysex_budget_reports_the_payload_limit() {
// A damaged first track sends import down the lenient path before it sees track two.
let mut bytes = smf_track(&[0, 0x90, 60]);
bytes[9] = 1; // SMF format 1
bytes[11] = 2;
let mut body = LARGE_SYSEX_HEADER.to_vec();
body.resize(body.len() + soundcraft_midi::MAX_SYSEX_BYTES + 1, 0);
bytes.extend_from_slice(b"MTrk");
bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
bytes.extend_from_slice(&body);
assert!(matches!(soundcraft_midi::read_smf(&bytes), Err(soundcraft_midi::MidiError::Truncated(_))));
assert!(soundcraft_midi::read_smf_lenient(&bytes).unwrap().over_limit);
let mut e = Engine::default();
let before = serde_json::to_value(e.session()).unwrap();
let error = io::import_midi_bytes(&mut e, &bytes, 0, true).unwrap_err().to_string();
assert!(error.contains("SysEx") && error.contains(&soundcraft_midi::MAX_SYSEX_BYTES.to_string()), "{error}");
assert_eq!(serde_json::to_value(e.session()).unwrap(), before);
}
+119
View File
@@ -0,0 +1,119 @@
//! Existing commands/history and saved session PCM for bounded send automation.
use craft_audio::AudioBuffer;
use serde_json::json;
use soundcraft_engine::{Engine, io};
use soundcraft_model::{AutoParam, ChannelFormat, Clip, FileFormat, Route, Session, TrackKind};
use soundcraft_time::Range;
use std::sync::Arc;
fn fixture() -> Engine {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Original"));
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 512]] };
let src = io::add_source(&mut s, "Original synthetic", buffer, None, FileFormat::Wav);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original", src, 0, 0, 512));
s.track_mut(t).unwrap().mixer.output = Route::None;
let mut e = Engine::new(s);
e.execute("mix.new_bus", &json!({"name":"Send","format":"stereo"})).unwrap();
e.execute("mix.send", &json!({"track":"Original","bus":"Send","slot":"A","level_db":0})).unwrap();
e.execute("track.new", &json!({"name":"Return","kind":"aux","format":"stereo"})).unwrap();
let bus = e.session().busses.iter().find(|b| b.name == "Send").unwrap().id;
let aux = e.session().tracks.iter().find(|t| t.kind == TrackKind::Aux).unwrap().id;
e.session_mut().track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
e.mark_clean();
e
}
fn render(e: &Engine) -> Vec<Vec<f32>> {
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 512), 37);
assert_eq!(out.len(), 2);
assert!(out.iter().all(|c| c.len() == 512));
out
}
fn point(e: &mut Engine, param: &str, at: i64, value: f32) {
e.execute("automation.set_point", &json!({"track":"Original","param":param,"at":at,"value":value})).unwrap();
}
#[test]
fn commands_undo_redo_reuse_renderer_and_preserve_render_state() {
let mut e = fixture();
let baseline = render(&e);
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_pan", 173, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let before = render(&e);
point(&mut e, "send_a_mute", 97, 1.0);
let after = render(&e);
assert_ne!(before, after);
assert_ne!(baseline, before);
let arc = e.session_arc();
let serialized = e.session().to_json().unwrap();
let revision = e.revision;
let history = e.undo_history();
let dirty = e.is_dirty();
let mut mix = soundcraft_mix::MixEngine::new(48_000.0, 512);
let mut out = vec![vec![0.0; 512]; 2];
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
mix.render(e.session(), 97, 13, &mut out);
assert!(Arc::ptr_eq(&arc, &e.session_arc()));
assert_eq!(serialized, e.session().to_json().unwrap());
assert_eq!(revision, e.revision);
assert_eq!(history, e.undo_history());
assert_eq!(dirty, e.is_dirty());
assert!(e.undo());
assert_eq!(render(&e), before);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, before);
assert!(e.redo());
assert_eq!(render(&e), after);
mix.render(e.session(), 0, 512, &mut out);
assert_eq!(out, after);
e.execute("mix.automation_mode", &json!({"track":"Original","mode":"off"})).unwrap();
assert_eq!(render(&e), baseline);
}
#[test]
fn lane_commands_survive_folder_and_bundle_save_reopen_with_exact_pcm() {
let mut e = fixture();
e.execute("mix.send_level", &json!({"track":"Original","slot":"A","pan":0.5,"mute":true})).unwrap();
point(&mut e, "send_a_pan", 37, -1.0);
point(&mut e, "send_a_pan", 401, 1.0);
point(&mut e, "send_a_mute", 0, 0.0);
e.execute("automation.write_range", &json!({"track":"Original","param":"send_a_mute","start":97,"end":173,"value":1.0})).unwrap();
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let dir = std::env::temp_dir().join(format!("soundcraft-send-automation-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("Original/Send.scraft").to_string_lossy().into_owned();
io::save_session(&mut e, &path).unwrap();
let mut reopened = Engine::default();
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
assert_eq!(render(&reopened), expected);
let tr = reopened.session().tracks.iter().find(|t| t.name == "Original").unwrap();
assert_eq!(tr.lane(&AutoParam::SendPan(0)).unwrap().points.len(), 2);
assert!(!reopened.is_dirty());
assert!(!reopened.can_undo());
let (bundle, _) = io::session_bundle(e.session()).unwrap();
let mut bundled = Engine::default();
io::open_session_bytes(&mut bundled, "Send.scraftz", &bundle).unwrap();
assert_eq!(render(&bundled), expected);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn absent_enabled_field_keeps_legacy_reader_behavior() {
let mut e = fixture();
point(&mut e, "send_a_pan", 0, -1.0);
point(&mut e, "send_a_mute", 0, 0.0);
let expected = render(&e);
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
let mut json = serde_json::to_value(e.session()).unwrap();
for track in json["tracks"].as_array_mut().unwrap() {
for lane in track["automation"].as_array_mut().unwrap() {
lane.as_object_mut().unwrap().remove("enabled");
}
}
let mut old: Session = serde_json::from_value(json).unwrap();
old.pool = e.session().pool.clone();
let tr = old.tracks.iter().find(|t| t.name == "Original").unwrap();
assert!(tr.automation.iter().all(|l| !l.enabled));
assert_eq!(soundcraft_mix::render_range(&old, Range::new(0, 512), 100), expected);
}
+2 -2
View File
@@ -14,8 +14,8 @@ pub mod ops;
mod rng;
pub use craft_midi::{
CtrlEvent, CtrlKind, LenientRead, MAX_EVENTS, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, SysExEvent, read_smf, read_smf_lenient,
write_smf,
CtrlEvent, CtrlKind, LenientRead, MAX_EVENTS, MAX_SYSEX_BYTES, MAX_TRACKS, MidiError, Note, PPQ, Sequence, Smf, SmfTrack, SysExEvent, read_smf,
read_smf_lenient, write_smf,
};
pub use names::{gm_drum_name, gm_program_name, note_name};
pub use rng::XorShift;
+68 -8
View File
@@ -70,6 +70,7 @@ mod midi;
mod offline;
mod pan;
mod routing;
mod send_automation;
mod strip;
mod threads;
@@ -292,6 +293,36 @@ impl MixEngine {
self.main_meter.reset_levels();
}
/// [`MixEngine::reset`], then prepares the hosted plugins again: their own `reset` may keep
/// audio (a VST3 processor's only flushes notes), and activating them again clears it.
/// Offline only: plugins allocate when they activate.
pub(crate) fn reset_and_reprepare(&mut self) {
self.reset();
let (sr, mb) = (self.sample_rate, self.max_block);
for s in self.strips.values_mut() {
for p in s.plugins.iter_mut().flatten().chain(s.instrument.as_mut()) {
if is_third_party(&p.id) {
p.plugin.prepare(sr, mb, p.ch);
}
}
}
}
/// Main-thread time for every plugin ([`Plugin::idle`]): offline renders give it between
/// blocks, the audio thread never does. True when an insert's or an instrument's latency
/// changed (both are delay-compensated).
pub(crate) fn idle_plugins(&mut self) -> bool {
let mut changed = false;
for s in self.strips.values_mut() {
for p in s.plugins.iter_mut().flatten().chain(s.instrument.as_mut()) {
let before = p.plugin.latency();
p.plugin.idle();
changed |= p.plugin.latency() != before;
}
}
changed
}
/// Bring plugin instances in line with the session (creates/destroys as needed). Allocates;
/// call outside the realtime thread when the document changes, or let `render` do it.
pub fn sync(&mut self, s: &Session) {
@@ -362,7 +393,7 @@ impl MixEngine {
}
for b in &s.busses {
let n = b.format.channels().clamp(1, MAX_CHANNELS);
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new() });
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new(), age: send_automation::SignalAge::Empty });
bus.fmt = b.format;
if bus.buf.len() != n {
bus.buf = vec![vec![0.0; mb]; n];
@@ -389,7 +420,7 @@ impl MixEngine {
self.begin_block(s, pos, frames);
let blk = Block { pos, frames, any_solo: any_solo(s) };
let order = std::mem::take(&mut self.order);
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
// Phase 1: independent strips (audio, instrument, MIDI), in parallel except on the audio thread.
let mut work = std::mem::take(&mut self.work);
work.clear();
for &i in &order {
@@ -454,6 +485,7 @@ impl MixEngine {
}
self.ensure_synced(s);
for b in self.busses.values_mut() {
b.age = send_automation::SignalAge::Empty;
for c in b.buf.iter_mut() {
c.iter_mut().take(frames).for_each(|x| *x = 0.0);
}
@@ -508,9 +540,11 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(lmax_t.saturating_sub(st.latency), ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
st.align_pre.set(lmax_t.saturating_sub(st.latency), ch);
st.align_pre.process(&mut st.pre, frames);
st.send_pre_age = st.send_pre_age.delayed(st.align_pre.len);
}
let waits = match &t.mixer.output {
Route::Main => true,
@@ -546,6 +580,7 @@ impl MixEngine {
let ch = st.buf.len();
st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch);
st.align.process(&mut st.buf, frames);
st.send_post_age = st.send_post_age.delayed(st.align.len);
st.out_extra.set(0, ch);
self.route_strip(t, &mut st, pos, frames);
self.strips.insert(t.id, st);
@@ -643,22 +678,41 @@ impl MixEngine {
let law = self.pan_law;
for (i, snd) in t.mixer.sends.iter().enumerate() {
let Some(snd) = snd else { continue };
if snd.mute || strip.muted {
if strip.muted {
continue;
}
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let age = if snd.pre_fader { strip.send_pre_age } else { strip.send_post_age };
let clock = age.clock(pos);
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
let ordinary = !src_fmt.is_ambisonic() && !dst.fmt.is_ambisonic();
let mute = ordinary.then(|| send_automation::Reader::for_send(t, AutoParam::SendMute, i, clock.at(0))).flatten();
if mute.is_none() && snd.mute {
continue;
}
let lvl = send_level(t, i, snd.level_db, pos);
let gain = db_to_gain(lvl);
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
let Route::Bus(b) = &snd.target else { continue };
let Some(dst) = self.busses.get_mut(b) else { continue };
if gain <= 0.0 {
continue;
}
dst.age.include(age);
let pan = (ordinary && src.len() == 1 && dst.fmt == ChannelFormat::Stereo)
.then(|| send_automation::Reader::for_send(t, AutoParam::SendPan, i, clock.at(0)))
.flatten();
if let Some(pan) = pan {
send_automation::apply_mono_stereo(src, frames, &mut dst.buf, gain, law, clock, pan, mute);
continue;
}
// Mono sends use the send's own pan; stereo sends go straight to L/R.
let stereo = if src.len() == 1 { [snd.pan, 0.0] } else { [-1.0, 1.0] };
let surround = snd.surround.as_ref().or(if snd.follow_main_pan { t.mixer.surround.as_ref() } else { None });
let m = build_matrix(src_fmt, src.len(), dst.fmt, dst.buf.len(), &PanSpec { stereo, surround }, law);
apply_matrix(src, frames, &mut dst.buf, &m, gain);
if let Some(mute) = mute {
send_automation::apply_gated(src, frames, &mut dst.buf, &m, gain, clock, mute);
} else {
apply_matrix(src, frames, &mut dst.buf, &m, gain);
}
}
let src: &[Vec<f32>] = match &t.mixer.output {
Route::Main | Route::Bus(_) if strip.out_extra.len > 0 => {
@@ -677,7 +731,10 @@ impl MixEngine {
let (dst, dst_fmt) = match &t.mixer.output {
Route::Main => (&mut self.main, self.main_fmt),
Route::Bus(b) => match self.busses.get_mut(b) {
Some(d) => (&mut d.buf, d.fmt),
Some(d) => {
d.age.include(strip.send_post_age.delayed(strip.out_extra.len));
(&mut d.buf, d.fmt)
}
None => return,
},
_ => return,
@@ -711,3 +768,6 @@ mod click;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod send_age_tests;
+20 -4
View File
@@ -18,13 +18,27 @@ fn midi_offset(s: &Session, t: &Track) -> i64 {
.map_or(0, |v| v as i64)
}
/// Send note on/offs and controllers for MIDI clips overlapping the block.
/// Send note on/offs and controllers for MIDI clips overlapping the block. With `chase` (the
/// first block after a start or seek), notes already sounding at `pos` are struck at the block
/// start too, so a chord that began before a seek is heard rather than skipped until the next one.
///
/// `live` holds the notes played live on the same instrument. Instruments end notes by pitch, so
/// a clip note-off is not sent while a live key holds that pitch: the key's own release ends it.
/// A note-off held back that way is told to `live`: when the key goes up earlier in the same
/// block, the note still lasts until the clip's note-off.
pub(crate) fn schedule_notes(s: &Session, t: &Track, pos: Samples, frames: usize, inst: &mut PluginSlot, held: &mut Vec<u8>, live: &mut LiveNotes) {
// The block, the instrument, its held and live notes, and whether this block chases: one call per
// block from `render_instrument`, so a struct would only repack these.
#[allow(clippy::too_many_arguments)]
pub(crate) fn schedule_notes(
s: &Session,
t: &Track,
pos: Samples,
frames: usize,
inst: &mut PluginSlot,
held: &mut Vec<u8>,
live: &mut LiveNotes,
chase: bool,
) {
let sr = s.sample_rate;
// MIDI Track Offsets: the track's notes sound `offset` samples later (earlier if negative), so
// the block looks that far back into the clips.
@@ -36,7 +50,9 @@ pub(crate) fn schedule_notes(s: &Session, t: &Track, pos: Samples, frames: usize
continue;
}
let ClipContent::Midi { sequence } = &clip.content else { continue };
if !clip.range().overlaps(&Range { start: pos, end }) {
// A note-off clamped to the clip end falls on the first sample after the
// clip, so a block starting exactly there still releases its notes.
if !clip.range().overlaps(&Range { start: pos, end }) && clip.end() != pos {
continue;
}
let base = s.tempo.samples_to_ticks(clip.start, sr);
@@ -71,7 +87,7 @@ pub(crate) fn schedule_notes(s: &Session, t: &Track, pos: Samples, frames: usize
if on >= clip.end() {
continue;
}
if on >= pos && on < end {
if (on >= pos && on < end) || (chase && on < pos && off > pos) {
inst.plugin.note_on(usize::try_from(on - pos).unwrap_or(0), n.pitch, n.velocity);
if !held.contains(&n.pitch) && held.len() < 128 {
held.push(n.pitch);
+30
View File
@@ -42,6 +42,9 @@ pub fn source_channels(s: &Session, bus: Option<BusId>) -> usize {
}
}
/// How many times [`RangeRender`] renders its first block again while a plugin's latency changes.
const FIRST_BLOCK_TRIES: usize = 4;
/// [`render_range`] or [`render_bus`] of any length, a block at a time.
pub struct RangeRender {
eng: MixEngine,
@@ -64,6 +67,12 @@ impl RangeRender {
RangeRender { eng, bus, tmp, start: range.start, done: 0, total: len, latency: 0 }
}
/// The engine, for tests that hand it fake hosted plugins.
#[cfg(test)]
pub(crate) fn engine(&mut self) -> &mut MixEngine {
&mut self.eng
}
fn render(&mut self, s: &Session, pos: Samples, n: usize) {
match self.bus {
Some(id) => {
@@ -83,6 +92,27 @@ impl RangeRender {
}
let n = (self.total - self.done).min(self.eng.max_block());
self.render(s, self.start + self.done as i64, n);
// Hosted plugins may only find their latency once they process, and apply it when they
// are restarted. If one did on the first block, start over from a clean state, so that
// block and the latency trimmed off it line up too. The head trim is the first block's:
// a later change (an automated lookahead) moves the alignment from that block on, as in
// playback, since the audio before it has already gone out.
if self.eng.idle_plugins() && self.done == 0 {
// A plugin may settle in more than one step: start over until none changes, a few
// times at most.
let mut settled = false;
for _ in 0..FIRST_BLOCK_TRIES {
self.eng.reset_and_reprepare();
self.render(s, self.start, n);
if !self.eng.idle_plugins() {
settled = true;
break;
}
}
if !settled {
log::warn!("a plugin's latency kept changing on the first block; the render may not line up with the timeline");
}
}
if self.done == 0 {
// The first block tells the mix's latency: render that much more and drop the head.
self.latency = match self.bus {
+1 -1
View File
@@ -1,7 +1,7 @@
use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains};
/// Per-block routing gains: `m[src][dst]`.
type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
pub(crate) type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
/// How a source is panned: the stereo pan pair (mono uses `[0]`) and the optional surround pan.
pub(crate) struct PanSpec<'a> {
+120
View File
@@ -0,0 +1,120 @@
use std::collections::HashMap;
use std::sync::Arc;
use craft_audio::AudioBuffer;
use soundcraft_dsp::Plugin;
use super::send_automation::SignalAge;
use super::strip::{Block, BusBuf, LiveInput, MAX_LATENCY, PluginSlot, Strip, process_strip};
use super::*;
#[test]
fn known_bus_ages_accumulate_and_mixed_ages_keep_the_legacy_clock() {
let mut bus = SignalAge::Empty;
assert_eq!(bus.input(), SignalAge::Known(0));
bus.include(SignalAge::Known(71));
bus.include(SignalAge::Known(71));
assert_eq!(bus, SignalAge::Known(71));
let aux_pre = bus.delayed(23);
let aux_post = aux_pre.delayed(48);
assert_eq!(aux_pre, SignalAge::Known(94));
assert_eq!(aux_post, SignalAge::Known(142));
assert_eq!(aux_pre.clock(300).at(0), 206);
assert_eq!(aux_post.clock(300).at(0), 158);
let nested = aux_post.delayed(71);
assert_eq!(nested, SignalAge::Known(213));
bus.include(SignalAge::Known(142));
assert_eq!(bus, SignalAge::Mixed);
assert_eq!(bus.delayed(71).clock(300).at(0), 300);
}
#[test]
fn age_overflow_preserves_audio_with_the_legacy_clock_fallback() {
let age = SignalAge::Known(u64::MAX).delayed(1);
assert_eq!(age, SignalAge::Mixed);
assert_eq!(age.clock(-7).at(3), -4);
let mut bus = SignalAge::Known(71);
bus.include(SignalAge::Empty);
assert_eq!(bus, SignalAge::Known(71));
}
#[test]
fn processed_insert_age_is_uncapped_while_pdc_stays_capped_and_overflow_falls_back() {
struct DeclaredDelay {
inner: Box<dyn Plugin>,
latency: usize,
}
impl Plugin for DeclaredDelay {
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
self.inner.info()
}
fn prepare(&mut self, rate: f32, block: usize, channels: usize) {
self.inner.prepare(rate, block, channels);
}
fn reset(&mut self) {
self.inner.reset();
}
fn set_param(&mut self, id: &str, value: f32) -> bool {
self.inner.set_param(id, value)
}
fn param(&self, id: &str) -> Option<f32> {
self.inner.param(id)
}
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
self.inner.process(io, frames);
}
fn latency(&self) -> usize {
self.latency
}
}
fn slot(latency: usize) -> PluginSlot {
let mut inner = soundcraft_dsp::create("gain").unwrap();
inner.prepare(48_000.0, 16, 1);
PluginSlot::test_instance("gain".into(), 1, Box::new(DeclaredDelay { inner, latency }))
}
let mut source = Session::default();
source.edit.delay_compensation = false;
let audio = source.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let source_id = soundcraft_model::SourceId(900);
source.pool.insert(source_id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 16]] })));
let clip = source.new_clip_id();
let track = source.track_mut(audio).unwrap();
track.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared-age reference", source_id, 0, 0, 16));
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
track.mixer.inserts[1] = Some(soundcraft_model::Insert::new("gain"));
let mut pre = soundcraft_model::SendSlot::new(Route::None);
pre.pre_fader = true;
track.mixer.sends[0] = Some(pre);
let mut strip = Strip::new();
strip.buf = vec![vec![0.0; 16]];
strip.scratch = vec![0.0; 16];
strip.plugins = vec![Some(slot(MAX_LATENCY + 5)), Some(slot(MAX_LATENCY + 9))];
let busses = HashMap::new();
let live = LiveInput { input: &[], midi: &[], ports: None, midi_lost: 0, monitor_only: false, recording: false };
let blk = Block { pos: 0, frames: 16, any_solo: false };
process_strip(&source, source.track(audio).unwrap(), &mut strip, &busses, &live, blk);
let declared_sum = 2 * MAX_LATENCY as u64 + 14;
assert_eq!(strip.latency, MAX_LATENCY, "the existing PDC cap remains unchanged");
assert_eq!(strip.send_pre_age, SignalAge::Known(declared_sum));
assert_eq!(strip.send_post_age, SignalAge::Known(declared_sum));
assert_eq!(strip.align.len, 0);
assert_eq!(strip.align_pre.len, 0);
assert_eq!(strip.pre, vec![vec![0.25; 16]]);
assert_eq!(strip.buf, strip.pre, "declared age metadata never changes the processed PCM");
let bus = source.add_bus("Overflowing known input", ChannelFormat::Mono);
let aux = source.add_track(TrackKind::Aux, ChannelFormat::Mono, None);
let track = source.track_mut(aux).unwrap();
track.mixer.input = Route::Bus(bus);
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
let busses = HashMap::from([(bus, BusBuf { fmt: ChannelFormat::Mono, buf: vec![vec![0.25; 16]], age: SignalAge::Known(u64::MAX) })]);
let mut aux_strip = Strip::new();
aux_strip.buf = vec![vec![0.0; 16]];
aux_strip.plugins = vec![Some(slot(1))];
process_strip(&source, source.track(aux).unwrap(), &mut aux_strip, &busses, &live, blk);
assert_eq!(aux_strip.latency, 1);
assert_eq!(aux_strip.send_pre_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age, SignalAge::Mixed);
assert_eq!(aux_strip.send_post_age.clock(300).at(0), 300);
assert_eq!(aux_strip.buf, vec![vec![0.25; 16]], "overflow preserves the output instead of silencing it");
}
+267
View File
@@ -0,0 +1,267 @@
//! Local send playback: sample-exact mono-to-stereo pan and stepped ordinary-bus mute.
//! No document mutation, allocation, locks or persistent cursor survive a callback/seek.
use super::MAX_CHANNELS;
use super::pan::Matrix;
use soundcraft_dsp::pan::{PanLaw, gains};
use soundcraft_model::{AutoParam, AutomationPoint, Track};
use soundcraft_time::Samples;
/// Source-sample age metadata only; it never changes routing or audio delay compensation.
/// A mixed-age sum has no single source clock, so new send readers retain their legacy clock.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub(crate) enum SignalAge {
#[default]
Empty,
Known(u64),
Mixed,
}
impl SignalAge {
pub(crate) fn input(self) -> Self {
match self {
Self::Empty => Self::Known(0),
other => other,
}
}
pub(crate) fn delayed(self, frames: usize) -> Self {
match self {
Self::Known(age) => u64::try_from(frames).ok().and_then(|frames| age.checked_add(frames)).map_or(Self::Mixed, Self::Known),
other => other,
}
}
pub(crate) fn include(&mut self, contribution: Self) {
*self = match (*self, contribution) {
(Self::Empty, age) | (age, Self::Empty) => age,
(Self::Known(a), Self::Known(b)) if a == b => Self::Known(a),
_ => Self::Mixed,
};
}
pub(crate) fn clock(self, position: Samples) -> Clock {
let age = match self {
Self::Known(age) => age,
Self::Empty | Self::Mixed => 0,
};
Clock::new(position, age)
}
}
/// A forward cursor rebuilt at each callback's absolute position. Like the existing mixer
/// readers, this deliberately ignores lane.enabled; global suspension/migration is separate.
/// Nonfinite or decreasing-time lanes fall back to the static control for the whole callback.
/// Finite values clamp to the control range; duplicate times deterministically use the last knot.
pub(super) struct Reader<'a> {
points: &'a [AutomationPoint],
next: usize,
mute: bool,
}
impl<'a> Reader<'a> {
pub(super) fn for_send(t: &'a Track, param: fn(u8) -> AutoParam, slot: usize, pos: Samples) -> Option<Self> {
if !t.mixer.automation_mode.reads() {
return None;
}
let param = param(u8::try_from(slot).ok()?);
let lane = t.lane(&param)?;
let points = &lane.points;
if points.is_empty() || points.iter().any(|p| !p.value.is_finite()) || points.windows(2).any(|p| p[0].at > p[1].at) {
return None;
}
Some(Self { points, next: points.partition_point(|p| p.at <= pos), mute: matches!(param, AutoParam::SendMute(_)) })
}
pub(super) fn value(&mut self, pos: Samples) -> f32 {
while self.points.get(self.next).is_some_and(|p| p.at <= pos) {
self.next = self.next.saturating_add(1);
}
let Some(a) = self.points.get(self.next.saturating_sub(1)) else { return 0.0 };
let lo = if self.mute { 0.0 } else { -1.0 };
let av = a.value.clamp(lo, 1.0);
if self.next == 0 || self.mute {
return av;
}
let Some(b) = self.points.get(self.next) else { return av };
// Valid timestamps may span i64::MIN..MAX. Widen before subtraction, and interpolate
// bounded values in f64 so neither timestamp nor value arithmetic can overflow.
let width = i128::from(b.at) - i128::from(a.at);
if width <= 0 {
return av;
}
let fraction = ((i128::from(pos) - i128::from(a.at)) as f64 / width as f64).clamp(0.0, 1.0);
(f64::from(av) + (f64::from(b.value.clamp(lo, 1.0)) - f64::from(av)) * fraction) as f32
}
}
/// Timeline position represented by a delayed source tap. Widen the entire expression before
/// clamping, so advancing a frame near MIN/MAX does not lose an earlier delay subtraction.
#[derive(Clone, Copy)]
pub(super) struct Clock {
position: Samples,
age: u64,
}
impl Clock {
pub(super) fn new(position: Samples, age: u64) -> Self {
Self { position, age }
}
pub(super) fn at(self, frame: usize) -> Samples {
let frame = i128::try_from(frame).unwrap_or(i128::MAX);
let at = i128::from(self.position).saturating_add(frame).saturating_sub(i128::from(self.age));
at.clamp(i128::from(Samples::MIN), i128::from(Samples::MAX)) as Samples
}
}
impl From<Samples> for Clock {
fn from(position: Samples) -> Self {
Self::new(position, 0)
}
}
#[cfg(test)]
fn frame_position(pos: Samples, frame: usize) -> Samples {
Clock::from(pos).at(frame)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn apply_mono_stereo(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
gain: f32,
law: PanLaw,
pos: impl Into<Clock>,
mut pan: Reader<'_>,
mut mute: Option<Reader<'_>>,
) {
let clock = pos.into();
let Some(src) = src.first() else { return };
for (i, sample) in src.iter().enumerate().take(frames) {
let at = clock.at(i);
if mute.as_mut().is_some_and(|m| m.value(at) >= 0.5) {
continue;
}
let (left, right) = gains(pan.value(at), law);
for (channel, factor) in [(0, left), (1, right)] {
if let Some(out) = dst.get_mut(channel).and_then(|c| c.get_mut(i)) {
*out += sample * gain * factor;
}
}
}
}
/// Keep the existing static routing matrix (including mono folds and surround positions),
/// applying only the exact mute gate. Sparse taps are prepared on the stack once per block.
pub(super) fn apply_gated(
src: &[Vec<f32>],
frames: usize,
dst: &mut [Vec<f32>],
matrix: &Matrix,
gain: f32,
pos: impl Into<Clock>,
mut mute: Reader<'_>,
) {
let clock = pos.into();
let mut taps = [[(0usize, 0.0f32); MAX_CHANNELS]; MAX_CHANNELS];
let mut counts = [0usize; MAX_CHANNELS];
for (d, (taps, count)) in taps.iter_mut().zip(counts.iter_mut()).enumerate().take(dst.len()) {
for (s, row) in matrix.iter().enumerate().take(src.len().min(MAX_CHANNELS)) {
let g = row.get(d).copied().unwrap_or(0.0);
if g != 0.0
&& let Some(tap) = taps.get_mut(*count)
{
*tap = (s, g);
*count += 1;
}
}
}
for i in 0..frames {
if mute.value(clock.at(i)) >= 0.5 {
continue;
}
for (d, channel) in dst.iter_mut().enumerate().take(MAX_CHANNELS) {
let Some(out) = channel.get_mut(i) else { continue };
let mut acc = 0.0;
for &(s, g) in taps.get(d).and_then(|t| counts.get(d).and_then(|n| t.get(..*n))).unwrap_or(&[]) {
acc += src.get(s).and_then(|c| c.get(i)).copied().unwrap_or(0.0) * gain * g;
}
*out += acc;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use soundcraft_model::{AutomationLane, ChannelFormat, Session, TrackKind};
fn track(points: &[(i64, f32)], mute: bool) -> Track {
let mut s = Session::default();
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
let t = s.track_mut(id).unwrap();
let mut lane = AutomationLane::new(if mute { AutoParam::SendMute(0) } else { AutoParam::SendPan(0) });
lane.points = points.iter().map(|&(at, value)| AutomationPoint { at, value }).collect();
t.automation.push(lane);
t.clone()
}
#[test]
fn wide_interpolation_does_not_overflow() {
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MIN).unwrap();
assert_eq!(r.value(i64::MIN), -1.0);
assert!(r.value(0).abs() < 1e-7);
assert_eq!(r.value(i64::MAX), 1.0);
assert_eq!(frame_position(i64::MAX - 1, 3), i64::MAX);
}
#[test]
fn endpoints_duplicates_and_finite_extremes_are_deterministic() {
let t = track(&[(3, -f32::MAX), (3, 0.25), (7, f32::MAX)], false);
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, 0).unwrap();
assert_eq!(r.value(0), -1.0);
assert_eq!(r.value(3), 0.25);
assert_eq!(r.value(5), 0.625);
assert_eq!(r.value(9), 1.0);
let t = track(&[(i64::MIN, -f32::MAX), (i64::MAX, f32::MAX)], true);
let mut r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MIN).unwrap();
assert_eq!(r.value(0), 0.0);
assert_eq!(r.value(i64::MAX), 1.0);
}
#[test]
fn short_buffers_and_saturating_positions_do_not_panic() {
let t = track(&[(i64::MIN, 0.0), (i64::MAX, 1.0)], true);
let r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MAX - 1).unwrap();
let mut dst = vec![vec![0.0; 1]];
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
apply_gated(&[vec![0.25; 2]], 4, &mut dst, &matrix, 1.0, i64::MAX - 1, r);
assert_eq!(dst, vec![vec![0.25]]);
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
let r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MAX - 1).unwrap();
apply_mono_stereo(&[vec![0.25; 2]], 4, &mut [], 1.0, PanLaw::Minus3, i64::MAX - 1, r, None);
}
#[test]
fn source_clock_clamps_after_the_composite_delay_expression() {
assert_eq!(Clock::new(i64::MIN + 5, 10).at(8), i64::MIN + 3);
assert_eq!(Clock::new(i64::MAX, 10).at(3), i64::MAX - 7);
assert_eq!(Clock::new(i64::MAX, 10).at(20), i64::MAX);
assert_eq!(Clock::new(-5, 10).at(3), -12);
assert_eq!(Clock::new(i64::MAX, u64::MAX).at(0), i64::MIN);
assert_eq!(Clock::new(i64::MIN, u64::MAX).at(0), i64::MIN);
}
#[test]
fn delayed_reader_seed_and_gate_advancement_use_the_same_clock() {
let t = track(&[(0, 0.0), (30, 1.0), (40, 0.0)], true);
let clock = Clock::new(45, 25);
let reader = Reader::for_send(&t, AutoParam::SendMute, 0, clock.at(0)).unwrap();
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
matrix[0][0] = 1.0;
let mut destination = vec![vec![0.0; 25]];
apply_gated(&[vec![0.25; 25]], 25, &mut destination, &matrix, 1.0, clock, reader);
assert_eq!(destination[0], (0..25).map(|frame| if (10..20).contains(&frame) { 0.0 } else { 0.25 }).collect::<Vec<_>>());
}
}
+43 -9
View File
@@ -5,6 +5,7 @@ use super::live_midi::{LiveMidi, LiveNotes, MidiPorts, midi_thru};
use super::midi::{chase_controllers, schedule_notes};
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
use super::routing::solo_muted;
use super::send_automation::SignalAge;
use super::{
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
db_to_gain,
@@ -16,6 +17,8 @@ use std::sync::Arc;
pub(crate) struct BusBuf {
pub(crate) fmt: ChannelFormat,
pub(crate) buf: Vec<Vec<f32>>,
/// Age shared by the routed contributions in this block, or Mixed when they differ.
pub(crate) age: SignalAge,
}
pub(crate) struct PluginSlot {
@@ -35,6 +38,13 @@ pub(crate) struct PluginSlot {
pub(crate) retried: bool,
}
#[cfg(test)]
impl PluginSlot {
pub(crate) fn test_instance(id: String, ch: usize, plugin: Box<dyn Plugin>) -> Self {
Self { id, ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }
}
}
pub(crate) struct Strip {
pub(crate) buf: Vec<Vec<f32>>,
/// Pre-fader copy for pre-fader sends.
@@ -50,6 +60,9 @@ pub(crate) struct Strip {
pub(crate) live: LiveNotes,
/// The instrument's next block starts somewhere new: send it the controllers in effect there.
pub(crate) chase: bool,
/// Live controllers moved the instrument and were let go: the next block sends it the clips'
/// controllers again, without striking the notes already sounding (that is `chase`).
pub(crate) restore_controllers: bool,
/// The last block played the clips: stopped monitoring has their sustain pedal to let go of.
pub(crate) clips_played: bool,
pub(crate) muted: bool,
@@ -59,6 +72,9 @@ pub(crate) struct Strip {
clipbuf: Vec<Vec<f32>>,
/// Total latency of the active inserts (samples).
pub(crate) latency: usize,
/// Sample ages of the selected send taps after their actual applied alignment.
pub(crate) send_pre_age: SignalAge,
pub(crate) send_post_age: SignalAge,
/// Delay compensation: align this strip with the slowest one (post- and pre-fader paths),
/// plus extra delay for direct-to-main outputs so they line up with aux returns.
pub(crate) align: DelayLine,
@@ -151,12 +167,15 @@ impl Strip {
held: Vec::new(),
live: LiveNotes::default(),
chase: true,
restore_controllers: false,
clips_played: false,
muted: false,
gr: 0.0,
clip_fx: HashMap::new(),
clipbuf: Vec::new(),
latency: 0,
send_pre_age: SignalAge::Known(0),
send_post_age: SignalAge::Known(0),
align: DelayLine::default(),
align_pre: DelayLine::default(),
out_extra: DelayLine::default(),
@@ -289,10 +308,11 @@ fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) {
}
/// An aux or folder reads the bus its input is routed from.
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) {
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) -> SignalAge {
if let Route::Bus(b) = &t.mixer.input
&& let Some(src) = busses.get(b)
{
let input_age = src.age.input();
let (ns, nd) = (src.buf.len(), strip.buf.len());
let dst_fmt = strip_format(t, nd);
let m = if src.fmt == dst_fmt && ns == nd {
@@ -308,7 +328,9 @@ fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, f
build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3)
};
apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0);
return input_age;
}
SignalAge::Known(0)
}
/// Render the track's instrument into the strip.
@@ -325,7 +347,10 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
}
inst.plugin.set_transport(transport);
// Whether the clips' controller values were sent to the instrument for this block.
let mut chased = std::mem::take(&mut strip.chase);
// A start or seek: notes already sounding are struck again too (not when only a live
// source went away, below; those notes are still held).
let chase = std::mem::take(&mut strip.chase);
let mut chased = chase | std::mem::take(&mut strip.restore_controllers);
if chased {
let from_clips = chase_controllers(s, t, pos, inst);
strip.live.restore_defaults(from_clips, inst.plugin.as_mut());
@@ -346,7 +371,7 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
chased = true;
}
if !live.monitor_only {
schedule_notes(s, t, pos, frames, inst, &mut strip.held, &mut strip.live);
schedule_notes(s, t, pos, frames, inst, &mut strip.held, &mut strip.live, chase);
strip.clips_played = true;
} else {
// Stopped: the clips are silent, only live MIDI input plays. Playback that ran to its
@@ -371,7 +396,7 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
strip.live.play(t, inst.plugin.as_mut(), live.midi, live.ports, frames);
} else if strip.live.touched() && strip.live.release(inst.plugin.as_mut()) {
// Live controllers moved the instrument: the next block sets them from the clips.
strip.chase = true;
strip.restore_controllers = true;
}
if strip.buf.len() >= 2 {
inst.plugin.process(&mut strip.buf, frames);
@@ -393,10 +418,12 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
}
/// Run the active inserts in order; records their latency and the first gain reduction.
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) {
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport, input_age: SignalAge) {
let Block { pos, frames, .. } = blk;
let mut gr = 0.0f32;
let mut latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
let inst_latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
let mut latency = inst_latency;
let mut send_age = input_age.delayed(inst_latency);
for (i, ins) in t.mixer.inserts.iter().enumerate() {
let (Some(ins), Some(Some(slot))) = (ins, strip.plugins.get_mut(i)) else { continue };
if !ins.active || ins.bypass || slot.failed {
@@ -409,13 +436,17 @@ fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport)
strip.failures.record(i);
continue;
}
latency = latency.saturating_add(slot.plugin.latency());
let declared_latency = slot.plugin.latency();
latency = latency.saturating_add(declared_latency);
send_age = send_age.delayed(declared_latency);
if gr == 0.0 {
gr = slot.plugin.gain_reduction_db();
}
}
strip.gr = gr;
strip.latency = latency.min(MAX_LATENCY);
strip.send_pre_age = send_age;
strip.send_post_age = send_age;
}
/// Fader gain (volume, trim and VCA automation), read at every sample of the block.
@@ -466,6 +497,7 @@ fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) {
pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, live: &LiveInput<'_>, blk: Block) {
let Block { pos, frames, any_solo } = blk;
zero_buf(&mut strip.buf, frames);
let mut input_age = SignalAge::Known(0);
let transport = transport_at(s, pos, !live.monitor_only, live.recording);
match t.kind {
TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => {
@@ -476,7 +508,9 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
// doing so, to release its notes).
TrackKind::Instrument | TrackKind::Midi if live.monitor_only && !midi_thru(t) && !strip.live.touched() => {}
TrackKind::Audio => render_audio_clips(s, t, strip, blk),
TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames),
TrackKind::Aux | TrackKind::Folder => {
input_age = read_aux_bus(t, strip, busses, frames);
}
TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, live, blk, &transport),
_ => {}
}
@@ -486,7 +520,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
c.iter_mut().take(frames).for_each(|x| *x *= trim);
}
}
run_inserts(t, strip, blk, &transport);
run_inserts(t, strip, blk, &transport, input_age);
let soloed_out = solo_muted(s, t, any_solo);
strip.muted = t.mixer.mute || soloed_out;
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
+306
View File
@@ -47,6 +47,20 @@ fn delay_line_change_keeps_buffers_and_history() {
assert_eq!(ptrs, after, "delay line reallocated going back to its size");
}
#[test]
fn note_off_at_the_clip_end_on_a_block_boundary_releases_the_note() {
// The note ends with its 24,000-sample clip; 480-frame blocks put that
// note-off at the first sample of the block after the clip.
let mut s = synth_session(-6.0);
if let Some(ins) = s.tracks[0].instrument.as_mut() {
ins.params.insert("amp_release".into(), 20.0);
}
let out = render_range(&s, Range::new(0, 48_000), 480);
let peak = |r: std::ops::Range<usize>| out[0].get(r).unwrap_or_default().iter().fold(0.0_f32, |p, x| p.max(x.abs()));
assert!(peak(12_000..24_000) > 0.01, "the synth should sound");
assert!(peak(30_000..48_000) < 1e-4, "the note must be released at the clip end");
}
#[test]
fn stored_instrument_params_reach_the_plugin() {
// #152: a saved instrument level of -12 dB must render quieter than -6 dB.
@@ -529,6 +543,36 @@ impl Plugin for Ears {
}
}
#[test]
fn notes_held_across_a_seek_are_struck_again() {
let mut s = Session::default();
let t = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, None);
s.track_mut(t).unwrap().instrument = Some(Insert::new("clap:test.keys"));
let mut seq = soundcraft_midi::Sequence::default();
// A two-note chord over the first two beats at 120 BPM (0..48_000), then a note from beat 3.
for pitch in [60, 64] {
seq.notes.push(soundcraft_midi::Note { pitch, velocity: 90, release_velocity: 64, channel: 0, start: 0, length: 1920 });
}
seq.notes.push(soundcraft_midi::Note { pitch: 67, velocity: 90, release_velocity: 64, channel: 0, start: 1920, length: 960 });
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::midi(cid, "m", 0, 96_000, seq));
let heard = Arc::new(std::sync::Mutex::new(Vec::new()));
let keys = Keys { inner: soundcraft_dsp::create("gain").unwrap(), heard: Arc::clone(&heard) };
let mut eng = MixEngine::new(48_000.0, 512);
eng.set_external_instances(true);
eng.adopt(vec![PreparedInstance { track: t, slot: INSTRUMENT_SLOT, id: "clap:test.keys".into(), ch: 2, plugin: Box::new(keys) }]);
render_block(&mut eng, &s, 0);
assert_eq!(std::mem::take(&mut *heard.lock().unwrap()), vec![(60, 90), (64, 90)]);
render_block(&mut eng, &s, 512);
assert!(heard.lock().unwrap().is_empty(), "continuing playback does not strike held notes again");
// Seek into the middle of the chord: both notes sound again from the block start.
render_block(&mut eng, &s, 24_000);
assert_eq!(std::mem::take(&mut *heard.lock().unwrap()), vec![(60, 90), (64, 90)]);
// Seek past the chord into the later note: only that one is chased.
render_block(&mut eng, &s, 60_000);
assert_eq!(std::mem::take(&mut *heard.lock().unwrap()), vec![(67, 90)]);
}
#[test]
fn controllers_play_at_their_offsets_and_are_chased_after_a_seek() {
let mut s = Session::default();
@@ -1448,6 +1492,268 @@ fn volume_automation_follows_its_breakpoints_in_any_block_size() {
}
}
/// Delays its input by `n` samples from its first block, like a lookahead limiter, but reports
/// that latency only after its first block and an `idle`, the way a CLAP plugin applies a new
/// latency through a restart (LSP Limiter: 0 at `activate`, a restart request once it processed).
struct LateLatency {
inner: Box<dyn Plugin>,
n: usize,
lines: Vec<std::collections::VecDeque<f32>>,
processed: bool,
reported: usize,
/// What it reports at each `idle` once it has processed (the last one stays).
steps: std::collections::VecDeque<usize>,
/// How many times it was prepared.
prepares: Arc<std::sync::atomic::AtomicUsize>,
}
impl LateLatency {
/// Prepared, as the host hands it over.
fn new(n: usize) -> Self {
Self::stepping(n, &[n])
}
/// Delays by `n` from the start, but reports `steps` one `idle` at a time.
fn stepping(n: usize, steps: &[usize]) -> Self {
let mut p = LateLatency {
inner: soundcraft_dsp::create("gain").unwrap(),
n,
lines: Vec::new(),
processed: false,
reported: 0,
steps: steps.iter().copied().collect(),
prepares: Arc::default(),
};
p.prepare(48_000.0, 512, 2);
p
}
}
impl Plugin for LateLatency {
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
self.inner.info()
}
fn prepare(&mut self, sr: f32, mb: usize, ch: usize) {
self.inner.prepare(sr, mb, ch);
self.lines = vec![std::iter::repeat_n(0.0, self.n).collect(); ch];
self.prepares.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn reset(&mut self) {
self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|x| *x = 0.0));
}
fn set_param(&mut self, id: &str, v: f32) -> bool {
self.inner.set_param(id, v)
}
fn param(&self, id: &str) -> Option<f32> {
self.inner.param(id)
}
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
for (c, line) in io.iter_mut().zip(&mut self.lines) {
for x in c.iter_mut().take(frames) {
line.push_back(*x);
*x = line.pop_front().unwrap();
}
}
self.processed = true;
}
fn latency(&self) -> usize {
self.reported
}
fn idle(&mut self) {
if self.processed
&& let Some(r) = self.steps.pop_front()
{
self.reported = r;
}
}
}
/// A hosted insert that reports its latency only after the first block (on a track, or on the
/// master, whose latency is read before it processes) still lines up from the first sample.
#[test]
fn offline_renders_follow_a_latency_reported_after_the_first_block() {
for kind in [TrackKind::Audio, TrackKind::Master] {
let mut s = Session::default();
s.edit.delay_compensation = true;
let n = 4096;
let mut clicks = vec![0.0f32; n];
for at in [100, 3000] {
clicks[at] = 0.25;
}
s.pool.insert(SourceId(902), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] })));
let mut tracks = Vec::new();
for _ in 0..2 {
let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(902), 0, 0, n as i64));
tracks.push(t);
}
let target = if kind == TrackKind::Audio { tracks[0] } else { s.add_track(TrackKind::Master, ChannelFormat::Stereo, None) };
s.track_mut(target).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late"));
let render = |s: &Session| {
let mut r = RangeRender::new(s, None, Range::new(0, n as i64), 512);
r.engine().set_external_instances(true);
r.engine().adopt(vec![PreparedInstance {
track: target,
slot: 0,
id: "clap:test.late".into(),
ch: 2,
plugin: Box::new(LateLatency::new(240)),
}]);
let mut out = vec![Vec::new(); 2];
while let Some((chunk, k)) = r.next_block(s) {
for (o, c) in out.iter_mut().zip(chunk) {
o.extend_from_slice(&c[..k]);
}
}
out
};
// Both tracks play the clicks: they land where they are on the timeline.
let out = render(&s);
assert_eq!(out[0].len(), n);
assert_eq!(impulse_at(&out[0]), vec![100, 3000], "{kind:?}: the plugin's 240 samples are compensated from the start");
// The second track flipped: with the two lined up, nothing is left.
s.track_mut(tracks[1]).unwrap().mixer.phase_invert = true;
let out = render(&s);
assert!(out.iter().flatten().all(|x| x.abs() < 1e-6), "{kind:?}: the tracks line up");
}
}
/// An echo 1000 samples later whose memory survives `reset` and is cleared only by `prepare`,
/// like a VST3 processor: its reset only flushes notes, and activating it again clears its audio.
struct KeepsTail {
inner: Box<dyn Plugin>,
ring: Vec<Vec<f32>>,
pos: usize,
}
impl KeepsTail {
/// Prepared, as the host hands it over.
fn new() -> Self {
let mut p = KeepsTail { inner: soundcraft_dsp::create("gain").unwrap(), ring: Vec::new(), pos: 0 };
p.prepare(48_000.0, 512, 2);
p
}
}
impl Plugin for KeepsTail {
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
self.inner.info()
}
fn prepare(&mut self, sr: f32, mb: usize, ch: usize) {
self.inner.prepare(sr, mb, ch);
self.ring = vec![vec![0.0; 1000]; ch];
self.pos = 0;
}
fn reset(&mut self) {}
fn set_param(&mut self, id: &str, v: f32) -> bool {
self.inner.set_param(id, v)
}
fn param(&self, id: &str) -> Option<f32> {
self.inner.param(id)
}
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
for i in 0..frames {
for (c, ring) in io.iter_mut().zip(&mut self.ring) {
let old = std::mem::replace(&mut ring[self.pos], c[i]);
c[i] += 0.5 * old;
}
self.pos = (self.pos + 1) % 1000;
}
}
}
/// Starting the first block over must not keep what the discarded pass left in an insert whose
/// own reset keeps its audio (a VST3 tail), on any track.
#[test]
fn a_first_block_rendered_again_carries_nothing_from_the_discarded_pass() {
let mut s = Session::default();
s.edit.delay_compensation = true;
let n = 4096;
let mut clicks = vec![0.0f32; n];
for at in [100, 3000] {
clicks[at] = 0.25;
}
s.pool.insert(SourceId(903), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] })));
let mut tracks = Vec::new();
for slot in ["clap:test.late", "clap:test.tail"] {
let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(903), 0, 0, n as i64));
s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new(slot));
tracks.push(t);
}
let mut r = RangeRender::new(&s, None, Range::new(0, n as i64), 512);
r.engine().set_external_instances(true);
r.engine().adopt(vec![
PreparedInstance { track: tracks[0], slot: 0, id: "clap:test.late".into(), ch: 2, plugin: Box::new(LateLatency::new(240)) },
PreparedInstance { track: tracks[1], slot: 0, id: "clap:test.tail".into(), ch: 2, plugin: Box::new(KeepsTail::new()) },
]);
let mut out = vec![Vec::new(); 2];
while let Some((chunk, k)) = r.next_block(&s) {
for (o, c) in out.iter_mut().zip(chunk) {
o.extend_from_slice(&c[..k]);
}
}
assert_eq!(impulse_at(&out[0]), vec![100, 1100, 3000, 4000], "the clicks and their echoes, and no echo of the first pass");
}
/// Clicks at 100 and 3000 on a stereo track with `plugin` as its insert, rendered in 512-sample
/// blocks: where the clicks land.
fn clicks_through(plugin: LateLatency) -> Vec<usize> {
let mut s = Session::default();
s.edit.delay_compensation = true;
let n = 4096;
let mut clicks = vec![0.0f32; n];
for at in [100, 3000] {
clicks[at] = 0.25;
}
s.pool.insert(SourceId(904), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] })));
let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None);
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(904), 0, 0, n as i64));
s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late"));
let mut r = RangeRender::new(&s, None, Range::new(0, n as i64), 512);
r.engine().set_external_instances(true);
r.engine().adopt(vec![PreparedInstance { track: t, slot: 0, id: "clap:test.late".into(), ch: 2, plugin: Box::new(plugin) }]);
let mut out = Vec::new();
while let Some((chunk, k)) = r.next_block(&s) {
out.extend_from_slice(&chunk[0][..k]);
}
impulse_at(&out)
}
/// A plugin whose latency settles in two steps (it changes again on the first block rendered a
/// second time) still lines up: the render starts over until no latency changes.
#[test]
fn a_latency_that_settles_in_two_steps_still_lines_up() {
assert_eq!(clicks_through(LateLatency::stepping(240, &[120, 240])), vec![100, 3000]);
assert_eq!(clicks_through(LateLatency::new(240)), vec![100, 3000], "one step");
}
/// An instrument's latency is compensated like an insert's (#1476), so either one reported late
/// renders the first block again (every hosted instance is prepared a second time).
#[test]
fn an_insert_or_instrument_latency_reported_late_renders_the_first_block_again() {
for insert_too in [false, true] {
let (mut s, a) = session_with_dc(0.5, 4096);
let inst = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, None);
s.track_mut(inst).unwrap().instrument = Some(Insert::new("clap:test.inst"));
let synth = LateLatency::new(64);
let prepares = Arc::clone(&synth.prepares);
let mut adopt = vec![PreparedInstance { track: inst, slot: INSTRUMENT_SLOT, id: "clap:test.inst".into(), ch: 2, plugin: Box::new(synth) }];
if insert_too {
s.track_mut(a).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late"));
adopt.push(PreparedInstance { track: a, slot: 0, id: "clap:test.late".into(), ch: 1, plugin: Box::new(LateLatency::new(240)) });
}
let mut r = RangeRender::new(&s, None, Range::new(0, 4096), 512);
r.engine().set_external_instances(true);
r.engine().adopt(adopt);
while r.next_block(&s).is_some() {}
assert_eq!(prepares.load(std::sync::atomic::Ordering::Relaxed), 2, "with an insert reporting late too: {insert_too}");
}
}
/// A master fader's breakpoint acts on its own sample too.
#[test]
fn master_volume_automation_follows_its_breakpoints_in_any_block_size() {
+8 -5
View File
@@ -1,16 +1,15 @@
use super::AUDIO_THREAD;
/// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks
/// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads
/// count as the audio thread while they render for it. Code that might run there asks
/// do, every call: one thread-local store). [`MixEngine::render`] renders every strip on that
/// thread itself instead of handing strips to worker threads. Code that might run there asks
/// [`on_audio_thread`] before doing anything that blocks; the desktop app's logger does, so a
/// `log::` record from the audio thread never takes a lock or touches a file.
pub fn mark_audio_thread() {
AUDIO_THREAD.set(true);
}
/// True on the thread [`mark_audio_thread`] marked, and on a worker while it renders strips for
/// it. Lock-free and allocation-free.
/// True on the thread [`mark_audio_thread`] marked. Lock-free and allocation-free.
pub fn on_audio_thread() -> bool {
AUDIO_THREAD.get()
}
@@ -29,7 +28,11 @@ fn as_audio_thread(audio: bool, f: impl FnOnce()) {
f();
}
/// Process strips, in parallel on native targets when there are enough of them.
/// Process strips: in parallel on native targets when there are enough of them, except on the
/// realtime audio thread. There they render one after the other on the thread itself: the pool's
/// workers run at normal priority, so under load the callback would wait for starved workers
/// (priority inversion) and miss its deadline, and waiting on them blocks, which the callback
/// never may. Offline renders (bounces) keep the parallelism.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn run_strips<T: Send>(work: &mut [T], f: impl Fn(&mut T) + Sync + Send) {
use rayon::prelude::*;
+435
View File
@@ -0,0 +1,435 @@
//! Independent PCM references for the bounded send consumers, with no hosted plugins/devices.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus, render_range};
use soundcraft_model::{
AutoParam, AutomationLane, AutomationMode, AutomationPoint, BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId,
TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
const LEN: usize = 640;
const PAN: [(i64, f32); 3] = [(37, -1.0), (173, 0.75), (401, 1.0)];
const MUTE: [(i64, f32); 5] = [(37, 0.0), (97, 1.0), (173, 0.0), (257, 1.0), (349, 0.0)];
fn fixture(format: ChannelFormat) -> (Session, TrackId, BusId) {
let mut s = Session::default();
let t = s.add_track(TrackKind::Audio, format, None);
let src = SourceId(900);
let channels = (0..format.channels()).map(|ch| (0..LEN).map(|n| signal(ch, n)).collect()).collect();
s.pool.insert(src, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels })));
let cid = s.new_clip_id();
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original synthetic", src, 0, 0, LEN as i64));
let bus = s.add_bus("Send", ChannelFormat::Stereo);
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
let tr = s.track_mut(t).unwrap();
tr.mixer.output = Route::None;
let mut send = SendSlot::new(Route::Bus(bus));
send.level_db = 0.0;
tr.mixer.sends[0] = Some(send);
(s, t, bus)
}
fn signal(ch: usize, n: usize) -> f32 {
if n % 17 < 9 { 0.25 + ch as f32 / 100.0 } else { -0.125 - ch as f32 / 200.0 }
}
fn lane(s: &mut Session, t: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
s.track_mut(t).unwrap().automation.push(lane);
}
fn automated() -> (Session, TrackId, BusId) {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
(s, t, bus)
}
// The expectation never calls AutomationLane::value_at, pan::gains or any mixer helper.
fn expected_pan(at: i64) -> f64 {
if at <= PAN[0].0 {
return f64::from(PAN[0].1);
}
for pair in PAN.windows(2) {
if at < pair[1].0 {
let f = (at - pair[0].0) as f64 / (pair[1].0 - pair[0].0) as f64;
return f64::from(pair[0].1) + f64::from(pair[1].1 - pair[0].1) * f;
}
}
f64::from(PAN[2].1)
}
fn muted(at: i64) -> bool {
MUTE.iter().rev().find(|p| p.0 <= at).unwrap_or(&MUTE[0]).1 >= 0.5
}
fn pan_factors(p: f64, law: PanLaw) -> [f64; 2] {
if law == PanLaw::Zero {
return [(1.0 - p).min(1.0), (1.0 + p).min(1.0)];
}
let depth = match law {
PanLaw::Minus3 => -3.0,
PanLaw::Minus4_5 => -4.5,
PanLaw::Minus6 => -6.0,
PanLaw::Zero => 0.0,
};
let angle = (p + 1.0) * std::f64::consts::PI / 4.0;
[angle.cos().max(0.0).powf(depth / -3.0103), angle.sin().max(0.0).powf(depth / -3.0103)]
}
fn assert_shape(out: &[Vec<f32>], channels: usize, frames: usize) {
assert_eq!(out.len(), channels);
for channel in out {
assert_eq!(channel.len(), frames);
}
}
fn check(out: &[Vec<f32>], start: i64, frames: usize, law: PanLaw, scale: f64) {
assert_shape(out, 2, frames);
for (ch, values) in out.iter().enumerate() {
for (n, &actual) in values.iter().enumerate() {
let at = start + n as i64;
let reference = if muted(at) { 0.0 } else { f64::from(signal(0, at as usize)) * scale * pan_factors(expected_pan(at), law)[ch] };
assert!((f64::from(actual) - reference).abs() < 2e-7, "channel {ch}, at {at}: {actual} vs {reference}");
}
}
}
fn chunks(eng: &mut MixEngine, s: &Session, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut out = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut k = 0;
while offset < length {
let n = sizes[k % sizes.len()].min(length - offset);
let mut block = vec![vec![0.0; n]; 2];
eng.render(s, start + offset as i64, n, &mut block);
for (out, block) in out.iter_mut().zip(block) {
out.extend(block);
}
offset += n;
k += 1;
}
out
}
#[test]
fn pan_and_mute_match_independent_pcm_across_chunks() {
let (s, _, bus) = automated();
for block in [1, 37, 64, 100, 512, 1024] {
let mut e = MixEngine::new(48_000.0, block.max(16));
let out = chunks(&mut e, &s, 0, LEN, &[block]);
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
let mut e = MixEngine::new(48_000.0, 1024);
check(&chunks(&mut e, &s, 0, LEN, &[1, 37, 64, 3, 100, 19]), 0, LEN, PanLaw::Minus3, 1.0);
check(&render_bus(&s, bus, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn all_pan_laws_match_numeric_reference_and_static_calibration() {
let (s, _, _) = automated();
for law in [PanLaw::Minus3, PanLaw::Minus4_5, PanLaw::Minus6, PanLaw::Zero] {
let mut e = MixEngine::new(48_000.0, 1024);
e.pan_law = law;
check(&chunks(&mut e, &s, 0, LEN, &[100]), 0, LEN, law, 1.0);
for at in [0, 77, 173, 349, 401] {
let (mut reference, t, _) = fixture(ChannelFormat::Mono);
reference.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pan = expected_pan(at) as f32;
let mut static_engine = MixEngine::new(48_000.0, 16);
static_engine.pan_law = law;
let static_pcm = chunks(&mut static_engine, &reference, at, 1, &[1]);
let automated_pcm = chunks(&mut e, &s, at, 1, &[1]);
assert_shape(&automated_pcm, 2, 1);
assert_shape(&static_pcm, 2, 1);
assert_eq!(automated_pcm, static_pcm);
}
}
}
#[test]
fn seeking_used_engine_has_no_cursor_history() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
let _ = chunks(&mut e, &s, 0, 520, &[100]);
for at in [31, 77, 97, 98, 173, 256, 257, 301] {
let out = chunks(&mut e, &s, at, 31, &[17, 1, 13]);
check(&out, at, 31, PanLaw::Minus3, 1.0);
let mut fresh = MixEngine::new(48_000.0, 1024);
assert_eq!(out, chunks(&mut fresh, &s, at, 31, &[17, 1, 13]));
}
}
#[test]
fn loop_wrap_and_tiny_final_chunks_use_absolute_knots() {
let (s, _, _) = automated();
let mut e = MixEngine::new(48_000.0, 1024);
// Same loop splitting as playback: do not render past the loop end before wrapping.
for _ in 0..3 {
check(&chunks(&mut e, &s, 37, 264, &[100, 63]), 37, 264, PanLaw::Minus3, 1.0);
}
for _ in 0..2 {
check(&chunks(&mut e, &s, 97, 76, &[37]), 97, 76, PanLaw::Minus3, 1.0);
}
}
#[test]
fn modes_and_lane_enabled_preserve_existing_reader_policy() {
for mode in AutomationMode::ALL {
let (mut s, t, _) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.automation_mode = mode;
tr.mixer.sends[0].as_mut().unwrap().mute = true;
for lane in &mut tr.automation {
lane.enabled = false;
}
let out = render_range(&s, Range::new(0, LEN as i64), 37);
assert_shape(&out, 2, LEN);
if mode == AutomationMode::Off {
assert!(out.iter().flatten().all(|v| *v == 0.0));
} else {
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
}
}
}
#[test]
fn missing_and_empty_lanes_keep_static_pan_and_mute() {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendPan(0), &[]);
lane(&mut s, t, AutoParam::SendMute(0), &[]);
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().mute = true;
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
#[test]
fn static_matrix_mute_steps_and_threshold_match_reference() {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
lane(&mut s, t, AutoParam::SendMute(0), &[(0, 0.49), (97, 0.5), (173, 0.0)]);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, 2, LEN);
assert_shape(&reference, 2, LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if (97..173).contains(&i) { 0.0 } else { r });
}
}
}
#[test]
fn mute_preserves_routing_for_mono_surround_and_sixteen_channels() {
for fmt in [ChannelFormat::Mono, ChannelFormat::Stereo, ChannelFormat::Surround51, ChannelFormat::Atmos714, ChannelFormat::Atmos916] {
let (mut s, t, bus) = fixture(fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
assert_shape(&out, fmt.channels(), LEN);
assert_shape(&reference, fmt.channels(), LEN);
assert_eq!(out.len(), reference.len());
for (actual, reference) in out.iter().zip(reference) {
assert_eq!(actual.len(), reference.len());
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
assert_eq!(a, if muted(i as i64) { 0.0 } else { r });
}
}
}
}
#[test]
fn wider_source_and_destination_send_pan_keep_static_routing() {
for (src_fmt, dst_fmt) in [
(ChannelFormat::Stereo, ChannelFormat::Stereo),
(ChannelFormat::Mono, ChannelFormat::Surround51),
(ChannelFormat::Surround51, ChannelFormat::Stereo),
] {
let (mut s, t, bus) = fixture(src_fmt);
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = dst_fmt;
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
assert_shape(&reference, dst_fmt.channels(), LEN);
let actual = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert_shape(&actual, dst_fmt.channels(), LEN);
assert_eq!(actual, reference);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
}
}
#[test]
fn pre_post_fader_send_level_and_direct_output_are_preserved() {
for pre in [false, true] {
let (mut s, t, bus) = automated();
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let snd = tr.mixer.sends[0].as_mut().unwrap();
snd.pre_fader = pre;
snd.level_db = -3.0;
let factor = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
check(&render_range(&s, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, factor);
// Keep the direct path isolated from the Aux while comparing source-main PCM.
let aux = s.tracks.iter().find(|tr| tr.kind == TrackKind::Aux).unwrap().id;
s.track_mut(aux).unwrap().inactive = true;
s.track_mut(t).unwrap().mixer.output = Route::Main;
let direct = render_range(&s, Range::new(0, LEN as i64), 37);
s.track_mut(t).unwrap().automation.clear();
s.track_mut(t).unwrap().mixer.sends[0] = None;
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 37), direct);
assert_eq!(s.bus(bus).unwrap().format, ChannelFormat::Stereo);
}
}
#[test]
fn track_solo_and_vca_suppression_cannot_be_unmuted_by_send_lane() {
for suppression in [0, 1, 2] {
let (mut s, t, _) = automated();
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pre_fader = true;
match suppression {
0 => s.track_mut(t).unwrap().mixer.mute = true,
1 => {
let other = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
s.track_mut(other).unwrap().mixer.solo = true;
}
_ => {
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, None);
s.track_mut(vca).unwrap().mixer.mute = true;
s.track_mut(t).unwrap().mixer.vca = Some(vca.0);
}
}
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
}
}
#[test]
fn slots_a_and_j_and_absent_slots_do_not_drive_each_other() {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let other = s.add_bus("J", ChannelFormat::Stereo);
let mut send = SendSlot::new(Route::Bus(other));
send.level_db = 0.0;
s.track_mut(t).unwrap().mixer.sends[9] = Some(send);
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
lane(&mut s, t, AutoParam::SendPan(9), &PAN);
lane(&mut s, t, AutoParam::SendMute(9), &MUTE);
lane(&mut s, t, AutoParam::SendMute(8), &[(0, 1.0)]);
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
check(&render_bus(&s, other, Range::new(0, LEN as i64), 100), 0, LEN, PanLaw::Minus3, 1.0);
}
#[test]
fn malformed_lanes_fall_back_without_changing_document() {
for points in [
vec![AutomationPoint { at: 3, value: -1.0 }, AutomationPoint { at: 1, value: 1.0 }],
vec![AutomationPoint { at: 0, value: f32::NAN }],
vec![AutomationPoint { at: 0, value: f32::INFINITY }],
] {
let (mut s, t, _) = fixture(ChannelFormat::Mono);
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut lane = AutomationLane::new(param);
lane.points = points.clone();
s.track_mut(t).unwrap().automation.push(lane);
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
#[test]
fn stereo_sends_keep_legacy_left_right_routing_for_every_static_pan() {
for static_pan in [-1.0, -0.75, 0.0, 0.75, 1.0, f32::NAN, f32::INFINITY] {
for state in ["absent", "empty", "off", "malformed", "active"] {
for pre in [false, true] {
for gated in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = static_pan;
send.pre_fader = pre;
send.level_db = -3.0;
match state {
"absent" => {}
"empty" => lane(&mut s, t, AutoParam::SendPan(0), &[]),
"off" => {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
}
"malformed" => {
let mut pan = AutomationLane::new(AutoParam::SendPan(0));
pan.points = vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: -1.0 }];
s.track_mut(t).unwrap().automation.push(pan);
}
"active" => lane(&mut s, t, AutoParam::SendPan(0), &PAN),
_ => unreachable!(),
}
if gated {
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
}
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
// Existing stereo sends route channels directly to L/R. This reference
// does not call either routing matrices or a pan helper.
let expected = if gated && state != "off" && muted(n as i64) { 0.0 } else { f64::from(signal(ch, n)) * scale };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} gated={gated} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
assert_eq!(s.track(t).unwrap().mixer.sends[0].as_ref().unwrap().pan.to_bits(), static_pan.to_bits());
}
}
}
}
}
#[test]
fn inactive_mono_send_lanes_match_independent_static_controls() {
for state in ["absent", "empty", "off", "unordered", "nan", "infinite"] {
for pre in [false, true] {
for static_mute in [false, true] {
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
let tr = s.track_mut(t).unwrap();
tr.mixer.volume_db = -6.0;
let send = tr.mixer.sends[0].as_mut().unwrap();
send.pan = -0.625;
send.mute = static_mute;
send.pre_fader = pre;
send.level_db = -3.0;
if state == "off" {
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
} else if state != "absent" {
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
let mut control = AutomationLane::new(param);
control.points = match state {
"empty" => vec![],
"unordered" => vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: 0.0 }],
"nan" => vec![AutomationPoint { at: 0, value: f32::NAN }],
"infinite" => vec![AutomationPoint { at: 0, value: f32::INFINITY }],
_ => unreachable!(),
};
s.track_mut(t).unwrap().automation.push(control);
}
}
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
let factors = pan_factors(-0.625, PanLaw::Minus3);
for block in [1, 37, 100] {
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
assert_shape(&out, 2, LEN);
for (ch, channel) in out.iter().enumerate() {
for (n, &actual) in channel.iter().enumerate() {
let expected = if static_mute { 0.0 } else { f64::from(signal(0, n)) * scale * factors[ch] };
assert!(
(f64::from(actual) - expected).abs() < 2e-7,
"{state} pre={pre} muted={static_mute} ch={ch} at={n}: {actual} != {expected}"
);
}
}
}
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
assert_eq!(before, after);
}
}
}
}
+322
View File
@@ -0,0 +1,322 @@
//! Send automation follows the delayed audio at its tap, without changing existing PDC routing.
use craft_audio::AudioBuffer;
use soundcraft_dsp::pan::PanLaw;
use soundcraft_mix::{MixEngine, render_bus};
use soundcraft_model::{
AutoParam, AutomationLane, BusId, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind,
};
use soundcraft_time::Range;
use std::sync::Arc;
// The built-in Maximizer uses 1.5 ms of lookahead: 72 samples at 48 kHz, with a declared
// and physical delay of 72 - 1 = 71. Its untouched threshold 0 dB gives unity drive;
// every synthetic level stays below the default -0.3 dB ceiling, so there is no limiting.
// Expected timelines use these declared values, not mixer latency fields or the clock helper.
const LOOKAHEAD: usize = 71;
const SOURCE_FRAMES: usize = 2048;
const MUTE_AT: i64 = 300;
const AMPLITUDE: f32 = 0.25;
struct Graph {
session: Session,
capture: BusId,
receiver: TrackId,
clip_start: i64,
pan_start: i64,
pan_end: i64,
}
fn maximizers(session: &mut Session, track: TrackId, count: usize) {
for slot in session.track_mut(track).unwrap().mixer.inserts.iter_mut().take(count) {
*slot = Some(Insert::new("maximizer"));
}
}
fn source(session: &mut Session, insert_count: usize, clip_start: i64) -> TrackId {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Declared DC"));
let id = SourceId(901);
session.pool.insert(id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![AMPLITUDE; SOURCE_FRAMES]] })));
let clip = session.new_clip_id();
let t = session.track_mut(track).unwrap();
t.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared DC", id, 0, clip_start, SOURCE_FRAMES as i64));
t.mixer.pan = vec![0.0];
t.mixer.output = Route::None;
maximizers(session, track, insert_count);
track
}
fn silent_audio(session: &mut Session, insert_count: usize) {
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Unrelated silent lookahead"));
session.track_mut(track).unwrap().mixer.output = Route::None;
maximizers(session, track, insert_count);
}
fn aux(session: &mut Session, input: BusId, format: ChannelFormat, insert_count: usize) -> TrackId {
let track = session.add_track(TrackKind::Aux, format, None);
let t = session.track_mut(track).unwrap();
t.mixer.input = Route::Bus(input);
t.mixer.output = Route::None;
t.mixer.pan = if format == ChannelFormat::Mono { vec![0.0] } else { vec![-1.0, 1.0] };
maximizers(session, track, insert_count);
track
}
fn silent_aux(session: &mut Session, insert_count: usize) {
let input = session.add_bus("Unrelated empty input", ChannelFormat::Mono);
aux(session, input, ChannelFormat::Mono, insert_count);
}
fn return_to_main(session: &mut Session, input: BusId) -> TrackId {
let track = aux(session, input, ChannelFormat::Stereo, 0);
session.track_mut(track).unwrap().mixer.output = Route::Main;
track
}
fn automation(session: &mut Session, track: TrackId, param: AutoParam, points: &[(i64, f32)]) {
let mut lane = AutomationLane::new(param);
for &(at, value) in points {
lane.set_point(at, value);
}
session.track_mut(track).unwrap().automation.push(lane);
}
fn send(session: &mut Session, sender: TrackId, capture: BusId, pre: bool, pan_start: i64, pan_end: i64, automated_pan: bool) {
let mut send = SendSlot::new(Route::Bus(capture));
send.level_db = 0.0;
send.pre_fader = pre;
send.pan = -1.0;
session.track_mut(sender).unwrap().mixer.sends[0] = Some(send);
automation(session, sender, AutoParam::SendMute(0), &[(-512, 0.0), (MUTE_AT, 1.0)]);
if automated_pan {
automation(session, sender, AutoParam::SendPan(0), &[(pan_start, -1.0), (pan_end, 1.0)]);
}
}
fn ordinary(pre: bool, own_inserts: usize, silent_inserts: usize, pdc: bool, clip_start: i64, pan_start: i64, pan_end: i64) -> Graph {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let sender = source(&mut session, own_inserts, clip_start);
if silent_inserts > 0 {
silent_audio(&mut session, silent_inserts);
}
let capture = session.add_bus("Automation capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, pan_start, pan_end, true);
let receiver = return_to_main(&mut session, capture);
Graph { session, capture, receiver, clip_start, pan_start, pan_end }
}
fn make_mix() -> MixEngine {
let mut mix = MixEngine::new(48_000.0, 1024);
mix.pan_law = PanLaw::Zero;
mix
}
fn capture_pcm(mix: &mut MixEngine, graph: &Graph, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
let mut main = vec![Vec::new(), Vec::new()];
let mut offset = 0;
let mut block = 0;
while offset < length {
let n = sizes[block % sizes.len()].min(length - offset);
let mut main_block = vec![vec![0.0; n]; 2];
mix.render(&graph.session, start + offset as i64, n, &mut main_block);
for (output, samples) in main.iter_mut().zip(main_block) {
assert_eq!(samples.len(), n);
output.extend(samples);
}
offset += n;
block += 1;
}
main
}
fn numeric_pan(at: i64, first: i64, last: i64) -> [f32; 2] {
let pan = if at <= first {
-1.0
} else if at >= last {
1.0
} else {
(-1.0 + 2.0 * (at - first) as f64 / (last - first) as f64) as f32
};
// Independent declared zero-depth pan law; no routing or automation helper is called.
[(1.0 - pan).min(1.0), (1.0 + pan).min(1.0)]
}
fn check_known(output: &[Vec<f32>], graph: &Graph, start: i64, delay: usize, length: usize) {
assert_eq!(output.len(), 2);
for (channel, samples) in output.iter().enumerate() {
assert_eq!(samples.len(), length);
for (offset, &sample) in samples.iter().enumerate() {
let source_time = start + offset as i64 - delay as i64;
let audible =
offset >= delay && source_time >= graph.clip_start && source_time < graph.clip_start + SOURCE_FRAMES as i64 && source_time < MUTE_AT;
let expected = if audible { AMPLITUDE * numeric_pan(source_time, graph.pan_start, graph.pan_end)[channel] } else { 0.0 };
assert!(sample.is_finite());
assert!(
(sample - expected).abs() < 2e-7,
"channel {channel}, emit {}, source {source_time}, delay {delay}: {sample} != {expected}",
start + offset as i64
);
}
}
assert!(output.iter().flatten().any(|sample| sample.abs() > 0.02), "declared capture must be audible");
}
#[test]
fn unrelated_silent_lookahead_keeps_audio_pre_post_pan_and_last_source_sample_299() {
for pre in [false, true] {
let graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 800, &[1, 7, 37, 100, 3, 64]);
assert_eq!(mix.latency, LOOKAHEAD, "the unrelated real Maximizer actually contributes latency");
check_known(&output, &graph, 0, LOOKAHEAD, 800);
let last = output[0].iter().rposition(|sample| sample.abs() > 1e-6).unwrap();
assert_eq!(last, MUTE_AT as usize - 1 + LOOKAHEAD);
// Public render_bus uses its default -3 dB law. This separate mute-only fixture
// holds the static send at its left endpoint, whose factors are exactly1/0.
let mut offline_session = graph.session.clone();
offline_session.tracks[0].automation.retain(|lane| lane.param != AutoParam::SendPan(0));
let offline = render_bus(&offline_session, graph.capture, Range::new(0, 640), 37);
assert_eq!(offline[0].len(), 640);
assert_eq!(offline[0].iter().rposition(|sample| sample.abs() > 1e-6), Some(299));
for (channel, samples) in offline.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let expected = if at < MUTE_AT as usize && channel == 0 { AMPLITUDE } else { 0.0 };
assert!((sample - expected).abs() < 2e-7);
}
}
}
}
#[test]
fn aux_pre_tap_omits_post_alignment_while_both_taps_include_upstream_and_own_delay() {
for pdc in [false, true] {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = pdc;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Own upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let sender = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Aux capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let tap_delay = if pdc && !pre { 3 * LOOKAHEAD } else { 2 * LOOKAHEAD };
let observation_delay = if pdc { 2 * LOOKAHEAD } else { 0 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[100, 17, 1, 37, 64]);
assert_eq!(mix.latency, if pdc { 3 * LOOKAHEAD } else { 0 });
check_known(&output, &graph, 0, tap_delay + observation_delay, 900);
}
}
}
#[test]
fn nested_aux_taps_accumulate_the_actual_upstream_path_instead_of_global_latency() {
for pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
silent_audio(&mut session, 2);
let first_bus = session.add_bus("Nested first", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(first_bus);
let first_aux = aux(&mut session, first_bus, ChannelFormat::Mono, 1);
let second_bus = session.add_bus("Nested second", ChannelFormat::Mono);
session.track_mut(first_aux).unwrap().mixer.output = Route::Bus(second_bus);
let sender = aux(&mut session, second_bus, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let capture = session.add_bus("Nested capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, pre, 0, 600, true);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
// Upstream audio2*71; first Aux own+alignment2*71; target pre adds1*71,
// target post adds2*71. The scalar global mix delay is only4*71.
let tap_delay = if pre { 5 * LOOKAHEAD } else { 6 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 1100, &[37, 3, 100, 64, 1]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
check_known(&output, &graph, 0, tap_delay + observation_delay, 1100);
}
}
#[test]
fn output_extra_downstream_aux_and_master_delay_do_not_shift_the_send_clock() {
for pre in [false, true] {
let mut graph = ordinary(pre, 0, 1, true, 0, 0, 600);
let source = graph.session.tracks[0].id;
graph.session.track_mut(source).unwrap().mixer.output = Route::Main;
maximizers(&mut graph.session, graph.receiver, 1);
silent_aux(&mut graph.session, 2);
let master = graph.session.add_track(TrackKind::Master, ChannelFormat::Stereo, None);
maximizers(&mut graph.session, master, 1);
let mut mix = make_mix();
let main = capture_pcm(&mut mix, &graph, 0, 900, &[100, 37, 1, 64]);
assert_eq!(mix.latency, 4 * LOOKAHEAD);
assert!(main.iter().all(|channel| channel[..4 * LOOKAHEAD].iter().all(|sample| *sample == 0.0)));
assert!(main[0][4 * LOOKAHEAD] > 0.4, "main really traverses the excluded output/Aux/Master delays");
for (channel, samples) in main.iter().enumerate() {
for (at, &sample) in samples.iter().enumerate() {
let source_time = at as i64 - (4 * LOOKAHEAD) as i64;
let expected = if source_time < 0 {
0.0
} else {
let sent = if source_time < MUTE_AT { AMPLITUDE * numeric_pan(source_time, 0, 600)[channel] } else { 0.0 };
AMPLITUDE + sent
};
assert!((sample - expected).abs() < 2e-7, "exclusion channel {channel}, emit {at}: {sample} != {expected}");
}
}
}
}
#[test]
fn unequal_aux_pre_and_direct_bus_ages_keep_the_documented_raw_clock_fallback() {
for target_pre in [false, true] {
let mut session = Session::default();
session.edit.delay_compensation = true;
let source = source(&mut session, 1, 0);
let input = session.add_bus("Mixed upstream", ChannelFormat::Mono);
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
let contributor = aux(&mut session, input, ChannelFormat::Mono, 1);
silent_aux(&mut session, 2);
let mixed_bus = session.add_bus("Unequal actual ages", ChannelFormat::Mono);
session.track_mut(contributor).unwrap().mixer.output = Route::Bus(mixed_bus);
let mut pre_send = SendSlot::new(Route::Bus(mixed_bus));
pre_send.level_db = 0.0;
pre_send.pre_fader = true;
session.track_mut(contributor).unwrap().mixer.sends[0] = Some(pre_send);
let sender = aux(&mut session, mixed_bus, ChannelFormat::Mono, 0);
let capture = session.add_bus("Mixed capture", ChannelFormat::Stereo);
send(&mut session, sender, capture, target_pre, 0, 600, false);
let receiver = return_to_main(&mut session, capture);
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
let mut mix = make_mix();
let output = capture_pcm(&mut mix, &graph, 0, 900, &[37, 100, 1, 3, 64]);
let extra = if target_pre { 0 } else { 2 * LOOKAHEAD };
let observation_delay = 2 * LOOKAHEAD;
let delays = [2 * LOOKAHEAD + extra + observation_delay, 3 * LOOKAHEAD + extra + observation_delay];
for (at, (&left, &right)) in output[0].iter().zip(&output[1]).enumerate() {
let contributions = delays.iter().filter(|&&delay| at >= delay).count();
let expected = if at < MUTE_AT as usize + observation_delay { AMPLITUDE * contributions as f32 } else { 0.0 };
assert!((left - expected).abs() < 2e-7, "mixed tap pre={target_pre} emit{at}: {left} != {expected}");
assert_eq!(right, 0.0);
}
assert!(output[0].iter().any(|sample| *sample > 0.02));
}
}
#[test]
fn negative_positions_and_reset_seek_use_the_delayed_source_clock_with_pdc_off() {
let graph = ordinary(false, 1, 0, false, -512, -300, 300);
let mut mix = make_mix();
let negative = capture_pcm(&mut mix, &graph, -128, 256, &[1, 37, 3, 64, 17]);
assert_eq!(mix.latency, 0, "PDC is off while the insert still physically delays its source");
check_known(&negative, &graph, -128, LOOKAHEAD, 256);
mix.reset();
let seek = capture_pcm(&mut mix, &graph, 240, 400, &[100, 1, 37, 3]);
check_known(&seek, &graph, 240, LOOKAHEAD, 400);
assert_eq!(seek[1].iter().rposition(|sample| sample.abs() > 1e-6), Some(130));
}
+74 -5
View File
@@ -1,7 +1,7 @@
use super::{
Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin,
PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId,
itu_stereo_fold, main_channels, midi, record, sync_channel,
Arc, AtomicBool, AtomicU32, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering,
OutputTrouble, Plugin, PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared,
SyncSender, TrackId, devices, itu_stereo_fold, main_channels, midi, record, sync_channel,
};
use soundcraft_mix::{LiveMidi, midi_port_bit, midi_thru};
use soundcraft_model::TrackKind;
@@ -17,6 +17,29 @@ pub(crate) struct Fault {
pub(crate) beats: std::sync::atomic::AtomicU64,
/// The UI has been told.
reported: AtomicBool,
/// Underruns the device reported, callbacks that overran their buffer period, and the worst
/// callback's share of its buffer time (‰), since the stream opened or the last
/// [`Player::take_health`], and the device callbacks in that time.
xruns: std::sync::atomic::AtomicU64,
late_callbacks: std::sync::atomic::AtomicU64,
worst_load: AtomicU32,
callbacks: std::sync::atomic::AtomicU64,
}
/// How the realtime audio path keeps up, for the UI and for stress tests: since the output
/// opened, or since the last [`Player::take_health`].
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub struct AudioHealth {
/// Device callbacks (none for the silent clock).
pub callbacks: u64,
/// Underruns (dropouts) the device reported.
pub xruns: u64,
/// Callbacks that overran their buffer period. Not every one is an audible gap, and the
/// device may report the same overrun as an xrun too (CoreAudio does).
pub late_callbacks: u64,
/// The slowest callback's render time as a share of its buffer period, to 0.001 (1.0 = it
/// overran).
pub worst_load: f64,
}
impl Fault {
@@ -33,6 +56,50 @@ impl Fault {
};
(!self.reported.swap(true, Ordering::Relaxed)).then_some(trouble)
}
/// A device callback rendered `frames` at `rate` in `took`. Lock-free and allocation-free.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn note_callback(&self, took: std::time::Duration, frames: usize, rate: f64) {
self.callbacks.fetch_add(1, Ordering::Relaxed);
if frames == 0 || rate <= 0.0 {
return;
}
let load = took.as_secs_f64() * rate / frames as f64;
if load > 1.0 {
self.late_callbacks.fetch_add(1, Ordering::Relaxed);
}
self.worst_load.fetch_max((load * 1000.0).min(f64::from(u32::MAX)) as u32, Ordering::Relaxed);
}
/// The stream reported an error (on the audio thread or another). A lost stream is recorded
/// as gone; a transient xrun is counted and the stream keeps playing.
pub(crate) fn note_stream_error(&self, e: &cpal::Error) {
if devices::stream_lost(e) {
self.gone.store(true, Ordering::Relaxed);
} else if e.kind() == cpal::ErrorKind::Xrun {
self.xruns.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.load(Ordering::Relaxed),
xruns: self.xruns.load(Ordering::Relaxed),
late_callbacks: self.late_callbacks.load(Ordering::Relaxed),
worst_load: f64::from(self.worst_load.load(Ordering::Relaxed)) / 1000.0,
}
}
/// The health so far, counting afresh from here: each counter is swapped for zero, so an
/// event the callback records meanwhile lands in this reading or the next, never in neither.
pub(crate) fn take_health(&self) -> AudioHealth {
AudioHealth {
callbacks: self.callbacks.swap(0, Ordering::Relaxed),
xruns: self.xruns.swap(0, Ordering::Relaxed),
late_callbacks: self.late_callbacks.swap(0, Ordering::Relaxed),
worst_load: f64::from(self.worst_load.swap(0, Ordering::Relaxed)) / 1000.0,
}
}
}
/// How long a playing output may go without a block before it counts as stalled.
@@ -981,14 +1048,16 @@ impl Side {
}
}
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) {
/// `false` when no block was rendered since the last take (`out` keeps its readings).
pub(crate) fn take_meter_snapshot(source: &mut MeterSnapshot, out: &mut MeterSnapshot) -> bool {
if !source.fresh {
// No block since the last take: keep the readings, but not those of deleted tracks.
out.tracks.retain(|id, _| source.tracks.contains_key(id));
return;
return false;
}
copy_meter_snapshot(source, out);
source.reset_levels();
true
}
pub(crate) fn copy_meter_snapshot(source: &MeterSnapshot, out: &mut MeterSnapshot) {
+30 -8
View File
@@ -48,8 +48,9 @@ const BLOCK: usize = 512;
/// Room for replaced snapshots on their way back; `update_session` empties it before each send.
const OLD_SESSIONS: usize = 16;
/// The realtime audio thread marker lives in the mix engine, which carries it into the strips it
/// renders on worker threads; the cpal callbacks here set it.
pub use callback::AudioHealth;
/// The realtime audio thread marker lives in the mix engine, which renders every strip on the
/// marked thread itself; the cpal callbacks here set it.
pub use soundcraft_mix::{mark_audio_thread, on_audio_thread};
mod callback;
@@ -105,6 +106,12 @@ impl MeterSnapshot {
self.fresh = true;
}
/// Zero every level, keeping the entries and their storage: for a reader whose readings went
/// stale because no block has arrived for a while (the device stopped calling back).
pub fn clear_levels(&mut self) {
self.reset_levels();
}
/// Drop the entries of deleted tracks.
fn forget(&mut self, gone: &[TrackId]) {
for id in gone {
@@ -215,6 +222,19 @@ impl Player {
self.fault.trouble(stalled)
}
/// How the realtime path has kept up since the output opened or the last
/// [`Player::take_health`]: callbacks, device-reported underruns, late callbacks and the
/// worst callback load.
pub fn health(&self) -> AudioHealth {
self.fault.health()
}
/// [`Player::health`] so far, then count afresh (a stress run measures from a take). No
/// event is lost between the reading and the restart.
pub fn take_health(&self) -> AudioHealth {
self.fault.take_health()
}
fn side(&self) -> std::sync::MutexGuard<'_, Side> {
self.side.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -551,13 +571,15 @@ impl Player {
/// Take the meters accumulated since the last call into reusable UI storage and start a new
/// period: `out` gets the highest peak of every block rendered in between. If no block was
/// rendered since (a large device buffer renders several blocks per callback), `out` keeps
/// the previous values rather than dropping to silence. Call it from one place only (two
/// readers would split the peaks between them). Once track/channel counts are stable this
/// performs no allocation. The audio thread only ever `try_lock`s, so holding the lock here
/// never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) {
/// the previous values rather than dropping to silence, and the call returns `false`: when
/// that goes on for longer than any device buffer lasts, the device has stopped calling back
/// and the reader should clear the readings ([`MeterSnapshot::clear_levels`]). Call it from
/// one place only (two readers would split the peaks between them). Once track/channel
/// counts are stable this performs no allocation. The audio thread only ever `try_lock`s, so
/// holding the lock here never blocks it; blocks rendered meanwhile reach the next call.
pub fn take_meters(&self, out: &mut MeterSnapshot) -> bool {
let mut source = self.shared.meters.lock().unwrap_or_else(PoisonError::into_inner);
take_meter_snapshot(&mut source, out);
take_meter_snapshot(&mut source, out)
}
}
+8 -4
View File
@@ -1,5 +1,5 @@
use super::callback::{AudioState, Fault, guarded_block};
use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
use super::{Arc, AudioConfig, Cmd, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
/// Start a freshly built output stream. `false` when the device refuses to start it, so the caller
/// treats it like a stream that failed to build and tries the next configuration.
@@ -63,10 +63,14 @@ where
let mut scratch = vec![0.0f32; 8192 * frame];
let chunk = scratch.len();
let (failed, guard, gone) = (Arc::clone(fault), Arc::clone(shared), Arc::clone(fault));
#[cfg(not(target_arch = "wasm32"))]
let rate = f64::from(config.sample_rate);
device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
mark_audio_thread();
#[cfg(not(target_arch = "wasm32"))]
let started = std::time::Instant::now();
for out in data.chunks_mut(chunk) {
let Some(s) = scratch.get_mut(..out.len()) else { return };
guarded_block(&failed, &guard, s, |d| state.fill(d, channels));
@@ -74,6 +78,8 @@ where
*o = T::from_sample(*x);
}
}
#[cfg(not(target_arch = "wasm32"))]
failed.note_callback(started.elapsed(), data.len() / frame, rate);
},
// cpal may call this on the audio thread (on ALSA in a loop while the device stays
// broken): marked, so the logger hands the record off instead of writing it.
@@ -83,9 +89,7 @@ where
// stream that must be rebuilt (`StreamInvalidated`), stops playback until the user
// reconnects; a rerouted default device (`DeviceChanged`) keeps playing on the new
// route, and an xrun is transient, so neither counts as losing the stream.
if devices::stream_lost(&e) {
gone.gone.store(true, Ordering::Relaxed);
}
gone.note_stream_error(&e);
log::warn!("audio stream error: {e}");
},
None,
+29 -4
View File
@@ -162,17 +162,20 @@ 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);
// Taking starts a new period: the next quiet blocks read quiet.
st.fill(&mut out, 2);
take_meter_snapshot(&mut shared.meters.lock().unwrap(), &mut ui);
assert!(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]
@@ -286,6 +289,28 @@ fn a_lost_or_stalled_device_is_reported_once() {
assert_eq!((fault.trouble(false), fault.trouble(true)), (Some(OutputTrouble::Gone), None));
}
#[test]
fn underruns_and_late_callbacks_are_counted_until_taken() {
use std::time::Duration;
let f = Fault::default();
let error = |kind| cpal::Error::with_message(kind, "test");
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
// 512 frames at 48 kHz last 10.67 ms.
f.note_callback(Duration::from_millis(4), 512, 48_000.0);
f.note_callback(Duration::from_millis(16), 512, 48_000.0);
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
let h = f.health();
assert_eq!(h, AudioHealth { callbacks: 3, xruns: 2, late_callbacks: 1, worst_load: 1.5 });
assert!(!f.gone.load(Ordering::Relaxed), "an underrun is not a lost device");
assert_eq!(f.take_health(), h);
assert_eq!(f.health(), AudioHealth::default());
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
assert_eq!(f.health().callbacks, 1);
f.note_stream_error(&error(cpal::ErrorKind::DeviceNotAvailable));
assert!(f.gone.load(Ordering::Relaxed));
}
#[test]
fn audio_state_plays_and_stops_at_end() {
let s = Arc::new(soundcraft_model::Session::default());
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+20 -2
View File
@@ -154,6 +154,8 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
"new" => "novo",
"New Bus" => "Novo bus",
"new bus..." => "novo bus...",
"new mono bus" => "novo bus mono",
"new stereo bus" => "novo bus estéreo",
"New Configuration…" => "Nova configuração…",
"New Group…" => "Novo grupo…",
"New..." => "Novo...",
@@ -325,6 +327,9 @@ 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."
}
@@ -778,6 +783,10 @@ fn menu_translate(source: &str) -> Option<&'static str> {
"Start to Insertion" => "Do início até o ponto de inserção",
"Step Input..." => "Entrada passo a passo...",
"Stretch..." => "Alongar...",
"Room Tone" => "Som ambiente",
"Set Room Tone" => "Definir som ambiente",
"Fill Gaps with Room Tone" => "Preencher lacunas com som ambiente",
"Clear Room Tone" => "Limpar som ambiente",
"Strip Silence" => "Remover silêncio",
"Sync Point" => "Ponto de sincronização",
"Synchronization" => "Sincronização",
@@ -1779,6 +1788,9 @@ fn menu_translate(source: &str) -> Option<&'static str> {
"Enable Track Notes Dialog" => "Ativar o diálogo de notas da pista",
"English" => "Inglês",
"Portuguese (Brazil)" => "Português (Brasil)",
"French" => "Francês",
"Spanish" => "Espanhol",
"Simplified Chinese" => "Chinês simplificado",
"key:Space" => "Espaço",
"key:Up" => "Cima",
"key:Down" => "Baixo",
@@ -2064,8 +2076,8 @@ fn menu_translate(source: &str) -> Option<&'static str> {
"♩ = {bpm:.2} {n}/{d}" => "♩ = {bpm:.2} {n}/{d}",
"{n} ch" => "{n} canais",
"{b}-bit" => "{b} bits",
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · Shift-drag for fine control · Alt-click for 0 dB · right-click for options" => {
"Envio {which} para {name}: {db} dB\nClique para abrir o fader do envio · arraste na vertical para ajustar · Shift-arraste para controle fino · Alt-clique para 0 dB · clique com o botão direito para opções"
"Send {which} to {name}: {db} dB\nClick for the send fader · drag vertically to adjust · {fine_drag} or Shift-drag for fine control · Alt-click for 0 dB · right-click for options" => {
"Envio {which} para {name}: {db} dB\nClique para abrir o fader do envio · arraste na vertical para ajustar · {fine_drag} ou Shift-arraste para controle fino · Alt-clique para 0 dB · clique com o botão direito para opções"
}
"1 {what}" => "1 {what}",
"{n} {what}s" => "{n} {what}s",
@@ -2081,6 +2093,11 @@ fn menu_translate(source: &str) -> Option<&'static str> {
" {n} of the files are used by {users}" => " {n} dos arquivos são usados por {users}",
" The file stays on disk." => " O arquivo permanece no disco.",
" The files stay on disk." => " Os arquivos permanecem no disco.",
"Unloop" => "Desativar loop",
"Flatten" => "Consolidar",
"Remove deletes the loop iterations and keeps the source clip. Flatten keeps each loop iteration as its own clip." => {
"Remover exclui as iterações do loop e mantém o clipe de origem. Consolidar mantém cada iteração do loop como um clipe próprio."
}
_ => return error_translation(source),
})
}
@@ -2109,6 +2126,7 @@ error_templates! {
"internal error in `{c}`: {why}" => "erro interno em `{c}`: {why}",
"stop recording first" => "pare a gravação primeiro",
"journal entry cap" => "limite de entradas do diário atingido",
"MIDI file exceeds a limit of {events} events, {tracks} tracks, or {bytes} bytes of SysEx payload" => "O arquivo MIDI excede um dos limites: {events} eventos, {tracks} pistas ou {bytes} bytes de dados SysEx",
"MIDI file: more than {n} meter changes" => "arquivo MIDI: mais de {n} mudanças de compasso",
"MIDI file: more than {n} tempo changes" => "arquivo MIDI: mais de {n} mudanças de andamento",
"MIDI file: more than {n} tracks" => "arquivo MIDI: mais de {n} pistas",
File diff suppressed because it is too large Load Diff
+2 -1
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(),
@@ -415,7 +416,7 @@ impl SoundApp {
if self.meters_live() {
let hz = if self.ui.window == MainWindow::Mix { 60 } else { 30 };
ctx.request_repaint_after(std::time::Duration::from_millis(1000 / hz));
} else if self.meters.values().any(|m| m.level[0] > 0.0001) {
} else if self.main_meter.is_moving() || self.meters.values().any(MeterDisplay::is_moving) {
ctx.request_repaint_after(std::time::Duration::from_millis(80));
} else if !self.pending_shots.is_empty() || !self.synthetic.is_empty() {
ctx.request_repaint();
+170 -16
View File
@@ -133,6 +133,24 @@ impl SoundApp {
}
}
/// How long the meters keep the last readings while no audio block arrives. Longer than the
/// longest device buffer (8192 frames at 44.1 kHz, 186 ms) plus the slowest meter poll (50 ms), so
/// a large buffer never reads as silence between its callbacks; once it has passed, the device has
/// stopped calling back (switched off, unplugged, stalled) and the meters fall to silence.
pub(super) const METER_STALE_SECS: f64 = 0.5;
/// After a meter take that `fresh`ly brought new blocks or not, at `now` (uptime, seconds): note
/// when the last block came in `last_block`, and clear `snap`'s readings once none has come for
/// [`METER_STALE_SECS`]. Otherwise the last block's levels would be fed to the meters every frame
/// and never fall.
pub(super) fn age_meters(snap: &mut soundcraft_playback::MeterSnapshot, fresh: bool, now: f64, last_block: &mut f64) {
if fresh {
*last_block = now;
} else if now - *last_block >= METER_STALE_SECS {
snap.clear_levels();
}
}
/// Open the new device of `cfg` with `open` in place of the one in `slot`, and return it; the caller
/// stores it, which closes the old one if it is still there.
///
@@ -155,33 +173,106 @@ 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) {
/// Fold one reading into a strip's meter. `peak` is the stereo pair (a mono strip repeats its one
/// channel), `peaks` every channel of the strip: channels from the third on read from `peaks`.
pub(super) fn feed_meter(d: &mut MeterDisplay, peak: [f32; 2], peaks: &[f32], gr: f32, dt: f32) {
// Instant attack, ~26 dB/s release, 2 s peak hold.
let fall = 10f32.powf(-26.0 * dt / 20.0);
for c in 0..2 {
let v = peak.get(c).copied().unwrap_or(0.0);
let lvl = d.level.get(c).copied().unwrap_or(0.0);
let nv = if v >= lvl { v } else { (lvl * fall).max(v) };
if let Some(x) = d.level.get_mut(c) {
*x = if nv < 1e-5 { 0.0 } else { nv };
// Each channel times its own hold, so activity on one channel cannot keep another's hold up.
let channels = d.level.iter_mut().zip(&mut d.hold).zip(&mut d.hold_age).enumerate();
for (c, ((lvl, hold), age)) in channels {
let v = if c < 2 { peak.get(c) } else { peaks.get(c) }.copied().filter(|v| v.is_finite()).unwrap_or(0.0);
let nv = if v >= *lvl { v } else { (*lvl * fall).max(v) };
*lvl = if nv < 1e-5 { 0.0 } else { nv };
if v >= *hold {
*hold = v;
*age = 0.0;
}
if v >= d.hold.get(c).copied().unwrap_or(0.0) {
if let Some(h) = d.hold.get_mut(c) {
*h = v;
}
d.hold_age = 0.0;
*age += dt;
if *age > 2.0 {
*hold = *lvl;
}
if v >= 1.0 {
d.clip = true;
}
}
d.hold_age += dt;
if d.hold_age > 2.0 {
d.hold = d.level;
}
d.gr = if gr > d.gr { gr } else { d.gr * fall };
}
#[cfg(test)]
mod tests {
use super::{MeterDisplay, feed_meter};
#[test]
fn surround_channels_get_levels_holds_and_clip_like_the_stereo_pair() {
let mut d = MeterDisplay::default();
// A 5.1 strip: L R C LFE Ls Rs; the surround right channel clips.
let peaks = [0.5, 0.4, 0.3, 0.2, 0.1, 1.0];
feed_meter(&mut d, [0.5, 0.4], &peaks, 0.0, 0.05);
assert_eq!(d.level.get(..6), Some(&peaks[..]));
assert_eq!(d.hold.get(..6), Some(&peaks[..]));
assert!(d.clip, "a clip on any channel lights the clip light");
assert!(d.level.get(6..).is_some_and(|rest| rest.iter().all(|v| *v == 0.0)));
// Silence: every channel falls back smoothly, and its peak hold stays up for now.
feed_meter(&mut d, [0.0, 0.0], &[], 0.0, 0.05);
let c = d.level.get(2).copied().unwrap_or_default();
assert!(c > 0.0 && c < 0.3, "C falls, not drops: {c}");
assert_eq!(d.hold.get(2).copied(), Some(0.3));
}
#[test]
fn peak_holds_expire_after_two_seconds_of_silence_on_a_strip_with_unused_channels() {
let mut d = MeterDisplay::default();
// A stereo strip: every channel past the pair is unused and reads 0.
feed_meter(&mut d, [0.5, 0.4], &[0.5, 0.4], 0.0, 0.05);
for _ in 0..50 {
feed_meter(&mut d, [0.0, 0.0], &[], 0.0, 0.05);
}
let l = d.hold.first().copied().unwrap_or_default();
assert!(l < 0.5, "the L hold drops back to the falling level: {l}");
assert_eq!(d.hold, d.level);
}
#[test]
fn a_busy_channel_does_not_keep_a_silent_channels_peak_hold_up() {
let mut d = MeterDisplay::default();
// A 5.1 strip: L peaks once, then only C carries a steady signal.
feed_meter(&mut d, [0.5, 0.0], &[0.5, 0.0, 0.3], 0.0, 0.05);
for _ in 0..50 {
feed_meter(&mut d, [0.0, 0.0], &[0.0, 0.0, 0.3], 0.0, 0.05);
}
let l = d.hold.first().copied().unwrap_or_default();
assert!(l < 0.5, "the L hold expires while C plays on: {l}");
assert_eq!(d.hold.get(2).copied(), Some(0.3));
}
#[test]
fn a_meter_moving_only_past_the_stereo_pair_still_needs_repaints() {
let mut d = MeterDisplay::default();
assert!(!d.is_moving());
// A 5.1 strip with signal on C only.
feed_meter(&mut d, [0.0, 0.0], &[0.0, 0.0, 0.3], 0.0, 0.05);
assert!(d.is_moving());
// Its level has fallen away but the C hold is still up.
d.level = Default::default();
assert!(d.is_moving(), "the hold has yet to expire");
d.hold = Default::default();
assert!(!d.is_moving());
}
#[test]
fn a_misbehaving_plugin_cannot_stick_a_meter() {
let mut d = MeterDisplay::default();
// Non-finite readings on the stereo pair and past it read as silence, not as a clip.
feed_meter(&mut d, [f32::NAN, f32::INFINITY], &[f32::NAN, f32::INFINITY, f32::NAN, f32::NEG_INFINITY], 0.0, 0.05);
assert!(d.level.iter().chain(&d.hold).all(|v| *v == 0.0) && !d.clip, "{d:?}");
// And the next good reading shows on every channel.
feed_meter(&mut d, [0.5, 0.4], &[0.5, 0.4, 0.3, 0.2], 0.0, 0.05);
assert_eq!(d.level.get(..4), Some(&[0.5, 0.4, 0.3, 0.2][..]));
assert_eq!(d.hold.get(..4), Some(&[0.5, 0.4, 0.3, 0.2][..]));
}
}
/// Whether a track needs the audio input opened: an audio track (or an aux) that is
/// record-enabled or input-monitored. A MIDI or instrument track listens to MIDI devices, so
/// arming one does not open an audio device or complain that there is none.
@@ -289,3 +380,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 (peak, peaks) = snap.tracks.get(&t).map_or(([0.0; 2], Vec::new()), |m| (m.peak, m.peaks.clone()));
feed_meter(&mut d, peak, &peaks, 0.0, dt as f32);
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.iter().chain(&d.hold).all(|v| *v == 0.0), "the meter still reads {d:?}");
}
/// A silent channel does not keep the other channel's peak hold up: 0.0 meets a hold of 0.0
/// every frame, which must not restart the other channel's hold time.
#[test]
fn a_silent_channel_does_not_keep_the_other_channels_peak_hold() {
let (d, _) = run(6.0, [0.4, 0.0], |_, now| now < 1.0);
assert!(d.level.iter().chain(&d.hold).all(|v| *v == 0.0), "the meter still reads {d:?}");
}
#[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");
}
}
+1
View File
@@ -12,6 +12,7 @@ impl SoundApp {
// The Output window shows a track of the old session: a track of the new one can have
// the same id.
self.ui.output_window = None;
self.dialogs.session_replaced();
}
/// The session is modified, or a plugin editor gesture still holds a state the session hasn't
+7 -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};
@@ -522,13 +522,14 @@ 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;
for (id, m) in &snap.tracks {
let d = self.meters.entry(*id).or_default();
feed_meter(d, m.peak, m.gain_reduction_db, dt);
feed_meter(d, m.peak, &m.peaks, m.gain_reduction_db, dt);
if m.plugin_failures.count != d.plugin_failures {
d.plugin_failures = m.plugin_failures.count;
if let Some(msg) = failed_plugin_status(self.engine.session(), *id, m.plugin_failures.last) {
@@ -536,8 +537,7 @@ impl SoundApp {
}
}
}
let main = snap.main.peak;
feed_meter(&mut self.main_meter, main, 0.0, dt);
feed_meter(&mut self.main_meter, snap.main.peak, &snap.main.peaks, 0.0, dt);
if ended {
self.stop_play();
}
@@ -557,9 +557,9 @@ impl SoundApp {
}
if !self.meters_live() {
for d in self.meters.values_mut() {
feed_meter(d, [0.0, 0.0], 0.0, dt);
feed_meter(d, [0.0, 0.0], &[], 0.0, dt);
}
feed_meter(&mut self.main_meter, [0.0, 0.0], 0.0, dt);
feed_meter(&mut self.main_meter, [0.0, 0.0], &[], 0.0, dt);
}
}
}
+13
View File
@@ -488,6 +488,19 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
"session.inspect" | "document.inspect" => {
ok(soundcraft_engine::inspect::session(&app.engine, p.get("detail").and_then(Value::as_str) == Some("full")))
}
"audio.health" => match &app.player {
Some(player) => {
let h = if p.get("reset").and_then(Value::as_bool) == Some(true) { player.take_health() } else { player.health() };
ok(json!({
"device": player.device_name,
"silent": player.silent,
"sample_rate": player.device_rate,
"buffer_frames": player.device_buffer,
"health": h,
}))
}
None => err("no audio output"),
},
"ui.inspect" => {
let mut v = app.inspect(ctx);
v["edit_layout"] = json!(app.edit_layout);
+109
View File
@@ -38,6 +38,8 @@ pub enum Dialog {
RenameClip { id: ClipId, name: String },
RenameMarker { id: soundcraft_model::MarkerId, name: String },
ClearClips { clips: Vec<ClipId>, sources: Vec<SourceId>, message: String },
// Clip › Unloop…: the clips `clip.unloop` would take when it opened.
Unloop { clips: Vec<ClipId> },
PathPrompt { cmd: String, title: String, path: String, key: String },
Number { cmd: String, title: String, key: String, value: f64, suffix: String },
TempoChange { at: Samples, bpm: f64 }, // from double-clicking the tempo ruler
@@ -97,6 +99,7 @@ impl Dialogs {
Dialog::RenameClip { .. } => "rename_clip",
Dialog::RenameMarker { .. } => "rename_marker",
Dialog::ClearClips { .. } => "clear_clips",
Dialog::Unloop { .. } => "unloop",
Dialog::PathPrompt { .. } => "path",
Dialog::Number { .. } => "number",
Dialog::TempoChange { .. } => "tempo_change",
@@ -126,6 +129,26 @@ impl Dialogs {
}
}
/// The open session was replaced: closes a dialog that holds track, clip, source, marker or group ids, since the new
/// session can reuse those ids for other objects.
pub(crate) fn session_replaced(&mut self) {
if matches!(
self.open,
Some(
Dialog::RenameTrack { .. }
| Dialog::RenameClip { .. }
| Dialog::RenameMarker { .. }
| Dialog::ClearClips { .. }
| Dialog::Unloop { .. }
| Dialog::AutoRename { .. }
| Dialog::Spot(_)
| Dialog::Group { .. }
)
) {
self.open = None;
}
}
pub fn open_rename_track(&mut self, id: TrackId, name: &str) {
self.set(Dialog::RenameTrack { id, name: name.to_string() });
}
@@ -174,6 +197,11 @@ impl Dialogs {
/// Open the dialog for a command; false when the command has no dialog.
pub fn open_for_command(&mut self, e: &Engine, id: &str) -> bool {
// Unloop with no looped clip opens nothing, so it leaves a pending Save-then-continue action in place.
let unloop_clips = if id == "clip.unloop" { soundcraft_engine::cmd::clip_ids_param(e, &json!({})) } else { Vec::new() };
if id == "clip.unloop" && !unloop_clips.iter().any(|&c| soundcraft_engine::cmd::is_looped(e.session(), c)) {
return false;
}
self.after_save = None;
let home = default_dir();
let name = e.session().name.clone();
@@ -182,6 +210,7 @@ impl Dialogs {
let ed = &e.session().edit;
return self.open_clear(e, ed.selected_clips.clone(), ed.selected_sources.clone());
}
"clip.unloop" => Dialog::Unloop { clips: unloop_clips },
"track.new" => Dialog::NewTracks(new_tracks::NewTracks::default()),
"session.new" => Dialog::NewSession { name: "Untitled".into(), sample_rate: 48_000, demo: false },
"file.bounce_mix" => {
@@ -496,6 +525,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
Dialog::RenameClip { .. } => "Rename Clip",
Dialog::RenameMarker { .. } => "Rename Marker",
Dialog::ClearClips { .. } => "Clear",
Dialog::Unloop { .. } => "Unloop",
Dialog::PathPrompt { title, .. } | Dialog::Number { title, .. } => title.as_str(),
Dialog::TempoChange { .. } => "Tempo Change (BPM)",
Dialog::Spot(_) => "Spot",
@@ -609,6 +639,22 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
action = Some(("clip.clear".into(), json!({"clips": clips, "sources": sources, "with_clips": true})));
}
}
Dialog::Unloop { clips } => {
ui.set_max_width(340.0);
ui.label(crate::localization::text(
"Remove deletes the loop iterations and keeps the source clip. Flatten keeps each loop iteration as its own clip.",
));
ui.separator();
ui.horizontal(|ui| {
if ui.button(crate::localization::text("Flatten")).clicked() {
action = Some(unloop_action(clips, false));
}
// A Flatten click in the same frame as Enter wins.
if buttons(ui, "Remove", enter && action.is_none()) {
action = Some(unloop_action(clips, true));
}
});
}
Dialog::PathPrompt { cmd, path, key, .. } => {
if let Some(c) = path_prompt_form(app, ui, cmd, path, key, enter) {
action = Some(c);
@@ -911,6 +957,11 @@ fn name_field(ui: &mut egui::Ui, name: &mut String) {
}
}
/// The command the Unloop dialog runs: Remove (`remove`) or Flatten.
fn unloop_action(clips: &[ClipId], remove: bool) -> (String, Value) {
("clip.unloop".into(), json!({"clips": clips, "mode": if remove { "remove" } else { "flatten" }}))
}
/// The command the tempo-change dialog runs on OK.
fn tempo_change_action(at: Samples, bpm: f64) -> (String, Value) {
("event.tempo".into(), json!({"bpm": bpm, "at": at}))
@@ -1226,6 +1277,64 @@ mod tests {
assert!(matches!(d.open, Some(Dialog::ScoreSetup { bars_per_system: 4, .. })));
}
#[test]
fn clip_unloop_opens_unloop_and_sends_the_chosen_mode() {
let mut e = soundcraft_engine::demo::demo_engine();
let mut d = Dialogs::default();
e.execute("edit.select_none", &json!({})).unwrap();
assert!(!d.open_for_command(&e, "clip.unloop"));
let track = e.session().track_by_name("Snare").unwrap().id;
let clip = e.session().track(track).unwrap().clips()[0].id;
e.execute("edit.select", &json!({"clips": [clip.0]})).unwrap();
assert!(!d.open_for_command(&e, "clip.unloop"), "a clip that is not looped opens no dialog");
assert!(d.open.is_none());
e.execute("clip.loop", &json!({"clip": clip.0, "count": 3})).unwrap();
e.execute("edit.select", &json!({"clips": [clip.0]})).unwrap();
assert!(d.open_for_command(&e, "clip.unloop"));
assert_eq!(d.open_name(), Some("unloop"));
let Some(Dialog::Unloop { clips }) = d.open.take() else { panic!("Unloop… did not open the Unloop dialog") };
assert_eq!(clips, vec![clip]);
let count = |e: &Engine| e.session().track(track).map_or(0, |t| t.clips().len());
let before = count(&e);
let (cmd, params) = unloop_action(&clips, false);
assert_eq!(params["mode"], "flatten");
e.execute(&cmd, &params).unwrap();
assert_eq!(count(&e), before, "Flatten keeps every iteration");
assert!(e.session().track(track).unwrap().clips().iter().all(|c| c.loop_id.is_none()));
e.execute("edit.undo", &json!({})).unwrap();
let (cmd, params) = unloop_action(&clips, true);
assert_eq!(params["mode"], "remove");
e.execute(&cmd, &params).unwrap();
assert_eq!(count(&e), before - 2, "Remove keeps only the source clip");
}
#[test]
fn unloop_without_a_looped_clip_keeps_the_pending_save_action() {
let mut e = soundcraft_engine::demo::demo_engine();
let mut d = Dialogs { after_save: Some(("app.quit".into(), json!({}))), ..Dialogs::default() };
let clip = e.session().track_by_name("Snare").unwrap().clips()[0].id;
e.execute("edit.select", &json!({"clips": [clip.0]})).unwrap();
assert!(!d.open_for_command(&e, "clip.unloop"));
assert!(d.after_save.is_some(), "an Unloop that opens nothing must not drop the action waiting on Save");
}
#[test]
fn replacing_the_session_closes_dialogs_that_hold_its_ids() {
let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, crate::Services::default());
app.dialogs.set(Dialog::Unloop { clips: vec![ClipId(1)] });
app.document_replaced();
assert!(app.dialogs.open.is_none(), "Unloop must not act on clips of the new session");
app.dialogs.set(Dialog::ClearClips { clips: vec![ClipId(1)], sources: Vec::new(), message: String::new() });
app.document_replaced();
assert!(app.dialogs.open.is_none());
app.dialogs.set(Dialog::Group { id: None, name: "Group".into(), edit: true, mix: true, members: vec![(1, "Kick".into(), true)] });
app.document_replaced();
assert!(app.dialogs.open.is_none(), "Create Group must not group tracks of the new session");
app.dialogs.set(Dialog::NewSession { name: "Untitled".into(), sample_rate: 48_000, demo: false });
app.document_replaced();
assert_eq!(app.dialogs.open_name(), Some("new_session"), "a dialog without session ids stays open");
}
#[test]
fn clip_rename_opens_the_rename_dialog_for_the_selected_clip() {
let mut e = soundcraft_engine::demo::demo_engine();
+8 -4
View File
@@ -45,7 +45,10 @@ use input::{clip_at, fade_midpoint};
use layout::COLUMN_TITLES_H;
#[cfg(test)]
use layout::lane_rect;
pub use layout::{COLUMN_W, EditLayout, HEADER_W, LANE_H, RULER_H, edit_columns, header_width, rect, sample_at, track_height, x_of};
pub use layout::{
COLUMN_W, EditLayout, HEADER_W, LANE_H, RULER_H, edit_columns, header_width, meter_channels, meter_width, rect, sample_at, track_header_width,
track_height, x_of,
};
use overlay::overlay;
#[cfg(test)]
use overlay::playhead_colour;
@@ -125,7 +128,7 @@ pub(crate) fn main_area(app: &mut SoundApp, ui: &mut Ui) {
if session.edit.flag("view.ruler.tempo_editor") && session.edit.rulers.iter().any(|ruler| ruler == "tempo") {
ruler_height_total += ruler_height("tempo_editor");
}
let minimum = vec2(header_width(&edit_columns(session)) + 64.0, ruler_height_total + 100.0);
let minimum = vec2(header_width(session, &edit_columns(session)) + 64.0, ruler_height_total + 100.0);
crate::docking::minimum_body(ui, minimum, |ui| main_area_content(app, ui));
}
@@ -144,7 +147,8 @@ fn main_area_content(app: &mut SoundApp, ui: &mut Ui) {
let titles_h = if cols.is_empty() { 0.0 } else { COLUMN_TITLES_H };
let rulers_h = rulers.iter().map(|r| ruler_height(r)).sum::<f32>() + 6.0 + titles_h;
let hscroll_h = 14.0;
let hw = header_width(&cols);
let head_w = track_header_width(app.engine.session());
let hw = head_w + cols.iter().map(|c| c.3).sum::<f32>();
let header = Rect::from_min_max(full.min, pos2(full.min.x + hw, full.max.y - hscroll_h));
let tl = Rect::from_min_max(pos2(full.min.x + hw, full.min.y + rulers_h), pos2(full.max.x - 12.0, full.max.y - hscroll_h));
let rulers_rect = Rect::from_min_max(pos2(full.min.x, full.min.y), pos2(full.max.x, full.min.y + rulers_h));
@@ -154,7 +158,7 @@ fn main_area_content(app: &mut SoundApp, ui: &mut Ui) {
scroll_and_zoom(app, ui, full, tl);
draw_rulers(app, ui, rulers_rect, tl, &rulers);
views_button(app, ui, rulers_rect);
column_titles(ui, rulers_rect, &cols);
column_titles(ui, app.engine.session(), rulers_rect, &cols);
if let Some(id) = app.edit_scroll_into_view.take() {
scroll_into_view(app, id, tl.height());
}
+13 -8
View File
@@ -1,4 +1,4 @@
use super::layout::STRIP_W;
use super::layout::{HEADER_W, METER_W, STRIP_W, meter_channels, meter_width};
use super::tracks::{click_track, folder_depth, height_targets, in_edit_window, track_context_menu, view_label, view_menu};
use super::{
Align2, AutoParam, Color32, Gesture, Pos2, Rect, Sense, Shape, SoundApp, Stroke, StrokeKind, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui,
@@ -25,7 +25,11 @@ pub(super) fn track_header(app: &mut SoundApp, ui: &mut Ui, track: &Track, head:
voice_row(app, ui, track, head);
field_row(app, ui, track, head, head_bg);
let md = app.meters.get(&id).copied().unwrap_or_default();
header_meter(ui, Rect::from_min_max(pos2(head.max.x - 8.0, head.min.y + 1.0), pos2(head.max.x, head.max.y - 1.5)), &md, track.channels() >= 2);
let channels = meter_channels(app.engine.session(), track);
// Every track's meter starts where a stereo meter would; wider ones run on into the space the
// header widened by (`track_header_width`).
let x = head.min.x + HEADER_W - METER_W;
header_meter(ui, Rect::from_min_max(pos2(x, head.min.y + 1.0), pos2(x + meter_width(channels), head.max.y - 1.5)), &md, channels);
}
/// The colour strip: a click selects the track as the header does, a double click opens the Color
@@ -524,8 +528,9 @@ fn header_toggle(ui: &Ui, r: Rect, track: TrackId, track_name: &str, key: Header
resp.on_hover_text(label)
}
/// The header's level meter: black-rimmed bars, dim where unlit, with a clip light on top.
fn header_meter(ui: &Ui, r: Rect, md: &crate::MeterDisplay, stereo: bool) {
/// The header's level meter: one black-rimmed bar per channel (a mono meter fills the width with
/// one), dim where unlit, with a clip light on top.
fn header_meter(ui: &Ui, r: Rect, md: &crate::MeterDisplay, channels: usize) {
let t = Tokens::current();
let p = ui.painter();
p.rect_filled(r, 0.0, Color32::BLACK);
@@ -533,20 +538,20 @@ fn header_meter(ui: &Ui, r: Rect, md: &crate::MeterDisplay, stereo: bool) {
let clip = inner.with_max_y(inner.min.y + 4.0);
p.rect_filled(clip, 0.0, if md.clip { t.meter_red } else { t.meter_red.gamma_multiply(0.18) });
let body = inner.with_min_y(clip.max.y + 1.0);
let n = if stereo { 2 } else { 1 };
let w = (body.width() - (n - 1) as f32) / n as f32;
let n = channels.clamp(1, md.level.len());
let w = ((body.width() - (n - 1) as f32) / n as f32).max(1.0);
let (amber, red) = (meter_pos(-12.0), meter_pos(-3.0));
for ch in 0..n {
let bar = Rect::from_min_size(pos2(body.min.x + ch as f32 * (w + 1.0), body.min.y), vec2(w, body.height()));
let y = |f: f32| bar.max.y - bar.height() * f;
let lv = level_pos(md.level[ch]);
let lv = level_pos(md.level.get(ch).copied().unwrap_or(0.0));
for (lo, hi, col) in [(0.0, amber, t.meter_green), (amber, red, t.meter_yellow), (red, 1.0, t.meter_red)] {
p.rect_filled(Rect::from_x_y_ranges(bar.x_range(), y(hi)..=y(lo)), 0.0, col.gamma_multiply(0.18));
if lv > lo {
p.rect_filled(Rect::from_x_y_ranges(bar.x_range(), y(lv.min(hi))..=y(lo)), 0.0, col);
}
}
let hv = level_pos(md.hold[ch]);
let hv = level_pos(md.hold.get(ch).copied().unwrap_or(0.0));
if hv > 0.01 {
p.hline(bar.x_range(), y(hv), Stroke::new(1.0, if hv > red { t.meter_red } else { t.meter_yellow }));
}
+27 -2
View File
@@ -32,8 +32,33 @@ pub fn edit_columns(s: &Session) -> Vec<Column> {
COLUMNS.into_iter().filter(|c| all || s.edit.flag(&format!("edit_view.{}", c.0))).collect()
}
pub fn header_width(cols: &[Column]) -> f32 {
HEADER_W + cols.iter().map(|c| c.3).sum::<f32>()
/// The meter at the right of a track header: one bar per channel as Pro Tools draws it, at the
/// density of the stereo meter (2.5 pt bars, 1 pt apart, inside a 1 pt rim). Mono and stereo
/// meters share the stereo width.
pub(super) const METER_W: f32 = 8.0;
/// The width of a track header's meter for `channels` channels.
pub fn meter_width(channels: usize) -> f32 {
let n = channels.clamp(1, soundcraft_mix::MAX_CHANNELS) as f32;
(2.0 + 2.5 * n + (n - 1.0)).max(METER_W)
}
/// How many bars a track's header meter has: its own channels, or the main output's for the
/// master fader (as on its Mix window strip).
pub fn meter_channels(s: &Session, t: &Track) -> usize {
let format = if t.kind == soundcraft_model::TrackKind::Master { s.main_format() } else { t.format };
format.channels().clamp(1, soundcraft_mix::MAX_CHANNELS)
}
/// The width of the track headers (without the optional columns). Like Pro Tools, it widens to fit
/// the widest meter of the tracks shown, so every track's meter starts at the same place.
pub fn track_header_width(s: &Session) -> f32 {
let widest = s.tracks.iter().filter(|t| super::tracks::in_edit_window(s, t)).map(|t| meter_channels(s, t)).max().unwrap_or(1);
HEADER_W + meter_width(widest) - METER_W
}
pub fn header_width(s: &Session, cols: &[Column]) -> f32 {
track_header_width(s) + cols.iter().map(|c| c.3).sum::<f32>()
}
pub const RULER_H: f32 = 17.0;
+6 -5
View File
@@ -1,5 +1,5 @@
use super::input::snap;
use super::layout::{COLUMN_TITLES_H, COLUMNS, Column, HEADER_W, RULER_H, edit_columns, header_width, sample_at, x_of};
use super::layout::{COLUMN_TITLES_H, COLUMNS, Column, RULER_H, edit_columns, sample_at, track_header_width, x_of};
use super::{
Align2, Color32, GridValue, NoteValue, Range, Rect, Samples, Sense, Session, Shape, SoundApp, Stroke, TimeFormat, Tokens, Ui, bold,
format_position, json, pos2, regular, rgb, vec2,
@@ -138,6 +138,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
ui.painter().rect_filled(area, 0.0, t.ruler_bg);
let view = Range::new(sample_at(&s, tl, tl.min.x), sample_at(&s, tl, tl.max.x));
let sr = s.sample_rate;
let head_w = track_header_width(&s);
// The selection is marked in the main timebase ruler, or in the top one when that is hidden.
let main = rulers.iter().position(|id| TimeFormat::from_id(id) == Some(s.edit.main_counter)).unwrap_or(0);
let marker = selection_marker_colour(&t, s.tracks.iter().any(|track| track.mixer.record_arm));
@@ -145,7 +146,7 @@ pub(super) fn draw_rulers(app: &mut SoundApp, ui: &mut Ui, area: Rect, tl: Rect,
for (i, id) in rulers.iter().enumerate() {
let h = ruler_height(id);
let row = Rect::from_min_max(pos2(tl.min.x, y0), pos2(tl.max.x, y0 + h));
let lab = Rect::from_min_max(pos2(area.min.x, y0), pos2(area.min.x + HEADER_W, y0 + h));
let lab = Rect::from_min_max(pos2(area.min.x, y0), pos2(area.min.x + head_w, y0 + h));
y0 += h;
let painter = ui.painter().with_clip_rect(row);
ui.painter().text(
@@ -431,14 +432,14 @@ fn timebase_ruler(painter: &egui::Painter, s: &Session, place: &RulerRow, f: Tim
}
/// Captions over the header columns, boxed in their own row under the rulers.
pub(super) fn column_titles(ui: &Ui, rulers: Rect, cols: &[Column]) {
pub(super) fn column_titles(ui: &Ui, s: &Session, rulers: Rect, cols: &[Column]) {
if cols.is_empty() {
return;
}
let t = Tokens::current();
let line = Stroke::new(1.0, t.border);
let mut x = rulers.min.x + HEADER_W;
let end = rulers.min.x + header_width(cols);
let mut x = rulers.min.x + track_header_width(s);
let end = x + cols.iter().map(|c| c.3).sum::<f32>();
let row = Rect::from_min_max(pos2(x, rulers.max.y - COLUMN_TITLES_H - 3.0), pos2(end, rulers.max.y));
ui.painter().rect_filled(row, 0.0, t.panel_bg2);
ui.painter().hline(rulers.min.x..=end, row.min.y + 0.5, line);
+6 -3
View File
@@ -2,7 +2,7 @@ use super::automation::draw_automation;
use super::clips::{ClipLane, GridLines, clip_cuts, draw_clip, draw_live_take, draw_strip_silence};
use super::header::{header_column, track_header};
use super::input::lane_interaction;
use super::layout::{Column, HEADER_W, LANE_H, STRIP_W, lane_rect, sample_at, x_of};
use super::layout::{Column, LANE_H, STRIP_W, lane_rect, sample_at, x_of};
use super::{
Align2, AutoParam, Range, Rect, Sense, Session, SoundApp, Stroke, Tokens, Track, TrackHeight, TrackId, TrackKind, Ui, json, ops, pos2, regular,
rgb, vec2,
@@ -58,13 +58,16 @@ pub(crate) fn click_track(app: &mut SoundApp, id: TrackId, mods: egui::Modifiers
// ---- track rows ------------------------------------------------------------------------------
/// Draw one track with grid positions shared by all lanes in the current frame.
/// Draw one track: its header, optional columns and lane, with grid positions shared by all lanes
/// in the current frame. The header is the same width for every track (the widest meter shown):
/// what the row leaves of the header column `tl` starts after, once the columns take theirs.
pub(super) fn track_row(app: &mut SoundApp, ui: &mut Ui, id: TrackId, row: Rect, tl: Rect, cols: &[Column], grid: &GridLines) {
let t = Tokens::current();
let s = app.engine.session_arc();
let Some(track) = s.track(id) else { return };
let selected = s.edit.selected_tracks.contains(&id);
let head = Rect::from_min_max(row.min, pos2(row.min.x + HEADER_W, row.max.y));
let head_w = tl.min.x - row.min.x - cols.iter().map(|c| c.3).sum::<f32>();
let head = Rect::from_min_max(row.min, pos2(row.min.x + head_w, row.max.y));
let (head_bg, lane_bg) = crate::theme::track_backgrounds(track.color, selected, app.ui.track_tint);
let mut x = head.max.x;
for &(col, _, _, w) in cols {
+196 -20
View File
@@ -1,10 +1,13 @@
//! Fonts: egui's bundled defaults, plus the operating system's own UI fonts loaded at runtime when
//! present (never redistributed). A "bold" family is always defined so the UI can use it.
//! present (never redistributed). The web build, which reaches no operating-system fonts, bundles a
//! small Open Font License subset of Noto Sans SC instead (see `assets/fonts/` and
//! `ATTRIBUTION.md`). A "bold" family is always defined so the UI can use it.
use egui::{FontData, FontDefinitions, FontFamily};
use std::sync::Arc;
/// (path, ttc index) candidates for regular and bold UI text, by platform.
#[cfg(not(target_arch = "wasm32"))]
const REGULAR: &[(&str, u32)] = &[
("/System/Library/Fonts/HelveticaNeue.ttc", 0),
("/System/Library/Fonts/Helvetica.ttc", 0),
@@ -17,6 +20,7 @@ const REGULAR: &[(&str, u32)] = &[
("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", 0),
("/usr/share/fonts/liberation-sans-fonts/LiberationSans-Regular.ttf", 0),
];
#[cfg(not(target_arch = "wasm32"))]
const BOLD: &[(&str, u32)] = &[
("/System/Library/Fonts/HelveticaNeue.ttc", 1),
("/System/Library/Fonts/Helvetica.ttc", 1),
@@ -31,6 +35,7 @@ const BOLD: &[(&str, u32)] = &[
];
/// Hangul fallback, appended after every family so Korean session, track and clip names draw
/// whatever the interface language. The Noto Sans CJK collection's face 1 is its Korean face.
#[cfg(not(target_arch = "wasm32"))]
const HANGUL: &[(&str, u32)] = &[
("/System/Library/Fonts/AppleSDGothicNeo.ttc", 0),
("/System/Library/Fonts/Supplemental/AppleGothic.ttf", 0),
@@ -42,9 +47,40 @@ const HANGUL: &[(&str, u32)] = &[
("/usr/share/fonts/truetype/nanum/NanumGothic.ttf", 0),
("/usr/share/fonts/naver-nanum/NanumGothic.ttf", 0),
];
/// Han fallback (Simplified Chinese first), placed before [`HANGUL`] for every interface language
/// except Korean, so a Chinese interface and Chinese session, track and clip names draw in Chinese
/// shapes instead of boxes. On Linux the first resolvable CJK face is often Noto Sans CJK's Korean
/// face, whose Han glyphs are Korean-styled; the first face with a glyph wins, so Han must come
/// first. Face 2 of the Noto Sans CJK collection is its Simplified Chinese face (face 0 is
/// Japanese, 1 Korean), and `Source Han Sans SC` / `Noto Sans CJK SC` ship as single-face files.
#[cfg(not(target_arch = "wasm32"))]
const HAN: &[(&str, u32)] = &[
("/System/Library/Fonts/PingFang.ttc", 0),
("/System/Library/Fonts/Supplemental/Songti.ttc", 0),
("/System/Library/Fonts/STHeiti Light.ttc", 0),
("C:\\Windows\\Fonts\\msyh.ttc", 0),
("C:\\Windows\\Fonts\\msyh.ttf", 0),
("C:\\Windows\\Fonts\\simhei.ttf", 0),
("/usr/share/fonts/opentype/source-han-cjk/SourceHanSansSC-Regular.otf", 0),
("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2),
("/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", 2),
("/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc", 2),
("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", 0),
("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0),
("/usr/share/fonts/wqy-microhei/wqy-microhei.ttc", 0),
("/usr/share/fonts/truetype/arphic/uming.ttc", 0),
];
/// Font files larger than this are skipped: egui keeps the whole file in memory.
#[cfg(not(target_arch = "wasm32"))]
const MAX_FONT_BYTES: u64 = 64 << 20;
/// The Han-capable TrueType font bundled for the web build only: egui's default fonts carry no Han
/// glyphs and a browser cannot reach the operating system's fonts, so a Chinese interface would
/// draw boxes. It is a Noto Sans SC (OFL-1.1) subset at weight 400 covering a superset of the UI
/// glyph set; regenerate it with `docs/i18n/tools/subset_web_font.py`. See `assets/fonts/OFL.txt`
/// and `ATTRIBUTION.md`. Native builds never embed it: the include is compiled out of them
/// (`test` keeps it available to the glyph-coverage tests).
#[cfg(any(target_arch = "wasm32", test))]
const BUNDLED_HAN: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/NotoSansSC-SoundCraftSubset.ttf"));
/// Asks fontconfig for the desktop's font matching `pattern`. Only TrueType/OpenType results are
/// used: egui cannot read Type 1 or bitmap fonts, which `fc-match` may return on minimal systems.
@@ -103,34 +139,79 @@ fn load(cands: &[(&str, u32)], pattern: &str, lang: Option<&str>, system_fonts:
None
}
/// The web build has no operating-system fonts: the bundled subset is the CJK fallback.
#[cfg(target_arch = "wasm32")]
fn load(_: &[(&str, u32)], _: &str, _: Option<&str>, _: bool) -> Option<FontData> {
None
fn bundled_han() -> FontData {
FontData::from_static(BUNDLED_HAN)
}
/// The font set: the bundled faces, plus the system ones when `system_fonts` is true.
/// Appends `name` as the lowest-priority fallback of every family. Only appends, so the order the
/// faces are added in is the order glyphs are looked up in.
fn add_fallback(fonts: &mut FontDefinitions, name: &'static str, font: FontData) {
fonts.font_data.insert(name.into(), Arc::new(font));
for family in fonts.families.values_mut() {
family.push(name.into());
}
}
/// Should a Chinese-shaped Han face claim the Han glyphs before the Korean face? The first face
/// with a glyph wins, so a Chinese interface must come first (on Linux fontconfig often resolves
/// Noto Sans CJK's Korean face, whose Han glyphs are Korean-styled). Every interface language
/// except Korean orders Han first; Korean reverses the two, so Hangul and Hanja draw from the
/// Korean face. A future `zh-Hant` (Traditional Chinese) or `ja` (Japanese) is expected to keep
/// Han first as well; only a language-suitable Han face would change (the [`HAN`] list is
/// Simplified-first today).
#[cfg(not(target_arch = "wasm32"))]
fn han_before_hangul(language: &str) -> bool {
language.split(['-', '_']).next() != Some("ko")
}
/// The font set: egui's bundled defaults, the operating system's faces where present and when
/// `system_fonts` is true, and (web only) the bundled Han face as the last fallback of every
/// family. The interface language decides the order of the two CJK fallbacks.
pub fn definitions(system_fonts: bool) -> FontDefinitions {
let mut fonts = FontDefinitions::default();
let base: Vec<String> = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
#[cfg(not(target_arch = "wasm32"))]
let mut bold_family = base.clone();
if let Some(reg) = load(REGULAR, "sans-serif", None, system_fonts) {
fonts.font_data.insert("system-regular".into(), Arc::new(reg));
if let Some(f) = fonts.families.get_mut(&FontFamily::Proportional) {
f.insert(0, "system-regular".into());
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(reg) = load(REGULAR, "sans-serif", None, system_fonts) {
fonts.font_data.insert("system-regular".into(), Arc::new(reg));
if let Some(f) = fonts.families.get_mut(&FontFamily::Proportional) {
f.insert(0, "system-regular".into());
}
}
if let Some(b) = load(BOLD, "sans-serif:style=Bold", None, system_fonts) {
fonts.font_data.insert("system-bold".into(), Arc::new(b));
bold_family.insert(0, "system-bold".into());
} else if fonts.font_data.contains_key("system-regular") {
bold_family.insert(0, "system-regular".into());
}
fonts.families.insert(FontFamily::Name("bold".into()), bold_family);
// The first face with a glyph wins, so the interface language decides whether a Han or a
// Korean face claims the Han glyphs a Chinese interface draws (see `han_before_hangul`).
let language = crate::localization::current_language().id();
let hangul = load(HANGUL, "sans-serif:lang=ko", Some("ko"), system_fonts);
let han = load(HAN, "sans-serif:lang=zh-cn", Some("zh-cn"), system_fonts);
let ordered = if han_before_hangul(language) {
[("system-han", han), ("system-hangul", hangul)]
} else {
[("system-hangul", hangul), ("system-han", han)]
};
for (name, font) in ordered {
if let Some(font) = font {
add_fallback(&mut fonts, name, font);
}
}
}
if let Some(b) = load(BOLD, "sans-serif:style=Bold", None, system_fonts) {
fonts.font_data.insert("system-bold".into(), Arc::new(b));
bold_family.insert(0, "system-bold".into());
} else if fonts.font_data.contains_key("system-regular") {
bold_family.insert(0, "system-regular".into());
}
fonts.families.insert(FontFamily::Name("bold".into()), bold_family);
if let Some(h) = load(HANGUL, "sans-serif:lang=ko", Some("ko"), system_fonts) {
fonts.font_data.insert("system-hangul".into(), Arc::new(h));
for family in fonts.families.values_mut() {
family.push("system-hangul".into());
}
#[cfg(target_arch = "wasm32")]
{
// No system fonts in the browser: the bundled Han face keeps a Chinese interface, and
// Chinese session, track and clip names, readable instead of drawing boxes.
let _ = system_fonts;
fonts.families.insert(FontFamily::Name("bold".into()), base);
add_fallback(&mut fonts, "web-han", bundled_han());
}
fonts
}
@@ -226,4 +307,99 @@ mod tests {
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "가한국어세션")), "{family:?} has no Hangul");
}
}
/// The interface language orders the two CJK fallbacks: a Chinese interface draws Han glyphs
/// from the Han face first, Korean draws them from the Korean face.
#[test]
fn cjk_fallback_order_follows_the_interface_language() {
assert!(han_before_hangul("zh-Hans"));
assert!(han_before_hangul("en"));
// A future Traditional Chinese or Japanese catalog keeps Han first; only the Han face
// itself would become Traditional Chinese or Japanese.
assert!(han_before_hangul("zh-Hant"));
assert!(han_before_hangul("ja"));
assert!(!han_before_hangul("ko"));
assert!(!han_before_hangul("ko-kr"));
}
/// Chinese names draw in every family, not as boxes; skipped when the system has no Han font.
#[test]
fn every_family_draws_han_with_a_system_han_font() {
let defs = definitions(true);
if !defs.font_data.contains_key("system-han") {
eprintln!("skipping: no Han system font");
return;
}
let families: Vec<FontFamily> = defs.families.keys().cloned().collect();
let ctx = egui::Context::default();
ctx.set_fonts(defs);
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
output.textures_delta.clear();
for family in families {
let font = egui::FontId::new(13.0, family.clone());
assert!(ctx.fonts_mut(|f| f.has_glyphs(&font, "轨道片段混音")), "{family:?} has no Han");
}
}
/// Under a Chinese interface every family that resolved both faces puts Han before Hangul, so
/// Chinese text never draws in Korean-styled shapes.
#[test]
fn chinese_interface_puts_han_before_hangul_in_every_family() {
let _language = crate::localization::enter(crate::localization::Language::SimplifiedChinese);
let defs = definitions(true);
let mut compared = 0;
for (family, family_fonts) in &defs.families {
let han = family_fonts.iter().position(|font| font == "system-han");
let hangul = family_fonts.iter().position(|font| font == "system-hangul");
if let (Some(han), Some(hangul)) = (han, hangul) {
assert!(han < hangul, "{family:?} puts Hangul before Han: {family_fonts:?}");
compared += 1;
}
}
if compared == 0 {
eprintln!("skipping: no system Han and Hangul fonts resolved");
}
}
/// The web fallback chain (egui defaults + the bundled face) draws the entire zh-Hans catalog in
/// every family: the property that keeps the browser build free of boxes.
#[test]
fn bundled_web_font_draws_the_zh_hans_catalog_in_every_family() {
let Some(catalog) = zh_hans_catalog() else { return };
let mut defs = definitions(false);
add_fallback(&mut defs, "web-han", FontData::from_static(BUNDLED_HAN));
let mut sample: Vec<char> = catalog.chars().filter(|c| !['\t', '\r', '\n'].contains(c)).collect();
sample.sort_unstable();
sample.dedup();
let sample: String = sample.into_iter().collect();
let families: Vec<FontFamily> = defs.families.keys().cloned().collect();
let ctx = egui::Context::default();
ctx.set_fonts(defs);
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
output.textures_delta.clear();
for family in families {
let font = egui::FontId::new(13.0, family.clone());
let missing: Vec<char> = sample.chars().filter(|c| !ctx.fonts_mut(|fonts| fonts.has_glyphs(&font, &c.to_string()))).collect();
assert!(missing.is_empty(), "{family:?} cannot draw {missing:?} of the zh-Hans catalog even with the bundled web font");
}
}
/// The asset must not silently grow into a full CJK font, which would bloat the web download.
#[test]
fn bundled_web_font_stays_within_its_size_budget() {
const BUDGET: usize = 2 << 20; // 2 MiB
assert!(BUNDLED_HAN.len() <= BUDGET, "the bundled web font is {} bytes; its budget is {BUDGET}", BUNDLED_HAN.len());
}
/// The source of the zh-Hans catalog, or `None` (skip) when it is not checked out.
fn zh_hans_catalog() -> Option<String> {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/i18n/zh-hans.tsv");
match std::fs::read_to_string(path) {
Ok(catalog) => Some(catalog),
Err(err) => {
eprintln!("skipping: cannot read {path}: {err}");
None
}
}
}
}
@@ -0,0 +1,22 @@
SoundCraft UI translations — license and provenance
====================================================
`crates/ui-egui/src/i18n/zh-hans.tsv` holds SoundCraft's own Simplified Chinese translation of the
English source strings in the code. `crates/ui-egui/locales/zh-Hans/mod.rs` is generated from it by
`docs/i18n/tools/gen_zh_hans_locale.py`; edit the TSV, never the module.
License: MIT OR Apache-2.0, the same terms as the SoundCraft code (see LICENSE-MIT and
LICENSE-APACHE in the repository root). The translations are bundled only in the SoundCraft UI; the
English source strings in the code remain the canonical text.
Provenance: the rows are original wording written for SoundCraft. No translated string, glossary or
translation memory from another product was copied. Wording decisions and their reasoning are
recorded in `docs/i18n/glossary.md`, so a reviewer can challenge a term without leaving the
repository.
Review status: AI-authored, not yet read by a native-speaking audio engineer.
Rules when editing: keep the format documented at the top of the TSV, keep every `{name}` and `{}`
placeholder (and its format spec) exactly, keep a trailing `…` in menu items, and run
`python3 docs/i18n/tools/gen_zh_hans_locale.py` followed by
`cargo test -p soundcraft-ui-egui --lib`.
File diff suppressed because it is too large Load Diff
+20 -4
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,
@@ -268,18 +271,29 @@ pub fn fit_window_to_screen(ctx: &egui::Context) {
}
}
/// Ballistic meter display state per strip.
/// Ballistic meter display state per strip, one level and peak hold per channel. Channels 0 and 1
/// are the stereo pair (a mono strip repeats channel 0 in 1); a surround or immersive strip fills
/// as many as it has, up to [`soundcraft_mix::MAX_CHANNELS`].
#[derive(Debug, Clone, Copy, Default)]
pub struct MeterDisplay {
pub level: [f32; 2],
pub hold: [f32; 2],
pub hold_age: f32,
pub level: [f32; soundcraft_mix::MAX_CHANNELS],
pub hold: [f32; soundcraft_mix::MAX_CHANNELS],
/// Seconds since each channel's peak hold was last set.
pub hold_age: [f32; soundcraft_mix::MAX_CHANNELS],
pub clip: bool,
pub gr: f32,
/// [`soundcraft_mix::PluginFailures::count`] as last seen.
pub plugin_failures: u32,
}
impl MeterDisplay {
/// Whether any channel still shows a level or a peak hold, so the meter keeps falling (or its
/// hold has yet to expire) and needs repainting.
pub fn is_moving(&self) -> bool {
self.level.iter().chain(&self.hold).any(|v| *v > 0.0001)
}
}
/// An in-progress mouse gesture in the Edit window.
#[derive(Debug, Clone)]
pub enum Gesture {
@@ -481,6 +495,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.
+114 -23
View File
@@ -1,7 +1,13 @@
//! Language selection and source-language fallback for UI strings.
#[path = "../locales/es/mod.rs"]
mod es;
#[path = "../locales/fr/mod.rs"]
mod fr;
#[path = "../locales/pt-BR/mod.rs"]
mod pt_br;
#[path = "../locales/zh-Hans/mod.rs"]
mod zh_hans;
use std::cell::Cell;
@@ -17,17 +23,26 @@ pub enum Language {
English,
#[serde(rename = "pt-BR")]
PortugueseBrazil,
#[serde(rename = "fr")]
French,
#[serde(rename = "es")]
Spanish,
#[serde(rename = "zh-Hans")]
SimplifiedChinese,
}
impl Language {
/// All supported languages, in the order they are shown in the language menu.
pub const ALL: [Self; 2] = [Self::English, Self::PortugueseBrazil];
pub const ALL: [Self; 5] = [Self::English, Self::PortugueseBrazil, Self::French, Self::Spanish, Self::SimplifiedChinese];
/// Stable language tag used in preferences and control commands.
pub const fn id(self) -> &'static str {
match self {
Self::English => "en",
Self::PortugueseBrazil => "pt-BR",
Self::French => "fr",
Self::Spanish => "es",
Self::SimplifiedChinese => "zh-Hans",
}
}
@@ -36,6 +51,9 @@ impl Language {
match self {
Self::English => "English",
Self::PortugueseBrazil => "Portuguese (Brazil)",
Self::French => "French",
Self::Spanish => "Spanish",
Self::SimplifiedChinese => "Simplified Chinese",
}
}
@@ -47,7 +65,8 @@ impl Language {
pub fn localize_decimal(self, number: &str) -> String {
match self {
Self::English => number.to_owned(),
Self::PortugueseBrazil => number.replace('.', ","),
Self::PortugueseBrazil | Self::French | Self::Spanish => number.replace('.', ","),
Self::SimplifiedChinese => number.to_owned(),
}
}
@@ -56,6 +75,9 @@ impl Language {
match self {
Self::English => source,
Self::PortugueseBrazil => pt_br::translate(source).unwrap_or(source),
Self::French => fr::translate(source).unwrap_or(source),
Self::Spanish => es::translate(source).unwrap_or(source),
Self::SimplifiedChinese => zh_hans::translate(source).unwrap_or(source),
}
}
}
@@ -89,6 +111,9 @@ fn error_text_in(language: Language, message: &str, depth: usize) -> String {
let templates: &[(&str, &str)] = match language {
Language::English => &[],
Language::PortugueseBrazil => pt_br::ERROR_TEMPLATES,
Language::French => fr::ERROR_TEMPLATES,
Language::Spanish => es::ERROR_TEMPLATES,
Language::SimplifiedChinese => zh_hans::ERROR_TEMPLATES,
};
let mut best: Option<(usize, &str, Vec<(String, String)>)> = None;
for (template, translation) in templates {
@@ -354,14 +379,40 @@ mod tests {
assert_eq!(decoded, language);
}
assert_eq!(Language::parse(" PT-br "), Some(Language::PortugueseBrazil));
assert_eq!(Language::parse("fr"), None);
assert_eq!(Language::parse(" FR "), Some(Language::French));
assert_eq!(Language::parse("de"), None);
assert_eq!(Language::parse(" ZH-hans "), Some(Language::SimplifiedChinese));
}
#[test]
fn language_translations_fall_back_to_the_english_source() {
assert_ne!(Language::PortugueseBrazil.text("Appearance"), "Appearance");
assert_eq!(Language::PortugueseBrazil.text("A source string with no catalog entry"), "A source string with no catalog entry");
assert_ne!(Language::SimplifiedChinese.text("Appearance"), "Appearance");
assert_eq!(Language::English.text("Appearance"), "Appearance");
for language in [Language::French, Language::Spanish] {
assert_ne!(language.text("Appearance"), "Appearance", "{language:?}");
assert_eq!(language.text("A source string with no catalog entry"), "A source string with no catalog entry");
}
}
#[test]
fn simplified_chinese_translates_the_language_menu() {
// `Language::native_name` is English source text; the menu draws it through the catalog, so
// a Chinese interface must name every language it offers in Chinese.
for language in Language::ALL {
assert_ne!(Language::SimplifiedChinese.text(language.native_name()), language.native_name(), "{language:?}");
}
assert_eq!(Language::SimplifiedChinese.text("Simplified Chinese"), "简体中文");
}
#[test]
fn simplified_chinese_catalog_covers_every_menu_label() {
for path in include_str!("../../engine/catalog/menus.txt").lines() {
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
assert!(super::zh_hans::translate(label).is_some(), "missing zh-Hans menu label: {label}");
}
}
}
#[test]
@@ -388,6 +439,23 @@ mod tests {
}
}
#[test]
fn room_tone_menu_labels_are_translated() {
for label in ["Room Tone", "Set Room Tone", "Fill Gaps with Room Tone", "Clear Room Tone"] {
let translated = super::pt_br::translate(label).expect("room tone menu translation");
assert_ne!(translated, label);
}
}
#[test]
fn spanish_catalog_covers_every_menu_label() {
for path in include_str!("../../engine/catalog/menus.txt").lines() {
for label in path.split(" > ").map(str::trim).filter(|label| !label.is_empty()) {
assert!(super::es::translate(label).is_some(), "missing es menu label: {label}");
}
}
}
#[test]
fn engine_errors_are_translated_with_their_values() {
assert_eq!(error_text("select a clip"), "select a clip");
@@ -460,9 +528,17 @@ mod tests {
None
}
/// Every `"source" => "translation"` pair of the catalog, read from its source file.
fn catalog_entries() -> Vec<(String, String)> {
let text = include_str!("../locales/pt-BR/mod.rs");
type Lookup = fn(&str) -> Option<&'static str>;
/// Every catalog: its tag, source file and lookup.
const CATALOGS: [(&str, &str, Lookup); 3] = [
("pt-BR", include_str!("../locales/pt-BR/mod.rs"), super::pt_br::translate),
("fr", include_str!("../locales/fr/mod.rs"), super::fr::translate),
("es", include_str!("../locales/es/mod.rs"), super::es::translate),
];
/// Every `"source" => "translation"` pair of a catalog, read from its source file.
fn catalog_entries(text: &str) -> Vec<(String, String)> {
let mut lines = text.lines().map(str::trim);
let mut entries = Vec::new();
while let Some(line) = lines.next() {
@@ -495,20 +571,24 @@ mod tests {
#[test]
fn catalog_entries_are_parsed_and_unique() {
let entries = catalog_entries();
assert!(entries.len() > 1000, "parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "duplicate catalog keys");
for (tag, text, _) in CATALOGS {
let entries = catalog_entries(text);
assert!(entries.len() > 1000, "{tag}: parsed only {} catalog entries", entries.len());
let mut keys: Vec<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
keys.sort_unstable();
let before = keys.len();
keys.dedup();
assert_eq!(before, keys.len(), "{tag}: duplicate catalog keys");
}
}
#[test]
fn catalog_translations_keep_the_english_placeholders() {
for (source, translation) in catalog_entries() {
assert_eq!(placeholders(&source), placeholders(&translation), "placeholders differ for {source:?}");
assert_eq!(super::pt_br::translate(&source), Some(translation.as_str()), "lookup differs for {source:?}");
for (tag, text, translate) in CATALOGS {
for (source, translation) in catalog_entries(text) {
assert_eq!(placeholders(&source), placeholders(&translation), "{tag}: placeholders differ for {source:?}");
assert_eq!(translate(&source), Some(translation.as_str()), "{tag}: lookup differs for {source:?}");
}
}
}
@@ -522,21 +602,22 @@ mod tests {
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>) {
/// Every string passed to `text` / `localized_format!` in this crate must have an entry in
/// `catalog`; `locale` names it in the failure.
fn assert_catalog_covers_the_source(catalog: fn(&str) -> Option<&'static str>, locale: &str) {
fn visit(dir: &std::path::Path, missing: &mut Vec<String>, catalog: fn(&str) -> Option<&'static str>) {
let Ok(read) = std::fs::read_dir(dir) else { return };
for entry in read.flatten() {
let path = entry.path();
if path.is_dir() {
visit(&path, missing);
visit(&path, missing, catalog);
} else if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("localization.rs") {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
for marker in ["localization::text(\"", "localized_format!(\""] {
for (at, _) in text.match_indices(marker) {
let start = at + marker.len() - 1;
if let Some((source, _)) = literal(&text[start..])
&& super::pt_br::translate(&source).is_none()
&& catalog(&source).is_none()
{
missing.push(format!("{}: {source:?}", path.display()));
}
@@ -546,7 +627,17 @@ mod tests {
}
}
let mut missing = Vec::new();
visit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut missing);
assert!(missing.is_empty(), "strings without a pt-BR entry:\n{}", missing.join("\n"));
visit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut missing, catalog);
assert!(missing.is_empty(), "strings without a {locale} entry:\n{}", missing.join("\n"));
}
#[test]
fn every_localized_source_string_has_a_catalog_entry() {
assert_catalog_covers_the_source(super::pt_br::translate, "pt-BR");
}
#[test]
fn every_localized_source_string_has_a_zh_hans_entry() {
assert_catalog_covers_the_source(super::zh_hans::translate, "zh-Hans");
}
}
+67
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.
@@ -157,6 +158,7 @@ pub const AUDIOSUITE: &[(&str, &str)] = &[
/// Commands that open a dialog when invoked from a menu (programmatic calls never do).
const DIALOG_COMMANDS: &[&str] = &[
"clip.clear",
"clip.unloop",
"track.new",
"file.bounce_mix",
"session.new",
@@ -254,6 +256,14 @@ pub fn tree() -> Vec<MenuNode> {
let at = clip.children.iter().position(|n| n.path == "Clip > Identify Sync Point").map_or(clip.children.len(), |i| i + 1);
clip.children.insert(at, MenuNode { label: "Remove Sync Point".into(), path: "Clip > Remove Sync Point".into(), children: Vec::new() });
}
// Not in the incumbent catalog: room tone fills gaps left by edits (and by Strip Silence) with
// recorded silence, so it sits right under Strip Silence.
if let Some(edit) = roots.iter_mut().find(|n| n.path == "Edit") {
let at = edit.children.iter().position(|n| n.path == "Edit > Strip Silence").map_or(edit.children.len(), |i| i + 1);
let leaf = |label: &str| MenuNode { label: label.into(), path: format!("Edit > Room Tone > {label}"), children: Vec::new() };
let children = vec![leaf("Set Room Tone"), leaf("Fill Gaps with Room Tone"), leaf("Clear Room Tone")];
edit.children.insert(at, MenuNode { label: "Room Tone".into(), path: "Edit > Room Tone".into(), children });
}
// Not in the incumbent catalog, but the only UI path to an empty MIDI clip (#282).
// It creates a clip rather than acting on the selected ones, so it leads the Clip menu.
insert_path(&mut roots, "Clip > New MIDI Clip");
@@ -849,6 +859,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()) {
@@ -953,6 +977,49 @@ 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()
}
+7 -29
View File
@@ -9,7 +9,6 @@ use crate::widgets::{
use egui::{Align2, Color32, CornerRadius, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use serde_json::json;
use soundcraft_model::{ChannelFormat, Route, SurroundPan, Track, TrackId, TrackKind};
use soundcraft_playback::MeterSnapshot;
mod output;
mod plugin_menu;
@@ -62,9 +61,6 @@ pub fn separate_closed(app: &mut SoundApp) {
/// New Tracks when the space past the last strip is double-clicked.
pub(crate) fn content(app: &mut SoundApp, ui: &mut Ui) {
let ids: Vec<TrackId> = app.engine.session().tracks.iter().filter(|x| !x.hidden && x.kind != TrackKind::Video).map(|x| x.id).collect();
// Per-channel peaks for multichannel meters, from the snapshot `logic` takes from the player
// (taking them here too would split each period's peaks between two readers).
let snap = (app.player.is_some() && app.meters_live()).then(|| app.meter_snapshot.clone());
// Taken for this frame only: a strip that isn't drawn (hidden track) must not scroll the Mix
// whenever it comes back. A request made during this frame (the strip's menu) waits for the next.
let scroll_to = app.mix_scroll_into_view.take();
@@ -72,7 +68,7 @@ pub(crate) fn content(app: &mut SoundApp, ui: &mut Ui) {
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = 1.0;
for id in ids {
strip(app, ui, id, snap.as_ref(), scroll_to == Some(id));
strip(app, ui, id, scroll_to == Some(id));
}
let rest = Rect::from_min_max(pos2(ui.cursor().min.x, ui.clip_rect().min.y), ui.clip_rect().max);
if rest.width() > 4.0 && ui.interact(rest, ui.scope_id().with("past_strips"), Sense::click()).double_clicked() {
@@ -112,24 +108,6 @@ fn panner_speakers(fmt: ChannelFormat) -> Vec<PannerSpeaker> {
.collect()
}
/// Ballistic per-channel meter levels for multichannel strips, kept in egui memory.
fn channel_levels(ui: &Ui, key: (&str, u64), peaks: &[f32], n: usize) -> Vec<f32> {
let id = egui::Id::unique(key);
let dt = ui.input(|i| i.stable_dt).clamp(0.0, 0.25);
let fall = 10f32.powf(-26.0 * dt / 20.0);
let mut lv: Vec<f32> = ui.data(|d| d.get_temp(id)).unwrap_or_default();
lv.resize(n, 0.0);
for (i, l) in lv.iter_mut().enumerate() {
let p = peaks.get(i).copied().filter(|x| x.is_finite()).unwrap_or(0.0);
*l = if p >= *l { p } else { (*l * fall).max(p) };
if *l < 1e-5 {
*l = 0.0;
}
}
ui.data_mut(|d| d.insert_temp(id, lv.clone()));
lv
}
/// Pro Tools' names for sections in narrow strips, and in any strip too narrow for the full ones.
fn short_label(text: &str) -> &str {
match text {
@@ -186,7 +164,7 @@ impl StripCtx<'_> {
}
}
fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapshot>, scroll_here: bool) {
fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, scroll_here: bool) {
let t = Tokens::current();
let session = app.engine.session_arc();
let Some(track) = session.track(id) else { return };
@@ -222,7 +200,7 @@ fn strip(app: &mut SoundApp, ui: &mut Ui, id: TrackId, snap: Option<&MeterSnapsh
y = group_selector(app, ui, &cx, y);
y = pan_section(app, ui, &cx, y);
y = toggle_rows(app, ui, &cx, y);
fader_and_meter(app, ui, &cx, y, snap);
fader_and_meter(app, ui, &cx, y);
name_and_readout(app, ui, &cx);
}
@@ -604,7 +582,7 @@ fn toggle_rows(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, mut y: f32) -
}
/// The fader and its meter.
fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32, snap: Option<&MeterSnapshot>) {
fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32) {
let StripCtx { track, id, narrow, x0, inner_w, r, .. } = *cx;
let t = Tokens::current();
// Fader + meter.
@@ -626,10 +604,10 @@ fn fader_and_meter(app: &mut SoundApp, ui: &mut Ui, cx: &StripCtx<'_>, y: f32, s
let chans = if track.kind == TrackKind::Master { 2 } else { track.channels().min(2) };
if all_chans > 2 {
// One bar per channel, labelled (L R C LFE …).
let peaks = snap.and_then(|s| s.tracks.get(&id)).map(|m| m.peaks.as_slice()).unwrap_or(&[]);
let lv = channel_levels(ui, ("mc_meter", id.0), peaks, all_chans);
let labels: Vec<String> = (0..all_chans).map(|c| strip_fmt.channel_label(c)).collect();
multi_meter(ui, mr, &lv, &labels, md.clip);
let level = md.level.get(..all_chans).unwrap_or_default();
let hold = md.hold.get(..all_chans).unwrap_or_default();
multi_meter(ui, mr, level, hold, &labels, md.clip);
} else if chans >= 2 {
let mw = mr.width() / 2.0 - 1.0;
meter(ui, Rect::from_min_size(mr.min, vec2(mw, mr.height())), md.level[0], md.hold[0], md.clip);

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