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) Select several devices and group them into a rack (#328) (#351)

Egor Khindikaynen1ba48d2d22fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef0849db..cd06c200 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Select several devices and group them into a rack** (#328): in the Devices panel ⇧-click
+ selects a range across MIDI effects, the instrument and audio effects, ⌘-click adds or
+ removes one, Esc clears. Copy, cut, paste, duplicate, delete, Move to track ▸ and dragging a
+ header act on the whole selection in one undo step; with the instrument selected along with
+ other devices, Delete always asks before its track goes. ⌘G (or **Group into rack**) folds
+ the selection into the matching rack — Audio Effect Rack, MIDI Effect Rack, or an Instrument
+ Rack whose first chain holds the MIDI effects, the instrument and the audio effects — in
+ place, sounding the same; ⌘⇧G takes any one-chain rack apart. Automation, modulation links,
+ an Arp's CC lane and sidechain keys follow the devices into the rack and back out, keep
+ working, and are saved with the project. MCP `group_devices`, `ungroup_rack`.
- **MIDI Effect Rack**: a new MIDI effect with chains of MIDI effects. Each chain takes the
notes its key and velocity zone lets in (or, in Select mode, the chains whose select range
holds the selector), runs them through its Arp, Chord, Scale and so on, can transpose them
diff --git a/FEATURES.md b/FEATURES.md
index 75f07948..73514144 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -245,6 +245,17 @@ track count and closes with Escape.
- **Move to track ▸** in a device's menu, or dragging its header onto a track in the
Arrangement or a Session column, moves it there with its automation; ⌥ copies instead.
The instrument replaces the other track's instrument and its own track goes.
+ - **Several devices at once**: ⇧-click selects a range across the MIDI effects, the
+ instrument and the audio effects, ⌘-click adds or removes one, Esc clears. Copy, cut, paste,
+ duplicate, delete, Move to track ▸ and dragging a header act on the whole selection, each in
+ one undo step (with the instrument selected too, Delete asks before its track goes).
+ - **Group into rack** (⌘G, or the device menu): the rack follows from the selection —
+ audio effects → Audio Effect Rack, MIDI effects → MIDI Effect Rack, the instrument with
+ the MIDI effects before it and / or the audio effects after it → Instrument Rack, its first
+ chain holding them in order. The track sounds the same; automation, modulation links, an
+ Arp's CC lane and sidechain keys follow the devices into the rack (and their lanes show in
+ the Arrangement as "Rack / Device · Param"). ⌘⇧G (**Ungroup rack**) takes a one-chain rack
+ apart. MCP `group_devices`, `ungroup_rack`.
---
@@ -944,7 +955,7 @@ audio effects after it keep running and keep their settings; saved with the proj
- **Nota Audio Effect Rack** — chains run **Parallel / Serial / Select**; in Select mode a
selector (dragged, mapped to a macro, or following the input level) picks the chains whose
select range holds it; Dry/wet, Gain, latency compensation; the add menu lists built-in
- effects and a Plug-ins submenu. ⌘G on a selected audio effect wraps it in a new rack
+ effects and a Plug-ins submenu. ⌘G on selected audio effects groups them into a new rack
(**Group into rack**); ⌘⇧G puts a one-chain rack's devices back.
- **Nota MIDI Effect Rack** — a MIDI effect with up to 16 chains of MIDI effects (Arp, Chord,
Scale, Length, Velocity, Random). Each chain takes the notes its key and velocity zone lets in
diff --git a/specs/044-device-multiselect-group/checklists/requirements.md b/specs/044-device-multiselect-group/checklists/requirements.md
new file mode 100644
index 00000000..48b6030c
--- /dev/null
+++ b/specs/044-device-multiselect-group/checklists/requirements.md
@@ -0,0 +1,35 @@
+# Specification Quality Checklist: Multi-select devices and group them into a rack
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-27
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details (languages, frameworks, APIs)
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] Success criteria are technology-agnostic (no implementation details)
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified
+- [x] Scope is clearly bounded
+- [x] Dependencies and assumptions identified
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+- [x] No implementation details leak into specification
+
+## Notes
+
+- Clarified 2026-10-27: links on grouped devices travel into the rack and back (FR-016).
+- The "Nota Context" and "Nota Compliance Checklist" sections name engine / managed layers because the project template asks for them; the requirements themselves stay behaviour-level.
diff --git a/specs/044-device-multiselect-group/contracts/c-abi.md b/specs/044-device-multiselect-group/contracts/c-abi.md
new file mode 100644
index 00000000..c67681ce
--- /dev/null
+++ b/specs/044-device-multiselect-group/contracts/c-abi.md
@@ -0,0 +1,97 @@
+# C ABI contract (`nota_engine.h`)
+
+All calls: message thread only. Every successful structural edit is one undo step (one
+published graph) unless noted.
+
+## New — group / ungroup (R3)
+
+```c
+/* Group a contiguous run of a track's devices into a new rack in their place (#328), one undo
+ * step. midi_first/midi_count: the MIDI effects (count 0 = none); with_instrument: 1 to include
+ * the instrument; fx_first/fx_count: the audio effects. The rack type follows from the run:
+ * audio effects only -> Audio Effect Rack at fx_first; MIDI effects only -> MIDI Effect Rack at
+ * midi_first; with the instrument -> an Instrument Rack as the track's instrument whose chain 0
+ * holds MIDI effects -> instrument -> audio effects (the MIDI run must end at the last MIDI
+ * effect and the audio run start at 0).
+ * Instances move in without re-preparing; automation lanes, CV links, Arp CC routes and
+ * sidechain keys on them are rewritten to point into the rack (nested address).
+ * Returns the rack's address (>= 0 audio-effect index, -1 the instrument, or the MIDI
+ * effect index encoded as for MIDI effects), or a reason < -1:
+ * -2 empty or out-of-range run -3 not contiguous / MIDI + audio without instrument
+ * -4 a rack in the run -5 a plug-in the target rack can't host
+ * -6 the instrument can't be a chain instrument (an Instrument Rack)
+ * -7 not an instrument track (MIDI effects / instrument on an audio track) */
+NOTA_API int32_t nota_track_group_devices(NotaEngine* engine, int32_t track_id,
+ int32_t midi_first, int32_t midi_count, int32_t with_instrument,
+ int32_t fx_first, int32_t fx_count);
+
+/* Ungroup a one-chain rack (Audio Effect Rack, MIDI Effect Rack, or an Instrument Rack as the
+ * track's instrument; family 0 audio effect at index, 1 MIDI effect at index, 2 the instrument)
+ * back into its chain's devices, in place, one undo step. Nested addresses pointing into the
+ * rack become track-level again; the rack's own macros, mappings, chain mix and settings are
+ * dropped. Returns the number of devices restored (>= 0), or
+ * -2 not a rack / bad address -3 two or more chains -4 a Drum Rack.
+ * *out_dropped (may be NULL): bit 0 macro mappings dropped, bit 1 non-default chain mix /
+ * zones dropped. */
+NOTA_API int32_t nota_track_ungroup_rack(NotaEngine* engine, int32_t track_id, int32_t family,
+ int32_t index, int32_t* out_dropped);
+```
+
+## Changed
+
+```c
+/* #257 wrappers, kept for callers: wrap = group_devices(track, 0, 0, 0, device_index, 1);
+ * unwrap = ungroup_rack(track, 0, device_index, NULL). They no longer refuse automated,
+ * modulated, keyed or CC-driven devices. */
+NOTA_API int32_t nota_track_wrap_device_in_rack(NotaEngine* engine, int32_t track_id, int32_t device_index);
+NOTA_API int32_t nota_track_unwrap_rack(NotaEngine* engine, int32_t track_id, int32_t device_index);
+
+/* clipboard_kind: 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument, 4 several devices. */
+NOTA_API int32_t nota_device_clipboard_kind(const NotaEngine* engine);
+```
+
+## New — multi-device clipboard (R8)
+
+```c
+/* Put a set of a track's devices on the device clipboard, in chain order (MIDI effects, the
+ * instrument, audio effects), each a full clone. Replaces the clipboard. Returns the entry
+ * count, or -1 bad address. */
+NOTA_API int32_t nota_track_copy_devices(NotaEngine* engine, int32_t track_id,
+ const int32_t* midi_idx, int32_t midi_n, int32_t with_instrument,
+ const int32_t* fx_idx, int32_t fx_n);
+NOTA_API int32_t nota_device_clipboard_count(const NotaEngine* engine);
+
+/* Paste every clipboard entry onto track_id in one undo step: MIDI effects at midi_at, audio
+ * effects at fx_at (-1 = the end of the section), an instrument replacing the track's.
+ * Entries the track can't take are skipped. Returns the number pasted (>= 0) and
+ * *out_skipped (may be NULL); -1 empty clipboard, -3 a clone failed (nothing changed). */
+NOTA_API int32_t nota_track_paste_devices(NotaEngine* engine, int32_t track_id,
+ int32_t midi_at, int32_t fx_at, int32_t* out_skipped);
+```
+
+## New — nested addresses on lanes and links (R1, R7)
+
+```c
+/* Chain and slot of a lane's target: chain_index -1 = track-level (the old meaning);
+ * otherwise the chain's index in the rack at the lane's device_index, and slot as in rack
+ * mappings (>= 0 device, -1 chain instrument, MIDI effects encoded as RackCore MIDI targets). */
+NOTA_API NotaResult nota_track_automation_lane_path(const NotaEngine* engine, int32_t track_id,
+ int32_t lane_index, int32_t* out_chain_index, int32_t* out_slot);
+/* Project load: add a lane addressed into a rack chain (plugin params by stable id). Returns
+ * the lane index or -1 when the address doesn't resolve. */
+NOTA_API int32_t nota_track_add_nested_automation_lane(NotaEngine* engine, int32_t track_id,
+ int32_t target, int32_t device_index, int32_t chain_index, int32_t slot,
+ int32_t param_index, const char* param_id);
+/* The same pair for CV links (source and target) and the Arp CC route, read for save and set
+ * on load; signatures mirror the existing CV / CC calls with chain_index + slot appended. */
+```
+
+The exact CV / CC signatures follow the existing `nota_track_*cv*` and Arp CC calls; they
+append `chain_index, slot` and keep the old calls as track-level wrappers.
+
+## Smoke coverage
+
+`DeviceGroupTests.cs` calls every function above: each rack type, each refusal code, render
+equality before / after (±0.1 dB), a nested lane / CV link / CC route / sidechain key still
+acting after Group and after Ungroup, undo of each, save → reload of a grouped project, multi
+copy / paste with skips.
diff --git a/specs/044-device-multiselect-group/contracts/mcp.md b/specs/044-device-multiselect-group/contracts/mcp.md
new file mode 100644
index 00000000..8d75c842
--- /dev/null
+++ b/specs/044-device-multiselect-group/contracts/mcp.md
@@ -0,0 +1,21 @@
+# MCP contract
+
+## `group_devices` (DeviceTools.cs) — new
+
+- Args: `trackId: int`, `midiFirst: int = -1`, `midiCount: int = 0`,
+ `withInstrument: bool = false`, `fxFirst: int = -1`, `fxCount: int = 0`.
+- Calls `nota_track_group_devices`. Returns `{ rackType: "audio" | "instrument" | "midi",
+ index }` (index −1 for the instrument), or an error naming the refusal (−2…−7 of the C
+ contract, in words).
+- Description notes: the run must be contiguous; MIDI effects + audio effects need the
+ instrument between them; automation and modulation follow the devices into the rack; inspect
+ the result with `get_effect_rack` / `get_rack` / `get_midi_rack`.
+
+## `ungroup_rack` (DeviceTools.cs) — new
+
+- Args: `trackId: int`, `chain: "audio" | "midi" | "instrument"`, `index: int = 0` (ignored
+ for "instrument").
+- Calls `nota_track_ungroup_rack`. Returns `{ restored, macrosDropped, chainMixDropped }`, or
+ an error for not a rack / two or more chains / a Drum Rack.
+
+Both are one undo step (`undo` reverts them).
diff --git a/specs/044-device-multiselect-group/contracts/ui.md b/specs/044-device-multiselect-group/contracts/ui.md
new file mode 100644
index 00000000..5e622b90
--- /dev/null
+++ b/specs/044-device-multiselect-group/contracts/ui.md
@@ -0,0 +1,65 @@
+# UI contract (Devices panel)
+
+The track's device chain in the detail panel (`DeviceChainView`). Rack cards' own chain
+selection (specs/042) is unchanged and single.
+
+## Gestures
+
+| Gesture | On | Result |
+|---------|----|--------|
+| Click | a card's header or empty body | selects only that card; anchor = it |
+| Shift-click | a card | selects anchor..card in chain order (MIDI → instrument → audio) |
+| ⌘-click (Ctrl-click on Windows / Linux) | a card | toggles it; anchor = it |
+| Click | empty chain space | clears the selection |
+| Esc | panel focused, nothing in text entry | clears the selection |
+| Drag a selected card's header | — | moves every selected card of that section to the drop gap |
+| Right-click | an unselected card | selects only it, then shows its menu |
+| Right-click | a selected card | menu for the whole selection |
+
+Every selected card shows the existing selection border (DESIGN.md accent); nothing marks the
+anchor.
+
+## Keys (panel focused, not typing)
+
+| Key | Action | Notes |
+|-----|--------|-------|
+| ⌘C / ⌘X / ⌘V | copy / cut / paste the selection | paste lands after each section's last selected device, or at its end |
+| ⌘D | duplicate each selected run after itself | the instrument is skipped |
+| Delete / Backspace | delete the selection | with the instrument: confirmation (below) |
+| ⌘G | Group into rack | status-line reason when refused |
+| ⌘⇧G | Ungroup rack | the selection must be one rack card |
+
+## Menu (selected card)
+
+- Header: the device name and badge for one device; **"N devices"** for several.
+- Groups: Save preset (one device only) · Copy, Cut, Paste, Duplicate · Move to track ▸ ·
+ **Group into rack** (enabled when the shape is valid) / **Ungroup rack** (on a one-chain
+ rack; disabled on two or more chains) · Delete (or **Delete track** when the selection
+ includes the instrument).
+- Group / Ungroup appear on MIDI-effect, instrument and audio-effect cards alike.
+
+## Confirmation
+
+The selection holds the instrument **and** another device, and the user deletes, cuts or
+moves it: a dialog "Delete track ‹name›? The track and its N selected devices will be
+removed." with Cancel / Delete, every time. The instrument alone keeps specs/043 (asks only
+when the track has clips).
+
+## Status line
+
+| Situation | Message |
+|-----------|---------|
+| Grouped | "Put N devices in an Audio Effect Rack" / "… an Instrument Rack" / "… a MIDI Effect Rack" |
+| Ungrouped | "Took N devices out of the rack" (+ " — its macros and chain settings were dropped" when bit set) |
+| Not contiguous | "Select devices next to each other to group them" |
+| MIDI + audio without instrument | "MIDI and audio effects go in one rack only with the instrument between them" |
+| Rack in the run | "‹Rack› can't go inside another rack" |
+| Plug-in in a MIDI Effect Rack | "‹Plug-in› can't go in a MIDI Effect Rack" |
+| Instrument Rack as the instrument | "An Instrument Rack can't go inside another Instrument Rack" |
+| Two or more chains | "Only a rack with one chain can be ungrouped" |
+| Paste skipped | "Pasted N devices, skipped M this track can't take" |
+
+## Selection lifetime
+
+Cleared on track switch, on a rack-chain device selection, and when its cards are removed;
+after Group the new rack is selected, after Ungroup the restored devices are.
diff --git a/specs/044-device-multiselect-group/data-model.md b/specs/044-device-multiselect-group/data-model.md
new file mode 100644
index 00000000..a39ba723
--- /dev/null
+++ b/specs/044-device-multiselect-group/data-model.md
@@ -0,0 +1,69 @@
+# Data Model: Multi-select devices and group them into a rack
+
+See [research.md](research.md) for the reasoning behind each shape.
+
+## ParamPath (engine, R1)
+
+The address of a parameter's owner, one rack level deep.
+
+| Field | Type | Meaning |
+|-------|------|---------|
+| `host` | int32 | Track-level device: ≥ 0 audio effect index, −1 the instrument, MIDI effects in the track's existing MIDI addressing |
+| `chainUid` | uint64 | 0 = `host` itself; otherwise the uid of a chain of the rack at `host` |
+| `slot` | int32 | Only when `chainUid` ≠ 0: ≥ 0 the chain's audio device, −1 the chain instrument, `RackCore::kMidiDeviceBase − i` the chain's i-th MIDI effect |
+
+Rules:
+- `chainUid` ≠ 0 requires `host` to be a rack (Audio Effect, Instrument or MIDI Effect Rack).
+- A path that resolves to nothing (chain or slot gone) is a no-op on the audio thread and is
+ pruned by the edit that removed it (R6).
+- Saved as `Chain` (chain index at save time) + `Slot`; turned back into a uid on load (R7).
+
+### Where it is used
+
+| Owner | Old fields | New fields |
+|-------|-----------|------------|
+| `AutomationLane` | `deviceIndex` (= host), `paramIndex`, `paramId` | `chainUid`, `slot` |
+| `CvLink` source (Param kind) | `sourceDevice` | `sourceChainUid`, `sourceSlot` |
+| `CvLink` target | `targetDevice` | `targetChainUid`, `targetSlot` |
+| Arp CC route (moves into `Track`, R4) | on `MidiDevice`: `ccDestDevice`, `ccDestParam` | `Track::ccRoutes[]`: `{ arp: ParamPath-like position of the MIDI effect, target: ParamPath, param }` |
+| Sidechain | `Device::sidechainSourceTrackId` (unchanged, now honoured inside rack chains) | — |
+
+## Group shape (UI rule + engine validation)
+
+Input: the selection's members in chain order. Output: one of
+
+| Shape | Condition | Result |
+|-------|-----------|--------|
+| `AudioRack` | only audio effects, indices consecutive | `RackDevice` at the first index |
+| `MidiRack` | only MIDI effects, indices consecutive | `MidiRack` at the first index |
+| `InstrumentRack` | the instrument; MIDI effects (if any) consecutive and ending at the last MIDI effect; audio effects (if any) consecutive and starting at index 0 | `RackInstrument` as the track's instrument, chain 0 = MIDI → instrument → audio |
+| `Refused(reason)` | gaps; MIDI + audio without the instrument; a rack among the effects; a plug-in into a MIDI Effect Rack; an instrument a chain can't hold (an Instrument Rack) | nothing changes |
+
+Ungroup validity: a rack (any of the three types, not a Drum Rack as the track instrument) with
+exactly one chain.
+
+## Device selection (UI, R9)
+
+| Field | Type | Meaning |
+|-------|------|---------|
+| `members` | ordered set of `(ChainKind, index)` | `ChainKind` ∈ Midi, Instrument (index −1), Effect |
+| `anchor` | `(ChainKind, index)?` | last plain- or ⌘-clicked card |
+
+Transitions: `Click(x)` → {x}, anchor x · `ShiftClick(x)` → range anchor..x in chain order ·
+`ToggleClick(x)` → members ⊕ x, anchor x · `Clear()` (Esc, empty space, track switch, rack
+selection) → {} · after an engine edit → members remapped from the returned indices.
+
+Chain order: MIDI effects 0..m−1, then the instrument, then audio effects 0..n−1.
+
+## Device clipboard (engine, R8)
+
+An ordered list of entries; each entry is `{family: AudioEffect | MidiEffect | Instrument,
+clone}` with full parameters and state (plug-in state, a rack's chains and macros). Copy
+replaces the whole list. `clipboard_kind` keeps answering for a one-entry list as before and
+returns 4 (mixed / several) otherwise; `clipboard_count` gives the length.
+
+## Card extra (UI, R10)
+
+`CardExtra.Wrapped`: from one `CardExtra?` to an ordered `List<CardExtra>` — the grouped
+devices' A/B snapshots and preset labels, restored on Ungroup / Undo when each card's
+signature matches.
diff --git a/specs/044-device-multiselect-group/plan.md b/specs/044-device-multiselect-group/plan.md
new file mode 100644
index 00000000..a74d82eb
--- /dev/null
+++ b/specs/044-device-multiselect-group/plan.md
@@ -0,0 +1,173 @@
+# Implementation Plan: Multi-select devices and group them into a rack
+
+**Branch**: `feat/device-multiselect-group` | **Date**: 2026-10-27 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `specs/044-device-multiselect-group/spec.md`
+
+## Summary
+
+The track's device chain gets a multi-selection (Shift-click range, ⌘/Ctrl-click toggle)
+across MIDI effects, the instrument and audio effects. Copy / Cut / Paste / Delete / Duplicate
+/ drag / Move to track ▸ act on the whole selection as one undo step. ⌘G groups a contiguous
+selection into the matching rack (Audio Effect, Instrument or MIDI Effect Rack), and ⌘⇧G
+ungroups any one-chain rack; both are one publish and one undo step, and the track sounds the
+same.
+
+Per the clarification, automation lanes, CV links, sidechain keys and Arp CC routes travel
+into the rack and back. That needs the engine's one real addition: a **nested parameter
+address** (`ParamPath`: host device → chain uid → slot) used by automation, CV, the Arp CC
+route (moved into the undo snapshot) and the sidechain feed, resolved on the audio thread by
+reading the rack's published snapshot. On top of that: general `groupDevices` /
+`ungroupRack` operations replacing the single wrap / unwrap (#257), a multi-entry device
+clipboard, project-format fields for nested lanes, and the selection model, menus and keys in
+`DeviceChainView`. See [research.md](research.md) R1–R11.
+
+## Nota: Read Before Planning
+
+- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-5 (Group / Ungroup / Paste
+ each publish one graph), AR-6 (the nested resolver only reads published snapshots — no
+ allocation or lock on the audio thread), AR-7 (new calls only in `nota_engine.h`).
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill (multi-selection
+ borders, the menu header with a count, disabled items).
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 + Avalonia (app, presentation, MCP)
+
+**Primary Dependencies**: None new
+
+**Storage**: Project file — automation-lane, CV-link and Arp-CC-route DTOs gain optional
+`Chain` / `Slot` fields (format version bump; old projects load unchanged, R7). The clipboard is
+not persisted.
+
+**Audio-Thread Impact**: `applyAutomation`, `applyMidiCcRouting`, the CV apply pass and the
+sidechain feed resolve nested targets by scanning the rack's published `RackState` chains
+(no allocation, no lock, AR-6). Group / Ungroup / Paste build off-graph and publish once
+(AR-5); moved instances are not re-prepared, so tails and held notes continue.
+
+**Testing**: `tests/Nota.SmokeTest` — new `DeviceGroupTests.cs` (engine through the C ABI:
+group / ungroup per rack type, render equality before / after, nested lanes / CV / CC /
+sidechain, undo, save-reload, multi-clipboard) and `DeviceSelectionTests.cs` (the selection
+model, headless). UI checked in the running app per [quickstart.md](quickstart.md).
+
+**Target Platform**: macOS, Windows, Linux desktop
+
+**Project Type**: Desktop app (native engine + managed UI)
+
+**Performance Goals**: Group / Ungroup during playback: no dropout (SC-006), the edit under one
+UI frame; render before vs after Group within 0.1 dB (SC-003); nested resolve adds no
+measurable block time (checked with the existing engine perf gate).
+
+**Constraints**: One undo step per user action (FR-020); racks nest one level (specs/041);
+Ungroup only for one-chain racks.
+
+**Scale/Scope**: ~6 engine files (+1 helper), ~6 C ABI calls, ~10 managed files, 1 MCP tool
+pair, 2 smoke files
+
+## Constitution Check
+
+*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
+
+| Principle | Status | Notes |
+|-----------|--------|-------|
+| I. Real-time audio safety | Pass | Nested resolve reads the published rack snapshot only (R2); structural edits publish once (R3) |
+| II. Boundary discipline | Pass | New calls in `nota_engine.h` (contracts/c-abi.md); no JUCE outside `pluginhost/` |
+| III. Licensing hygiene | Pass | New files carry the SPDX header; no dependencies |
+| IV. Verification gate | Pass | `DeviceGroupTests` covers every new C ABI call; `scripts/build.sh` before the PR |
+| V. One logical change | Pass, noted | One issue (#328); the nested address is its prerequisite and lands in the same PR, first commit(s) |
+| VI. Docs in sync | Planned | CHANGELOG `[Unreleased]`, FEATURES.md (nota-features), user docs (nota-docs), Shortcuts pane (nota-shortcuts) |
+| VII. Spec-first | Pass | spec.md with 3 clarifications, this plan, tasks.md next |
+| VIII. Rules not weakened | Pass | — |
+
+Post-design re-check (after Phase 1): unchanged — the contracts add audio-thread reads of
+already-published data only, and cross the boundary only through the C ABI.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/044-device-multiselect-group/
+├── spec.md
+├── plan.md # this file
+├── research.md # R1–R11
+├── data-model.md # ParamPath, selection, clipboard, group shape
+├── quickstart.md # end-to-end checks in the app + smoke
+├── contracts/
+│ ├── c-abi.md # new / changed nota_engine.h calls
+│ ├── ui.md # gestures, menus, keys, status messages
+│ └── mcp.md # group_devices, ungroup_rack
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (repository root)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # + group/ungroup, multi copy/paste, nested lane/CV info
+└── src/
+ ├── abi/
+ │ ├── nota_engine_device.cpp # group / ungroup / copy_devices / paste_devices wrappers
+ │ └── nota_engine_automation.cpp # nested lane info + add (for load)
+ ├── devices/
+ │ ├── MidiDevice.h # CC destination leaves the device (R4)
+ │ └── racks/RackCore.h/.cpp # setChainInstrumentInstance; child walk helper for the feed
+ └── engine/
+ ├── ParamPath.h # new: the nested address + resolver declaration (R1)
+ ├── Automation.h, Modulation.h, Track.h # lanes, CV links, CC routes carry chain/slot
+ ├── Engine.h
+ ├── Engine_Rack.cpp # groupDevices / ungroupRack (R3), remapPathsAfterRackEdit (R6)
+ ├── Engine_Automation.cpp # applyAutomation via resolver; remap helpers take paths
+ ├── Engine_Modulation.cpp # CV apply / remap via paths
+ ├── Engine_Render.cpp # applyMidiCcRouting + sidechain feed walk rack chains (R4, R5)
+ └── Engine_Devices.cpp # multi-entry clipboard (R8), route claims walk racks
+
+src/managed/
+├── Nota.Application/Engine/IAudioEngine.cs, EngineContracts.cs # GroupDevices, UngroupRack, CopyDevices, PasteDevices, lane Chain/Slot
+├── Nota.Infrastructure/
+│ ├── Interop/NativeMethods.*.cs, NotaEngine.*.cs # P/Invoke
+│ └── Persistence/ProjectService.cs # Chain / Slot on lane, CV, CC-route DTOs (R7)
+├── Nota.App/
+│ ├── DeviceSelection.cs # new: the selection model (R9)
+│ ├── DeviceChainView.Clipboard.cs # selection gestures, batch ops, ⌘G / ⌘⇧G, menus
+│ ├── DeviceChainView.Shell.cs # CardExtra.Wrapped → list (R10); selection border per card
+│ ├── DeviceChainView.Move.cs # Move to track ▸ for a selection; multi drag-reorder
+│ ├── DeviceChainView.Instruments.cs, DeviceChainView.Midi.cs # click modifiers on those cards
+│ ├── ArrangementView.Automation.cs # nested lane titles ("Rack › Reverb · Mix")
+│ └── PreferencesWindow (Shortcuts list) # Shift/⌘-click, ⌘G/⌘⇧G in Devices
+└── Nota.Mcp/Tools/DeviceTools.cs # group_devices, ungroup_rack
+
+tests/Nota.SmokeTest/
+├── DeviceGroupTests.cs # new
+├── DeviceSelectionTests.cs # new
+├── Fixtures/ # an old-format project with an Arp CC lane (R4 migration)
+└── Program.cs # run them; --device-group
+```
+
+**Structure Decision**: The existing engine / managed split. The nested address lives in one
+new engine header used by the automation, modulation and render files; the UI work stays in
+the `DeviceChainView` partials with the rules factored into `DeviceSelection`.
+
+## Phases (for /speckit-tasks)
+
+1. **Foundation: nested address** — `ParamPath` + resolver; lanes, CV links, Arp CC route
+ (moved into the snapshot, with load migration) and the sidechain feed / route claims go
+ through it; `remapPathsAfterRackEdit` on rack chain edits; nested lane info in the ABI;
+ persistence fields; smoke tests for each consumer. Behaviour today is unchanged (no nested
+ paths exist until Group).
+2. **Engine Group / Ungroup** — `groupDevices` / `ungroupRack` for the three rack types,
+ `setChainInstrumentInstance`, path rewriting, old wrap / unwrap as wrappers; smoke: render
+ equality, undo, save-reload.
+3. **US1 (P1)** — ⌘G / ⌘⇧G and menu items on audio-effect selections (single and range).
+4. **US2 (P1)** — `DeviceSelection`, gestures, borders, multi-entry clipboard (engine + UI),
+ batch Delete / Cut / Duplicate / drag / Move to track ▸, confirmation with the instrument.
+5. **US3 (P2)** — Instrument Rack group / ungroup from the UI.
+6. **US4 (P3)** — MIDI Effect Rack group / ungroup from the UI.
+7. **MCP, nested lane titles, Shortcuts, CHANGELOG, FEATURES, docs; build + smoke + perf gate.**
+
+## Complexity Tracking
+
+No constitution violations. The nested address (phase 1) is the large part and exists only
+because of the FR-016 clarification; it is kept to one rack level and one shared resolver.
diff --git a/specs/044-device-multiselect-group/quickstart.md b/specs/044-device-multiselect-group/quickstart.md
new file mode 100644
index 00000000..73e19073
--- /dev/null
+++ b/specs/044-device-multiselect-group/quickstart.md
@@ -0,0 +1,55 @@
+# Quickstart: validating the feature
+
+## Prerequisites
+
+- `scripts/build.sh` (Release engine in `build/`, see the engine-build-dirs note in BUILD.md).
+- Run the app with an isolated data dir: `NOTA_DATA_DIR=/tmp/nota-044 <app>`.
+
+## Engine (smoke)
+
+```bash
+dotnet run --project tests/Nota.SmokeTest -- --device-group
+```
+
+Expected: every `DeviceGroupTests` and `DeviceSelectionTests` check passes (see
+[contracts/c-abi.md](contracts/c-abi.md) § Smoke coverage and
+[data-model.md](data-model.md) § Group shape). `scripts/build.sh` runs them with the full suite,
+plus the engine perf gate (nested resolve adds no measurable block time).
+
+## In the app
+
+1. **Group audio effects (US1)** — Nota Volt track with a MIDI clip; add EQ-8, Compressor,
+ Saturator, Reverb. Click Compressor, Shift-click Reverb: three borders. ⌘G: EQ-8 → Audio
+ Effect Rack; its chain lists Compressor, Saturator, Reverb with the same values. Play: same
+ sound (export a bar before and after; levels within 0.1 dB). ⌘Z: four cards back, the three
+ selected. ⌘G again, then ⌘⇧G on the rack: same result as undo.
+2. **Links travel (FR-016)** — Draw a lane on the Reverb's Mix, add an LFO CV link to the
+ Saturator's Drive, key the Compressor from another track, and set an Arp's CC lane on the
+ EQ-8 gain. Select EQ-8..Reverb, ⌘G. Play: the Mix lane still moves the Reverb (the lane
+ title reads "Audio Effect Rack / Reverb · Mix"), the LFO still wobbles Drive, the Compressor
+ still ducks, the Arp still drives EQ-8. Save, reopen: all still act. ⌘⇧G: all back on the
+ track devices; ⌘Z twice: back to the start.
+3. **Multi-select (US2)** — ⌘-click EQ-8 and Reverb (not adjacent): ⌘G is refused with
+ "Select devices next to each other…", the menu item is disabled. ⌘C, select another
+ instrument track's last effect, ⌘V: both land after it in order. Shift-click a range of
+ three effects, Delete: gone in one step; ⌘Z restores. Drag the selected range's header two
+ slots left: the range moves together; ⌘Z.
+4. **Instrument in the selection** — Shift-click from an Arp to the Chorus after Volt, press
+ Delete: the "Delete track …?" dialog appears even on a track without clips; Cancel leaves
+ everything. ⌘C on that selection, select another instrument track, ⌘V: its instrument is now
+ Volt, Arp and Chorus land in their sections, one ⌘Z undoes all.
+5. **Instrument Rack (US3)** — Select Arp → Volt → Chorus, ⌘G: the instrument is an Instrument
+ Rack whose chain 0 holds Arp, Volt, Chorus; the clip plays the same notes. Add a chain,
+ save the rack as a preset, load it on a new track: same chains. ⌘⇧G on a one-chain rack:
+ Arp after the track's MIDI effects, Volt as the instrument, Chorus before the track's audio
+ effects. Select an Instrument Rack instrument and ⌘G: refused with a reason.
+6. **MIDI Effect Rack (US4)** — Select Chord → Scale → Arp, ⌘G: one MIDI Effect Rack; same notes;
+ ⌘⇧G restores.
+7. **Refusals** — An Audio Effect Rack inside the selection: refused, naming it. A rack with two
+ chains: Ungroup disabled. MIDI effect + audio effect without the instrument: refused.
+8. **During playback** — Repeat 1 and 5 with the transport running and a Reverb tail sounding:
+ no gap or click; the tail continues through the edit.
+9. **MCP** — `group_devices` (trackId, fxFirst 1, fxCount 3) then `get_effect_rack`, then
+ `ungroup_rack` and `undo`; each answer matches the UI's.
+10. **Themes** — Multi-selection borders, the "N devices" menu header and the disabled Group
+ item in all four themes.
diff --git a/specs/044-device-multiselect-group/research.md b/specs/044-device-multiselect-group/research.md
new file mode 100644
index 00000000..c56cb153
--- /dev/null
+++ b/specs/044-device-multiselect-group/research.md
@@ -0,0 +1,208 @@
+# Research: Multi-select devices and group them into a rack
+
+Phase 0 of [plan.md](plan.md). Each entry: decision, rationale, alternatives.
+
+## What exists (read before the decisions)
+
+- **Single wrap / unwrap (#257)** — `Engine::wrapDeviceInRack` / `unwrapRack`
+ (`src/native/nota.engine/src/engine/Engine_Rack.cpp`) move one audio effect *instance* into a
+ new `RackDevice` chain without re-preparing it (a Reverb keeps its tail) and publish once.
+ Both refuse when `deviceIsReferenced` finds an automation lane, an Arp CC lane or a CV link
+ on the device, or when the device has a sidechain key: nothing outside a track's own chain
+ can address a device inside a rack chain.
+- **Addressing today** — `AutomationLane` (`Automation.h`) is `{target, deviceIndex,
+ paramIndex, paramId}` on the track's chain only; `CvLink` (`Modulation.h`) the same for
+ source and target; an Arp's CC destination is `ccDestDevice/ccDestParam` on the
+ `MidiDevice` itself (outside the undo snapshot). Rack macro mappings are the only thing that
+ reach chain children (`RackCore::MacroMapping {chainIndex, deviceIndex, paramIndex}`,
+ `deviceIndex` −1 = chain instrument, `kMidiDeviceBase − i` = chain MIDI effect).
+- **Sidechain** — `Engine_Render.cpp` hands each *track-level* keyed device (and the
+ instrument) its previous-block route bus; route claims (`Engine_Devices.cpp` ~1370) look at
+ track-level devices only. Rack chain children are never fed a key.
+- **Rack state** — `RackCore` keeps its chains in its own immutable `RackState` snapshot
+ (`live()` is read by the audio thread; edits `commit` a new one), chains have a stable
+ `uid`; children take `setParam` from the audio thread already (macros do it).
+- **Undo** — every structural engine edit republishes a graph (one undo step);
+ `nota_engine_undo_group_begin/end` folds several into one.
+- **Clipboard** — `clipDevice_` / `clipMidi_` / `clipInstrument_`: one device (specs/043).
+- **UI** — `DeviceChainView.Clipboard.cs` holds one selection (`_selChainKind`,
+ `_selDeviceIndex`, `_instrumentSelected`), ⌘G / ⌘⇧G call the single wrap, the card's
+ per-device UI state (`CardExtra`: A/B snapshots, preset label) moves with the device, and a
+ rack keeps the one wrapped device's extra in `CardExtra.Wrapped`.
+
+## R1 — A nested parameter address (the foundation for FR-016)
+
+**Decision**: Introduce one engine value type, `ParamPath`, used wherever something points at
+a device parameter:
+
+```text
+ParamPath { int32 host; // track-level device: >= 0 audio effect, -1 instrument,
+ // MIDI effect as today's MIDI addressing
+ uint64 chainUid; // 0 = the host itself; else a chain of the rack at `host`
+ int32 slot; } // in that chain: >= 0 audio device, -1 the chain instrument,
+ // RackCore::kMidiDeviceBase − i the chain's i-th MIDI effect
+```
+
+`AutomationLane`, `CvLink` (source and target) and the Arp CC route each gain
+`chainUid` + `slot` beside their existing `deviceIndex` (which becomes `host`). A shared
+resolver `Engine::resolveParamOwner(Track&, host, chainUid, slot)` returns the `Device*`,
+`MidiDevice*` or `Instrument*`; with `chainUid` 0 it is today's lookup. Nesting goes one rack
+level deep, which is all Group can create (racks don't nest in rack chains; specs/041).
+
+**Rationale**: The user chose that automation, CV, sidechain and Arp CC travel into the rack
+(spec Clarifications). Rack macros can't stand in (only 8 per rack; an automated chain easily
+has more targets, and a macro-bridge would show macros the user never made). A path keyed by
+chain **uid** survives chain reorders, duplicates and deletes inside the rack without
+re-indexing the track's lanes; a lane whose chain is gone resolves to nothing and is pruned by
+the chain-delete path (R6).
+
+**Alternatives**: (a) macro bridging — rejected (8-macro limit, visible side effect); (b) a
+per-device uid across the engine — the cleanest long-term address but a project-wide refactor
+of every index-based API, out of proportion for this feature; (c) keep refusing (#257) —
+rejected by the clarification.
+
+## R2 — Resolving on the audio thread
+
+**Decision**: `resolveParamOwner` walks `RackCore::live()->chains` (a vector scan by uid, no
+allocation, no lock) and is called from `applyAutomation`, `applyMidiCcRouting`, the CV apply
+pass and the sidechain feed. Results are not cached.
+
+**Rationale**: AR-6 — the walk only reads the published rack snapshot, exactly as the rack's
+own render does; chains are few (≤ 16 MIDI / tens of audio), so the scan is cheaper than the
+param set itself. A cache would have to be invalidated on every rack edit.
+
+**Alternatives**: resolve once per graph publish into raw pointers — rejected: rack edits
+commit their own snapshot without republishing the graph, so the cache would go stale.
+
+## R3 — Group and Ungroup as single-publish engine operations
+
+**Decision**: Replace `wrapDeviceInRack` / `unwrapRack` with general operations (the old ABI
+calls become thin wrappers so nothing breaks):
+
+- `groupDevices(trackId, midiFirst, midiCount, withInstrument, fxFirst, fxCount)` builds the
+ rack off-graph, **moves** the instances in (no re-prepare, as #257 does), rewrites every
+ `ParamPath` that pointed at a moved device to its nested path, shifts the indices of
+ devices after the group (`remapAutomationAfterDeviceChange`, `remapCvLinksAfterDeviceChange`
+ generalised to paths), and publishes once.
+ - only audio effects → `RackDevice` at `fxFirst`;
+ - only MIDI effects → `MidiRack` at `midiFirst`;
+ - with the instrument → a `RackInstrument` whose chain 0 holds the MIDI effects, the
+ instrument (a new `RackCore::setChainInstrumentInstance` moves the instance; held notes keep
+ sounding) and the audio effects; it replaces the track's instrument through
+ `replaceTrackInstrument` (specs/043) inside the same publish.
+- `ungroupRack(trackId, family, index)` is the inverse for a one-chain rack of any of the three
+ types (Drum Rack excluded), rewriting nested paths back to track-level ones.
+- Validation happens before anything is built; failures return a reason code (contracts/c-abi.md).
+
+**Rationale**: FR-020 / FR-022 / SC-006: one publish means the device is never on the track
+and in the rack at once, nor missing; one publish is one undo step with no undo-group needed.
+
+**Alternatives**: compose from add-rack + per-device moves inside an undo group — rejected:
+intermediate graphs would be audible (devices missing for a block) and re-prepare would reset
+tails.
+
+## R4 — The Arp CC route moves into the snapshot
+
+**Decision**: Move the Arp's CC destination from the `MidiDevice` (`ccDestDevice/ccDestParam`)
+into the track snapshot as a route keyed by the MIDI effect's position path, with the target as
+a `ParamPath`. `applyMidiCcRouting` walks track MIDI effects **and** MIDI effects inside rack
+chains (a grouped Arp keeps driving its target). The existing set/get ABI keeps its signature
+and writes the snapshot; projects load the old per-Arp field and migrate it.
+
+**Rationale**: `unwrapRack` already refuses because a CC destination outside the snapshot can't
+be undone; Group and Ungroup must rewrite it and undo must restore it.
+
+**Alternatives**: clone the Arp on every rewrite — rejected: resets its running pattern and
+breaks "the track sounds the same" (FR-013).
+
+## R5 — Sidechain keys inside rack chains
+
+**Decision**: Rack chain children keep their own `sidechainSourceTrackId` (it already lives on
+the device). The render's sidechain feed and the route-bus claims walk rack chains (audio effect
+racks' devices, Instrument Rack chains' audio effects and instrument) via the R2 resolver walk.
+The rack device itself gains no key.
+
+**Rationale**: the key is previous-block route-bus data, so nesting adds no ordering
+constraint; feeding per child keeps two grouped devices with different keys working.
+
+**Alternatives**: one key per rack forwarded to all children — rejected: breaks a group of
+two devices keyed from different tracks.
+
+## R6 — Chain edits and dangling paths
+
+**Decision**: Deleting a chain, deleting / moving a device inside a chain (specs/042), or
+deleting / replacing the rack prunes or rewrites the track's lanes, CV links and CC routes that
+point into it, in the same publish (one helper, `remapPathsAfterRackEdit`). Undo restores them
+with the snapshot.
+
+**Rationale**: once lanes can point into a rack, every rack edit that removes or moves a child
+must keep them consistent, or a lane would silently drive the wrong parameter.
+
+## R7 — Persistence
+
+**Decision**: Lane and CV DTOs in `ProjectService` gain optional `Chain` (chain **index** at
+save time) and `Slot`; absent means track-level, so old projects load unchanged. On load, after
+the devices are rebuilt, the index is turned into the chain's uid. Bump the project format
+version. The Arp CC route DTO follows R4.
+
+**Rationale**: chain uids are runtime ids (regenerated on load); the index is stable within a
+saved file.
+
+## R8 — The multi-device clipboard and batch edits
+
+**Decision**: The engine clipboard becomes an ordered list of entries (family + clone), filled
+by `copyDevices(track, set)` and inserted by `pasteDevices(track, midiAt, fxAt)` in one
+publish: MIDI effects at `midiAt`, the instrument replacing the target's (specs/043), audio
+effects at `fxAt`; entries the target can't take are skipped and counted. Single-device copy /
+paste ABI stays as a one-entry wrapper. Rack-chain paste (specs/042) takes the entries that fit
+the chain's sections, instrument skipped.
+Delete, Cut, Duplicate, drag-move within a section and Move to track ▸ for a selection run the
+existing per-device engine calls inside one `undo_group` (highest index first so indices stay
+valid); the instrument in a Move goes last (it removes the source track).
+
+**Rationale**: paste must be one publish for FR-005 (the instrument swap and effect inserts
+together); the other batch edits only remove or reorder, and every intermediate graph is a
+valid chain, so an undo group gives one step without new engine surface.
+
+## R9 — Selection model in the UI
+
+**Decision**: A small `DeviceSelection` class (Nota.App) replaces `_selChainKind` /
+`_selDeviceIndex` / `_instrumentSelected`: an ordered set of `(ChainKind, index)` plus an
+anchor, with `Click`, `ShiftClick`, `ToggleClick`, `Clear`, chain-order ranges
+(MIDI → instrument → audio) and a `GroupShape()` query that returns the rack type or the
+refusal reason (non-contiguous, MIDI + audio without instrument). Indices are remapped after
+each edit from the engine's return values. The rack-chain selection (`_rackSel`, specs/042)
+stays single and still clears the track selection.
+
+**Rationale**: keeps the contiguity / rack-type rules in one testable place (the smoke test
+can drive it headless) and out of the view code.
+
+## R10 — Card UI state across Group / Ungroup
+
+**Decision**: `CardExtra.Wrapped` becomes a list: on Group the rack's extra keeps the grouped
+devices' extras in order; on Ungroup (or Undo) they come back to the restored cards when their
+signature matches, as the single-device case does today.
+
+**Rationale**: FR-013 (A/B snapshots and preset labels survive a round trip).
+
+## R11 — ⌘G routing and menus
+
+**Decision**: Keep the existing focus rule: ⌘G / ⌘⇧G in the Devices panel act on devices,
+elsewhere on tracks. The device menu's **Group into rack** / **Ungroup rack** items move into
+every card's menu (MIDI effects, instrument, audio effects) and are enabled from
+`GroupShape()` / the rack's chain count.
+
+## As built
+
+R4 changed: the Arp's CC target stays on the Arp (nested part added) and is rewritten on a
+clone, as the device-removal path already did — see tasks.md § Implementation notes. R9: the
+selection model is in `Nota.Presentation`. Everything else as above.
+
+## Open risks
+
+- R4 touches Arp persistence; the migration needs a fixture project with an Arp CC lane.
+- R1 widens three structs that are copied with every track snapshot; their size stays small
+ (two extra fields each).
+- Writing new automation from a chain device's knob (arming a lane from inside a rack) stays
+ out of scope: lanes that came in through Group play, show and edit in the Arrangement, but
+ the rack card's knobs don't start new lanes.
diff --git a/specs/044-device-multiselect-group/spec.md b/specs/044-device-multiselect-group/spec.md
new file mode 100644
index 00000000..4ed37957
--- /dev/null
+++ b/specs/044-device-multiselect-group/spec.md
@@ -0,0 +1,258 @@
+# Feature Specification: Multi-select devices and group them into a rack
+
+**Feature Branch**: `feat/device-multiselect-group`
+
+**Created**: 2026-10-27
+
+**Status**: Draft
+
+**Input**: User description: "Device chain: multi-select devices and group them into a rack (GitHub issue nota-daw/nota#328). Goal: select several devices in a chain at once and fold them into a rack so they can be duplicated, macro-mapped and saved as one preset. Today only one device can be selected at a time and there is no "group into rack" command. Wanted: (1) Multi-select devices — Shift-click selects a range, Cmd/Ctrl-click toggles — across MIDI effects, the instrument and audio effects; copy / cut / paste / delete / move act on the whole selection. (2) Group into rack (Cmd/Ctrl+G and the context menu), the rack type chosen from what's selected: only audio effects → Audio Effect Rack; an instrument (with MIDI effects before it and/or audio effects after it) → Instrument Rack whose first chain holds those devices in order; only MIDI effects → MIDI Effect Rack. The selection must be contiguous within its domain; the new rack takes its place in the chain. (3) Ungroup is the reverse. Group and Ungroup are each one undo step. Split out of #326; depends on #327 (selecting the instrument, done), #329 (MIDI effects in Instrument Rack chains, done) and #330 (MIDI Effect Rack, done)."
+
+Issue: nota-daw/nota#328 (split out of #326).
+
+## Clarifications
+
+### Session 2026-10-27
+
+- Q: What happens on Group / Ungroup to automation lanes, sidechain keys, modulation (CV) links and Arp CC lanes on the devices (today #257 refuses to wrap such a device)? → A: They travel with the devices into the rack chain on Group and back out on Ungroup; nothing is refused for having them.
+- Q: What do Delete, Cut and Move to track do when a multi-selection includes the instrument along with effects? → A: Remove the track as in specs/043, but always ask for confirmation first when the selection holds more than the instrument, even if the track has no clips.
+- Q: What does Paste do when the clipboard holds the instrument together with effects and the target is another instrument track? → A: Replace the target's instrument and insert the effects into their sections, as one undo step (specs/043); on a track that can't take an instrument, the instrument and MIDI effects are skipped.
+
+## Nota Context *(fill in — drives plan and tasks)*
+
+**Feature area** *(pick the main one)*:
+
+- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table
+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+What exists today: the track's device chain has one selection (an audio effect, a MIDI
+effect or, since specs/043, the instrument). ⌘G already wraps **one** selected audio effect
+in an Audio Effect Rack and ⌘⇧G unwraps a one-chain Audio Effect Rack (#257), but the engine
+refuses a device that has a sidechain key, automation, a modulation (CV) link or an Arp CC
+lane on it. MIDI effects and the instrument can't be grouped at all, and there is no
+ungroup for an Instrument Rack or a MIDI Effect Rack. The device clipboard holds one device.
+This feature widens the selection to a set, the clipboard to a run of devices, and ⌘G / ⌘⇧G
+to all three rack types. The plan decides how much is engine work (one undo step per group
+/ ungroup, a multi-device clipboard, moving automation into a rack chain).
+
+**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:
+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),
+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR
+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),
+[`FEATURES.md`](../../FEATURES.md).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Group several audio effects into an Audio Effect Rack (Priority: P1)
+
+The user has EQ-8 → Compressor → Saturator → Reverb on a track. They click the Compressor,
+Shift-click the Reverb (three cards now show the selection border) and press ⌘G. The three
+effects are replaced, in place, by one Audio Effect Rack whose single chain holds them in the
+same order with the same settings. The sound doesn't change. The rack can now be duplicated,
+macro-mapped and saved as one preset. ⌘⇧G on the rack puts the three effects back.
+
+**Why this priority**: The core of #328 and the most common case: building an effect chain,
+then wanting to save, duplicate or macro-control it as one unit. Today it means rebuilding
+the chain inside an empty rack device by device.
+
+**Independent Test**: Build the chain above, select Compressor..Reverb, press ⌘G: the chain
+shows EQ-8 → Audio Effect Rack, the rack's chain lists Compressor, Saturator, Reverb with the
+same values, and a rendered clip sounds the same (level within 0.1 dB). One Undo restores the
+four separate cards; ⌘⇧G on the rack does the same.
+
+**Acceptance Scenarios**:
+
+1. **Given** a contiguous selection of two or more audio effects, **When** the user presses ⌘G or picks **Group into rack** in the right-click menu of any selected card, **Then** they are replaced by an Audio Effect Rack at the position of the first one, holding them in one chain, in order, with identical parameters and state; the new rack is selected.
+2. **Given** one selected audio effect, **When** grouped, **Then** it behaves as today (#257): a one-device Audio Effect Rack.
+3. **Given** the grouped rack, **When** the user presses ⌘Z once, **Then** the chain is back exactly as it was, with the same devices selected.
+4. **Given** a one-chain Audio Effect Rack, **When** the user presses ⌘⇧G or picks **Ungroup rack**, **Then** its chain's devices take its place in order, with their settings, as one undo step, and they are selected.
+5. **Given** grouping during playback, **When** the rack replaces the devices, **Then** there is no audible gap, click or level jump on the track.
+
+---
+
+### User Story 2 - Multi-select devices and act on them together (Priority: P1)
+
+In the device chain the user Shift-clicks to extend the selection to a range and ⌘-clicks
+(Ctrl on Windows/Linux) to add or remove a single card. The selection may span MIDI effects,
+the instrument and audio effects. Copy, Cut, Paste, Delete, Duplicate, dragging and
+**Move to track ▸** act on every selected device at once, each as one undo step.
+
+**Why this priority**: Multi-select is the precondition for grouping and is useful on its
+own: deleting or copying half a chain is one action instead of many.
+
+**Independent Test**: On a track with Arp → Volt → EQ-8 → Delay → Reverb, click EQ-8, ⌘-click
+Reverb: two cards are selected. ⌘C, select another instrument track's last effect, ⌘V: EQ-8
+and Reverb land after it, in that order, with their settings. Back on the first track,
+Shift-click from EQ-8 to Reverb and press Delete: all three effects go in one step, and one
+Undo brings them back with their settings.
+
+**Acceptance Scenarios**:
+
+1. **Given** one selected card, **When** the user Shift-clicks another card in the same track chain, **Then** every card between them (inclusive, in chain order MIDI effects → instrument → audio effects) is selected.
+2. **Given** a selection, **When** the user ⌘-clicks (Ctrl-clicks) a card, **Then** that card toggles in or out of the selection and the others stay selected.
+3. **Given** a selection, **When** the user plain-clicks a card, **Then** only that card is selected; clicking empty chain space or pressing Esc clears the selection.
+4. **Given** several selected effects, **When** the user presses ⌘C then ⌘V on another track (or on the same one), **Then** copies of all of them are pasted together, in their original order, each into its own section (MIDI effects among MIDI effects, audio effects among audio effects), after the selected device of that section or at its end; one Undo removes them all.
+5. **Given** several selected effects, **When** the user presses Delete, Backspace or ⌘X, **Then** all of them are removed (⌘X copies first) in one undo step.
+6. **Given** several selected effects, **When** the user presses ⌘D, **Then** each selected run is duplicated right after itself, in one undo step, and the copies become the selection.
+7. **Given** several selected effects of one section, **When** the user drags any selected card's header, **Then** the whole selection moves together to the drop gap, keeping its order, in one undo step.
+8. **Given** a selection, **When** the user picks **Move to track ▸ X**, **Then** every selected device moves to X (appended to its matching sections, in order) in one undo step, following specs/043's rules for what X can take.
+9. **Given** a multi-selection, **When** the user right-clicks a selected card, **Then** the menu acts on the whole selection and its header says how many devices are selected (e.g. "3 devices"); right-clicking an unselected card selects only that card first.
+
+---
+
+### User Story 3 - Group an instrument with its effects into an Instrument Rack (Priority: P2)
+
+The user selects Arp → Volt → Chorus (a MIDI effect, the instrument and an audio effect) and
+presses ⌘G. The track's instrument becomes an Instrument Rack whose first chain is
+Arp → Volt → Chorus, in that order, with the same settings; the track plays the same. Now they
+can add a second chain to layer another sound with the same Arp, map macros across both, and
+save the whole thing as one instrument preset. ⌘⇧G on a one-chain Instrument Rack puts the
+MIDI effects, the instrument and the audio effects back on the track.
+
+**Why this priority**: The step from "a sound I built" to "a layered instrument", the second
+half of #328. It depends on stories 1–2 and on MIDI effects in rack chains (#329, done).
+
+**Independent Test**: Build Arp → Volt → Chorus, select all three, ⌘G: the track's instrument
+is an Instrument Rack with one chain holding Arp, Volt, Chorus. Play a clip: same notes, same
+sound. One Undo restores the three separate devices.
+
+**Acceptance Scenarios**:
+
+1. **Given** a selection containing the instrument plus the MIDI effects directly before it and/or the audio effects directly after it, **When** grouped, **Then** the track's instrument becomes an Instrument Rack whose first chain holds those devices in order; unselected MIDI effects before and audio effects after stay on the track, around the rack.
+2. **Given** only the instrument selected, **When** grouped, **Then** it becomes a one-chain Instrument Rack holding just that instrument.
+3. **Given** a one-chain Instrument Rack as the track's instrument, **When** ungrouped, **Then** its chain's MIDI effects go after the track's own MIDI effects, its instrument becomes the track's instrument, and its audio effects go before the track's own audio effects, in one undo step.
+4. **Given** the instrument is a kind an Instrument Rack chain can't hold (an Instrument Rack itself, or anything else the rack refuses per specs/040–041), **When** the user tries to group, **Then** nothing changes and the status line says why.
+5. **Given** a grouped Instrument Rack, **When** the user saves it as a preset and loads it on another track, **Then** that track gets the same chain with the same settings.
+
+---
+
+### User Story 4 - Group MIDI effects into a MIDI Effect Rack (Priority: P3)
+
+The user selects Chord → Scale → Arp and presses ⌘G: they become one MIDI Effect Rack in the
+MIDI effect section, with one chain holding them in order. ⌘⇧G reverses it.
+
+**Why this priority**: Same gesture for the third rack type; less common than audio-effect
+and instrument grouping.
+
+**Independent Test**: Select three MIDI effects, ⌘G: the MIDI section shows one MIDI Effect
+Rack; its chain lists the three with the same values; the clip plays the same notes. Undo and
+⌘⇧G both restore them.
+
+**Acceptance Scenarios**:
+
+1. **Given** a contiguous selection of one or more MIDI effects only, **When** grouped, **Then** they become a MIDI Effect Rack at the position of the first one, in one chain, in order, with identical settings.
+2. **Given** a one-chain MIDI Effect Rack, **When** ungrouped, **Then** its devices take its place in order, in one undo step.
+
+---
+
+### Edge Cases
+
+- **Non-contiguous selection** (e.g. EQ-8 and Reverb with Delay between them unselected): **Group into rack** is disabled in the menu and ⌘G says "Select devices next to each other to group them" in the status line.
+- **MIDI effects and audio effects selected without the instrument**: can't be grouped (no rack type holds both without an instrument); status line says why.
+- **Instrument selection whose MIDI part doesn't end at the instrument or whose audio part doesn't start right after it**: not contiguous; refused as above.
+- **A rack in the selection** (an Audio Effect Rack, MIDI Effect Rack or Drum Rack among the effects): racks can't nest inside rack chains (specs/041 allows only a Drum Rack as a chain's instrument); refused with a reason naming the rack.
+- **A plug-in effect in the selection**: grouped like a built-in where the target rack hosts plug-ins (Audio Effect Rack, Instrument Rack chains); refused with a reason where it doesn't (MIDI Effect Rack).
+- **A plug-in instrument** in an Instrument Rack group: grouped with its plug-in state where rack chains can host it; refused with a reason otherwise.
+- **Devices with automation, a sidechain key, a modulation (CV) link or an Arp CC lane**: grouped and ungrouped like any other device; the lanes, key and links follow the device into the rack chain and back out (FR-016). Automation keeps playing during and after the move.
+- **Ungroup on a rack with two or more chains**: disabled; status line says only a one-chain rack can be ungrouped (as today).
+- **Ungroup of a rack with macro mappings**: the macros go away with the rack; the devices keep their current parameter values; one Undo restores the rack with its mappings.
+- **Ungroup of a rack whose chain has a key/velocity zone, chain volume, pan or transpose other than default**: the chain's mix settings are dropped (the sound may change) and the status line says so (FR-019).
+- **Selection with a folded card**: folded cards are selectable and grouped like unfolded ones; the new rack card opens unfolded.
+- **Selection and track switch**: switching tracks clears the selection; the clipboard survives (as today).
+- **Paste of a multi-device clipboard where some devices don't fit** (MIDI effects onto an audio track): the ones that fit are pasted, the rest are skipped, and the status line names how many were skipped; if none fit, nothing changes.
+- **Pasting a multi-device clipboard into a rack chain** (specs/042): same per-section rules; the instrument is skipped.
+- **Delete / Cut / Move with the instrument in the selection**: the whole track is removed as in specs/043, and the other selected devices go with it; with more than the instrument selected the confirmation always appears (FR-009), so a Shift-click range that swept over the instrument can't silently delete the track.
+- **Paste of Arp → Volt → Chorus onto another instrument track**: that track's instrument becomes the Volt copy, Arp and Chorus land in their sections, one undo step (FR-005).
+- **Typing in a rename box or value entry**: ⌘G, Delete and the clipboard keys never act on devices.
+- **⌘G while the arrangement or track headers have focus**: still groups tracks, not devices (as today).
+- **Rack chain devices** (inside a rack card) keep their own single selection; multi-select is the track chain only.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+**Selection**
+
+- **FR-001**: The track's device chain MUST support selecting several devices at once across MIDI effects, the instrument and audio effects. Plain click selects one card; Shift-click selects the range from the anchor (the last plain- or ⌘-clicked card) to the clicked card in chain order; ⌘-click (Ctrl-click on Windows/Linux) toggles one card.
+- **FR-002**: Every selected card MUST show the existing selection border; the anchor needs no separate look.
+- **FR-003**: Esc, a click on empty chain space, a track switch, or selecting a device in a rack chain MUST clear the track chain's selection.
+
+**Acting on the selection**
+
+- **FR-004**: Copy (⌘C) MUST put every selected device on the device clipboard, in chain order, with full parameters and state. The clipboard holds one or more devices.
+- **FR-005**: Paste (⌘V) MUST insert the clipboard's devices into their matching sections of the target chain (MIDI effects / instrument / audio effects), keeping order, after that section's last selected device or at its end, as one undo step. An instrument on the clipboard (alone or with effects) replaces the target's instrument as specs/043 FR-004 says, in the same undo step as the effects' insertion. Devices the target can't take (on an audio, return, group or master track: the instrument and MIDI effects) are skipped with a status-line count.
+- **FR-006**: Delete / Backspace and Cut (⌘X) MUST remove every selected device in one undo step; Duplicate (⌘D) MUST duplicate each contiguous run of selected effects right after itself in one undo step.
+- **FR-007**: Dragging the header of a selected card MUST move the whole selection when all selected cards are in that card's section; the selection keeps its order and lands at the drop gap in one undo step. A selection spanning sections drags only the grabbed card's section's devices.
+- **FR-008**: **Move to track ▸** MUST move every selected device to the target track in one undo step, each landing at the end of its matching section, following specs/043 FR-013 for what the target can take and what travels.
+- **FR-009**: When the instrument is in the selection, Delete, Cut and Move MUST follow specs/043 FR-005 (the source track is removed; the other selected devices go with it). When the selection holds the instrument plus at least one other device, a confirmation naming the track MUST appear every time, even if the track has no clips; the instrument alone keeps specs/043's rule (confirm only when the track has clips).
+- **FR-010**: The right-click menu of a selected card MUST act on the whole selection and show the selection's size in its header; right-clicking an unselected card first makes it the only selection.
+
+**Group into rack**
+
+- **FR-011**: **Group into rack** (⌘G with the Devices panel focused, and in the device context menu) MUST pick the rack type from the selection:
+ - only audio effects → **Audio Effect Rack**, placed where the first selected effect was;
+ - the instrument, optionally with the MIDI effects directly before it and/or the audio effects directly after it → **Instrument Rack** as the track's instrument, its first chain holding those devices in order (MIDI effects → instrument → audio effects);
+ - only MIDI effects → **MIDI Effect Rack**, placed where the first selected MIDI effect was.
+- **FR-012**: Group MUST require a contiguous selection: within each section the selected devices are adjacent, and in an instrument group the MIDI part ends at the instrument and the audio part starts right after it. Any other selection (gaps, MIDI + audio effects without the instrument) MUST change nothing, with **Group into rack** disabled in the menu and a status-line reason on ⌘G.
+- **FR-013**: Grouped devices MUST keep their parameters, state, bypass, fold state and A/B snapshots / preset labels; the track MUST sound the same right after grouping.
+- **FR-014**: Group MUST refuse, with a reason, a selection that contains something the target rack's chain can't hold (a rack inside a rack beyond specs/041's nested Drum Rack, a plug-in where the rack can't host one, an instrument kind the Instrument Rack refuses).
+- **FR-015**: The new rack MUST be selected, unfolded, with one chain named after its first device (or the instrument for an Instrument Rack), default macros (none mapped) and default rack settings.
+- **FR-016**: Automation lanes, sidechain keys, modulation (CV) links, outer-rack / track macro mappings and Arp CC lanes on grouped devices MUST follow the devices into the rack chain on Group, and back to the track chain on Ungroup, still driving the same parameters; the #257 refusal for such devices goes away. Undo restores them where they were.
+
+**Ungroup**
+
+- **FR-017**: **Ungroup rack** (⌘⇧G and the context menu) MUST work on a one-chain Audio Effect Rack, Instrument Rack (as the track's instrument) and MIDI Effect Rack, putting the chain's devices back in the rack's place in order (for an Instrument Rack: MIDI effects after the track's own, its instrument as the track's instrument, audio effects before the track's own). The restored devices become the selection.
+- **FR-018**: Ungroup MUST be disabled (with a status-line reason on ⌘⇧G) for a rack with two or more chains, a Drum Rack, or a nested Drum Rack in a chain.
+- **FR-019**: On Ungroup the rack's macros, macro mappings, chain mix (volume, pan, transpose, zones) and rack settings are dropped; the devices keep their current parameter values. The status line says what was dropped when anything non-default was.
+
+**Undo, persistence, sync**
+
+- **FR-020**: Every Group, Ungroup and multi-device Copy-Paste / Cut / Delete / Duplicate / drag / Move MUST be exactly one undo step; Undo restores the chain, the devices' state and the selection.
+- **FR-021**: A grouped rack MUST save and reopen with the project, and save / load as a preset (Audio Effect Rack and MIDI Effect Rack presets; Instrument Rack as an instrument preset) like any rack built by hand.
+- **FR-022**: Grouping or ungrouping during playback MUST NOT cause an audible gap, click or dropout on that track or others.
+- **FR-023**: The MCP device tools MUST be able to group a contiguous range of devices into a rack and ungroup a rack, matching the UI's rules and reasons.
+- **FR-024**: The Preferences → Shortcuts list (Shift-click, ⌘-click, ⌘G, ⌘⇧G in the Devices panel), `CHANGELOG.md`, `FEATURES.md` and the user docs MUST reflect the new gestures and commands.
+- **FR-025**: Selection borders, the disabled menu items and the multi-selection menu header MUST follow the Studio design language in all four themes.
+
+### Key Entities *(include if feature involves data)*
+
+- **Device selection**: a set of devices on one track's chain (MIDI effects, the instrument, audio effects) plus an anchor for Shift-click ranges. Lives in the panel, not in the project.
+- **Device clipboard**: now an ordered run of one or more devices (each an audio effect, MIDI effect or instrument, with full state), shared by the track chain and rack chains.
+- **Group**: a contiguous selection turned into one new rack of the matching type, in place, with one chain holding the devices in order; one undo step.
+- **Ungroup**: a one-chain rack replaced by its chain's devices, in place; one undo step.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: Folding N adjacent devices into a rack takes 3 actions (click, Shift-click, ⌘G) regardless of N, down from creating an empty rack and re-adding N devices by hand.
+- **SC-002**: Grouping and then ungrouping (or grouping and undoing) returns a chain whose devices, order and parameter values are identical to the original, for 100% of built-in device kinds the rack chains can hold.
+- **SC-003**: A clip rendered before and after Group matches within 0.1 dB peak and RMS for every rack type.
+- **SC-004**: Copying, deleting or moving N devices is one action and one undo step, instead of N.
+- **SC-005**: Every invalid Group / Ungroup attempt leaves the project unchanged and shows a reason; no attempt leaves a half-built rack.
+- **SC-006**: No audible dropout on any track while grouping or ungrouping during playback.
+
+## Assumptions
+
+- Multi-select covers the track's device chain only; devices inside a rack card keep the single selection of specs/042.
+- Shift-click ranges follow the chain's visual order (MIDI effects → instrument → audio effects); a range may cross sections.
+- Pasting a multi-device clipboard spreads it by section, as single-device paste does today; the clipboard keeps no gaps between devices copied from non-adjacent positions.
+- Group creates one chain; adding more chains afterwards uses the rack's existing controls.
+- Ungroup stays limited to one-chain racks (as #257 today); flattening parallel chains has no single correct order.
+- Grouping an Instrument Rack inside an Instrument Rack chain stays out of scope (specs/041), so selecting an Instrument Rack instrument and pressing ⌘G is refused.
+- ⌘G / ⌘⇧G keep their meaning per focus: device grouping in the Devices panel, track grouping in the arrangement and track headers.
+- Links that target a grouped device (automation, CV, sidechain key, Arp CC, macro mappings from outside) follow it (FR-016); links that belong to the removed rack itself (its own macros and chain mix) are dropped on Ungroup (FR-019).
+
+## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*
+
+- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)
+- [ ] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned
+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5)
+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`
+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`
+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)
+- [ ] UI change → follows `DESIGN.md` (Studio design language)
diff --git a/specs/044-device-multiselect-group/tasks.md b/specs/044-device-multiselect-group/tasks.md
new file mode 100644
index 00000000..8811e233
--- /dev/null
+++ b/specs/044-device-multiselect-group/tasks.md
@@ -0,0 +1,184 @@
+---
+
+description: "Task list for multi-select devices and group them into a rack"
+---
+
+# Tasks: Multi-select devices and group them into a rack
+
+**Input**: Design documents from `specs/044-device-multiselect-group/`
+
+**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),
+[data-model.md](data-model.md), [contracts/](contracts/), [quickstart.md](quickstart.md)
+
+**Tests**: The constitution (IV) requires smoke coverage for engine behaviour changes and
+every new C ABI call, so smoke tasks are included.
+
+**Organization**: Grouped by user story; the nested address (Phase 2) and the engine group /
+ungroup (Phase 3) block every story.
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependencies)
+- **[Story]**: US1 audio-effect group, US2 multi-select, US3 Instrument Rack, US4 MIDI Effect Rack
+
+## Path Conventions
+
+- Engine: `src/native/nota.engine/` (`E/` below = `src/native/nota.engine/src/engine/`)
+- C ABI: `src/native/nota.engine/include/nota/nota_engine.h`, wrappers in `src/native/nota.engine/src/abi/`
+- Managed: `src/managed/<Project>/`; Smoke: `tests/Nota.SmokeTest/`
+
+---
+
+## Phase 1: Setup
+
+- [X] T001 Create `src/native/nota.engine/src/engine/ParamPath.h` (SPDX header) with `struct ParamPath { int32_t host = -1; uint64_t chainUid = 0; int32_t slot = -1; }`, `isNested()`, equality; add it to the engine target in `src/native/nota.engine/CMakeLists.txt` if headers are listed
+
+---
+
+## Phase 2: Foundational — the nested parameter address (R1, R2, R4, R5, R6, R7)
+
+**Purpose**: Let automation, CV links, Arp CC routes and sidechain keys point at a device
+inside a rack chain. No behaviour changes until Group creates such paths.
+
+- [X] T002 Add `RackCore` audio-thread-safe lookups in `src/native/nota.engine/src/devices/racks/RackCore.h`: `chainIndexOfUid(uint64)`, `childDevice(uint64 chainUid, int32 slot)` → `Device*`, `childMidi(uint64, slot)` → `MidiDevice*`, `childInstrument(uint64)` → `Instrument*`, all reading `live()` without allocation; plus `chainUidAt(int32 index)` for the message thread
+- [X] T003 Add `Engine::resolveParamOwner(Track&, host, chainUid, slot, Device*&, MidiDevice*&, Instrument*&)` in `E/Engine_Automation.cpp` (declared in `E/Engine.h`): chainUid 0 = today's lookup (host ≥ 0 audio effect, −1 instrument, MIDI per target kind); otherwise the rack at `host` (`RackDevice`, `RackInstrument` at −1, or `MidiRack` among MIDI effects) and its child per T002
+- [X] T004 Add `chainUid` + `slot` to `AutomationLane` in `E/Automation.h`; route `applyAutomation` in `E/Engine_Automation.cpp` through `resolveParamOwner` for DeviceParam / MidiDeviceParam / PluginParam lanes when `chainUid != 0`
+- [X] T005 Add `sourceChainUid/sourceSlot` and `targetChainUid/targetSlot` to `CvLink` in `E/Modulation.h` (copy-assignment in `Modulation.cpp` too); make `targetValid/targetGet/targetSet` and the Param-source read in `applyModulation` (`E/Engine_Modulation.cpp`) resolve nested paths
+- [X] T006 Move the Arp CC destination into the snapshot: add `struct CcRoute { int32_t arpHost; uint64_t arpChainUid; int32_t arpSlot; ParamPath target; int32_t param; }` and `std::vector<CcRoute> ccRoutes` on `Track` (`E/Track.h`, cloned with the track); rewrite `applyMidiCcRouting` in `E/Engine_Render.cpp` to iterate routes, resolving the Arp (track MIDI effect, or a MIDI effect in a `MidiRack` / Instrument Rack chain) and the target; keep `MidiDevice::ccValue/ccDepth` as the source
+- [X] T007 Re-implement the existing Arp CC set/get engine methods (`setMidiEffectCcDest` and getters behind `nota_*_cc_dest*` in `src/native/nota.engine/src/abi/` and `E/Engine_Devices.cpp`) on `Track::ccRoutes` with an undo checkpoint; drop `MidiDevice::ccDestDevice/setCcDest` use in the engine (`src/native/nota.engine/src/devices/MidiDevice.h` keeps the virtuals only if devices still need them)
+- [X] T008 Make MIDI-effect and device remaps keep `ccRoutes` valid: in `remapAutomationAfterDeviceChange` (`E/Engine_Automation.cpp`) or a sibling `remapCcRoutesAfterDeviceChange`, shift / drop routes whose Arp host (midi=true) or target host (midi=false) moved or was removed; call it everywhere `remapAutomationAfterDeviceChange` is called (`E/Engine_Devices.cpp`, `E/Engine_Rack.cpp`)
+- [X] T009 Replace `Engine::deviceIsReferenced` users: `deviceIsReferenced` reads `ccRoutes` instead of `md->ccDestDevice()` (`E/Engine_Rack.cpp`)
+- [X] T010 Sidechain inside racks (R5): add `RackCore::forEachChild(fn)` over `live()` chains (devices, MIDI, instrument); in `E/Engine_Render.cpp` (`processLeafDevices`, the `LeafPath::Instrument` branch and the two other sidechain feeds ~2428 / ~2501) feed keyed children of `RackDevice` devices and of a `RackInstrument` instrument; extend the route-bus claims in `E/Engine_Devices.cpp` (~1370) to claim children's sources
+- [X] T011 Rack-edit consistency (R6): add `Engine::remapPathsAfterRackEdit(Track& nt, int32 host, uint64 chainUid, int32 removedSlot, int32 fromSlot, int32 toSlot, bool chainRemoved, bool midiSlot)` in `E/Engine_Rack.cpp` that drops / shifts nested lanes, CV links and CC routes; call it from rack chain delete, chain-device delete / move / cross-chain move (specs/042 paths in `E/Engine_Rack.cpp`), and from replacing the rack's chain instrument
+- [X] T012 C ABI for nested lane / link / route addresses in `include/nota/nota_engine.h` + `src/abi/nota_engine_automation.cpp` (and the CV / CC abi files): `nota_track_automation_lane_path`, `nota_track_add_nested_automation_lane`, CV-link path get/set, CC-route path get/set (chain index ↔ uid conversion via T002) — signatures per [contracts/c-abi.md](contracts/c-abi.md)
+- [X] T013 [P] Managed interop for T012: `src/managed/Nota.Infrastructure/Interop/NativeMethods.Automation.cs`, `NotaEngine.Automation.cs` (+ CV / devices files), `src/managed/Nota.Application/Engine/IAudioEngine.cs`, `EngineContracts.cs`
+- [X] T014 Persistence (R7): `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs` — `AutomationLaneDto.Chain/Slot`, CV DTO `SourceChain/SourceSlot/TargetChain/TargetSlot`, track-level `CcRoutes` list (`ArpHost, ArpChain, ArpSlot, TargetHost, TargetChain, TargetSlot, Param`); `ProjectService.cs` saves them (chain **index**), loads them after devices are rebuilt, reads the legacy per-MIDI-effect `CcDestDevice/CcDestParam` when `CcRoutes` is absent; bump the format version with a comment
+- [X] T015 Smoke: `tests/Nota.SmokeTest/DeviceGroupTests.cs` (SPDX) part 1 — an existing project with an Arp CC lane loads and still drives its target; undo / redo of a CC destination change restore it (the route is in the snapshot); register `--device-group` in `tests/Nota.SmokeTest/Program.cs` and add the class to the full run
+
+**Checkpoint**: Build + smoke green; nothing visible changed.
+
+---
+
+## Phase 3: Foundational — engine Group / Ungroup and the multi-device clipboard (R3, R8)
+
+- [X] T016 `RackCore::setChainInstrumentInstance(chain, std::shared_ptr<Instrument>, bool prepare=false)` in `src/native/nota.engine/src/devices/racks/RackCore.h/.cpp` (bumps the chain's instrument generation like `setChainInstrument`)
+- [X] T017 `Engine::groupDevices(trackId, midiFirst, midiCount, withInstrument, fxFirst, fxCount)` in `E/Engine_Rack.cpp`: validate (codes −2…−7 of contracts/c-abi.md: contiguity, "MIDI run ends at last MIDI effect / audio run starts at 0" with the instrument, no rack in the run, no plug-in into a `MidiRack`, instrument not an Instrument Rack, instrument track), build the rack off-graph moving instances with `prepare=false`, then in one cloned track: replace the run, rewrite lanes / CV links / CC routes / (sidechain needs nothing) to nested paths, shift indices of later devices (`remapAutomationAfterDeviceChange`, CC routes), publish once (`republishWithTrack`), then fix CV links (`remapCvLinksAfterDeviceChange` generalised to rewrite into paths), `recomputePdc()`
+- [X] T018 Instrument branch of T017: new `RackInstrument` with chain 0 = MIDI effects (`addChainMidiDeviceInstance`), instrument (T016), audio effects (`addChainDeviceInstance`, prepare=false); swap via the `replaceTrackInstrument` internals inside the same publish; `RackInstrument::adoptUid` not used (new device)
+- [X] T019 `Engine::ungroupRack(trackId, family, index, int32_t* outDropped)` in `E/Engine_Rack.cpp`: one-chain `RackDevice` / `MidiRack` / `RackInstrument` (not `DrumRack`), splice the chain's instances back (instrument via the replace internals), rewrite nested paths to track-level, shift later indices, report macro-mapping / non-default chain-mix drops, publish once
+- [X] T020 Rewrite `wrapDeviceInRack` / `unwrapRack` as wrappers over T017 / T019 (no more `deviceIsReferenced` refusal) in `E/Engine_Rack.cpp`
+- [X] T021 Multi-device clipboard in `E/Engine_Devices.cpp` + `E/Engine.h`: `std::vector<ClipEntry> clip_` replacing `clipDevice_ / clipMidi_ / clipInstrument_` (single-copy calls fill one entry); `copyDevices(track, midiIdx, withInstrument, fxIdx)`, `clipboardCount()`, `clipboardKind()` returns 4 for several; `pasteDevices(track, midiAt, fxAt, int* skipped)` clones all first (−3 on any failure, nothing changed), then inserts MIDI effects / replaces the instrument / inserts audio effects in one cloned track and one publish; rack-chain paste (specs/042) takes the fitting entries
+- [X] T022 C ABI: `nota_track_group_devices`, `nota_track_ungroup_rack`, `nota_track_copy_devices`, `nota_device_clipboard_count`, `nota_track_paste_devices` in `include/nota/nota_engine.h` + `src/abi/nota_engine_device.cpp`; update the comment on `wrap/unwrap` and `clipboard_kind`
+- [X] T023 [P] Managed interop for T022: `NativeMethods.Devices.cs`, `NotaEngine.Devices.cs`, `IAudioEngine.cs` (`GroupDevices`, `UngroupRack`, `CopyDevices`, `DeviceClipboardCount`, `PasteDevices`) and any test doubles implementing `IAudioEngine`
+- [X] T024 Smoke `DeviceGroupTests.cs` part 2: for each rack type — group, render a bar before / after (peak & RMS within 0.1 dB), rack contents and params identical, undo restores, ungroup restores; each refusal code; an automated / CV-linked / keyed / Arp-CC-driven device keeps acting after group and after ungroup; save → reload of a grouped project with a nested lane; multi copy / paste incl. instrument replace and skips on an audio track; update `DeviceCopyTests.cs` expectations that relied on the old wrap refusal
+
+**Checkpoint**: Engine complete; every new ABI call covered by smoke.
+
+---
+
+## Phase 4: User Story 1 — group audio effects into an Audio Effect Rack (P1) 🎯 MVP
+
+**Goal**: ⌘G / menu groups one or a contiguous range of audio effects; ⌘⇧G ungroups.
+**Independent test**: quickstart step 1.
+
+- [X] T025 [US1] `CardExtra.Wrapped` → `List<CardExtra>? Wrapped` in `src/managed/Nota.App/DeviceChainView.Shell.cs` (R10); keep the single-device restore path working through the list
+- [X] T026 [US1] Rewrite `GroupSelectedDevice` / `UngroupSelectedDevice` in `src/managed/Nota.App/DeviceChainView.Clipboard.cs` on `GroupDevices` / `UngroupRack`: extras moved into / out of the rack's `Wrapped` list, indices after the run shifted (`ExtrasMoved` / `ExtrasRemoved`), the new rack (or restored devices) selected, status lines and refusal messages per [contracts/ui.md](contracts/ui.md)
+
+---
+
+## Phase 5: User Story 2 — multi-select and batch actions (P1)
+
+**Goal**: Shift-click / ⌘-click selection across MIDI effects, instrument and audio effects;
+batch Copy / Cut / Paste / Delete / Duplicate / drag / Move to track ▸; Group on a range.
+**Independent test**: quickstart steps 3–4.
+
+- [X] T027 [P] [US2] `src/managed/Nota.App/DeviceSelection.cs` (SPDX): ordered members of `(ChainKind, index)` + anchor; `Click`, `ShiftClick`, `ToggleClick`, `Clear`, `Contains`, chain-order ranges given counts (MIDI 0..m−1 → instrument → audio 0..n−1); `GroupShape(midiCount, fxCount)` → AudioRack / MidiRack / InstrumentRack / Refused(reason) per [data-model.md](data-model.md) § Group shape; `Remap(kind, Func<int,int>)` after edits
+- [X] T028 [P] [US2] Smoke `tests/Nota.SmokeTest/DeviceSelectionTests.cs` (SPDX): ranges across sections, toggles, anchor, every GroupShape row incl. refusals; run under `--device-group`
+- [X] T029 [US2] Replace `_selChainKind / _selDeviceIndex / _instrumentSelected` with a `DeviceSelection` in `DeviceChainView.Clipboard.cs`; `HasDeviceSelection` / `HasEffectSelection` / `SelectDevice` / `ClearDeviceSelection` on top of it; card borders from `Contains` in `DeviceChainView.Shell.cs`, `DeviceChainView.Instruments.cs`, `DeviceChainView.Midi.cs`, `DeviceChainView.Fold.cs`
+- [X] T030 [US2] Click modifiers: plain / Shift / ⌘ (Ctrl on Windows / Linux) on card headers and bodies in the same files; Esc and empty-space click clear; right-click on an unselected card selects only it
+- [X] T031 [US2] Batch Copy / Cut / Paste via `CopyDevices` / `PasteDevices` (status "Pasted N, skipped M"); Delete / Cut / Duplicate over the selection inside `UndoGroupBegin/End`, highest index first, extras remapped; confirmation dialog when the selection holds the instrument and another device (always) in `DeviceChainView.Clipboard.cs`
+- [X] T032 [US2] Drag a selected card's header: move every selected card of that section to the drop gap in order, inside one undo group, in `DeviceChainView.Clipboard.cs` (drag section) / `DeviceChainView.Move.cs`
+- [X] T033 [US2] Move to track ▸ for a selection in `DeviceChainView.Move.cs`: every selected device via `TransferDevice` inside one undo group, the instrument last with the specs/043 confirmation (always when more than the instrument is selected)
+- [X] T034 [US2] Context menu for a selection: "N devices" header, Save preset only for one device, Group into rack enabled from `GroupShape`, Ungroup rack on a one-chain rack of any type, Delete / Delete track; ⌘G on a range calls Group with the run (`DeviceChainView.Clipboard.cs`)
+
+---
+
+## Phase 6: User Story 3 — Instrument Rack (P2)
+
+**Independent test**: quickstart step 5.
+
+- [X] T035 [US3] Group with the instrument from the UI: the `InstrumentRack` shape calls `GroupDevices(…, withInstrument: true, …)`; extras of the instrument (key −1) and the grouped effects into the new instrument card's `Wrapped`; the rack card is selected and unfolded (`DeviceChainView.Clipboard.cs`, `DeviceChainView.Instruments.cs`)
+- [X] T036 [US3] Ungroup on a one-chain Instrument Rack instrument (menu + ⌘⇧G): `UngroupRack(family 2)`; restored MIDI effects / instrument / audio effects selected with their extras
+
+---
+
+## Phase 7: User Story 4 — MIDI Effect Rack (P3)
+
+**Independent test**: quickstart step 6.
+
+- [X] T037 [US4] Group / Ungroup for MIDI-effect runs and `MidiRack` cards in `DeviceChainView.Clipboard.cs` / `DeviceChainView.Midi.cs` (extras keyed by `ExtraKey(Midi, i)`)
+
+---
+
+## Phase 8: Polish & cross-cutting
+
+- [X] T038 [P] Nested lane titles in `src/managed/Nota.App/ArrangementView.Automation.cs` ("‹Rack› › ‹Device› · ‹Param›") from `AutomationLanePath` and the rack chain device / param name calls
+- [X] T039 [P] MCP `group_devices` and `ungroup_rack` in `src/managed/Nota.Mcp/Tools/DeviceTools.cs` per [contracts/mcp.md](contracts/mcp.md)
+- [X] T040 [P] Preferences → Shortcuts: Shift-click, ⌘/Ctrl-click, ⌘G, ⌘⇧G in the Devices panel (nota-shortcuts skill)
+- [X] T041 `CHANGELOG.md` `[Unreleased]` Added entry; FEATURES.md (nota-features skill); user docs (nota-docs skill)
+- [X] T042 `scripts/build.sh` green (smoke incl. `--device-group`, perf gate); run quickstart in the app with `NOTA_DATA_DIR`, all four themes
+
+---
+
+## Implementation notes (deviations, 2026-10-27)
+
+- T006–T008: the Arp's CC target stays on the Arp, gaining a nested (chain uid, slot) part; a
+ rewrite (group, ungroup, an edit inside a rack) replaces the Arp with a clone, the existing
+ undo-safe pattern of the device-removal path, instead of moving routes into `Track`. Saved
+ per MIDI effect (`CcDestChain/CcDestSlot`) and, for Arps inside racks, in the track's
+ `NestedCcRoutes`; chain children's sidechain keys in `NestedSidechains` (v25).
+- T021: a rack chain's Paste of several devices came with T045 (`nota_rackdev_chain_paste_devices`).
+- T025: `CardExtra.Wrapped` stays for the one-device case (undo / redo swaps it, as before); a
+ multi-device group keeps the extras in `WrappedMany`, restored by Ungroup and (T046) by Undo.
+- T043: Arps inside racks (a MIDI Effect Rack, Instrument Rack chains) get their CC target
+ rewritten too: the rack is forked with a clone of the Arp (`rewriteRackArps`).
+- T027: `DeviceSelection` lives in `Nota.Presentation` (the smoke test doesn't reference
+ `Nota.App`); its section enum is `DeviceSection` (`ChainSection` is the palette's).
+- T033: multi-device drags out of the panel onto a track header still carry one device.
+- T041: user docs (nota-docs, the sibling repo) not updated yet.
+
+## Dependencies & Execution Order
+
+- Phase 1 → Phase 2 → Phase 3 → user stories. Phase 2's T002–T003 first; T004–T011 depend on
+ them; T012–T014 after T004–T008; T015 last.
+- US1 (Phase 4) needs Phase 3. US2 needs Phase 3 (clipboard) and builds on US1's Group code.
+ US3 and US4 need US2's selection (T027–T030).
+- Polish after the stories; T038–T040 can run in parallel.
+
+### Parallel opportunities
+
+- T013 with T014 (different managed files) once T012's signatures are fixed.
+- T023 with T024 once T022 is in.
+- T027 + T028 (new files) alongside T025–T026.
+- T038, T039, T040 together.
+
+## Implementation Strategy
+
+MVP = Phases 1–4 (nested address, engine group / ungroup, ⌘G on audio-effect runs): the most
+common case (#328's headline) works with links travelling. Then US2 (multi-select and batch
+actions), US3, US4, polish. Each phase ends with a build + smoke run.
+
+---
+
+## Phase 9: Convergence
+
+- [X] T043 Extend `tests/Nota.SmokeTest/DeviceGroupTests.cs` to call `nota_rack_chain_midi_cc_dest` / `nota_rack_chain_midi_set_cc_dest`: group an Arp whose CC lane drives an audio effect into a MIDI Effect Rack, check its CC target and that it still drives the effect after a render, then save → reload and check `NestedCcRoutes` brings it back per Constitution IV (partial)
+- [X] T044 Name the new rack's chain after its first device (the instrument for an Instrument Rack) in `groupDevices`, `src/native/nota.engine/src/engine/Engine_Rack.cpp`, and assert the name in `DeviceGroupTests.cs` per FR-015 (partial)
+- [X] T045 Let a rack chain's Paste take a multi-device clipboard: the entries that fit the chain's sections, the instrument skipped, one undo step (`rackChainDevicePaste` / `rackChainMidiPaste` in `src/native/nota.engine/src/engine/Engine_Rack.cpp`), with a smoke check per FR-005 / spec Edge Cases (partial)
+- [X] T046 After Undo / Redo of a multi-device Group, give the restored cards their A/B snapshots and preset labels back from the rack card's `WrappedMany` (match by signature in `ExtraFor`, `src/managed/Nota.App/DeviceChainView.Shell.cs`) per FR-013 / FR-020 (partial)
+- [X] T047 Add render checks for the MIDI Effect Rack and Instrument Rack groups (same notes / level within 0.1 dB against an ungrouped twin engine, a deterministic instrument such as Sampler) in `DeviceGroupTests.cs` per SC-003 (partial)
+
+---
+
+## Phase 10: Convergence
+
+- [ ] T048 After ⌘Z / ⌘⇧Z of a device edit made in the Devices panel (group, ungroup, a batch delete or paste), select the devices the edit is undone back to, instead of letting the selection fall away (`src/managed/Nota.App/DeviceChainView.Clipboard.cs`) per FR-020 (partial)
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index cb18bff8..be506843 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -22,7 +22,7 @@ public sealed partial class ArrangementView
// --- parameter automation (M9-A3) --------------------------------------
internal bool AutomationModeActive => _automationMode;
- private string AutoLabelFor(TrackVM t) => t.AutoTarget switch
+ private string AutoLabelFor(TrackVM t) => t.AutoChain >= 0 && _engine is { } ne ? Short(NestedParam(ne, t).Name) : t.AutoTarget switch
{
AutomationTarget.Volume => "Vol",
AutomationTarget.Pan => "Pan",
@@ -35,7 +35,8 @@ public sealed partial class ArrangementView
private static string Short(string s) => s.Length <= 10 ? s : s.Substring(0, 10);
/// <summary>Value range of a track's current automation target (plugin params are 0..1).</summary>
- internal (float min, float max) AutoRange(TrackVM t) => t.AutoTarget switch
+ internal (float min, float max) AutoRange(TrackVM t) => t.AutoChain >= 0 && _engine is { } ne
+ ? (NestedParam(ne, t).Min, NestedParam(ne, t).Max) : t.AutoTarget switch
{
AutomationTarget.Volume => (0f, 2f),
AutomationTarget.Pan => (-1f, 1f),
@@ -51,7 +52,7 @@ public sealed partial class ArrangementView
};
/// <summary>Current live value of the target (baseline when the lane has no points).</summary>
- internal float AutoCurrent(TrackVM t) => t.AutoTarget switch
+ internal float AutoCurrent(TrackVM t) => t.AutoChain >= 0 && _engine is { } ne ? NestedParam(ne, t).Value : t.AutoTarget switch
{
AutomationTarget.Volume => t.Volume,
AutomationTarget.Pan => t.Pan,
@@ -73,11 +74,17 @@ public sealed partial class ArrangementView
private int FindAutoLane(TrackVM t)
{
if (_engine is not { } e) return -1;
+ if (t.AutoChain >= 0 && NestedLaneStill(e, t, t.AutoLane)) return t.AutoLane;
int n = e.AutomationLaneCount(t.Id);
for (int i = 0; i < n; i++)
{
var info = e.AutomationLaneInfo(t.Id, i);
- if (info.Target != t.AutoTarget) continue;
+ if (info.Target != t.AutoTarget || e.AutomationLanePath(t.Id, i) != (t.AutoChain, t.AutoSlot)) continue;
+ if (t.AutoChain >= 0) // a lane into a rack: its param index is resolved (specs/044)
+ {
+ if (info.DeviceIndex == t.AutoDeviceIndex && info.ParamIndex == t.AutoParamIndex) return i;
+ continue;
+ }
bool match = t.AutoTarget switch
{
AutomationTarget.DeviceParam or AutomationTarget.MidiDeviceParam =>
@@ -126,7 +133,8 @@ public sealed partial class ArrangementView
t.AutoDeviceIndex = target is AutomationTarget.DeviceParam or AutomationTarget.PluginParam or AutomationTarget.MidiDeviceParam ? dev : -1;
t.AutoParamIndex = target is AutomationTarget.DeviceParam or AutomationTarget.MidiDeviceParam ? param : -1;
t.AutoParamId = "";
- _autoTargets[t.Id] = (t.AutoTarget, t.AutoDeviceIndex, t.AutoParamIndex, t.AutoParamId);
+ t.AutoChain = t.AutoSlot = t.AutoLane = -1;
+ _autoTargets[t.Id] = (t.AutoTarget, t.AutoDeviceIndex, t.AutoParamIndex, t.AutoParamId, -1, -1, -1);
t.AutoLabel = AutoLabelFor(t);
if (ReferenceEquals(_autoSelTrack, t)) _autoSelTrack = null; // selection was for the old lane
LoadAutoPoints(t);
@@ -135,18 +143,20 @@ public sealed partial class ArrangementView
/// <summary>The first lane on a track that carries points — the top entry of the target
/// menu's quick-access section — or null when the track has no automation yet.</summary>
- private static (AutomationTarget target, int dev, int param, string paramId)? FirstAutomatedTarget(IAudioEngine e, int trackId)
+ private static (AutomationTarget target, int dev, int param, string paramId, int chain, int slot, int lane)? FirstAutomatedTarget(IAudioEngine e, int trackId)
{
int n = e.AutomationLaneCount(trackId);
for (int i = 0; i < n; i++)
{
var info = e.AutomationLaneInfo(trackId, i);
if (info.PointCount <= 0) continue;
+ var (chain, slot) = e.AutomationLanePath(trackId, i);
+ if (chain >= 0) return (info.Target, info.DeviceIndex, info.ParamIndex, e.AutomationLaneParamId(trackId, i), chain, slot, i);
return info.Target switch
{
- AutomationTarget.Volume or AutomationTarget.Pan => (info.Target, -1, -1, ""),
- AutomationTarget.PluginParam => (info.Target, info.DeviceIndex, -1, e.AutomationLaneParamId(trackId, i)),
- _ => (info.Target, info.DeviceIndex, info.ParamIndex, ""),
+ AutomationTarget.Volume or AutomationTarget.Pan => (info.Target, -1, -1, "", -1, -1, -1),
+ AutomationTarget.PluginParam => (info.Target, info.DeviceIndex, -1, e.AutomationLaneParamId(trackId, i), -1, -1, -1),
+ _ => (info.Target, info.DeviceIndex, info.ParamIndex, "", -1, -1, -1),
};
}
return null;
@@ -162,12 +172,20 @@ public sealed partial class ArrangementView
internal void RemapAutoTargets(int trackId, bool midi, Func<int, int> map)
{
if (!_autoTargets.TryGetValue(trackId, out var sel)) return;
+ if (sel.chain >= 0) // a lane into a rack follows the rack (specs/044)
+ {
+ bool midiRack = sel.dev <= -1000;
+ if (sel.dev == -1 || midiRack != midi) return;
+ int nh = map(midiRack ? -1000 - sel.dev : sel.dev);
+ _autoTargets[trackId] = nh >= 0 ? sel with { dev = midiRack ? -1000 - nh : nh } : (AutomationTarget.Volume, -1, -1, "", -1, -1, -1);
+ return;
+ }
bool onChain = midi ? sel.target == AutomationTarget.MidiDeviceParam
: sel.target == AutomationTarget.DeviceParam
|| (sel.target == AutomationTarget.PluginParam && sel.dev >= 0);
if (!onChain) return;
int ni = map(sel.dev);
- _autoTargets[trackId] = ni >= 0 ? sel with { dev = ni } : (AutomationTarget.Volume, -1, -1, "");
+ _autoTargets[trackId] = ni >= 0 ? sel with { dev = ni } : (AutomationTarget.Volume, -1, -1, "", -1, -1, -1);
// Refresh() (raised by the chain's Changed) rebuilds the lanes from _autoTargets.
}
@@ -178,7 +196,8 @@ public sealed partial class ArrangementView
t.AutoDeviceIndex = deviceIndex;
t.AutoParamIndex = -1;
t.AutoParamId = paramId;
- _autoTargets[t.Id] = (t.AutoTarget, t.AutoDeviceIndex, t.AutoParamIndex, t.AutoParamId);
+ t.AutoChain = t.AutoSlot = t.AutoLane = -1;
+ _autoTargets[t.Id] = (t.AutoTarget, t.AutoDeviceIndex, t.AutoParamIndex, t.AutoParamId, -1, -1, -1);
t.AutoLabel = AutoLabelFor(t);
if (ReferenceEquals(_autoSelTrack, t)) _autoSelTrack = null; // selection was for the old lane
LoadAutoPoints(t);
@@ -340,7 +359,11 @@ public sealed partial class ArrangementView
private void CommitAutoImpl(TrackVM t, bool live)
{
if (_engine is not { } e) return;
- int lane = t.AutoTarget == AutomationTarget.PluginParam
+ int lane = t.AutoChain >= 0 && NestedLaneStill(e, t, t.AutoLane) ? t.AutoLane // the lane itself, wherever its device moved
+ : t.AutoChain >= 0 // a lane into a rack (specs/044): reused, never a new track-level one
+ ? e.AddNestedAutomationLane(t.Id, t.AutoTarget, t.AutoDeviceIndex, t.AutoChain, t.AutoSlot, t.AutoParamIndex,
+ t.AutoParamId.Length > 0 ? t.AutoParamId : null)
+ : t.AutoTarget == AutomationTarget.PluginParam
? e.AddPluginAutomationLane(t.Id, t.AutoDeviceIndex, t.AutoParamId)
: e.AddAutomationLane(t.Id, t.AutoTarget, t.AutoDeviceIndex, t.AutoParamIndex);
if (lane < 0) return;
@@ -372,6 +395,10 @@ public sealed partial class ArrangementView
string key; Action apply;
switch (info.Target)
{
+ case var _ when eA.AutomationLanePath(t.Id, i) is { Chain: >= 0 } np: // a lane into a rack (specs/044)
+ { var tg = info.Target; int dv = info.DeviceIndex, pr = info.ParamIndex; string pid = eA.AutomationLaneParamId(t.Id, i);
+ int ln = i;
+ key = $"N:{dv}:{np.Chain}:{np.Slot}:{(int)tg}:{pr}"; apply = () => SetAutoNestedTarget(t, tg, dv, np.Chain, np.Slot, pr, pid, ln); break; }
case AutomationTarget.Volume:
key = "V"; apply = () => SetAutoTarget(t, AutomationTarget.Volume, -1, -1); break;
case AutomationTarget.Pan:
@@ -621,7 +648,10 @@ public sealed partial class ArrangementView
}
// Human-readable "Device · Param" label for an existing lane (used in the quick-access section).
- private string AutoLaneLabel(IAudioEngine e, TrackVM t, AutomationLaneInfo info, int laneIndex) => info.Target switch
+ private string AutoLaneLabel(IAudioEngine e, TrackVM t, AutomationLaneInfo info, int laneIndex)
+ => e.AutomationLanePath(t.Id, laneIndex) is { Chain: >= 0 } p ? NestedLaneLabel(e, t.Id, info, p.Chain, p.Slot) : AutoLaneLabelTop(e, t, info, laneIndex);
+
+ private string AutoLaneLabelTop(IAudioEngine e, TrackVM t, AutomationLaneInfo info, int laneIndex) => info.Target switch
{
AutomationTarget.Volume => "Volume",
AutomationTarget.Pan => "Pan",
@@ -630,6 +660,82 @@ public sealed partial class ArrangementView
_ => $"{e.DeviceName(t.Id, info.DeviceIndex)} · {e.DeviceParamName(t.Id, info.DeviceIndex, info.ParamIndex)}",
};
+ // ---- lanes on devices grouped into a rack (specs/044) ------------------------
+ // AutoDeviceIndex is the rack's address on the track (>= 0 effect, -1 instrument, -1000 - i
+ // MIDI effect); (AutoChain, AutoSlot) the child: slot >= 0 a device, -1 the chain
+ // instrument (plug-in surface, 0..1), -1000 - i the chain's i-th MIDI effect.
+ private static (string Name, float Min, float Max, float Value) NestedParam(IAudioEngine e, int track, int host, int c, int s, int p)
+ {
+ if (s >= 0)
+ return (e.RackDevChainDeviceParamName(track, host, c, s, p), e.RackDevChainDeviceParamMin(track, host, c, s, p),
+ e.RackDevChainDeviceParamMax(track, host, c, s, p), e.RackDevChainDeviceParamGet(track, host, c, s, p));
+ if (s == -1)
+ return (e.RackDevChainInstrumentParamName(track, host, c, p), 0f, 1f, e.RackDevChainInstrumentParamGet(track, host, c, p));
+ int mi = -1000 - s;
+ if (host == -1)
+ return (e.RackChainMidiParamName(track, c, mi, p), e.RackChainMidiParamMin(track, c, mi, p),
+ e.RackChainMidiParamMax(track, c, mi, p), e.RackChainMidiParamGet(track, c, mi, p));
+ int rm = -1000 - host;
+ return (e.MidiRackChainDeviceParamName(track, rm, c, mi, p), e.MidiRackChainDeviceParamMin(track, rm, c, mi, p),
+ e.MidiRackChainDeviceParamMax(track, rm, c, mi, p), e.MidiRackChainDeviceParamGet(track, rm, c, mi, p));
+ }
+ private static (string Name, float Min, float Max, float Value) NestedParam(IAudioEngine e, TrackVM t)
+ => NestedParam(e, t.Id, t.AutoDeviceIndex, t.AutoChain, t.AutoSlot, t.AutoParamIndex);
+
+ // "Audio Effect Rack / Reverb · Mix".
+ private static string NestedLaneLabel(IAudioEngine e, int track, AutomationLaneInfo info, int c, int s)
+ {
+ int host = info.DeviceIndex;
+ string rack = host <= -1000 ? e.MidiEffectName(track, -1000 - host) : e.DeviceName(track, host);
+ string child = s >= 0 ? e.RackDevChainDeviceName(track, host, c, s)
+ : s == -1 ? e.RackDevChainInstrumentName(track, host, c)
+ : host == -1 ? e.RackChainMidiName(track, c, -1000 - s)
+ : e.MidiRackChainDeviceName(track, -1000 - host, c, -1000 - s);
+ return $"{rack} / {child} · {NestedParam(e, track, host, c, s, info.ParamIndex).Name}";
+ }
+
+ // Whether lane i is still the nested lane t shows: the same kind of target, rack and param.
+ private static bool NestedLaneStill(IAudioEngine e, TrackVM t, int i)
+ {
+ if (i < 0 || i >= e.AutomationLaneCount(t.Id)) return false;
+ var info = e.AutomationLaneInfo(t.Id, i);
+ return info.Target == t.AutoTarget && info.DeviceIndex == t.AutoDeviceIndex && info.ParamIndex == t.AutoParamIndex
+ && e.AutomationLanePath(t.Id, i).Chain >= 0;
+ }
+
+ // A rack edit moves a nested lane's (chain, slot) in the engine; follow the lane, so point edits
+ // never write to whichever device now sits at the old slot. A lane that is gone falls back to Volume.
+ private void ResyncNestedTarget(TrackVM t)
+ {
+ if (_engine is not { } e) return;
+ if (!NestedLaneStill(e, t, t.AutoLane))
+ {
+ t.AutoTarget = AutomationTarget.Volume;
+ t.AutoDeviceIndex = t.AutoParamIndex = t.AutoChain = t.AutoSlot = t.AutoLane = -1;
+ t.AutoParamId = "";
+ _autoTargets[t.Id] = (AutomationTarget.Volume, -1, -1, "", -1, -1, -1);
+ return;
+ }
+ (t.AutoChain, t.AutoSlot) = e.AutomationLanePath(t.Id, t.AutoLane);
+ _autoTargets[t.Id] = (t.AutoTarget, t.AutoDeviceIndex, t.AutoParamIndex, t.AutoParamId, t.AutoChain, t.AutoSlot, t.AutoLane);
+ }
+
+ internal void SetAutoNestedTarget(TrackVM t, AutomationTarget target, int host, int chain, int slot, int param, string paramId, int lane)
+ {
+ t.AutoTarget = target;
+ t.AutoDeviceIndex = host;
+ t.AutoParamIndex = param;
+ t.AutoParamId = paramId;
+ t.AutoChain = chain;
+ t.AutoSlot = slot;
+ t.AutoLane = lane;
+ _autoTargets[t.Id] = (target, host, param, paramId, chain, slot, lane);
+ t.AutoLabel = AutoLabelFor(t);
+ if (ReferenceEquals(_autoSelTrack, t)) _autoSelTrack = null;
+ LoadAutoPoints(t);
+ Redraw();
+ }
+
private static string PluginParamNameById(IAudioEngine e, TrackVM t, int dev, string paramId)
{
int n = e.PluginParamCount(t.Id, dev);
diff --git a/src/managed/Nota.App/ArrangementView.Vms.cs b/src/managed/Nota.App/ArrangementView.Vms.cs
index 0dcc983a..6d3a9ff1 100644
--- a/src/managed/Nota.App/ArrangementView.Vms.cs
+++ b/src/managed/Nota.App/ArrangementView.Vms.cs
@@ -44,6 +44,10 @@ public sealed partial class ArrangementView
public int AutoDeviceIndex = -1;
public int AutoParamIndex = -1;
public string AutoParamId = ""; // PluginParam target (M9-B3)
+ // A device grouped into a rack (specs/044): AutoDeviceIndex is the rack's address and
+ // these the chain index and slot of the child the lane drives; -1 = track level.
+ public int AutoChain = -1, AutoSlot = -1;
+ public int AutoLane = -1; // the nested lane itself: rack edits move its (chain, slot)
public string AutoLabel = "Vol";
public List<AutoPt> AutoPoints = new();
// Group lane summary (M-groups): descendant clips aggregated for the lane preview —
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 0cc2e1d1..3158592c 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -85,7 +85,7 @@ public sealed partial class ArrangementView : UserControl
// properties instead of tearing down and rebuilding every header control (click latency).
private readonly Dictionary<int, (Border card, TextBlock name, bool isGroup, Border spine, IBrush spineIdle)> _headerCards = new();
// Per-track chosen automation target, kept across Refresh (which rebuilds VMs).
- private readonly Dictionary<int, (AutomationTarget target, int dev, int param, string paramId)> _autoTargets = new();
+ private readonly Dictionary<int, (AutomationTarget target, int dev, int param, string paramId, int chain, int slot, int lane)> _autoTargets = new();
// Header column width and track row heights are user-resizable (ArrangementView.Sizing.cs).
private double HeaderW => _headerW;
@@ -997,7 +997,10 @@ public sealed partial class ArrangementView : UserControl
if (!_autoTargets.TryGetValue(ti.Id, out var sel) && FirstAutomatedTarget(eng, ti.Id) is { } first)
_autoTargets[ti.Id] = sel = first;
if (_autoTargets.ContainsKey(ti.Id))
- (tvm.AutoTarget, tvm.AutoDeviceIndex, tvm.AutoParamIndex, tvm.AutoParamId) = sel;
+ {
+ (tvm.AutoTarget, tvm.AutoDeviceIndex, tvm.AutoParamIndex, tvm.AutoParamId, tvm.AutoChain, tvm.AutoSlot, tvm.AutoLane) = sel;
+ if (tvm.AutoChain >= 0) ResyncNestedTarget(tvm); // a rack edit may have moved its device
+ }
tvm.AutoLabel = AutoLabelFor(tvm);
LoadAutoPoints(tvm);
}
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs
index c3e628b9..092ca790 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs
@@ -562,7 +562,7 @@ internal sealed partial class RackCardView
private void RcAddMidiMenu(Control anchor, int c)
{
var f = new MenuFlyout();
- if (_ra.RackAddress is not null && E.DeviceClipboardKind() == 2) { f.Items.Add(RcPasteItem(c)); f.Items.Add(new Separator()); }
+ if (_ra.RackAddress is not null && E.DeviceClipboardKind() is 2 or 4 && RcCanPaste(c)) { f.Items.Add(RcPasteItem(c)); f.Items.Add(new Separator()); }
foreach (var (name, kind) in RcMidiKinds)
{
var mi = new MenuItem { Header = name };
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs
index 60dbc54b..2ffb3cfc 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs
@@ -105,7 +105,9 @@ internal sealed partial class RackCardView
{
int kind = E.DeviceClipboardKind();
if (_ra.RackAddress is null || kind == 0) return false;
- if (kind == 2) return _rp.TakesMidiEffects && !(_rp.Kind == RackKind.Instrument && c >= RcMidiChainCount);
+ bool midiOk = _rp.TakesMidiEffects && !(_rp.Kind == RackKind.Instrument && c >= RcMidiChainCount);
+ if (kind == 2) return midiOk;
+ if (kind == 4) return midiOk || _rp.TakesAudioEffects; // several devices: whatever of them fits (specs/044)
return _rp.TakesAudioEffects;
}
private const int RcMidiChainCount = 16; // MIDI effects run in an Instrument Rack's first 16 chains
@@ -117,6 +119,7 @@ internal sealed partial class RackCardView
if (_ra.RackAddress is not int rack) return;
int kind = E.DeviceClipboardKind();
if (kind == 0) { _ctx.Status("Nothing to paste"); return; }
+ if (kind == 4) { RcPasteMany(rack, c, after); return; }
bool midi = kind == 2;
int at = after is { Index: >= 0 } s && s.Chain == c && s.Midi == midi ? s.Index + 1 : -1;
bool keyed = !midi && E.DeviceClipboardSidechain();
@@ -129,6 +132,21 @@ internal sealed partial class RackCardView
DeferRebuild();
}
+ // Several devices copied (specs/044): each section takes its own, after the selected device
+ // of that section or at its end; the rest are skipped. One undo step.
+ private void RcPasteMany(int rack, int c, RackDeviceSel? after)
+ {
+ int midiAt = after is { Index: >= 0, Midi: true } m && m.Chain == c ? m.Index + 1 : -1;
+ int fxAt = after is { Index: >= 0, Midi: false } d && d.Chain == c ? d.Index + 1 : -1;
+ int n = E.RackDevChainPasteDevices(T, rack, c, midiAt, fxAt, out int skipped, out int firstMidi, out int firstFx);
+ if (n < 0) { _ctx.Status(n == -3 ? "Couldn't paste: a device failed to load." : "Nothing to paste here."); return; }
+ if (n == 0) { _ctx.Status("This chain can't take the copied devices."); return; }
+ _ctx.Status(skipped > 0 ? $"Pasted {n} devices, skipped {skipped} this chain can't take" : $"Pasted {n} devices");
+ if (Sel != c) Sel = c;
+ RcSelect(firstFx >= 0 ? new RackDeviceSel(rack, c, false, firstFx) : new RackDeviceSel(rack, c, true, firstMidi));
+ DeferRebuild();
+ }
+
private string RcPasteRefusal(int code, bool midi) => code switch
{
-2 => _rp.Kind switch
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
index 6e8c6824..d0fa766a 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
@@ -176,7 +176,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)
private void ShowAddDeviceMenu(IRackAccess a, int sc, Control anchor, bool withPaste = false)
{
var f = new MenuFlyout();
- if (withPaste && E.DeviceClipboardKind() == 1) { f.Items.Add(RcPasteItem(sc)); f.Items.Add(new Separator()); }
+ if (withPaste && E.DeviceClipboardKind() is 1 or 4) { f.Items.Add(RcPasteItem(sc)); f.Items.Add(new Separator()); }
for (int k = 0; k < RackDeviceNames.Length; k++)
{
int kk = RackDeviceKinds[k];
diff --git a/src/managed/Nota.App/DeviceChainView.Clipboard.cs b/src/managed/Nota.App/DeviceChainView.Clipboard.cs
index d4cf06c3..48e8e6a5 100644
--- a/src/managed/Nota.App/DeviceChainView.Clipboard.cs
+++ b/src/managed/Nota.App/DeviceChainView.Clipboard.cs
@@ -8,12 +8,15 @@
// ⠿ handle; an accent bar marks the drop gap within the same domain (MIDI FX / audio FX).
using System;
+using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
+using Nota.Application;
using Nota.Infrastructure;
+using Nota.Presentation;
using static Nota.App.DeviceCardKit;
namespace Nota.App;
@@ -21,32 +24,60 @@ namespace Nota.App;
public sealed partial class DeviceChainView
{
// ---- selection --------------------------------------------------------
- private ChainKind _selChainKind;
- private int _selDeviceIndex = -1; // -1 = nothing selected. Paired with _selChainKind.
- // The track's instrument card is selected (specs/043); _selDeviceIndex stays -1 then, as the
- // instrument is device -1 to the engine.
- private bool _instrumentSelected;
+ // Several devices across the MIDI effects, the instrument and the audio effects (specs/044):
+ // click selects one, Shift-click a range in chain order, ⌘/Ctrl-click toggles one. The rules
+ // (ranges, what ⌘G can make of it) live in DeviceSelection.
+ private readonly DeviceSelection _sel = new();
+
+ private static DeviceSection SectionOf(ChainKind k)
+ => k switch { ChainKind.Midi => DeviceSection.Midi, ChainKind.Instrument => DeviceSection.Instrument, _ => DeviceSection.Audio };
+ private static ChainKind KindOf(DeviceSection s)
+ => s switch { DeviceSection.Midi => ChainKind.Midi, DeviceSection.Instrument => ChainKind.Instrument, _ => ChainKind.Effect };
+ private static ChainSlot SlotOf(ChainKind k, int di) => new(SectionOf(k), k == ChainKind.Instrument ? -1 : di);
// Audio effects, MIDI effects and the instrument take copy/cut/paste/delete (sends/add
// aren't devices). The instrument's Delete and Cut take its track (specs/043).
private static bool SelectableKind(ChainKind k) => k is ChainKind.Effect or ChainKind.Midi or ChainKind.Instrument;
- private bool HasDeviceSelection => _instrumentSelected || (_selDeviceIndex >= 0 && _selChainKind is ChainKind.Effect or ChainKind.Midi);
- // An effect or MIDI effect (not the instrument) is selected: what ⌘D, ⌘G and an indexed paste need.
- private bool HasEffectSelection => !_instrumentSelected && _selDeviceIndex >= 0 && _selChainKind is ChainKind.Effect or ChainKind.Midi;
+ private bool HasDeviceSelection => !_sel.IsEmpty;
+ // Any effect (MIDI or audio) selected: what ⌘D needs.
+ private bool HasEffectSelection => _sel.Members.Any(m => m.Section != DeviceSection.Instrument);
+ // Exactly one device: the single-device commands (Save preset, the instrument's own menu).
+ private ChainSlot? SingleSelection => _sel.Count == 1 ? _sel.Members[0] : null;
+
+ private int MidiCount => _engine.TrackMidiEffectCount(_trackId);
+ private int FxCount => _engine.TrackDeviceCount(_trackId);
- private void SelectDevice(ChainKind kind, int index)
+ private void SelectDevice(ChainKind kind, int index, KeyModifiers mods = KeyModifiers.None)
{
if (!SelectableKind(kind)) return;
Focus(); // route Ctrl+C/X/V + Delete here
bool hadRack = _rackSel != null;
_rackSel = null; _rackCmds = null; // one selection on the panel (specs/042)
- bool inst = kind == ChainKind.Instrument;
- if (!hadRack && _selChainKind == kind && (inst ? _instrumentSelected : !_instrumentSelected && _selDeviceIndex == index)) return;
- _selChainKind = kind; _selDeviceIndex = inst ? -1 : index; _instrumentSelected = inst;
+ var slot = SlotOf(kind, index);
+ if ((mods & KeyModifiers.Shift) != 0) _sel.ExtendTo(slot, MidiCount, IsInstrumentTrack(_trackId), FxCount);
+ else if ((mods & (KeyModifiers.Meta | KeyModifiers.Control)) != 0) _sel.Toggle(slot);
+ else if (!hadRack && _sel.Count == 1 && _sel.Contains(slot)) return;
+ else if (!hadRack && _sel.Count > 1 && _sel.Contains(slot)) { _pendingClick = slot; return; } // may be a drag
+ else _sel.Click(slot);
Rebuild();
}
- private void ClearDeviceSelection() { _selDeviceIndex = -1; _instrumentSelected = false; }
+ // A plain press on a device inside a multi-selection: the press may start a drag of the whole
+ // selection, so it narrows to this device only when the button comes up without a drag.
+ private ChainSlot? _pendingClick;
+ private void ApplyPendingClick()
+ {
+ if (_pendingClick is not { } s) return;
+ _pendingClick = null;
+ _sel.Click(s);
+ Rebuild();
+ }
+
+ // Select exactly these devices (after a paste, a group, an ungroup).
+ private void SelectDevices(IEnumerable<(ChainKind Kind, int Index)> devices)
+ => _sel.Set(devices.Select(d => SlotOf(d.Kind, d.Index)));
+
+ private void ClearDeviceSelection() => _sel.Clear();
// A device in a rack chain (specs/042): the rack card selects it and hands over what the
// keys do to it; the track chain's selection clears.
@@ -58,7 +89,7 @@ public sealed partial class DeviceChainView
if (sel != null) Focus();
_rackSel = sel;
_rackCmds = sel != null ? cmds : null;
- if (sel != null && (_selDeviceIndex >= 0 || _instrumentSelected))
+ if (sel != null && HasDeviceSelection)
{
ClearDeviceSelection();
foreach (var r in _selRings) r.IsVisible = false; // no rebuild: the rack card may be mid-drag
@@ -68,9 +99,7 @@ public sealed partial class DeviceChainView
// The track cards' selection rings, refilled on every rebuild.
private readonly System.Collections.Generic.List<Border> _selRings = new();
- private bool IsSelected(ChainKind kind, int index)
- => kind == ChainKind.Instrument ? _instrumentSelected
- : HasEffectSelection && _selChainKind == kind && _selDeviceIndex == index;
+ private bool IsSelected(ChainKind kind, int index) => SelectableKind(kind) && _sel.Contains(SlotOf(kind, index));
// ---- clipboard --------------------------------------------------------
// The device itself is copied by the engine (#238): a full clone with every parameter,
@@ -93,80 +122,164 @@ public sealed partial class DeviceChainView
private void CopySelectedDevice() => TryCopySelectedDevice();
// False when nothing was copied (a plug-in that won't open a second instance): Cut stops then.
+ // One device keeps its card's preset label on the clipboard; several go as the engine's run.
private bool TryCopySelectedDevice()
{
if (!HasDeviceSelection) return false;
- int di = _selDeviceIndex;
- bool ok = _instrumentSelected ? _engine.CopyInstrument(_trackId) : _selChainKind switch
+ if (SingleSelection is { } one)
{
- ChainKind.Effect => _engine.CopyDevice(_trackId, di),
- ChainKind.Midi => _engine.CopyMidiEffect(_trackId, di),
- _ => false,
- };
- if (!ok) return false;
- _clipFromTrack = true;
- var ex = Extra(_selChainKind, di);
- _clip = new DeviceClip { Kind = _selChainKind, Preset = ex.Preset, PresetId = ex.PresetId };
+ var k = KindOf(one.Section); int di = one.Index;
+ bool ok = k switch
+ {
+ ChainKind.Instrument => _engine.CopyInstrument(_trackId),
+ ChainKind.Effect => _engine.CopyDevice(_trackId, di),
+ _ => _engine.CopyMidiEffect(_trackId, di),
+ };
+ if (!ok) return false;
+ _clipFromTrack = true;
+ var ex = Extra(k, di);
+ _clip = new DeviceClip { Kind = k, Preset = ex.Preset, PresetId = ex.PresetId };
+ return true;
+ }
+ if (_engine.CopyDevices(_trackId, _sel.Indices(DeviceSection.Midi).ToArray(), _sel.HasInstrument,
+ _sel.Indices(DeviceSection.Audio).ToArray()) < 0)
+ return false;
+ _clipFromTrack = false; _clip = null;
return true;
}
private void DeleteSelectedDevice()
{
if (!HasDeviceSelection) return;
- RemoveDeviceAt(_instrumentSelected ? ChainKind.Instrument : _selChainKind, _selDeviceIndex);
+ // The instrument takes its track (specs/043); with more selected the host always asks.
+ if (_sel.HasInstrument) { TrackDeleteRequested?.Invoke(_trackId, false, _sel.Count); return; }
+ if (SingleSelection is { } one) { RemoveDeviceAt(KindOf(one.Section), one.Index); return; }
+ int n = _sel.Count;
+ _engine.BeginUndoGroup();
+ try
+ {
+ // Highest index first, so the ones still to go keep theirs.
+ foreach (int i in _sel.Indices(DeviceSection.Audio).OrderByDescending(i => i))
+ { _engine.RemoveDevice(_trackId, i); ExtrasRemoved(ChainKind.Effect, i); }
+ foreach (int i in _sel.Indices(DeviceSection.Midi).OrderByDescending(i => i))
+ { _engine.RemoveMidiEffect(_trackId, i); ExtrasRemoved(ChainKind.Midi, i); }
+ }
+ finally { _engine.EndUndoGroup(); }
+ ClearDeviceSelection();
+ StatusMessage?.Invoke($"Deleted {n} devices");
+ Rebuild(); Changed?.Invoke();
}
// Delete, the menu's Delete and the header's Remove control (#110). An instrument track never
// stands without its instrument: removing it takes the track (specs/043), which the host asks about.
private void RemoveDeviceAt(ChainKind k, int di)
{
- if (k == ChainKind.Instrument) { TrackDeleteRequested?.Invoke(_trackId, false); return; }
+ if (k == ChainKind.Instrument) { TrackDeleteRequested?.Invoke(_trackId, false, 1); return; }
if (k == ChainKind.Effect) _engine.RemoveDevice(_trackId, di);
else if (k == ChainKind.Midi) _engine.RemoveMidiEffect(_trackId, di);
else return;
ExtrasRemoved(k, di);
- if (HasEffectSelection && _selChainKind == k) // the selection stays on its own device
- _selDeviceIndex = _selDeviceIndex == di ? -1 : _selDeviceIndex > di ? _selDeviceIndex - 1 : _selDeviceIndex;
+ RemapSelection(k, i => i == di ? -1 : i > di ? i - 1 : i); // the selection stays on its own devices
Rebuild(); Changed?.Invoke();
}
+ // Keep the selection on its devices when indices in one section move.
+ private void RemapSelection(ChainKind k, Func<int, int> map)
+ {
+ var sec = SectionOf(k);
+ _sel.Set(_sel.Members.Select(m => m.Section == sec ? new ChainSlot(sec, map(m.Index)) : m)
+ .Where(m => m.Section == DeviceSection.Instrument || m.Index >= 0).ToList());
+ }
+
private void CutSelectedDevice()
{
// Nothing removed unless the copy landed: a cut device must stay pasteable.
if (!TryCopySelectedDevice())
{
- if (HasDeviceSelection) StatusMessage?.Invoke("This device can't be copied, so it wasn't cut.");
+ if (HasDeviceSelection) StatusMessage?.Invoke(_sel.Count > 1 ? "These devices can't be copied, so they weren't cut." : "This device can't be copied, so it wasn't cut.");
return;
}
- if (_instrumentSelected) TrackDeleteRequested?.Invoke(_trackId, true);
+ if (_sel.HasInstrument) TrackDeleteRequested?.Invoke(_trackId, true, _sel.Count);
else DeleteSelectedDevice();
}
- // ⌘D: a copy right after the selected device, the clipboard untouched (specs/042).
+ // ⌘D: each run of selected effects copied right after itself, the clipboard untouched
+ // (specs/042, specs/044); the copies become the selection. One undo step.
private void DuplicateSelectedDevice()
{
if (!HasEffectSelection) return;
- int di = _selDeviceIndex; var k = _selChainKind;
- int end = k == ChainKind.Midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);
- int newIdx = k == ChainKind.Midi ? _engine.DuplicateMidiEffect(_trackId, di) : _engine.DuplicateDevice(_trackId, di);
- if (newIdx < 0) { StatusMessage?.Invoke("This device can't be duplicated"); return; }
- var src = Extra(k, di);
- if (newIdx < end) ExtrasMoved(k, end, newIdx);
- TrackExtras().Remove(ExtraKey(k, newIdx));
- var copy = Extra(k, newIdx); copy.Preset = src.Preset; copy.PresetId = src.PresetId;
- _selDeviceIndex = newIdx;
+ var copies = new List<(ChainKind Kind, int Index)>();
+ bool failed = false;
+ _engine.BeginUndoGroup();
+ try
+ {
+ foreach (var k in new[] { ChainKind.Effect, ChainKind.Midi })
+ {
+ var runs = Runs(_sel.Indices(SectionOf(k)).OrderBy(i => i).ToList());
+ for (int r = runs.Count - 1; r >= 0; r--) // the last run first: earlier indices hold
+ {
+ var (a, b) = runs[r];
+ for (int i = 0; i <= b - a; i++)
+ {
+ int end = k == ChainKind.Midi ? MidiCount : FxCount;
+ int src = a + i;
+ int newIdx = k == ChainKind.Midi ? _engine.DuplicateMidiEffect(_trackId, src) : _engine.DuplicateDevice(_trackId, src);
+ if (newIdx < 0) { failed = true; continue; }
+ if (newIdx < end) ExtrasMoved(k, end, newIdx);
+ TrackExtras().Remove(ExtraKey(k, newIdx));
+ var from = Extra(k, src);
+ int to = b + 1 + i; // after the run and the copies before it
+ if (newIdx != to)
+ {
+ if (k == ChainKind.Midi) _engine.MoveMidiEffect(_trackId, newIdx, to); else _engine.MoveDevice(_trackId, newIdx, to);
+ ExtrasMoved(k, newIdx, to);
+ }
+ var copy = Extra(k, to); copy.Preset = from.Preset; copy.PresetId = from.PresetId;
+ copies.Add((k, to));
+ }
+ // The copies of later runs moved up by this run's length.
+ int len = b - a + 1;
+ for (int c = 0; c < copies.Count - (b - a + 1); c++)
+ if (copies[c].Kind == k && copies[c].Index > b) copies[c] = (k, copies[c].Index + len);
+ }
+ }
+ }
+ finally { _engine.EndUndoGroup(); }
+ if (failed) StatusMessage?.Invoke("Some devices can't be duplicated");
+ if (copies.Count > 0) SelectDevices(copies);
Rebuild(); Changed?.Invoke();
}
+ // Consecutive runs (first, last) of sorted indices.
+ private static List<(int First, int Last)> Runs(List<int> sorted)
+ {
+ var runs = new List<(int, int)>();
+ for (int i = 0; i < sorted.Count; i++)
+ {
+ int a = sorted[i];
+ while (i + 1 < sorted.Count && sorted[i + 1] == sorted[i] + 1) i++;
+ runs.Add((a, sorted[i]));
+ }
+ return runs;
+ }
+
+ // Where a paste of `section` goes: after the last selected device there, else the end (-1).
+ private int PasteAt(DeviceSection section)
+ {
+ var idx = _sel.Indices(section).ToList();
+ return idx.Count > 0 ? idx.Max() + 1 : -1;
+ }
+
private void PasteDevice()
{
if (!CanPaste) return;
+ if (_engine.DeviceClipboardKind() == 4) { PasteDevices(); return; }
var c = _clipFromTrack && _clip is { } own && own.Kind == ClipKind ? own : new DeviceClip { Kind = ClipKind };
if (c.Kind == ChainKind.Instrument) { PasteInstrument(c); return; }
if (c.Kind != ChainKind.Effect && c.Kind != ChainKind.Midi) return;
- // Drop it right after the selected device of the same domain, else at the end.
- int at = HasEffectSelection && _selChainKind == c.Kind ? _selDeviceIndex + 1 : -1;
- int end = c.Kind == ChainKind.Midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);
+ // Drop it right after the last selected device of the same domain, else at the end.
+ int at = PasteAt(SectionOf(c.Kind));
+ int end = c.Kind == ChainKind.Midi ? MidiCount : FxCount;
if (at > end) at = -1;
int newIdx = c.Kind == ChainKind.Midi ? _engine.PasteMidiEffect(_trackId, at) : _engine.PasteDevice(_trackId, at);
if (newIdx < 0) return;
@@ -174,74 +287,178 @@ public sealed partial class DeviceChainView
if (newIdx < end) ExtrasMoved(c.Kind, end, newIdx);
TrackExtras().Remove(ExtraKey(c.Kind, newIdx));
var pasted = Extra(c.Kind, newIdx); pasted.Preset = c.Preset; pasted.PresetId = c.PresetId;
- _selChainKind = c.Kind;
- _selDeviceIndex = newIdx; _instrumentSelected = false;
+ SelectDevices(new[] { (c.Kind, newIdx) });
+ Rebuild(); Changed?.Invoke();
+ }
+
+ // Several devices on the clipboard (specs/044): each lands in its section after the last
+ // selected device there (else at the end), an instrument replaces this track's; one undo step.
+ private void PasteDevices()
+ {
+ int mEnd = MidiCount, fEnd = FxCount;
+ int midiAt = PasteAt(DeviceSection.Midi), fxAt = PasteAt(DeviceSection.Audio);
+ int n = _engine.PasteDevices(_trackId, midiAt, fxAt, out int skipped);
+ if (n < 0) { StatusMessage?.Invoke(n == -3 ? "Couldn't paste: a device failed to load." : "Nothing to paste."); return; }
+ if (n == 0) { StatusMessage?.Invoke("This track can't take the copied devices."); return; }
+ int km = MidiCount - mEnd, kf = FxCount - fEnd;
+ int ma = midiAt < 0 ? mEnd : midiAt, fa = fxAt < 0 ? fEnd : fxAt;
+ if (km > 0) RemapExtras(ChainKind.Midi, i => i >= ma ? i + km : i);
+ if (kf > 0) RemapExtras(ChainKind.Effect, i => i >= fa ? i + kf : i);
+ bool instrument = n - km - kf > 0;
+ if (instrument) ForgetInstrumentState(_trackId);
+ var pasted = new List<(ChainKind, int)>();
+ for (int i = 0; i < km; i++) pasted.Add((ChainKind.Midi, ma + i));
+ if (instrument) pasted.Add((ChainKind.Instrument, -1));
+ for (int i = 0; i < kf; i++) pasted.Add((ChainKind.Effect, fa + i));
+ SelectDevices(pasted);
+ StatusMessage?.Invoke(skipped > 0 ? $"Pasted {n} devices, skipped {skipped} this track can't take" : $"Pasted {n} devices");
Rebuild(); Changed?.Invoke();
}
// An instrument on the clipboard replaces this track's instrument (specs/043): with the
- // instrument card or nothing selected; with an effect selected it would read as "paste here".
+ // instrument card or nothing selected; with only effects selected it would read as "paste here".
private void PasteInstrument(DeviceClip c)
{
- if (HasEffectSelection) { StatusMessage?.Invoke("Paste an instrument on an instrument card."); return; }
+ if (HasDeviceSelection && !_sel.HasInstrument) { StatusMessage?.Invoke("Paste an instrument on an instrument card."); return; }
int r = _engine.PasteInstrument(_trackId);
if (r == -2) { StatusMessage?.Invoke("Only an instrument track takes an instrument."); return; }
if (r < 0) { StatusMessage?.Invoke("Couldn't paste the instrument."); return; }
ForgetInstrumentState(_trackId);
var ex = Extra(ChainKind.Instrument, -1); ex.Preset = c.Preset; ex.PresetId = c.PresetId;
- _selChainKind = ChainKind.Instrument; _selDeviceIndex = -1; _instrumentSelected = true;
+ SelectDevices(new[] { (ChainKind.Instrument, -1) });
StatusMessage?.Invoke($"Pasted {_engine.DeviceName(_trackId, -1)}");
Rebuild(); Changed?.Invoke();
}
- // ---- ⌘G / ⌘⇧G: wrap the selected device in a rack / unwrap it (#257) ----
- // With the Devices panel focused these act on the device, never on the tracks: grouping
- // tracks stays ⌘G in the arrangement and the track headers.
- private bool SelectedIsRack => _selChainKind == ChainKind.Effect && _selDeviceIndex >= 0
- && _engine.TrackDeviceBuiltinKind(_trackId, _selDeviceIndex) == 5;
+ // ---- ⌘G / ⌘⇧G: group the selection into a rack / ungroup a rack (#257, #328) ----
+ // With the Devices panel focused these act on devices, never on the tracks: grouping
+ // tracks stays ⌘G in the arrangement and the track headers. The rack type follows from
+ // what is selected (DeviceSelection.Shape); links on the devices follow them (specs/044).
+
+ // A one-chain rack card the selection can ungroup: its chain count (0 when not a rack).
+ private int RackChains(ChainSlot s) => s.Section switch
+ {
+ DeviceSection.Audio => _engine.TrackDeviceBuiltinKind(_trackId, s.Index) == 5 ? _engine.RackDevChainCount(_trackId, s.Index) : 0,
+ DeviceSection.Midi => _engine.MidiEffectKind(_trackId, s.Index) == 6 ? _engine.MidiRackChainCount(_trackId, s.Index) : 0,
+ _ => _engine.TrackInstrumentKind(_trackId) == 3 ? _engine.RackChainCount(_trackId) : 0,
+ };
+ private bool SelectedIsRack => SingleSelection is { } s && RackChains(s) > 0;
+ private GroupShape SelectionShape => _sel.Shape(MidiCount, FxCount);
+
+ private static string GroupRefusalText(int r) => (GroupRefusal)r switch
+ {
+ GroupRefusal.NotContiguous => "Select devices next to each other to group them",
+ GroupRefusal.RackInRun => "A rack can't go inside another rack",
+ GroupRefusal.CantHost => "A plug-in can't go in a MIDI Effect Rack",
+ GroupRefusal.InstrumentCantNest => "An Instrument Rack can't go inside another Instrument Rack",
+ GroupRefusal.NotInstrumentTrack => "Only an instrument track takes MIDI effects and an instrument",
+ _ => "These devices can't be grouped",
+ };
private void GroupSelectedDevice()
{
- if (!HasEffectSelection) { StatusMessage?.Invoke("Select an audio effect to put it in a rack"); return; }
- if (_selChainKind == ChainKind.Midi) { StatusMessage?.Invoke("MIDI effects can't go in a rack"); return; }
- int di = _selDeviceIndex;
- string name = _engine.DeviceName(_trackId, di);
- if (_engine.WrapDeviceInRack(_trackId, di) < 0)
+ if (!HasDeviceSelection) { StatusMessage?.Invoke("Select devices to put them in a rack"); return; }
+ var shape = SelectionShape;
+ if (!shape.CanGroup) { StatusMessage?.Invoke(shape.Reason ?? "These devices can't be grouped"); return; }
+ // The grouped devices' card state (A/B, preset label) rides on the rack's card until
+ // ungroup brings it back.
+ var wrapped = new List<CardExtra>();
+ foreach (var m in _sel.Members)
+ if (TrackExtras().TryGetValue(ExtraKey(KindOf(m.Section), m.Index), out var ex)) wrapped.Add(ex);
+ int n = _sel.Count;
+ string first = n == 1 && SingleSelection is { } one ? CardName(KindOf(one.Section), one.Index) : "";
+ int r = _engine.GroupDevices(_trackId, shape.MidiFirst, shape.MidiCount, shape.WithInstrument, shape.FxFirst, shape.FxCount);
+ bool ok = shape.WithInstrument ? r == -1 : r >= 0 || r <= -1000;
+ if (!ok) { StatusMessage?.Invoke(GroupRefusalText(r)); return; }
+ ChainKind rackKind; int rackIdx; string rackName;
+ switch (shape.Kind)
{
- StatusMessage?.Invoke($"{name} can't go in a rack: it has a sidechain key, automation, a modulation link or an Arp's CC lane");
- return;
+ case GroupShapeKind.AudioRack:
+ {
+ int a = shape.FxFirst, c = shape.FxCount;
+ RemapExtras(ChainKind.Effect, i => i < a ? i : i < a + c ? -1 : i - c + 1);
+ rackKind = ChainKind.Effect; rackIdx = a; rackName = "an Audio Effect Rack";
+ break;
+ }
+ case GroupShapeKind.MidiRack:
+ {
+ int a = shape.MidiFirst, c = shape.MidiCount;
+ RemapExtras(ChainKind.Midi, i => i < a ? i : i < a + c ? -1 : i - c + 1);
+ rackKind = ChainKind.Midi; rackIdx = a; rackName = "a MIDI Effect Rack";
+ break;
+ }
+ default:
+ {
+ int mf = shape.MidiFirst, fc = shape.FxCount;
+ if (shape.MidiCount > 0) RemapExtras(ChainKind.Midi, i => i >= mf ? -1 : i);
+ if (fc > 0) RemapExtras(ChainKind.Effect, i => i < fc ? -1 : i - fc);
+ ForgetInstrumentState(_trackId);
+ rackKind = ChainKind.Instrument; rackIdx = -1; rackName = "an Instrument Rack";
+ break;
+ }
}
- // The device's A/B snapshots and preset label live only here: the rack keeps them for
- // when ⌘⇧G (or undo) brings the device back out.
- TrackExtras().Remove(ExtraKey(ChainKind.Effect, di), out var own);
- if (own != null) Extra(ChainKind.Effect, di).Wrapped = own;
- StatusMessage?.Invoke($"Put {name} in an Audio Effect Rack");
+ var rex = Extra(rackKind, rackIdx);
+ if (wrapped.Count == 1) rex.Wrapped = wrapped[0]; // ⌘Z / ⌘⇧Z swap the two (ExtraFor)
+ else if (wrapped.Count > 1) rex.WrappedMany = wrapped;
+ SelectDevices(new[] { (rackKind, rackIdx) });
+ StatusMessage?.Invoke(n == 1 && first.Length > 0 ? $"Put {first} in {rackName}" : $"Put {n} devices in {rackName}");
Rebuild(); Changed?.Invoke();
}
+ private string CardName(ChainKind k, int di)
+ => k == ChainKind.Midi ? _engine.MidiEffectName(_trackId, di) : _engine.DeviceName(_trackId, k == ChainKind.Instrument ? -1 : di);
+
private void UngroupSelectedDevice()
{
- if (!SelectedIsRack) { StatusMessage?.Invoke("Select an Audio Effect Rack to take its devices out"); return; }
- int di = _selDeviceIndex;
- int end = _engine.TrackDeviceCount(_trackId);
- var wrapped = Extra(ChainKind.Effect, di).Wrapped;
- int n = _engine.UnwrapRack(_trackId, di);
+ if (SingleSelection is not { } s || RackChains(s) == 0) { StatusMessage?.Invoke("Select a rack to take its devices out"); return; }
+ if (RackChains(s) != 1) { StatusMessage?.Invoke("Only a rack with one chain can be ungrouped"); return; }
+ var k = KindOf(s.Section);
+ TrackExtras().TryGetValue(ExtraKey(k, s.Index), out var rex);
+ int mBefore = MidiCount, fBefore = FxCount;
+ int n = _engine.UngroupRack(_trackId, FamilyOf(k), k == ChainKind.Instrument ? 0 : s.Index, out var dropped);
if (n < 0)
{
- StatusMessage?.Invoke("Only a rack with one chain can be ungrouped, and not while it is automated, modulated or driven by an Arp's CC lane");
+ StatusMessage?.Invoke((UngroupRefusal)n switch
+ {
+ UngroupRefusal.SeveralChains => "Only a rack with one chain can be ungrouped",
+ UngroupRefusal.DrumRack => "A Drum Rack can't be ungrouped",
+ UngroupRefusal.NoInstrument => "The rack's chain has no instrument to put back",
+ _ => "This rack can't be ungrouped",
+ });
return;
}
- // The rack's slot becomes its n devices; the cards after it shift with them.
- if (n == 0) ExtrasRemoved(ChainKind.Effect, di);
+ // The cards after the rack shift; the restored devices are selected and get their own
+ // card state back where it matches (the same kind and name).
+ var restored = new List<(ChainKind Kind, int Index)>();
+ if (k == ChainKind.Instrument)
+ {
+ int km = MidiCount - mBefore, kf = FxCount - fBefore;
+ ForgetInstrumentState(_trackId);
+ if (kf > 0) RemapExtras(ChainKind.Effect, i => i + kf);
+ for (int i = 0; i < km; i++) restored.Add((ChainKind.Midi, mBefore + i));
+ restored.Add((ChainKind.Instrument, -1));
+ for (int i = 0; i < kf; i++) restored.Add((ChainKind.Effect, i));
+ }
else
{
- TrackExtras().Remove(ExtraKey(ChainKind.Effect, di));
- for (int i = 1; i < n; i++) ExtrasMoved(ChainKind.Effect, end - 1 + i, di + i);
- if (wrapped != null && wrapped.Sig == CardSig(_trackId, ChainKind.Effect, di))
- TrackExtras()[ExtraKey(ChainKind.Effect, di)] = wrapped;
+ int a = s.Index;
+ TrackExtras().Remove(ExtraKey(k, a));
+ RemapExtras(k, i => i > a ? i + n - 1 : i);
+ for (int i = 0; i < n; i++) restored.Add((k, a + i));
}
- _selDeviceIndex = n > 0 ? di : -1;
- StatusMessage?.Invoke(n == 1 ? "Took the device out of the rack" : $"Took {n} devices out of the rack");
+ var saved = rex?.WrappedMany ?? (rex?.Wrapped is { } w ? new List<CardExtra> { w } : new List<CardExtra>());
+ foreach (var (rk, ri) in restored)
+ {
+ string sig = CardSig(_trackId, rk, ri);
+ var hit = saved.FirstOrDefault(x => x.Sig == sig);
+ if (hit is null) continue;
+ saved.Remove(hit);
+ TrackExtras()[ExtraKey(rk, ri)] = hit;
+ }
+ SelectDevices(restored);
+ string msg = n == 1 ? "Took the device out of the rack" : $"Took {n} devices out of the rack";
+ if (dropped != UngroupDropped.None) msg += " — its macros and chain settings were dropped";
+ StatusMessage?.Invoke(msg);
Rebuild(); Changed?.Invoke();
}
@@ -265,6 +482,7 @@ public sealed partial class DeviceChainView
if (mod && e.Key == Key.V && CanPaste) { PasteDevice(); e.Handled = true; return; }
if (mod && e.Key == Key.D && HasEffectSelection) { DuplicateSelectedDevice(); e.Handled = true; return; }
if (!mod && (e.Key == Key.Delete || e.Key == Key.Back) && HasDeviceSelection) { DeleteSelectedDevice(); e.Handled = true; return; }
+ if (!mod && e.Key == Key.Escape && HasDeviceSelection) { ClearDeviceSelection(); Rebuild(); e.Handled = true; return; }
base.OnKeyDown(e);
}
@@ -273,7 +491,9 @@ public sealed partial class DeviceChainView
// compare, move, docs, fold), Save preset, the clipboard group, and Delete last.
private void ShowDeviceContextMenu(Control anchor, ChainKind kind, int di, Action<MenuFlyout>? header = null)
{
- SelectDevice(kind, di);
+ // A right-click inside the selection acts on all of it; outside, it selects that card alone.
+ if (!_sel.Contains(SlotOf(kind, di))) SelectDevice(kind, di);
+ if (_sel.Count > 1) { ShowSelectionMenu(anchor); return; }
var flyout = new MenuFlyout();
string name = kind switch
{
@@ -304,6 +524,7 @@ public sealed partial class DeviceChainView
MenuKit.Item("Paste", GlyphKind.Paste, PasteDevice, MenuKit.PasteKey, _engine.DeviceClipboardKind() == 3),
},
MoveToTrackGroup(kind, di),
+ new Control[] { GroupItem() },
new Control[] { MenuKit.Danger("Delete track", GlyphKind.Trash, DeleteSelectedDevice, MenuKit.DeleteKey) });
flyout.ShowAt(anchor, showAtPointer: true);
return;
@@ -319,18 +540,45 @@ public sealed partial class DeviceChainView
MenuKit.Item("Duplicate", GlyphKind.Duplicate, DuplicateSelectedDevice, MenuKit.DuplicateKey, selectable),
},
MoveToTrackGroup(kind, di),
- kind == ChainKind.Effect
- ? new Control[]
- {
- _engine.TrackDeviceBuiltinKind(_trackId, di) == 5
- ? MenuKit.Item("Ungroup rack", GlyphKind.Ungroup, UngroupSelectedDevice, MenuKit.UngroupKey, _engine.RackDevChainCount(_trackId, di) == 1)
- : MenuKit.Item("Group into rack", GlyphKind.Folder, GroupSelectedDevice, MenuKit.GroupKey),
- }
- : Array.Empty<Control>(),
+ new Control[] { GroupItem() },
new Control[] { MenuKit.Danger("Delete", GlyphKind.Trash, DeleteSelectedDevice, MenuKit.DeleteKey, selectable) });
flyout.ShowAt(anchor, showAtPointer: true);
}
+ // Group into rack, or Ungroup rack on a rack card (any of the three; one chain to be enabled).
+ private Control GroupItem()
+ {
+ if (SingleSelection is { } s && RackChains(s) > 0)
+ return MenuKit.Item("Ungroup rack", GlyphKind.Ungroup, UngroupSelectedDevice, MenuKit.UngroupKey, RackChains(s) == 1);
+ return MenuKit.Item("Group into rack", GlyphKind.Folder, GroupSelectedDevice, MenuKit.GroupKey, SelectionShape.CanGroup);
+ }
+
+ // The menu of several selected devices (specs/044): what it does, it does to all of them.
+ private void ShowSelectionMenu(Control anchor)
+ {
+ var flyout = new MenuFlyout();
+ int n = _sel.Count;
+ flyout.Items.Add(MenuKit.Header($"{n} devices", null, _sel.HasInstrument ? "With the instrument" : "Selected"));
+ flyout.Items.Add(new Separator());
+ MenuKit.AddGroups(flyout.Items,
+ new Control[]
+ {
+ MenuKit.Item("Copy", GlyphKind.Copy, CopySelectedDevice, MenuKit.CopyKey),
+ MenuKit.Item("Cut", GlyphKind.Cut, CutSelectedDevice, MenuKit.CutKey),
+ MenuKit.Item("Paste", GlyphKind.Paste, PasteDevice, MenuKit.PasteKey, CanPaste),
+ MenuKit.Item("Duplicate", GlyphKind.Duplicate, DuplicateSelectedDevice, MenuKit.DuplicateKey, HasEffectSelection),
+ },
+ MoveSelectionToTrackGroup(),
+ new Control[] { GroupItem() },
+ new Control[]
+ {
+ _sel.HasInstrument
+ ? MenuKit.Danger("Delete track", GlyphKind.Trash, DeleteSelectedDevice, MenuKit.DeleteKey)
+ : MenuKit.Danger("Delete", GlyphKind.Trash, DeleteSelectedDevice, MenuKit.DeleteKey),
+ });
+ flyout.ShowAt(anchor, showAtPointer: true);
+ }
+
// ---- drag-reorder (grab a card by its header) ---------------------------
// Tag stamped on each device card so a drag can find its same-domain siblings in _row.
private sealed record DevTag(ChainKind Kind, int Index);
@@ -388,9 +636,10 @@ public sealed partial class DeviceChainView
};
handle.PointerReleased += (_, e) =>
{
- if (inst) { EndDeviceDrag(e.Pointer); return; }
- if (_devDragFrom < 0) return;
+ if (inst) { bool moved = _devDragging; EndDeviceDrag(e.Pointer); if (!moved) ApplyPendingClick(); else _pendingClick = null; return; }
+ if (_devDragFrom < 0) { ApplyPendingClick(); return; }
var kindL = _devDragKind; int from = _devDragFrom; bool dragged = _devDragging;
+ if (dragged) _pendingClick = null; else ApplyPendingClick();
int gap = _devDragging ? GapAt(e.GetPosition(_row).X) : -1;
if (_devDragCard != null) _devDragCard.Opacity = 1.0;
_devDragFrom = -1; _devDragging = false; _devDragCard = null;
@@ -398,19 +647,51 @@ public sealed partial class DeviceChainView
e.Pointer.Capture(null);
if (!dragged || gap < 0) return;
int m = DomainCards(kindL).Count;
+ // A selected card drags its whole section of the selection along (specs/044).
+ if (_sel.Contains(SlotOf(kindL, from)))
+ {
+ var group = _sel.Indices(SectionOf(kindL)).OrderBy(i => i).ToList();
+ if (group.Count > 1) { MoveBlock(kindL, group, gap, m); return; }
+ }
int to = gap > from ? gap - 1 : gap;
to = Math.Clamp(to, 0, m - 1);
if (to == from) return;
if (kindL == ChainKind.Midi) _engine.MoveMidiEffect(_trackId, from, to);
else _engine.MoveDevice(_trackId, from, to);
ExtrasMoved(kindL, from, to);
- _selChainKind = kindL; _selDeviceIndex = to; _instrumentSelected = false;
+ SelectDevices(new[] { (kindL, to) });
Rebuild(); Changed?.Invoke();
};
}
private PointerPressedEventArgs? _devDragPress;
+ // Several selected devices of one section dropped on a gap (0..m): they land there together,
+ // in order, one undo step; they stay selected.
+ private void MoveBlock(ChainKind k, List<int> group, int gap, int m)
+ {
+ var others = Enumerable.Range(0, m).Where(i => !group.Contains(i)).ToList();
+ int at = gap - group.Count(i => i < gap);
+ var final = others.Take(at).Concat(group).Concat(others.Skip(at)).ToList();
+ var cur = Enumerable.Range(0, m).ToList();
+ if (cur.SequenceEqual(final)) return;
+ _engine.BeginUndoGroup();
+ try
+ {
+ for (int p = 0; p < m; p++)
+ {
+ if (cur[p] == final[p]) continue;
+ int from = cur.IndexOf(final[p]);
+ if (k == ChainKind.Midi) _engine.MoveMidiEffect(_trackId, from, p); else _engine.MoveDevice(_trackId, from, p);
+ ExtrasMoved(k, from, p);
+ int id = cur[from]; cur.RemoveAt(from); cur.Insert(p, id);
+ }
+ }
+ finally { _engine.EndUndoGroup(); }
+ SelectDevices(Enumerable.Range(at, group.Count).Select(i => (k, i)));
+ Rebuild(); Changed?.Invoke();
+ }
+
// Ends an in-panel header drag without dropping: the card, the drop bar and the capture go back.
private void EndDeviceDrag(IPointer pointer)
{
diff --git a/src/managed/Nota.App/DeviceChainView.Drop.cs b/src/managed/Nota.App/DeviceChainView.Drop.cs
index c4e2aa49..f6ee4bb5 100644
--- a/src/managed/Nota.App/DeviceChainView.Drop.cs
+++ b/src/managed/Nota.App/DeviceChainView.Drop.cs
@@ -9,6 +9,7 @@
// presets, external files — lights the whole panel as before.
using System;
+using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
@@ -174,7 +175,7 @@ public sealed partial class DeviceChainView
if (trackId != _trackId) return; // only the shown chain has moved cards to follow
if (final != added) ExtrasMoved(k, added, final);
if (replaced) ExtrasRemoved(k, final + 1);
- _selChainKind = k; _selDeviceIndex = final; _instrumentSelected = false;
+ SelectDevices(new[] { (k, final) });
Rebuild(); Changed?.Invoke();
}
@@ -183,13 +184,14 @@ public sealed partial class DeviceChainView
internal Nota.Application.Palette.InsertPoint CurrentInsertPoint()
{
if (_trackId <= 0) return Nota.Application.Palette.InsertPoint.None;
- if (HasEffectSelection)
+ // The last selected effect (several selected: the palette inserts after the last one).
+ if (_sel.Members.LastOrDefault(m => m.Section != DeviceSection.Instrument) is { Section: var sec, Index: var di } && HasEffectSelection)
{
- bool midi = _selChainKind == ChainKind.Midi;
+ bool midi = sec == DeviceSection.Midi;
int n = midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);
- if (_selDeviceIndex < n)
- return new(midi ? Nota.Application.Palette.ChainSection.Midi : Nota.Application.Palette.ChainSection.Audio, _selDeviceIndex,
- midi ? _engine.MidiEffectName(_trackId, _selDeviceIndex) : _engine.DeviceName(_trackId, _selDeviceIndex));
+ if (di < n)
+ return new(midi ? Nota.Application.Palette.ChainSection.Midi : Nota.Application.Palette.ChainSection.Audio, di,
+ midi ? _engine.MidiEffectName(_trackId, di) : _engine.DeviceName(_trackId, di));
}
return Nota.Application.Palette.InsertPoint.None;
}
diff --git a/src/managed/Nota.App/DeviceChainView.Fold.cs b/src/managed/Nota.App/DeviceChainView.Fold.cs
index 4da2465f..7ecd11e5 100644
--- a/src/managed/Nota.App/DeviceChainView.Fold.cs
+++ b/src/managed/Nota.App/DeviceChainView.Fold.cs
@@ -105,7 +105,7 @@ public sealed partial class DeviceChainView
if (pt.IsRightButtonPressed) { ShowDeviceContextMenu(strip, k, di, Menu); return; }
if (!pt.IsLeftButtonPressed) return;
if (e.ClickCount == 2) { e.Handled = true; SetFolded(k, di, false); return; }
- SelectDevice(k, di);
+ SelectDevice(k, di, e.KeyModifiers);
};
HookDeviceDrag(strip, card, k, di); // the instrument's strip drags onto other tracks only
return card;
diff --git a/src/managed/Nota.App/DeviceChainView.Move.cs b/src/managed/Nota.App/DeviceChainView.Move.cs
index 43002a31..667c1ea3 100644
--- a/src/managed/Nota.App/DeviceChainView.Move.cs
+++ b/src/managed/Nota.App/DeviceChainView.Move.cs
@@ -116,6 +116,23 @@ public sealed partial class DeviceChainView
return new Control[] { menu };
}
+ // Move to track ▸ for several selected devices (specs/044): tracks that can take all of them.
+ // The host moves them in one undo step, the instrument last (it takes the source track).
+ private IEnumerable<Control> MoveSelectionToTrackGroup()
+ {
+ var menu = MenuKit.Item("Move to track", GlyphKind.Track);
+ var kind = _sel.HasInstrument || _sel.Indices(DeviceSection.Midi).Any() ? ChainKind.Midi : ChainKind.Effect;
+ foreach (var (id, name) in TracksThatTake(_engine, kind, _trackId))
+ menu.Items.Add(MenuKit.Item(name, null, () =>
+ {
+ var moves = _sel.Members.Select(m => new DeviceMoveRequest(_trackId, FamilyOf(KindOf(m.Section)), m.Index, id, false)).ToList();
+ ClearDeviceSelection();
+ MovesRequested?.Invoke(moves);
+ }));
+ menu.IsEnabled = menu.Items.Count > 0;
+ return new Control[] { menu };
+ }
+
internal static DeviceFamily FamilyOf(ChainKind k)
=> k switch { ChainKind.Midi => DeviceFamily.Midi, ChainKind.Instrument => DeviceFamily.Instrument, _ => DeviceFamily.Audio };
diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.cs
index 8bf5548c..37e22c51 100644
--- a/src/managed/Nota.App/DeviceChainView.Shell.cs
+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs
@@ -39,7 +39,8 @@ public sealed partial class DeviceChainView
// don't collide. Sig ties an entry to the device it was made for: when that slot now
// holds a different device (swapped, removed behind our back, undo), the card starts fresh.
private sealed class CardExtra { public string Sig = ""; public float[]? A, B; public int Active; public string Preset = "", PresetId = ""; public PluginCard.ViewState Plugin = new();
- public CardExtra? Wrapped; } // a rack's: the extra of the device ⌘G put in it, back when it comes out
+ public CardExtra? Wrapped; // a rack's: the extra of the device ⌘G put in it, back when it comes out
+ public List<CardExtra>? WrappedMany; } // a rack's: those of several devices grouped into it (specs/044)
private readonly System.Collections.Generic.Dictionary<int, System.Collections.Generic.Dictionary<int, CardExtra>> _cardExtra = new(); // trackId → key → extra
private static int ExtraKey(ChainKind k, int di) => k switch { ChainKind.Instrument => -1, ChainKind.Midi => -1000 - di, _ => di };
private static ChainKind KeyKind(int key) => key >= 0 ? ChainKind.Effect : key == -1 ? ChainKind.Instrument : ChainKind.Midi;
@@ -66,7 +67,11 @@ public sealed partial class DeviceChainView
// Undo / redo of ⌘G swap the device and its rack in one slot: each keeps the other's
// extra, so the A/B snapshots and preset label survive any number of swaps.
var prev = e;
- e = prev?.Wrapped is { } w && w.Sig == sig ? w : new CardExtra { Sig = sig };
+ e = prev?.Wrapped is { } w && w.Sig == sig ? w : null;
+ // Undo of a group of several devices (specs/044): the rack's card held all their
+ // states; hand each back to its device, which may sit in another slot.
+ if (e is null && prev?.WrappedMany is { } many) e = RestoreWrapped(t, d, many, key, sig);
+ e ??= new CardExtra { Sig = sig };
if (prev != null) { prev.Wrapped = null; e.Wrapped = prev; }
d[key] = e;
}
@@ -74,6 +79,32 @@ public sealed partial class DeviceChainView
}
private CardExtra Extra(ChainKind k, int di) => ExtraFor(_trackId, k, di);
+ // Gives each saved card state to a device on track t whose signature matches and that has no
+ // state of its own yet; returns the one for `ownKey`, or null.
+ private CardExtra? RestoreWrapped(int t, Dictionary<int, CardExtra> d, List<CardExtra> many, int ownKey, string ownSig)
+ {
+ CardExtra? own = null;
+ var slots = new List<(ChainKind K, int I)>();
+ for (int i = 0; i < _engine.TrackMidiEffectCount(t); i++) slots.Add((ChainKind.Midi, i));
+ if (IsInstrumentTrack(t)) slots.Add((ChainKind.Instrument, -1));
+ for (int i = 0; i < _engine.TrackDeviceCount(t); i++) slots.Add((ChainKind.Effect, i));
+ foreach (var x in many)
+ {
+ foreach (var (k, i) in slots)
+ {
+ int key = ExtraKey(k, i);
+ string sig = key == ownKey ? ownSig : CardSig(t, k, i);
+ if (sig != x.Sig) continue;
+ if (key == ownKey) { if (own != null) continue; own = x; break; }
+ // A card built a moment earlier in this rebuild holds a blank state: take its place.
+ if (d.TryGetValue(key, out var cur) && cur.Sig == sig && (cur.A != null || cur.B != null || cur.Preset.Length > 0)) continue;
+ d[key] = x;
+ break;
+ }
+ }
+ return own;
+ }
+
// Keep each card's extra glued to its device when this view reorders / removes devices.
// map: old index → new index, or -1 when the device is gone.
private void RemapExtras(ChainKind k, Func<int, int> map) => RemapExtras(_trackId, k, map);
@@ -371,7 +402,7 @@ public sealed partial class DeviceChainView
// selects and rebuilds the row, so the second lands on a new header.
if (e.ClickCount == 2 && !Within(e.Source, picker) && !Within(e.Source, power) && !Within(e.Source, s.HeaderExtra))
{ e.Handled = true; SetFolded(s.Kind, di, true); return; }
- SelectDevice(s.Kind, di);
+ SelectDevice(s.Kind, di, e.KeyModifiers); // Shift: a range, ⌘/Ctrl: toggle (specs/044)
};
DockPanel.SetDock(headerBar, Dock.Top);
diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.cs
index 4fe952c2..b72591f6 100644
--- a/src/managed/Nota.App/DeviceChainView.cs
+++ b/src/managed/Nota.App/DeviceChainView.cs
@@ -76,7 +76,11 @@ public sealed partial class DeviceChainView : UserControl
public event Action<string>? StatusMessage;
/// <summary>The instrument's Delete / Cut / Remove (specs/043): the host deletes the track
/// (trackId), asking first when it has clips. <c>cut</c>: the instrument was copied first.</summary>
- public event Action<int, bool>? TrackDeleteRequested;
+ // The instrument's Delete / Cut take its track (specs/043): (track, cut, how many devices were
+ // selected — more than one means the host asks every time, specs/044).
+ public event Action<int, bool, int>? TrackDeleteRequested;
+ // Move to track ▸ for several selected devices (specs/044), in chain order.
+ public event Action<System.Collections.Generic.IReadOnlyList<DeviceMoveRequest>>? MovesRequested;
/// <summary>Replace… in the instrument's menu: the host swaps the shown track's instrument
/// for this one (racks included), one undo step.</summary>
public event Action<BrowserItem>? InstrumentReplaceRequested;
@@ -123,11 +127,19 @@ public sealed partial class DeviceChainView : UserControl
scroller.Offset = scroller.Offset.WithX(x);
e.Handled = true;
};
+ // A click on the chain's empty space clears the selection (specs/044).
+ scroller.Background = Brushes.Transparent;
+ scroller.PointerPressed += (_, e) =>
+ {
+ if (!HasDeviceSelection || !e.GetCurrentPoint(scroller).Properties.IsLeftButtonPressed) return;
+ if (e.Source is ScrollViewer or Avalonia.Controls.Presenters.ScrollContentPresenter || ReferenceEquals(e.Source, _row))
+ { ClearDeviceSelection(); Rebuild(); }
+ };
Content = new Panel { Children = { scroller, _dropGlow, _dropLayer } };
HookBrowserDrop();
}
- public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; _selDeviceIndex = -1; _instrumentSelected = false; _rackSel = null; _rackCmds = null; Rebuild(); }
+ public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; ClearDeviceSelection(); _rackSel = null; _rackCmds = null; Rebuild(); }
/// <summary>Forgets every card's remembered preset label + A/B slots (a project was
/// opened / created, so track ids no longer mean the same tracks).</summary>
@@ -198,6 +210,7 @@ public sealed partial class DeviceChainView : UserControl
// MIDI effects sit before the instrument (they shape the note stream).
int midiCount = _engine.TrackMidiEffectCount(_trackId);
+ _sel.Prune(midiCount, IsInstrumentTrack(_trackId), _engine.TrackDeviceCount(_trackId)); // an edit elsewhere shrank the chain
for (int i = 0; i < midiCount; i++) _row.Children.Add(MidiDeviceCard(i, midiCount));
if (IsInstrumentTrack(_trackId)) _row.Children.Add(_instrumentCard = InstrumentCard());
diff --git a/src/managed/Nota.App/MainWindow.DeviceMoves.cs b/src/managed/Nota.App/MainWindow.DeviceMoves.cs
index c35338b1..ab1ef721 100644
--- a/src/managed/Nota.App/MainWindow.DeviceMoves.cs
+++ b/src/managed/Nota.App/MainWindow.DeviceMoves.cs
@@ -5,6 +5,8 @@
// card, and moving a device to another track (menu or drag onto a track header). An instrument
// track never stands without its instrument, so deleting it — or moving it away — takes the track.
+using System.Collections.Generic;
+using System.Linq;
using System.Threading.Tasks;
using Nota.Application;
using Nota.Presentation;
@@ -17,8 +19,9 @@ public partial class MainWindow
{
if (_deviceChain is null) return;
_deviceChain.InstrumentReplaceRequested += OnInstrumentReplaceRequested;
- _deviceChain.TrackDeleteRequested += (t, cut) => _ = OnTrackDeleteRequestedAsync(t, cut);
+ _deviceChain.TrackDeleteRequested += (t, cut, n) => _ = OnTrackDeleteRequestedAsync(t, cut, n);
_deviceChain.MoveRequested += r => _ = OnDeviceMoveRequestedAsync(r);
+ _deviceChain.MovesRequested += m => _ = OnDevicesMoveRequestedAsync(m);
Timeline.DeviceDropped += r => _ = OnDeviceMoveRequestedAsync(r); // a card dragged onto a track row
}
@@ -55,17 +58,62 @@ public partial class MainWindow
return await new ConfirmWindow("Delete track", message, affirmative, "Cancel").ShowDialog<bool>(this);
}
- private async Task OnTrackDeleteRequestedAsync(int trackId, bool cut)
+ // selected: how many devices the panel had selected. With the instrument and more (specs/044)
+ // the host asks every time: a Shift-click range that swept over the instrument must not
+ // take the track silently.
+ private async Task OnTrackDeleteRequestedAsync(int trackId, bool cut, int selected = 1)
{
if (_vm is null || trackId <= 0) return;
string name = TrackLabel(trackId), inst = Engine.DeviceName(trackId, -1);
- if (!await ConfirmTrackGoesAsync(trackId, $"“{name}” has clips. Delete the track with its clips?", "Delete")) return;
+ if (selected > 1)
+ {
+ if (!await new ConfirmWindow("Delete track", $"Delete track “{name}”? The track and its {selected} selected devices will be removed.",
+ "Delete", "Cancel").ShowDialog<bool>(this)) return;
+ }
+ else if (!await ConfirmTrackGoesAsync(trackId, $"“{name}” has clips. Delete the track with its clips?", "Delete")) return;
if (!Timeline.DeleteTrack(trackId)) return;
if (_deviceChain?.TrackId == trackId) ShowDevices(-1, takeOverPanel: false); // its cards would edit a removed track
_session?.Refresh();
_vm.StatusText = cut ? $"Cut {inst} — deleted {name}" : $"Deleted {name}";
}
+ // Move to track ▸ for several selected devices (specs/044): one undo step, in chain order so
+ // they land in order at the end of the target's sections; the instrument goes last (it takes
+ // the source track) and, with others, always asks first.
+ private async Task OnDevicesMoveRequestedAsync(IReadOnlyList<DeviceMoveRequest> moves)
+ {
+ if (_vm is null || moves.Count == 0) return;
+ if (moves.Count == 1) { await OnDeviceMoveRequestedAsync(moves[0]); return; }
+ int srcId = moves[0].SrcTrackId, dstId = moves[0].DstTrackId;
+ string src = TrackLabel(srcId), dst = TrackLabel(dstId);
+ bool withInstrument = moves.Any(m => m.Family == DeviceFamily.Instrument);
+ if (withInstrument && !await new ConfirmWindow("Delete track",
+ $"Move {moves.Count} devices to “{dst}” and delete “{src}”?", "Move", "Cancel").ShowDialog<bool>(this))
+ return;
+ int moved = 0, failed = 0;
+ var shift = new Dictionary<DeviceFamily, int>(); // earlier moves of a section close its gaps
+ Engine.BeginUndoGroup();
+ try
+ {
+ foreach (var r in moves.Where(m => m.Family != DeviceFamily.Instrument).Concat(moves.Where(m => m.Family == DeviceFamily.Instrument)))
+ {
+ int gone = shift.TryGetValue(r.Family, out var g) ? g : 0;
+ var req = r with { Index = r.Family == DeviceFamily.Instrument ? r.Index : r.Index - gone };
+ int at = Engine.TransferDevice(req.SrcTrackId, req.Family, req.Index, req.DstTrackId, -1, false, out _);
+ if (at < 0) { failed++; continue; }
+ _deviceChain?.DeviceTransferred(req, at);
+ shift[r.Family] = gone + 1;
+ moved++;
+ }
+ }
+ finally { Engine.EndUndoGroup(); }
+ Timeline.Refresh();
+ _session?.Refresh();
+ if (dstId != Engine.MasterTrackId) Timeline.Select(dstId, -1);
+ ShowDevices(dstId);
+ _vm.StatusText = failed == 0 ? $"Moved {moved} devices to {dst}" : $"Moved {moved} devices to {dst} · {failed} couldn't move";
+ }
+
// Move to track ▸, or a device card dropped on a track header (⌥ = copy). One undo step; an
// instrument's move takes its track away, so a track with clips asks first.
private async Task OnDeviceMoveRequestedAsync(DeviceMoveRequest r)
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 3e64918a..7c6b328f 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -1166,7 +1166,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("⌘⇧M", "Toggle the Mixer view"),
("Tab", "Cycle Devices / Pattern / Clip in the detail panel"),
("Esc", "Cancel the current gesture / clear the selection · close the patch-bay overlay"),
- ("⌘G ⌘⇧G", "Group / ungroup selected tracks · on a selected device: wrap it in a rack / take it out"),
+ ("⌘G ⌘⇧G", "Group / ungroup selected tracks · on selected devices: group them into a rack / take a rack apart"),
("⌘C ⌘X ⌘V", "Copy / cut / paste clips, a time range or an automation range · pastes onto the track clicked last"),
("⌘⇧C", "Copy the selected clips to Session · the first scene row where they fit"),
("⌘⇧V", "Paste the last range as audio rendered through its devices"),
@@ -1201,11 +1201,14 @@ public sealed partial class PreferencesWindow : NotaWindow
}),
("Devices (after a click on a device)", new[]
{
- ("⌘C ⌘X ⌘V", "Copy / cut / paste the device with all its settings · paste lands after the selected device, on any track or rack chain · a copied instrument replaces the instrument it is pasted on"),
- ("⌘D", "Duplicate the selected device"),
- ("⌘G", "Wrap the selected audio effect in an Audio Effect Rack"),
+ ("⇧-click ⌘-click", "Select a range of devices (MIDI effects, instrument, audio effects) / add or remove one"),
+ ("Esc", "Clear the device selection · so does a click on the chain's empty space"),
+ ("⌘C ⌘X ⌘V", "Copy / cut / paste the selected devices with all their settings · each lands in its section after the selected device · a copied instrument replaces the instrument it is pasted on"),
+ ("⌘D", "Duplicate the selected devices · each run right after itself"),
+ ("⌘G", "Group the selected devices into a rack · audio effects: Audio Effect Rack · MIDI effects: MIDI Effect Rack · with the instrument: Instrument Rack"),
("⌘⇧G", "Take the devices out of a selected one-chain rack"),
- ("Delete", "Delete the selected device · on the instrument, its track"),
+ ("Delete", "Delete the selected devices · with the instrument, its track"),
+ ("Drag a selected device's header", "Move the selected devices of that section together"),
("Drag a device onto a track", "Move it there (out of the panel, onto a track row or Session column) · the instrument replaces that track's and its own track goes"),
("⌥-drag a device onto a track", "Copy it there"),
}),
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index 5078ee9e..4c0ace7e 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -259,6 +259,30 @@ public enum DeviceFamily { Audio = 0, Midi = 1, Instrument = 2 }
[Flags]
public enum TransferFlags { None = 0, SidechainCleared = 1, LinksDropped = 2, SourceTrackRemoved = 4 }
+/// <summary>Where a CV link's source and target sit when they reach into a rack (specs/044):
+/// chain index and slot, -1 at track level.</summary>
+public readonly record struct CvLinkPath(int SourceChain, int SourceSlot, int TargetChain, int TargetSlot);
+
+/// <summary>A rack chain MIDI effect's CC target (specs/044): a device on the track, or the
+/// child (Chain, Slot) of the rack at Device; Chain -1 = track level.</summary>
+public readonly record struct NestedCcDest(int Device, int Chain, int Slot, int Param, float Depth);
+
+/// <summary>A rack chain child's sidechain key (specs/044); SourceTrack -1 = none.</summary>
+public readonly record struct NestedSidechain(int SourceTrack, bool TapPre, float GainDb, float Mix);
+
+/// <summary>Why nota_track_group_devices refused a run (specs/044).</summary>
+public enum GroupRefusal
+{
+ BadRun = -2, NotContiguous = -3, RackInRun = -4, CantHost = -5, InstrumentCantNest = -6, NotInstrumentTrack = -7,
+}
+
+/// <summary>Why nota_track_ungroup_rack refused (specs/044).</summary>
+public enum UngroupRefusal { NotARack = -2, SeveralChains = -3, DrumRack = -4, NoInstrument = -5 }
+
+/// <summary>What an ungroup left behind (nota_track_ungroup_rack's out_dropped).</summary>
+[Flags]
+public enum UngroupDropped { None = 0, MacroMappings = 1, ChainMix = 2 }
+
/// <summary>Project pan law (specs/006). Matches NOTA_PAN_LAW_*: Balance drops the far
/// channel as a track pans, Stereo folds it into the near side.</summary>
public enum PanLaw { Balance = 0, Stereo = 1 }
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 07840e23..26ae235b 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -512,7 +512,7 @@ public interface IAudioEngine : IDisposable
// Device clipboard (#238): a full clone held by the engine; paste is one undo step.
bool CopyDevice(int trackId, int deviceIndex);
bool CopyMidiEffect(int trackId, int index);
- int DeviceClipboardKind(); // 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument
+ int DeviceClipboardKind(); // 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument, 4 several
bool DeviceClipboardSidechain(); // the copied audio effect is keyed from another track
int PasteDevice(int trackId, int atIndex); // atIndex -1 = end; new index or -1
int PasteMidiEffect(int trackId, int atIndex);
@@ -528,9 +528,20 @@ public interface IAudioEngine : IDisposable
// clone failed. A move takes the device's automation; the instrument's removes its track.
int TransferDevice(int srcTrackId, DeviceFamily family, int index, int dstTrackId, int atIndex, bool keepSource, out TransferFlags flags);
// ⌘G / ⌘⇧G on a device (#257): wrap an audio effect in an Audio Effect Rack (its index or
- // -1: keyed / automated / CV-linked devices stay out), unwrap a one-chain rack (count or -1).
+ // -1), unwrap a one-chain Audio Effect Rack (count or -1). The one-device cases of:
int WrapDeviceInRack(int trackId, int deviceIndex);
int UnwrapRack(int trackId, int deviceIndex);
+ // Group a contiguous run into a rack in its place, links following (specs/044); one undo
+ // step. Returns the rack's address (>= 0 effect, -1 the instrument, -1000 - i MIDI effect)
+ // or a GroupRefusal (< -1). See nota_track_group_devices.
+ int GroupDevices(int trackId, int midiFirst, int midiCount, bool withInstrument, int fxFirst, int fxCount);
+ // Ungroup a one-chain rack: devices restored (>= 0) or an UngroupRefusal (< 0).
+ int UngroupRack(int trackId, DeviceFamily family, int index, out UngroupDropped dropped);
+ // Several devices on the clipboard (specs/044): count, or -1. Paste: the number pasted (>= 0,
+ // skipped = what the track can't take), -1 empty, -3 a clone failed.
+ int CopyDevices(int trackId, int[] midiIndices, bool withInstrument, int[] fxIndices);
+ int DeviceClipboardCount();
+ int PasteDevices(int trackId, int midiAt, int fxAt, out int skipped);
string DeviceName(int trackId, int deviceIndex);
int DeviceParamCount(int trackId, int deviceIndex);
string DeviceParamName(int trackId, int deviceIndex, int paramIndex);
@@ -581,6 +592,16 @@ public interface IAudioEngine : IDisposable
void SetMidiEffectCcDepth(int trackId, int index, float depth);
int MidiEffectCcDestDevice(int trackId, int index);
int MidiEffectCcDestParam(int trackId, int index);
+ // The CC target inside a rack (specs/044): chain index + slot, (-1, -1) at track level.
+ (int Chain, int Slot) MidiEffectCcDestPath(int trackId, int index);
+ bool SetMidiEffectCcDestPath(int trackId, int index, int chain, int slot);
+ // What lives on rack chain children outside the rack blob (specs/044; save / load): a chain
+ // MIDI effect's CC target and a child's sidechain key (slot >= 0 a device, -1 the chain
+ // instrument). rackAddress as the rack calls take it (>= 0 effect, -1 instrument, -1000 - i).
+ NestedCcDest? RackChainMidiCcDest(int trackId, int rackAddress, int chain, int index);
+ bool RackChainMidiSetCcDest(int trackId, int rackAddress, int chain, int index, NestedCcDest dest);
+ NestedSidechain? RackChainSidechain(int trackId, int rackAddress, int chain, int slot);
+ bool RackChainSetSidechain(int trackId, int rackAddress, int chain, int slot, NestedSidechain sc);
float MidiEffectCcDepth(int trackId, int index);
/// <summary>Copies up to maxSamples of the device's live readings into outSamples; returns
/// the count written. Each device defines its own layout (the analysers: a telemetry block,
@@ -946,6 +967,9 @@ public interface IAudioEngine : IDisposable
bool RackDevChainMidiCopy(int trackId, int deviceIndex, int chain, int index);
int RackDevChainDevicePaste(int trackId, int deviceIndex, int chain, int atIndex);
int RackDevChainMidiPaste(int trackId, int deviceIndex, int chain, int atIndex);
+ // Several devices on the clipboard into a chain (specs/044): the number pasted (>= 0), with the
+ // skipped count and the first new index per section (-1 none); -1 nothing / bad address, -3 clone failed.
+ int RackDevChainPasteDevices(int trackId, int deviceIndex, int chain, int midiAt, int fxAt, out int skipped, out int firstMidi, out int firstFx);
int RackDevChainDeviceDuplicate(int trackId, int deviceIndex, int chain, int index);
int RackDevChainMidiDuplicate(int trackId, int deviceIndex, int chain, int index);
int RackDevChainDeviceMoveTo(int trackId, int deviceIndex, int chain, int index, int toChain);
@@ -1174,6 +1198,10 @@ public interface IAudioEngine : IDisposable
void PluginParamSet(int trackId, int deviceIndex, int paramIndex, float normalized);
int AddPluginAutomationLane(int trackId, int deviceIndex, string paramId);
string AutomationLaneParamId(int trackId, int laneIndex);
+ // A lane on a device grouped into a rack (specs/044): (chain index, slot) in the rack at the
+ // lane's device index; (-1, -1) for a track-level lane. AddNested is for project load.
+ (int Chain, int Slot) AutomationLanePath(int trackId, int laneIndex);
+ int AddNestedAutomationLane(int trackId, AutomationTarget target, int deviceIndex, int chain, int slot, int paramIndex, string? paramId);
int PluginLastTouchedParam(int trackId, int deviceIndex); // "Learn" (M9-B3)
bool AutomationWriteSelfTest(); // M9-C: device-free write-path check
bool AutomationDeviceRemapSelfTest(); // lanes follow their device on reorder / remove
@@ -1264,6 +1292,11 @@ public interface IAudioEngine : IDisposable
int CvLinkTargetTrack(int trackId, int index);
int CvLinkDevice(int trackId, int index);
int CvLinkParam(int trackId, int index);
+ // Links reaching into a rack (specs/044): chain index + slot of the source / target, -1 at
+ // track level. AddNested is for project load (kinds as CvLinkAddFromParamToTarget).
+ CvLinkPath CvLinkPath(int trackId, int index);
+ int CvLinkAddNested(int trackId, int sourceKind, int modId, int srcDevice, int srcChain, int srcSlot, int srcParam,
+ int targetKind, int targetTrack, int targetDevice, int tgtChain, int tgtSlot, int targetParam);
float CvLinkDepth(int trackId, int index);
int CvLinkMode(int trackId, int index);
void SetCvLinkDepth(int trackId, int index, float depth);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Automation.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Automation.cs
index bbec418b..cd1cfc68 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Automation.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Automation.cs
@@ -24,6 +24,13 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_track_add_plugin_automation_lane", StringMarshalling = StringMarshalling.Utf8)]
internal static partial int AddPluginAutomationLane(IntPtr engine, int trackId, int deviceIndex, string paramId);
+ [LibraryImport(Lib, EntryPoint = "nota_track_automation_lane_path")]
+ internal static partial NotaResult AutomationLanePath(IntPtr engine, int trackId, int laneIndex, out int chain, out int slot);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_add_nested_automation_lane", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial int AddNestedAutomationLane(IntPtr engine, int trackId, int target, int deviceIndex, int chain,
+ int slot, int paramIndex, string? paramId);
+
[LibraryImport(Lib, EntryPoint = "nota_track_automation_lane_param_id")]
internal static partial IntPtr AutomationLaneParamId(IntPtr engine, int trackId, int laneIndex);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
index cf2b3c23..bbd1bc08 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
@@ -77,6 +77,46 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_track_unwrap_rack")]
internal static partial int UnwrapRack(IntPtr engine, int trackId, int deviceIndex);
+ [LibraryImport(Lib, EntryPoint = "nota_track_group_devices")]
+ internal static partial int GroupDevices(IntPtr engine, int trackId, int midiFirst, int midiCount, int withInstrument,
+ int fxFirst, int fxCount);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_ungroup_rack")]
+ internal static partial int UngroupRack(IntPtr engine, int trackId, int family, int index, out int dropped);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_copy_devices")]
+ internal static partial int CopyDevices(IntPtr engine, int trackId, int[] midiIdx, int midiN, int withInstrument,
+ int[] fxIdx, int fxN);
+
+ [LibraryImport(Lib, EntryPoint = "nota_device_clipboard_count")]
+ internal static partial int DeviceClipboardCount(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_paste_devices")]
+ internal static partial int PasteDevices(IntPtr engine, int trackId, int midiAt, int fxAt, out int skipped);
+
+ [LibraryImport(Lib, EntryPoint = "nota_midi_effect_cc_dest_path")]
+ internal static partial int MidiEffectCcDestPath(IntPtr engine, int trackId, int index, out int chain, out int slot);
+
+ [LibraryImport(Lib, EntryPoint = "nota_midi_effect_set_cc_dest_path")]
+ internal static partial int MidiEffectSetCcDestPath(IntPtr engine, int trackId, int index, int chain, int slot);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_cc_dest")]
+ internal static partial int RackChainMidiCcDest(IntPtr engine, int trackId, int deviceIndex, int chain, int index,
+ out int destDevice, out int destChain, out int destSlot, out int param,
+ out float depth);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_set_cc_dest")]
+ internal static partial int RackChainMidiSetCcDest(IntPtr engine, int trackId, int deviceIndex, int chain, int index,
+ int destDevice, int destChain, int destSlot, int param, float depth);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_sidechain")]
+ internal static partial int RackChainSidechain(IntPtr engine, int trackId, int deviceIndex, int chain, int slot,
+ out int sourceTrack, out int tapPre, out float gainDb, out float mix);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_set_sidechain")]
+ internal static partial int RackChainSetSidechain(IntPtr engine, int trackId, int deviceIndex, int chain, int slot,
+ int sourceTrack, int tapPre, float gainDb, float mix);
+
[LibraryImport(Lib, EntryPoint = "nota_device_name")]
internal static partial IntPtr DeviceName(IntPtr engine, int trackId, int deviceIndex);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs
index 83260536..a1b22b05 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs
@@ -87,6 +87,15 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_track_cv_link_param")]
internal static partial int CvLinkParam(IntPtr engine, int trackId, int index);
+ [LibraryImport(Lib, EntryPoint = "nota_track_cv_link_path")]
+ internal static partial int CvLinkPath(IntPtr engine, int trackId, int index, out int srcChain, out int srcSlot,
+ out int tgtChain, out int tgtSlot);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_add_nested_cv_link")]
+ internal static partial int AddNestedCvLink(IntPtr engine, int trackId, int sourceKind, int modId, int srcDevice,
+ int srcChain, int srcSlot, int srcParam, int targetKind, int targetTrack,
+ int targetDevice, int tgtChain, int tgtSlot, int targetParam);
+
[LibraryImport(Lib, EntryPoint = "nota_track_cv_link_depth")]
internal static partial float CvLinkDepth(IntPtr engine, int trackId, int index);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs
index de0b99a9..a65fc8ad 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs
@@ -215,6 +215,10 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_midi_paste")]
internal static partial int RackDevChainMidiPaste(IntPtr engine, int trackId, int deviceIndex, int chain, int atIndex);
+ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_paste_devices")]
+ internal static partial int RackDevChainPasteDevices(IntPtr engine, int trackId, int deviceIndex, int chain, int midiAt, int fxAt,
+ out int skipped, out int firstMidi, out int firstFx);
+
[LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_device_duplicate")]
internal static partial int RackDevChainDeviceDuplicate(IntPtr engine, int trackId, int deviceIndex, int chain, int index);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
index 1ec86a3b..0f8b4347 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
@@ -121,6 +121,25 @@ public sealed partial class NotaEngine
public int UnwrapRack(int trackId, int deviceIndex)
{ ThrowIfDisposed(); return NativeMethods.UnwrapRack(_handle, trackId, deviceIndex); }
+ public int GroupDevices(int trackId, int midiFirst, int midiCount, bool withInstrument, int fxFirst, int fxCount)
+ { ThrowIfDisposed(); return NativeMethods.GroupDevices(_handle, trackId, midiFirst, midiCount, withInstrument ? 1 : 0, fxFirst, fxCount); }
+
+ public int UngroupRack(int trackId, DeviceFamily family, int index, out UngroupDropped dropped)
+ {
+ ThrowIfDisposed();
+ int r = NativeMethods.UngroupRack(_handle, trackId, (int)family, index, out int d);
+ dropped = (UngroupDropped)d;
+ return r;
+ }
+
+ public int CopyDevices(int trackId, int[] midiIndices, bool withInstrument, int[] fxIndices)
+ { ThrowIfDisposed(); return NativeMethods.CopyDevices(_handle, trackId, midiIndices, midiIndices.Length, withInstrument ? 1 : 0, fxIndices, fxIndices.Length); }
+
+ public int DeviceClipboardCount() { ThrowIfDisposed(); return NativeMethods.DeviceClipboardCount(_handle); }
+
+ public int PasteDevices(int trackId, int midiAt, int fxAt, out int skipped)
+ { ThrowIfDisposed(); return NativeMethods.PasteDevices(_handle, trackId, midiAt, fxAt, out skipped); }
+
public string DeviceName(int trackId, int deviceIndex)
{ ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.DeviceName(_handle, trackId, deviceIndex)) ?? ""; }
@@ -232,6 +251,37 @@ public sealed partial class NotaEngine
public void SetMidiEffectCcDepth(int trackId, int index, float depth) { ThrowIfDisposed(); NativeMethods.MidiEffectSetCcDepth(_handle, trackId, index, depth); }
public int MidiEffectCcDestDevice(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDestDevice(_handle, trackId, index); }
public int MidiEffectCcDestParam(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDestParam(_handle, trackId, index); }
+ public (int Chain, int Slot) MidiEffectCcDestPath(int trackId, int index)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.MidiEffectCcDestPath(_handle, trackId, index, out int c, out int s) == 0 ? (c, s) : (-1, -1);
+ }
+ public bool SetMidiEffectCcDestPath(int trackId, int index, int chain, int slot)
+ { ThrowIfDisposed(); return NativeMethods.MidiEffectSetCcDestPath(_handle, trackId, index, chain, slot) == 0; }
+ public NestedCcDest? RackChainMidiCcDest(int trackId, int rackAddress, int chain, int index)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.RackChainMidiCcDest(_handle, trackId, rackAddress, chain, index, out int dev, out int dc, out int ds,
+ out int p, out float depth) == 0 ? new NestedCcDest(dev, dc, ds, p, depth) : null;
+ }
+ public bool RackChainMidiSetCcDest(int trackId, int rackAddress, int chain, int index, NestedCcDest dest)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.RackChainMidiSetCcDest(_handle, trackId, rackAddress, chain, index, dest.Device, dest.Chain,
+ dest.Slot, dest.Param, dest.Depth) == 0;
+ }
+ public NestedSidechain? RackChainSidechain(int trackId, int rackAddress, int chain, int slot)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.RackChainSidechain(_handle, trackId, rackAddress, chain, slot, out int src, out int pre,
+ out float g, out float m) == 0 ? new NestedSidechain(src, pre != 0, g, m) : null;
+ }
+ public bool RackChainSetSidechain(int trackId, int rackAddress, int chain, int slot, NestedSidechain sc)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.RackChainSetSidechain(_handle, trackId, rackAddress, chain, slot, sc.SourceTrack, sc.TapPre ? 1 : 0,
+ sc.GainDb, sc.Mix) == 0;
+ }
public float MidiEffectCcDepth(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDepth(_handle, trackId, index); }
public void SetDeviceSidechainSource(int trackId, int deviceIndex, int sourceTrackId)
@@ -379,6 +429,13 @@ public sealed partial class NotaEngine
{ ThrowIfDisposed(); return NativeMethods.AddPluginAutomationLane(_handle, trackId, deviceIndex, paramId); }
public string AutomationLaneParamId(int trackId, int laneIndex)
{ ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.AutomationLaneParamId(_handle, trackId, laneIndex)) ?? ""; }
+ public (int Chain, int Slot) AutomationLanePath(int trackId, int laneIndex)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.AutomationLanePath(_handle, trackId, laneIndex, out int c, out int sl) == NativeMethods.NotaResult.Ok ? (c, sl) : (-1, -1);
+ }
+ public int AddNestedAutomationLane(int trackId, AutomationTarget target, int deviceIndex, int chain, int slot, int paramIndex, string? paramId)
+ { ThrowIfDisposed(); return NativeMethods.AddNestedAutomationLane(_handle, trackId, (int)target, deviceIndex, chain, slot, paramIndex, paramId); }
public int PluginLastTouchedParam(int trackId, int deviceIndex)
{ ThrowIfDisposed(); return NativeMethods.PluginLastTouchedParam(_handle, trackId, deviceIndex); }
}
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs
index a25843a4..3ddfd69f 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs
@@ -60,6 +60,21 @@ public sealed partial class NotaEngine
{ ThrowIfDisposed(); return NativeMethods.CvLinkDevice(_handle, trackId, index); }
public int CvLinkParam(int trackId, int index)
{ ThrowIfDisposed(); return NativeMethods.CvLinkParam(_handle, trackId, index); }
+
+ public CvLinkPath CvLinkPath(int trackId, int index)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.CvLinkPath(_handle, trackId, index, out int sc, out int ss, out int tc, out int ts) == 0
+ ? new CvLinkPath(sc, ss, tc, ts) : new CvLinkPath(-1, -1, -1, -1);
+ }
+
+ public int CvLinkAddNested(int trackId, int sourceKind, int modId, int srcDevice, int srcChain, int srcSlot, int srcParam,
+ int targetKind, int targetTrack, int targetDevice, int tgtChain, int tgtSlot, int targetParam)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.AddNestedCvLink(_handle, trackId, sourceKind, modId, srcDevice, srcChain, srcSlot, srcParam,
+ targetKind, targetTrack, targetDevice, tgtChain, tgtSlot, targetParam);
+ }
public float CvLinkDepth(int trackId, int index)
{ ThrowIfDisposed(); return NativeMethods.CvLinkDepth(_handle, trackId, index); }
public int CvLinkMode(int trackId, int index)
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs
index f0d47407..f770af77 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs
@@ -217,6 +217,8 @@ public sealed partial class NotaEngine
public int RackDevChainMidiPaste(int trackId, int deviceIndex, int chain, int atIndex)
{ ThrowIfDisposed(); return NativeMethods.RackDevChainMidiPaste(_handle, trackId, deviceIndex, chain, atIndex); }
+ public int RackDevChainPasteDevices(int trackId, int deviceIndex, int chain, int midiAt, int fxAt, out int skipped, out int firstMidi, out int firstFx)
+ { ThrowIfDisposed(); return NativeMethods.RackDevChainPasteDevices(_handle, trackId, deviceIndex, chain, midiAt, fxAt, out skipped, out firstMidi, out firstFx); }
public int RackDevChainDeviceDuplicate(int trackId, int deviceIndex, int chain, int index)
{ ThrowIfDisposed(); return NativeMethods.RackDevChainDeviceDuplicate(_handle, trackId, deviceIndex, chain, index); }
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index 4240df47..0478130f 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -100,6 +100,10 @@ public static class ProjectMigrations
// v23 -> v24: MIDI effects gain State (the MIDI Effect Rack's blob, specs/040). Absent in
// v23 documents, which hold no MIDI Effect Rack; null = params only — no-op.
new Migration(23, _ => { }),
+ // v24 -> v25: lanes, CV links and Arp CC targets may point into a rack chain, and racks'
+ // chain children keep sidechain keys and CC targets in the track (specs/044). All absent
+ // in v24 documents, where every reference is track level — no-op.
+ new Migration(24, _ => { }),
};
/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 63db8b5e..d2c4c1cb 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -63,6 +63,8 @@ public sealed class MasterDto
public string? Name { get; set; }
public int ColorIndex { get; set; } = -1;
public List<DeviceDto> Devices { get; set; } = new();
+ // Sidechain keys of devices inside the master's racks (v25, specs/044), as on a track.
+ public List<NestedSidechainDto>? NestedSidechains { get; set; }
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
@@ -134,6 +136,11 @@ public sealed class TrackDto
public List<AutomationLaneDto> Automation { get; set; } = new(); // M9-A4 (format v2)
public List<ModulatorDto> Modulators { get; set; } = new(); // CV modulation sources (Phase 3)
public List<CvLinkDto> CvLinks { get; set; } = new(); // CV modulation edges (Phase 3)
+ // Links on devices inside the track's racks that the rack blob can't hold (v25, specs/044):
+ // a chain child's sidechain key (its source is a doc index, like a device's) and a chain
+ // MIDI effect's CC target. Null = none.
+ public List<NestedSidechainDto>? NestedSidechains { get; set; }
+ public List<NestedCcRouteDto>? NestedCcRoutes { get; set; }
/// <summary>Freeze (M7): relative path to the track's frozen-audio blob in
/// <c>plugin-states/</c> (null = not frozen). Restored + re-flagged frozen on load.</summary>
public string? FrozenState { get; set; }
@@ -176,6 +183,12 @@ public sealed class CvLinkDto
public int TargetTrack { get; set; } = -1;
public int Device { get; set; } = -1;
public int Param { get; set; } = -1;
+ // A source / target inside a rack (v25, specs/044): SourceDevice / Device is then the rack's
+ // address and these the chain index and slot. Null = track level.
+ public int? SourceChain { get; set; }
+ public int? SourceSlot { get; set; }
+ public int? TargetChain { get; set; }
+ public int? TargetSlot { get; set; }
public float Depth { get; set; } = 1.0f;
public int Mode { get; set; }
/// <summary>Modulation centre (base) value — the device param value the link swings around.</summary>
@@ -186,6 +199,37 @@ public sealed class CvLinkDto
/// <summary>A parameter-automation lane and its breakpoints (M9-A4, format v2).
/// Target: 0 = track volume, 1 = pan, 2 = built-in device param (Device/Param set).</summary>
+/// <summary>A rack chain child's sidechain key (v25, specs/044). Host is the rack's address on
+/// the track, Slot >= 0 a device, -1 the chain instrument; Source a doc index.</summary>
+public sealed class NestedSidechainDto
+{
+ public int Host { get; set; }
+ public int Chain { get; set; }
+ public int Slot { get; set; }
+ public int Source { get; set; } = -1;
+ public bool TapPre { get; set; }
+ public float GainDb { get; set; }
+ public float Mix { get; set; } = 1.0f;
+
+ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
+}
+
+/// <summary>A rack chain MIDI effect's CC target (v25, specs/044): the MIDI effect at (Host,
+/// Chain, Index) drives DestDevice's Param, or the child (DestChain, DestSlot) of the rack there.</summary>
+public sealed class NestedCcRouteDto
+{
+ public int Host { get; set; }
+ public int Chain { get; set; }
+ public int Index { get; set; }
+ public int DestDevice { get; set; } = -2;
+ public int DestChain { get; set; } = -1;
+ public int DestSlot { get; set; } = -1;
+ public int Param { get; set; } = -1;
+ public float Depth { get; set; } = 1.0f;
+
+ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
+}
+
public sealed class AutomationLaneDto
{
public int Target { get; set; }
@@ -194,6 +238,11 @@ public sealed class AutomationLaneDto
/// <summary>Stable hosted-plugin parameter id when Target == 3 (PluginParam, M9-B4).
/// Persisted instead of the version-unstable index; resolved on load.</summary>
public string? PluginParamId { get; set; }
+ // A lane on a device grouped into a rack (v25, specs/044): DeviceIndex is then the rack's
+ // address (>= 0 effect, -1 instrument, -1000 - i MIDI effect) and these the chain index and
+ // slot (>= 0 device, -1 chain instrument, -1000 - i chain MIDI effect). Null = track level.
+ public int? Chain { get; set; }
+ public int? Slot { get; set; }
public AutomationPointDto[] Points { get; set; } = System.Array.Empty<AutomationPointDto>();
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
@@ -349,6 +398,9 @@ public sealed class MidiDeviceDto
// Map/CC routing (arp): CC lane → an audio-device param on the same track.
public int CcDestDevice { get; set; } = -2; // -2 = no routing
public int CcDestParam { get; set; } = -1;
+ // A CC target inside a rack (v25, specs/044): chain index + slot in the rack at CcDestDevice.
+ public int? CcDestChain { get; set; }
+ public int? CcDestSlot { get; set; }
public float CcDepth { get; set; } = 1.0f;
// Opaque state blob (v24, specs/040): the MIDI Effect Rack's chains, devices, zones and
// macros. Null for params-only MIDI effects.
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 0fb1b4cd..7cae8346 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -33,7 +33,9 @@ public sealed class ProjectService
/// v18 (Phase 3) adds CV modulation: per-track LFO modulators + CV links to device params.
/// v22 (specs/020) adds MIDI controller curves on MIDI clips and Session slot clips.
/// v23 (specs/022) adds the Devices-panel fold on devices, MIDI effects and instruments.
- public const int CurrentFormatVersion = 24;
+ /// v25 (specs/044) adds references into rack chains (lanes, CV links, Arp CC targets) and
+ /// chain children's sidechain keys / CC targets.
+ public const int CurrentFormatVersion = 25;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -178,6 +180,8 @@ public sealed class ProjectService
for (int p = 0; p < pc; p++) mdev.Params[p] = engine.MidiEffectGetParam(ti.Id, m, p);
mdev.CcDestDevice = engine.MidiEffectCcDestDevice(ti.Id, m);
mdev.CcDestParam = engine.MidiEffectCcDestParam(ti.Id, m);
+ var (ccChain, ccSlot) = engine.MidiEffectCcDestPath(ti.Id, m);
+ if (ccChain >= 0) { mdev.CcDestChain = ccChain; mdev.CcDestSlot = ccSlot; }
mdev.CcDepth = engine.MidiEffectCcDepth(ti.Id, m);
var mstate = engine.MidiEffectGetState(ti.Id, m); // the MIDI Effect Rack's structure
if (mstate.Length > 0) mdev.State = RegisterBlob(doc, mstate);
@@ -268,8 +272,11 @@ public sealed class ProjectService
for (int l = 0; l < laneCount; l++)
{
var info = engine.AutomationLaneInfo(ti.Id, l);
+ var (laneChain, laneSlot) = engine.AutomationLanePath(ti.Id, l);
t.Automation.Add(new AutomationLaneDto
{
+ Chain = laneChain >= 0 ? laneChain : null,
+ Slot = laneChain >= 0 ? laneSlot : null,
Target = (int)info.Target,
DeviceIndex = info.DeviceIndex,
ParamIndex = info.ParamIndex,
@@ -308,8 +315,13 @@ public sealed class ProjectService
for (int c = 0; c < cvCount; c++)
{
int tgtId = engine.CvLinkTargetTrack(ti.Id, c); // -1 = self
+ var path = engine.CvLinkPath(ti.Id, c);
t.CvLinks.Add(new CvLinkDto
{
+ SourceChain = path.SourceChain >= 0 ? path.SourceChain : null,
+ SourceSlot = path.SourceChain >= 0 ? path.SourceSlot : null,
+ TargetChain = path.TargetChain >= 0 ? path.TargetChain : null,
+ TargetSlot = path.TargetChain >= 0 ? path.TargetSlot : null,
Source = engine.CvLinkSource(ti.Id, c),
SourceKind = engine.CvLinkSourceKind(ti.Id, c),
SourceDevice = engine.CvLinkSourceDevice(ti.Id, c),
@@ -324,6 +336,7 @@ public sealed class ProjectService
});
}
+ SaveNestedLinks(engine, ti.Id, t, idToIndex);
doc.Tracks.Add(t);
}
@@ -338,6 +351,7 @@ public sealed class ProjectService
Name = engine.GetTrackName(masterId) is { Length: > 0 } mName ? mName : null,
ColorIndex = engine.GetTrackColorIndex(masterId),
Devices = CaptureDevices(engine, masterId, doc, idToIndex, warnings, "Master"),
+ NestedSidechains = NestedLinks(engine, masterId, idToIndex).Item1, // keys inside the master's racks
};
return doc;
@@ -388,6 +402,47 @@ public sealed class ProjectService
// Recreate a device chain onto a track (or the master). Sidechain sources are deferred
// (resolved once every track exists).
+ // Links on devices inside the track's racks that the rack blob can't hold (specs/044): a
+ // chain child's sidechain key (source as a doc index) and a chain MIDI effect's CC target.
+ private static void SaveNestedLinks(IAudioEngine engine, int trackId, TrackDto t, Dictionary<int, int> idToIndex)
+ {
+ var (scs, ccs) = NestedLinks(engine, trackId, idToIndex);
+ t.NestedSidechains = scs;
+ t.NestedCcRoutes = ccs;
+ }
+
+ private static (List<NestedSidechainDto>?, List<NestedCcRouteDto>?) NestedLinks(IAudioEngine engine, int trackId, Dictionary<int, int> idToIndex)
+ {
+ var scs = new List<NestedSidechainDto>();
+ var ccs = new List<NestedCcRouteDto>();
+ void Rack(int host, int chains, System.Func<int, int> devCount, System.Func<int, int> midiCount, bool hasInstrument)
+ {
+ for (int c = 0; c < chains; c++)
+ {
+ int n = devCount(c);
+ for (int slot = hasInstrument ? -1 : 0; slot < n; slot++)
+ if (engine.RackChainSidechain(trackId, host, c, slot) is { SourceTrack: >= 0 } sc
+ && idToIndex.TryGetValue(sc.SourceTrack, out int src))
+ scs.Add(new NestedSidechainDto { Host = host, Chain = c, Slot = slot, Source = src, TapPre = sc.TapPre, GainDb = sc.GainDb, Mix = sc.Mix });
+ int mn = midiCount(c);
+ for (int i = 0; i < mn; i++)
+ if (engine.RackChainMidiCcDest(trackId, host, c, i) is { } d && (d.Device >= 0 || d.Chain >= 0) && d.Param >= 0)
+ ccs.Add(new NestedCcRouteDto { Host = host, Chain = c, Index = i, DestDevice = d.Device, DestChain = d.Chain, DestSlot = d.Slot, Param = d.Param, Depth = d.Depth });
+ }
+ }
+ if (engine.RackChainCount(trackId) > 0) // 0 unless the instrument is a rack
+ Rack(-1, engine.RackChainCount(trackId), c => engine.RackChainDeviceCount(trackId, c), c => engine.RackChainMidiCount(trackId, c), true);
+ int devs = engine.TrackDeviceCount(trackId);
+ for (int d = 0; d < devs; d++)
+ if (engine.TrackDeviceBuiltinKind(trackId, d) == 5)
+ Rack(d, engine.RackDevChainCount(trackId, d), c => engine.RackDevChainDeviceCount(trackId, d, c), _ => 0, false);
+ int mids = engine.TrackMidiEffectCount(trackId);
+ for (int m = 0; m < mids; m++)
+ if (engine.MidiEffectKind(trackId, m) == 6)
+ Rack(-1000 - m, engine.MidiRackChainCount(trackId, m), _ => 0, c => engine.MidiRackChainDeviceCount(trackId, m, c), false);
+ return (scs.Count > 0 ? scs : null, ccs.Count > 0 ? ccs : null);
+ }
+
private static void ApplyDevices(IAudioEngine engine, int trackId, IEnumerable<DeviceDto> devices,
string bundleDir, List<(int track, int dev, int srcIndex)> scDeferred, List<string> warnings)
{
@@ -471,6 +526,7 @@ public sealed class ProjectService
// a track created later), both resolved after every track exists (Phase B).
var newTrackIds = new List<int>();
var scDeferred = new List<(int track, int dev, int srcIndex)>();
+ var nestedScDeferred = new List<(int track, NestedSidechainDto dto)>();
var instScDeferred = new List<(int track, int srcIndex)>(); // instrument React source (Nota Flux)
var recInputDeferred = new List<(int trackId, int encoded)>();
var monitorDeferred = new List<(int trackId, bool on)>();
@@ -621,6 +677,7 @@ public sealed class ProjectService
if (t.MidiFrom >= 0) midiFromDeferred.Add((id, t.MidiFrom)); // resolve after all tracks exist
for (int b = 0; b < t.Sends.Length && b < 4; b++) engine.SetTrackSend(id, b, t.Sends[b]);
+ var ccPaths = new List<(int mi, int chain, int slot)>(); // CC targets inside racks: after the devices
foreach (var m in t.MidiEffects)
{
int mi = engine.AddMidiEffect(id, m.Kind);
@@ -637,14 +694,22 @@ public sealed class ProjectService
}
if (m.Bypassed) engine.SetMidiEffectBypassed(id, mi, true);
if (m.Folded) engine.SetMidiEffectFolded(id, mi, true);
- if (m.CcDestDevice >= 0 && m.CcDestParam >= 0)
+ if ((m.CcDestDevice >= 0 || m.CcDestChain is not null) && m.CcDestParam >= 0)
{
engine.SetMidiEffectCcDest(id, mi, m.CcDestDevice, m.CcDestParam);
engine.SetMidiEffectCcDepth(id, mi, m.CcDepth);
+ if (m.CcDestChain is int cc) ccPaths.Add((mi, cc, m.CcDestSlot ?? 0));
}
}
ApplyDevices(engine, id, t.Devices, bundleDir, scDeferred, warnings);
+ foreach (var (mi, cc, cs) in ccPaths)
+ if (!engine.SetMidiEffectCcDestPath(id, mi, cc, cs)) warnings.Add("Couldn't reconnect an Arp's CC lane to a device in a rack.");
+ foreach (var r in t.NestedCcRoutes ?? new())
+ if (!engine.RackChainMidiSetCcDest(id, r.Host, r.Chain, r.Index, new NestedCcDest(r.DestDevice, r.DestChain, r.DestSlot, r.Param, r.Depth)))
+ warnings.Add("Couldn't reconnect the CC lane of an Arp in a rack.");
+ foreach (var n in t.NestedSidechains ?? new())
+ if (n.Source >= 0) nestedScDeferred.Add((id, n));
foreach (var c in t.MidiClips)
{
@@ -708,7 +773,13 @@ public sealed class ProjectService
foreach (var lane in t.Automation)
{
int li;
- if ((AutomationTarget)lane.Target == AutomationTarget.PluginParam)
+ if (lane.Chain is int lc) // a lane on a device grouped into a rack (specs/044)
+ {
+ li = engine.AddNestedAutomationLane(id, (AutomationTarget)lane.Target, lane.DeviceIndex, lc, lane.Slot ?? 0,
+ lane.ParamIndex, lane.PluginParamId);
+ if (li < 0) { warnings.Add("Couldn't recreate an automation lane on a device in a rack."); continue; }
+ }
+ else if ((AutomationTarget)lane.Target == AutomationTarget.PluginParam)
{
string pid = lane.PluginParamId ?? "";
li = engine.AddPluginAutomationLane(id, lane.DeviceIndex, pid);
@@ -771,7 +842,10 @@ public sealed class ProjectService
foreach (var (owner, l, modId) in cvLinkDeferred)
{
int targetTrack = l.TargetTrack >= 0 && l.TargetTrack < newTrackIds.Count ? newTrackIds[l.TargetTrack] : -1;
- int idx = l.SourceKind == 1
+ int idx = l.SourceChain is not null || l.TargetChain is not null // reaching into a rack (specs/044)
+ ? engine.CvLinkAddNested(owner, l.SourceKind, modId, l.SourceDevice, l.SourceChain ?? -1, l.SourceSlot ?? -1, l.SourceParam,
+ l.TargetKind, targetTrack, l.Device, l.TargetChain ?? -1, l.TargetSlot ?? -1, l.Param)
+ : l.SourceKind == 1
? engine.CvLinkAddFromParamToTarget(owner, l.SourceDevice, l.SourceParam, l.TargetKind, targetTrack, l.Device, l.Param)
: engine.CvLinkAddToTarget(owner, modId, l.TargetKind, targetTrack, l.Device, l.Param);
if (idx < 0) { warnings.Add("Couldn't recreate a CV link."); continue; }
@@ -788,6 +862,8 @@ public sealed class ProjectService
if (md.Name is { Length: > 0 } mnm) engine.SetTrackName(masterId, mnm);
if (md.ColorIndex >= 0) engine.SetTrackColorIndex(masterId, md.ColorIndex);
ApplyDevices(engine, masterId, md.Devices, bundleDir, scDeferred, warnings);
+ foreach (var n in md.NestedSidechains ?? new())
+ if (n.Source >= 0) nestedScDeferred.Add((masterId, n));
}
// Sidechain wiring, now that every track exists (Phase B). Source is a doc index.
@@ -796,6 +872,13 @@ public sealed class ProjectService
if (srcIndex < newTrackIds.Count && newTrackIds[srcIndex] > 0)
engine.SetDeviceSidechainSource(track, dev, newTrackIds[srcIndex]);
}
+ // Keys of devices inside racks (specs/044), same deferral.
+ foreach (var (track, n) in nestedScDeferred)
+ {
+ if (n.Source < newTrackIds.Count && newTrackIds[n.Source] > 0)
+ engine.RackChainSetSidechain(track, n.Host, n.Chain, n.Slot,
+ new NestedSidechain(newTrackIds[n.Source], n.TapPre, n.GainDb, n.Mix));
+ }
// Instrument React source (Nota Flux), same deferral.
foreach (var (track, srcIndex) in instScDeferred)
{
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 014eaf4e..67fcba3b 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -73,6 +73,60 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
return new DeviceMoveResult(r, f.HasFlag(TransferFlags.SidechainCleared), f.HasFlag(TransferFlags.LinksDropped), f.HasFlag(TransferFlags.SourceTrackRemoved));
});
+ public sealed record GroupResult(string RackType, int Index);
+
+ [McpServerTool(Name = "group_devices"), Description("Group a contiguous run of a track's devices into a new rack in their place, one undo step (⌘G in the Devices panel). Audio effects only → an Audio Effect Rack at fxFirst; MIDI effects only → a MIDI Effect Rack at midiFirst; withInstrument → an Instrument Rack as the track's instrument whose first chain holds the MIDI effects, the instrument and the audio effects in order (the MIDI run must end at the last MIDI effect and the audio run start at 0). MIDI and audio effects share a rack only with the instrument between them. The devices keep their settings and sound; automation, modulation links, an Arp's CC lane and sidechain keys on them follow into the rack. Inspect the result with get_effect_rack, get_midi_rack or get_rack. Returns the rack type and its index (-1 for the instrument).")]
+ public Task<GroupResult> GroupDevices(
+ int trackId,
+ [Description("First MIDI effect of the run, -1 = none")] int midiFirst = -1,
+ [Description("How many MIDI effects")] int midiCount = 0,
+ [Description("Include the track's instrument")] bool withInstrument = false,
+ [Description("First audio effect of the run, -1 = none")] int fxFirst = -1,
+ [Description("How many audio effects")] int fxCount = 0) => Mutate(() =>
+ {
+ int r = E.GroupDevices(trackId, midiFirst, midiCount, withInstrument, fxFirst, fxCount);
+ bool ok = withInstrument ? r == -1 : r >= 0 || r <= -1000;
+ if (!ok)
+ throw new InvalidOperationException((GroupRefusal)r switch
+ {
+ GroupRefusal.NotContiguous => "Not contiguous: the MIDI run must end at the instrument and the audio run start after it, and MIDI + audio effects need the instrument.",
+ GroupRefusal.RackInRun => "A rack can't go inside another rack.",
+ GroupRefusal.CantHost => "A MIDI Effect Rack holds built-in MIDI effects only.",
+ GroupRefusal.InstrumentCantNest => "An Instrument Rack can't go inside another Instrument Rack.",
+ GroupRefusal.NotInstrumentTrack => "Only an instrument track has MIDI effects and an instrument.",
+ _ => "No such track or run.",
+ });
+ return withInstrument ? new GroupResult("instrument", -1)
+ : r <= -1000 ? new GroupResult("midi", -1000 - r)
+ : new GroupResult("audio", r);
+ });
+
+ public sealed record UngroupResult(int Restored, bool MacrosDropped, bool ChainMixDropped);
+
+ [McpServerTool(Name = "ungroup_rack"), Description("Take a one-chain rack apart: its chain's devices take its place in order, one undo step (⌘⇧G). chain: \"audio\" (an Audio Effect Rack at index), \"midi\" (a MIDI Effect Rack at index) or \"instrument\" (the track's Instrument Rack; index ignored — its MIDI effects go after the track's, its instrument becomes the track's, its audio effects go before the track's). The rack's macros, mappings and chain settings are dropped; automation and links on its devices follow them out.")]
+ public Task<UngroupResult> UngroupRack(int trackId,
+ [Description("\"audio\", \"midi\" or \"instrument\"")] string chain,
+ [Description("The rack's index in that chain (ignored for the instrument)")] int index = 0) => Mutate(() =>
+ {
+ var family = chain switch
+ {
+ "audio" => DeviceFamily.Audio,
+ "midi" => DeviceFamily.Midi,
+ "instrument" => DeviceFamily.Instrument,
+ _ => throw new ArgumentException("chain must be 'audio', 'midi' or 'instrument'."),
+ };
+ int n = E.UngroupRack(trackId, family, index, out var dropped);
+ if (n < 0)
+ throw new InvalidOperationException((UngroupRefusal)n switch
+ {
+ UngroupRefusal.SeveralChains => "Only a rack with one chain can be ungrouped.",
+ UngroupRefusal.DrumRack => "A Drum Rack can't be ungrouped.",
+ UngroupRefusal.NoInstrument => "The Instrument Rack's chain has no instrument.",
+ _ => "That device isn't a rack.",
+ });
+ return new UngroupResult(n, dropped.HasFlag(UngroupDropped.MacroMappings), dropped.HasFlag(UngroupDropped.ChainMix));
+ });
+
[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));
diff --git a/src/managed/Nota.Presentation/DeviceSelection.cs b/src/managed/Nota.Presentation/DeviceSelection.cs
new file mode 100644
index 00000000..ddeb52d8
--- /dev/null
+++ b/src/managed/Nota.Presentation/DeviceSelection.cs
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The Devices panel's selection on a track's chain (specs/044): several devices across the
+// MIDI effects, the instrument and the audio effects, picked with click, Shift-click (a range
+// in chain order) and ⌘/Ctrl-click (toggle). It also decides what ⌘G can make of it — which
+// rack, or why not — so the panel, its menu and the smoke test share one rule.
+
+namespace Nota.Presentation;
+
+/// <summary>Where a device sits in a track's chain, in chain order.</summary>
+public enum DeviceSection { Midi = 0, Instrument = 1, Audio = 2 }
+
+/// <summary>A device in the chain: its section and index there (the instrument is index -1).</summary>
+public readonly record struct ChainSlot(DeviceSection Section, int Index)
+{
+ public static ChainSlot Instrument => new(DeviceSection.Instrument, -1);
+}
+
+/// <summary>What Group into rack would make of a selection.</summary>
+public enum GroupShapeKind { None, AudioRack, MidiRack, InstrumentRack, Refused }
+
+/// <summary>The rack a selection groups into and the runs it takes, or the reason it can't.</summary>
+public readonly record struct GroupShape(GroupShapeKind Kind, int MidiFirst, int MidiCount, bool WithInstrument,
+ int FxFirst, int FxCount, string? Reason)
+{
+ public bool CanGroup => Kind is GroupShapeKind.AudioRack or GroupShapeKind.MidiRack or GroupShapeKind.InstrumentRack;
+}
+
+public sealed class DeviceSelection
+{
+ private readonly List<ChainSlot> _members = new();
+
+ /// <summary>The selected devices in chain order.</summary>
+ public IReadOnlyList<ChainSlot> Members => _members;
+ public ChainSlot? Anchor { get; private set; }
+ public int Count => _members.Count;
+ public bool IsEmpty => _members.Count == 0;
+ public bool Contains(ChainSlot s) => _members.Contains(s);
+ public bool HasInstrument => _members.Contains(ChainSlot.Instrument);
+ public IEnumerable<int> Indices(DeviceSection section) => _members.Where(m => m.Section == section).Select(m => m.Index);
+
+ /// <summary>Plain click: only this device.</summary>
+ public void Click(ChainSlot s)
+ {
+ _members.Clear();
+ _members.Add(s);
+ Anchor = s;
+ }
+
+ /// <summary>⌘/Ctrl-click: this device in or out; it becomes the anchor.</summary>
+ public void Toggle(ChainSlot s)
+ {
+ if (!_members.Remove(s)) Insert(s);
+ Anchor = s;
+ }
+
+ /// <summary>Shift-click: every device from the anchor to this one in chain order
+ /// (<paramref name="midiCount"/> MIDI effects → the instrument if <paramref name="hasInstrument"/> → <paramref name="fxCount"/> audio effects).</summary>
+ public void ExtendTo(ChainSlot s, int midiCount, bool hasInstrument, int fxCount)
+ {
+ if (Anchor is not { } a) { Click(s); return; }
+ var order = Order(midiCount, hasInstrument, fxCount);
+ int i = order.IndexOf(a), j = order.IndexOf(s);
+ if (i < 0 || j < 0) { Click(s); return; }
+ _members.Clear();
+ for (int k = Math.Min(i, j); k <= Math.Max(i, j); k++) _members.Add(order[k]);
+ }
+
+ public void Clear()
+ {
+ _members.Clear();
+ Anchor = null;
+ }
+
+ /// <summary>Select exactly these (after an edit: the new rack, the restored devices, a paste).</summary>
+ public void Set(IEnumerable<ChainSlot> slots)
+ {
+ _members.Clear();
+ foreach (var s in slots) Insert(s);
+ Anchor = _members.Count > 0 ? _members[0] : null;
+ }
+
+ /// <summary>Drop selected devices that no longer exist (the chain shrank under the selection).</summary>
+ public void Prune(int midiCount, bool hasInstrument, int fxCount)
+ {
+ _members.RemoveAll(m => m.Section switch
+ {
+ DeviceSection.Midi => m.Index >= midiCount,
+ DeviceSection.Instrument => !hasInstrument,
+ _ => m.Index >= fxCount,
+ });
+ if (Anchor is { } a && !_members.Contains(a)) Anchor = _members.Count > 0 ? _members[0] : null;
+ }
+
+ /// <summary>What ⌘G makes of the selection (data-model.md § Group shape).</summary>
+ public GroupShape Shape(int midiCount, int fxCount)
+ {
+ if (IsEmpty) return new(GroupShapeKind.None, -1, 0, false, -1, 0, null);
+ var midi = Indices(DeviceSection.Midi).OrderBy(i => i).ToList();
+ var fx = Indices(DeviceSection.Audio).OrderBy(i => i).ToList();
+ bool inst = HasInstrument;
+ static bool Consecutive(List<int> l) => l.Count == 0 || l[^1] - l[0] == l.Count - 1;
+ GroupShape Refuse(string why) => new(GroupShapeKind.Refused, -1, 0, false, -1, 0, why);
+ if (!Consecutive(midi) || !Consecutive(fx)) return Refuse("Select devices next to each other to group them");
+ int mf = midi.Count > 0 ? midi[0] : -1, ff = fx.Count > 0 ? fx[0] : -1;
+ if (inst)
+ {
+ if (midi.Count > 0 && midi[^1] != midiCount - 1) return Refuse("Select devices next to each other to group them");
+ if (fx.Count > 0 && ff != 0) return Refuse("Select devices next to each other to group them");
+ return new(GroupShapeKind.InstrumentRack, mf, midi.Count, true, ff, fx.Count, null);
+ }
+ if (midi.Count > 0 && fx.Count > 0)
+ return Refuse("MIDI and audio effects go in one rack only with the instrument between them");
+ return midi.Count > 0
+ ? new(GroupShapeKind.MidiRack, mf, midi.Count, false, -1, 0, null)
+ : new(GroupShapeKind.AudioRack, -1, 0, false, ff, fx.Count, null);
+ }
+
+ private static List<ChainSlot> Order(int midiCount, bool hasInstrument, int fxCount)
+ {
+ var o = new List<ChainSlot>(midiCount + fxCount + 1);
+ for (int i = 0; i < midiCount; i++) o.Add(new(DeviceSection.Midi, i));
+ if (hasInstrument) o.Add(ChainSlot.Instrument);
+ for (int i = 0; i < fxCount; i++) o.Add(new(DeviceSection.Audio, i));
+ return o;
+ }
+
+ // Keep members in chain order: section, then index.
+ private void Insert(ChainSlot s)
+ {
+ int at = _members.FindIndex(m => m.Section > s.Section || (m.Section == s.Section && m.Index > s.Index));
+ if (at < 0) _members.Add(s);
+ else _members.Insert(at, s);
+ }
+}
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index bedf1f4e..4a6ecd6c 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -362,6 +362,17 @@ NOTA_API NotaResult nota_track_automation_set_points(NotaEngine* engine, int32_t
NOTA_API NotaResult nota_track_automation_set_points_live(NotaEngine* engine, int32_t track_id,
int32_t lane_index, const NotaAutomationPoint* pts, int32_t count);
NOTA_API NotaResult nota_track_remove_automation_lane(NotaEngine* engine, int32_t track_id, int32_t lane_index);
+/* A lane on a device grouped into a rack (specs/044): its device_index (lane_info) is the rack's
+ * address on the track (>= 0 effect, -1 instrument, -1000 - i MIDI effect) and the path names
+ * the chain child: chain index and slot (>= 0 a device, -1 the chain instrument, -1000 - i the
+ * chain's i-th MIDI effect). out_chain -1 = a track-level lane. */
+NOTA_API NotaResult nota_track_automation_lane_path(const NotaEngine* engine, int32_t track_id, int32_t lane_index,
+ int32_t* out_chain, int32_t* out_slot);
+/* Project load: add (or reuse) a lane on a chain child; param_id for plug-in params (target 3),
+ * else param_index. Returns the lane index, or -1 when the address doesn't resolve. */
+NOTA_API int32_t nota_track_add_nested_automation_lane(NotaEngine* engine, int32_t track_id, int32_t target,
+ int32_t device_index, int32_t chain, int32_t slot,
+ int32_t param_index, const char* param_id);
/* ---- CV modulation (Phase 3, Modular editor) ----------------------------
* Modulator (LFO) sources + edges to built-in device params on the same track.
@@ -395,6 +406,16 @@ NOTA_API int32_t nota_track_cv_link_source(const NotaEngine* engine, int32_t tra
NOTA_API int32_t nota_track_cv_link_target_track(const NotaEngine* engine, int32_t track_id, int32_t index);
NOTA_API int32_t nota_track_cv_link_device(const NotaEngine* engine, int32_t track_id, int32_t index);
NOTA_API int32_t nota_track_cv_link_param(const NotaEngine* engine, int32_t track_id, int32_t index);
+/* Links reaching into a rack (specs/044): source / target as (device, chain index, slot), chain
+ * -1 = track level; device is then the rack's address. path: 0 = done, -1 bad link. */
+NOTA_API int32_t nota_track_cv_link_path(const NotaEngine* engine, int32_t track_id, int32_t index,
+ int32_t* out_src_chain, int32_t* out_src_slot, int32_t* out_tgt_chain,
+ int32_t* out_tgt_slot);
+NOTA_API int32_t nota_track_add_nested_cv_link(NotaEngine* engine, int32_t track_id, int32_t source_kind,
+ int32_t mod_id, int32_t src_device, int32_t src_chain, int32_t src_slot,
+ int32_t src_param, int32_t target_kind, int32_t target_track,
+ int32_t target_device, int32_t tgt_chain, int32_t tgt_slot,
+ int32_t target_param);
NOTA_API float nota_track_cv_link_depth(const NotaEngine* engine, int32_t track_id, int32_t index);
NOTA_API int32_t nota_track_cv_link_mode(const NotaEngine* engine, int32_t track_id, int32_t index);
NOTA_API NotaResult nota_track_set_cv_link_depth(NotaEngine* engine, int32_t track_id, int32_t index, float depth);
@@ -1532,6 +1553,29 @@ NOTA_API void nota_midi_effect_set_cc_dest(NotaEngine* engine, int32_t tr
NOTA_API void nota_midi_effect_set_cc_depth(NotaEngine* engine, int32_t track_id, int32_t index, float depth);
NOTA_API int32_t nota_midi_effect_cc_dest_device(const NotaEngine* engine, int32_t track_id, int32_t index);
NOTA_API int32_t nota_midi_effect_cc_dest_param(const NotaEngine* engine, int32_t track_id, int32_t index);
+/* The CC target inside a rack (specs/044): chain index + slot in the rack at cc_dest_device
+ * (slot >= 0 a device); chain -1 = track level. Set it after set_cc_dest. 0 = done, -1 not. */
+NOTA_API int32_t nota_midi_effect_cc_dest_path(const NotaEngine* engine, int32_t track_id, int32_t index,
+ int32_t* out_chain, int32_t* out_slot);
+NOTA_API int32_t nota_midi_effect_set_cc_dest_path(NotaEngine* engine, int32_t track_id, int32_t index,
+ int32_t chain, int32_t slot);
+/* The same for a MIDI effect inside a rack chain (rack at device_index on the track, as the
+ * rack calls address it), and a chain child's sidechain key (slot >= 0 a device, -1 the chain
+ * instrument; tap_pre / gain / mix for devices). For save / load: track ids and chain uids
+ * don't survive in the rack blob. 0 = done, -1 bad address. */
+NOTA_API int32_t nota_rack_chain_midi_cc_dest(const NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t index, int32_t* out_dest_device,
+ int32_t* out_dest_chain, int32_t* out_dest_slot, int32_t* out_param,
+ float* out_depth);
+NOTA_API int32_t nota_rack_chain_midi_set_cc_dest(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t index, int32_t dest_device, int32_t dest_chain,
+ int32_t dest_slot, int32_t param, float depth);
+NOTA_API int32_t nota_rack_chain_sidechain(const NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t* out_source_track,
+ int32_t* out_tap_pre, float* out_gain_db, float* out_mix);
+NOTA_API int32_t nota_rack_chain_set_sidechain(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t source_track, int32_t tap_pre,
+ float gain_db, float mix);
NOTA_API float nota_midi_effect_cc_depth(const NotaEngine* engine, int32_t track_id, int32_t index);
/* ---- Built-in devices + generic params (M4-4/5) -------------------------- */
@@ -1544,10 +1588,24 @@ NOTA_API NotaResult nota_track_remove_device(NotaEngine* engine, int32_t track_
/* Device clipboard (#238). Copy keeps a full clone of an audio effect (every param, its
* state blob, bypass, sidechain key; a rack or plug-in copies itself) or a MIDI effect;
* paste inserts a clone of it at at_index (-1 = the end) as one undo step and returns the
- * new index, or <0. clipboard_kind: 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument. */
+ * new index, or <0. clipboard_kind: 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument, 4 several devices (specs/044). */
NOTA_API NotaResult nota_track_copy_device(NotaEngine* engine, int32_t track_id, int32_t device_index);
NOTA_API NotaResult nota_track_copy_midi_effect(NotaEngine* engine, int32_t track_id, int32_t index);
NOTA_API int32_t nota_device_clipboard_kind(const NotaEngine* engine);
+/* Several devices on the device clipboard (specs/044): full clones of the listed MIDI effects,
+ * the instrument (with_instrument 1) and audio effects, in chain order; replaces the clipboard
+ * (clipboard_kind then 4; one device fills it as the single copies do). Returns the count, or -1. */
+NOTA_API int32_t nota_track_copy_devices(NotaEngine* engine, int32_t track_id, const int32_t* midi_idx,
+ int32_t midi_n, int32_t with_instrument, const int32_t* fx_idx,
+ int32_t fx_n);
+NOTA_API int32_t nota_device_clipboard_count(const NotaEngine* engine);
+/* Paste every clipboard entry the track can take, one undo step: MIDI effects at midi_at, audio
+ * effects at fx_at (-1 = the end of the section), an instrument replacing the track's. Pasted
+ * MIDI effects carry no CC target. Returns the number pasted (>= 0), *out_skipped (may be NULL)
+ * the ones the track can't take; -1 empty clipboard or bad track, -3 a clone failed (nothing
+ * changed). */
+NOTA_API int32_t nota_track_paste_devices(NotaEngine* engine, int32_t track_id, int32_t midi_at, int32_t fx_at,
+ int32_t* out_skipped);
NOTA_API int32_t nota_track_paste_device(NotaEngine* engine, int32_t track_id, int32_t at_index);
NOTA_API int32_t nota_track_paste_midi_effect(NotaEngine* engine, int32_t track_id, int32_t at_index);
/* A full clone of the device / MIDI effect right after it, one undo step; the clipboard is left
@@ -1578,11 +1636,35 @@ NOTA_API int32_t nota_track_transfer_device(NotaEngine* engine, int32_t src_
int32_t index, int32_t dst_track_id, int32_t at_index,
int32_t keep_source, int32_t* out_flags);
/* ⌘G on a device (#257): wrap the audio effect at device_index in a new Audio Effect Rack
- * in its place (one undo step). Returns the rack's index, or <0 when the device can't move
- * into a rack chain (not an effect; a sidechain key, automation or a CV link on it).
- * Unwrap replaces a one-chain rack with its chain's devices; returns their count, or <0. */
+ * in its place (one undo step); its links follow it in (specs/044). Returns the rack's index,
+ * or <0. Unwrap replaces a one-chain Audio Effect Rack with its chain's devices; returns their
+ * count, or <0. Both are the one-device cases of group_devices / ungroup_rack below. */
NOTA_API int32_t nota_track_wrap_device_in_rack(NotaEngine* engine, int32_t track_id, int32_t device_index);
NOTA_API int32_t nota_track_unwrap_rack(NotaEngine* engine, int32_t track_id, int32_t device_index);
+/* Group a contiguous run of a track's devices into a new rack in their place (#328), one undo
+ * step; wrap / unwrap above are its one-device cases and no longer refuse a linked device.
+ * midi_first/midi_count: the MIDI effects (count 0 = none); with_instrument 1 to include the
+ * instrument; fx_first/fx_count: the audio effects. Audio effects only -> an Audio Effect Rack at
+ * fx_first; MIDI effects only -> a MIDI Effect Rack at midi_first; with the instrument -> an
+ * Instrument Rack as the track's instrument, chain 0 = MIDI effects -> instrument -> audio
+ * effects (the MIDI run must end at the last MIDI effect, the audio run start at 0).
+ * The instances move in without being prepared again; automation lanes, CV links, Arp CC
+ * targets and sidechain keys on them follow into the rack chain.
+ * Returns the rack's address (>= 0 audio effect, -1 the instrument, -1000 - i the i-th MIDI
+ * effect) or: -2 bad run, -3 not contiguous / MIDI + audio effects without the instrument,
+ * -4 a rack in the run, -5 a device the rack can't host, -6 an instrument a chain can't hold
+ * (an Instrument Rack), -7 not an instrument track. Distinguish -1 (instrument) by the call. */
+NOTA_API int32_t nota_track_group_devices(NotaEngine* engine, int32_t track_id, int32_t midi_first,
+ int32_t midi_count, int32_t with_instrument, int32_t fx_first,
+ int32_t fx_count);
+/* Ungroup a one-chain rack (family 0 audio effect at index, 1 MIDI effect at index, 2 the
+ * instrument) back into its chain's devices, in place, one undo step; references follow them,
+ * the rack's own macros, mappings, chain mix and settings are dropped (and lanes or links on
+ * its macros removed). Returns the number of devices restored, or -2 not a rack, -3 two or
+ * more chains, -4 a Drum Rack, -5 an Instrument Rack chain without an instrument.
+ * *out_dropped (may be NULL): bit 0 macro mappings dropped, bit 1 a non-default chain mix. */
+NOTA_API int32_t nota_track_ungroup_rack(NotaEngine* engine, int32_t track_id, int32_t family, int32_t index,
+ int32_t* out_dropped);
/* Device display name (built-ins: "EQ"/"Compressor"; plugins: plugin name). */
NOTA_API const char* nota_device_name(const NotaEngine* engine, int32_t track_id, int32_t device_index);
/* Generic float params (built-ins expose these; hosted plugins report 0). */
@@ -1768,6 +1850,14 @@ NOTA_API int32_t nota_rackdev_chain_device_copy(NotaEngine* engine, int32_t
NOTA_API int32_t nota_rackdev_chain_midi_copy(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);
NOTA_API int32_t nota_rackdev_chain_device_paste(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t at_index);
NOTA_API int32_t nota_rackdev_chain_midi_paste(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t at_index);
+/* Several devices on the clipboard into chain `chain` (specs/044): the MIDI effects at midi_at,
+ * the audio effects at fx_at (-1 = the end of the section), what the chain can't take skipped
+ * (an instrument, a rack, a non-built-in MIDI effect), keys dropped; one undo step. Returns the
+ * number pasted (>= 0) with the skipped count and the first new index per section (-1 none),
+ * or -1 bad address / empty clipboard, -3 a clone failed. */
+NOTA_API int32_t nota_rackdev_chain_paste_devices(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t midi_at, int32_t fx_at, int32_t* out_skipped,
+ int32_t* out_first_midi, int32_t* out_first_fx);
NOTA_API int32_t nota_rackdev_chain_device_duplicate(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);
NOTA_API int32_t nota_rackdev_chain_midi_duplicate(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);
NOTA_API int32_t nota_rackdev_chain_device_move_to(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index, int32_t to_chain);
diff --git a/src/native/nota.engine/src/abi/nota_engine_automation.cpp b/src/native/nota.engine/src/abi/nota_engine_automation.cpp
index 8cb429c6..bafd0094 100644
--- a/src/native/nota.engine/src/abi/nota_engine_automation.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_automation.cpp
@@ -79,6 +79,14 @@ int32_t nota_track_add_plugin_automation_lane(
NotaEngine* e, int32_t track_id, int32_t device_index, const char* param_id) {
return e ? ENG(e)->addPluginAutomationLane(track_id, device_index, param_id) : -1;
}
+NotaResult nota_track_automation_lane_path(const NotaEngine* e, int32_t track_id, int32_t lane_index,
+ int32_t* out_chain, int32_t* out_slot) {
+ return e && CENG(e)->automationLanePath(track_id, lane_index, out_chain, out_slot) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
+int32_t nota_track_add_nested_automation_lane(NotaEngine* e, int32_t track_id, int32_t target, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t param_index, const char* param_id) {
+ return e ? ENG(e)->addNestedAutomationLane(track_id, target, device_index, chain, slot, param_index, param_id) : -1;
+}
const char* nota_track_automation_lane_param_id(const NotaEngine* e, int32_t track_id, int32_t lane_index) {
static std::string s; // owned by the engine, valid until the next call
s = e ? CENG(e)->automationLaneParamId(track_id, lane_index) : std::string{};
diff --git a/src/native/nota.engine/src/abi/nota_engine_device.cpp b/src/native/nota.engine/src/abi/nota_engine_device.cpp
index e8a00c62..5803ef54 100644
--- a/src/native/nota.engine/src/abi/nota_engine_device.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_device.cpp
@@ -94,6 +94,45 @@ int32_t nota_track_wrap_device_in_rack(NotaEngine* e, int32_t track_id, int32_t
int32_t nota_track_unwrap_rack(NotaEngine* e, int32_t track_id, int32_t device_index) {
return e ? ENG(e)->unwrapRack(track_id, device_index) : -1;
}
+int32_t nota_track_group_devices(NotaEngine* e, int32_t track_id, int32_t midi_first, int32_t midi_count,
+ int32_t with_instrument, int32_t fx_first, int32_t fx_count) {
+ return e ? ENG(e)->groupDevices(track_id, midi_first, midi_count, with_instrument != 0, fx_first, fx_count) : -2;
+}
+int32_t nota_track_ungroup_rack(NotaEngine* e, int32_t track_id, int32_t family, int32_t index, int32_t* out_dropped) {
+ if (out_dropped) *out_dropped = 0;
+ return e ? ENG(e)->ungroupRack(track_id, family, index, out_dropped) : -2;
+}
+int32_t nota_track_copy_devices(NotaEngine* e, int32_t track_id, const int32_t* midi_idx, int32_t midi_n,
+ int32_t with_instrument, const int32_t* fx_idx, int32_t fx_n) {
+ return e ? ENG(e)->copyDevices(track_id, midi_idx, midi_n, with_instrument != 0, fx_idx, fx_n) : -1;
+}
+int32_t nota_device_clipboard_count(const NotaEngine* e) { return e ? CENG(e)->deviceClipboardCount() : 0; }
+int32_t nota_track_paste_devices(NotaEngine* e, int32_t track_id, int32_t midi_at, int32_t fx_at, int32_t* out_skipped) {
+ if (out_skipped) *out_skipped = 0;
+ return e ? ENG(e)->pasteDevices(track_id, midi_at, fx_at, out_skipped) : -1;
+}
+int32_t nota_midi_effect_cc_dest_path(const NotaEngine* e, int32_t t, int32_t i, int32_t* out_chain, int32_t* out_slot) {
+ return e && CENG(e)->midiEffectCcDestPath(t, i, out_chain, out_slot) ? 0 : -1;
+}
+int32_t nota_rack_chain_midi_cc_dest(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i,
+ int32_t* out_dev, int32_t* out_chain, int32_t* out_slot, int32_t* out_param, float* out_depth) {
+ return e && CENG(e)->rackChainMidiCcDest(t, di, c, i, out_dev, out_chain, out_slot, out_param, out_depth) ? 0 : -1;
+}
+int32_t nota_rack_chain_midi_set_cc_dest(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i, int32_t dev,
+ int32_t dest_chain, int32_t dest_slot, int32_t param, float depth) {
+ return e && ENG(e)->rackChainMidiSetCcDest(t, di, c, i, dev, dest_chain, dest_slot, param, depth) ? 0 : -1;
+}
+int32_t nota_rack_chain_sidechain(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t slot,
+ int32_t* out_src, int32_t* out_pre, float* out_gain, float* out_mix) {
+ return e && CENG(e)->rackChainSidechain(t, di, c, slot, out_src, out_pre, out_gain, out_mix) ? 0 : -1;
+}
+int32_t nota_rack_chain_set_sidechain(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t slot, int32_t src,
+ int32_t pre, float gain, float mix) {
+ return e && ENG(e)->rackChainSetSidechain(t, di, c, slot, src, pre, gain, mix) ? 0 : -1;
+}
+int32_t nota_midi_effect_set_cc_dest_path(NotaEngine* e, int32_t t, int32_t i, int32_t chain, int32_t slot) {
+ return e && ENG(e)->setMidiEffectCcDestPath(t, i, chain, slot) ? 0 : -1;
+}
const char* nota_device_name(const NotaEngine* e, int32_t track_id, int32_t device_index) {
return e ? CENG(e)->deviceName(track_id, device_index) : "";
}
diff --git a/src/native/nota.engine/src/abi/nota_engine_modulation.cpp b/src/native/nota.engine/src/abi/nota_engine_modulation.cpp
index 20d5f842..52ed3157 100644
--- a/src/native/nota.engine/src/abi/nota_engine_modulation.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_modulation.cpp
@@ -94,6 +94,17 @@ int32_t nota_track_cv_link_target_track(const NotaEngine* e, int32_t track_id, i
int32_t nota_track_cv_link_device(const NotaEngine* e, int32_t track_id, int32_t index) {
return e ? CENG(e)->cvLinkDevice(track_id, index) : -1;
}
+int32_t nota_track_cv_link_path(const NotaEngine* e, int32_t track_id, int32_t index, int32_t* out_src_chain,
+ int32_t* out_src_slot, int32_t* out_tgt_chain, int32_t* out_tgt_slot) {
+ return e && CENG(e)->cvLinkPath(track_id, index, out_src_chain, out_src_slot, out_tgt_chain, out_tgt_slot) ? 0 : -1;
+}
+int32_t nota_track_add_nested_cv_link(NotaEngine* e, int32_t track_id, int32_t source_kind, int32_t mod_id,
+ int32_t src_device, int32_t src_chain, int32_t src_slot, int32_t src_param, int32_t target_kind,
+ int32_t target_track, int32_t target_device, int32_t tgt_chain, int32_t tgt_slot, int32_t target_param) {
+ return e ? ENG(e)->addNestedCvLink(track_id, source_kind, mod_id, src_device, src_chain, src_slot, src_param,
+ target_kind, target_track, target_device, tgt_chain, tgt_slot, target_param)
+ : -1;
+}
int32_t nota_track_cv_link_param(const NotaEngine* e, int32_t track_id, int32_t index) {
return e ? CENG(e)->cvLinkParam(track_id, index) : -1;
}
diff --git a/src/native/nota.engine/src/abi/nota_engine_rack.cpp b/src/native/nota.engine/src/abi/nota_engine_rack.cpp
index 4aa029e8..256376f6 100644
--- a/src/native/nota.engine/src/abi/nota_engine_rack.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_rack.cpp
@@ -244,6 +244,10 @@ int32_t nota_rackdev_chain_midi_copy(NotaEngine* e, int32_t t, int32_t di, int32
int32_t nota_rackdev_chain_device_paste(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t at) {
return e ? ENG(e)->rackChainDevicePaste(t, di, c, at) : -1;
}
+int32_t nota_rackdev_chain_paste_devices(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t midi_at, int32_t fx_at,
+ int32_t* out_skipped, int32_t* out_first_midi, int32_t* out_first_fx) {
+ return e ? ENG(e)->rackChainPasteDevices(t, di, c, midi_at, fx_at, out_skipped, out_first_midi, out_first_fx) : -1;
+}
int32_t nota_rackdev_chain_midi_paste(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t at) {
return e ? ENG(e)->rackChainMidiPaste(t, di, c, at) : -1;
}
@@ -645,8 +649,7 @@ float nota_rack_chain_midi_param_get(const NotaEngine* e, int32_t t, int32_t cha
return m ? m->getParam(param) : 0.0f;
}
void nota_rack_chain_midi_param_set(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param, float value) {
- auto* m = e ? ENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;
- if (m) m->setParam(param, value);
+ if (e) ENG(e)->rackChainMidiParamSet(t, -1, chain, index, param, value);
}
void nota_rack_chain_midi_set_bypassed(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t bypassed) {
if (e) ENG(e)->rackSetChainMidiBypassed(t, -1, chain, index, bypassed != 0);
@@ -712,8 +715,7 @@ float nota_midirack_chain_device_param_get(const NotaEngine* e, int32_t t, int32
return m ? m->getParam(param) : 0.0f;
}
void nota_midirack_chain_device_param_set(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param, float value) {
- auto* m = e ? ENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;
- if (m) m->setParam(param, value);
+ if (e) ENG(e)->rackChainMidiParamSet(t, MR(mi), chain, index, param, value);
}
void nota_midirack_chain_device_set_bypassed(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t bypassed) {
if (e) ENG(e)->rackSetChainMidiBypassed(t, MR(mi), chain, index, bypassed != 0);
diff --git a/src/native/nota.engine/src/devices/Device.h b/src/native/nota.engine/src/devices/Device.h
index 8058b03a..419b9d20 100644
--- a/src/native/nota.engine/src/devices/Device.h
+++ b/src/native/nota.engine/src/devices/Device.h
@@ -22,8 +22,13 @@ namespace nota {
struct MidiEv;
+class RackCore;
+
class Device {
public:
+ // The rack behind this device, if it is one (specs/044): a virtual call where the audio
+ // thread walks rack chains every block, instead of a dynamic_cast per device.
+ virtual const RackCore* asRack() const { return nullptr; }
virtual ~Device() = default;
// Called on the message thread before the device is used (and on sample-rate
diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.h
index 320635c4..851be3e3 100644
--- a/src/native/nota.engine/src/devices/Instrument.h
+++ b/src/native/nota.engine/src/devices/Instrument.h
@@ -23,8 +23,13 @@ namespace nota {
struct MidiEv;
+class RackCore;
+
class Instrument {
public:
+ // The rack behind this device, if it is one (specs/044): a virtual call where the audio
+ // thread walks rack chains every block, instead of a dynamic_cast per device.
+ virtual const RackCore* asRack() const { return nullptr; }
virtual ~Instrument() = default;
virtual void setSampleRate(double sr) = 0;
diff --git a/src/native/nota.engine/src/devices/MidiDevice.h b/src/native/nota.engine/src/devices/MidiDevice.h
index b0da9404..3031352a 100644
--- a/src/native/nota.engine/src/devices/MidiDevice.h
+++ b/src/native/nota.engine/src/devices/MidiDevice.h
@@ -32,8 +32,13 @@ struct MidiEv {
// Lets a device that needs the length up front (Nota Length's Gate %) use it.
};
+class RackCore;
+
class MidiDevice {
public:
+ // The rack behind this device, if it is one (specs/044): a virtual call where the audio
+ // thread walks rack chains every block, instead of a dynamic_cast per device.
+ virtual const RackCore* asRack() const { return nullptr; }
virtual ~MidiDevice() = default;
virtual void setSampleRate(double sr, int32_t /*maxBlock*/) {}
@@ -126,6 +131,11 @@ class MidiDevice {
virtual float ccDepth() const { return 0.0f; }
virtual float ccValue() const { return 0.0f; }
virtual void setCcDest(int32_t /*destDevice*/, int32_t /*destParam*/) {}
+ // A target grouped into a rack (specs/044): destDevice is then the rack's index in the
+ // chain and (chainUid, slot) its child, as a nested automation lane. setCcDest resets these.
+ virtual uint64_t ccDestChainUid() const { return 0; }
+ virtual int32_t ccDestSlot() const { return -1; }
+ virtual void setCcDestNested(uint64_t /*chainUid*/, int32_t /*slot*/) {}
virtual void setCcDepth(float /*depth*/) {}
private:
diff --git a/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.cpp b/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.cpp
index 62b30f2c..12910a75 100644
--- a/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.cpp
+++ b/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.cpp
@@ -98,6 +98,7 @@ std::shared_ptr<MidiDevice> Arpeggiator::clone() const {
a->p_[i].store(p_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);
a->setBypassed(bypassed());
a->setCcDest(ccDev_.load(std::memory_order_relaxed), ccParam_.load(std::memory_order_relaxed));
+ a->setCcDestNested(ccUid_.load(std::memory_order_relaxed), ccSlot_.load(std::memory_order_relaxed));
a->setCcDepth(ccDepth_.load(std::memory_order_relaxed));
a->setSampleRate(sr_, 0);
return a; // transient live state (held/pending/phase) starts fresh
diff --git a/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.h b/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.h
index 1c6618f0..e9ef6310 100644
--- a/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.h
+++ b/src/native/nota.engine/src/devices/midi_fx/Arpeggiator.h
@@ -98,8 +98,16 @@ class Arpeggiator final : public MidiDevice {
void setCcDest(int32_t dev, int32_t param) override {
ccDev_.store(dev, std::memory_order_relaxed);
ccParam_.store(param, std::memory_order_relaxed);
+ ccUid_.store(0, std::memory_order_relaxed);
+ ccSlot_.store(-1, std::memory_order_relaxed);
}
void setCcDepth(float d) override { ccDepth_.store(std::clamp(d, 0.0f, 1.0f), std::memory_order_relaxed); }
+ uint64_t ccDestChainUid() const override { return ccUid_.load(std::memory_order_relaxed); }
+ int32_t ccDestSlot() const override { return ccSlot_.load(std::memory_order_relaxed); }
+ void setCcDestNested(uint64_t uid, int32_t slot) override {
+ ccUid_.store(uid, std::memory_order_relaxed);
+ ccSlot_.store(slot, std::memory_order_relaxed);
+ }
// ---- the arpeggiator -------------------------------------------------
void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut, int32_t frames, double beatStart,
@@ -197,6 +205,8 @@ class Arpeggiator final : public MidiDevice {
std::atomic<int32_t> curLp_{-1}, curK_{-1}, heldLive_{0}, chordN_{0};
std::atomic<int32_t> chord_[kMaxHeld]{};
std::atomic<int32_t> ccDev_{-2}, ccParam_{-1};
+ std::atomic<uint64_t> ccUid_{0}; // nested CC target (specs/044)
+ std::atomic<int32_t> ccSlot_{-1};
std::atomic<float> p_[kNumParams];
};
diff --git a/src/native/nota.engine/src/devices/racks/MidiRack.h b/src/native/nota.engine/src/devices/racks/MidiRack.h
index fc074722..305b328e 100644
--- a/src/native/nota.engine/src/devices/racks/MidiRack.h
+++ b/src/native/nota.engine/src/devices/racks/MidiRack.h
@@ -34,6 +34,7 @@ class MidiRack final : public MidiDevice, public RackCore {
MidiRack();
int32_t midiKind() const override { return kKind; }
+ const RackCore* asRack() const override { return this; }
const char* displayName() const override { return "Nota MIDI Effect Rack"; }
void setSampleRate(double sr, int32_t maxBlock) override { setRates(sr, maxBlock); }
diff --git a/src/native/nota.engine/src/devices/racks/RackCore.h b/src/native/nota.engine/src/devices/racks/RackCore.h
index b74dcd30..65fd0287 100644
--- a/src/native/nota.engine/src/devices/racks/RackCore.h
+++ b/src/native/nota.engine/src/devices/racks/RackCore.h
@@ -204,6 +204,68 @@ class RackCore {
// with a playing copy (a nested rack's fork): preparing them again would reset live effects.
bool replaceChainInstrument(int32_t chain, std::shared_ptr<Instrument> inst, bool prepare = true);
uint64_t chainUid(int32_t chain) const; // uid and instrument generation, see RackChain
+
+ // ---- nested parameter addresses (specs/044) ------------------------------
+ // A lane, CV link or Arp CC route can point at a chain child by the chain's own uid
+ // (RackChain::uid, without the instrument generation: a swapped instrument keeps its
+ // chain's lanes) and a slot: >= 0 a device, -1 the chain instrument, midiTarget(i) the
+ // chain's i-th MIDI effect. The lookups read the live snapshot only and allocate
+ // nothing, so the audio thread may call them during a block: a snapshot retired
+ // meanwhile is freed only after two more renders of this rack (SnapshotHistory).
+ const RackChain* chainByUid(uint64_t uid) const {
+ RackState* st = live();
+ if (!st || uid == 0) return nullptr;
+ for (auto& c : st->chains)
+ if (c.uid == uid) return &c;
+ return nullptr;
+ }
+ uint64_t chainBaseUid(int32_t chain) const {
+ RackState* st = live();
+ return (st && chain >= 0 && chain < static_cast<int32_t>(st->chains.size())) ? st->chains[chain].uid : 0;
+ }
+ int32_t chainIndexOfUid(uint64_t uid) const {
+ RackState* st = live();
+ if (!st || uid == 0) return -1;
+ for (size_t i = 0; i < st->chains.size(); ++i)
+ if (st->chains[i].uid == uid) return static_cast<int32_t>(i);
+ return -1;
+ }
+ Device* childDevice(uint64_t uid, int32_t slot) const {
+ const RackChain* c = chainByUid(uid);
+ return c && slot >= 0 && slot < static_cast<int32_t>(c->devices.size()) ? c->devices[slot].get() : nullptr;
+ }
+ MidiDevice* childMidi(uint64_t uid, int32_t slot) const {
+ const RackChain* c = chainByUid(uid);
+ if (!c || !isMidiTarget(slot)) return nullptr;
+ const int32_t i = midiTargetIndex(slot);
+ return i >= 0 && i < static_cast<int32_t>(c->midiDevices.size()) ? c->midiDevices[i].get() : nullptr;
+ }
+ Instrument* childInstrument(uint64_t uid) const {
+ const RackChain* c = chainByUid(uid);
+ return c ? c->instrument.get() : nullptr;
+ }
+ // Every chain child on the live snapshot (devices, MIDI effects, instrument), for the
+ // sidechain feed. Audio thread safe; fn must not allocate.
+ template <class Fn> void forEachChildDevice(Fn&& fn) const {
+ RackState* st = live();
+ if (!st) return;
+ for (auto& c : st->chains)
+ for (auto& d : c.devices)
+ if (d) fn(*d);
+ }
+ template <class Fn> void forEachChildMidi(Fn&& fn) const {
+ RackState* st = live();
+ if (!st) return;
+ for (auto& c : st->chains)
+ for (auto& m : c.midiDevices)
+ if (m) fn(*m);
+ }
+ template <class Fn> void forEachChildInstrument(Fn&& fn) const {
+ RackState* st = live();
+ if (!st) return;
+ for (auto& c : st->chains)
+ if (c.instrument) fn(*c.instrument);
+ }
int32_t chainInstrumentKind(int32_t chain) const;
Instrument* chainInstrument(int32_t chain) const;
int32_t chainDeviceCount(int32_t chain) const;
diff --git a/src/native/nota.engine/src/devices/racks/RackDevice.h b/src/native/nota.engine/src/devices/racks/RackDevice.h
index 2c7916f6..aa0f7c0e 100644
--- a/src/native/nota.engine/src/devices/racks/RackDevice.h
+++ b/src/native/nota.engine/src/devices/racks/RackDevice.h
@@ -24,6 +24,7 @@ namespace nota {
class RackDevice final : public Device, public RackCore {
public:
int32_t builtinKind() const override { return 5; } // Audio Effect Rack (project compat)
+ const RackCore* asRack() const override { return this; }
const char* displayName() const override { return "Nota Audio Effect Rack"; }
bool hostsPlugin() const override { return chainsHostPlugin(); }
diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.h b/src/native/nota.engine/src/devices/racks/RackInstrument.h
index f1fa6358..c5fbd2fc 100644
--- a/src/native/nota.engine/src/devices/racks/RackInstrument.h
+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.h
@@ -26,6 +26,7 @@ class RackInstrument : public Instrument, public RackCore {
public:
RackInstrument();
int32_t kind() const override { return 3; } // built-in Instrument Rack (project compat)
+ const RackCore* asRack() const override { return this; }
const char* displayName() const override { return "Nota Instrument Rack"; }
bool hostsPlugin() const override { return chainsHostPlugin(); } // Drum Rack too
diff --git a/src/native/nota.engine/src/engine/Automation.h b/src/native/nota.engine/src/engine/Automation.h
index d1ed4566..1d58a6ae 100644
--- a/src/native/nota.engine/src/engine/Automation.h
+++ b/src/native/nota.engine/src/engine/Automation.h
@@ -48,4 +48,17 @@ struct AutomationLane {
}
};
+// A track's own automation lane (specs/044): it may point at a device grouped into a rack.
+// deviceIndex is then the rack's address on the track (>= 0 effect, -1 instrument,
+// midiHost(i) MIDI effect) and the lane drives the child at (chainUid, slot); `target` names
+// the child's param surface (DeviceParam / MidiDeviceParam generic params, PluginParam the
+// plugin-param surface, slot -1 = the chain instrument). chainUid 0 = a track-level lane.
+// Clip envelopes stay plain AutomationLanes: every audio clip copies two of them, and a
+// bigger lane made clip edits measurably slower.
+struct TrackLane : AutomationLane {
+ uint64_t chainUid = 0;
+ int32_t slot = -1;
+ bool nested() const { return chainUid != 0; }
+};
+
} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index 3149da76..18614d24 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -567,6 +567,7 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {
nt->automation = t.automation; // automation lanes (M9)
nt->modulators = t.modulators; // CV modulation sources (Phase 3)
nt->cvLinks = t.cvLinks; // CV modulation edges (Phase 3)
+ nt->ccRoutesDirty = true; // Arp CC routes (specs/044): rebuilt when published
nt->nextModId = t.nextModId;
nt->sessionPlayer = t.sessionPlayer; // shared — playback state persists (M5-2)
nt->setFrozen(t.frozen()); // M7: freeze state + buffer (shared by pointer)
@@ -610,6 +611,14 @@ void Engine::publishRaw(std::shared_ptr<Graph> g) {
authoring_ = g;
retired_.push_back(g);
if (g) ensureRenderScratch(g->tracks.size());
+ // Fresh track objects only: the audio thread never sees them change. Before any CC target
+ // exists their routes are complete as they are (empty): marking them so keeps an undo to
+ // such a snapshot from rebuilding them from targets set later.
+ if (g && ccDestsSet_) syncCcRoutes(*g);
+ else if (g) {
+ for (auto& t : g->tracks) t->ccRoutesDirty = false;
+ if (g->masterTrack) g->masterTrack->ccRoutesDirty = false;
+ }
liveGraph_.store(g.get(), std::memory_order_release);
recomputeRouting(); // Phase B: refresh sidechain source-track → route-slot table
updateMonitorInput(); // a monitoring track may have come or gone (undo, delete, load)
@@ -690,6 +699,7 @@ bool Engine::undo() {
publishRaw(std::move(e.graph));
recomputePdc();
reapplyRackMacros();
+ reapplyCcRoutes();
applied = true;
}
for (const auto& c : e.mix) applied |= applyMix(c, false);
@@ -724,6 +734,7 @@ bool Engine::redo() {
publishRaw(std::move(e.graph));
recomputePdc();
reapplyRackMacros();
+ reapplyCcRoutes();
applied = true;
}
for (const auto& c : e.mix) applied |= applyMix(c, true);
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index 6e23348d..54fb210a 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -248,6 +248,33 @@ class Engine {
// Add (or reuse) a PluginParam lane; resolves paramId -> current index now.
int32_t addPluginAutomationLane(int32_t trackId, int32_t deviceIndex, const char* paramId);
std::string automationLaneParamId(int32_t trackId, int32_t laneIndex) const;
+ // Nested addresses for save / load (specs/044): a path is (chain index, slot) in the rack at
+ // the lane's / link's / Arp target's device index; chain index -1 = track level.
+ bool automationLanePath(int32_t trackId, int32_t laneIndex, int32_t* chainIndex, int32_t* slot) const;
+ int32_t addNestedAutomationLane(int32_t trackId, int32_t target, int32_t host, int32_t chainIndex, int32_t slot,
+ int32_t paramIndex, const char* paramId);
+ bool cvLinkPath(int32_t trackId, int32_t index, int32_t* srcChain, int32_t* srcSlot, int32_t* tgtChain,
+ int32_t* tgtSlot) const;
+ int32_t addNestedCvLink(int32_t trackId, int32_t sourceKind, int32_t modId, int32_t srcDev, int32_t srcChain,
+ int32_t srcSlot, int32_t srcParam, int32_t targetKind, int32_t targetTrack, int32_t targetDevice,
+ int32_t tgtChain, int32_t tgtSlot, int32_t targetParam);
+ bool midiEffectCcDestPath(int32_t trackId, int32_t index, int32_t* chainIndex, int32_t* slot) const;
+ bool setMidiEffectCcDestPath(int32_t trackId, int32_t index, int32_t chainIndex, int32_t slot);
+ // The uid of chain `chainIndex` of the rack at `host` on trackId (0 if none), and back.
+ uint64_t nestedChainUid(int32_t trackId, int32_t host, int32_t chainIndex) const;
+ // What lives on chain children and must survive save / load outside the rack blob, whose
+ // track ids and chain uids don't (specs/044): an Arp's CC target (dest as device, chain
+ // index, slot) and a child's sidechain key (slot >= 0 a device, -1 the chain instrument).
+ // The setters edit the live child like the track-level ones (no undo; project load).
+ bool rackChainMidiCcDest(int32_t t, int32_t host, int32_t chain, int32_t idx, int32_t* dev, int32_t* destChain,
+ int32_t* destSlot, int32_t* param, float* depth) const;
+ bool rackChainMidiSetCcDest(int32_t t, int32_t host, int32_t chain, int32_t idx, int32_t dev, int32_t destChain,
+ int32_t destSlot, int32_t param, float depth);
+ bool rackChainSidechain(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t* src, int32_t* tapPre,
+ float* gainDb, float* mix) const;
+ bool rackChainSetSidechain(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t src, int32_t tapPre,
+ float gainDb, float mix);
+ int32_t nestedChainIndex(int32_t trackId, int32_t host, uint64_t uid) const;
// --- automation write / record (M9-C) ---
// There are no record modes. Lanes always play back; recording is contextual:
@@ -752,6 +779,21 @@ class Engine {
// track, -3 the clone failed.
bool copyInstrument(int32_t trackId);
int32_t pasteInstrument(int32_t trackId);
+ // Several devices on the clipboard (specs/044): clones of the given MIDI effects, the
+ // instrument and audio effects, in chain order; one device fills the single clipboard as
+ // before. Returns the count, or -1. Paste puts every entry the track can take in one undo
+ // step — MIDI effects at midiAt, the instrument replacing the track's, audio effects at
+ // fxAt (-1 = the end) — and reports the skipped ones; -1 empty, -3 a clone failed.
+ int32_t copyDevices(int32_t trackId, const int32_t* midiIdx, int32_t midiN, bool withInstrument,
+ const int32_t* fxIdx, int32_t fxN);
+ int32_t deviceClipboardCount() const;
+ int32_t pasteDevices(int32_t trackId, int32_t midiAt, int32_t fxAt, int32_t* outSkipped);
+ // The same into chain c of the rack at (trackId, rack): the entries its sections take (an
+ // instrument, a rack, a plug-in into a MIDI Effect Rack are skipped), keys dropped, one undo
+ // step. Returns the number pasted (>= 0) and the first new index in each section (-1 none),
+ // or -1 bad address / nothing on the clipboard, -3 a clone failed.
+ int32_t rackChainPasteDevices(int32_t trackId, int32_t rack, int32_t chain, int32_t midiAt, int32_t fxAt,
+ int32_t* outSkipped, int32_t* outFirstMidi, int32_t* outFirstFx);
// The one place a track's instrument is swapped (Replace, Paste, the built-in / plug-in
// setters): the old instrument's editor closes, one undo step.
bool replaceTrackInstrument(int32_t trackId, std::shared_ptr<Instrument> inst);
@@ -882,17 +924,54 @@ class Engine {
int32_t rackAddPluginInstrumentChain(int32_t trackId, int32_t deviceIndex, int32_t catalogIndex);
int32_t rackAddPluginChainDevice(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t catalogIndex);
RackCore* rackCoreAt(int32_t trackId, int32_t deviceIndex) const; // null if not a rack
+ // specs/044: lanes, CV links and Arp CC targets that point into the rack at (trackId, host)
+ // follow an edit of its chain children. map(chainUid, slot) gives the new (chainUid, slot);
+ // a chainUid of 0 drops the reference. No undo step of its own: part of the rack edit.
+ using NestedMap = std::function<std::pair<uint64_t, int32_t>(uint64_t, int32_t)>;
+ void remapNestedAfterRackEdit(int32_t trackId, int32_t host, const NestedMap& map);
// The rack to apply an undoable edit to (#236): a fork of the rack at (trackId,
// deviceIndex), republished in its track as one undo step. Null if not a rack.
RackCore* rackForEdit(int32_t trackId, int32_t deviceIndex);
- // ⌘G on a device (#257): put the audio effect at deviceIndex into a new Audio Effect Rack
- // (one chain holding the device itself, so nothing restarts) in its place, one undo step;
- // returns the rack's index, or -1 (not an effect, or keyed / automated / CV-linked, which
- // can't follow it into a chain). ⌘⇧G: replace a one-chain rack with that chain's devices;
- // returns how many came out, or -1.
+ // ⌘G on a contiguous run of devices (#257, #328): one new rack in their place holding the
+ // instances themselves (nothing restarts), lanes / CV links / Arp CC targets / sidechain
+ // keys following them into its chain, one undo step. Audio effects only → Audio Effect Rack
+ // at fxFirst; MIDI effects only → MIDI Effect Rack at midiFirst; with the instrument → an
+ // Instrument Rack as the track's instrument, chain 0 = MIDI effects → instrument → audio
+ // effects (the MIDI run must end at the last MIDI effect, the audio run start at 0).
+ // Returns the rack's address (effect index, -1 instrument, kMidiRackBase - i), or a
+ // reason: -2 bad run, -3 not contiguous / MIDI + audio without the instrument, -4 a rack in
+ // the run, -5 a plug-in the rack can't host, -6 an instrument a chain can't hold,
+ // -7 not an instrument track.
+ int32_t groupDevices(int32_t trackId, int32_t midiFirst, int32_t midiCount, bool withInstrument,
+ int32_t fxFirst, int32_t fxCount);
+ // ⌘⇧G: a one-chain rack (family 0 effect at index, 1 MIDI effect at index, 2 the
+ // instrument) back into its chain's devices, references following them. Returns how many
+ // came out, or -2 not a rack, -3 two or more chains, -4 a Drum Rack, -5 an Instrument
+ // Rack chain without an instrument. *outDropped: bit 0 macro mappings, bit 1 chain mix.
+ int32_t ungroupRack(int32_t trackId, int32_t family, int32_t index, int32_t* outDropped);
int32_t wrapDeviceInRack(int32_t trackId, int32_t deviceIndex);
int32_t unwrapRack(int32_t trackId, int32_t deviceIndex);
- bool deviceIsReferenced(const Track& t, int32_t deviceIndex) const;
+ // A reference to a parameter owner on one track, one shape for every kind of pointer
+ // (automation lane, CV link source / target, Arp CC target): fam 0 audio effect, 1 MIDI
+ // effect, 2 the instrument (idx -1); a chain uid + slot when it points into the rack at
+ // (fam, idx). fam -1 = not a device reference; a map returning fam -2 drops it.
+ struct DeviceRef {
+ int32_t fam = -1;
+ int32_t idx = -1;
+ uint64_t uid = 0;
+ int32_t slot = -1;
+ };
+ using DeviceRefMap = std::function<DeviceRef(const DeviceRef&)>;
+ // Group / Ungroup: rewrite every reference into trackId through map and publish nt with
+ // the rewritten links of every track as one undo step.
+ // fresh: a rack Group just built, whose Arps were rewritten already.
+ void publishWithRefMap(int32_t trackId, std::shared_ptr<Track> nt, const DeviceRefMap& map, const RackCore* fresh = nullptr);
+ // An Arp's CC target through map; a changed Arp becomes a clone (shared with undo snapshots).
+ // Retarget an Arp's authoring copy; the route goes live with the next published track.
+ void rewriteArpRef(MidiDevice& m, const DeviceRefMap& map);
+ // The same for Arps inside the track's racks (a MIDI Effect Rack, the Instrument Rack's
+ // chains): a rack holding one to change is forked into nt with clones in its chains.
+ void rewriteRackArps(Track& nt, const DeviceRefMap& map, const RackCore* fresh = nullptr);
// Drum Rack pad note per chain (-1 = all notes; instrument/effect racks ignore it).
int32_t rackChainTriggerNote(int32_t trackId, int32_t deviceIndex, int32_t chain) const;
void rackSetChainTriggerNote(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t note);
@@ -946,6 +1025,8 @@ class Engine {
bool rackRemoveChainMidi(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index);
bool rackMoveChainMidi(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t from, int32_t to);
MidiDevice* rackChainMidiAt(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index) const;
+ // A chain MIDI effect's param, moving a CV link's base on it (specs/044).
+ void rackChainMidiParamSet(int32_t trackId, int32_t rack, int32_t chain, int32_t index, int32_t param, float value);
void rackSetChainMidiBypassed(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index, bool b);
void rackChainSelectRange(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t& lo, int32_t& hi) const;
void rackSetChainSelectRange(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t lo, int32_t hi);
@@ -1244,6 +1325,9 @@ class Engine {
Graph* g, int32_t frames, double blockStart, double spb, bool playing, bool arrangementActive);
// Hand a MIDI-keyed device its source track's notes for this block (from rs_->blockMidi).
void feedMidiKey(Graph* g, Device& d, int32_t srcTrackId);
+ // Sidechain / MIDI key for a device and, for a rack, its chain children (specs/044).
+ void feedDeviceKey(Graph* g, Device& d, int32_t ownTrackId, int32_t frames);
+ void feedRackChildKeys(Graph* g, const RackCore& r, int32_t ownTrackId, int32_t frames);
void renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double spb);
// Session P0 (audio thread): queue a follow action / Repeat retrigger before the launch
// request applies, and after rendering advance the player + end a one-shot slot.
@@ -1278,6 +1362,10 @@ class Engine {
float modOutput(Track& t, int32_t modId, double beat, double timeSec);
void restoreLinkTarget(int32_t ownerTrack, const CvLink& l); // drive target param back to base
void routeCvBaseEdit(int32_t targetKind, int32_t trackId, int32_t device, int32_t param, float value);
+ // The same for a rack chain child (specs/044): a knob turned on a grouped, CV-linked device
+ // moves the link's base, or the next modulation block would overwrite it. slot as in
+ // ParamPath (>= 0 device, -1 the chain instrument, RackCore::midiTarget(i) MIDI effect).
+ void routeNestedCvBaseEdit(int32_t trackId, int32_t rack, int32_t chain, int32_t slot, int32_t param, float value);
// The base a CV link holds for this target, if one targets it (what a UI edit sets).
bool cvBaseValue(int32_t targetKind, int32_t trackId, int32_t device, int32_t param, float& out) const;
int32_t addCvLinkFull(int32_t trackId, int32_t sourceKind, int32_t modId, int32_t srcDev, int32_t srcParam,
@@ -1317,17 +1405,30 @@ class Engine {
void republishWithTrackRaw(int32_t trackId, std::shared_ptr<Track> nt); // no undo entry
void pushUndo(); // snapshot authoring_ onto the undo stack, clear redo
void reapplyRackMacros(); // after undo/redo: racks drive their shared children again
+ void reapplyCcRoutes(); // after undo/redo: Arps take their restored snapshot's targets
+ void syncCcRoutes(Graph& g); // before a publish: routes of fresh tracks from their Arps
+ void republishCcRoutes(int32_t trackId); // after a live CC target change: publish its route
+ bool ccRoutesUsed_ = false; // no Arp has had a CC target yet: undo / redo skip the walk
+ bool ccDestsSet_ = false; // no CC target was ever set: publishes skip syncCcRoutes
static int32_t trackLatency(const Track& t);
std::shared_ptr<Instrument> cloneInstrument(const Track& src) const; // duplicateTrack helper
std::shared_ptr<Instrument> cloneInstrumentFrom(const Instrument& src) const;
// Copies of the automation lanes on one device of `t` (family as transferDevice; for the
// instrument, PluginParam lanes with deviceIndex < 0), in lane order.
- std::vector<AutomationLane> deviceLanes(const Track& t, int32_t family, int32_t index) const;
+ std::vector<TrackLane> deviceLanes(const Track& t, int32_t family, int32_t index) const;
std::shared_ptr<Device> cloneDevice(const Device& src) const;
std::shared_ptr<MidiDevice> cloneMidiDevice(const MidiDevice& src) const;
std::shared_ptr<Device> clipDevice_; // device clipboard (#238): a clone of the copied audio effect
std::shared_ptr<MidiDevice> clipMidi_;
std::shared_ptr<Instrument> clipInstrument_; // the instrument on the device clipboard (specs/043)
+ // Several devices on the clipboard (specs/044), in chain order; empty while the single
+ // fields above hold it.
+ struct ClipEntry {
+ std::shared_ptr<MidiDevice> midi;
+ std::shared_ptr<Instrument> inst;
+ std::shared_ptr<Device> dev;
+ };
+ std::vector<ClipEntry> clipMany_;
int32_t insertDeviceClone(int32_t trackId, std::shared_ptr<Device> dev, int32_t atIndex);
int32_t insertMidiEffectClone(int32_t trackId, std::shared_ptr<MidiDevice> md, int32_t atIndex); // ... or of the copied MIDI effect (one of the two at a time)
void recomputePdc(); // message thread: realign all tracks
@@ -1382,7 +1483,7 @@ class Engine {
// the points inside the clip's span, beats stored RELATIVE to the clip start.
// Reapplied on paste/duplicate. clipboardAutoTrack_ = the source track (so a paste
// back onto it can restore device/plugin lanes, whose indices are track-positional).
- std::vector<AutomationLane> clipboardAuto_;
+ std::vector<TrackLane> clipboardAuto_;
int32_t clipboardAutoTrack_ = -1;
// Block clip clipboard (multi-selection). Each entry is one captured clip with its
@@ -1396,7 +1497,7 @@ class Engine {
bool sameTrack = true; // false once remapped to another track
AudioClip audio;
MidiClip midi;
- std::vector<AutomationLane> autom; // clip-relative automation snippet
+ std::vector<TrackLane> autom; // clip-relative automation snippet
};
std::vector<BlockClip> clipboardBlock_;
double clipboardBlockLen_ = 0.0;
@@ -1415,8 +1516,8 @@ class Engine {
// applyClipAutomation re-lands them at placedStart (clearing that span first on each
// matching lane); non-Volume/Pan lanes are applied only on the source track (sameTrack)
// since device/param indices are positional. removeAutomationInRange clears a span.
- std::vector<AutomationLane> captureClipAutomation(const Track& t, double start, double end) const;
- void applyClipAutomation(Track& nt, int32_t trackId, const std::vector<AutomationLane>& snips, double placedStart,
+ std::vector<TrackLane> captureClipAutomation(const Track& t, double start, double end) const;
+ void applyClipAutomation(Track& nt, int32_t trackId, const std::vector<TrackLane>& snips, double placedStart,
double len, bool sameTrack) const;
static void removeAutomationInRange(Track& t, double start, double end);
// Two tracks have an identical device layout (same instrument kind + same device kinds in
diff --git a/src/native/nota.engine/src/engine/Engine_Automation.cpp b/src/native/nota.engine/src/engine/Engine_Automation.cpp
index e132ce2f..2b2b202c 100644
--- a/src/native/nota.engine/src/engine/Engine_Automation.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Automation.cpp
@@ -4,6 +4,7 @@
// Engine — parameter automation (M9): read/apply, lane CRUD, hosted-plugin parameter surface, contextual write recording, self-tests.
#include "Engine.h"
+#include "ParamResolve.h"
#include "bridge/PluginHostBridge.h"
#include "devices/instruments/Synth.h"
@@ -17,9 +18,19 @@ namespace nota {
void Engine::applyAutomation(Graph* g, double beat) {
for (auto& tptr : g->tracks) {
Track& t = *tptr;
- for (const AutomationLane& lane : t.automation) {
+ for (const TrackLane& lane : t.automation) {
if (lane.points.empty() || lane.suppressRead) continue; // M9-C: control leads while writing
const float v = lane.valueAt(beat);
+ if (lane.nested()) { // a device grouped into a rack (specs/044)
+ const ParamOwner o = resolveNested(t, lane.deviceIndex, lane.chainUid, lane.slot);
+ if (lane.target == AutomationTarget::PluginParam) {
+ if (lane.paramIndex < 0) continue;
+ if (o.instrument) o.instrument->pluginParamSet(lane.paramIndex, v);
+ else if (o.device) o.device->pluginParamSet(lane.paramIndex, v);
+ } else if (o.device) o.device->setParam(lane.paramIndex, v);
+ else if (o.midi) o.midi->setParam(lane.paramIndex, v);
+ continue;
+ }
switch (lane.target) {
case AutomationTarget::Volume: t.setVolume(v); break;
case AutomationTarget::Pan: t.setPan(v); break;
@@ -51,7 +62,7 @@ void Engine::applyAutomation(Graph* g, double beat) {
bool Engine::automationSelfTest() {
// Volume lane: 1.0 at beat 0, 0.0 at beat 4 -> 0.5 at beat 2; hold at ends.
- AutomationLane lane;
+ TrackLane lane;
lane.target = AutomationTarget::Volume;
lane.points = {{0.0, 1.0f}, {4.0, 0.0f}};
if (std::fabs(lane.valueAt(2.0) - 0.5f) > 1e-4f) return false;
@@ -72,7 +83,7 @@ bool Engine::automationCurveSelfTest() {
// Segment 0->4, value 0->1. At the midpoint (beat 2) a linear lane reads 0.5;
// ease-out curve (+1) reads well above, ease-in (-1) well below, and the curve
// rides on the LEFT point of the segment. Endpoints stay exact.
- AutomationLane lane;
+ TrackLane lane;
lane.target = AutomationTarget::Volume;
lane.points = {{0.0, 0.0f, 0.0f}, {4.0, 1.0f, 0.0f}};
if (std::fabs(lane.valueAt(2.0) - 0.5f) > 1e-4f) return false; // linear baseline
@@ -174,12 +185,12 @@ int32_t Engine::addPluginAutomationLane(int32_t trackId, int32_t deviceIndex, co
const std::string id = paramId ? paramId : "";
// Reuse an existing lane on the same (device, param).
for (size_t i = 0; i < old->automation.size(); ++i) {
- const AutomationLane& l = old->automation[i];
- if (l.target == AutomationTarget::PluginParam && l.deviceIndex == deviceIndex && l.paramId == id)
+ const TrackLane& l = old->automation[i];
+ if (!l.nested() && l.target == AutomationTarget::PluginParam && l.deviceIndex == deviceIndex && l.paramId == id)
return static_cast<int32_t>(i);
}
auto nt = cloneTrack(*old);
- AutomationLane lane;
+ TrackLane lane;
lane.target = AutomationTarget::PluginParam;
lane.deviceIndex = deviceIndex;
lane.paramId = id;
@@ -190,6 +201,61 @@ int32_t Engine::addPluginAutomationLane(int32_t trackId, int32_t deviceIndex, co
return index;
}
+// ---- nested addresses for save / load (specs/044) ---------------------------
+uint64_t Engine::nestedChainUid(int32_t trackId, int32_t host, int32_t chainIndex) const {
+ auto t = findTrackAuthoring(trackId);
+ const RackCore* r = t ? rackAtHost(*t, host) : nullptr;
+ return r ? r->chainBaseUid(chainIndex) : 0;
+}
+int32_t Engine::nestedChainIndex(int32_t trackId, int32_t host, uint64_t uid) const {
+ auto t = findTrackAuthoring(trackId);
+ const RackCore* r = t ? rackAtHost(*t, host) : nullptr;
+ return r ? r->chainIndexOfUid(uid) : -1;
+}
+
+bool Engine::automationLanePath(int32_t trackId, int32_t laneIndex, int32_t* chainIndex, int32_t* slot) const {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || laneIndex < 0 || laneIndex >= static_cast<int32_t>(t->automation.size())) return false;
+ const TrackLane& l = t->automation[laneIndex];
+ if (chainIndex) *chainIndex = l.nested() ? nestedChainIndex(trackId, l.deviceIndex, l.chainUid) : -1;
+ if (slot) *slot = l.nested() ? l.slot : -1;
+ return true;
+}
+
+int32_t Engine::addNestedAutomationLane(int32_t trackId, int32_t target, int32_t host, int32_t chainIndex,
+ int32_t slot, int32_t paramIndex, const char* paramId) {
+ auto old = findTrackAuthoring(trackId);
+ const uint64_t uid = nestedChainUid(trackId, host, chainIndex);
+ if (!old || uid == 0) return -1;
+ const auto tgt = static_cast<AutomationTarget>(target);
+ if (tgt != AutomationTarget::DeviceParam && tgt != AutomationTarget::MidiDeviceParam && tgt != AutomationTarget::PluginParam)
+ return -1;
+ TrackLane lane;
+ lane.target = tgt;
+ lane.deviceIndex = host;
+ lane.chainUid = uid;
+ lane.slot = slot;
+ lane.paramId = paramId ? paramId : "";
+ lane.paramIndex = paramIndex;
+ if (tgt == AutomationTarget::PluginParam && !lane.paramId.empty()) {
+ const ParamOwner o = resolveNested(*old, host, uid, slot);
+ lane.paramIndex = o.instrument ? o.instrument->pluginParamIndexOfId(lane.paramId)
+ : o.device ? o.device->pluginParamIndexOfId(lane.paramId)
+ : -1;
+ }
+ for (size_t i = 0; i < old->automation.size(); ++i) { // one lane per target
+ const TrackLane& l = old->automation[i];
+ if (l.target == tgt && l.deviceIndex == host && l.chainUid == uid && l.slot == slot
+ && (tgt == AutomationTarget::PluginParam ? l.paramId == lane.paramId : l.paramIndex == paramIndex))
+ return static_cast<int32_t>(i);
+ }
+ auto nt = cloneTrack(*old);
+ nt->automation.push_back(std::move(lane));
+ const int32_t index = static_cast<int32_t>(nt->automation.size()) - 1;
+ republishWithTrack(trackId, nt);
+ return index;
+}
+
std::string Engine::automationLaneParamId(int32_t trackId, int32_t laneIndex) const {
auto t = findTrackAuthoring(trackId);
if (!t || laneIndex < 0 || laneIndex >= static_cast<int32_t>(t->automation.size())) return {};
@@ -251,8 +317,8 @@ void Engine::setAutomationRecord(bool on) {
static int32_t findLaneFor(
const Track& t, int32_t target, int32_t deviceIndex, int32_t paramIndex, const std::string& paramId) {
for (size_t i = 0; i < t.automation.size(); ++i) {
- const AutomationLane& l = t.automation[i];
- if (l.target != static_cast<AutomationTarget>(target)) continue;
+ const TrackLane& l = t.automation[i];
+ if (l.nested() || l.target != static_cast<AutomationTarget>(target)) continue; // specs/044
switch (l.target) {
case AutomationTarget::DeviceParam:
case AutomationTarget::MidiDeviceParam:
@@ -469,7 +535,7 @@ bool Engine::pluginAutomationSelfTest() {
auto g = std::make_shared<Graph>();
auto t = std::make_shared<Track>(9998, TrackType::Instrument);
t->instrument = std::make_shared<Synth>();
- AutomationLane lane;
+ TrackLane lane;
lane.target = AutomationTarget::PluginParam;
lane.deviceIndex = -1; // instrument
lane.paramIndex = 0;
@@ -489,12 +555,12 @@ int32_t Engine::addAutomationLane(int32_t trackId, int32_t target, int32_t devic
const bool usesDev = tgt == AutomationTarget::DeviceParam || tgt == AutomationTarget::MidiDeviceParam;
// Reuse an existing lane on the same target (no snapshot) — one lane per target.
for (size_t i = 0; i < old->automation.size(); ++i) {
- const AutomationLane& l = old->automation[i];
- if (l.target == tgt && (!usesDev || (l.deviceIndex == deviceIndex && l.paramIndex == paramIndex)))
+ const TrackLane& l = old->automation[i];
+ if (!l.nested() && l.target == tgt && (!usesDev || (l.deviceIndex == deviceIndex && l.paramIndex == paramIndex)))
return static_cast<int32_t>(i);
}
auto nt = cloneTrack(*old);
- AutomationLane lane;
+ TrackLane lane;
lane.target = tgt;
lane.deviceIndex = usesDev ? deviceIndex : -1;
lane.paramIndex = usesDev ? paramIndex : -1;
@@ -508,7 +574,9 @@ int32_t Engine::addAutomationLane(int32_t trackId, int32_t target, int32_t devic
void Engine::remapAutomationAfterDeviceChange(Track& nt, bool midi, int32_t removedIndex, int32_t from, int32_t to) {
// Lanes on the effect chain (DeviceParam / PluginParam >= 0) or the MIDI-FX chain.
- auto onChain = [midi](const AutomationLane& l) {
+ auto onChain = [midi](const TrackLane& l) {
+ // A nested lane (specs/044) follows its rack: deviceIndex is the rack's address.
+ if (l.nested()) return midi ? isMidiHost(l.deviceIndex) : l.deviceIndex >= 0;
if (midi) return l.target == AutomationTarget::MidiDeviceParam;
return l.target == AutomationTarget::DeviceParam ||
(l.target == AutomationTarget::PluginParam && l.deviceIndex >= 0);
@@ -527,17 +595,18 @@ void Engine::remapAutomationAfterDeviceChange(Track& nt, bool midi, int32_t remo
// laneMap: old lane index → new lane index (-1 = dropped with its device).
std::vector<int32_t> laneMap(nt.automation.size());
- std::vector<AutomationLane> kept;
+ std::vector<TrackLane> kept;
kept.reserve(nt.automation.size());
for (size_t i = 0; i < nt.automation.size(); ++i) {
- AutomationLane& l = nt.automation[i];
+ TrackLane& l = nt.automation[i];
if (onChain(l)) {
- const int32_t ni = remap(l.deviceIndex);
+ const bool midiRack = l.nested() && midi;
+ const int32_t ni = remap(midiRack ? midiHostIndex(l.deviceIndex) : l.deviceIndex);
if (ni < 0) {
laneMap[i] = -1;
continue;
}
- l.deviceIndex = ni;
+ l.deviceIndex = midiRack ? midiHost(ni) : ni;
}
laneMap[i] = static_cast<int32_t>(kept.size());
kept.push_back(std::move(l));
@@ -564,11 +633,15 @@ void Engine::remapAutomationAfterDeviceChange(Track& nt, bool midi, int32_t remo
std::erase_if(overrides_, [&](OverrideTarget& o) { return o.trackId == trackId && laneGone(o.laneIndex); });
}
-std::vector<AutomationLane> Engine::deviceLanes(const Track& t, int32_t family, int32_t index) const {
- std::vector<AutomationLane> out;
+std::vector<TrackLane> Engine::deviceLanes(const Track& t, int32_t family, int32_t index) const {
+ std::vector<TrackLane> out;
for (const auto& l : t.automation) {
bool on = false;
- switch (family) {
+ if (l.nested()) // lanes into a rack go where the rack goes (specs/044)
+ on = family == 0 ? l.deviceIndex == index && index >= 0
+ : family == 1 ? l.deviceIndex == midiHost(index)
+ : family == 2 && l.deviceIndex == -1;
+ else switch (family) {
case 0:
on = (l.target == AutomationTarget::DeviceParam || l.target == AutomationTarget::PluginParam) && l.deviceIndex == index;
break;
@@ -626,7 +699,7 @@ bool Engine::automationLaneInfo(int32_t trackId, int32_t laneIndex, int32_t* out
int32_t* outParamIndex, int32_t* outPointCount) const {
auto t = findTrackAuthoring(trackId);
if (!t || laneIndex < 0 || laneIndex >= static_cast<int32_t>(t->automation.size())) return false;
- const AutomationLane& l = t->automation[laneIndex];
+ const TrackLane& l = t->automation[laneIndex];
if (outTarget) *outTarget = static_cast<int32_t>(l.target);
if (outDeviceIndex) *outDeviceIndex = l.deviceIndex;
if (outParamIndex) *outParamIndex = l.paramIndex;
diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cpp
index 8ce90f6a..6e09eb9d 100644
--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp
@@ -4,6 +4,7 @@
// Engine — hosted plugins & device chain (M3): load instrument/effect, device CRUD/params/bypass/editor/state, clone helpers, kind/id introspection, PDC latency.
#include "Engine.h"
+#include "ParamResolve.h"
#include "devices/DeviceFactory.h"
#include "devices/racks/MidiRack.h"
#include "devices/racks/RackInstrument.h"
@@ -774,6 +775,7 @@ std::shared_ptr<MidiDevice> Engine::cloneMidiDevice(const MidiDevice& src) const
if (!st.empty()) d->setState(st.data(), (int32_t)st.size());
}
d->setCcDest(src.ccDestDevice(), src.ccDestParam()); // the Arp's CC modulation (#238)
+ d->setCcDestNested(src.ccDestChainUid(), src.ccDestSlot());
d->setCcDepth(src.ccDepth());
d->setBypassed(src.bypassed());
d->setFolded(src.folded());
@@ -791,6 +793,7 @@ bool Engine::copyDevice(int32_t trackId, int32_t deviceIndex) {
clipDevice_ = std::move(c);
clipMidi_.reset();
clipInstrument_.reset();
+ clipMany_.clear();
return true;
}
@@ -801,6 +804,7 @@ bool Engine::copyMidiEffect(int32_t trackId, int32_t index) {
clipMidi_ = std::move(c);
clipDevice_.reset();
clipInstrument_.reset();
+ clipMany_.clear();
return true;
}
@@ -813,6 +817,7 @@ bool Engine::copyInstrument(int32_t trackId) {
clipInstrument_ = std::move(c);
clipDevice_.reset();
clipMidi_.reset();
+ clipMany_.clear();
return true;
}
@@ -863,7 +868,7 @@ int32_t Engine::transferDevice(int32_t srcId, int32_t family, int32_t index, int
auto ns = (keepSource || inst) ? nullptr : cloneTrack(*src);
auto nd = cloneTrack(*dst);
- std::vector<AutomationLane> lanes;
+ std::vector<TrackLane> lanes;
if (!keepSource) lanes = deviceLanes(*src, family, index);
int32_t at = 0;
@@ -890,8 +895,10 @@ int32_t Engine::transferDevice(int32_t srcId, int32_t family, int32_t index, int
if (d == index) {
c->setCcDest(-1, -1);
flags |= kTransferLinksDropped;
- } else
+ } else {
c->setCcDest(d - 1, m->ccDestParam());
+ c->setCcDestNested(m->ccDestChainUid(), m->ccDestSlot()); // a target in a rack keeps its child
+ }
m = c;
}
}
@@ -925,13 +932,13 @@ int32_t Engine::transferDevice(int32_t srcId, int32_t family, int32_t index, int
nd->instrument = in;
}
for (auto& l : lanes) {
- if (!inst) l.deviceIndex = at;
+ if (!inst) l.deviceIndex = l.nested() && family == 1 ? midiHost(at) : at; // a MIDI rack's nested lanes keep its encoding
// An instrument lane for a parameter the new track already automates takes that lane's
// place, so there is one lane per parameter (edits and recording find the first one).
- AutomationLane* same = nullptr;
- if (inst)
+ TrackLane* same = nullptr;
+ if (inst && !l.nested())
for (auto& d : nd->automation)
- if (d.target == AutomationTarget::PluginParam && d.deviceIndex < 0
+ if (!d.nested() && d.target == AutomationTarget::PluginParam && d.deviceIndex < 0
&& (l.paramId.empty() ? d.paramId.empty() && d.paramIndex == l.paramIndex : d.paramId == l.paramId)) {
same = &d;
break;
@@ -984,7 +991,119 @@ int32_t Engine::transferDevice(int32_t srcId, int32_t family, int32_t index, int
return inst ? 0 : at;
}
-int32_t Engine::deviceClipboardKind() const { return clipDevice_ ? 1 : clipMidi_ ? 2 : clipInstrument_ ? 3 : 0; }
+int32_t Engine::deviceClipboardKind() const {
+ if (!clipMany_.empty()) return 4;
+ return clipDevice_ ? 1 : clipMidi_ ? 2 : clipInstrument_ ? 3 : 0;
+}
+
+int32_t Engine::deviceClipboardCount() const {
+ if (!clipMany_.empty()) return static_cast<int32_t>(clipMany_.size());
+ return clipDevice_ || clipMidi_ || clipInstrument_ ? 1 : 0;
+}
+
+// ---- several devices on the clipboard (specs/044) ----------------------------
+int32_t Engine::copyDevices(int32_t trackId, const int32_t* midiIdx, int32_t midiN, bool withInstrument,
+ const int32_t* fxIdx, int32_t fxN) {
+ midiN = midiIdx ? std::max(0, midiN) : 0;
+ fxN = fxIdx ? std::max(0, fxN) : 0;
+ const int32_t total = midiN + fxN + (withInstrument ? 1 : 0);
+ if (total == 0) return -1;
+ if (total == 1) { // one device: the single clipboard, as before
+ const bool ok = midiN ? copyMidiEffect(trackId, midiIdx[0]) : fxN ? copyDevice(trackId, fxIdx[0]) : copyInstrument(trackId);
+ return ok ? 1 : -1;
+ }
+ auto t = findTrackAuthoring(trackId);
+ if (!t) return -1;
+ std::vector<int32_t> mi(midiIdx, midiIdx + midiN), fi(fxIdx, fxIdx + fxN);
+ std::sort(mi.begin(), mi.end());
+ std::sort(fi.begin(), fi.end());
+ std::vector<ClipEntry> out;
+ for (int32_t i : mi) {
+ MidiDevice* m = i >= 0 && i < static_cast<int32_t>(t->midiEffects.size()) ? t->midiEffects[i].get() : nullptr;
+ auto c = m ? cloneMidiDevice(*m) : nullptr;
+ if (!c) return -1;
+ out.push_back({std::move(c), nullptr, nullptr});
+ }
+ if (withInstrument) {
+ if (t->type() != TrackType::Instrument || !t->instrument) return -1;
+ auto c = cloneInstrumentFrom(*t->instrument);
+ if (!c) return -1;
+ c->setBypassed(t->instrument->bypassed());
+ out.push_back({nullptr, std::move(c), nullptr});
+ }
+ for (int32_t i : fi) {
+ Device* d = i >= 0 && i < static_cast<int32_t>(t->devices.size()) ? t->devices[i].get() : nullptr;
+ auto c = d ? cloneDevice(*d) : nullptr;
+ if (!c) return -1;
+ out.push_back({nullptr, nullptr, std::move(c)});
+ }
+ clipMany_ = std::move(out);
+ clipDevice_.reset();
+ clipMidi_.reset();
+ clipInstrument_.reset();
+ return total;
+}
+
+int32_t Engine::pasteDevices(int32_t trackId, int32_t midiAt, int32_t fxAt, int32_t* outSkipped) {
+ if (outSkipped) *outSkipped = 0;
+ std::vector<ClipEntry> src = clipMany_;
+ if (src.empty()) {
+ if (clipMidi_) src.push_back({clipMidi_, nullptr, nullptr});
+ else if (clipInstrument_) src.push_back({nullptr, clipInstrument_, nullptr});
+ else if (clipDevice_) src.push_back({nullptr, nullptr, clipDevice_});
+ }
+ if (src.empty()) return -1;
+ auto old = findTrackAuthoring(trackId);
+ if (!old) return -1;
+ const bool instTrack = old->type() == TrackType::Instrument;
+ // Clone everything first, so a plug-in that won't load leaves the track untouched.
+ std::vector<std::shared_ptr<MidiDevice>> mids;
+ std::shared_ptr<Instrument> inst;
+ std::vector<std::shared_ptr<Device>> devs;
+ int32_t skipped = 0;
+ for (auto& e : src) {
+ if (e.midi) {
+ if (!instTrack) { ++skipped; continue; }
+ auto c = cloneMidiDevice(*e.midi);
+ if (!c) return -3;
+ c->setCcDest(-1, -1); // its CC target named a device on the track it came from
+ mids.push_back(std::move(c));
+ } else if (e.inst) {
+ if (!instTrack) { ++skipped; continue; }
+ inst = cloneInstrumentFrom(*e.inst);
+ if (!inst) return -3;
+ inst->setBypassed(e.inst->bypassed());
+ } else if (e.dev) {
+ auto c = cloneDevice(*e.dev);
+ if (!c) return -3;
+ if (c->sidechainSourceTrackId() == trackId) c->setSidechainSourceTrackId(-1); // no key from itself
+ devs.push_back(std::move(c));
+ }
+ }
+ if (outSkipped) *outSkipped = skipped;
+ const int32_t pasted = static_cast<int32_t>(mids.size() + devs.size()) + (inst ? 1 : 0);
+ if (pasted == 0) return 0;
+ auto nt = cloneTrack(*old);
+ const int32_t mEnd = static_cast<int32_t>(nt->midiEffects.size()), fEnd = static_cast<int32_t>(nt->devices.size());
+ const int32_t ma = midiAt < 0 || midiAt > mEnd ? mEnd : midiAt, fa = fxAt < 0 || fxAt > fEnd ? fEnd : fxAt;
+ const int32_t km = static_cast<int32_t>(mids.size()), kf = static_cast<int32_t>(devs.size());
+ // References to the devices after each insert shift; the pasted ones have none yet.
+ DeviceRefMap map = [=](const DeviceRef& r) -> DeviceRef {
+ if (r.fam == 0 && r.idx >= fa) return {0, r.idx + kf, r.uid, r.slot};
+ if (r.fam == 1 && r.idx >= ma) return {1, r.idx + km, r.uid, r.slot};
+ return r;
+ };
+ if (inst) {
+ if (old->instrument) old->instrument->closeEditor();
+ nt->instrument = inst;
+ }
+ // The pasted MIDI effects carry no CC target, so the map leaves them alone.
+ nt->midiEffects.insert(nt->midiEffects.begin() + ma, mids.begin(), mids.end());
+ nt->devices.insert(nt->devices.begin() + fa, devs.begin(), devs.end());
+ publishWithRefMap(trackId, nt, map);
+ recomputePdc();
+ return pasted;
+}
bool Engine::deviceClipboardSidechain() const { return clipDevice_ && clipDevice_->sidechainSourceTrackId() >= 0; }
@@ -1168,7 +1287,38 @@ void Engine::midiEffectCommand(int32_t t, int32_t i, int32_t cmd) {
if (auto* m = midiDeviceAt(t, i)) m->midiCommand(cmd);
}
void Engine::setMidiEffectCcDest(int32_t t, int32_t i, int32_t dev, int32_t param) {
- if (auto* m = midiDeviceAt(t, i)) m->setCcDest(dev, param);
+ auto* m = midiDeviceAt(t, i);
+ if (!m) return;
+ m->setCcDest(dev, param);
+ republishCcRoutes(t);
+}
+
+// The audio thread plays the routes of the published track (Track::ccRoutes): after a live CC
+// target change, publish the track again so the route follows (no undo step, as before).
+void Engine::republishCcRoutes(int32_t trackId) {
+ // The first target ever set turns route syncing on. Until then no Arp has a target, so the
+ // tracks skipped meanwhile have no route to lose (their empty lists stay as they are).
+ ccDestsSet_ = true;
+ if (auto old = findTrackAuthoring(trackId)) republishWithTrackRaw(trackId, cloneTrack(*old));
+}
+// The Arp's CC target inside a rack (specs/044), for save / load: (chain index, slot) in the
+// rack at its ccDestDevice; set it after setMidiEffectCcDest.
+bool Engine::midiEffectCcDestPath(int32_t t, int32_t i, int32_t* chainIndex, int32_t* slot) const {
+ auto* m = midiDeviceAt(t, i);
+ if (!m) return false;
+ const uint64_t uid = m->ccDestChainUid();
+ if (chainIndex) *chainIndex = uid ? nestedChainIndex(t, m->ccDestDevice(), uid) : -1;
+ if (slot) *slot = uid ? m->ccDestSlot() : -1;
+ return true;
+}
+bool Engine::setMidiEffectCcDestPath(int32_t t, int32_t i, int32_t chainIndex, int32_t slot) {
+ auto* m = midiDeviceAt(t, i);
+ if (!m) return false;
+ const uint64_t uid = nestedChainUid(t, m->ccDestDevice(), chainIndex);
+ if (!uid) return false;
+ m->setCcDestNested(uid, slot);
+ republishCcRoutes(t);
+ return true;
}
void Engine::setMidiEffectCcDepth(int32_t t, int32_t i, float d) {
if (auto* m = midiDeviceAt(t, i)) m->setCcDepth(d);
@@ -1367,9 +1517,20 @@ void Engine::recomputeRouting() {
if (next < kMaxRoutes) routeSlotTrackId_[next++].store(src, std::memory_order_relaxed);
};
for (auto& t : authoring_->tracks) {
- if (t->instrument) claim(t->instrument->sidechainSourceTrackId());
+ // Keyed children inside racks claim too (specs/044).
+ auto claimChildren = [&](const RackCore& r) {
+ r.forEachChildDevice([&](Device& c) { claim(c.sidechainSourceTrackId()); });
+ r.forEachChildInstrument([&](Instrument& i) { claim(i.sidechainSourceTrackId()); });
+ };
+ if (t->instrument) {
+ claim(t->instrument->sidechainSourceTrackId());
+ if (auto* r = t->instrument->asRack()) claimChildren(*r);
+ }
for (auto& d : t->devices)
- if (d) claim(d->sidechainSourceTrackId());
+ if (d) {
+ claim(d->sidechainSourceTrackId());
+ if (auto* r = d->asRack()) claimChildren(*r);
+ }
// A monitoring audio track hears its source track's post-fader tap.
if (t->type() == TrackType::Audio && t->monitor() && t->recordInputSource() > 0) claim(t->recordInputSource());
}
diff --git a/src/native/nota.engine/src/engine/Engine_Modulation.cpp b/src/native/nota.engine/src/engine/Engine_Modulation.cpp
index 7a5bb9ff..e5688cc7 100644
--- a/src/native/nota.engine/src/engine/Engine_Modulation.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Modulation.cpp
@@ -11,6 +11,7 @@
// layer copies trivially across graph snapshots and needs no per-block phase state.
#include "Engine.h"
+#include "ParamResolve.h"
#include <algorithm>
@@ -108,45 +109,55 @@ float Engine::modulatorValue(int32_t trackId, int32_t modId) const {
// ---- modulation target read/write (device / instrument / MIDI-FX) ----------
+// The owner of a link's target: a track-level device, the instrument or a MIDI effect,
+// or (uid != 0, specs/044) a child of the rack at `dev`. Reads the published graph only.
+static ParamOwner targetOwner(Track& t, int32_t kind, int32_t dev, uint64_t uid, int32_t slot) {
+ if (uid != 0) return resolveNested(t, dev, uid, slot);
+ ParamOwner o;
+ if (kind == static_cast<int32_t>(CvTargetKind::Instrument)) o.instrument = t.instrument.get();
+ else if (kind == static_cast<int32_t>(CvTargetKind::MidiFx)) {
+ if (dev >= 0 && dev < static_cast<int32_t>(t.midiEffects.size())) o.midi = t.midiEffects[dev].get();
+ } else if (dev >= 0 && dev < static_cast<int32_t>(t.devices.size()))
+ o.device = t.devices[dev].get();
+ return o;
+}
+
// True if (kind, dev, param) names a live target on track t.
-static bool targetValid(Track& t, int32_t kind, int32_t dev, int32_t param) {
+static bool targetValid(Track& t, int32_t kind, int32_t dev, int32_t param, uint64_t uid = 0, int32_t slot = -1) {
+ const ParamOwner o = targetOwner(t, kind, dev, uid, slot);
+ if (param < 0) return false;
if (kind == static_cast<int32_t>(CvTargetKind::Instrument))
- return t.instrument && param >= 0 && param < t.instrument->pluginParamCount();
- if (kind == static_cast<int32_t>(CvTargetKind::MidiFx))
- return dev >= 0 && dev < static_cast<int32_t>(t.midiEffects.size()) && t.midiEffects[dev] && param >= 0 &&
- param < t.midiEffects[dev]->paramCount();
- return dev >= 0 && dev < static_cast<int32_t>(t.devices.size()) && t.devices[dev] && param >= 0 &&
- param < t.devices[dev]->paramCount();
-}
-// Current value + range of a target (instrument params are normalized 0..1).
-static float targetGet(Track& t, int32_t kind, int32_t dev, int32_t param, float& mn, float& mx) {
+ return o.instrument && param < o.instrument->pluginParamCount();
+ if (kind == static_cast<int32_t>(CvTargetKind::MidiFx)) return o.midi && param < o.midi->paramCount();
+ return o.device && param < o.device->paramCount();
+}
+// Current value + range of a target (instrument params are normalized 0..1). Call after targetValid.
+static float targetGet(Track& t, int32_t kind, int32_t dev, int32_t param, float& mn, float& mx, uint64_t uid = 0,
+ int32_t slot = -1) {
mn = 0.0f;
mx = 1.0f;
+ const ParamOwner o = targetOwner(t, kind, dev, uid, slot);
if (kind == static_cast<int32_t>(CvTargetKind::Instrument))
- return t.instrument ? t.instrument->pluginParamGet(param) : 0.0f;
+ return o.instrument ? o.instrument->pluginParamGet(param) : 0.0f;
if (kind == static_cast<int32_t>(CvTargetKind::MidiFx)) {
- auto* m = t.midiEffects[dev].get();
- mn = m->paramMin(param);
- mx = m->paramMax(param);
- return m->getParam(param);
+ if (!o.midi) return 0.0f;
+ mn = o.midi->paramMin(param);
+ mx = o.midi->paramMax(param);
+ return o.midi->getParam(param);
}
- auto* d = t.devices[dev].get();
- mn = d->paramMin(param);
- mx = d->paramMax(param);
- return d->getParam(param);
+ if (!o.device) return 0.0f;
+ mn = o.device->paramMin(param);
+ mx = o.device->paramMax(param);
+ return o.device->getParam(param);
}
-static void targetSet(Track& t, int32_t kind, int32_t dev, int32_t param, float v) {
+static void targetSet(Track& t, int32_t kind, int32_t dev, int32_t param, float v, uint64_t uid = 0, int32_t slot = -1) {
+ const ParamOwner o = targetOwner(t, kind, dev, uid, slot);
if (kind == static_cast<int32_t>(CvTargetKind::Instrument)) {
- if (t.instrument) t.instrument->pluginParamSet(param, v);
- return;
- }
- if (kind == static_cast<int32_t>(CvTargetKind::MidiFx)) {
- if (dev >= 0 && dev < static_cast<int32_t>(t.midiEffects.size()))
- if (auto* m = t.midiEffects[dev].get()) m->setParam(param, v);
- return;
- }
- if (dev >= 0 && dev < static_cast<int32_t>(t.devices.size()))
- if (auto* d = t.devices[dev].get()) d->setParam(param, v);
+ if (o.instrument) o.instrument->pluginParamSet(param, v);
+ } else if (kind == static_cast<int32_t>(CvTargetKind::MidiFx)) {
+ if (o.midi) o.midi->setParam(param, v);
+ } else if (o.device)
+ o.device->setParam(param, v);
}
// Generalized link creation. Source: modulator or param. Target: device / instrument / MIDI-FX.
@@ -163,7 +174,7 @@ int32_t Engine::addCvLinkFull(int32_t trackId, int32_t sourceKind, int32_t modId
if (!tgtTrack || !targetValid(*tgtTrack, targetKind, targetDevice, targetParam)) return -1;
const int32_t storedTarget = tgt == trackId ? -1 : tgt;
for (auto& l : old->cvLinks)
- if (l.sourceKind == sourceKind && l.sourceModId == modId && l.sourceDevice == srcDev &&
+ if (l.sourceChainUid == 0 && l.targetChainUid == 0 && l.sourceKind == sourceKind && l.sourceModId == modId && l.sourceDevice == srcDev &&
l.sourceParam == srcParam && l.targetKind == targetKind && l.targetTrack == storedTarget &&
l.targetDevice == targetDevice && l.targetParam == targetParam)
return -1;
@@ -185,6 +196,58 @@ int32_t Engine::addCvLinkFull(int32_t trackId, int32_t sourceKind, int32_t modId
return idx;
}
+// A link reaching into a rack (specs/044), for project load: as addCvLinkFull with the source
+// and / or target given as (device, chain index, slot); chain index -1 = track level.
+int32_t Engine::addNestedCvLink(int32_t trackId, int32_t sourceKind, int32_t modId, int32_t srcDev, int32_t srcChain,
+ int32_t srcSlot, int32_t srcParam, int32_t targetKind, int32_t targetTrack, int32_t targetDevice, int32_t tgtChain,
+ int32_t tgtSlot, int32_t targetParam) {
+ auto old = findTrackAuthoring(trackId);
+ if (!old) return -1;
+ const int32_t tgt = targetTrack < 0 ? trackId : targetTrack;
+ auto tgtTrack = findTrackAuthoring(tgt);
+ if (!tgtTrack) return -1;
+ const uint64_t su = srcChain >= 0 ? nestedChainUid(trackId, srcDev, srcChain) : 0;
+ const uint64_t tu = tgtChain >= 0 ? nestedChainUid(tgt, targetDevice, tgtChain) : 0;
+ if ((srcChain >= 0 && !su) || (tgtChain >= 0 && !tu)) return -1;
+ if (sourceKind == static_cast<int32_t>(CvSourceKind::Param) && !su
+ && (srcDev < 0 || srcDev >= static_cast<int32_t>(old->devices.size())))
+ return -1;
+ if (!targetValid(*tgtTrack, targetKind, targetDevice, targetParam, tu, tgtSlot)) return -1;
+ auto nt = cloneTrack(*old);
+ CvLink l;
+ l.sourceKind = sourceKind;
+ l.sourceModId = modId;
+ l.sourceDevice = srcDev;
+ l.sourceParam = srcParam;
+ l.sourceChainUid = su;
+ l.sourceSlot = su ? srcSlot : -1;
+ l.targetKind = targetKind;
+ l.targetTrack = tgt == trackId ? -1 : tgt;
+ l.targetDevice = targetDevice;
+ l.targetParam = targetParam;
+ l.targetChainUid = tu;
+ l.targetSlot = tu ? tgtSlot : -1;
+ float mn, mx;
+ l.base.store(targetGet(*tgtTrack, targetKind, targetDevice, targetParam, mn, mx, tu, tgtSlot), std::memory_order_relaxed);
+ nt->cvLinks.push_back(l);
+ const int32_t idx = static_cast<int32_t>(nt->cvLinks.size()) - 1;
+ republishWithTrack(trackId, nt);
+ return idx;
+}
+
+bool Engine::cvLinkPath(int32_t trackId, int32_t index, int32_t* srcChain, int32_t* srcSlot, int32_t* tgtChain,
+ int32_t* tgtSlot) const {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || index < 0 || index >= static_cast<int32_t>(t->cvLinks.size())) return false;
+ const CvLink& l = t->cvLinks[index];
+ const int32_t tgt = l.targetTrack < 0 ? trackId : l.targetTrack;
+ if (srcChain) *srcChain = l.sourceChainUid ? nestedChainIndex(trackId, l.sourceDevice, l.sourceChainUid) : -1;
+ if (srcSlot) *srcSlot = l.sourceChainUid ? l.sourceSlot : -1;
+ if (tgtChain) *tgtChain = l.targetChainUid ? nestedChainIndex(tgt, l.targetDevice, l.targetChainUid) : -1;
+ if (tgtSlot) *tgtSlot = l.targetChainUid ? l.targetSlot : -1;
+ return true;
+}
+
int32_t Engine::addCvLink(int32_t trackId, int32_t modId, int32_t device, int32_t param) {
return addCvLinkFull(trackId, 0, modId, -1, -1, 0, -1, device, param);
}
@@ -210,8 +273,9 @@ int32_t Engine::addCvLinkFromParamToTarget(int32_t trackId, int32_t srcDevice, i
void Engine::restoreLinkTarget(int32_t ownerTrack, const CvLink& l) {
const int32_t tgt = l.targetTrack < 0 ? ownerTrack : l.targetTrack;
if (auto tt = findTrackAuthoring(tgt))
- if (targetValid(*tt, l.targetKind, l.targetDevice, l.targetParam))
- targetSet(*tt, l.targetKind, l.targetDevice, l.targetParam, l.base.load(std::memory_order_relaxed));
+ if (targetValid(*tt, l.targetKind, l.targetDevice, l.targetParam, l.targetChainUid, l.targetSlot))
+ targetSet(*tt, l.targetKind, l.targetDevice, l.targetParam, l.base.load(std::memory_order_relaxed),
+ l.targetChainUid, l.targetSlot);
}
bool Engine::removeCvLink(int32_t trackId, int32_t index) {
@@ -305,7 +369,7 @@ bool Engine::paramModulated(int32_t targetKind, int32_t trackId, int32_t device,
const int32_t owner = op->id();
for (auto& l : op->cvLinks) {
const int32_t tgt = l.targetTrack < 0 ? owner : l.targetTrack;
- if (tgt == trackId && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param)
+ if (tgt == trackId && l.targetChainUid == 0 && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param)
return true;
}
}
@@ -320,7 +384,22 @@ void Engine::routeCvBaseEdit(int32_t targetKind, int32_t trackId, int32_t device
const int32_t owner = op->id();
for (auto& l : op->cvLinks) {
const int32_t tgt = l.targetTrack < 0 ? owner : l.targetTrack;
- if (tgt == trackId && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param)
+ if (tgt == trackId && l.targetChainUid == 0 && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param)
+ l.base.store(value, std::memory_order_relaxed);
+ }
+ }
+}
+
+void Engine::routeNestedCvBaseEdit(int32_t trackId, int32_t rack, int32_t chain, int32_t slot, int32_t param, float value) {
+ if (!authoring_) return;
+ const uint64_t uid = nestedChainUid(trackId, rack, chain);
+ if (!uid) return;
+ for (auto& op : authoring_->tracks) {
+ const int32_t owner = op->id();
+ for (auto& l : op->cvLinks) {
+ const int32_t tgt = l.targetTrack < 0 ? owner : l.targetTrack;
+ if (tgt == trackId && l.targetChainUid == uid && l.targetDevice == rack && l.targetSlot == slot
+ && l.targetParam == param)
l.base.store(value, std::memory_order_relaxed);
}
}
@@ -332,7 +411,7 @@ bool Engine::cvBaseValue(int32_t targetKind, int32_t trackId, int32_t device, in
const int32_t owner = op->id();
for (auto& l : op->cvLinks) {
const int32_t tgt = l.targetTrack < 0 ? owner : l.targetTrack;
- if (tgt == trackId && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param) {
+ if (tgt == trackId && l.targetChainUid == 0 && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param) {
out = l.base.load(std::memory_order_relaxed);
return true;
}
@@ -383,16 +462,24 @@ void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex,
bool drop = false;
// Target index fix-up (links into the edited chain of the edited track).
const int32_t tgt = l.targetTrack < 0 ? nt->id() : l.targetTrack;
- if (tgt == track && l.targetKind == chainKind) {
+ // A target inside a rack (specs/044) follows the rack: targetDevice is its address.
+ const bool nestedTgt = l.targetChainUid != 0;
+ const bool tgtOnChain = nestedTgt ? (midi ? isMidiHost(l.targetDevice) : l.targetDevice >= 0)
+ : l.targetKind == chainKind;
+ if (tgt == track && tgtOnChain) {
+ int32_t idx = nestedTgt && midi ? midiHostIndex(l.targetDevice) : l.targetDevice;
if (removedIndex >= 0) {
- if (l.targetDevice == removedIndex) drop = true;
- else if (l.targetDevice > removedIndex)
- l.targetDevice -= 1;
+ if (idx == removedIndex) drop = true;
+ else if (idx > removedIndex)
+ idx -= 1;
} else
- l.targetDevice = remappedMoveIndex(l.targetDevice, from, to);
+ idx = remappedMoveIndex(idx, from, to);
+ l.targetDevice = nestedTgt && midi ? midiHost(idx) : idx;
}
- // Source index fix-up (param source lives on the owner = edited track).
- if (!drop && !midi && ownerIsEdited && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param)) {
+ // Source index fix-up (param source lives on the owner = edited track; a nested source
+ // inside the Instrument Rack has no chain index to follow).
+ if (!drop && !midi && ownerIsEdited && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param)
+ && (l.sourceChainUid == 0 || l.sourceDevice >= 0)) {
if (removedIndex >= 0) {
if (l.sourceDevice == removedIndex) drop = true;
else if (l.sourceDevice > removedIndex)
@@ -420,8 +507,9 @@ void Engine::applyModulation(Graph* g, double beat, double timeSec) {
float mv;
if (link.sourceKind == static_cast<int32_t>(CvSourceKind::Param)) {
const int32_t sd = link.sourceDevice, sp = link.sourceParam;
- if (sd < 0 || sd >= static_cast<int32_t>(t.devices.size())) continue;
- Device* sdev = t.devices[sd].get();
+ Device* sdev = link.sourceChainUid != 0 ? resolveNested(t, sd, link.sourceChainUid, link.sourceSlot).device
+ : sd >= 0 && sd < static_cast<int32_t>(t.devices.size()) ? t.devices[sd].get()
+ : nullptr;
if (!sdev || sp < 0 || sp >= sdev->paramCount()) continue;
const float smn = sdev->paramMin(sp), smx = sdev->paramMax(sp), sspan = smx - smn;
mv = sspan > 1e-9f ? (sdev->getParam(sp) - smn) / sspan : 0.0f; // 0..1
@@ -447,13 +535,15 @@ void Engine::applyModulation(Graph* g, double beat, double timeSec) {
if (!tgt) continue;
}
const int32_t tk = link.targetKind, di = link.targetDevice, pi = link.targetParam;
- if (!targetValid(*tgt, tk, di, pi)) continue;
+ const uint64_t tu = link.targetChainUid;
+ const int32_t ts = link.targetSlot;
+ if (!targetValid(*tgt, tk, di, pi, tu, ts)) continue;
// Swing around the stored base (the target atomic holds the live modulated
// value continuously — no per-block restore — so the UI shows it smoothly).
const float base = link.base.load(std::memory_order_relaxed);
float mn, mx;
- targetGet(*tgt, tk, di, pi, mn, mx);
+ targetGet(*tgt, tk, di, pi, mn, mx, tu, ts);
const float span = mx - mn;
const float ld = link.depth.load(std::memory_order_relaxed);
float v;
@@ -466,7 +556,7 @@ void Engine::applyModulation(Graph* g, double beat, double timeSec) {
}
default: v = base + ld * mv * span; break; // Add
}
- targetSet(*tgt, tk, di, pi, std::clamp(v, mn, mx));
+ targetSet(*tgt, tk, di, pi, std::clamp(v, mn, mx), tu, ts);
}
}
}
diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cpp
index 3ecff627..9f57c13f 100644
--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp
@@ -14,6 +14,7 @@
#include "Engine.h"
#include "media/AudioFile.h"
#include "bridge/PluginHostBridge.h"
+#include "ParamPath.h"
#include "devices/racks/RackCore.h"
#include "devices/racks/RackInstrument.h"
#include "devices/racks/RackDevice.h"
@@ -247,73 +248,628 @@ bool Engine::rackKindAllowed(int32_t trackId, int32_t deviceIndex, int32_t kind)
return kind == 4 && deviceIndex == -1 && nestingHost(findTrackAuthoring(trackId)) != nullptr;
}
-// ---- wrap a device in a rack / unwrap it (#257) ----------------------------
-// Whether anything outside the device points at it by its chain index: automation lanes
-// CV links, or an Arp's CC target. Wrapping moves the device into a rack chain, where those can't follow it.
-bool Engine::deviceIsReferenced(const Track& t, int32_t deviceIndex) const {
- for (auto& l : t.automation)
- if ((l.target == AutomationTarget::DeviceParam || l.target == AutomationTarget::PluginParam) && l.deviceIndex == deviceIndex)
- return true;
- // An Arp's CC lane drives a device param by chain index (applyMidiCcRouting).
- for (auto& md : t.midiEffects)
- if (md && md->ccDestDevice() == deviceIndex) return true;
- for (auto& l : t.cvLinks)
- if (l.sourceKind == static_cast<int32_t>(CvSourceKind::Param) && l.sourceDevice == deviceIndex) return true;
- for (auto& ot : authoring_->tracks)
- for (auto& l : ot->cvLinks) {
- const int32_t tgt = l.targetTrack < 0 ? ot->id() : l.targetTrack;
- if (tgt == t.id() && l.targetKind == static_cast<int32_t>(CvTargetKind::Device) && l.targetDevice == deviceIndex)
- return true;
+// ---- group devices into a rack / ungroup it (#257, #328, specs/044) ----------
+namespace {
+
+// Group and Ungroup are each a function from old references to new ones (Engine::DeviceRef).
+using Ref = Engine::DeviceRef;
+using RefMap = Engine::DeviceRefMap;
+
+Ref hostRef(int32_t host, uint64_t uid, int32_t slot) {
+ if (isMidiHost(host)) return {1, midiHostIndex(host), uid, slot};
+ if (host < 0) return {2, -1, uid, slot};
+ return {0, host, uid, slot};
+}
+int32_t hostOf(const Ref& r) { return r.fam == 1 ? midiHost(r.idx) : r.fam == 2 ? -1 : r.idx; }
+
+Ref laneRef(const TrackLane& l) {
+ if (l.nested()) return hostRef(l.deviceIndex, l.chainUid, l.slot);
+ switch (l.target) {
+ case AutomationTarget::DeviceParam: return {0, l.deviceIndex};
+ case AutomationTarget::MidiDeviceParam: return {1, l.deviceIndex};
+ case AutomationTarget::PluginParam: return l.deviceIndex < 0 ? Ref{2, -1} : Ref{0, l.deviceIndex};
+ default: return {};
+ }
+}
+// The lane's target names the param surface of whatever it points at, and that surface is the
+// same before and after a move into or out of a rack, so only the address changes.
+void setLaneRef(TrackLane& l, const Ref& r) {
+ l.chainUid = r.uid;
+ l.slot = r.uid ? r.slot : -1;
+ l.deviceIndex = r.uid ? hostOf(r) : r.idx;
+}
+Ref cvTargetRef(const CvLink& l) {
+ if (l.targetChainUid) return hostRef(l.targetDevice, l.targetChainUid, l.targetSlot);
+ if (l.targetKind == static_cast<int32_t>(CvTargetKind::Instrument)) return {2, -1};
+ return {l.targetKind == static_cast<int32_t>(CvTargetKind::MidiFx) ? 1 : 0, l.targetDevice};
+}
+void setCvTargetRef(CvLink& l, const Ref& r) {
+ l.targetChainUid = r.uid;
+ l.targetSlot = r.uid ? r.slot : -1;
+ l.targetDevice = r.uid ? hostOf(r) : r.idx;
+}
+Ref cvSourceRef(const CvLink& l) {
+ if (l.sourceKind != static_cast<int32_t>(CvSourceKind::Param)) return {};
+ return l.sourceChainUid ? hostRef(l.sourceDevice, l.sourceChainUid, l.sourceSlot) : Ref{0, l.sourceDevice};
+}
+void setCvSourceRef(CvLink& l, const Ref& r) {
+ l.sourceChainUid = r.uid;
+ l.sourceSlot = r.uid ? r.slot : -1;
+ l.sourceDevice = r.uid ? hostOf(r) : r.idx;
+}
+Ref ccRef(const MidiDevice& m) {
+ if (m.ccDestChainUid()) return hostRef(m.ccDestDevice(), m.ccDestChainUid(), m.ccDestSlot());
+ return m.ccDestDevice() >= 0 ? Ref{0, m.ccDestDevice()} : Ref{};
+}
+bool sameRef(const Ref& a, const Ref& b) { return a.fam == b.fam && a.idx == b.idx && a.uid == b.uid && a.slot == b.slot; }
+
+// A map result that removes the reference (a lane or link on the ungrouped rack's own macros).
+constexpr int32_t kDropRef = -2;
+
+} // namespace
+
+// ---- Arp CC routes in the published snapshot (specs/044) ---------------------
+void Engine::syncCcRoutes(Graph& g) {
+ auto sync = [&](Track& t) {
+ if (!t.ccRoutesDirty) return; // published before: the audio thread may be reading it
+ t.ccRoutesDirty = false;
+ t.ccRoutes.reset();
+ auto add = [&](const MidiDevice& m) {
+ if (m.ccDestParam() < 0 || (m.ccDestDevice() < 0 && m.ccDestChainUid() == 0)) return;
+ if (!t.ccRoutes) t.ccRoutes = std::make_unique<std::vector<Track::CcRoute>>();
+ t.ccRoutes->push_back({&m, m.ccDestDevice(), m.ccDestChainUid(), m.ccDestSlot(), m.ccDestParam()});
+ };
+ for (auto& md : t.midiEffects) {
+ if (!md) continue;
+ add(*md);
+ if (auto* r = md->asRack()) r->forEachChildMidi([&](MidiDevice& c) { add(c); });
}
- return false;
+ if (auto* r = t.instrument ? t.instrument->asRack() : nullptr) r->forEachChildMidi([&](MidiDevice& c) { add(c); });
+ if (t.ccRoutes) ccRoutesUsed_ = true;
+ };
+ for (auto& t : g.tracks) sync(*t);
+ if (g.masterTrack) sync(*g.masterTrack);
}
-int32_t Engine::wrapDeviceInRack(int32_t trackId, int32_t deviceIndex) {
+void Engine::reapplyCcRoutes() {
+ if (!ccRoutesUsed_ || !authoring_) return;
+ // Every Arp of the restored snapshot takes its route, and one without a route loses its
+ // target (an ungroup that dropped it, then redo), or the next publish would revive it.
+ auto apply = [](const Track& t) {
+ auto one = [&](MidiDevice& m) {
+ const Track::CcRoute* rt = nullptr;
+ if (t.ccRoutes)
+ for (auto& e : *t.ccRoutes)
+ if (e.arp == &m) { rt = &e; break; }
+ if (!rt) {
+ if (m.ccDestDevice() >= 0 || m.ccDestChainUid() != 0) m.setCcDest(-1, -1);
+ return;
+ }
+ if (m.ccDestDevice() == rt->dev && m.ccDestChainUid() == rt->uid && m.ccDestSlot() == rt->slot
+ && m.ccDestParam() == rt->param)
+ return;
+ m.setCcDest(rt->dev, rt->param);
+ if (rt->uid) m.setCcDestNested(rt->uid, rt->slot);
+ };
+ for (auto& md : t.midiEffects) {
+ if (!md) continue;
+ one(*md);
+ if (auto* r = md->asRack()) r->forEachChildMidi(one);
+ }
+ if (auto* r = t.instrument ? t.instrument->asRack() : nullptr) r->forEachChildMidi(one);
+ };
+ for (auto& t : authoring_->tracks) apply(*t);
+ if (authoring_->masterTrack) apply(*authoring_->masterTrack);
+}
+
+// Every Arp inside the track's racks (a MIDI Effect Rack, the Instrument Rack's chains).
+void Engine::rewriteRackArps(Track& nt, const DeviceRefMap& map, const RackCore* fresh) {
+ auto walk = [&](const RackCore& r) {
+ if (&r == fresh) return; // its Arps were rewritten on the way in
+ r.forEachChildMidi([&](MidiDevice& m) { rewriteArpRef(m, map); });
+ };
+ for (auto& md : nt.midiEffects)
+ if (auto* r = md ? md->asRack() : nullptr) walk(*r);
+ if (auto* r = nt.instrument ? nt.instrument->asRack() : nullptr) walk(*r);
+}
+
+// Retargets the Arp's authoring copy in place: a clone would start with no held notes or pending
+// note-offs and interrupt a sustained pattern. The audio thread keeps playing the route of the
+// snapshot it renders; the new one goes live with the published track (syncCcRoutes), and undo /
+// redo copy a restored snapshot's routes back (reapplyCcRoutes).
+void Engine::rewriteArpRef(MidiDevice& m, const DeviceRefMap& map) {
+ const Ref r = ccRef(m);
+ if (r.fam < 0) return;
+ const Ref n = map(r);
+ if (sameRef(r, n)) return;
+ if (n.fam == kDropRef) m.setCcDest(-1, -1);
+ else {
+ m.setCcDest(n.uid ? hostOf(n) : n.idx, m.ccDestParam());
+ if (n.uid) m.setCcDestNested(n.uid, n.slot);
+ }
+}
+
+// Rewrite every reference into `trackId` through `map` and publish the result as one undo
+// step: lanes and CV sources of `nt` (the track's new state), CV targets on any track
+// pointing at it, and the CC targets of the Arps on the track (in place, see rewriteArpRef).
+void Engine::publishWithRefMap(int32_t trackId, std::shared_ptr<Track> nt, const DeviceRefMap& map, const RackCore* fresh) {
+ // Lanes.
+ std::vector<int32_t> laneMap(nt->automation.size());
+ std::vector<TrackLane> kept;
+ kept.reserve(nt->automation.size());
+ for (size_t i = 0; i < nt->automation.size(); ++i) {
+ TrackLane& l = nt->automation[i];
+ const Ref r = laneRef(l);
+ if (r.fam >= 0) {
+ const Ref n = map(r);
+ if (n.fam == kDropRef) {
+ laneMap[i] = -1;
+ continue;
+ }
+ setLaneRef(l, n);
+ }
+ laneMap[i] = static_cast<int32_t>(kept.size());
+ kept.push_back(std::move(l));
+ }
+ nt->automation = std::move(kept);
+ auto laneGone = [&](int32_t& li) {
+ if (li < 0 || li >= static_cast<int32_t>(laneMap.size())) return true;
+ li = laneMap[li];
+ return li < 0;
+ };
+ std::erase_if(activeWrites_, [&](ActiveWrite& aw) { return aw.trackId == trackId && laneGone(aw.laneIndex); });
+ std::erase_if(overrides_, [&](OverrideTarget& o) { return o.trackId == trackId && laneGone(o.laneIndex); });
+ for (auto& m : nt->midiEffects)
+ if (m) rewriteArpRef(*m, map);
+ rewriteRackArps(*nt, map, fresh);
+ // CV links, on this track and on any track whose links target it.
+ auto rewriteLinks = [&](Track& t, bool own) {
+ std::vector<CvLink> keep;
+ keep.reserve(t.cvLinks.size());
+ for (auto& l : t.cvLinks) {
+ const int32_t tgt = l.targetTrack < 0 ? t.id() : l.targetTrack;
+ if (tgt == trackId) {
+ const Ref n = map(cvTargetRef(l));
+ if (n.fam == kDropRef) continue;
+ setCvTargetRef(l, n);
+ }
+ if (own) {
+ const Ref r = cvSourceRef(l);
+ if (r.fam >= 0) {
+ const Ref n = map(r);
+ if (n.fam == kDropRef) continue;
+ setCvSourceRef(l, n);
+ }
+ }
+ keep.push_back(l);
+ }
+ t.cvLinks = std::move(keep);
+ };
+ rewriteLinks(*nt, true);
+ auto g = std::make_shared<Graph>();
+ inheritGraphLevel(*g, *authoring_);
+ if (trackId == kMasterTrackId) g->masterTrack = nt;
+ g->tracks.reserve(authoring_->tracks.size());
+ for (auto& t : authoring_->tracks) {
+ if (t->id() == trackId) {
+ g->tracks.push_back(nt);
+ continue;
+ }
+ bool targets = false;
+ for (auto& l : t->cvLinks) targets |= l.targetTrack == trackId;
+ if (!targets) {
+ g->tracks.push_back(t);
+ continue;
+ }
+ auto ot = cloneTrack(*t);
+ rewriteLinks(*ot, false);
+ g->tracks.push_back(ot);
+ }
+ publish(std::move(g));
+}
+
+int32_t Engine::groupDevices(int32_t trackId, int32_t midiFirst, int32_t midiCount, bool withInstrument,
+ int32_t fxFirst, int32_t fxCount) {
auto old = findTrackAuthoring(trackId);
- if (!old || deviceIndex < 0 || deviceIndex >= static_cast<int32_t>(old->devices.size())) return -1;
- auto dev = old->devices[deviceIndex];
- if (!dev || dev->sidechainSourceTrackId() > 0 || deviceIsReferenced(*old, deviceIndex)) return -1;
+ if (!old) return -2;
+ const int32_t nMidi = static_cast<int32_t>(old->midiEffects.size());
+ const int32_t nFx = static_cast<int32_t>(old->devices.size());
+ midiCount = std::max(0, midiCount);
+ fxCount = std::max(0, fxCount);
+ if (midiCount + fxCount == 0 && !withInstrument) return -2;
+ if (midiCount && (midiFirst < 0 || midiFirst + midiCount > nMidi)) return -2;
+ if (fxCount && (fxFirst < 0 || fxFirst + fxCount > nFx)) return -2;
+ if ((midiCount || withInstrument) && (old->type() != TrackType::Instrument || !old->instrument)) return -7;
+ if (withInstrument) {
+ if (midiCount && midiFirst + midiCount != nMidi) return -3; // the MIDI run must reach the instrument
+ if (fxCount && fxFirst != 0) return -3; // the audio run must start at it
+ } else if (midiCount && fxCount)
+ return -3; // MIDI and audio effects share a rack only with the instrument between them
+ for (int32_t i = 0; i < fxCount; ++i) {
+ auto& d = old->devices[fxFirst + i];
+ if (!d) return -2;
+ if (dynamic_cast<const RackCore*>(d.get())) return -4;
+ }
+ for (int32_t i = 0; i < midiCount; ++i) {
+ auto& m = old->midiEffects[midiFirst + i];
+ if (!m) return -2;
+ if (dynamic_cast<const RackCore*>(m.get())) return -4;
+ if (m->midiKind() < 0 || m->midiKind() > 5) return -5; // chains take the built-in MIDI effects
+ }
+ if (withInstrument) {
+ auto* ri = dynamic_cast<const RackInstrument*>(old->instrument.get());
+ if (ri && !dynamic_cast<const DrumRack*>(ri)) return -6; // an Instrument Rack never nests
+ }
+
const double sr = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;
- auto rack = std::make_shared<RackDevice>();
- rack->setSampleRate(sr, kMaxBlock);
- const int32_t chain = rack->addChain(-1);
- // The device itself moves in, already prepared at this rate: preparing it again would reset
- // it (a Reverb clears its tail) while the published graph may still be playing it.
- if (rack->addChainDeviceInstance(chain, dev, /*prepare=*/false) < 0) return -1;
auto nt = cloneTrack(*old);
- nt->devices[deviceIndex] = rack;
- republishWithTrack(trackId, nt);
+ uint64_t uid = 0;
+ const RackCore* freshRack = nullptr; // its Arps are rewritten on the way in
+ int32_t result = 0;
+ RefMap map;
+ if (withInstrument) {
+ // Instrument Rack: chain 0 = MIDI tail → instrument → audio head; the track keeps the rest.
+ auto rack = std::make_shared<RackInstrument>();
+ freshRack = rack.get();
+ rack->setSampleRate(sr);
+ const int32_t c = rack->chainCount() > 0 ? 0 : rack->addChain(-1); // a MIDI Effect Rack starts with one
+ uid = rack->chainBaseUid(c);
+ const int32_t m0 = midiFirst, f0 = fxCount;
+ map = [=](const Ref& r) -> Ref {
+ if (r.uid) return r.fam == 0 && r.idx >= f0 ? Ref{0, r.idx - f0, r.uid, r.slot} : r;
+ if (r.fam == 2) return {2, -1, uid, -1};
+ if (r.fam == 1 && midiCount && r.idx >= m0) return {2, -1, uid, RackCore::midiTarget(r.idx - m0)};
+ if (r.fam == 0) return r.idx < f0 ? Ref{2, -1, uid, r.idx} : Ref{0, r.idx - f0};
+ return r;
+ };
+ for (int32_t i = 0; i < midiCount; ++i) {
+ auto& m = nt->midiEffects[midiFirst + i];
+ if (m) rewriteArpRef(*m, map); // an Arp going in keeps driving its (maybe moved) target
+ rack->addChainMidiDeviceInstance(c, m);
+ }
+ rack->replaceChainInstrument(c, nt->instrument, /*prepare=*/false); // no chain name: it shows the instrument's
+ for (int32_t i = 0; i < fxCount; ++i) rack->addChainDeviceInstance(c, nt->devices[i], /*prepare=*/false);
+ if (midiCount > 0) // midiFirst is -1 with no MIDI effects: begin() - 1 isn't an iterator
+ nt->midiEffects.erase(nt->midiEffects.begin() + midiFirst, nt->midiEffects.begin() + midiFirst + midiCount);
+ nt->devices.erase(nt->devices.begin(), nt->devices.begin() + fxCount);
+ if (old->instrument) old->instrument->closeEditor();
+ nt->instrument = rack;
+ result = -1;
+ } else if (midiCount) {
+ auto rack = std::make_shared<MidiRack>();
+ freshRack = rack.get();
+ rack->setSampleRate(sr, kMaxBlock);
+ const int32_t c = rack->chainCount() > 0 ? 0 : rack->addChain(-1); // a MIDI Effect Rack starts with one
+ uid = rack->chainBaseUid(c);
+ const int32_t a = midiFirst, n = midiCount;
+ map = [=](const Ref& r) -> Ref {
+ if (r.fam != 1) return r;
+ if (!r.uid && r.idx >= a && r.idx < a + n) return {1, a, uid, RackCore::midiTarget(r.idx - a)};
+ return r.idx >= a + n ? Ref{1, r.idx - n + 1, r.uid, r.slot} : r;
+ };
+ for (int32_t i = 0; i < n; ++i) {
+ auto& m = nt->midiEffects[a + i];
+ if (m) rewriteArpRef(*m, map);
+ rack->addChainMidiDeviceInstance(c, m);
+ }
+ rack->setChainName(c, nt->midiEffects[a]->displayName()); // named after its first device (FR-015)
+ nt->midiEffects.erase(nt->midiEffects.begin() + a, nt->midiEffects.begin() + a + n);
+ nt->midiEffects.insert(nt->midiEffects.begin() + a, rack);
+ result = kMidiRackBase - a;
+ } else {
+ auto rack = std::make_shared<RackDevice>();
+ freshRack = rack.get();
+ rack->setSampleRate(sr, kMaxBlock);
+ const int32_t c = rack->chainCount() > 0 ? 0 : rack->addChain(-1); // a MIDI Effect Rack starts with one
+ uid = rack->chainBaseUid(c);
+ const int32_t a = fxFirst, n = fxCount;
+ map = [=](const Ref& r) -> Ref {
+ if (r.fam != 0) return r;
+ if (!r.uid && r.idx >= a && r.idx < a + n) return {0, a, uid, r.idx - a};
+ return r.idx >= a + n ? Ref{0, r.idx - n + 1, r.uid, r.slot} : r;
+ };
+ // The devices move in already prepared at this rate: preparing them again would reset
+ // them (a Reverb clears its tail) while the published graph may still be playing them.
+ for (int32_t i = 0; i < n; ++i) rack->addChainDeviceInstance(c, nt->devices[a + i], /*prepare=*/false);
+ rack->setChainName(c, nt->devices[a]->displayName()); // named after its first device (FR-015)
+ nt->devices.erase(nt->devices.begin() + a, nt->devices.begin() + a + n);
+ nt->devices.insert(nt->devices.begin() + a, rack);
+ result = a;
+ }
+ publishWithRefMap(trackId, nt, map, freshRack);
recomputePdc();
- return deviceIndex;
+ return result;
}
-int32_t Engine::unwrapRack(int32_t trackId, int32_t deviceIndex) {
+int32_t Engine::ungroupRack(int32_t trackId, int32_t family, int32_t index, int32_t* outDropped) {
+ if (outDropped) *outDropped = 0;
auto old = findTrackAuthoring(trackId);
- if (!old || deviceIndex < 0 || deviceIndex >= static_cast<int32_t>(old->devices.size())) return -1;
- auto* rack = dynamic_cast<RackDevice*>(old->devices[deviceIndex].get());
+ if (!old) return -2;
+ RackCore* rack = nullptr;
+ if (family == 0 && index >= 0 && index < static_cast<int32_t>(old->devices.size()))
+ rack = dynamic_cast<RackDevice*>(old->devices[index].get());
+ else if (family == 1 && index >= 0 && index < static_cast<int32_t>(old->midiEffects.size()))
+ rack = dynamic_cast<MidiRack*>(old->midiEffects[index].get());
+ else if (family == 2 && old->instrument) {
+ if (dynamic_cast<DrumRack*>(old->instrument.get())) return -4;
+ rack = dynamic_cast<RackInstrument*>(old->instrument.get());
+ }
RackCore::RackState* st = rack ? rack->live() : nullptr;
- if (!st || st->chains.size() != 1 || deviceIsReferenced(*old, deviceIndex)) return -1;
- auto devs = st->chains[0].devices;
- // The devices after the rack shift by (n - 1). Lanes and CV links are remapped below; an
- // Arp's CC target lives on the shared MIDI device, outside the undo snapshot, so rather
- // than move it, don't unwrap under one.
- if (devs.size() != 1)
- for (auto& md : old->midiEffects)
- if (md && md->ccDestDevice() > deviceIndex) return -1;
+ if (!st) return -2;
+ if (st->chains.size() != 1) return -3;
+ const RackCore::RackChain& ch = st->chains[0];
+ if (family == 2 && !ch.instrument) return -5;
+ int32_t dropped = st->mappings.empty() ? 0 : 1;
+ {
+ const auto& k = *ch.ctl;
+ constexpr auto rl = std::memory_order_relaxed;
+ const bool mixDefault = std::fabs(k.gain.load(rl) - 1.0f) < 1e-6f && std::fabs(k.pan.load(rl)) < 1e-6f
+ && !k.mute.load(rl) && !k.solo.load(rl) && k.keyLo.load(rl) == 0 && k.keyHi.load(rl) == 127
+ && k.velLo.load(rl) == 0 && k.velHi.load(rl) == 127 && k.transpose.load(rl) == 0
+ && std::fabs(k.velScale.load(rl) - 1.0f) < 1e-6f && k.selLo.load(rl) == 0 && k.selHi.load(rl) == 127;
+ if (!mixDefault) dropped |= 2;
+ }
+ const uint64_t uid = ch.uid;
+ auto devs = ch.devices;
+ auto mids = ch.midiDevices;
+ auto inst = ch.instrument;
+
auto nt = cloneTrack(*old);
- nt->devices.erase(nt->devices.begin() + deviceIndex);
- nt->devices.insert(nt->devices.begin() + deviceIndex, devs.begin(), devs.end());
- // The devices after the rack shift by (n - 1): their lanes and CV links follow.
- const int32_t n = static_cast<int32_t>(devs.size());
- if (n == 0) remapAutomationAfterDeviceChange(*nt, false, deviceIndex, -1, -1);
- for (int32_t i = 1; i < n; ++i)
- remapAutomationAfterDeviceChange(*nt, false, -1, static_cast<int32_t>(nt->devices.size()) - n + i, deviceIndex + i);
- republishWithTrack(trackId, nt);
- if (n == 0) remapCvLinksAfterDeviceChange(trackId, deviceIndex, -1, -1);
- for (int32_t i = 1; i < n; ++i)
- remapCvLinksAfterDeviceChange(trackId, -1, static_cast<int32_t>(nt->devices.size()) - n + i, deviceIndex + i);
+ RefMap map;
+ int32_t restored = 0;
+ if (family == 0) {
+ const int32_t a = index, n = static_cast<int32_t>(devs.size());
+ map = [=](const Ref& r) -> Ref {
+ if (r.fam != 0) return r;
+ if (r.idx == a) return r.uid == uid && r.slot >= 0 ? Ref{0, a + r.slot} : Ref{kDropRef}; // its macros go
+ return r.idx > a ? Ref{0, r.idx + n - 1, r.uid, r.slot} : r;
+ };
+ nt->devices.erase(nt->devices.begin() + a);
+ nt->devices.insert(nt->devices.begin() + a, devs.begin(), devs.end());
+ restored = n;
+ } else if (family == 1) {
+ const int32_t a = index, n = static_cast<int32_t>(mids.size());
+ map = [=](const Ref& r) -> Ref {
+ if (r.fam != 1) return r;
+ if (r.idx == a)
+ return r.uid == uid && RackCore::isMidiTarget(r.slot) ? Ref{1, a + RackCore::midiTargetIndex(r.slot)}
+ : Ref{kDropRef};
+ return r.idx > a ? Ref{1, r.idx + n - 1, r.uid, r.slot} : r;
+ };
+ nt->midiEffects.erase(nt->midiEffects.begin() + a);
+ nt->midiEffects.insert(nt->midiEffects.begin() + a, mids.begin(), mids.end());
+ restored = n;
+ } else {
+ const int32_t m0 = static_cast<int32_t>(nt->midiEffects.size()), nA = static_cast<int32_t>(devs.size());
+ map = [=](const Ref& r) -> Ref {
+ if (r.fam == 2) {
+ if (r.uid != uid) return Ref{kDropRef}; // the rack's own macros
+ if (r.slot == -1) return {2, -1};
+ if (RackCore::isMidiTarget(r.slot)) return {1, m0 + RackCore::midiTargetIndex(r.slot)};
+ return {0, r.slot};
+ }
+ if (r.fam == 0) return {0, r.idx + nA, r.uid, r.slot};
+ return r;
+ };
+ nt->midiEffects.insert(nt->midiEffects.end(), mids.begin(), mids.end());
+ nt->devices.insert(nt->devices.begin(), devs.begin(), devs.end());
+ old->instrument->closeEditor();
+ nt->instrument = inst;
+ restored = static_cast<int32_t>(mids.size()) + 1 + nA;
+ }
+ publishWithRefMap(trackId, nt, map); // the MIDI effects taken out are among nt's now
recomputePdc();
- return n;
+ if (outDropped) *outDropped = dropped;
+ return restored;
+}
+
+int32_t Engine::wrapDeviceInRack(int32_t trackId, int32_t deviceIndex) {
+ const int32_t r = groupDevices(trackId, -1, 0, false, deviceIndex, 1);
+ return r < 0 ? -1 : r;
+}
+
+int32_t Engine::unwrapRack(int32_t trackId, int32_t deviceIndex) {
+ const int32_t r = ungroupRack(trackId, 0, deviceIndex, nullptr);
+ return r < 0 ? -1 : r;
+}
+
+// ---- chain children's links, for save / load (specs/044) --------------------
+bool Engine::rackChainMidiCcDest(int32_t t, int32_t host, int32_t chain, int32_t idx, int32_t* dev,
+ int32_t* destChain, int32_t* destSlot, int32_t* param, float* depth) const {
+ auto* r = rackCoreAt(t, host);
+ MidiDevice* m = r && !isNestedRack(host) ? r->chainMidiDeviceAt(chain, idx) : nullptr;
+ if (!m) return false;
+ const uint64_t uid = m->ccDestChainUid();
+ if (dev) *dev = m->ccDestDevice();
+ if (destChain) *destChain = uid ? nestedChainIndex(t, m->ccDestDevice(), uid) : -1;
+ if (destSlot) *destSlot = uid ? m->ccDestSlot() : -1;
+ if (param) *param = m->ccDestParam();
+ if (depth) *depth = m->ccDepth();
+ return true;
+}
+bool Engine::rackChainMidiSetCcDest(int32_t t, int32_t host, int32_t chain, int32_t idx, int32_t dev,
+ int32_t destChain, int32_t destSlot, int32_t param, float depth) {
+ auto* r = rackCoreAt(t, host);
+ MidiDevice* m = r && !isNestedRack(host) ? r->chainMidiDeviceAt(chain, idx) : nullptr;
+ if (!m) return false;
+ m->setCcDest(dev, param);
+ if (destChain >= 0) {
+ const uint64_t uid = nestedChainUid(t, dev, destChain);
+ if (!uid) return false;
+ m->setCcDestNested(uid, destSlot);
+ }
+ m->setCcDepth(depth);
+ republishCcRoutes(t);
+ return true;
+}
+bool Engine::rackChainSidechain(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t* src,
+ int32_t* tapPre, float* gainDb, float* mix) const {
+ auto* r = rackCoreAt(t, host);
+ if (!r || isNestedRack(host)) return false;
+ if (slot >= 0) {
+ Device* d = r->chainDeviceAt(chain, slot);
+ if (!d) return false;
+ if (src) *src = d->sidechainSourceTrackId();
+ if (tapPre) *tapPre = d->sidechainTapPre();
+ if (gainDb) *gainDb = d->sidechainGainDb();
+ if (mix) *mix = d->sidechainMix();
+ return true;
+ }
+ Instrument* in = r->chainInstrument(chain);
+ if (!in) return false;
+ if (src) *src = in->sidechainSourceTrackId();
+ if (tapPre) *tapPre = 0;
+ if (gainDb) *gainDb = 0.0f;
+ if (mix) *mix = 1.0f;
+ return true;
+}
+bool Engine::rackChainSetSidechain(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t src,
+ int32_t tapPre, float gainDb, float mix) {
+ auto* r = rackCoreAt(t, host);
+ if (!r || isNestedRack(host)) return false;
+ if (slot >= 0) {
+ Device* d = r->chainDeviceAt(chain, slot);
+ if (!d) return false;
+ d->setSidechainSourceTrackId(src);
+ d->setSidechainTapPre(tapPre);
+ d->setSidechainGainDb(gainDb);
+ d->setSidechainMix(mix);
+ } else {
+ Instrument* in = r->chainInstrument(chain);
+ if (!in) return false;
+ in->setSidechainSourceTrackId(src);
+ }
+ recomputeRouting();
+ return true;
+}
+
+// ---- nested addresses follow rack edits (specs/044) -----------------------
+void Engine::remapNestedAfterRackEdit(int32_t trackId, int32_t host, const NestedMap& map) {
+ if (!authoring_ || isNestedRack(host)) return; // paths reach one rack level only
+ auto into = [&](uint64_t uid, int32_t dev) { return uid != 0 && dev == host; };
+ auto g = std::make_shared<Graph>();
+ inheritGraphLevel(*g, *authoring_);
+ g->tracks.reserve(authoring_->tracks.size());
+ bool any = false;
+ for (auto& ot : authoring_->tracks) {
+ const bool own = ot->id() == trackId;
+ auto cvTouches = [&](const CvLink& l) {
+ const int32_t tgt = l.targetTrack < 0 ? ot->id() : l.targetTrack;
+ return (tgt == trackId && into(l.targetChainUid, l.targetDevice))
+ || (own && into(l.sourceChainUid, l.sourceDevice));
+ };
+ bool needs = own; // the edited track: its lanes, Arps (also inside racks) and links
+ for (auto& l : ot->cvLinks) needs |= cvTouches(l);
+ if (!needs) {
+ g->tracks.push_back(ot);
+ continue;
+ }
+ auto nt = cloneTrack(*ot);
+ if (own) {
+ // Lanes: rewrite or drop, keeping in-flight gestures on the right lane index.
+ std::vector<int32_t> laneMap(nt->automation.size());
+ std::vector<TrackLane> kept;
+ kept.reserve(nt->automation.size());
+ for (size_t i = 0; i < nt->automation.size(); ++i) {
+ TrackLane& l = nt->automation[i];
+ if (into(l.chainUid, l.deviceIndex)) {
+ const auto [u, sl] = map(l.chainUid, l.slot);
+ if (u == 0) {
+ laneMap[i] = -1;
+ continue;
+ }
+ l.chainUid = u;
+ l.slot = sl;
+ }
+ laneMap[i] = static_cast<int32_t>(kept.size());
+ kept.push_back(std::move(l));
+ }
+ nt->automation = std::move(kept);
+ auto laneGone = [&](int32_t& li) {
+ if (li < 0 || li >= static_cast<int32_t>(laneMap.size())) return true;
+ li = laneMap[li];
+ return li < 0;
+ };
+ std::erase_if(activeWrites_, [&](ActiveWrite& aw) { return aw.trackId == trackId && laneGone(aw.laneIndex); });
+ std::erase_if(overrides_, [&](OverrideTarget& o) { return o.trackId == trackId && laneGone(o.laneIndex); });
+ // The Arps' CC targets, on the track and inside its racks (an Instrument Rack chain
+ // often holds both the Arp and its target); the routes go live with nt.
+ const DeviceRefMap refMap = [&](const DeviceRef& r) -> DeviceRef {
+ if (!r.uid || hostOf(r) != host) return r;
+ const auto [u, sl] = map(r.uid, r.slot);
+ return u == 0 ? DeviceRef{kDropRef} : DeviceRef{r.fam, r.idx, u, sl};
+ };
+ for (auto& m : nt->midiEffects)
+ if (m) rewriteArpRef(*m, refMap);
+ rewriteRackArps(*nt, refMap);
+ }
+ std::vector<CvLink> keptLinks;
+ keptLinks.reserve(nt->cvLinks.size());
+ for (auto& l : nt->cvLinks) {
+ const int32_t tgt = l.targetTrack < 0 ? nt->id() : l.targetTrack;
+ if (tgt == trackId && into(l.targetChainUid, l.targetDevice)) {
+ const auto [u, sl] = map(l.targetChainUid, l.targetSlot);
+ if (u == 0) continue;
+ l.targetChainUid = u;
+ l.targetSlot = sl;
+ }
+ if (own && into(l.sourceChainUid, l.sourceDevice)) {
+ const auto [u, sl] = map(l.sourceChainUid, l.sourceSlot);
+ if (u == 0) continue;
+ l.sourceChainUid = u;
+ l.sourceSlot = sl;
+ }
+ keptLinks.push_back(l);
+ }
+ nt->cvLinks = std::move(keptLinks);
+ any = true;
+ g->tracks.push_back(nt);
+ }
+ if (any) publishRaw(std::move(g)); // no extra undo step: part of the rack edit
+}
+
+// Slot maps for the common chain edits: a child removed at `idx`, moved within its chain,
+// or a new one inserted at `at` (MIDI slots use RackCore::midiTarget encoding).
+static Engine::NestedMap slotRemoved(uint64_t uid, int32_t idx, bool midi) {
+ return [=](uint64_t u, int32_t sl) -> std::pair<uint64_t, int32_t> {
+ if (u != uid || (midi ? !RackCore::isMidiTarget(sl) : sl < 0)) return {u, sl};
+ const int32_t i = midi ? RackCore::midiTargetIndex(sl) : sl;
+ if (i == idx) return {0, -1};
+ const int32_t ni = i > idx ? i - 1 : i;
+ return {u, midi ? RackCore::midiTarget(ni) : ni};
+ };
+}
+static Engine::NestedMap slotInserted(uint64_t uid, int32_t at, bool midi) {
+ return [=](uint64_t u, int32_t sl) -> std::pair<uint64_t, int32_t> {
+ if (u != uid || (midi ? !RackCore::isMidiTarget(sl) : sl < 0)) return {u, sl};
+ const int32_t i = midi ? RackCore::midiTargetIndex(sl) : sl;
+ const int32_t ni = i >= at ? i + 1 : i;
+ return {u, midi ? RackCore::midiTarget(ni) : ni};
+ };
+}
+static Engine::NestedMap slotMoved(uint64_t uid, int32_t from, int32_t to, bool midi) {
+ return [=](uint64_t u, int32_t sl) -> std::pair<uint64_t, int32_t> {
+ if (u != uid || (midi ? !RackCore::isMidiTarget(sl) : sl < 0)) return {u, sl};
+ int32_t i = midi ? RackCore::midiTargetIndex(sl) : sl;
+ if (i == from) i = to;
+ else if (from < to && i > from && i <= to) --i;
+ else if (from > to && i >= to && i < from) ++i;
+ return {u, midi ? RackCore::midiTarget(i) : i};
+ };
+}
+static Engine::NestedMap slotToChain(uint64_t uid, int32_t idx, uint64_t toUid, int32_t toIdx, bool midi) {
+ auto removed = slotRemoved(uid, idx, midi);
+ return [=](uint64_t u, int32_t sl) -> std::pair<uint64_t, int32_t> {
+ if (u == uid && sl == (midi ? RackCore::midiTarget(idx) : idx))
+ return {toUid, midi ? RackCore::midiTarget(toIdx) : toIdx};
+ return removed(u, sl);
+ };
+}
+static Engine::NestedMap chainDropped(uint64_t uid, bool instrumentOnly) {
+ return [=](uint64_t u, int32_t sl) -> std::pair<uint64_t, int32_t> {
+ if (u == uid && (!instrumentOnly || sl == -1)) return {0, -1};
+ return {u, sl};
+ };
}
// ---- chains --------------------------------------------------------------
@@ -359,6 +915,7 @@ bool Engine::rackChainDeviceCopy(int32_t t, int32_t di, int32_t c, int32_t i) {
clipDevice_ = std::move(copy);
clipMidi_.reset();
clipInstrument_.reset();
+ clipMany_.clear();
return true;
}
bool Engine::rackChainMidiCopy(int32_t t, int32_t di, int32_t c, int32_t i) {
@@ -369,6 +926,7 @@ bool Engine::rackChainMidiCopy(int32_t t, int32_t di, int32_t c, int32_t i) {
clipMidi_ = std::move(copy);
clipDevice_.reset();
clipInstrument_.reset();
+ clipMany_.clear();
return true;
}
int32_t Engine::rackChainDevicePaste(int32_t t, int32_t di, int32_t c, int32_t at) {
@@ -379,8 +937,10 @@ int32_t Engine::rackChainDevicePaste(int32_t t, int32_t di, int32_t c, int32_t a
if (dynamic_cast<const RackDevice*>(clipDevice_.get())) return -3;
auto dev = cloneDevice(*clipDevice_);
if (!dev) return -1;
- dev->setSidechainSourceTrackId(-1); // a chain has no sidechain input
+ dev->setSidechainSourceTrackId(-1); // a pasted device starts without a key
+ const uint64_t uid = r->chainBaseUid(c);
const int32_t idx = rackForEdit(t, di)->insertChainDeviceInstance(c, std::move(dev), at);
+ if (idx >= 0) remapNestedAfterRackEdit(t, di, slotInserted(uid, idx, false));
recomputePdc();
return idx;
}
@@ -393,14 +953,79 @@ int32_t Engine::rackChainMidiPaste(int32_t t, int32_t di, int32_t c, int32_t at)
if (di == -1 && c >= RackInstrument::kMaxMidiChains) return -5;
auto dev = cloneMidiDevice(*clipMidi_);
if (!dev) return -1;
- return rackForEdit(t, di)->insertChainMidiDeviceInstance(c, std::move(dev), at);
+ const uint64_t uid = r->chainBaseUid(c);
+ const int32_t idx = rackForEdit(t, di)->insertChainMidiDeviceInstance(c, std::move(dev), at);
+ if (idx >= 0) remapNestedAfterRackEdit(t, di, slotInserted(uid, idx, true));
+ return idx;
+}
+int32_t Engine::rackChainPasteDevices(int32_t t, int32_t di, int32_t c, int32_t midiAt, int32_t fxAt,
+ int32_t* outSkipped, int32_t* outFirstMidi, int32_t* outFirstFx) {
+ if (outSkipped) *outSkipped = 0;
+ if (outFirstMidi) *outFirstMidi = -1;
+ if (outFirstFx) *outFirstFx = -1;
+ auto* r = rackCoreAt(t, di);
+ if (!r || c < 0 || c >= r->chainCount()) return -1;
+ std::vector<ClipEntry> src = clipMany_;
+ if (src.empty()) {
+ if (clipMidi_) src.push_back({clipMidi_, nullptr, nullptr});
+ else if (clipInstrument_) src.push_back({nullptr, clipInstrument_, nullptr});
+ else if (clipDevice_) src.push_back({nullptr, nullptr, clipDevice_});
+ }
+ if (src.empty()) return -1;
+ const bool takesMidi = rackTakesMidi(r) && !(di == -1 && c >= RackInstrument::kMaxMidiChains);
+ const bool takesAudio = rackTakesAudio(r);
+ // Clone what fits first: a plug-in that won't load leaves the chain as it was.
+ std::vector<std::shared_ptr<MidiDevice>> mids;
+ std::vector<std::shared_ptr<Device>> devs;
+ int32_t skipped = 0;
+ for (auto& e : src) {
+ if (e.midi && takesMidi && e.midi->midiKind() >= 0 && e.midi->midiKind() <= 5) {
+ auto m = cloneMidiDevice(*e.midi);
+ if (!m) return -3;
+ m->setCcDest(-1, -1);
+ mids.push_back(std::move(m));
+ } else if (e.dev && takesAudio && !e.dev->asRack()) {
+ auto d = cloneDevice(*e.dev);
+ if (!d) return -3;
+ d->setSidechainSourceTrackId(-1); // a pasted device starts without a key
+ devs.push_back(std::move(d));
+ } else
+ ++skipped;
+ }
+ if (outSkipped) *outSkipped = skipped;
+ if (mids.empty() && devs.empty()) return 0;
+ const uint64_t uid = r->chainBaseUid(c);
+ RackCore* fr = rackForEdit(t, di); // one fork: one undo step for the whole paste
+ if (!fr) return -1;
+ int32_t ma = midiAt < 0 || midiAt > fr->chainMidiDeviceCount(c) ? fr->chainMidiDeviceCount(c) : midiAt;
+ int32_t fa = fxAt < 0 || fxAt > fr->chainDeviceCount(c) ? fr->chainDeviceCount(c) : fxAt;
+ // Every insert lands in the fork first: a remap republishes the track (and may fork a rack
+ // holding an Arp), after which `fr` is no longer the rack in the graph.
+ std::vector<std::pair<int32_t, bool>> inserted;
+ for (size_t i = 0; i < mids.size(); ++i) {
+ const int32_t idx = fr->insertChainMidiDeviceInstance(c, std::move(mids[i]), ma + static_cast<int32_t>(i));
+ if (idx < 0) continue;
+ if (outFirstMidi && *outFirstMidi < 0) *outFirstMidi = idx;
+ inserted.push_back({idx, true});
+ }
+ for (size_t i = 0; i < devs.size(); ++i) {
+ const int32_t idx = fr->insertChainDeviceInstance(c, std::move(devs[i]), fa + static_cast<int32_t>(i));
+ if (idx < 0) continue;
+ if (outFirstFx && *outFirstFx < 0) *outFirstFx = idx;
+ inserted.push_back({idx, false});
+ }
+ for (auto [idx, midi] : inserted) remapNestedAfterRackEdit(t, di, slotInserted(uid, idx, midi));
+ recomputePdc();
+ return static_cast<int32_t>(mids.size() + devs.size());
}
int32_t Engine::rackChainDeviceDuplicate(int32_t t, int32_t di, int32_t c, int32_t i) {
auto* r = rackCoreAt(t, di);
Device* src = r ? r->chainDeviceAt(c, i) : nullptr;
auto dev = src ? cloneDevice(*src) : nullptr;
if (!dev) return -1;
+ const uint64_t uid = r->chainBaseUid(c);
const int32_t idx = rackForEdit(t, di)->insertChainDeviceInstance(c, std::move(dev), i + 1);
+ if (idx >= 0) remapNestedAfterRackEdit(t, di, slotInserted(uid, idx, false));
recomputePdc();
return idx;
}
@@ -409,12 +1034,17 @@ int32_t Engine::rackChainMidiDuplicate(int32_t t, int32_t di, int32_t c, int32_t
MidiDevice* src = r ? r->chainMidiDeviceAt(c, i) : nullptr;
auto dev = src ? cloneMidiDevice(*src) : nullptr;
if (!dev) return -1;
- return rackForEdit(t, di)->insertChainMidiDeviceInstance(c, std::move(dev), i + 1);
+ const uint64_t uid = r->chainBaseUid(c);
+ const int32_t idx = rackForEdit(t, di)->insertChainMidiDeviceInstance(c, std::move(dev), i + 1);
+ if (idx >= 0) remapNestedAfterRackEdit(t, di, slotInserted(uid, idx, true));
+ return idx;
}
int32_t Engine::rackChainDeviceMoveTo(int32_t t, int32_t di, int32_t c, int32_t i, int32_t to) {
auto* r = rackCoreAt(t, di);
if (!r || !r->chainDeviceAt(c, i) || to < 0 || to >= r->chainCount() || to == c) return -1;
+ const uint64_t uid = r->chainBaseUid(c), toUid = r->chainBaseUid(to);
const int32_t idx = rackForEdit(t, di)->moveChainDeviceToChain(c, i, to);
+ if (idx >= 0) remapNestedAfterRackEdit(t, di, slotToChain(uid, i, toUid, idx, false));
recomputePdc();
return idx;
}
@@ -422,7 +1052,10 @@ int32_t Engine::rackChainMidiMoveTo(int32_t t, int32_t di, int32_t c, int32_t i,
auto* r = rackCoreAt(t, di);
if (!r || !r->chainMidiDeviceAt(c, i) || to < 0 || to >= r->chainCount() || to == c) return -1;
if (di == -1 && to >= RackInstrument::kMaxMidiChains) return -5;
- return rackForEdit(t, di)->moveChainMidiDeviceToChain(c, i, to);
+ const uint64_t uid = r->chainBaseUid(c), toUid = r->chainBaseUid(to);
+ const int32_t idx = rackForEdit(t, di)->moveChainMidiDeviceToChain(c, i, to);
+ if (idx >= 0) remapNestedAfterRackEdit(t, di, slotToChain(uid, i, toUid, idx, true));
+ return idx;
}
bool Engine::rackMono(int32_t t) const {
auto* r = rackCoreAt(t, -1);
@@ -445,14 +1078,18 @@ int32_t Engine::rackAddChain(int32_t t, int32_t di, int32_t k) {
bool Engine::rackRemoveChain(int32_t t, int32_t di, int32_t c) {
auto* r = rackCoreAt(t, di);
if (!r || c < 0 || c >= r->chainCount()) return false;
+ const uint64_t uid = r->chainBaseUid(c);
const bool ok = rackForEdit(t, di)->removeChain(c);
+ if (ok) remapNestedAfterRackEdit(t, di, chainDropped(uid, false));
recomputePdc(); // the chain may have held the rack's longest latency
return ok;
}
bool Engine::rackSetChainInstrument(int32_t t, int32_t di, int32_t c, int32_t k) {
auto* r = rackCoreAt(t, di);
if (!r || c < 0 || c >= r->chainCount() || !rackKindAllowed(t, di, k) || !RackCore::makeInstrument(k)) return false;
+ const uint64_t uid = r->chainBaseUid(c);
const bool ok = rackForEdit(t, di)->setChainInstrument(c, k);
+ if (ok) remapNestedAfterRackEdit(t, di, chainDropped(uid, /*instrumentOnly=*/true));
recomputePdc();
return ok;
}
@@ -488,7 +1125,9 @@ float Engine::rackChainInstrumentParamGet(int32_t t, int32_t di, int32_t c, int3
void Engine::rackChainInstrumentParamSet(int32_t t, int32_t di, int32_t c, int32_t p, float v) {
auto* r = rackCoreAt(t, di);
Instrument* inst = r ? r->chainInstrument(c) : nullptr;
- if (inst) inst->pluginParamSet(p, v);
+ if (!inst) return;
+ inst->pluginParamSet(p, v);
+ routeNestedCvBaseEdit(t, di, c, -1, p, v); // a grouped, CV-linked instrument (specs/044)
}
float Engine::rackChainInstrumentParamDefault(int32_t t, int32_t di, int32_t c, int32_t p) const {
auto* r = rackCoreAt(t, di);
@@ -647,13 +1286,20 @@ int32_t Engine::rackAddChainDevice(int32_t t, int32_t di, int32_t c, int32_t k)
bool Engine::rackRemoveChainDevice(int32_t t, int32_t di, int32_t c, int32_t d) {
auto* r = rackCoreAt(t, di);
if (!r || d < 0 || d >= r->chainDeviceCount(c)) return false;
- return rackForEdit(t, di)->removeChainDevice(c, d);
+ const uint64_t uid = r->chainBaseUid(c);
+ const bool ok = rackForEdit(t, di)->removeChainDevice(c, d);
+ if (ok) remapNestedAfterRackEdit(t, di, slotRemoved(uid, d, false));
+ return ok;
}
bool Engine::rackMoveChainDevice(int32_t t, int32_t di, int32_t c, int32_t from, int32_t to) {
auto* r = rackCoreAt(t, di);
if (!r || from < 0 || from >= r->chainDeviceCount(c)) return false;
- if (std::clamp(to, 0, r->chainDeviceCount(c) - 1) == from) return true;
- return rackForEdit(t, di)->moveChainDevice(c, from, to);
+ to = std::clamp(to, 0, r->chainDeviceCount(c) - 1);
+ if (to == from) return true;
+ const uint64_t uid = r->chainBaseUid(c);
+ const bool ok = rackForEdit(t, di)->moveChainDevice(c, from, to);
+ if (ok) remapNestedAfterRackEdit(t, di, slotMoved(uid, from, to, false));
+ return ok;
}
const char* Engine::rackChainDeviceName(int32_t t, int32_t di, int32_t c, int32_t d) const {
auto* r = rackCoreAt(t, di);
@@ -705,12 +1351,20 @@ int32_t Engine::rackAddChainMidi(int32_t t, int32_t di, int32_t c, int32_t kind)
bool Engine::rackRemoveChainMidi(int32_t t, int32_t di, int32_t c, int32_t i) {
auto* r = rackCoreAt(t, di);
if (!r || i < 0 || i >= r->chainMidiDeviceCount(c)) return false;
- return rackForEdit(t, di)->removeChainMidiDevice(c, i);
+ const uint64_t uid = r->chainBaseUid(c);
+ const bool ok = rackForEdit(t, di)->removeChainMidiDevice(c, i);
+ if (ok) remapNestedAfterRackEdit(t, di, slotRemoved(uid, i, true));
+ return ok;
}
bool Engine::rackMoveChainMidi(int32_t t, int32_t di, int32_t c, int32_t from, int32_t to) {
auto* r = rackCoreAt(t, di);
if (!r || from < 0 || from >= r->chainMidiDeviceCount(c)) return false;
- return rackForEdit(t, di)->moveChainMidiDevice(c, from, to);
+ to = std::clamp(to, 0, r->chainMidiDeviceCount(c) - 1);
+ if (to == from) return true;
+ const uint64_t uid = r->chainBaseUid(c);
+ const bool ok = rackForEdit(t, di)->moveChainMidiDevice(c, from, to);
+ if (ok) remapNestedAfterRackEdit(t, di, slotMoved(uid, from, to, true));
+ return ok;
}
MidiDevice* Engine::rackChainMidiAt(int32_t t, int32_t di, int32_t c, int32_t i) const {
auto* r = rackCoreAt(t, di);
@@ -761,7 +1415,15 @@ void Engine::rackSetThru(int32_t t, int32_t di, bool on) {
void Engine::rackChainDeviceParamSet(int32_t t, int32_t di, int32_t c, int32_t d, int32_t p, float v) {
auto* r = rackCoreAt(t, di);
Device* dev = r ? r->chainDeviceAt(c, d) : nullptr;
- if (dev) dev->setParam(p, v);
+ if (!dev) return;
+ dev->setParam(p, v);
+ routeNestedCvBaseEdit(t, di, c, d, p, v); // a grouped, CV-linked device (specs/044)
+}
+void Engine::rackChainMidiParamSet(int32_t t, int32_t di, int32_t c, int32_t i, int32_t p, float v) {
+ MidiDevice* m = rackChainMidiAt(t, di, c, i);
+ if (!m) return;
+ m->setParam(p, v);
+ routeNestedCvBaseEdit(t, di, c, RackCore::midiTarget(i), p, v);
}
void Engine::rackSetChainDeviceBypassed(int32_t t, int32_t di, int32_t c, int32_t d, bool b) {
auto* r = rackCoreAt(t, di);
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index 2daefb15..4714b9a8 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -7,6 +7,9 @@
#include "dsp/core/ScopedNoDenormals.h"
#include "dsp/math/SimdAudio.h"
#include "devices/racks/DrumRack.h"
+#include "ParamResolve.h"
+#include "devices/racks/RackDevice.h"
+#include "devices/racks/RackInstrument.h"
#include "bridge/PluginHostBridge.h"
#include "media/WarpStream.h"
@@ -310,17 +313,36 @@ int Engine::applyMidiEffects(
// Map/CC routing: a MIDI effect (the arpeggiator) drives a target audio-device param
// on the same track from its per-step CC lane. Runs each block after the MIDI chain,
// before the device chain processes, so the modulation applies this block.
+// An Arp grouped into a rack (a MIDI Effect Rack or an Instrument Rack chain) keeps driving
+// its target, and a target grouped into a rack is reached through its nested address
+// (specs/044); both walks read published snapshots only.
+// The route comes from the published snapshot (Track::ccRoutes), never from the Arp's own fields:
+// a group or rack edit retargets those before the new device order is published.
+static void applyCcRoute(Track& t, const MidiDevice& md) {
+ const Track::CcRoute* rt = nullptr;
+ for (auto& r : *t.ccRoutes)
+ if (r.arp == &md) { rt = &r; break; }
+ if (!rt) return;
+ const int di = rt->dev, pi = rt->param;
+ if (pi < 0) return;
+ Device* d = nullptr;
+ if (rt->uid) d = resolveNested(t, di, rt->uid, rt->slot).device;
+ else if (di >= 0 && di < static_cast<int>(t.devices.size())) d = t.devices[di].get();
+ if (!d || pi >= d->paramCount()) return;
+ const float mn = d->paramMin(pi), mx = d->paramMax(pi);
+ const float mod = std::clamp(md.ccValue() * md.ccDepth(), 0.0f, 1.0f);
+ d->setParam(pi, mn + (mx - mn) * mod);
+}
+
void Engine::applyMidiCcRouting(Track& t) {
+ if (!t.ccRoutes) return;
for (auto& md : t.midiEffects) {
if (!md) continue;
- const int di = md->ccDestDevice(), pi = md->ccDestParam();
- if (di < 0 || pi < 0 || di >= static_cast<int>(t.devices.size())) continue;
- auto* d = t.devices[di].get();
- if (!d) continue;
- const float mn = d->paramMin(pi), mx = d->paramMax(pi);
- const float mod = std::clamp(md->ccValue() * md->ccDepth(), 0.0f, 1.0f);
- d->setParam(pi, mn + (mx - mn) * mod);
+ applyCcRoute(t, *md);
+ if (auto* r = md->asRack()) r->forEachChildMidi([&](MidiDevice& c) { applyCcRoute(t, c); });
}
+ if (auto* r = t.instrument ? t.instrument->asRack() : nullptr)
+ r->forEachChildMidi([&](MidiDevice& c) { applyCcRoute(t, c); });
}
void Engine::poll() {
@@ -1226,7 +1248,8 @@ int Engine::computeInstrumentMidi(Track& t, MidiEv* evs, int32_t frames, double
n = applyMidiEffects(t, evs, n, scratch, frames, spb > 0.0 ? blockStart / spb : 0.0, spb, playing);
applyMidiCcRouting(t);
std::sort(evs, evs + n, midiEvLess);
- }
+ } else if (t.instrument && t.instrument->asRack())
+ applyMidiCcRouting(t); // Arps grouped into the Instrument Rack's chains (specs/044)
t.updateMidiCv(evs, n); // MIDI→CV modulators read the post-FX note stream
return n;
}
@@ -1437,7 +1460,8 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double s
n = applyMidiEffects(t, evs, n, scratch, frames, p, spb, true);
applyMidiCcRouting(t);
std::sort(evs, evs + n, midiEvLess);
- }
+ } else if (t.instrument && t.instrument->asRack())
+ applyMidiCcRouting(t); // Arps grouped into the Instrument Rack's chains (specs/044)
// The monitored live expression, after the offset-0 notes (as in renderInstrumentRaw).
playEvents(*inst, dst, frames, evs, n, xev, xn, p, spb, true, [&] { // the slot's own loop clock
@@ -1908,6 +1932,8 @@ void Engine::renderLeafDry(Track& t, float* dst, const LeafWork& w, Graph* g, in
const int32_t s = routeSlotForTrack(iSc);
t.instrument->setSidechain(s < 0 ? nullptr : routeBus_[s].data(), frames);
}
+ // Keyed devices and instruments inside an Instrument Rack's chains (specs/044).
+ if (auto* r = t.instrument->asRack()) feedRackChildKeys(g, *r, t.id(), frames);
}
renderInstrumentRaw(g, t, dst, frames, blockStart, spb, playing);
break;
@@ -1916,6 +1942,33 @@ void Engine::renderLeafDry(Track& t, float* dst, const LeafWork& w, Graph* g, in
}
}
+// Hand a device its sidechain key for this block (the source track's previous-block
+// signal, pre- or post-FX tap) or its MIDI key; a rack passes keys on to its chain
+// children, each with its own source (specs/044). Audio thread.
+void Engine::feedDeviceKey(Graph* g, Device& d, int32_t ownTrackId, int32_t frames) {
+ const int32_t src = d.sidechainSourceTrackId();
+ if (src >= 0) {
+ const int32_t s = routeSlotForTrack(src);
+ const float* sc = s < 0 ? nullptr : (d.sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());
+ d.setSidechain(sc, frames);
+ if (d.wantsMidiKey()) feedMidiKey(g, d, src);
+ } else if (d.wantsOwnMidiKey())
+ feedMidiKey(g, d, ownTrackId); // no key track: this track's notes
+ if (auto* r = d.asRack()) feedRackChildKeys(g, *r, ownTrackId, frames);
+}
+
+void Engine::feedRackChildKeys(Graph* g, const RackCore& r, int32_t ownTrackId, int32_t frames) {
+ r.forEachChildDevice([&](Device& c) {
+ if (!c.bypassed() && !c.asRack()) feedDeviceKey(g, c, ownTrackId, frames);
+ });
+ r.forEachChildInstrument([&](Instrument& i) {
+ const int32_t src = i.sidechainSourceTrackId();
+ if (src < 0) return;
+ const int32_t s = routeSlotForTrack(src);
+ i.setSidechain(s < 0 ? nullptr : routeBus_[s].data(), frames);
+ });
+}
+
// Step 2/2b for Pass 1: insert effect chain (M3) + PDC, in place. Verbatim
// moved from the old inline loop (sidechain taps read the previous block,
// tempo sync, hosted-plugin sync, frozen tracks skip baked-in devices).
@@ -1928,15 +1981,7 @@ void Engine::processLeafDevices(Track& t, float* buf, const LeafWork& w, Graph*
if (!w.frozenActive)
for (auto& d : t.devices)
if (d && !d->bypassed()) {
- const int32_t src = d->sidechainSourceTrackId();
- if (src >= 0) {
- const int32_t s = routeSlotForTrack(src);
- const float* sc =
- s < 0 ? nullptr : (d->sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());
- d->setSidechain(sc, frames);
- if (d->wantsMidiKey()) feedMidiKey(g, *d, src);
- } else if (d->wantsOwnMidiKey())
- feedMidiKey(g, *d, t.id()); // no key track: this track's notes
+ feedDeviceKey(g, *d, t.id(), frames);
if (spb > 0.0) d->setTransport(blockStart / spb, spb, playing); // tempo-synced devices
d->setTransportInfo(ti); // hosted-plugin sync
d->process(buf, frames);
@@ -2425,15 +2470,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
for (auto& d : t.devices)
if (d && !d->bypassed()) {
- const int32_t src = d->sidechainSourceTrackId();
- if (src >= 0) {
- const int32_t s = routeSlotForTrack(src);
- const float* sc =
- s < 0 ? nullptr : (d->sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());
- d->setSidechain(sc, frames);
- if (d->wantsMidiKey()) feedMidiKey(g, *d, src);
- } else if (d->wantsOwnMidiKey())
- feedMidiKey(g, *d, t.id()); // no key track: this track's notes
+ feedDeviceKey(g, *d, t.id(), frames);
if (spb > 0.0) d->setTransport(blockStart / spb, spb, playing);
d->setTransportInfo(ti);
d->process(scratch_.data(), frames);
@@ -2498,15 +2535,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
for (auto& d : t.devices)
if (d && !d->bypassed()) {
- const int32_t src = d->sidechainSourceTrackId();
- if (src >= 0) {
- const int32_t s = routeSlotForTrack(src);
- const float* sc =
- s < 0 ? nullptr : (d->sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());
- d->setSidechain(sc, frames);
- if (d->wantsMidiKey()) feedMidiKey(g, *d, src);
- } else if (d->wantsOwnMidiKey())
- feedMidiKey(g, *d, t.id()); // no key track: this track's notes
+ feedDeviceKey(g, *d, t.id(), frames);
if (spb > 0.0) d->setTransport(blockStart / spb, spb, playing);
d->setTransportInfo(ti); // hosted-plugin sync
d->process(scratch_.data(), frames);
diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
index 9e6e5a05..f2441b46 100644
--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
@@ -1603,7 +1603,7 @@ bool Engine::moveClipBlock(const std::vector<ClipMoveReq>& moves) {
AudioClip ac;
double oldStart, len, newStart;
bool sameTrack, layoutMatch;
- std::vector<AutomationLane> snips;
+ std::vector<TrackLane> snips;
};
std::vector<Item> items;
items.reserve(moves.size());
@@ -2492,15 +2492,17 @@ int32_t Engine::duplicateClip(int32_t trackId, int32_t clipIndex) {
// Pull the points of every automation lane that fall in [start,end] out into a
// per-lane snippet, with beats rebased to be relative to `start`. Empty lanes are
// dropped so paste only touches targets the clip actually carried.
-std::vector<AutomationLane> Engine::captureClipAutomation(const Track& t, double start, double end) const {
+std::vector<TrackLane> Engine::captureClipAutomation(const Track& t, double start, double end) const {
constexpr double eps = 1e-6;
- std::vector<AutomationLane> out;
+ std::vector<TrackLane> out;
for (const auto& lane : t.automation) {
- AutomationLane snip;
+ TrackLane snip;
snip.target = lane.target;
snip.deviceIndex = lane.deviceIndex;
snip.paramIndex = lane.paramIndex;
snip.paramId = lane.paramId;
+ snip.chainUid = lane.chainUid; // a lane into a rack (specs/044)
+ snip.slot = lane.slot;
for (const auto& p : lane.points)
if (p.beat >= start - eps && p.beat <= end + eps) {
AutomationPoint q = p;
@@ -2539,15 +2541,15 @@ bool Engine::tracksDeviceLayoutMatch(const Track& a, const Track& b) {
// the pasted envelope replaces (not overlaps) whatever was there. Device/plugin/MIDI
// lanes only apply when sameTrack — their indices are positional, so a cross-track
// paste would otherwise bind them to the wrong device.
-void Engine::applyClipAutomation(Track& nt, int32_t trackId, const std::vector<AutomationLane>& snips,
+void Engine::applyClipAutomation(Track& nt, int32_t trackId, const std::vector<TrackLane>& snips,
double placedStart, double len, bool sameTrack) const {
const double s = placedStart, e = placedStart + len;
for (const auto& snip : snips) {
if (!sameTrack && snip.target != AutomationTarget::Volume && snip.target != AutomationTarget::Pan) continue;
// Find the matching lane on nt, or create one bound to the same target.
- AutomationLane* lane = nullptr;
+ TrackLane* lane = nullptr;
for (auto& l : nt.automation) {
- if (l.target != snip.target) continue;
+ if (l.target != snip.target || l.chainUid != snip.chainUid || l.slot != snip.slot) continue;
bool match = true;
switch (snip.target) {
case AutomationTarget::DeviceParam:
@@ -2565,11 +2567,13 @@ void Engine::applyClipAutomation(Track& nt, int32_t trackId, const std::vector<A
}
}
if (!lane) {
- AutomationLane nl;
+ TrackLane nl;
nl.target = snip.target;
nl.deviceIndex = snip.deviceIndex;
nl.paramId = snip.paramId;
- nl.paramIndex = snip.target == AutomationTarget::PluginParam
+ nl.chainUid = snip.chainUid;
+ nl.slot = snip.slot;
+ nl.paramIndex = snip.target == AutomationTarget::PluginParam && !snip.nested()
? pluginParamIndexOfId(trackId, snip.deviceIndex, snip.paramId)
: snip.paramIndex;
nt.automation.push_back(std::move(nl));
diff --git a/src/native/nota.engine/src/engine/Modulation.cpp b/src/native/nota.engine/src/engine/Modulation.cpp
index f668acea..d7435181 100644
--- a/src/native/nota.engine/src/engine/Modulation.cpp
+++ b/src/native/nota.engine/src/engine/Modulation.cpp
@@ -179,6 +179,10 @@ CvLink& CvLink::operator=(const CvLink& o) {
targetTrack = o.targetTrack;
targetDevice = o.targetDevice;
targetParam = o.targetParam;
+ sourceChainUid = o.sourceChainUid;
+ sourceSlot = o.sourceSlot;
+ targetChainUid = o.targetChainUid;
+ targetSlot = o.targetSlot;
depth.store(o.depth.load(std::memory_order_relaxed), std::memory_order_relaxed);
mode.store(o.mode.load(std::memory_order_relaxed), std::memory_order_relaxed);
base.store(o.base.load(std::memory_order_relaxed), std::memory_order_relaxed);
diff --git a/src/native/nota.engine/src/engine/Modulation.h b/src/native/nota.engine/src/engine/Modulation.h
index 73b1faaf..4df826eb 100644
--- a/src/native/nota.engine/src/engine/Modulation.h
+++ b/src/native/nota.engine/src/engine/Modulation.h
@@ -120,6 +120,13 @@ struct CvLink {
int32_t targetTrack = -1; // target track id (-1 = the owner track)
int32_t targetDevice = -1; // insert-effect / MIDI-FX index on the target track
int32_t targetParam = -1;
+ // A source or target grouped into a rack (specs/044): sourceDevice / targetDevice is then
+ // the rack's address on its track (ParamPath host) and these name the chain child; the
+ // kinds keep naming the child's param surface. 0 = track level as before.
+ uint64_t sourceChainUid = 0;
+ int32_t sourceSlot = -1;
+ uint64_t targetChainUid = 0;
+ int32_t targetSlot = -1;
std::atomic<float> depth{1.0f}; // -1..1
std::atomic<int32_t> mode{0}; // CvMode
// The target param's *base* value (the centre the modulation swings around). The
diff --git a/src/native/nota.engine/src/engine/ParamPath.h b/src/native/nota.engine/src/engine/ParamPath.h
new file mode 100644
index 00000000..e3c999f3
--- /dev/null
+++ b/src/native/nota.engine/src/engine/ParamPath.h
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// ParamPath — where a parameter's owner sits once devices can be grouped into a rack
+// (specs/044). Automation lanes, CV links and Arp CC routes used to name a device by its
+// index in the track's chain; a device grouped into a rack lives one level down, in a
+// chain of the rack at that index. The nested part is the chain's uid (stable while
+// chains move, duplicate or swap instruments) and a slot in it. Racks nest one level
+// (specs/041), so one step is all a path needs.
+
+#pragma once
+
+#include <cstdint>
+
+namespace nota {
+
+// A track-level device in the engine's rack addressing: >= 0 an audio effect, -1 the
+// instrument, kMidiHostBase - i the track's i-th MIDI effect (Engine::kMidiRackBase).
+constexpr int32_t kMidiHostBase = -1000;
+inline bool isMidiHost(int32_t host) { return host <= kMidiHostBase; }
+inline int32_t midiHost(int32_t midiIndex) { return kMidiHostBase - midiIndex; }
+inline int32_t midiHostIndex(int32_t host) { return kMidiHostBase - host; }
+
+struct ParamPath {
+ int32_t host = -1; // the track-level device (see above)
+ uint64_t chainUid = 0; // 0 = the host itself; else a chain of the rack at host
+ int32_t slot = -1; // in that chain: >= 0 a device, -1 the instrument,
+ // RackCore::midiTarget(i) its i-th MIDI effect
+ bool nested() const { return chainUid != 0; }
+ bool operator==(const ParamPath&) const = default;
+};
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/ParamResolve.h b/src/native/nota.engine/src/engine/ParamResolve.h
new file mode 100644
index 00000000..404c3694
--- /dev/null
+++ b/src/native/nota.engine/src/engine/ParamResolve.h
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Finding the owner of a nested parameter (specs/044) on a track snapshot: the rack at a
+// ParamPath host, then its chain child. Used by automation, CV links, Arp CC routes and
+// the sidechain feed. Reads the published graph and the rack's live snapshot only and
+// allocates nothing, so the audio thread may call it (AR-6).
+
+#pragma once
+
+#include "engine/ParamPath.h"
+#include "engine/Track.h"
+#include "devices/racks/MidiRack.h"
+#include "devices/racks/RackDevice.h"
+#include "devices/racks/RackInstrument.h"
+
+namespace nota {
+
+// The rack at a track-level host (null when the host isn't a rack).
+inline const RackCore* rackAtHost(const Track& t, int32_t host) {
+ if (isMidiHost(host)) {
+ const int32_t mi = midiHostIndex(host);
+ if (mi < 0 || mi >= static_cast<int32_t>(t.midiEffects.size()) || !t.midiEffects[mi]) return nullptr;
+ return t.midiEffects[mi]->asRack();
+ }
+ if (host == -1) return t.instrument ? t.instrument->asRack() : nullptr;
+ if (host < 0 || host >= static_cast<int32_t>(t.devices.size()) || !t.devices[host]) return nullptr;
+ return t.devices[host]->asRack();
+}
+
+// The child a nested path names; exactly one pointer is set, or none when the rack, the
+// chain or the slot is gone.
+struct ParamOwner {
+ Device* device = nullptr;
+ MidiDevice* midi = nullptr;
+ Instrument* instrument = nullptr;
+};
+inline ParamOwner resolveNested(const Track& t, int32_t host, uint64_t chainUid, int32_t slot) {
+ ParamOwner o;
+ const RackCore* r = rackAtHost(t, host);
+ if (!r) return o;
+ if (slot >= 0) o.device = r->childDevice(chainUid, slot);
+ else if (RackCore::isMidiTarget(slot)) o.midi = r->childMidi(chainUid, slot);
+ else if (slot == -1) o.instrument = r->childInstrument(chainUid);
+ return o;
+}
+inline ParamOwner resolveNested(const Track& t, const ParamPath& p) {
+ return resolveNested(t, p.host, p.chainUid, p.slot);
+}
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Track.h b/src/native/nota.engine/src/engine/Track.h
index a2063958..0afda1dc 100644
--- a/src/native/nota.engine/src/engine/Track.h
+++ b/src/native/nota.engine/src/engine/Track.h
@@ -249,12 +249,29 @@ class Track {
std::vector<AudioClip> clips; // audio tracks
std::vector<MidiClip> midiClips; // instrument tracks
std::vector<SessionSlot> sessionSlots; // Session view, one per scene (M5)
- std::vector<AutomationLane> automation; // parameter automation lanes (M9)
+ std::vector<TrackLane> automation; // parameter automation lanes (M9)
// CV modulation (Phase 3, Modular editor). Sources + edges to device params.
// Config lives in atomics (live-tweakable); add/remove is structural (clone).
std::vector<Modulator> modulators;
std::vector<CvLink> cvLinks;
+ // Where each Arp on this track (top level or in a rack chain) sends its CC lane, as published
+ // with this snapshot: the audio thread reads the route from here, so a new device order and
+ // the targets that fit it go live together (an Arp is shared by every snapshot and keeps
+ // its own fields only as the authoring copy). Filled from the Arps when a fresh track object
+ // is published (ccRoutesDirty), never on a published one; undo / redo copy a restored
+ // snapshot's routes back onto its Arps. specs/044.
+ struct CcRoute {
+ const MidiDevice* arp = nullptr;
+ int32_t dev = -2;
+ uint64_t uid = 0;
+ int32_t slot = -1;
+ int32_t param = -1;
+ };
+ // Out of line and only when some Arp has a target: every edit clones a track, and a bigger
+ // track made small edits measurably costlier (the edit-path gate).
+ std::unique_ptr<std::vector<CcRoute>> ccRoutes;
+ bool ccRoutesDirty = true;
int32_t nextModId = 1; // monotonic modulator-id source
// UI metadata (message thread only; never read by the audio thread). `name` is the
diff --git a/tests/Nota.SmokeTest/DeviceCopyTests.cs b/tests/Nota.SmokeTest/DeviceCopyTests.cs
index 007a5717..d238c1e7 100644
--- a/tests/Nota.SmokeTest/DeviceCopyTests.cs
+++ b/tests/Nota.SmokeTest/DeviceCopyTests.cs
@@ -9,7 +9,8 @@
// - Drum Rack / Instrument Rack edits (a sample dropped on a pad, pad note + name, chains,
// chain devices, zones) are undoable, and a pad drop grouped as one gesture is one step.
// - ⌘G wraps a device in an Audio Effect Rack and ⌘⇧G takes it out again (#257), keeping the
-// device's settings and the chain order, one undo step each.
+// device's settings and the chain order, one undo step each; its key and an Arp's CC target
+// follow it in and out (specs/044).
// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --device-copy`.
using Nota.Application;
@@ -60,34 +61,33 @@ internal static class DeviceCopyTests
$"wrap in rack: ⌘⇧G puts the chain's devices back in order ({Chain(e, t)})");
yield return (e.Undo() && Chain(e, t) == "0,5,2", "wrap in rack: undo brings the rack back");
- // A keyed device stays out: a rack chain has no sidechain input.
+ // A keyed device goes in with its key (specs/044: rack chains feed their children's keys).
int src = e.AddAudioTrack();
int keyed = e.AddBuiltinDevice(t, 1);
e.SetDeviceSidechainSource(t, keyed, src);
- yield return (e.WrapDeviceInRack(t, keyed) < 0 && Chain(e, t) == "0,5,2,1", $"wrap in rack: a device with a sidechain key isn't wrapped ({Chain(e, t)})");
+ int kr = e.WrapDeviceInRack(t, keyed);
+ yield return (kr == keyed && Chain(e, t) == "0,5,2,5" && e.RackChainSidechain(t, kr, 0, 0) is { SourceTrack: var ks } && ks == src,
+ $"wrap in rack: a keyed device goes in with its key ({Chain(e, t)})");
// A rack with two chains isn't unwrapped (which chain would win?).
e.RackDevAddChain(t, r, -1);
- yield return (e.UnwrapRack(t, r) < 0 && Chain(e, t) == "0,5,2,1", $"wrap in rack: a rack with two chains isn't unwrapped ({Chain(e, t)})");
+ yield return (e.UnwrapRack(t, r) < 0 && Chain(e, t) == "0,5,2,5", $"wrap in rack: a rack with two chains isn't unwrapped ({Chain(e, t)})");
- // A device an Arp's CC lane drives stays out: the Arp addresses it by chain index.
+ // A device an Arp's CC lane drives goes in, and the Arp follows it into the chain.
int it = e.AddInstrumentTrack();
e.SetTrackBuiltinInstrument(it, 0);
int arp = e.AddMidiEffect(it, Arp);
e.AddBuiltinDevice(it, 0);
int target = e.AddBuiltinDevice(it, 1);
e.SetMidiEffectCcDest(it, arp, target, 0);
- yield return (e.WrapDeviceInRack(it, target) < 0 && Chain(e, it) == "0,1", $"wrap in rack: a device an Arp's CC targets isn't wrapped ({Chain(e, it)})");
- e.SetMidiEffectCcDest(it, arp, -1, -1);
- yield return (e.WrapDeviceInRack(it, target) == target, "wrap in rack: it wraps once the Arp lets go");
- // Unwrapping a rack the Arp drives, or one whose devices would shift the Arp's target, is refused.
- e.SetMidiEffectCcDest(it, arp, target, 0);
- yield return (e.UnwrapRack(it, target) < 0 && Chain(e, it) == "0,5", "wrap in rack: a rack an Arp's CC lane drives isn't unwrapped");
+ yield return (e.WrapDeviceInRack(it, target) == target && Chain(e, it) == "0,5" && e.MidiEffectCcDestDevice(it, arp) == target
+ && e.MidiEffectCcDestPath(it, arp) == (0, 0),
+ $"wrap in rack: a device an Arp's CC targets goes in, the Arp's target with it ({Chain(e, it)})");
+ // Unwrapping a rack whose devices shift the Arp's target moves the target along.
int after = e.AddBuiltinDevice(it, 3);
e.RackDevAddChainDevice(it, target, 0, 3);
e.SetMidiEffectCcDest(it, arp, after, 0);
- yield return (e.UnwrapRack(it, target) < 0 && Chain(e, it) == "0,5,3", "wrap in rack: an unwrap that would shift the Arp's target is refused");
- e.SetMidiEffectCcDest(it, arp, -1, -1);
- yield return (e.UnwrapRack(it, target) == 2 && Chain(e, it) == "0,1,3,3", $"wrap in rack: with the Arp unhooked it comes out ({Chain(e, it)})");
+ yield return (e.UnwrapRack(it, target) == 2 && Chain(e, it) == "0,1,3,3" && e.MidiEffectCcDestDevice(it, arp) == after + 1,
+ $"wrap in rack: an unwrap shifts the Arp's target with its device ({Chain(e, it)}, target {e.MidiEffectCcDestDevice(it, arp)})");
foreach (var x in WrapKeepsTail()) yield return x;
}
diff --git a/tests/Nota.SmokeTest/DeviceGroupTests.cs b/tests/Nota.SmokeTest/DeviceGroupTests.cs
new file mode 100644
index 00000000..f1694c17
--- /dev/null
+++ b/tests/Nota.SmokeTest/DeviceGroupTests.cs
@@ -0,0 +1,595 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Group devices into a rack and back (specs/044, #328).
+// - group_devices folds a contiguous run into an Audio Effect, MIDI Effect or Instrument Rack in
+// place, the instances themselves (the output is the same sample for sample), one undo step;
+// ungroup_rack is the reverse; every refusal leaves the chain alone.
+// - Automation lanes, CV links, an Arp's CC target and sidechain keys follow the devices into
+// the rack chain (nested addresses) and back, keep acting, follow edits inside the rack, and
+// survive save / reload.
+// - Several devices on the clipboard paste in one undo step, the instrument replacing the
+// target's, what a track can't take skipped.
+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --device-group`.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class DeviceGroupTests
+{
+ private const int Eq8 = 0, Compressor = 1, Reverb = 2, Delay = 3, Utility = 4, AudioRack = 5;
+ private const int Volt = 6, Arp = 0, Chord = 1, Scale = 2, MidiRackKind = 6;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in AudioGroup()) yield return r;
+ foreach (var r in Refusals()) yield return r;
+ foreach (var r in LinksFollow()) yield return r;
+ foreach (var r in InstrumentGroup()) yield return r;
+ foreach (var r in MidiGroup()) yield return r;
+ foreach (var r in Clipboard()) yield return r;
+ foreach (var r in ChainNames()) yield return r;
+ foreach (var r in ArpInMidiRack()) yield return r;
+ foreach (var r in RackChainPaste()) yield return r;
+ foreach (var r in RackRenders()) yield return r;
+ foreach (var r in MasterKey()) yield return r;
+ foreach (var r in UndoBeforeFirstTarget()) yield return r;
+ }
+
+ // A fresh engine: undoing to a snapshot from before any CC target existed drops the target
+ // (the snapshot's routes are empty, not rebuilt from the Arp's later setting).
+ private static IEnumerable<(bool, string)> UndoBeforeFirstTarget()
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ int arp = e.AddMidiEffect(t, Arp);
+ e.AddBuiltinDevice(t, Eq8);
+ int dl = e.AddBuiltinDevice(t, Delay);
+ e.SetMidiEffectCcDest(t, arp, dl, 1); // the first CC target in this engine (no undo step)
+ e.Undo(); // the Delay's insertion
+ yield return (e.TrackDeviceCount(t) == 1 && e.MidiEffectCcDestDevice(t, arp) < 0,
+ $"undo before the first CC target: the removed Delay isn't targeted ({e.TrackDeviceCount(t)} devices, target {e.MidiEffectCcDestDevice(t, arp)})");
+ }
+
+ // A keyed Compressor grouped on the master keeps its key through save / reload.
+ private static IEnumerable<(bool, string)> MasterKey()
+ {
+ using var e = new NotaEngine();
+ int src = e.AddAudioTrack();
+ int m = e.MasterTrackId;
+ int cp = e.AddBuiltinDevice(m, Compressor);
+ e.SetDeviceSidechainSource(m, cp, src);
+ e.WrapDeviceInRack(m, cp);
+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-group-master-" + Guid.NewGuid().ToString("N") + ".nota");
+ try
+ {
+ ProjectService.Save(ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), new List<string>()), dir, e);
+ using var x = new NotaEngine();
+ var w = ProjectService.Apply(ProjectService.Load(dir), x, dir);
+ int xs = -1;
+ for (int i = 0; i < x.TrackCount; i++) if (x.TryGetTrackInfo(i, out var ti) && !ti.IsInstrument) xs = ti.Id;
+ yield return (w.Count == 0 && x.RackChainSidechain(x.MasterTrackId, cp, 0, 0) is { SourceTrack: var k } && k == xs && xs > 0,
+ $"master: a keyed Compressor grouped on the master keeps its key through save / reload ({string.Join("; ", w)})");
+ }
+ finally { try { Directory.Delete(dir, true); } catch { } }
+ }
+
+ // FR-015: the new rack's chain is named after its first device (an Instrument Rack's after
+ // its instrument: an empty name shows the instrument's).
+ private static IEnumerable<(bool, string)> ChainNames()
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ e.AddMidiEffect(t, Chord);
+ e.AddMidiEffect(t, Scale);
+ e.AddBuiltinDevice(t, Compressor);
+ e.AddBuiltinDevice(t, Delay);
+ e.GroupDevices(t, -1, 0, false, 0, 2);
+ e.GroupDevices(t, 0, 2, false, -1, 0);
+ yield return (e.RackDevChainName(t, 0, 0) == e.RackDevChainDeviceName(t, 0, 0, 0) && e.RackDevChainName(t, 0, 0).Length > 0,
+ $"chain name: an Audio Effect Rack's chain takes its first device's name ({e.RackDevChainName(t, 0, 0)})");
+ yield return (e.MidiRackChainName(t, 0, 0) == e.MidiRackChainDeviceName(t, 0, 0, 0) && e.MidiRackChainName(t, 0, 0).Length > 0,
+ $"chain name: a MIDI Effect Rack's chain takes its first device's name ({e.MidiRackChainName(t, 0, 0)})");
+ }
+
+ // An Arp whose CC lane drives an effect, grouped into a MIDI Effect Rack: it keeps its target
+ // (read through the rack chain's CC calls), and save / reload brings it back (NestedCcRoutes).
+ private static IEnumerable<(bool, string)> ArpInMidiRack()
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ int arp = e.AddMidiEffect(t, Arp);
+ e.AddBuiltinDevice(t, Eq8);
+ int dl = e.AddBuiltinDevice(t, Delay);
+ e.SetMidiEffectCcDest(t, arp, dl, 1);
+ e.SetMidiEffectCcDepth(t, arp, 0.5f);
+ int r = e.GroupDevices(t, 0, 1, false, -1, 0);
+ var d = e.RackChainMidiCcDest(t, -1000, 0, 0);
+ yield return (r == -1000 && d is { Device: 1, Chain: -1, Param: 1 } && Math.Abs(d.Value.Depth - 0.5f) < 1e-4f,
+ $"arp in a rack: the grouped Arp keeps its CC target ({d})");
+ // Set through the chain call: the Delay goes into an Audio Effect Rack, the Arp follows it.
+ e.GroupDevices(t, -1, 0, false, 1, 1);
+ d = e.RackChainMidiCcDest(t, -1000, 0, 0);
+ yield return (d is { Device: 1, Chain: 0, Slot: 0, Param: 1 },
+ $"arp in a rack: grouping its target too makes the target nested ({d})");
+ // Undo / redo of grouping the target put the Arp's target back and forth (shadows, no clone).
+ e.Undo();
+ var u = e.RackChainMidiCcDest(t, -1000, 0, 0);
+ e.Redo();
+ var re = e.RackChainMidiCcDest(t, -1000, 0, 0);
+ yield return (u is { Device: 1, Chain: -1 } && re is { Device: 1, Chain: 0, Slot: 0 },
+ $"arp in a rack: undo / redo of grouping its target restore the target ({u} / {re})");
+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-group-arp-" + Guid.NewGuid().ToString("N") + ".nota");
+ try
+ {
+ ProjectService.Save(ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), new List<string>()), dir, e);
+ using var x = new NotaEngine();
+ var w = ProjectService.Apply(ProjectService.Load(dir), x, dir);
+ int xt = -1;
+ for (int i = 0; i < x.TrackCount; i++) if (x.TryGetTrackInfo(i, out var ti) && ti.IsInstrument) xt = ti.Id;
+ var xd = x.RackChainMidiCcDest(xt, -1000, 0, 0);
+ yield return (w.Count == 0 && xd is { Device: 1, Chain: 0, Slot: 0, Param: 1 } && Math.Abs(xd.Value.Depth - 0.5f) < 1e-4f,
+ $"arp in a rack: save / reload brings the CC target back ({xd}; {string.Join("; ", w)})");
+ yield return (x.RackChainMidiSetCcDest(xt, -1000, 0, 0, new NestedCcDest(0, -1, -1, 2, 1f))
+ && x.RackChainMidiCcDest(xt, -1000, 0, 0) is { Device: 0, Chain: -1, Param: 2 },
+ "arp in a rack: the chain call sets a track-level target");
+ }
+ finally { try { Directory.Delete(dir, true); } catch { } }
+
+ // An Arp going into an Instrument Rack whose target stays outside: the target shifts once.
+ using var ie = new NotaEngine();
+ int it = ie.AddInstrumentTrack();
+ ie.SetTrackBuiltinInstrument(it, Volt);
+ int ia = ie.AddMidiEffect(it, Arp);
+ ie.AddBuiltinDevice(it, Eq8);
+ int idl = ie.AddBuiltinDevice(it, Delay);
+ ie.SetMidiEffectCcDest(it, ia, idl, 1);
+ ie.GroupDevices(it, 0, 1, true, 0, 1); // Arp, Volt, EQ-8 in; the Delay stays at index 0
+ yield return (ie.RackChainMidiCount(it, 0) == 1 && ie.RackChainMidiCcDest(it, -1, 0, 0) is { Device: 0, Chain: -1, Param: 1 },
+ $"arp in a rack: a target left outside an Instrument Rack group shifts once ({ie.RackChainMidiCcDest(it, -1, 0, 0)})");
+ // With no MIDI effects left on the track the grouped Arp's CC route still runs: its CC
+ // value (0 before any note) drives the Delay param to its minimum while playing.
+ float mn = ie.DeviceParamMin(it, 0, 1), mx = ie.DeviceParamMax(it, 0, 1);
+ ie.DeviceSetParam(it, 0, 1, mx);
+ var pb = new float[512 * 2];
+ ie.Seek(0); ie.Play();
+ for (int k = 0; k < 4; k++) ie.RenderOffline(pb, 512, 44100);
+ ie.StopTransport();
+ yield return (ie.TrackMidiEffectCount(it) == 0 && Math.Abs(ie.DeviceGetParam(it, 0, 1) - mn) < 1e-4f * Math.Max(1f, mx - mn),
+ $"arp in a rack: the grouped Arp still drives its target with no MIDI effects on the track ({ie.DeviceGetParam(it, 0, 1):F3}, min {mn:F3})");
+
+ // Arp and target in one Instrument Rack chain: a move inside the chain takes the target
+ // along, removing the target drops it.
+ using var je = new NotaEngine();
+ int jt = je.AddInstrumentTrack();
+ je.SetTrackBuiltinInstrument(jt, Volt);
+ int ja = je.AddMidiEffect(jt, Arp);
+ je.AddBuiltinDevice(jt, Eq8);
+ int jd = je.AddBuiltinDevice(jt, Delay);
+ je.SetMidiEffectCcDest(jt, ja, jd, 1);
+ je.GroupDevices(jt, 0, 1, true, 0, 2);
+ var j0 = je.RackChainMidiCcDest(jt, -1, 0, 0);
+ je.RackDevMoveChainDevice(jt, -1, 0, 1, 0); // the Delay before the EQ-8
+ var j1 = je.RackChainMidiCcDest(jt, -1, 0, 0);
+ je.RackDevRemoveChainDevice(jt, -1, 0, 0); // the Delay goes
+ var j2 = je.RackChainMidiCcDest(jt, -1, 0, 0);
+ je.Undo();
+ var j3 = je.RackChainMidiCcDest(jt, -1, 0, 0);
+ yield return (j0 is { Chain: 0, Slot: 1 } && j1 is { Chain: 0, Slot: 0 } && j2 is { Chain: -1 } && j2.Value.Device < 0
+ && j3 is { Chain: 0, Slot: 0 },
+ $"arp in a rack: edits inside the rack keep the Arp's target ({j0} → {j1} → {j2}, undo {j3})");
+
+ // Two effects pasted before the target in one undo step: undo puts the target back
+ // exactly (the routes of the step's snapshot, not the last remap's).
+ using var pe = new NotaEngine();
+ int pt = pe.AddInstrumentTrack();
+ pe.SetTrackBuiltinInstrument(pt, Volt);
+ int pa = pe.AddMidiEffect(pt, Arp);
+ int pd = pe.AddBuiltinDevice(pt, Delay);
+ pe.SetMidiEffectCcDest(pt, pa, pd, 1);
+ pe.GroupDevices(pt, 0, 1, true, 0, 1); // Arp, Volt, Delay in one chain
+ int other = pe.AddAudioTrack();
+ pe.AddBuiltinDevice(other, Eq8);
+ pe.AddBuiltinDevice(other, Utility);
+ pe.CopyDevices(other, Array.Empty<int>(), false, new[] { 0, 1 });
+ pe.RackDevChainPasteDevices(pt, -1, 0, -1, 0, out _, out _, out _);
+ var p1 = pe.RackChainMidiCcDest(pt, -1, 0, 0);
+ pe.Undo();
+ var p2 = pe.RackChainMidiCcDest(pt, -1, 0, 0);
+ yield return (p1 is { Chain: 0, Slot: 2 } && p2 is { Chain: 0, Slot: 0 },
+ $"arp in a rack: undo of a paste of two effects before the target restores it ({p1} → undo {p2})");
+
+ // An Arp on a rack's own control loses it with Ungroup; undo brings it back, redo drops it
+ // again (a restored snapshot without the route clears the Arp's target).
+ using var ue = new NotaEngine();
+ int ut = ue.AddInstrumentTrack();
+ ue.SetTrackBuiltinInstrument(ut, Volt);
+ int ua = ue.AddMidiEffect(ut, Arp);
+ ue.AddBuiltinDevice(ut, Eq8);
+ ue.WrapDeviceInRack(ut, 0);
+ ue.SetMidiEffectCcDest(ut, ua, 0, 0); // the rack itself
+ ue.UngroupRack(ut, DeviceFamily.Audio, 0, out _);
+ int afterUngroup = ue.MidiEffectCcDestDevice(ut, ua);
+ ue.Undo();
+ int afterUndo = ue.MidiEffectCcDestDevice(ut, ua);
+ ue.Redo();
+ int afterRedo = ue.MidiEffectCcDestDevice(ut, ua);
+ yield return (afterUngroup < 0 && afterUndo == 0 && afterRedo < 0,
+ $"arp in a rack: a target dropped by ungroup stays dropped after undo + redo ({afterUngroup} / {afterUndo} / {afterRedo})");
+ }
+
+ // Several devices pasted into a rack chain: what the chain takes, in order, one undo step.
+ private static IEnumerable<(bool, string)> RackChainPaste()
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ e.AddMidiEffect(t, Chord);
+ e.AddBuiltinDevice(t, Eq8);
+ e.AddBuiltinDevice(t, Delay);
+ int a = e.AddAudioTrack();
+ e.AddBuiltinDevice(a, Utility);
+ e.WrapDeviceInRack(a, 0); // an Audio Effect Rack holding the Utility
+ e.CopyDevices(t, new[] { 0 }, true, new[] { 0, 1 });
+ int n = e.RackDevChainPasteDevices(a, 0, 0, -1, 0, out int skipped, out int fm, out int ff);
+ string kinds = string.Join(",", Enumerable.Range(0, e.RackDevChainDeviceCount(a, 0, 0)).Select(i => e.RackDevChainDeviceBuiltinKind(a, 0, 0, i)));
+ yield return (n == 2 && skipped == 2 && ff == 0 && fm == -1 && kinds == $"{Eq8},{Delay},{Utility}",
+ $"rack chain paste: the effects land in order, the MIDI effect and the instrument are skipped ({n}, {skipped}, {kinds})");
+ e.Undo();
+ yield return (e.RackDevChainDeviceCount(a, 0, 0) == 1, "rack chain paste: one undo takes the whole paste back");
+ }
+
+ // SC-003 for the MIDI Effect Rack and the Instrument Rack: a deterministic Sampler track
+ // renders the same samples grouped and ungrouped.
+ private static IEnumerable<(bool, string)> RackRenders()
+ {
+ string wav = Path.Combine(Path.GetTempPath(), "nota_smoke_group_sine.wav");
+ WavWriter.WriteSine(wav, seconds: 2.0, freq: 220, sampleRate: 44100);
+ foreach (var (name, group) in new (string, Func<NotaEngine, int, int>)[]
+ {
+ ("MIDI Effect Rack", (x, t) => x.GroupDevices(t, 0, 2, false, -1, 0)),
+ ("Instrument Rack", (x, t) => x.GroupDevices(t, 0, 2, true, 0, 1)),
+ })
+ {
+ using var a = new NotaEngine();
+ using var b = new NotaEngine();
+ int ta = Build(a), tb = Build(b);
+ var ba = new float[512 * 2];
+ var bb = new float[512 * 2];
+ a.Seek(0); a.Play(); b.Seek(0); b.Play();
+ for (int i = 0; i < 8; i++) { a.RenderOffline(ba, 512, 44100); b.RenderOffline(bb, 512, 44100); }
+ int r = group(a, ta);
+ double worst = 0;
+ float level = 0;
+ for (int i = 0; i < 60; i++)
+ {
+ a.RenderOffline(ba, 512, 44100);
+ b.RenderOffline(bb, 512, 44100);
+ float ra = Rms(ba), rb = Rms(bb);
+ level = Math.Max(level, rb);
+ if (rb > 1e-4f) worst = Math.Max(worst, Math.Abs(20 * Math.Log10(Math.Max(ra, 1e-9f) / rb)));
+ }
+ a.StopTransport(); b.StopTransport();
+ yield return (r != -2 && level > 1e-3f && worst <= 0.1,
+ $"{name}: a grouped Sampler track sounds the same (worst block {worst:F3} dB, level {level:F3})");
+ }
+
+ int Build(NotaEngine x)
+ {
+ x.SetBpm(120); x.SetMetronome(false);
+ int t = x.AddSamplerTrack(wav, 60, false);
+ x.AddMidiEffect(t, Chord);
+ x.AddMidiEffect(t, Scale);
+ x.AddBuiltinDevice(t, Eq8);
+ int clip = x.AddMidiClip(t, 0.0, 8.0);
+ x.SetClipNotes(t, clip, new[] { new NotaNote(60, 0.0, 6.0, 0.9f), new NotaNote(64, 0.0, 6.0, 0.7f) });
+ return t;
+ }
+ }
+
+ private static bool Same(float a, float b) => Math.Abs(a - b) <= 1e-4f * Math.Max(1f, Math.Abs(a));
+
+ private static string Chain(NotaEngine e, int t)
+ {
+ var k = new int[e.TrackDeviceCount(t)];
+ for (int i = 0; i < k.Length; i++) k[i] = e.TrackDeviceBuiltinKind(t, i);
+ return string.Join(",", k);
+ }
+
+ private static string RackChain(NotaEngine e, int t, int rack)
+ {
+ var k = new int[e.RackDevChainDeviceCount(t, rack, 0)];
+ for (int i = 0; i < k.Length; i++) k[i] = e.RackDevChainDeviceBuiltinKind(t, rack, 0, i);
+ return string.Join(",", k);
+ }
+
+ private static string Midi(NotaEngine e, int t)
+ {
+ var k = new int[e.TrackMidiEffectCount(t)];
+ for (int i = 0; i < k.Length; i++) k[i] = e.MidiEffectKind(t, i);
+ return string.Join(",", k);
+ }
+
+ private static float Rms(float[] b)
+ {
+ double a = 0;
+ foreach (var v in b) a += v * v;
+ return (float)Math.Sqrt(a / b.Length);
+ }
+
+ // An audio track playing a steady two-tone through EQ-8, Compressor, Utility and Delay:
+ // deterministic, so two engines render the same samples.
+ private static int SteadyChain(NotaEngine e)
+ {
+ e.SetBpm(120); e.SetMetronome(false);
+ int t = e.AddAudioTrack();
+ const int frames = 44100 * 4;
+ var pcm = new float[frames * 2];
+ for (int i = 0; i < frames; i++)
+ pcm[2 * i] = pcm[2 * i + 1] = 0.3f * MathF.Sin(2 * MathF.PI * 220 * i / 44100f) + 0.2f * MathF.Sin(2 * MathF.PI * 1330 * i / 44100f);
+ e.PasteAudioFrames(t, pcm, frames, 0.0, "tone");
+ e.AddBuiltinDevice(t, Eq8);
+ int c = e.AddBuiltinDevice(t, Compressor);
+ e.DeviceSetParam(t, c, 0, -24f);
+ e.AddBuiltinDevice(t, Utility);
+ int d = e.AddBuiltinDevice(t, Delay);
+ e.DeviceSetParam(t, d, 1, e.DeviceParamMin(t, d, 1) + 0.4f * (e.DeviceParamMax(t, d, 1) - e.DeviceParamMin(t, d, 1)));
+ return t;
+ }
+
+ private static IEnumerable<(bool, string)> AudioGroup()
+ {
+ using var a = new NotaEngine();
+ using var b = new NotaEngine();
+ int ta = SteadyChain(a), tb = SteadyChain(b);
+ var ba = new float[512 * 2];
+ var bb = new float[512 * 2];
+ a.Seek(0); a.Play(); b.Seek(0); b.Play();
+ for (int i = 0; i < 20; i++) { a.RenderOffline(ba, 512, 44100); b.RenderOffline(bb, 512, 44100); }
+ int r = a.GroupDevices(ta, -1, 0, false, 1, 3);
+ yield return (r == 1 && Chain(a, ta) == $"{Eq8},{AudioRack}" && RackChain(a, ta, 1) == $"{Compressor},{Utility},{Delay}"
+ && Same(a.RackDevChainDeviceParamGet(ta, 1, 0, 0, 0), -24f),
+ $"group: Compressor..Delay become one Audio Effect Rack in place, in order, with their settings ({Chain(a, ta)} / {RackChain(a, ta, 1)})");
+ double worst = 0;
+ float maxDiff = 0;
+ for (int i = 0; i < 40; i++)
+ {
+ a.RenderOffline(ba, 512, 44100);
+ b.RenderOffline(bb, 512, 44100);
+ float ra = Rms(ba), rb = Rms(bb);
+ if (rb > 1e-5f) worst = Math.Max(worst, Math.Abs(20 * Math.Log10(ra / rb)));
+ for (int s = 0; s < ba.Length; s++) maxDiff = Math.Max(maxDiff, Math.Abs(ba[s] - bb[s]));
+ }
+ a.StopTransport(); b.StopTransport();
+ yield return (worst <= 0.1 && Rms(bb) > 1e-3f, $"group: the track sounds the same after grouping (worst block {worst:F3} dB, max sample diff {maxDiff:E1})");
+
+ yield return (a.Undo() && Chain(a, ta) == $"{Eq8},{Compressor},{Utility},{Delay}" && Same(a.DeviceGetParam(ta, 1, 0), -24f),
+ "group: one undo restores the four devices");
+ a.Redo();
+ int n = a.UngroupRack(ta, DeviceFamily.Audio, 1, out var dropped);
+ yield return (n == 3 && Chain(a, ta) == $"{Eq8},{Compressor},{Utility},{Delay}" && dropped == UngroupDropped.None,
+ $"ungroup: the chain's devices come back in place ({Chain(a, ta)}, {dropped})");
+ yield return (a.Undo() && Chain(a, ta) == $"{Eq8},{AudioRack}", "ungroup: one undo brings the rack back");
+ yield return (a.WrapDeviceInRack(ta, 0) == 0 && Chain(a, ta) == $"{AudioRack},{AudioRack}", "wrap: ⌘G on one device is a one-device group");
+ }
+
+ private static IEnumerable<(bool, string)> Refusals()
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ e.AddMidiEffect(t, Arp);
+ e.AddBuiltinDevice(t, Eq8);
+ e.AddBuiltinDevice(t, Reverb);
+ string before = Chain(e, t);
+ yield return (e.GroupDevices(t, 0, 1, false, 0, 1) == (int)GroupRefusal.NotContiguous && Chain(e, t) == before && Midi(e, t) == $"{Arp}",
+ "refused: MIDI and audio effects without the instrument");
+ yield return (e.GroupDevices(t, -1, 0, true, 1, 1) == (int)GroupRefusal.NotContiguous, "refused: an audio run that doesn't start at the instrument");
+ yield return (e.GroupDevices(t, -1, 0, false, 1, 5) == (int)GroupRefusal.BadRun, "refused: a run past the end");
+ e.GroupDevices(t, -1, 0, false, 1, 1); // Reverb into a rack
+ yield return (e.GroupDevices(t, -1, 0, false, 0, 2) == (int)GroupRefusal.RackInRun && Chain(e, t) == $"{Eq8},{AudioRack}",
+ "refused: a rack inside the run");
+ e.RackDevAddChain(t, 1, -1);
+ yield return (e.UngroupRack(t, DeviceFamily.Audio, 1, out _) == (int)UngroupRefusal.SeveralChains, "refused: ungroup of a rack with two chains");
+ yield return (e.UngroupRack(t, DeviceFamily.Audio, 0, out _) == (int)UngroupRefusal.NotARack, "refused: ungroup of a device that isn't a rack");
+ int rack = e.AddInstrumentRackTrack();
+ yield return (e.GroupDevices(rack, -1, 0, true, -1, 0) == (int)GroupRefusal.InstrumentCantNest, "refused: an Instrument Rack into an Instrument Rack");
+ int drums = e.AddDrumRackTrack();
+ yield return (e.UngroupRack(drums, DeviceFamily.Instrument, 0, out _) == (int)UngroupRefusal.DrumRack, "refused: ungroup of a Drum Rack");
+ int audio = e.AddAudioTrack();
+ yield return (e.GroupDevices(audio, -1, 0, true, -1, 0) == (int)GroupRefusal.NotInstrumentTrack, "refused: the instrument of an audio track");
+ }
+
+ // Lanes, CV links, an Arp's CC target and a sidechain key on grouped devices follow them.
+ private static IEnumerable<(bool, string)> LinksFollow()
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120); e.SetMetronome(false);
+ int src = e.AddAudioTrack();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ int arp = e.AddMidiEffect(t, Arp);
+ e.AddBuiltinDevice(t, Eq8); // 0
+ int dl = e.AddBuiltinDevice(t, Delay); // 1
+ int rv = e.AddBuiltinDevice(t, Reverb); // 2
+ int cp = e.AddBuiltinDevice(t, Compressor); // 3
+ e.AddBuiltinDevice(t, Utility); // 4 (after the run)
+ const int lanePar = 1;
+ float lo = e.DeviceParamMin(t, dl, lanePar), hi = e.DeviceParamMax(t, dl, lanePar);
+ float v = lo + 0.73f * (hi - lo);
+ int lane = e.AddAutomationLane(t, AutomationTarget.DeviceParam, dl, lanePar);
+ e.SetAutomationPoints(t, lane, new[] { new AutomationPoint(0, v), new AutomationPoint(16, v) });
+ int utilLane = e.AddAutomationLane(t, AutomationTarget.DeviceParam, 4, 0);
+ e.SetAutomationPoints(t, utilLane, new[] { new AutomationPoint(0, e.DeviceParamMin(t, 4, 0)) });
+ int mod = e.ModulatorAdd(t, 0);
+ int link = e.CvLinkAddToTarget(t, mod, 0, -1, rv, 0);
+ e.SetMidiEffectCcDest(t, arp, dl, 0);
+ e.SetDeviceSidechainSource(t, cp, src);
+
+ int r = e.GroupDevices(t, -1, 0, false, 1, 3);
+ var li = e.AutomationLaneInfo(t, lane);
+ yield return (r == 1 && li.DeviceIndex == 1 && e.AutomationLanePath(t, lane) == (0, 0),
+ $"links: the Delay's lane points into the rack (device {li.DeviceIndex}, path {e.AutomationLanePath(t, lane)})");
+ yield return (e.AutomationLaneInfo(t, utilLane).DeviceIndex == 2 && e.AutomationLanePath(t, utilLane) == (-1, -1),
+ $"links: the Utility's lane after the run shifts with it (device {e.AutomationLaneInfo(t, utilLane).DeviceIndex})");
+ var cvp = e.CvLinkPath(t, link);
+ yield return (e.CvLinkDevice(t, link) == 1 && cvp.TargetChain == 0 && cvp.TargetSlot == 1,
+ $"links: the LFO's CV link targets the Reverb in the rack ({e.CvLinkDevice(t, link)}, {cvp})");
+ float rlo = e.RackDevChainDeviceParamMin(t, 1, 0, 1, 0), rhi = e.RackDevChainDeviceParamMax(t, 1, 0, 1, 0);
+ float knob = rlo + 0.42f * (rhi - rlo);
+ e.RackDevChainDeviceParamSet(t, 1, 0, 1, 0, knob);
+ yield return (Same(e.CvLinkBase(t, link), knob),
+ $"links: turning the grouped Reverb's knob moves its CV link's base ({e.CvLinkBase(t, link):F3}, knob {knob:F3})");
+ yield return (e.MidiEffectCcDestDevice(t, arp) == 1 && e.MidiEffectCcDestPath(t, arp) == (0, 0),
+ $"links: the Arp's CC lane drives the Delay in the rack ({e.MidiEffectCcDestDevice(t, arp)}, {e.MidiEffectCcDestPath(t, arp)})");
+ yield return (e.RackChainSidechain(t, 1, 0, 2) is { SourceTrack: var s } && s == src,
+ "links: the Compressor in the rack keeps its sidechain key");
+
+ // The lane still drives the Delay: write the other value into it, play, read it back.
+ e.SetMidiEffectCcDest(t, arp, -1, -1); // the Arp would drive the same param
+ e.RackDevChainDeviceParamSet(t, 1, 0, 0, lanePar, lo);
+ var buf = new float[512 * 2];
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 4; i++) e.RenderOffline(buf, 512, 44100);
+ e.StopTransport();
+ yield return (Same(e.RackDevChainDeviceParamGet(t, 1, 0, 0, lanePar), v),
+ $"links: the nested lane plays (Delay param {e.RackDevChainDeviceParamGet(t, 1, 0, 0, lanePar):F3}, lane {v:F3})");
+ e.SetMidiEffectCcDest(t, arp, 1, 0); // a live setting, not an undo step: put it back by hand
+ e.SetMidiEffectCcDestPath(t, arp, 0, 0);
+
+ // An edit inside the rack: the Delay moves to the end of its chain, its lane follows.
+ e.RackDevMoveChainDevice(t, 1, 0, 0, 2);
+ yield return (e.AutomationLanePath(t, lane) == (0, 2) && e.CvLinkPath(t, link).TargetSlot == 0,
+ $"links: a move inside the rack takes the lane along ({e.AutomationLanePath(t, lane)}, CV slot {e.CvLinkPath(t, link).TargetSlot})");
+ e.Undo();
+ yield return (e.AutomationLanePath(t, lane) == (0, 0), $"links: undo of the move puts the lane back ({e.AutomationLanePath(t, lane)})");
+
+ // Save and reload: the nested references come back.
+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-group-" + Guid.NewGuid().ToString("N") + ".nota");
+ var transport = new TransportState(120.0, 1.0, false, false);
+ try
+ {
+ ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), dir, e);
+ using var d = new NotaEngine();
+ var w = ProjectService.Apply(ProjectService.Load(dir), d, dir);
+ int dt = -1, ds = -1;
+ for (int i = 0; i < d.TrackCount; i++)
+ if (d.TryGetTrackInfo(i, out var ti))
+ {
+ if (ti.IsInstrument) dt = ti.Id;
+ else if (ds < 0) ds = ti.Id;
+ }
+ int dLane = -1, dLink = d.CvLinkCount(dt) - 1;
+ for (int l = 0; l < d.AutomationLaneCount(dt); l++)
+ if (d.AutomationLanePath(dt, l).Chain >= 0) dLane = l;
+ yield return (w.Count == 0 && dLane >= 0 && d.AutomationLanePath(dt, dLane) == (0, 0) && Chain(d, dt) == $"{Eq8},{AudioRack},{Utility}",
+ $"reload: the nested lane comes back ({w.Count} warnings: {string.Join("; ", w)})");
+ yield return (dLink >= 0 && d.CvLinkPath(dt, dLink).TargetChain == 0 && d.CvLinkPath(dt, dLink).TargetSlot == 1,
+ "reload: the CV link into the rack comes back");
+ yield return (d.MidiEffectCcDestPath(dt, 0) == (0, 0) && d.MidiEffectCcDestDevice(dt, 0) == 1, "reload: the Arp's CC target in the rack comes back");
+ yield return (d.RackChainSidechain(dt, 1, 0, 2) is { SourceTrack: var s2 } && s2 == ds, "reload: the keyed Compressor's source comes back");
+ }
+ finally { try { Directory.Delete(dir, true); } catch { } }
+
+ // Ungroup: everything back at track level, in place.
+ int n = e.UngroupRack(t, DeviceFamily.Audio, 1, out _);
+ yield return (n == 3 && Chain(e, t) == $"{Eq8},{Delay},{Reverb},{Compressor},{Utility}" && e.AutomationLanePath(t, lane) == (-1, -1)
+ && e.AutomationLaneInfo(t, lane).DeviceIndex == 1 && e.AutomationLaneInfo(t, utilLane).DeviceIndex == 4,
+ $"ungroup: lanes return to the track's devices ({e.AutomationLaneInfo(t, lane).DeviceIndex}, {e.AutomationLaneInfo(t, utilLane).DeviceIndex})");
+ yield return (e.CvLinkDevice(t, link) == 2 && e.CvLinkPath(t, link).TargetChain == -1 && e.MidiEffectCcDestDevice(t, arp) == 1
+ && e.MidiEffectCcDestPath(t, arp) == (-1, -1) && e.DeviceSidechainSource(t, 3) == src,
+ "ungroup: the CV link, the Arp's CC target and the key return too");
+ yield return (e.Undo() && e.AutomationLanePath(t, lane) == (0, 0) && Chain(e, t) == $"{Eq8},{AudioRack},{Utility}",
+ "undo: ungroup steps back to the rack with its lanes inside");
+ }
+
+ private static IEnumerable<(bool, string)> InstrumentGroup()
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120); e.SetMetronome(false);
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ e.AddMidiEffect(t, Chord);
+ e.AddMidiEffect(t, Scale);
+ e.AddBuiltinDevice(t, Eq8);
+ e.AddBuiltinDevice(t, Reverb);
+ int lane = e.AddAutomationLane(t, AutomationTarget.DeviceParam, 0, 1);
+ int clip = e.AddMidiClip(t, 0.0, 8.0);
+ e.SetClipNotes(t, clip, new[] { new NotaNote(57, 0.0, 8.0, 0.9f) });
+ var buf = new float[512 * 2];
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 40; i++) e.RenderOffline(buf, 512, 44100);
+ float before = Rms(buf);
+ // Scale (the last MIDI effect), the instrument and the EQ-8 (the first audio effect).
+ int r = e.GroupDevices(t, 1, 1, true, 0, 1);
+ e.RenderOffline(buf, 512, 44100);
+ float after = Rms(buf);
+ e.StopTransport();
+ yield return (r == -1 && e.TrackInstrumentKind(t) == 3 && e.RackChainCount(t) == 1 && e.RackChainMidiCount(t, 0) == 1
+ && e.RackChainMidiKind(t, 0, 0) == Scale && e.RackChainInstrumentKind(t, 0) == Volt
+ && e.RackChainDeviceCount(t, 0) == 1 && e.RackChainDeviceBuiltinKind(t, 0, 0) == Eq8
+ && Midi(e, t) == $"{Chord}" && Chain(e, t) == $"{Reverb}",
+ $"instrument group: an Instrument Rack whose chain is Scale → Volt → EQ-8; Chord and Reverb stay around it ({Midi(e, t)} / {Chain(e, t)})");
+ double db = before > 1e-5f && after > 1e-5f ? 20 * Math.Log10(after / before) : 99;
+ yield return (Math.Abs(db) < 1.5, $"instrument group: the held note plays on through the edit ({db:+0.00;-0.00} dB)");
+ yield return (e.AutomationLaneInfo(t, lane).DeviceIndex == -1 && e.AutomationLanePath(t, lane) == (0, 0),
+ "instrument group: the EQ-8's lane points into the Instrument Rack's chain");
+ int n = e.UngroupRack(t, DeviceFamily.Instrument, 0, out _);
+ yield return (n == 3 && e.TrackInstrumentKind(t) == Volt && Midi(e, t) == $"{Chord},{Scale}" && Chain(e, t) == $"{Eq8},{Reverb}"
+ && e.AutomationLaneInfo(t, lane).DeviceIndex == 0 && e.AutomationLanePath(t, lane) == (-1, -1),
+ $"instrument ungroup: MIDI effects after the track's, the instrument back, effects before the track's ({Midi(e, t)} / {Chain(e, t)})");
+ yield return (e.Undo() && e.TrackInstrumentKind(t) == 3 && e.Undo() && e.TrackInstrumentKind(t) == Volt && Chain(e, t) == $"{Eq8},{Reverb}",
+ "instrument group: undo steps back through ungroup and group");
+ }
+
+ private static IEnumerable<(bool, string)> MidiGroup()
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, Volt);
+ e.AddMidiEffect(t, Chord);
+ e.AddMidiEffect(t, Scale);
+ e.AddMidiEffect(t, Arp);
+ int r = e.GroupDevices(t, 0, 3, false, -1, 0);
+ yield return (r == -1000 && Midi(e, t) == $"{MidiRackKind}" && e.MidiRackChainCount(t, 0) == 1 && e.MidiRackChainDeviceCount(t, 0, 0) == 3
+ && e.MidiRackChainDeviceKind(t, 0, 0, 2) == Arp,
+ $"MIDI group: Chord, Scale, Arp become one MIDI Effect Rack ({Midi(e, t)})");
+ int n = e.UngroupRack(t, DeviceFamily.Midi, 0, out _);
+ yield return (n == 3 && Midi(e, t) == $"{Chord},{Scale},{Arp}", $"MIDI ungroup: the three come back in order ({Midi(e, t)})");
+ }
+
+ private static IEnumerable<(bool, string)> Clipboard()
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(a, Volt);
+ e.AddMidiEffect(a, Chord);
+ e.AddBuiltinDevice(a, Eq8);
+ e.AddBuiltinDevice(a, Delay);
+ e.AddBuiltinDevice(a, Reverb);
+ e.DeviceSetParam(a, 2, 1, e.DeviceParamMin(a, 2, 1) + 0.61f * (e.DeviceParamMax(a, 2, 1) - e.DeviceParamMin(a, 2, 1)));
+ int b = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(b, 0);
+ e.AddBuiltinDevice(b, Utility);
+ yield return (e.CopyDevices(a, new[] { 0 }, false, new[] { 0, 2 }) == 3 && e.DeviceClipboardKind() == 4 && e.DeviceClipboardCount() == 3,
+ "clipboard: Chord, EQ-8 and Reverb copied together");
+ int n = e.PasteDevices(b, -1, 0, out int skipped);
+ yield return (n == 3 && skipped == 0 && Chain(e, b) == $"{Eq8},{Reverb},{Utility}" && Midi(e, b) == $"{Chord}"
+ && Same(e.DeviceGetParam(b, 1, 1), e.DeviceGetParam(a, 2, 1)),
+ $"clipboard: pasted in order into their sections, settings kept ({Chain(e, b)} / {Midi(e, b)})");
+ yield return (e.Undo() && Chain(e, b) == $"{Utility}" && Midi(e, b) == "", "clipboard: one undo takes the whole paste back");
+ int audio = e.AddAudioTrack();
+ n = e.PasteDevices(audio, -1, -1, out skipped);
+ yield return (n == 2 && skipped == 1 && Chain(e, audio) == $"{Eq8},{Reverb}", $"clipboard: an audio track takes the effects and skips the MIDI effect ({n}, {skipped})");
+ yield return (e.CopyDevices(a, new[] { 0 }, true, new[] { 1 }) == 3, "clipboard: the instrument copies with its effects");
+ e.PasteDevices(b, -1, -1, out _);
+ yield return (e.TrackInstrumentKind(b) == Volt && Midi(e, b) == $"{Chord}" && Chain(e, b) == $"{Utility},{Delay}",
+ $"clipboard: pasting it replaces the target's instrument and adds the effects ({e.TrackInstrumentKind(b)} / {Chain(e, b)})");
+ yield return (e.Undo() && e.TrackInstrumentKind(b) == 0 && Chain(e, b) == $"{Utility}", "clipboard: one undo restores the target's instrument");
+ }
+}
diff --git a/tests/Nota.SmokeTest/DeviceSelectionTests.cs b/tests/Nota.SmokeTest/DeviceSelectionTests.cs
new file mode 100644
index 00000000..503f71da
--- /dev/null
+++ b/tests/Nota.SmokeTest/DeviceSelectionTests.cs
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The Devices panel's multi-selection and what ⌘G makes of it (specs/044): Shift-click ranges
+// across MIDI effects, the instrument and audio effects, ⌘-click toggles, and every row of the
+// group-shape table (data-model.md). Headless: no window, no engine.
+
+using Nota.Presentation;
+
+namespace Nota.SmokeTest;
+
+internal static class DeviceSelectionTests
+{
+ private static ChainSlot M(int i) => new(DeviceSection.Midi, i);
+ private static ChainSlot A(int i) => new(DeviceSection.Audio, i);
+ private static ChainSlot I => ChainSlot.Instrument;
+
+ private static string Show(DeviceSelection s) =>
+ string.Join(",", s.Members.Select(m => m.Section switch { DeviceSection.Midi => $"m{m.Index}", DeviceSection.Instrument => "i", _ => $"a{m.Index}" }));
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ // A chain of 2 MIDI effects, the instrument and 3 audio effects.
+ const int mc = 2, fc = 3;
+ var s = new DeviceSelection();
+ s.Click(M(1));
+ s.ExtendTo(A(1), mc, true, fc);
+ yield return (Show(s) == "m1,i,a0,a1", $"selection: Shift-click spans MIDI → instrument → audio ({Show(s)})");
+ s.ExtendTo(M(0), mc, true, fc);
+ yield return (Show(s) == "m0,m1", $"selection: Shift-click again re-spans from the same anchor ({Show(s)})");
+ s.Click(A(0));
+ s.Toggle(A(2));
+ yield return (Show(s) == "a0,a2" && s.Anchor == A(2), $"selection: ⌘-click adds and becomes the anchor ({Show(s)})");
+ s.Toggle(A(0));
+ yield return (Show(s) == "a2", $"selection: ⌘-click on a selected device takes it out ({Show(s)})");
+ s.Clear();
+ yield return (s.IsEmpty && s.Anchor is null, "selection: Clear empties it");
+
+ // Group shapes.
+ GroupShape Shape(params ChainSlot[] slots) { var x = new DeviceSelection(); x.Set(slots); return x.Shape(mc, fc); }
+ var g = Shape(A(1), A(2));
+ yield return (g.Kind == GroupShapeKind.AudioRack && g.FxFirst == 1 && g.FxCount == 2, "shape: adjacent audio effects → Audio Effect Rack");
+ g = Shape(A(0), A(2));
+ yield return (g.Kind == GroupShapeKind.Refused && g.Reason!.Contains("next to each other"), "shape: a gap is refused");
+ g = Shape(M(0), M(1));
+ yield return (g.Kind == GroupShapeKind.MidiRack && g.MidiFirst == 0 && g.MidiCount == 2, "shape: MIDI effects → MIDI Effect Rack");
+ g = Shape(M(1), A(0));
+ yield return (g.Kind == GroupShapeKind.Refused && g.Reason!.Contains("instrument"), "shape: MIDI + audio without the instrument is refused");
+ g = Shape(M(1), I, A(0), A(1));
+ yield return (g.Kind == GroupShapeKind.InstrumentRack && g.MidiFirst == 1 && g.MidiCount == 1 && g.FxFirst == 0 && g.FxCount == 2,
+ "shape: MIDI tail + instrument + audio head → Instrument Rack");
+ g = Shape(I);
+ yield return (g.Kind == GroupShapeKind.InstrumentRack && g.MidiCount == 0 && g.FxCount == 0, "shape: the instrument alone → Instrument Rack");
+ g = Shape(M(0), I);
+ yield return (g.Kind == GroupShapeKind.Refused, "shape: a MIDI run that doesn't reach the instrument is refused");
+ g = Shape(I, A(1));
+ yield return (g.Kind == GroupShapeKind.Refused, "shape: an audio run that doesn't start at the instrument is refused");
+ var p = new DeviceSelection();
+ p.Set(new[] { A(1), A(2) });
+ p.Prune(mc, true, 2);
+ yield return (Show(p) == "a1", $"selection: pruning drops devices past the chain's end ({Show(p)})");
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 43cf329e..0f05ded6 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -436,6 +436,15 @@ if (args.Length >= 1 && args[0] == "--device-copy")
Console.WriteLine(failures == 0 ? "DEVICE COPY PASSED" : $"DEVICE COPY FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Group devices into a rack and back (specs/044) alone: `--device-group`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--device-group")
+{
+ Console.WriteLine("-- device group --");
+ foreach (var (ok, label) in DeviceGroupTests.Run()) Check(ok, label);
+ foreach (var (ok, label) in DeviceSelectionTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "DEVICE GROUP PASSED" : $"DEVICE GROUP FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// The instrument as a device in the chain (specs/043) alone: `--instrument-chain`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--instrument-chain")
{
@@ -15151,6 +15160,8 @@ Console.WriteLine("-- device copy + rack undo --");
foreach (var (ok, label) in DeviceCopyTests.Run()) Check(ok, label);
Console.WriteLine("-- instrument chain --");
foreach (var (ok, label) in InstrumentChainTests.Run()) Check(ok, label);
+foreach (var (ok, label) in DeviceGroupTests.Run()) Check(ok, label);
+foreach (var (ok, label) in DeviceSelectionTests.Run()) Check(ok, label);
// --- racks redesign (specs/040): v8 compatibility, mapping rules, MIDI racks, chain MIDI effects ---
foreach (var (title, run) in RackSections())