Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) Instrument cards get an on/off switch (#148) (#151)

Chris Laupamaea78afc81e7c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f901f19f..0e4ca959 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,14 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **An on/off switch on instrument cards** (nota-daw/nota#148): every instrument in the
+ Devices panel (built-in synths and samplers, Instrument and Drum Racks, hosted plug-ins)
+ now has the same switch as the effects. Off silences the instrument without muting the
+ track or deleting anything: it fades out over a few milliseconds and then uses no CPU,
+ while the MIDI effects before it and the audio effects after it keep their settings (a
+ reverb tail rings out). Back on, it plays from the next note. The switch is saved with
+ the project and kept when the track is duplicated; the AI assistant reaches it through
+ `set_device_bypass` with device index -1.
- **Double-click the loop brace to turn the loop off and on** (nota-daw/nota#59): in the
arrangement ruler, a double-click on the loop region switches looping off without losing
the region. It stays in the ruler in grey, and another double-click turns it back on. A
diff --git a/FEATURES.md b/FEATURES.md
index fde457fa..38c8b0d3 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -454,7 +454,10 @@ track count and closes with Escape.
Every built-in device uses the same 700×260 shell with a shared header: on/bypass dot,
name, subtitle, preset picker, **A/B comparison** (parameter snapshots), stereo meter,
voice count (on synths), move arrows, delete, and the ⠿ drag handle. All support factory
-and user presets, automation, persistence and cloning.
+and user presets, automation, persistence and cloning. Instrument cards (built-in, racks
+and hosted plug-ins) have the same on/off switch as effects: off silences the instrument
+(after a one-block fade it isn't rendered at all) while the MIDI effects before it and the
+audio effects after it keep running and keep their settings; saved with the project.
### Instruments
- **Nota Synth** — subtractive synthesizer (the basic one): one oscillator
@@ -1089,7 +1092,8 @@ Coverage:
each changed), `save_version` with a note, `switch_version`, `annotate_version` (name, note,
star). Deleting versions stays with the user.
- **Tracks**: add and remove, volume/pan/mute/solo, groups, sends.
-- **Instruments**: add by kind, read and write parameters (by index or by stable id); read /
+- **Instruments**: add by kind, read and write parameters (by index or by stable id), turn
+ on or off (`set_device_bypass` with device index -1; `get_overview` shows it); read /
shape Nota Keys in musical terms (`read_keys`, `set_keys`).
- **Audio effects**: add, remove, reorder, bypass, parameters; load an audio file into a
device (a Nota Chamber impulse response) and read its resource text (IR names).
diff --git a/specs/021-instrument-on-off/plan.md b/specs/021-instrument-on-off/plan.md
new file mode 100644
index 00000000..098b503d
--- /dev/null
+++ b/specs/021-instrument-on-off/plan.md
@@ -0,0 +1,53 @@
+# Implementation Plan: An On/Off Switch for Instruments
+
+**Branch**: `fix/issue-148-lksrgg` | **Date**: 2026-10-17 | **Spec**: [spec.md](spec.md)
+
+## Summary
+
+`Instrument` gains the same relaxed atomic bypass flag `Device` has. The engine's device
+bypass call treats device index −1 as the instrument (as names, parameters and state already
+do). `playEvents`, which drives every instrument render (arrangement, live notes, Session
+slots), checks the flag: on the first block after the switch goes off it renders as usual,
+applies a linear fade to zero, then calls `allNotesOff` and releases held controllers; from
+the next block it returns at once, leaving the zeroed buffer. The MIDI pre-pass and the
+insert chain are untouched. The card shells pass `Bypassable: true` and route the switch to
+index −1; the project stores `instrument.bypassed`; MCP gains the −1 meaning.
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (managed)
+
+**Primary Dependencies**: none new
+
+**Storage**: `project.json` → `tracks[].instrument.bypassed` (optional, default false; no
+format bump — older builds keep it in the DTO's extension data)
+
+**Audio-Thread Impact**: one relaxed atomic load per instrument per block, plus a
+plain `bool` the audio thread alone writes (`Instrument::offSettled`). No locks, no
+allocation. Off saves the instrument's whole render.
+
+**Testing**: smoke test `InstrumentBypassTests` (`--instrument-off`, also in the full run)
+
+## Constitution Check
+
+| Principle | Status |
+|---|---|
+| I. Real-time audio safety | ✅ atomic flag, no alloc / lock; fade then early return |
+| II. Boundary discipline | ✅ existing C ABI call, documented meaning for −1 |
+| III. Licensing hygiene | ✅ new test file has the SPDX header; no dependency |
+| IV. Verification gate | ✅ smoke test |
+| V. One logical change | ✅ #148 only |
+| VI. Docs in sync | ✅ CHANGELOG, FEATURES.md, nota-docs EN + RU |
+| VII. Spec-first | ✅ |
+| VIII. Rules not weakened | ✅ |
+
+## Files
+
+- Engine: `Instrument.h` (flag), `Engine_Render.cpp` (`playEvents`), `Engine_Devices.cpp`
+ (−1 in set/get bypass), `Engine_Tracks.cpp` (duplicate), `Engine.h` + `nota_engine.h`
+ (comments).
+- App: `DeviceChainView.Instruments.cs`, `DeviceChainView.Plugin.cs`,
+ `DeviceChainView.Shell.cs` (switch, tooltip, index −1).
+- Persistence: `ProjectModel.cs` (`InstrumentDto.Bypassed`), `ProjectService.cs`.
+- MCP: `DeviceTools.cs` (description), `ProjectTools.cs` (`InstrumentOff`).
+- Tests: `tests/Nota.SmokeTest/InstrumentBypassTests.cs`, `Program.cs`.
diff --git a/specs/021-instrument-on-off/spec.md b/specs/021-instrument-on-off/spec.md
new file mode 100644
index 00000000..aa26e502
--- /dev/null
+++ b/specs/021-instrument-on-off/spec.md
@@ -0,0 +1,117 @@
+# Feature Specification: An On/Off Switch for Instruments
+
+**Feature Branch**: `fix/issue-148-lksrgg`
+
+**Created**: 2026-10-17
+
+**Status**: Implemented
+
+## Clarifications
+
+### Session 2026-10-17
+
+- Q: What does "off" do to notes that are sounding at the moment the switch is flipped? →
+ A: They fade out over one audio block (a few milliseconds, no click) and are released.
+ Turning the instrument back on does not bring them back; it plays from the next note.
+- Q: Where does the switch live in the engine API? → A: On the existing device bypass
+ call with device index −1, which already means "the instrument" for names, parameters
+ and state. No new C ABI function.
+- Q: Does a replaced instrument (a different synth dropped on the track) inherit the off
+ state? → A: No. A new instrument is a new card and starts on, like a newly added effect.
+ Duplicating the track keeps it.
+- Q: Is the switch an undo step? → A: No, as for the effects' switches (bypass is not in
+ the undo history today; the engine's undo comment lists it as not covered).
+
+**Input**: nota-daw/nota#148 — "Devices panel: an on/off switch for instruments. Quickly
+silence an instrument (e.g. to compare layers or hear the track without it) without muting
+the whole track or deleting it. Instrument cards get the same on/off switch as effects.
+Off = the instrument makes no sound (and ideally uses no CPU); the MIDI effects and audio
+effects after it keep their settings. Instrument shells are `Bypassable: false`
+(`DeviceChainView.Instruments.cs`); the engine needs an instrument bypass."
+
+## Nota Context
+
+**Feature area**:
+
+- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply
+- [x] Managed app (C#, `src/managed/*`)
+- [x] UI (Avalonia) — follow `DESIGN.md`
+- [ ] Plugin hosting (`pluginhost/`)
+- [ ] Build / packaging / CI
+- [ ] Docs only
+
+**Current state**: every audio effect and MIDI effect card has a power switch in its
+header (`SwitchTrack`); instrument cards reserve the same slot but leave it empty
+(`Bypassable: false`). The engine's `Instrument` has no bypass flag, so the only way to
+silence an instrument is to mute the whole track (which also silences returns fed from it
+and the effects' tails) or to delete the instrument.
+
+## User Scenarios & Testing
+
+### User Story 1 - Silence an instrument from its card (Priority: P1)
+
+A producer layering two synths on separate tracks clicks the switch on one synth's card:
+it goes quiet at once, without a click, while the other keeps playing. The card takes the
+inactive look but its knobs stay editable. Clicking again brings it back on the next note.
+
+**Independent Test**: play a held note or a clip, switch the instrument off and on.
+
+**Acceptance Scenarios**:
+
+1. **Given** any instrument card (built-in synth or sampler, Instrument Rack, Drum Rack,
+ hosted plug-in), **Then** its header shows the same on/off switch as an effect card.
+2. **Given** a sounding instrument, **When** it is switched off, **Then** it fades to
+ silence within one block and then outputs exact silence while clips and live notes go on.
+3. **Given** an instrument that is off, **When** it is switched on, **Then** the next note
+ sounds; notes held across the switch do not resume.
+4. **Given** an instrument that is off, **Then** the engine does not render it (no CPU).
+
+### User Story 2 - The rest of the chain is untouched (Priority: P1)
+
+**Acceptance Scenarios**:
+
+1. **Given** audio effects after the instrument, **When** it is switched off, **Then**
+ they keep running (a reverb's tail rings out) and keep their settings and switches.
+2. **Given** MIDI effects before it, **Then** they keep their settings and switches.
+
+### User Story 3 - It stays the way you left it (Priority: P2)
+
+**Acceptance Scenarios**:
+
+1. **Given** an instrument that is off, **When** the project is saved and reopened,
+ **Then** it is still off. A project saved before this feature loads with every
+ instrument on.
+2. **Given** a track whose instrument is off, **When** it is duplicated, **Then** the copy's
+ instrument is off too.
+3. **Given** the AI assistant (MCP), **Then** `set_device_bypass` with device index −1
+ turns the instrument on or off and `get_overview` reports it.
+
+### Edge Cases
+
+- **Frozen track**: the freeze already baked the instrument; the switch affects the live
+ render only, as for an effect's switch.
+- **Session clips**: an instrument that is off is silent for Session slots too.
+- **MIDI routed to another track** (MIDI In): the source track's MIDI is computed before
+ its instrument, so a destination still receives it.
+- **Recording**: notes are still recorded; only the sound is off.
+
+## Requirements
+
+- **FR-001**: Every instrument card in the Devices panel MUST show the on/off switch in the
+ header's power slot, with the same look and the inactive body when off.
+- **FR-002**: Off MUST fade the instrument out over one block, release its voices and held
+ controllers, and then skip rendering it entirely until it is switched on.
+- **FR-003**: The MIDI effects and audio effects of the track MUST keep running and keep
+ their own state and switches.
+- **FR-004**: The state MUST be saved with the project (optional `bypassed` member of the
+ track's `instrument`, no format bump) and kept on track duplication.
+- **FR-005**: The engine API is the device bypass call with device index −1; MCP reaches it
+ through `set_device_bypass` and reports it in `get_overview`.
+- **FR-006**: The switch is set from the message thread and read on the audio thread
+ without locks or allocation.
+
+## Success Criteria
+
+- **SC-001**: After switching off, the instrument's output is exactly zero from the second
+ block on (smoke test).
+- **SC-002**: Save / load, duplicate and an older project behave as in US3 (smoke test).
diff --git a/specs/021-instrument-on-off/tasks.md b/specs/021-instrument-on-off/tasks.md
new file mode 100644
index 00000000..fb397b35
--- /dev/null
+++ b/specs/021-instrument-on-off/tasks.md
@@ -0,0 +1,33 @@
+---
+
+description: "Task list for 021 An On/Off Switch for Instruments"
+---
+
+# Tasks: An On/Off Switch for Instruments
+
+**Input**: [spec.md](spec.md), [plan.md](plan.md)
+
+**Tests**: `tests/Nota.SmokeTest/InstrumentBypassTests.cs`
+
+## Phase 1: Engine
+
+- [x] T001 `Instrument.h`: atomic `bypassed()` / `setBypassed()`, audio-thread `offSettled`
+- [x] T002 `Engine_Render.cpp` `playEvents`: fade the switch-off block, release voices and held controllers, then skip rendering
+- [x] T003 `Engine_Devices.cpp`: device index −1 in `setTrackDeviceBypassed` / `trackDeviceBypassed`; comments in `Engine.h`, `nota_engine.h`
+- [x] T004 `Engine_Tracks.cpp`: a duplicated track keeps the instrument's switch
+
+## Phase 2: App (US1, US2)
+
+- [x] T005 Instrument shells (built-in, racks, hosted plug-in) `Bypassable: true`, read the state from index −1
+- [x] T006 `BuildCardShell`: the switch writes index −1 for an instrument; on/off tooltip
+
+## Phase 3: Persistence and MCP (US3)
+
+- [x] T007 `InstrumentDto.Bypassed`, captured and applied in `ProjectService`
+- [x] T008 MCP: `set_device_bypass` documents −1; `get_overview` reports `InstrumentOff`
+
+## Phase 4: Verification and docs
+
+- [x] T009 Smoke: fade, exact silence, release, next note, reverb tail, switches separate, clip playback, duplicate, save / load, older project, MCP
+- [x] T010 CHANGELOG, FEATURES.md, nota-docs (EN + RU)
+- [x] T011 `scripts/build-linux.sh` green (`CI=true`)
diff --git a/src/managed/Nota.App/DeviceChainView.Instruments.cs b/src/managed/Nota.App/DeviceChainView.Instruments.cs
index 4a497ba2..dfd5a6a6 100644
--- a/src/managed/Nota.App/DeviceChainView.Instruments.cs
+++ b/src/managed/Nota.App/DeviceChainView.Instruments.cs
@@ -29,7 +29,7 @@ public sealed partial class DeviceChainView
double width = strategy.WidthFor(_engine, _trackId);
var spec = new ShellSpec(
Name: _engine.DeviceName(_trackId, -1), Subtitle: strategy.Subtitle, DeviceIndex: -1, Count: 1,
- Bypassed: false, Bypassable: false, CanMove: false, CanDelete: false,
+ Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: false,
PresetKind: kind, IsInstrument: true, Width: width, Kind: ChainKind.Instrument,
VoiceLabel: strategy.VoiceLabel,
Presets: kind == Nota.Application.RhythmModel.Kind ? KitPresets() : kind == Nota.Application.MosaicModel.Kind ? MosaicPresets() : null,
@@ -88,7 +88,7 @@ public sealed partial class DeviceChainView
var body = new RackCardView(NewCardContext()).BuildInstrumentRackBody(out int chains);
var spec = new ShellSpec(
Name: _engine.DeviceName(_trackId, -1), Subtitle: $"Rack · {chains} chain{(chains == 1 ? "" : "s")}", DeviceIndex: -1, Count: 1,
- Bypassed: false, Bypassable: false, CanMove: false, CanDelete: false,
+ Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: false,
PresetKind: 3, IsInstrument: true, Width: 700, Kind: ChainKind.Instrument);
return BuildCardShell(spec, body);
}
@@ -101,7 +101,7 @@ public sealed partial class DeviceChainView
var kits = KitPresets();
var spec = new ShellSpec(
Name: _engine.DeviceName(_trackId, -1), Subtitle: $"Drums · {pads} pad{(pads == 1 ? "" : "s")}", DeviceIndex: -1, Count: 1,
- Bypassed: false, Bypassable: false, CanMove: false, CanDelete: false,
+ Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: false,
PresetKind: 4, IsInstrument: true, Width: 700, Kind: ChainKind.Instrument, Presets: kits);
return BuildCardShell(spec, body);
}
diff --git a/src/managed/Nota.App/DeviceChainView.Plugin.cs b/src/managed/Nota.App/DeviceChainView.Plugin.cs
index 0db24866..afce7c74 100644
--- a/src/managed/Nota.App/DeviceChainView.Plugin.cs
+++ b/src/managed/Nota.App/DeviceChainView.Plugin.cs
@@ -23,7 +23,7 @@ public sealed partial class DeviceChainView
bool effect = k == ChainKind.Effect;
var spec = new ShellSpec(
Name: info.Name, Subtitle: info.Format, DeviceIndex: di, Count: count,
- Bypassed: effect && _engine.DeviceBypassed(_trackId, di), Bypassable: effect,
+ Bypassed: _engine.DeviceBypassed(_trackId, effect ? di : -1), Bypassable: true,
CanMove: effect, CanDelete: effect, PresetKind: -1, IsInstrument: !effect, Width: width, Kind: k,
HeaderExtra: toggle, Compact: state.Mini);
return BuildCardShell(spec, new Border { Padding = new Thickness(NotaSpace.DeviceInset), Child = body });
diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.cs
index 8bcc8a54..b6351cac 100644
--- a/src/managed/Nota.App/DeviceChainView.Shell.cs
+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs
@@ -163,13 +163,15 @@ public sealed partial class DeviceChainView
if (s.Bypassable)
{
var bypass = new SwitchTrack { IsOn = !s.Bypassed, Cursor = new Cursor(StandardCursorType.Hand) };
- ToolTip.SetTip(bypass, s.Bypassed ? "Bypassed — click to enable" : "Active — click to bypass");
+ ToolTip.SetTip(bypass, s.IsInstrument
+ ? (s.Bypassed ? "Off — click to turn the instrument on" : "On — click to turn the instrument off")
+ : (s.Bypassed ? "Bypassed — click to enable" : "Active — click to bypass"));
bypass.PointerPressed += (_, e) =>
{
if (!e.GetCurrentPoint(bypass).Properties.IsLeftButtonPressed) return;
e.Handled = true; // not a drag, not a selection click
if (s.Kind == ChainKind.Midi) _engine.SetMidiEffectBypassed(_trackId, di, !s.Bypassed);
- else _engine.SetDeviceBypassed(_trackId, di, !s.Bypassed);
+ else _engine.SetDeviceBypassed(_trackId, s.IsInstrument ? -1 : di, !s.Bypassed); // -1: the instrument (#148)
Rebuild(); Changed?.Invoke();
};
power.Child = bypass;
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 0ad2948d..f547b1c7 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -259,6 +259,8 @@ public sealed class InstrumentDto
public int SidechainSource { get; set; } = -1;
/// <summary>Nota Rhythm (Kind == 12) per-voice one-shots (only sample-source voices).</summary>
public List<VoiceSampleDto>? VoiceSamples { get; set; }
+ /// <summary>The card's on/off switch is off: the instrument makes no sound (#148).</summary>
+ public bool Bypassed { get; set; }
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 69093869..847cddfa 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -162,6 +162,7 @@ public sealed class ProjectService
// React source (Nota Flux): store as a doc index, resolved on load.
int instScSrc = engine.InstrumentSidechainSource(ti.Id);
instDto.SidechainSource = instScSrc >= 0 && idToIndex.TryGetValue(instScSrc, out var isi) ? isi : -1;
+ instDto.Bypassed = engine.DeviceBypassed(ti.Id, -1);
t.Instrument = instDto;
}
@@ -589,6 +590,8 @@ public sealed class ProjectService
id = engine.AddAudioTrack();
}
+ if (id > 0 && t.Instrument is { Bypassed: true })
+ engine.SetDeviceBypassed(id, -1, true); // the instrument card's switch is off (#148)
if (id > 0 && t.Instrument is { SidechainSource: >= 0 } insc)
instScDeferred.Add((id, insc.SidechainSource)); // wire React source once every track exists
if (id > 0 && t.GroupId >= 0)
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 4eb8744b..b21a7ad7 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -48,7 +48,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "move_device"), Description("Reorder a device within a track's chain.")]
public Task MoveDevice(int trackId, int fromIndex, int toIndex) => Mutate(() => E.MoveDevice(trackId, fromIndex, toIndex));
- [McpServerTool(Name = "set_device_bypass"), Description("Bypass or enable a device.")]
+ [McpServerTool(Name = "set_device_bypass"), Description("Bypass or enable a device. deviceIndex -1 is the track's instrument: bypassed, it makes no sound (its MIDI effects and audio effects keep running).")]
public Task SetDeviceBypass(int trackId, int deviceIndex, bool bypassed) => Mutate(() => E.SetDeviceBypassed(trackId, deviceIndex, bypassed));
[McpServerTool(Name = "get_device_params"), Description("List a device's parameters (index, name, min, max, current value).")]
diff --git a/src/managed/Nota.Mcp/Tools/ProjectTools.cs b/src/managed/Nota.Mcp/Tools/ProjectTools.cs
index 5a528e71..16ed0914 100644
--- a/src/managed/Nota.Mcp/Tools/ProjectTools.cs
+++ b/src/managed/Nota.Mcp/Tools/ProjectTools.cs
@@ -18,12 +18,12 @@ public sealed class ProjectTools(IAudioEngine engine, IEngineDispatch dispatch,
public sealed record DeviceInfo(int Index, int BuiltinKind, string Name, bool Bypassed);
public sealed record MidiFxInfo(int Index, int Kind, string Name, bool Bypassed);
public sealed record TrackInfo(int Id, string Name, string Type, int ColorIndex, bool Muted, bool Soloed,
- float Volume, float Pan, int InstrumentKind, int GroupId, ClipInfo[] Clips, MidiFxInfo[] MidiFx, DeviceInfo[] Devices);
+ float Volume, float Pan, int InstrumentKind, bool InstrumentOff, int GroupId, ClipInfo[] Clips, MidiFxInfo[] MidiFx, DeviceInfo[] Devices);
public sealed record Overview(double Bpm, bool Playing, double PositionBeats, TrackInfo[] Tracks);
[McpServerTool(Name = "get_overview"), Description(
"Full snapshot of the open project: tempo, transport, and every track with its type, mixer state, "
- + "instrument kind, clips (index/start/length/midi), MIDI effects and audio devices. Call this first to see state.")]
+ + "instrument kind (and whether its on/off switch is off), clips (index/start/length/midi), MIDI effects and audio devices. Call this first to see state.")]
public Task<Overview> GetOverview() => Read(() =>
{
int n = E.TrackCount;
@@ -43,7 +43,7 @@ public sealed class ProjectTools(IAudioEngine engine, IEngineDispatch dispatch,
for (int d = 0; d < dc; d++) devs.Add(new DeviceInfo(d, E.TrackDeviceBuiltinKind(ti.Id, d), E.DeviceName(ti.Id, d), E.DeviceBypassed(ti.Id, d)));
tracks.Add(new TrackInfo(ti.Id, E.GetTrackName(ti.Id), TypeName(ti.Type), E.GetTrackColorIndex(ti.Id),
ti.Muted != 0, ti.Soloed != 0, ti.Volume, ti.Pan, ti.IsInstrument ? E.TrackInstrumentKind(ti.Id) : -1,
- ti.GroupId, clips.ToArray(), mfx.ToArray(), devs.ToArray()));
+ ti.IsInstrument && E.DeviceBypassed(ti.Id, -1), ti.GroupId, clips.ToArray(), mfx.ToArray(), devs.ToArray()));
}
return new Overview(E.Bpm, E.IsPlaying, E.PositionBeats, tracks.ToArray());
});
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index edb1c1da..eeacf0e0 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1691,7 +1691,9 @@ NOTA_API NotaResult nota_plugin_set_state(NotaEngine* engine, int32_t track_id,
const uint8_t* data, int32_t size);
/* Device bypass (M3-6, FR-37). When bypassed, the effect is skipped in the
- * render chain (buffer passes through untouched). */
+ * render chain (buffer passes through untouched). device_index -1 is the track's
+ * instrument (#148): switched off, it fades out over one block, releases its voices
+ * and is no longer rendered; its MIDI effects and audio effects keep running. */
NOTA_API NotaResult nota_track_set_device_bypassed(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t bypassed);
NOTA_API int32_t nota_track_device_bypassed(const NotaEngine* engine, int32_t track_id, int32_t device_index);
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 78503a89..90611de3 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -794,6 +794,7 @@ public:
int32_t getPluginState(int32_t trackId, int32_t deviceIndex, uint8_t* out, int32_t cap) const;
bool setPluginState(int32_t trackId, int32_t deviceIndex, const uint8_t* data, int32_t size);
// Device bypass (M3-6). Atomic on the stable Device — no snapshot republish.
+ // deviceIndex -1 is the instrument's on/off switch (#148).
void setTrackDeviceBypassed(int32_t trackId, int32_t deviceIndex, bool bypassed);
bool trackDeviceBypassed(int32_t trackId, int32_t deviceIndex) const;
// Plugin delay compensation (M3-7).
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index 211eb306..6d49a085 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -1053,13 +1053,17 @@ bool Engine::setPluginState(int32_t trackId, int32_t deviceIndex, const uint8_t*
void Engine::setTrackDeviceBypassed(int32_t trackId, int32_t deviceIndex, bool bypassed) {
auto t = findTrackAuthoring(trackId);
- if (!t || deviceIndex < 0 || deviceIndex >= static_cast<int32_t>(t->devices.size())) return;
+ if (!t) return;
+ if (deviceIndex == -1) { if (t->instrument) t->instrument->setBypassed(bypassed); return; } // the instrument (#148)
+ if (deviceIndex < 0 || deviceIndex >= static_cast<int32_t>(t->devices.size())) return;
if (t->devices[deviceIndex]) t->devices[deviceIndex]->setBypassed(bypassed);
}
bool Engine::trackDeviceBypassed(int32_t trackId, int32_t deviceIndex) const {
auto t = findTrackAuthoring(trackId);
- if (!t || deviceIndex < 0 || deviceIndex >= static_cast<int32_t>(t->devices.size())) return false;
+ if (!t) return false;
+ if (deviceIndex == -1) return t->instrument && t->instrument->bypassed();
+ if (deviceIndex < 0 || deviceIndex >= static_cast<int32_t>(t->devices.size())) return false;
return t->devices[deviceIndex] && t->devices[deviceIndex]->bypassed();
}
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index 9ae36853..d4b891ac 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -145,9 +145,17 @@ inline void deliverExpr(Instrument& inst, int32_t pitch, int32_t dim, float valu
// sample offset (notes first at a shared offset, so a note's opening expression lands on it),
// rendering the stretches in between. `live` runs once, before the first sample is rendered —
// after the offset-0 notes, where live input sits — to apply the block's live expression.
+// An instrument switched off (#148) renders its first block off once more, without the block's
+// events, fading what was sounding to silence, then releases every voice and held controller;
+// after that it isn't rendered at all (no CPU) until it is switched back on, so `dst` stays
+// silent. The MIDI before it keeps running.
template <class Live>
void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs, int n,
const ExprEv* xev, int xn, Live&& live) {
+ const bool off = inst.bypassed();
+ if (!off) inst.offSettled = false;
+ else if (inst.offSettled) return;
+ if (off) n = xn = 0; // nothing new starts on the way out
int32_t cursor = 0;
bool liveDone = false;
auto renderTo = [&](int32_t to) {
@@ -173,6 +181,16 @@ void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs,
}
if (!liveDone) { live(); liveDone = true; }
renderTo(frames);
+ if (off) {
+ const float step = frames > 0 ? 1.0f / static_cast<float>(frames) : 1.0f;
+ for (int32_t i = 0; i < frames; ++i) {
+ const float g = 1.0f - static_cast<float>(i + 1) * step;
+ dst[i * 2] *= g; dst[i * 2 + 1] *= g;
+ }
+ inst.allNotesOff();
+ releaseHeldControllers(inst);
+ inst.offSettled = true;
+ }
}
}
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index 86ed5485..472e836d 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -2665,6 +2665,7 @@ std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId) {
nt->name = src.name;
nt->colorIndex = src.colorIndex;
nt->instrument = cloneInstrument(src);
+ if (nt->instrument && src.instrument) nt->instrument->setBypassed(src.instrument->bypassed());
for (auto& m : src.midiEffects) if (auto nm = cloneMidiDevice(*m)) nt->midiEffects.push_back(nm);
for (auto& d : src.devices) if (auto nd = cloneDevice(*d)) nt->devices.push_back(nd);
// Warped clips must not share a stretcher across tracks — rebuild per clip.
diff --git a/src/native/nota.engine/src/Instrument.h b/src/native/nota.engine/src/Instrument.h
index 5721111a..2401e0a9 100644
--- a/src/native/nota.engine/src/Instrument.h
+++ b/src/native/nota.engine/src/Instrument.h
@@ -68,6 +68,15 @@ public:
// Add `frames` of interleaved stereo into `out`. Continues current voices.
virtual void render(float* out, int32_t frames) = 0;
+ // The card's on/off switch (#148). Off = the engine stops rendering the instrument (it
+ // fades out over one block and releases its voices); its settings, the MIDI effects
+ // before it and the audio effects after it are untouched. Atomic: set from the message
+ // thread, read on the audio thread. offSettled is the audio thread's own note that the
+ // fade-out has run.
+ bool bypassed() const { return bypassed_.load(std::memory_order_relaxed); }
+ void setBypassed(bool b) { bypassed_.store(b, std::memory_order_relaxed); }
+ bool offSettled = false;
+
// Musical transport for generative instruments (e.g. Nota Pendulum): the engine
// calls this once per block before render() with the block's start beat,
// samples-per-beat and whether the transport is rolling. Others ignore it.
@@ -161,6 +170,9 @@ public:
// engine from `kind()`; hosted plugins re-instantiate here (fresh DSP instance +
// copied state). Returns nullptr if the engine should handle it. Message thread.
virtual std::shared_ptr<Instrument> clone() const { return nullptr; }
+
+private:
+ std::atomic<bool> bypassed_{false};
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/InstrumentBypassTests.cs b/tests/Nota.SmokeTest/InstrumentBypassTests.cs
new file mode 100644
index 00000000..f8dfefca
--- /dev/null
+++ b/tests/Nota.SmokeTest/InstrumentBypassTests.cs
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The instrument card's on/off switch (#148): device index -1 is the instrument. Off fades the
+// instrument out over one block, releases its voices and then renders exact silence; the audio
+// effects after it keep running (a reverb tail rings out), the MIDI effects before it and the
+// effects' own switches are untouched; back on, it plays the next note. Survives duplicate and
+// save / load; a project without the flag loads with the instrument on. MCP reaches it too.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class InstrumentBypassTests
+{
+ private const int Block = 512;
+
+ private static float[] Render(NotaEngine e, int blocks)
+ {
+ var all = new float[blocks * Block * 2];
+ var b = new float[Block * 2];
+ for (int i = 0; i < blocks; i++) { e.RenderOffline(b, Block); Array.Copy(b, 0, all, i * Block * 2, Block * 2); }
+ return all;
+ }
+ private static double Peak(float[] st, int fromBlock = 0, int toBlock = -1)
+ {
+ int to = toBlock < 0 ? st.Length : toBlock * Block * 2;
+ double p = 0;
+ for (int i = fromBlock * Block * 2; i < to; i++) p = Math.Max(p, Math.Abs(st[i]));
+ return p;
+ }
+
+ // Which tracks' instruments are off, in track order ("1" = off): "101", say.
+ private static string Pattern(NotaEngine e)
+ {
+ var sb = new System.Text.StringBuilder();
+ for (int i = 0; i < e.TrackCount; i++)
+ if (e.TryGetTrackInfo(i, out var ti)) sb.Append(e.DeviceBypassed(ti.Id, -1) ? '1' : '0');
+ return sb.ToString();
+ }
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ // ---- off / on with a held note ----------------------------------------------------
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ yield return (!e.DeviceBypassed(t, -1), "a new instrument is on");
+ e.TrackNoteOn(t, 60, 0.8f);
+ double on = Peak(Render(e, 8), 2);
+ e.SetDeviceBypassed(t, -1, true);
+ yield return (e.DeviceBypassed(t, -1), "the instrument's switch turns off (device index -1)");
+ var off = Render(e, 6);
+ // The first block fades out: it starts near the playing level and ends at zero.
+ double head = 0, tail = Math.Abs(off[(Block - 1) * 2]) + Math.Abs(off[(Block - 1) * 2 + 1]);
+ for (int i = 0; i < 64; i++) head = Math.Max(head, Math.Abs(off[i]));
+ yield return (on > 0.01 && head > on * 0.2 && tail < on * 0.02, $"switching off fades the instrument out over one block (playing {on:F3}, start {head:F3}, end {tail:F5})");
+ yield return (Peak(off, 1) == 0.0, $"once off, the instrument renders exact silence (peak {Peak(off, 1):E1})");
+ e.SetDeviceBypassed(t, -1, false);
+ double held = Peak(Render(e, 4));
+ yield return (held == 0.0, $"back on, the note held across the switch stays released (peak {held:E1})");
+ e.TrackNoteOff(t, 60);
+ e.TrackNoteOn(t, 64, 0.8f);
+ double again = Peak(Render(e, 6), 2);
+ yield return (again > 0.01, $"back on, the next note sounds (peak {again:F3})");
+ e.TrackNoteOff(t, 64);
+ }
+
+ // ---- the effects after it keep running, and keep their own switches ---------------
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ int rv = e.AddBuiltinDevice(t, 2); // Reverb
+ int arp = e.AddMidiEffect(t, 0);
+ e.TrackNoteOn(t, 60, 0.8f);
+ Render(e, 40);
+ e.SetDeviceBypassed(t, -1, true);
+ var off = Render(e, 12);
+ yield return (Peak(off, 4, 12) > 1e-4, $"a reverb after the instrument rings out after it is switched off (peak {Peak(off, 4, 12):E1})");
+ yield return (rv >= 0 && !e.DeviceBypassed(t, rv) && (arp < 0 || !e.MidiEffectBypassed(t, arp)),
+ "switching the instrument off leaves the effects' own switches alone");
+ e.SetDeviceBypassed(t, rv, true);
+ yield return (e.DeviceBypassed(t, -1) && e.DeviceBypassed(t, rv), "an effect's switch and the instrument's are separate");
+ e.TrackNoteOff(t, 60);
+ }
+
+ // ---- clip playback ---------------------------------------------------------------
+ using (var e = new NotaEngine())
+ {
+ e.SetBpm(120);
+ int t = e.AddInstrumentTrack();
+ e.AddMidiClip(t, 0.0, 8.0);
+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 4.0, 0.8f), new NotaNote(64, 2.0, 4.0, 0.8f) });
+ e.SetDeviceBypassed(t, -1, true);
+ e.Seek(0); e.Play();
+ double p = Peak(Render(e, 300));
+ e.StopTransport();
+ yield return (p == 0.0, $"an instrument that is off stays silent while its clip plays (peak {p:E1})");
+ }
+
+ // ---- duplicate, save / load, older projects --------------------------------------
+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-instoff-" + Guid.NewGuid().ToString("N") + ".nota");
+ var transport = new TransportState(120.0, 1.0, false, false);
+ string saved = "";
+ try
+ {
+ using (var src = new NotaEngine())
+ {
+ int a = src.AddInstrumentTrack();
+ int b = src.AddInstrumentTrack();
+ src.SetDeviceBypassed(a, -1, true);
+ int dup = src.DuplicateTrack(a);
+ yield return (dup > 0 && src.DeviceBypassed(dup, -1) && !src.DeviceBypassed(b, -1), "a duplicated track keeps its instrument off");
+ saved = Pattern(src);
+ ProjectService.Save(ProjectService.Capture(src, transport, new List<string>()), dir, src);
+ }
+ using (var dst = new NotaEngine())
+ {
+ var warn = ProjectService.Apply(ProjectService.Load(dir), dst, dir);
+ string loaded = Pattern(dst);
+ yield return (warn.Count == 0 && saved.Length == 3 && saved.Contains('1') && saved.Contains('0') && loaded == saved,
+ $"save / load keeps which instruments are off (saved {saved}, loaded {loaded}, warnings {warn.Count})");
+ }
+ // A project written before the switch existed has no flag: its instruments load on.
+ string manifest = Path.Combine(dir, ProjectService.ManifestName);
+ var root = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(manifest))!.AsObject();
+ int stripped = 0;
+ foreach (var tr in root["tracks"]!.AsArray())
+ if (tr?["instrument"] is System.Text.Json.Nodes.JsonObject inst && inst.Remove("bypassed")) stripped++;
+ File.WriteAllText(manifest, root.ToJsonString());
+ using (var dst = new NotaEngine())
+ {
+ var warn = ProjectService.Apply(ProjectService.Load(dir), dst, dir);
+ int a = dst.TryGetTrackInfo(0, out var ta) ? ta.Id : -1;
+ yield return (stripped == 3 && warn.Count == 0 && a > 0 && !dst.DeviceBypassed(a, -1),
+ $"a project without the flag loads with its instruments on (stripped {stripped})");
+ }
+ }
+ finally { try { Directory.Delete(dir, true); } catch { } }
+
+ // ---- MCP ---------------------------------------------------------------------------
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ var dev = new Nota.Mcp.Tools.DeviceTools(e, new SyncDispatch(), new NoRefresh());
+ var proj = new Nota.Mcp.Tools.ProjectTools(e, new SyncDispatch(), new NoRefresh());
+ dev.SetDeviceBypass(t, -1, true).GetAwaiter().GetResult();
+ var ov = proj.GetOverview().GetAwaiter().GetResult();
+ yield return (e.DeviceBypassed(t, -1) && ov.Tracks.Length == 1 && ov.Tracks[0].InstrumentOff,
+ "MCP set_device_bypass with device index -1 turns the instrument off, and get_overview shows it");
+ }
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 5e6ee509..53f02834 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -380,6 +380,14 @@ if (args.Length >= 1 && args[0] == "--midi-ctl")
Console.WriteLine(failures == 0 ? "MIDI CTL PASSED" : $"MIDI CTL FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// The instrument's on/off switch alone (fast iteration): `--instrument-off`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--instrument-off")
+{
+ Console.WriteLine("-- instrument on/off --");
+ foreach (var (ok, label) in InstrumentBypassTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "INSTRUMENT OFF PASSED" : $"INSTRUMENT OFF FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// MPE alone (fast iteration): `--mpe`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--mpe")
{
@@ -14760,6 +14768,8 @@ Console.WriteLine("-- loop record mode --");
foreach (var (ok, label) in LoopRecordModeTests.Run()) Check(ok, label);
Console.WriteLine("-- nota keys --");
foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);
+Console.WriteLine("-- instrument on/off --");
+foreach (var (ok, label) in InstrumentBypassTests.Run()) Check(ok, label);
Console.WriteLine("-- nota mosaic --");
foreach (var (ok, label) in MosaicTests.Run()) Check(ok, label);