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) Sidechain from a single pad, chain or voice (#190) (#381)

Egor Khindikaynen894fb5928ab3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3f8e356d..417db1ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Sidechain from a single pad, chain or voice** (#190): a sidechain key can now listen to one
+ pad of a Drum Rack, one chain of an Instrument Rack or one voice of Nota Rhythm instead of the
+ whole track — duck the bass from just the kick. Every key source picker lists the parts under
+ their track (Compressor, Auto Filter, Auto Gain, Ceiling, Dynamic EQ, Prism, Shutter, Vocoder,
+ plug-in sidechain inputs and Nota Flux's React). Pre takes the part before its own effects (the
+ raw hit), Post after its effects and its level and pan. A muted or solo-silenced pad still drives
+ its key — the "ghost kick". The key stays on its pad when pads are added, removed or renamed,
+ goes quiet while its pad is deleted (undo brings it back) and is saved with the project. MCP:
+ `list_sidechain_sources`, `get_instrument_sidechain`, `set_instrument_sidechain`, and a
+ `sourcePart` on `get_device_sidechain` / `set_device_sidechain`.
- **ASIO on Windows**: Settings → Audio → **Audio system** now offers ASIO beside WASAPI.
Pick the driver and the output and input channel pairs by the driver's own names (the
other outputs stay silent); **Driver settings…** opens the driver's panel, where the buffer
@@ -184,6 +194,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
before keep the stereo pair. Saved with the project; MCP `set_input_channels`.
### Changed
+- **16 sidechain routes instead of 8** (#190): whole tracks and single pads share the pool; a
+ source picker greys out what no free route can take, and a project that needs more says how many
+ keys it had to drop.
- **Return and master rows start compact**: new projects, new returns and projects saved
before this version show them at the Compact height, so the tracks get the room.
- **One click arms one track** (nota-daw/nota#332): a click on a track's arm button arms that
diff --git a/FEATURES.md b/FEATURES.md
index 10f128bb..40f6303d 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -236,6 +236,12 @@ track count and closes with Escape.
Recording on the receiver prints the incoming MIDI into a clip. Saved with the
project.
- **Send/Return** buses (sends to returns) with a return list.
+ - **Sidechain keys** — a device's key (and Nota Flux's React) listens to another track, or
+ to one pad of a Drum Rack, one chain of an Instrument Rack or one voice of Nota Rhythm on
+ it: every source picker lists the parts under their track. Pre takes a part before its own
+ effects, Post after them and its level and pan. A muted or solo-silenced pad still drives
+ its key (a "ghost kick"); the key follows its pad through edits and is saved with the
+ project. Up to 16 distinct sources at once.
- **Level meters** (peak/RMS) on every channel and on the master, plus true peak.
- **Device chain** per track: instrument + effects + MIDI effects, laid out in a row. The
**+** at its end opens the browser on Audio effects with the cursor in the search.
@@ -699,8 +705,8 @@ audio effects after it keep running and keep their settings; saved with the proj
presets; MCP `read_eq8`, `set_eq8_band`, `set_eq8`.
- **Nota Compressor** (1) — 5 character models (Clean/Glue/Punch/Opto/FET), soft knee,
look-ahead (reported as latency for PDC), Peak/RMS/Auto detection, hold, auto-release,
- auto-gain, Range, MIX; a sidechain key (internal or another track, pre/post tap, External
- key switch) through 2-pole HP/LP filters with Q and SC Gain, Listen, Stereo link on/off.
+ auto-gain, Range, MIX; a sidechain key (internal, another track or one pad / chain / voice
+ of it, pre/post tap, External key switch) through 2-pole HP/LP filters with Q and SC Gain, Listen, Stereo link on/off.
Tabs: Curve (draggable transfer curve + gain-reduction history, crest in → out) / Motion
(reduction envelope against the input, measured transient and recovery) / Sidechain (key
spectrum under draggable filters), and Dynamics / Output, with a LEVEL column and a status
@@ -1301,6 +1307,9 @@ Coverage:
name), load a sample onto a track or into a rack chain, read sample info, and read / shape a
Sampler in real units (`read_sampler`, `set_sampler`).
- **Mixer**: sends to returns, the return list, track and master meters, record source.
+- **Sidechain**: `list_sidechain_sources` (tracks with their pads / chains / voices and the free
+ routes), `set_device_sidechain` / `get_device_sidechain` with a `sourcePart`, and Nota
+ Flux's React with `set_instrument_sidechain` / `get_instrument_sidechain`.
- **Plugins**: list the AU/VST3 catalogue, look up by id, add as an instrument or insert
effect, open and close the editor, read and write parameters and state.
- **Presets**: factory (list, apply to a new track or in place) and user (list, apply,
diff --git a/specs/050-sidechain-sub-sources/checklists/requirements.md b/specs/050-sidechain-sub-sources/checklists/requirements.md
new file mode 100644
index 00000000..109325a4
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/checklists/requirements.md
@@ -0,0 +1,37 @@
+# Specification Quality Checklist: Sidechain from individual pads, voices and chains
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-28
+**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
+
+- Engine internals appear only in the template's "Nota Context" section (as context for the plan),
+ not in requirements or success criteria.
+- The 3 open questions (muted parts / ghost kick, route budget, devices inside rack chains as
+ consumers) were answered on 2026-10-28 and recorded under Clarifications. All items pass.
diff --git a/specs/050-sidechain-sub-sources/contracts/c-abi.md b/specs/050-sidechain-sub-sources/contracts/c-abi.md
new file mode 100644
index 00000000..89aefd62
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/contracts/c-abi.md
@@ -0,0 +1,61 @@
+# Contract: C ABI additions (`nota_engine.h`)
+
+All message thread. Existing calls keep their meaning: `nota_device_set_sidechain_source` and
+`nota_track_set_instrument_sidechain_source` set a **whole-track** key (part cleared);
+`nota_device_sidechain_source` / `nota_track_instrument_sidechain_source` still return the source
+track id for any key, part or not.
+
+```c
+/* ---- Sidechain sub-sources (specs/050) -----------------------------------
+ * A key may name one part of the source track's instrument: a Drum Rack pad, an Instrument
+ * Rack chain (first level) or a Nota Rhythm voice. Parts are addressed by their CURRENT
+ * index; the engine keeps the key on the same part through reorder / insert / delete of
+ * others. part -1 = whole track. Getters report -2 when the keyed part no longer exists
+ * (the key is silent until an undo brings the part back). */
+
+/* Number of parts of the track's instrument (0 = none / not multi-part). */
+NOTA_API int32_t nota_track_part_count(const NotaEngine* engine, int32_t track_id);
+/* Display name of part `index` (chain name, else its instrument's; Rhythm "1 Kick").
+ * Returns the full UTF-8 length; copies up to cap-1 bytes + NUL when out is non-null. */
+NOTA_API int32_t nota_track_part_name(const NotaEngine* engine, int32_t track_id, int32_t index,
+ char* out, int32_t cap);
+
+/* Device key. 0 = set, -1 bad address / part, -2 no free route (nothing changed). */
+NOTA_API int32_t nota_device_set_sidechain_key(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t source_track_id, int32_t part);
+/* 0 = read, -1 bad address. *out_source -1 = none; *out_part -1 whole, -2 missing. */
+NOTA_API int32_t nota_device_sidechain_key(const NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t* out_source, int32_t* out_part);
+
+/* Instrument key (React, Nota Flux) — always the Post tap. Same results as above. */
+NOTA_API int32_t nota_track_set_instrument_sidechain_key(NotaEngine* engine, int32_t track_id,
+ int32_t source_track_id, int32_t part);
+NOTA_API int32_t nota_track_instrument_sidechain_key(const NotaEngine* engine, int32_t track_id,
+ int32_t* out_source, int32_t* out_part);
+
+/* Keyed rack children (save / load, specs/044): the part of a chain child's key. */
+NOTA_API int32_t nota_rack_chain_sidechain_part(const NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t* out_part);
+NOTA_API int32_t nota_rack_chain_set_sidechain_part(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t part);
+/* The whole key in one step (source, part, tap, gain, mix): only the final key meets the
+ * route check; -2 leaves key and shaping as they were. Used by project load. */
+NOTA_API int32_t nota_rack_chain_set_sidechain_key(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t source_track, int32_t part,
+ int32_t tap_pre, float gain_db, float mix);
+
+/* Route pool: capacity (16), free slots now, and whether (source, part) already has a slot
+ * (a further consumer of it needs no new one). */
+NOTA_API int32_t nota_sidechain_route_capacity(const NotaEngine* engine);
+NOTA_API int32_t nota_sidechain_routes_free(const NotaEngine* engine);
+NOTA_API int32_t nota_sidechain_route_in_use(const NotaEngine* engine, int32_t source_track_id, int32_t part);
+```
+
+Behaviour that the smoke test pins:
+
+- `set_sidechain_key(.., part)` then `sidechain_key` round-trips the index; after moving the keyed
+ pad to index 0 the getter returns 0.
+- Removing the keyed chain → getter `-2`; `nota_engine_undo` → the original index again.
+- Filling the pool: the 17th distinct source returns `-2`, `routes_free` = 0, an in-use source still
+ returns 0.
+- `nota_device_set_sidechain_source(t, d, s)` after a part key → `sidechain_key` part = -1.
diff --git a/specs/050-sidechain-sub-sources/contracts/mcp.md b/specs/050-sidechain-sub-sources/contracts/mcp.md
new file mode 100644
index 00000000..fefef9bb
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/contracts/mcp.md
@@ -0,0 +1,17 @@
+# Contract: MCP tools (`Nota.Mcp/Tools/DeviceTools.cs`)
+
+Changed:
+
+- `get_device_sidechain` → adds `sourcePart` (int: -1 whole track, -2 the keyed part is gone) and
+ `sourceName` ("Drums · Kick").
+- `set_device_sidechain` → optional `sourcePart` (int, default -1 = whole track; the part index from
+ `list_sidechain_sources`). Fails with a clear message when no route is free.
+
+New:
+
+- `list_sidechain_sources` → every track that can be a source: `{ trackId, name, frozen,
+ routeInUse, parts: [{ index, name, routeInUse }] }`, plus `routesFree` / `routeCapacity`.
+- `get_instrument_sidechain` / `set_instrument_sidechain` (Nota Flux React): `trackId`,
+ `sourceTrackId`, optional `sourcePart`; React always taps Post.
+
+Descriptions mention the "duck the bass from the kick pad" recipe so an agent finds it.
diff --git a/specs/050-sidechain-sub-sources/data-model.md b/specs/050-sidechain-sub-sources/data-model.md
new file mode 100644
index 00000000..d81d633b
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/data-model.md
@@ -0,0 +1,77 @@
+# Data model: Sidechain from individual pads, voices and chains
+
+## Engine (C++)
+
+### Part id
+
+`uint64_t`. 0 = whole track. Rack chain → `RackChain::uid` (base uid, no `instGen`). Rhythm voice
+`v` (0..7) → `v + 1`. Only meaningful together with the source track's current instrument.
+
+### Consumer key (on `Device` and `Instrument` base classes)
+
+| Field | Type | Notes |
+|---|---|---|
+| source track | `int32_t` (existing, per subclass) | -1 = none |
+| `scPart_` | `std::atomic<uint64_t>` (new, base class) | 0 = whole track |
+| tap | `int32_t` (existing on devices) | 0 post, 1 pre; Instrument (React) has none = post |
+
+Copied with the track id wherever a device / instrument is cloned, grouped into a rack, or moved;
+cleared with it.
+
+### Multi-part instrument surface (`Instrument`, virtual, message thread unless noted)
+
+| Member | Meaning |
+|---|---|
+| `int32_t partCount() const` | 0 for single-part instruments |
+| `uint64_t partId(int32_t index) const` | stable id of the part at `index` |
+| `int32_t partIndex(uint64_t id) const` | current index, -1 if gone |
+| `std::string partName(int32_t index) const` | chain name, else its instrument's name; Rhythm "1 Kick" |
+| `void setPartTaps(const PartTap*, int32_t n)` | **audio thread**, per block, before render |
+
+`PartTap { uint64_t part; float* pre; float* post; }` — `pre`/`post` point at the slot's Next
+buffers (stereo interleaved, `frames * 2`), added into (not overwritten).
+
+Implemented by `RackCore` (Drum Rack, Instrument Rack; first level) and `RhythmMachine`.
+
+### Route slot (`Engine`)
+
+| Field | Type |
+|---|---|
+| `routeSlotTrackId_[kMaxRoutes]` | `std::atomic<int32_t>`, -1 free |
+| `routeSlotPart_[kMaxRoutes]` (new) | `std::atomic<uint64_t>`, 0 whole track |
+| `routeBus_`, `routeBusNext_`, `routeBusPre_`, `routeBusPreNext_` | existing, `kMaxRoutes` 8 → 16 |
+
+Rules: one slot per distinct *(track, part)*; a key whose track or part is missing claims none; a
+consumer whose key has no slot hears nothing (nullptr). A track owning any slot keeps rendering while
+muted / solo-gated (existing `keying`, extended to part slots).
+
+### Lifecycle of a part key
+
+```text
+set(track, partIndex) ──► stored (track, partId) ──► recomputeRouting: slot claimed ──► live
+ │ │
+ │ no free slot → -2, not stored └─ part deleted / instrument replaced → no slot (dormant)
+ │ └─ undo restores chain (same uid) → live again
+```
+
+## Managed (C#)
+
+### `IAudioEngine` additions
+
+`TrackPartCount(track)`, `TrackPartName(track, index)`, `SetDeviceSidechainKey(track, device, source,
+part) → int`, `DeviceSidechainKey(track, device) → (Source, Part)`,
+`SetInstrumentSidechainKey(track, source, part) → int`, `InstrumentSidechainKey(track) → (Source,
+Part)`, `SidechainRoutesFree()`, `SidechainRouteInUse(source, part)`, rack-child
+`RackChainSidechainPart` / `RackChainSetSidechainPart`. `Part` = current index, -1 whole track, -2
+missing (dormant).
+
+### Project format v28
+
+| DTO | New field | Default |
+|---|---|---|
+| `DeviceDto` | `int SidechainPart` | -1 |
+| `InstrumentDto` | `int SidechainPart` | -1 |
+| `NestedSidechainDto` | `int Part` | -1 |
+
+Value = part index at save time on the source track's instrument. A dormant key (Part -2) saves as
+`SidechainSource = -1`. Migration v27 → v28: no-op.
diff --git a/specs/050-sidechain-sub-sources/plan.md b/specs/050-sidechain-sub-sources/plan.md
new file mode 100644
index 00000000..ff9a51c0
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/plan.md
@@ -0,0 +1,133 @@
+# Implementation Plan: Sidechain from individual pads, voices and chains
+
+**Branch**: `feat/sidechain-sub-sources` | **Date**: 2026-10-28 | **Spec**: [spec.md](spec.md) |
+**Issue**: nota-daw/nota#190
+
+## Summary
+
+A sidechain route slot is keyed by *(source track, part)* instead of a track. A part is a Drum Rack
+pad or Instrument Rack chain (its runtime `RackChain::uid`) or a Rhythm voice (`v + 1`); 0 means the
+whole track. Right before a source track's instrument renders, the engine hands it the Pre/Post
+buffers of the slots that name its parts (`setPartTaps`, a per-block stack array — no allocation, no
+lock); the rack / Rhythm render adds each tapped part into them in the loop that already sums it. A
+tapped part that is muted or solo-gated still renders for its taps. The pool grows from 8 to 16 slots
+and set calls report when it is full. The C ABI addresses parts by current index; persistence saves
+that index (format v28) and resolves it back to the new chain's uid on load. One shared source
+picker replaces the per-card track combos and lists parts indented under their track.
+
+Details and alternatives: [research.md](research.md). Shapes: [data-model.md](data-model.md).
+Interfaces: [contracts/c-abi.md](contracts/c-abi.md), [contracts/mcp.md](contracts/mcp.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (managed, Avalonia UI, MCP)
+
+**Primary Dependencies**: none new
+
+**Storage**: project file format v27 → v28 (`SidechainPart` on `DeviceDto` / `InstrumentDto`,
+`Part` on `NestedSidechainDto`); no-op migration
+
+**Audio-Thread Impact**: yes — new per-part tap writes inside `DrumRack::render`,
+`RackInstrument::render`, `RhythmMachine::render`, fed by a per-block pointer hand-off from
+`renderLeafDry`. Buffers are the engine's preallocated route buses (16 × 4 × kMaxBlock stereo,
+≈ 8 MiB, allocated in the `Engine` constructor). No allocation, lock or I/O on the audio thread
+(AR-6); key selection changes go through `recomputeRouting` on the message thread writing atomics,
+as today; rack structure keeps its immutable snapshots (AR-5). With no part keys the render pays
+one `n > 0` branch per instrument.
+
+**Testing**: `tests/Nota.SmokeTest` (new `SidechainPartTests.cs`), engine perf gate (specs/034)
+
+**Target Platform**: macOS, Windows, Linux (desktop app)
+
+**Project Type**: desktop app (native engine + managed UI)
+
+**Performance Goals**: no measurable change without part keys (SC-005); a part key costs no more
+than a whole-track key (one stereo add per tap)
+
+**Constraints**: one block of key latency (unchanged); first rack level only; Rhythm voices 0..7
+
+**Scale/Scope**: up to 16 distinct sources; a Drum Rack typically 16 pads (tap lookup is a scan of ≤ 16
+taps, only when the track has part keys); 11 sidechain consumers in UI
+
+## Constitution Check
+
+| Principle | Status |
+|---|---|
+| I. Real-time safety | ✅ Taps use preallocated engine buffers handed per block; no alloc / lock / I/O; slot table stays atomics written on the message thread (R3, R6) |
+| II. Boundary discipline | ✅ New calls are plain C in `nota_engine.h` (contracts/c-abi.md); no JUCE outside `pluginhost/` |
+| III. Licensing | ✅ No new dependency; new files (`SidechainPartTests.cs`, `SidechainSourcePicker.cs`) get the SPDX header |
+| IV. Verification gate | ✅ Smoke test extended (quickstart.md) and covers every new ABI call |
+| V. One logical change | ⚠️ Large but one feature; delivered as ordered commits (engine → ABI → persistence → UI → MCP → docs) in one PR, as the issue asks |
+| VI. Docs in sync | ✅ CHANGELOG `[Unreleased]`, FEATURES.md (nota-features), user manual EN+RU (nota-docs) |
+| VII. Spec-first | ✅ This spec / plan / tasks |
+| VIII. No weakened rules | ✅ |
+
+Post-design re-check: unchanged — the design keeps every audio-thread write inside buffers owned by
+the rendering track, so parallel leaf render stays race-free.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/050-sidechain-sub-sources/
+├── spec.md, plan.md, research.md, data-model.md, quickstart.md
+├── contracts/c-abi.md, contracts/mcp.md
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # specs/050 block (contracts/c-abi.md)
+└── src/
+ ├── devices/Device.h, Instrument.h # scPart_; part surface; setPartTaps
+ ├── devices/racks/RackCore.{h,cpp} # partCount/partId/partIndex/partName
+ ├── devices/racks/DrumRack.cpp # taps + ghost render
+ ├── devices/racks/RackInstrument.{h,cpp} # taps + ghost render; tap table
+ ├── devices/instruments/RhythmMachine.{h,cpp} # voice taps
+ ├── engine/Engine.h, Engine.cpp # kMaxRoutes 16; routeSlotPart_; routeSlotFor
+ ├── engine/Engine_Devices.cpp # recomputeRouting; key set/get; clone/move copy
+ ├── engine/Engine_Rack.cpp # rack-child key part; grouping copy
+ ├── engine/Engine_Render.cpp # feed by (track, part); setPartTaps hand-off; keying
+ └── abi/nota_engine*.cpp # new entry points
+src/managed/
+├── Nota.Application/Engine/IAudioEngine.cs # new members
+├── Nota.Infrastructure/Interop/NativeMethods.Devices.cs, NotaEngine.Devices.cs (+ RackDev)
+├── Nota.Infrastructure/Persistence/ProjectModel.cs, ProjectService.cs, ProjectMigrations.cs
+├── Nota.App/DeviceCards/SidechainSourcePicker.cs # NEW shared picker
+├── Nota.App/DeviceCards/DeviceParamControls.cs, PluginCard.cs
+├── Nota.App/DeviceCards/Bodies/{Compressor,AutoFilter,AutoGain,AutoShift,Ceiling,DynamicEq,Prism,Shutter,Vocoder}DeviceBody.cs
+├── Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs
+└── Nota.Mcp/Tools/DeviceTools.cs
+tests/Nota.SmokeTest/SidechainPartTests.cs # NEW (+ registration in Program.cs)
+CHANGELOG.md, FEATURES.md, ../nota-docs # docs
+```
+
+**Structure Decision**: existing layout; one new managed file for the picker, one new test file.
+
+## Delivery order
+
+1. Engine core: part id + `Instrument` part surface; `scPart_`; slot table (16, part-aware);
+ `recomputeRouting`; consumers fed by `(track, part)`; `keying` for part slots.
+2. Capture: `setPartTaps` hand-off; Drum Rack / Instrument Rack / Rhythm taps; ghost render.
+3. C ABI + smoke tests 1–8 (engine-only, no UI) — MVP for US1–US4 at the engine level.
+4. Persistence v28 + smoke test 9.
+5. Shared picker; switch all 11 consumers; Listen / source names.
+6. MCP tools.
+7. Docs: CHANGELOG, FEATURES.md, nota-docs; PR screenshots.
+
+## Out of scope / follow-ups
+
+- Sidechain keys for devices inside rack chains (rack card UI) — separate issue.
+- Hosted plug-ins with multiple output buses as sources.
+- Making key edits undoable (today's behaviour is kept, FR-015).
+- Nested racks below the first level.
+
+## Complexity Tracking
+
+| Violation | Why Needed | Simpler Alternative Rejected Because |
+|---|---|---|
+| Principle V: one PR spans engine, persistence, UI, MCP | The issue's acceptance needs the whole path; a half (engine without picker) is not user-visible | Splitting into PRs would ship an ABI with no caller or a picker with no engine support |
diff --git a/specs/050-sidechain-sub-sources/quickstart.md b/specs/050-sidechain-sub-sources/quickstart.md
new file mode 100644
index 00000000..1d581c16
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/quickstart.md
@@ -0,0 +1,37 @@
+# Quickstart: validating sidechain sub-sources
+
+## Automated (the PR gate)
+
+```bash
+scripts/build.sh
+```
+
+`tests/Nota.SmokeTest/SidechainPartTests.cs` must pass. It covers:
+
+1. **Kick pad only (FR-016, SC-001)** — Drum Rack with two Sampler pads (kick, hat) loaded from a
+ fixture WAV, kick on steps 1/3, hat on 2/4. Bass track: a sustained deterministic clip → Compressor
+ keyed `(drums, kickPad)`. Offline render; per block read `DeviceGainReduction`. Expect GR ≥ 3 dB in
+ kick blocks and < 0.1 dB in hat blocks — once with Pre, once with Post.
+2. **Pre vs Post** — a Utility at −20 dB on the kick pad: Pre GR unchanged, Post GR drops.
+3. **Ghost kick (FR-007a, SC-005a)** — mute the kick pad: the Drum Rack track's output loses the
+ kick, GR on the bass stays.
+4. **Stable identity (FR-003, SC-003)** — move the kick pad, add a pad, delete the hat: the key
+ still follows the kick (GR pattern and `sidechain_key` index).
+5. **Dormant key (FR-004)** — delete the kick pad → part -2, no GR; undo → key live again.
+6. **Rhythm voice and Instrument Rack chain** — same check as 1 against Rhythm voice 1 and a chain.
+7. **React** — Flux keyed off the kick pad reacts on kick blocks only.
+8. **Route pool (FR-007b/c)** — 16 distinct sources set, the 17th returns -2; shared sources reuse.
+9. **Persistence (FR-012/013)** — save → reopen keeps `(source, part, tap)`; the `racks-v8` fixture
+ and a v27 project with whole-track keys open unchanged.
+10. **Idle cost (FR-011)** — the engine perf gate (specs/034) shows no regression with no part keys.
+
+## Manual (the app)
+
+1. New project → "Drums" (Drum Rack: Kick, Hat), "Bass" (any synth + Compressor).
+2. Compressor → Sidechain tab → source dropdown: "Drums" with indented "Kick", "Hat". Pick "Kick".
+3. Play: the GR meter moves on kicks only; Listen reads "Listen: … Drums · Kick post …".
+4. Rename the pad → the card follows. Mute the pad → you still hear the duck, not the kick.
+5. Save, reopen → still "Drums · Kick".
+6. Flux on another track → React source "Drums ▸ Kick" (no Pre/Post control).
+
+Screenshots of the picker go into the PR via the `nota-pr` skill.
diff --git a/specs/050-sidechain-sub-sources/research.md b/specs/050-sidechain-sub-sources/research.md
new file mode 100644
index 00000000..db39cfc2
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/research.md
@@ -0,0 +1,160 @@
+# Research: Sidechain from individual pads, voices and chains
+
+Findings from the code as of `develop` @ 89bc635, and the decisions they lead to.
+
+## R1. How a sidechain key flows today
+
+- A consumer stores its source track id (`Device::sidechainSourceTrackId()`, ten built-in overrides
+ each with their own `scTrackId_` atomic; `Instrument::sidechainSourceTrackId()` for Nota Flux).
+- `Engine::recomputeRouting()` (message thread, `Engine_Devices.cpp`) clears `routeSlotTrackId_[8]`
+ and claims one slot per distinct source track referenced by a track device, a track instrument, a
+ keyed rack child (specs/044) or a monitoring audio track. A source not in the graph gets no slot.
+- Render (`Engine_Render.cpp`): every slot has four buffers (`routeBus_`/`routeBusNext_` post,
+ `routeBusPre_`/`routeBusPreNext_` pre). A source track adds its pre-FX signal into
+ `routeBusPreNext_` (step 1b) and its post-fader signal into `routeBusNext_`; consumers read the
+ previous block's `routeBus_`/`routeBusPre_` in `feedDeviceKey` / the instrument path; buffers swap
+ at block end. One block of key latency, order-independent, parallel-safe (a slot is written by
+ exactly one source track).
+- A muted / solo-gated source track keeps rendering while it owns a slot (`keying`), with its
+ post-fader tap silent while muted.
+
+**Decision**: keep this design. A route slot's identity becomes *(track id, part)* instead of a
+track id; part slots are filled from inside the instrument's render, using the same Next buffers
+and the same swap.
+
+## R2. Where the per-part signal exists
+
+- **Drum Rack** (`DrumRack::render`): per pad `scratch_` ← instrument; inserts process in place; then
+ one loop applies decay VCA (`env`) and `g * rv * pan` while summing into `out`.
+ - Pre tap = `scratch_` right after `instrument->render`.
+ - Post tap = per sample `l * env * gPan` (pad gain/pan, **not** rack volume `rv`) — computed in the
+ same loop, so no extra pass.
+- **Instrument Rack** (`RackInstrument::render`): same shape without the decay VCA; MIDI chains render
+ `scratch_` in pieces, complete before the inserts run. Pre / Post as above.
+- **Nota Rhythm** (`RhythmMachine::render`): 256-frame chunks; each active voice adds
+ `voiceStereo * panGains` into `vbuf_[v]` (voices with FX) or straight into `mix_`; voice FX run per
+ chunk; then Glue + Volume. Rhythm voices have no mute/solo.
+ - Pre tap = the voice's panned output (`sl*gl, sr*gr`), written at `base + j`.
+ - Post tap = `vbuf_[v]` after its FX; for a voice without FX, Post = Pre.
+- Mute / solo-gated rack chains `continue` before rendering (DrumRack also drops `retrig`).
+
+**Decision**: a tapped chain that is muted / solo-gated renders anyway (inserts included, decay VCA
+kicked as usual) and feeds its taps, but skips the add into `out` and keeps its meter at 0
+(FR-007a). Untapped chains keep the early `continue`.
+
+## R3. Handing taps to the instrument without allocation or locks
+
+The engine already hands per-block pointers to instruments right before render
+(`setSidechain(ptr, frames)`, `setTransportInfo`). **Decision**: same pattern —
+
+```text
+struct PartTap { uint64_t part; float* pre; float* post; }; // part = stable id (R4)
+virtual void setPartTaps(const PartTap* taps, int32_t n) {} // Instrument; audio thread
+```
+
+`renderLeafDry` builds a stack array (≤ kMaxRoutes) by scanning the route slots owned by this track
+with a part ≠ 0, passes it before `renderInstrumentRaw`, and clears it after. The instrument looks up
+each chain's tap by a linear scan of ≤ 16 entries (only when `n > 0`), so a project without part keys
+pays one branch per render (FR-011, SC-005). Pointers target `routeBus*Next_[slot]` — engine-owned,
+preallocated, written only by this track's render ⇒ safe under the parallel leaf render.
+
+Rejected: a persistent per-instrument tap table published from the message thread (needs its own
+snapshot/RCU lifetime; the per-block hand-off has none).
+
+Review follow-up (PR #381): the instrument **copies** the table (`Instrument::PartTaps`, ≤ 16
+entries) and keeps an offset into the block — `playEvents` renders a block in pieces split at MIDI
+events, and each piece must write its own stretch of the key. The hand-off runs for both the
+Arrangement and the Session instrument paths. A part key whose part is gone gets a silent buffer,
+not nullptr (a detector handed nullptr keys off its own input).
+
+## R4. Stable part identity
+
+- Rack chains carry `RackChain::uid` (global counter, kept by rack forks for undo, used by lanes /
+ CV links / CC routes via `chainByUid` — lock-free, audio-thread safe). It is **not** saved in the
+ rack blob; saved cross-references into a rack use the chain index at save time (specs/044).
+- Rhythm voices are fixed slots 0..7.
+
+**Decision**: a part id is a `uint64_t`, 0 = whole track.
+- Rack chain → `RackChain::uid` (base uid, *without* `instGen`: swapping a pad's sample instrument
+ keeps the key, like lanes do).
+- Rhythm voice v → top bit | the Rhythm's instrument uid << 4 | `v + 1`, so a fresh Rhythm put in
+ its place (or a rack chain uid) never answers to an old key; the uid survives undo.
+Resolution (uid ↔ current index, name) is a virtual on `Instrument`, implemented by `RackCore`
+(first level only) and `RhythmMachine`. The C ABI speaks **part indices** (current position), like
+every other rack call; the engine converts to/from the stable id. Saving writes the index at save
+time; loading converts it back to the freshly loaded chain's uid (R7).
+
+Reorder / insert / delete-other keep the uid ⇒ FR-003. Deleting the chain leaves a dangling uid ⇒
+`recomputeRouting` finds no such part and claims no slot ⇒ silent key; an undo restores the rack
+snapshot with the same uid ⇒ the key resumes (FR-004, mirrors deleted-track behaviour).
+
+## R5. Where the key's part lives on the consumer
+
+Ten `Device` subclasses and `FluxSynth` each own `scTrackId_`. **Decision**: don't touch them; add a
+non-virtual `std::atomic<uint64_t> scPart_{0}` with `sidechainPart()/setSidechainPart()` on the
+`Device` and `Instrument` base classes. Hosted plug-ins get it for free. Every place that copies a
+key (`Engine_Devices.cpp` device clone ~L698, `Engine_Rack.cpp` grouping ~L215, the device clipboard,
+move-to-track's self-key clear ~L893/L1093) copies / clears the part with the track id.
+
+## R6. Route budget (FR-007b/c)
+
+`kMaxRoutes` 8 → 16. Memory: 16 slots × 4 buffers × `kMaxBlock` (16384) × 2 ch × 4 B ≈ 8 MiB
+(today ≈ 4 MiB), allocated once in the `Engine` constructor. `routeSlotForTrack` becomes
+`routeSlotFor(track, part)`. Slots fill from 0 in order, so a `routeSlotCount_` bounds every
+scan to the used slots: lookups run several times per track per block, and a first benchmark
+showed a scan over all 16 slots costing late blocks at 64-sample buffers with 192 tracks. With
+the bound, a project without sidechains pays one load per lookup.
+
+Slot identity is two atomics (`routeSlotTrackId_`, `routeSlotPart_`). `recomputeRouting` writes the
+part before the track (release) and the audio thread reads track then part (acquire); a reroute can
+at worst mis-key one block, the same tolerance today's non-atomic clear-and-reclaim already has.
+
+Set calls return `-2` when the source needs a new slot and none is free, or when taking it would
+push out another listener's route (claims run in track order); the key is then left as it was.
+The picker greys out unused sources from `nota_sidechain_routes_free == 0` and
+`nota_sidechain_route_in_use(track, part)`. Project load counts `-2` results and shows one notice.
+
+## R7. Persistence
+
+- Format **v27 → v28** (`ProjectService.CurrentFormatVersion`), no-op migration: absent fields read as
+ -1 = whole track (FR-013).
+- `DeviceDto.SidechainPart`, `InstrumentDto.SidechainPart` (React), `NestedSidechainDto.Part` — the
+ part **index** at save time; -1 whole track. A dormant key (part gone) saves as no source.
+- Load already defers key wiring until every track exists; by then racks are loaded, so the index
+ resolves to the new chain's uid.
+- Keyed rack children must carry the part too: `group_devices` moves a keyed Compressor into a rack
+ with its key (specs/044), so `nota_rack_chain_sidechain`/`_set_sidechain` gain a part variant.
+
+Risk: the ASIO branch (`specs/049`) may also bump the format; whoever merges second renumbers.
+
+## R8. Undo
+
+`nota_engine_undo` covers structural snapshots and value gestures; the sidechain source is a mutable
+member of a device whose pointer survives snapshots, and no managed caller wraps it in an undo group.
+**Decision**: picking a part is no more undoable than picking a track today (FR-015). Rack chain
+edits remain undoable and carry the uid, which is what FR-004 relies on.
+
+## R9. UI
+
+Nine device bodies (Compressor, Auto Filter, Auto Gain, Auto Shift, Ceiling, Dynamic EQ, Prism,
+Shutter, Vocoder), `DeviceParamControls.SidechainSelector` (plug-ins and generic cards) and
+`FluxInstrumentCard` each build their own `srcIds` / `srcNames` ComboBox from the track list.
+
+**Decision**: one shared builder, `SidechainSourcePicker` (Nota.App/DeviceCards), returning the
+ComboBox plus `SourceName()` for readouts. Items: "Internal / None", then per track one row (= whole
+track) and, when the track's instrument has parts, indented part rows ("Kick", "Snare"…) under it.
+This is the tree of FR-009 in a single flat dropdown — selecting a part is open → pick (2 clicks,
+SC-002) and it keeps every body's current layout. Items rebuild on `DropDownOpened` (part names /
+order change while the card is open) and follow external changes from the existing readout tick.
+Disabled rows carry the "No free routes" tooltip; a frozen track's parts are disabled. Display name
+"Track · Part" + " pre"/" post" for Listen. Styling per `DESIGN.md` (the combo already uses it).
+Rejected: a cascading submenu (two hovers, and Avalonia's ComboBox has no native tree).
+
+Rack cards keep refusing sidechain for chain children (out of scope, Clarifications Q3).
+
+## R10. Verification
+
+The smoke test drives the engine offline through the C ABI and can read
+`DeviceGainReduction(track, device)`. Test file `tests/Nota.SmokeTest/SidechainPartTests.cs`
+(deterministic Drum Rack with two Sampler pads fed by a fixture WAV, per the
+"compare levels with a deterministic clip" rule — synth notes drift between renders).
diff --git a/specs/050-sidechain-sub-sources/spec.md b/specs/050-sidechain-sub-sources/spec.md
new file mode 100644
index 00000000..adc5ae49
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/spec.md
@@ -0,0 +1,360 @@
+# Feature Specification: Sidechain from individual pads, voices and chains
+
+**Feature Branch**: `feat/sidechain-sub-sources`
+
+**Created**: 2026-10-28
+
+**Status**: Draft
+
+**Input**: User description: GitHub issue [nota-daw/nota#190](https://github.com/nota-daw/nota/issues/190) —
+"Sidechain from individual pads / voices / chains (Drum Rack, Rhythm, Instrument Rack)". A sidechain
+key can only be a whole track today; a user wants a Compressor on a bass track to duck from just the
+kick pad of a Drum Rack on another track, the way Ableton's sidechain picker lists every chain of a
+rack with its own Pre/Post tap.
+
+## 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
+
+Main area: Engine (per-part capture inside the rack / Rhythm render and the sidechain routing),
+with the persistence, MCP and picker UI on top.
+
+**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).
+
+**Where this touches today's behaviour** (context for the plan, not a design):
+
+- Sidechain keys are addressed by source track only; the engine mirrors each referenced source track
+ into one of a fixed pool of 8 route slots, with a post-FX/post-fader and a pre-FX/pre-fader tap.
+- Drum Rack, Instrument Rack and Nota Rhythm sum their parts inside the instrument, so no per-part
+ signal exists outside it.
+- Rack chains already carry a runtime-unique identity (used by lanes, CV links and CC routes that
+ point into a chain), but that identity is not saved; saved references into a rack use the chain's
+ position at save time.
+- The engine already stores a sidechain key for devices *inside* a rack chain (for save / load), but
+ the rack card does not let the user set one.
+
+## Clarifications
+
+### Session 2026-10-28
+
+- Q: Should a muted (or non-soloed) part still feed its sidechain key — the "ghost kick"? → A: Yes.
+ A part that some key references keeps rendering while muted / not soloed; it stays out of the mix
+ but feeds both its Pre and Post taps. Unreferenced muted parts still skip rendering.
+- Q: Do sub-sources share the route pool with whole-track sources, and what happens when it is full?
+ → A: One shared pool, enlarged from 8 to 16 sources (whole tracks and parts alike). When no slot is
+ free, sources not already in use show as disabled in the picker with the hint "No free routes".
+- Q: Are devices inside rack chains enabled as sidechain consumers in this feature? → A: No — a
+ separate follow-up; this feature only adds sub-sources.
+- Q: Which tap does Nota Flux's React key use when its source is a part? → A: Always Post, as
+ React does for a whole track today; Flux gets the sub-source tree but no Pre/Post control.
+- Q: (from planning) Is choosing a sidechain source undoable today, and what happens to a key when
+ its source is deleted? → A: Not undoable today, so FR-015 keeps that; a deleted source leaves the
+ key in place but silent until undo restores the source — parts follow the same rule (FR-004).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Duck the bass from just the kick pad (Priority: P1)
+
+A producer has a "Drums" track with a Nota Drum Rack (Kick, Snare, Hat pads) and a "Bass" track with
+a synth followed by a Compressor. In the Compressor's sidechain source picker they expand "Drums",
+pick "Kick", choose Pre or Post, and the bass now ducks only on kick hits. Snare and hat hits leave
+the bass alone.
+
+**Why this priority**: This is the reported use case and the reason the issue exists. It delivers the
+whole value on its own for the most common setup (drum rack + bass), and every other story reuses
+what it builds (sub-source addressing, per-part capture, the tree picker).
+
+**Independent Test**: Build the two tracks above with a pattern where kick and hat never coincide,
+key the Compressor off "Drums · Kick", play, and confirm gain reduction appears only on kick hits — in
+the Compressor's GR meter, through Listen, and in a deterministic render.
+
+**Acceptance Scenarios**:
+
+1. **Given** a Drum Rack track "Drums" with Kick and Hat pads and a Compressor on "Bass",
+ **When** the user opens the Compressor's sidechain source picker,
+ **Then** "Drums" offers "Whole track" plus one entry per pad, labelled with the pad's name.
+2. **Given** the Compressor is keyed to "Drums · Kick" with the Post tap,
+ **When** the pattern plays,
+ **Then** gain reduction follows kick hits only, and the hat pad never causes gain reduction.
+3. **Given** the Compressor is keyed to "Drums · Kick" with the Pre tap and the Kick pad has an insert
+ that changes its level (e.g. a Utility at −20 dB),
+ **When** the pattern plays,
+ **Then** the detector hears the kick before that insert (the level change does not alter the key),
+ while with Post it hears the kick after its inserts and its pad gain/pan.
+4. **Given** the Compressor is keyed to "Drums · Kick",
+ **When** the user turns on Listen or looks at the source name on the card,
+ **Then** the source reads "Drums · Kick" with the tap shown (e.g. "Drums · Kick pre").
+5. **Given** the Compressor is keyed to "Drums · Kick",
+ **When** the user picks "Drums ▸ Whole track",
+ **Then** the key returns to today's whole-track behaviour.
+
+---
+
+### User Story 2 - The key stays on the same pad through edits and reloads (Priority: P1)
+
+The user keeps working on the drum kit after setting the key: they reorder pads, add a clap pad,
+delete the snare, rename the kick to "Kick 909", save, close and reopen the project. The Compressor
+still keys off the same kick pad throughout.
+
+**Why this priority**: A key that silently jumps to another pad after a reorder or a reload is worse
+than no feature — the mix changes without the user noticing. Without this, Story 1 is not shippable.
+
+**Independent Test**: Set a key to one pad, then perform reorder / insert / delete-other / rename /
+save-reopen, and after each step confirm the GR still follows that pad and the picker still shows it
+selected.
+
+**Acceptance Scenarios**:
+
+1. **Given** a key on "Drums · Kick", **When** the user moves the Kick pad to another position or
+ another note, **Then** the key still follows the Kick pad.
+2. **Given** a key on "Drums · Kick", **When** the user adds or deletes *other* pads, **Then** the key
+ still follows the Kick pad.
+3. **Given** a key on "Drums · Kick", **When** the user renames the pad, **Then** the source name on
+ the consuming device updates to the new pad name.
+4. **Given** a key on "Drums · Kick", **When** the user deletes the Kick pad, **Then** the device
+ hears no key (as it does today when a source track is deleted) and its source reads as missing;
+ undo of the delete brings the pad back and the key works again.
+5. **Given** a key on "Drums · Kick", **When** the user replaces the Drum Rack on "Drums" with an
+ instrument that has no parts, **Then** the device hears no key and its source reads as missing, as
+ in scenario 4.
+6. **Given** a saved project with a key on a pad, **When** it is reopened, **Then** the key points at
+ the same pad with the same tap.
+7. **Given** a project saved by an older version with whole-track keys, **When** it is opened,
+ **Then** every key loads unchanged as "Whole track".
+
+---
+
+### User Story 3 - Key off a Nota Rhythm voice (Priority: P2)
+
+A user drives drums with Nota Rhythm. They key a Compressor (or Auto Filter, Shutter, …) on a pad
+track off Rhythm's kick voice only.
+
+**Why this priority**: Rhythm is Nota's own drum machine and has the same problem; its voices are
+fixed (8), so it is a smaller slice once Story 1 exists.
+
+**Independent Test**: A Rhythm track with kick and hat voices playing on alternate steps; key a
+Compressor off "Rhythm · Voice 1 (Kick)"; GR follows only that voice.
+
+**Acceptance Scenarios**:
+
+1. **Given** a Nota Rhythm track, **When** the user opens a sidechain picker on another track,
+ **Then** the Rhythm track offers "Whole track" plus its 8 voices, each labelled with its number and
+ the voice's current name/model.
+2. **Given** a key on one Rhythm voice with Pre, **When** it plays, **Then** the detector hears that
+ voice before its voice-FX chain; with Post, after its voice-FX and its level/pan, before the voices
+ are summed into Rhythm's Glue/Volume stage.
+
+---
+
+### User Story 4 - Key off an Instrument Rack chain (Priority: P2)
+
+A user has an Instrument Rack layering a sub-bass chain and a pad chain on one track and wants a
+device on another track to react only to the sub-bass chain.
+
+**Why this priority**: Same mechanism as Story 1 for the other rack type; less common than drums.
+
+**Independent Test**: An Instrument Rack with two chains playing different notes; key a device off one
+chain; it reacts only to that chain.
+
+**Acceptance Scenarios**:
+
+1. **Given** an Instrument Rack track, **When** the user opens a sidechain picker elsewhere,
+ **Then** the track offers "Whole track" plus one entry per chain, labelled with the chain name.
+2. **Given** a key on one chain, **When** the rack's chains are reordered, added or deleted (other than
+ the keyed one), **Then** the key follows the same chain (as in Story 2).
+
+---
+
+### User Story 5 - Every sidechain consumer gets sub-sources (Priority: P2)
+
+Whatever device the user keys — Compressor, Auto Filter, Auto Gain, Auto Shift, Ceiling, Dynamic EQ,
+Prism, Shutter, Nota Vocoder's modulator, a hosted plug-in's sidechain input, or Nota Flux's React —
+the source picker offers the same tree with sub-sources. Devices keep their Pre/Post control; Nota
+Flux's React has none and always listens to Post.
+
+**Why this priority**: Consistency: one picker everywhere. Each consumer is cheap once the picker and
+routing exist.
+
+**Independent Test**: For each consumer, key it off a Drum Rack pad and confirm it reacts only to
+that pad.
+
+**Acceptance Scenarios**:
+
+1. **Given** any device that accepts a sidechain key (or Nota Flux's React), **When** the user opens
+ its source picker, **Then** it shows the same tree of tracks and sub-sources.
+2. **Given** Nota Flux's React keyed off "Drums · Kick", **When** the pattern plays, **Then** React
+ follows the kick pad's Post signal only, and the card offers no Pre/Post choice.
+3. **Given** an AI agent connected over MCP, **When** it sets or reads a device's sidechain source,
+ **Then** it can address a sub-source (track + part) and read back which part is selected.
+
+---
+
+### Edge Cases
+
+- **Muted or non-soloed part ("ghost kick")**: a muted pad / chain / voice, or one silenced because
+ another is soloed, still feeds its key (Pre and Post) when some key references it; it stays out of
+ the mix. An unreferenced muted part keeps skipping its render as today.
+- **Muted source track**: a muted (or solo-gated) source track keeps rendering while it is keyed, as
+ today. Part taps sit inside the instrument, before the track's own devices and fader, so — like
+ today's whole-track Pre tap — they stay live while the track is muted.
+- **Route budget exhausted**: whole tracks and parts share one pool of 16 sources. When it is full,
+ every source not already in use is disabled in the picker with the hint "No free routes"; sources
+ already in use stay selectable for further consumers (several consumers keying the same part share
+ one route).
+- **Devices inside rack chains as consumers**: out of scope — a Compressor *inside* a Drum Rack pad's
+ chain still cannot be keyed; tracked as a separate follow-up.
+- **Nested racks**: a Drum Rack pad that itself holds an Instrument Rack — only the outer pad is a
+ sub-source; the inner rack's chains are not listed.
+- **Keying a part of the device's own track**: the existing rule for a track keying itself stays as it
+ is today; sub-sources of the consumer's own track follow the same rule.
+- **Source track deleted or its instrument bypassed / turned off**: same as today's whole-track
+ behaviour (deleted → no key until undo brings it back; silent instrument → silent key).
+- **Frozen source track**: a frozen track plays its freeze buffer and does not render its parts, so
+ part keys on it are silent while it is frozen; whole-track keys work as today. The picker marks a
+ frozen track's parts as unavailable.
+- **Pad with no sound loaded / chain with no instrument**: listed, produces a silent key.
+- **Audio Effect Rack chains**: not sub-sources in this feature (they are effect chains on a track,
+ not sounding parts of an instrument).
+- **Hosted plug-ins with multiple outputs**: out of scope (listed in the issue as "later").
+- **Clipboard / duplicate**: duplicating the consuming device or the whole consuming track keeps the
+ sub-source key; duplicating the *source* track does not re-point existing keys to the copy.
+- **Undo**: choosing a sidechain source is not an undo step today; picking a part keeps that
+ behaviour (making key edits undoable is a separate change).
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+**Sources**
+
+- **FR-001**: A sidechain source MUST be either a whole track (today's behaviour) or one sounding part
+ of the instrument on a track ("sub-source").
+- **FR-002**: Sub-sources MUST exist for: each pad (chain) of a Nota Drum Rack, each chain of a Nota
+ Instrument Rack, and each of the 8 voices of Nota Rhythm. Only the first level of a rack is offered.
+- **FR-003**: A sub-source MUST keep pointing at the same part when other parts are added, deleted or
+ reordered, when the part is moved or renamed, and across save / reopen.
+- **FR-004**: When the referenced part (or the instrument that holds it) is removed, the consumer
+ MUST hear no key and show its source as missing — as when a source track is deleted today — and an
+ undo that brings the part back MUST make the key work again. A project saved meanwhile stores no
+ source for that key.
+
+**Taps**
+
+- **FR-005**: For a sub-source, the Pre tap MUST deliver the part's raw signal: the part's instrument
+ output before its own insert chain (Drum Rack pad / rack chain inserts; Rhythm voice-FX) and before
+ any per-pad shaping applied after the instrument (the Drum Rack pad's decay envelope).
+- **FR-006**: For a sub-source, the Post tap MUST deliver the part's signal after its insert chain and
+ its own gain/pan (and, for a Drum Rack pad, its decay envelope) — exactly what the part contributes
+ to the sum — before it is summed with the other parts (before rack volume / Rhythm Glue and Volume).
+- **FR-007**: Whole-track sources MUST keep today's Pre/Post meaning unchanged.
+- **FR-007a**: A part referenced by at least one key MUST keep producing its Pre and Post key signal
+ while it is muted or silenced by another part's solo, without being heard in the mix. Parts no key
+ references MUST keep today's mute/solo behaviour (no render).
+
+**Route budget**
+
+- **FR-007b**: Whole-track and sub-source keys MUST share one pool of 16 distinct sources; several
+ consumers keying the same source and tap combination MUST share one route.
+- **FR-007c**: When the pool is full, the picker MUST show every source not already in use as
+ disabled with the hint "No free routes"; already-used sources stay selectable. Loading a project
+ that needs more than 16 sources MUST keep the first 16 and clear the rest, with a one-time notice.
+
+**Consumers and UI**
+
+- **FR-008**: Every sidechain consumer — all devices that accept a sidechain key (built-in and hosted
+ plug-in sidechain inputs) and the instrument-level key of Nota Flux (React) — MUST be able to select
+ sub-sources. Nota Flux's React MUST always listen to the Post tap of its source (whole track or
+ part) and shows no Pre/Post choice.
+- **FR-009**: The source picker MUST present sources as a tree: each track, and under tracks whose
+ instrument has parts, "Whole track" followed by the parts in their current order with their current
+ names. Tracks without parts stay single entries as today.
+- **FR-010**: The consuming device MUST show the selected source as "Track · Part" with the tap
+ (e.g. "Drums · Kick pre") on the card and in the Listen readout.
+- **FR-011**: Only parts that are actually used as a key MAY cost extra processing; a project with no
+ sub-source keys MUST perform as it does today.
+
+**Persistence, automation, agents**
+
+- **FR-012**: The selected sub-source and tap MUST be saved with the project and restored on load.
+- **FR-013**: Projects from older versions MUST load with every key as "Whole track", unchanged in
+ sound.
+- **FR-014**: The engine's public interface MUST let a client set and read a sub-source key for a
+ device and for an instrument-level (React) key, and the MCP device tools MUST expose the same.
+- **FR-015**: Choosing a part behaves like choosing a track today with respect to undo (not an undo
+ step); the plan MUST NOT make whole-track keys behave differently.
+
+**Verification**
+
+- **FR-016**: The end-to-end smoke test MUST cover a deterministic render of a Drum Rack with a kick
+ pad and a hat pad on alternating steps, keyed by a Compressor on another track via the kick pad, and
+ show gain reduction on kick hits and none on hat hits — for both Pre and Post.
+
+### Key Entities
+
+- **Sidechain source**: what a consumer listens to — a source track, an optional part of that track's
+ instrument, and a tap (Pre / Post). "No part" means the whole track.
+- **Part (sub-source)**: one sounding element of a multi-part instrument — a Drum Rack pad, an
+ Instrument Rack chain, or a Rhythm voice. Has a stable identity within its instrument, a display
+ name, and an order position (which may change without changing identity).
+- **Sidechain consumer**: a device that accepts a key (or an instrument with a React key); holds one
+ sidechain source plus its existing shaping settings (gain, mix).
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: In the reported setup (Drum Rack kick + hat, Compressor on a bass track keyed off the
+ kick pad), hat hits cause no gain reduction (below 0.1 dB) while kick hits cause the same reduction
+ as a whole-track key on a kick-only track, for both Pre and Post.
+- **SC-002**: A user can switch a key from a whole track to one pad in at most 3 interactions from the
+ device card (open picker, expand track, pick part; tap stays as set).
+- **SC-003**: After any sequence of add / delete-other / reorder / rename / save-reopen, the key still
+ follows the originally chosen part in 100% of the covered test cases.
+- **SC-004**: 100% of projects saved by previous versions open with their sidechain keys and their
+ rendered output unchanged.
+- **SC-005**: A project with no sub-source keys shows no measurable change in audio-thread CPU load
+ versus the previous version; each active sub-source key adds no more cost than a whole-track key.
+- **SC-005a**: A muted kick pad referenced by a key produces no audible output on the source track
+ yet drives the same gain reduction as when unmuted.
+- **SC-006**: All sidechain consumers listed in FR-008 can be keyed off a sub-source, verified per
+ consumer.
+
+## Assumptions
+
+- Racks: only the first level of a Drum Rack / Instrument Rack is offered as sub-sources; nested racks
+ inside a pad are reached through the outer pad.
+- Hosted plug-ins with multiple output buses are a later feature, not part of this one.
+- Devices inside rack chains as sidechain consumers are a separate follow-up (Clarifications
+ 2026-10-28).
+- Audio Effect Rack and MIDI Rack chains are not sub-sources.
+- Rhythm voices are identified by their fixed slot (1–8); their labels show the current voice name.
+- The rule about a track keying itself is unchanged and applies to its sub-sources too.
+- Saved projects need a format change with a migration; old whole-track keys map to "no part".
+- Nota Auto Shift is not offered parts: its key is the source track's MIDI notes (its MIDI
+ target), and a pad or voice has no notes of its own.
+- Each card keeps its own picker style (dropdown, flyout or menu); parts appear under their track
+ in each — indented in lists, as "Track · Part" in menus.
+- Pre/Post remain a per-consumer setting (as today), not a per-part one; Nota Flux's React has no
+ such setting and always uses Post.
+- The tree picker follows the existing Studio picker styling (`DESIGN.md`); no new design language.
+
+## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*
+
+- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)
+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned
+- [x] 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) — per-part capture buffers pre-allocated; part selection published with the routing snapshot
+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`
+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest` (FR-016)
+- [x] 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)
+- [x] UI change → follows `DESIGN.md` (Studio design language)
diff --git a/specs/050-sidechain-sub-sources/tasks.md b/specs/050-sidechain-sub-sources/tasks.md
new file mode 100644
index 00000000..989c1c70
--- /dev/null
+++ b/specs/050-sidechain-sub-sources/tasks.md
@@ -0,0 +1,181 @@
+---
+description: "Tasks: sidechain from individual pads, voices and chains"
+---
+
+# Tasks: Sidechain from individual pads, voices and chains
+
+**Input**: [spec.md](spec.md), [plan.md](plan.md), [research.md](research.md),
+[data-model.md](data-model.md), [contracts/c-abi.md](contracts/c-abi.md),
+[contracts/mcp.md](contracts/mcp.md), [quickstart.md](quickstart.md)
+
+**Tests**: requested by the spec (FR-016) — smoke tests in `tests/Nota.SmokeTest/SidechainPartTests.cs`,
+run by `scripts/build.sh` and alone with `--sidechain-parts`.
+
+**Path shorthands**: `E/` = `src/native/nota.engine/src/`, `H` = `src/native/nota.engine/include/nota/nota_engine.h`,
+`M/` = `src/managed/`, `T/` = `tests/Nota.SmokeTest/`.
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: can run in parallel (different files, no dependency on an unfinished task)
+- **[Story]**: US1…US5 from spec.md
+
+---
+
+## Phase 1: Setup
+
+- [X] T001 Add the test file `T/SidechainPartTests.cs` (SPDX header, `public static IEnumerable<(bool, string)> Run()`, empty for now) and register it in `T/Program.cs` both as the `--sidechain-parts` flag (pattern of `--preset-state`, ~L473) and in the full run (~L15203)
+- [X] T002 [P] Add a deterministic drum fixture for the tests: reuse an existing short WAV in `T/Fixtures/` or add a ≤ 50 ms kick-like and hat-like clip there (licence: generated in-repo); note its use in a comment at the top of `T/SidechainPartTests.cs` — done without a fixture: the tests generate their sine-burst WAVs at run time (as `DeviceCopyTests` does)
+
+---
+
+## Phase 2: Foundational (blocks every story)
+
+**Purpose**: part identity, part-aware route slots and the per-block tap hand-off — no instrument fills taps yet.
+
+- [X] T003 [P] `E/devices/Device.h` and `E/devices/Instrument.h`: non-virtual `std::atomic<uint64_t> scPart_{0}` with `uint64_t sidechainPart() const` / `void setSidechainPart(uint64_t)` on both base classes (0 = whole track; comment: "part id, see specs/050")
+- [X] T004 [P] `E/devices/Instrument.h`: `struct PartTap { uint64_t part; float* pre; float* post; };` and virtuals `int32_t partCount() const {return 0;}`, `uint64_t partId(int32_t) const {return 0;}`, `int32_t partIndex(uint64_t) const {return -1;}`, `std::string partName(int32_t) const {return {};}`, `void setPartTaps(const PartTap*, int32_t) {}` (audio thread; pointers valid for the coming render only; add, never overwrite)
+- [X] T005 `E/engine/Engine.h` + `E/engine/Engine.cpp`: `kMaxRoutes` 8 → 16; add `std::atomic<uint64_t> routeSlotPart_[kMaxRoutes]` (init 0); replace `routeSlotForTrack(id)` with `routeSlotFor(int32_t track, uint64_t part)` (keep `routeSlotForTrack(id)` as `routeSlotFor(id, 0)`); readers load track then part with acquire
+- [X] T006 `E/engine/Engine_Devices.cpp` `recomputeRouting()`: claim per distinct `(track, part)` from every consumer (`sidechainSourceTrackId()` + `sidechainPart()`, incl. rack children and the monitoring-audio claim with part 0); a part key claims only when the source track's instrument `partIndex(part) >= 0`; write `routeSlotPart_` before `routeSlotTrackId_` (release)
+- [X] T007 `E/engine/Engine_Render.cpp`: `feedDeviceKey`, `feedRackChildKeys` and the instrument React path look up `routeSlotFor(src, consumer.sidechainPart())` (React keeps `routeBus_` = post); the `keying` flag (~L2168) is true when the track owns *any* slot (whole or part)
+- [X] T008 `E/engine/Engine_Render.cpp` `renderLeafDry` (LeafPath::Instrument, ~L1927): before `renderInstrumentRaw`, build a stack `PartTap taps[kMaxRoutes]` from the slots with this track id and part ≠ 0 (pre → `routeBusPreNext_[s]`, post → `routeBusNext_[s]`) and call `t.instrument->setPartTaps(taps, n)`; call `setPartTaps(nullptr, 0)` after; nothing else when `n == 0`
+- [X] T009 `E/engine/Engine_Devices.cpp` + `E/engine/Engine_Rack.cpp`: every place that copies or clears a key copies / clears the part with the track id — device clone (~L698), move-to-track self-key clear (~L893, ~L1093), clipboard (`deviceClipboardSidechain` stays track-based), rack grouping (`Engine_Rack.cpp` ~L215), rack child clone; `setDeviceSidechainSource` / `setInstrumentSidechainSource` (whole-track setters) reset the part to 0
+- [X] T010 `E/engine/Engine.h` + `E/engine/Engine_Devices.cpp`: engine methods `setDeviceSidechainKey(track, dev, src, partIndex) → int` (0 ok, -1 bad, -2 no free route: a new distinct `(src, part)` when no slot is free leaves the key unchanged), `deviceSidechainKey(track, dev, &src, &partIndex)` (-1 whole, -2 missing), instrument variants, `sidechainRoutesFree()`, `sidechainRouteInUse(src, partIndex)`, `trackPartCount(track)`, `trackPartName(track, i)` — converting index ↔ id through the source track's instrument
+- [X] T011 `H` + `E/abi/nota_engine_device.cpp` (+ `E/abi/nota_engine_track.cpp` for the track part calls): the specs/050 block exactly as in [contracts/c-abi.md](contracts/c-abi.md) except the rack-child pair (T030)
+- [X] T012 [P] `M/Nota.Application/Engine/IAudioEngine.cs`, `M/Nota.Infrastructure/Interop/NativeMethods.Devices.cs`, `M/Nota.Infrastructure/Interop/NotaEngine.Devices.cs`: managed members per [data-model.md](data-model.md) (`TrackPartCount`, `TrackPartName`, `SetDeviceSidechainKey → int`, `DeviceSidechainKey → (int Source, int Part)`, instrument variants, `SidechainRoutesFree`, `SidechainRouteInUse`); stubs in every other `IAudioEngine` implementation (`RackEngineProxies.cs`, `RackCardView.cs` proxy switch: no parts, -1)
+- [X] T013 Smoke (in `T/SidechainPartTests.cs`): with no part keys, whole-track keys still duck as before (regression guard; copy the existing Compressor sidechain check shape) and `nota_sidechain_route_capacity` = 16
+
+**Checkpoint**: builds; existing smoke tests pass; nothing user-visible yet.
+
+---
+
+## Phase 3: User Story 1 — Duck the bass from just the kick pad (P1) 🎯 MVP
+
+**Goal**: a Compressor keys off one Drum Rack pad, Pre or Post, and the card shows "Drums · Kick pre".
+
+**Independent test**: quickstart.md automated 1–3; manual 1–4.
+
+### Tests
+
+- [X] T014 [P] [US1] `T/SidechainPartTests.cs` `KickPadOnly()`: Drum Rack (kick + hat Sampler pads from the T002 fixture, kick steps 1/3, hat 2/4), bass track with a sustained deterministic clip + Compressor keyed `(drums, kickIndex)`; offline render; per block `DeviceGainReduction` ≥ 3 dB in kick blocks, < 0.1 dB in hat blocks — once Post, once Pre (FR-016, SC-001)
+- [X] T015 [P] [US1] `T/SidechainPartTests.cs` `PreVsPost()`: Utility −20 dB on the kick pad → Pre GR within 0.5 dB of before, Post GR lower (FR-005/006)
+- [X] T016 [P] [US1] `T/SidechainPartTests.cs` `GhostKick()`: mute the kick pad → drums track peak in kick blocks drops (no kick in the mix) while bass GR stays ≥ 3 dB; solo the hat → same (FR-007a, SC-005a)
+
+### Implementation
+
+- [X] T017 [US1] `E/devices/racks/RackCore.{h,cpp}`: implement `partCount` (chains with an instrument rack kinds only; 0 for Audio Effect / MIDI racks), `partId(i)` = `chains[i].uid`, `partIndex(uid)` via the live snapshot, `partName(i)` = chain name or its instrument's display name — implemented on `RackInstrument` (the Instrument-facing class over RackCore), so Audio Effect / MIDI racks have no parts by construction
+- [X] T018 [US1] `E/devices/racks/RackInstrument.h`: store the per-block taps (`const PartTap* taps_ = nullptr; int32_t nTaps_ = 0;` + `setPartTaps` override) and a helper `const PartTap* tapFor(uint64_t uid) const` (linear scan, nullptr when `nTaps_ == 0`)
+- [X] T019 [US1] `E/devices/racks/DrumRack.cpp` `render`: per pad `tap = tapFor(c.uid)`; when muted / solo-gated and `tap == nullptr` keep today's `continue`; otherwise render (tapped-but-silent pads keep `meter` at 0 and skip the add into `out`). After `instrument->render` add `scratch_` into `tap->pre`; in the sum loop add `l*env*gL`, `r*env*gR` with pad gain/pan **without** rack volume `rv` into `tap->post`
+- [X] T020 [US1] `M/Nota.App/DeviceCards/SidechainSourcePicker.cs` (new, SPDX header): builder returning a ComboBox + `Func<string> SourceName` + sync action for a consumer given get/set delegates; items "Internal" then per track a row (whole track) and indented part rows from `TrackPartCount/Name`; rebuild on `DropDownOpened`; follow external changes (MCP) while closed; name format "Track · Part"; a `-2` set result shows the "No free routes" tooltip; styling per DESIGN.md (reuse the existing combo's sizes / palette)
+- [X] T021 [US1] `M/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs`: replace the `srcIds`/`srcNames` combo (~L353–L392) with the picker; `SourceName()` and the Listen readout (~L564) show "Drums · Kick pre/post"; picking any source still turns External on
+
+**Checkpoint**: US1 works end to end in the app and in the smoke test.
+
+---
+
+## Phase 4: User Story 2 — The key stays on the same pad (P1)
+
+**Goal**: reorder / add / delete-other / rename / delete+undo / save+reopen keep the key on its pad.
+
+**Independent test**: quickstart.md automated 4, 5, 9; manual 4–5.
+
+### Tests
+
+- [X] T022 [P] [US2] `T/SidechainPartTests.cs` `StableIdentity()`: key the kick, then move the kick pad to index 0, add a pad, delete the hat, rename the kick — after each, `DeviceSidechainKey` part = the kick's new index and the GR pattern of T014 holds (FR-003, SC-003)
+- [X] T023 [P] [US2] `T/SidechainPartTests.cs` `DormantKey()`: delete the kick pad → part -2 and GR < 0.1 dB everywhere; `nota_engine_undo` → part = original index and GR back; replace the Drum Rack with a Sampler → part -2 (FR-004)
+- [X] T024 [P] [US2] `T/SidechainPartTests.cs` `SaveReopen()`: save a project with a pad key (Pre) and a whole-track key, reopen → both keys with the same part / tap; open a v27 project (and `T/Fixtures/racks-v8`) → keys whole-track, render unchanged (FR-012/013, SC-004)
+
+### Implementation
+
+- [X] T025 [US2] `M/Nota.Infrastructure/Persistence/ProjectModel.cs`: `DeviceDto.SidechainPart`, `InstrumentDto.SidechainPart`, `NestedSidechainDto.Part` — `int`, default `-1` ("part index at save time on the source track's instrument; -1 whole track (specs/050, v28)")
+- [X] T026 [US2] `M/Nota.Infrastructure/Persistence/ProjectService.cs`: `CurrentFormatVersion` 27 → 28; save writes part from `DeviceSidechainKey` / `InstrumentSidechainKey` (a `-2` key saves as `SidechainSource = -1`); load keeps the deferred wiring (~L913–L930) and calls `SetDeviceSidechainKey` / `SetInstrumentSidechainKey` with the part; count `-2` results for T048
+- [X] T027 [US2] `M/Nota.Infrastructure/Persistence/ProjectMigrations.cs`: v27 → v28 no-op step with a comment (absent `SidechainPart` = -1)
+- [X] T028 [US2] `M/Nota.App/DeviceCards/SidechainSourcePicker.cs`: a part key reading -2 shows "Track · (missing)" in the combo and readouts
+- [X] T029 [US2] Verify `E/devices/racks/RackCore.cpp` chain reorder / duplicate / remove keep `uid` on survivors and that `duplicateChain` gives the copy a fresh uid (the key stays on the original); fix if not — verified: survivors keep `uid`; `duplicateChain` rebuilds the copy from the blob, so it gets a fresh one (covered by `StableKey`)
+- [X] T030 [US2] `H` + `E/abi/nota_engine_rack.cpp` + `E/engine/Engine_Rack.cpp`: `nota_rack_chain_sidechain_part` / `nota_rack_chain_set_sidechain_part` per contracts; managed `RackChainSidechainPart` / `RackChainSetSidechainPart` in `M/Nota.Application/Engine/IAudioEngine.cs`, `M/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs`, `NotaEngine.RackDev.cs`; `ProjectService.NestedLinks` saves `NestedSidechainDto.Part` and load restores it (keyed devices grouped into a rack keep their pad key)
+
+**Checkpoint**: US1 + US2 = the reported use case, shippable.
+
+---
+
+## Phase 5: User Story 3 — Key off a Nota Rhythm voice (P2)
+
+**Independent test**: quickstart.md automated 6 (Rhythm half).
+
+- [X] T031 [P] [US3] `T/SidechainPartTests.cs` `RhythmVoice()`: Rhythm with voice 1 (kick) on 1/3 and voice 5 (hat) on 2/4 → Compressor keyed `(rhythm, 0)` ducks on voice-1 steps only, Pre and Post; voice FX (Utility −20 dB) on voice 1 changes Post only; `TrackPartCount` = 8, names "1 Kick"…
+- [X] T032 [US3] `E/devices/instruments/RhythmMachine.{h,cpp}`: part surface (`partCount` 8, `partId(v)` = v+1, `partIndex(id)` = id−1 when 1..8, `partName(v)` = "{v+1} {voice name}"), `setPartTaps` storing the taps; in `render` per chunk write the panned voice output to `tap->pre[(base+j)*2…]` and `vbuf_[v]` after FX (or the same voice output when the voice has no FX) to `tap->post`; untapped voices unchanged
+
+---
+
+## Phase 6: User Story 4 — Key off an Instrument Rack chain (P2)
+
+**Independent test**: quickstart.md automated 6 (rack half).
+
+- [X] T033 [P] [US4] `T/SidechainPartTests.cs` `InstrumentRackChain()`: Instrument Rack with two Sampler chains on disjoint key zones playing alternate beats → key on chain 0 ducks on its beats only; reorder chains → still chain 0's sound; mute chain 0 → still ducks (ghost)
+- [X] T034 [US4] `E/devices/racks/RackInstrument.cpp` `render`: same tap / ghost logic as T019 (no decay VCA; post = after inserts × chain gain/pan, without `rv`); a muted MIDI chain that is tapped renders its events instead of only delivering them
+
+---
+
+## Phase 7: User Story 5 — Every sidechain consumer gets sub-sources (P2)
+
+**Independent test**: quickstart.md automated 7–8, manual 6; each consumer keyed off a pad reacts to it only.
+
+### Tests
+
+- [X] T035 [P] [US5] `T/SidechainPartTests.cs` `FluxReact()`: Flux React keyed `(drums, kick)` via `SetInstrumentSidechainKey` → its React reading moves on kick blocks only
+- [X] T036 [P] [US5] `T/SidechainPartTests.cs` `RoutePool()`: 16 distinct sources set → the 17th returns -2 and leaves the key unchanged, `SidechainRoutesFree` = 0; a second consumer of an in-use `(track, part)` returns 0; whole-track `SetDeviceSidechainSource` after a part key → part -1
+- [X] T037 [P] [US5] `T/SidechainPartTests.cs` `EveryConsumer()`: for kinds Auto Filter, Auto Gain, Ceiling, Dynamic EQ, Prism, Shutter, Vocoder — key off the kick pad and check the key arrives (device scope / reading non-zero in kick blocks, zero in hat blocks)
+
+### Implementation
+
+- [X] T038 [P] [US5] Switch to `SidechainSourcePicker`: `M/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs`, `AutoGainDeviceBody.cs`, `AutoShiftDeviceBody.cs`, `CeilingDeviceBody.cs`, `DynamicEqDeviceBody.cs`, `PrismDeviceBody.cs`, `ShutterDeviceBody.cs` (incl. its "External sidechain" switch's first-other-track pick, ~L314), `VocoderDeviceBody.cs` — cards keep their own menus: they take rows from `SidechainSourcePicker.Entries` / `MenuRows` (parts read "Drums · Kick"); Auto Shift is left on whole tracks — its key is the source's MIDI notes, which a pad doesn't have
+- [X] T039 [P] [US5] `M/Nota.App/DeviceCards/DeviceParamControls.cs` `SidechainSelector` (plug-ins, generic cards) and `M/Nota.App/DeviceCards/PluginCard.cs` use the picker
+- [X] T040 [P] [US5] `M/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs`: React source via the picker with `SetInstrumentSidechainKey` / `InstrumentSidechainKey`; no Pre/Post control (always Post)
+- [X] T041 [US5] `M/Nota.App/DeviceCards/SidechainSourcePicker.cs`: disable rows when `SidechainRoutesFree() == 0 && !SidechainRouteInUse(track, part)` with tooltip "No free routes"; disable a frozen track's part rows (tooltip: "Frozen — parts don't render") — the dropdown greys such rows; the menu-style cards leave them out
+- [X] T042 [US5] `M/Nota.Mcp/Tools/DeviceTools.cs`: `get_device_sidechain` + `sourcePart`, `sourceName`; `set_device_sidechain` + optional `sourcePart` (error text on -2); new `list_sidechain_sources`, `get_instrument_sidechain`, `set_instrument_sidechain` per [contracts/mcp.md](contracts/mcp.md); descriptions name the kick-pad recipe
+
+---
+
+## Phase 8: Polish & cross-cutting
+
+- [X] T043 [P] `CHANGELOG.md` `[Unreleased]` → Added: sidechain keys from a single Drum Rack pad, Instrument Rack chain or Nota Rhythm voice, Pre/Post, ghost parts; Changed: 16 sidechain routes
+- [X] T044 [P] `FEATURES.md` via the `nota-features` skill
+- [X] T045 [P] User manual EN + RU (`../nota-docs`) via the `nota-docs` skill: sidechain picker, ghost kick recipe; re-shoot the Compressor Sidechain tab — Devices (Sidechain), Compressor, Drum Rack, Flux pages EN + RU in ../nota-docs (uncommitted); the Compressor shot is visually unchanged, not retaken
+- [X] T046 Engine perf gate (specs/034) with no part keys and with 4 pad keys — record numbers in the PR (FR-011, SC-005) — the Callgrind gate needs Linux + valgrind (runs in CI on the PR); locally `scripts/bench-engine.sh` before/after on an M4 Max: no change beyond run-order noise (the 16-synth export swing follows whichever build runs second). A third run caught late blocks at 192 tracks · 64-sample buffers that didn't flip with the order: the route-slot scans are now bounded by the used count (research R6), after which the PR is no worse than develop (build/pr-050/issue-190)
+- [X] T047 Re-check the Nota Compliance Checklist in [spec.md](spec.md): SPDX headers on `SidechainPartTests.cs` and `SidechainSourcePicker.cs`; no audio-thread allocation in T008/T019/T032/T034
+- [X] T048 Project load: when T026 counted `-2` keys, show one notice ("Some sidechain keys were cleared: no free routes") through the existing load-warnings path in `M/Nota.Infrastructure/Persistence/ProjectService.cs`
+- [X] T049 `scripts/build.sh` green (smoke incl. `--sidechain-parts`); macOS manual pass of quickstart.md "Manual" with before/after screenshots for the PR (`nota-pr` skill) — build.sh green (SMOKE TEST PASSED, SCAN SCALE PASSED); the picker checked in a headless render (Compressor Sidechain tab + source list, dark / light; build/pr-050), which led to the closed box naming the track ("Drums · Kick"). Not driven in the live app
+- [X] T050 `/speckit-converge` → Converged
+
+---
+
+## Dependencies
+
+```text
+Setup (T001–T002) → Foundational (T003–T013) → US1 (T014–T021)
+US1 → US2 (needs pad keys) US1 → US4 (shares RackCore / tap helper T017–T018)
+Foundational → US3 (Rhythm is independent of racks)
+US1 (picker T020) → US5 (T038–T041); T010/T011 → T035–T036, T042
+US2 T026 → T048; all stories → Polish
+```
+
+Inside Foundational: T003, T004 ∥ → T005 → T006 → T007, T008 → T009 → T010 → T011 → T012 → T013.
+
+## Parallel examples
+
+- Foundational: T003 ∥ T004; T012 ∥ T013 once T011 is in.
+- US1: tests T014 ∥ T015 ∥ T016 (same file, distinct methods — merge-friendly if written by one hand; otherwise sequence), engine T017 → T018 → T019 ∥ UI T020 → T021.
+- US3 (T031–T032) can run alongside US1 once Foundational is done.
+- US5: T038 ∥ T039 ∥ T040 (different files), then T041; T042 any time after T011.
+- Polish: T043 ∥ T044 ∥ T045.
+
+## Implementation strategy
+
+1. **MVP = Foundational + US1 + US2** — the reported "duck the bass from the kick pad" with stable keys and saved projects.
+2. Then US3 and US4 (small: one render loop each, reusing the foundation).
+3. Then US5 (UI sweep + MCP) and Polish.
+4. Commit per phase in the repo's style; the user makes the commits and the PR.
+
+## Phase 9: Convergence
+
+- [X] T051 Show full-pool sources as disabled rows with the "No free routes" hint in the menu-style pickers (Auto Gain, Ceiling, Dynamic EQ, Prism, Shutter, Vocoder, Flux React) instead of leaving them out — `SidechainSourcePicker.MenuRows` and the cards' menu builders in `src/managed/Nota.App/DeviceCards/` per FR-007c (partial)
+- [X] T052 Cover the remaining edge cases in `tests/Nota.SmokeTest/SidechainPartTests.cs`: a frozen source track's part key is silent while its whole-track key still works; duplicating the consuming track and copy / paste of the keyed device keep the part key per spec Edge Cases (Frozen source track, Clipboard / duplicate) (partial)
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs
index a790380b..f3edb055 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs
@@ -463,8 +463,10 @@ internal sealed class AutoFilterDeviceBody : IDeviceBody
// ======================================================================
int centreTab = 0;
- // Sidechain key: the switch picks a source (a flyout with the tracks and the key gain).
- string SrcName(int id) => TrackNames.Of(engine, id);
+ // Sidechain key: the switch picks a source (a flyout with the tracks — and the pads / chains
+ // / voices of a track's instrument, indented under it, specs/050 — and the key gain).
+ SidechainKey Key() => engine.DeviceSidechainKey(track, di);
+ string KeyName() => SidechainSourcePicker.Name(engine, Key());
Control SidechainSwitch()
{
Border? host = null;
@@ -472,17 +474,19 @@ internal sealed class AutoFilterDeviceBody : IDeviceBody
{
var list = new StackPanel { Spacing = 1 };
var fly = new Flyout();
- void Item(string name, int id)
+ void Item(string name, SidechainKey k, bool indent = false, bool enabled = true, string? tip = null)
{
- bool cur = engine.DeviceSidechainSource(track, di) == id;
- var tb = new TextBlock { Text = name, FontSize = 10, Foreground = cur ? AccentBright : TextPrimary, FontWeight = cur ? FontWeight.SemiBold : FontWeight.Normal };
- var b = new Border { Padding = new Thickness(8, 3), CornerRadius = NotaRadius.Badge, Background = cur ? NotaPalette.AccentSubtle : Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
- b.PointerPressed += (_, e) => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); RefreshAll(); fly.Hide(); e.Handled = true; };
+ bool cur = Key() == k;
+ var tb = new TextBlock { Text = name, FontSize = 10, Foreground = !enabled ? TextDisabled : cur ? AccentBright : TextPrimary, FontWeight = cur ? FontWeight.SemiBold : FontWeight.Normal };
+ var b = new Border { Padding = new Thickness(indent ? 20 : 8, 3, 8, 3), CornerRadius = NotaRadius.Badge, Background = cur ? NotaPalette.AccentSubtle : Brushes.Transparent, Cursor = enabled ? new Cursor(StandardCursorType.Hand) : Cursor.Default, Child = tb };
+ if (tip != null) ToolTip.SetTip(b, tip);
+ if (enabled)
+ b.PointerPressed += (_, e) => { SidechainSourcePicker.SetDeviceKey(engine, track, di, k); ctx.NotifyChanged(); RefreshAll(); fly.Hide(); e.Handled = true; };
list.Children.Add(b);
}
- Item("None — this track's input", -1);
- for (int i = 0; i < engine.TrackCount; i++)
- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) Item(SrcName(ti.Id), ti.Id);
+ Item("None — this track's input", SidechainKey.None);
+ foreach (var en in SidechainSourcePicker.Entries(engine, track, Key()))
+ Item(en.Label, en.Key, en.IsPart, en.Enabled, en.Tip);
var gain = DeviceCardKit.SliderRow("KEY GAIN", () => (engine.DeviceSidechainGain(track, di) + 24) / 48.0,
v => engine.SetDeviceSidechainGain(track, di, (float)(v * 48 - 24)),
() => NotaNum.F($"{engine.DeviceSidechainGain(track, di):+0.0;−0.0;0.0} dB"), out _, bipolar: true,
@@ -496,8 +500,7 @@ internal sealed class AutoFilterDeviceBody : IDeviceBody
else ShowPicker();
}, out var sync, liveLabel: () =>
{
- int src = engine.DeviceSidechainSource(track, di);
- return src >= 0 ? "Key: " + SrcName(src) : "Sidechain key";
+ return engine.DeviceSidechainSource(track, di) >= 0 ? "Key: " + KeyName() : "Sidechain key";
});
host = sw;
readouts.Add(sync);
@@ -675,7 +678,7 @@ internal sealed class AutoFilterDeviceBody : IDeviceBody
parts.Add(NotaNum.F($"mix {Pct(P(DryWet))}"));
break;
}
- if (engine.DeviceSidechainSource(track, di) >= 0) parts.Add("key: " + SrcName(engine.DeviceSidechainSource(track, di)));
+ if (engine.DeviceSidechainSource(track, di) >= 0) parts.Add("key: " + KeyName());
return string.Join(" · ", parts);
}
readouts.Add(() =>
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs
index a2eac4ec..621445cb 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs
@@ -68,7 +68,8 @@ internal sealed class AutoGainDeviceBody : IDeviceBody
double MaxG() => MaxGainDb(P(MaxGain));
// ---- reference track (the device's sidechain) ---------------------------------------
- string TrackName(int id) => TrackNames.Of(engine, id);
+ // The reference may be one pad / chain / voice of a track (specs/050).
+ string RefName() => SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di));
int Ref() => engine.DeviceSidechainSource(track, di);
bool HasRef() => Ref() >= 0;
@@ -155,7 +156,9 @@ internal sealed class AutoGainDeviceBody : IDeviceBody
}
// A dropdown menu under a control.
- void Menu(Control at, IEnumerable<(string Label, bool Current, Action Pick)?> items)
+ // Key-source rows (specs/050) go after the others, unavailable ones disabled.
+ void Menu(Control at, IEnumerable<(string Label, bool Current, Action Pick)?> items,
+ IEnumerable<(string Label, bool Checked, Action? Pick, string? Tip)>? sources = null)
{
var fly = new MenuFlyout();
foreach (var it in items)
@@ -167,6 +170,8 @@ internal sealed class AutoGainDeviceBody : IDeviceBody
mi.Click += (_, _) => { pk(); RefreshAll(); };
fly.Items.Add(mi);
}
+ foreach (var row in sources ?? Array.Empty<(string, bool, Action?, string?)>())
+ fly.Items.Add(SidechainSourcePicker.MenuItemFor(row, RefreshAll));
fly.ShowAt(at);
}
@@ -184,13 +189,7 @@ internal sealed class AutoGainDeviceBody : IDeviceBody
}
list.Add(null);
list.Add(("Fixed target — no reference", !HasRef(), () => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); }));
- for (int i = 0; i < engine.TrackCount; i++)
- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track)
- {
- int id = ti.Id;
- list.Add(("Match track: " + TrackName(id), Ref() == id, () => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); }));
- }
- Menu(at, list);
+ Menu(at, list, SidechainSourcePicker.MenuRows(engine, track, di, ctx.NotifyChanged, "Match track: "));
}
// ======================================================================
@@ -266,7 +265,7 @@ internal sealed class AutoGainDeviceBody : IDeviceBody
var targetRow = Slider("TARGET", Target, TargetF,
"Target loudness, −36 … 0 LUFS. Click the value for the standards or to match another track's loudness (a reference); drag the dashed line in the graph for the same",
38, 50, dim: HasRef,
- valueOverride: () => HasRef() ? ("REF " + TrackName(Ref()), TextSecondary) : ("", null),
+ valueOverride: () => HasRef() ? ("REF " + RefName(), TextSecondary) : ("", null),
valueClick: TargetMenu);
var trimRow = Slider("TRIM", Trim, TrimF, "Trim — a fixed offset after the correction, −12 … +12\u2009dB (the output then sits that far off the target)", 38, 50, bipolar: true);
@@ -458,7 +457,7 @@ internal sealed class AutoGainDeviceBody : IDeviceBody
else
{
foot = (locked ? "On target" : "Catching up") + " · " + ScaleLong[si] + " · window " + WindowF(P(WindowP));
- if (HasRef()) foot += " · matching " + TrackName(Ref());
+ if (HasRef()) foot += " · matching " + RefName();
else if (Math.Abs(trim) > 0.05) foot += " · trim " + Sgn(trim) + "\u2009dB";
}
statusLeft.Text = foot; statusLeft.Foreground = footInk;
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs
index 34adad95..c1ff35bb 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs
@@ -211,7 +211,9 @@ internal sealed class CeilingDeviceBody : IDeviceBody
}
// A dropdown: [label value ▾] opens `items`; the current one is dotted.
- Border Drop(string caps, Func<string> text, Func<bool> hot, Func<IEnumerable<(string Label, bool Current, Action Pick)>> items, string tip, int learnParam = -1)
+ // sources: key-source rows (specs/050) after the items, unavailable ones disabled.
+ Border Drop(string caps, Func<string> text, Func<bool> hot, Func<IEnumerable<(string Label, bool Current, Action Pick)>> items, string tip, int learnParam = -1,
+ Func<IEnumerable<(string Label, bool Checked, Action? Pick, string? Tip)>>? sources = null)
{
var name = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
var chev = new Glyph(GlyphKind.ChevronDown, 7) { Margin = new Thickness(6, 0, 0, 0) };
@@ -245,31 +247,27 @@ internal sealed class CeilingDeviceBody : IDeviceBody
mi.Click += (_, _) => { pk(); RefreshAll(); };
fly.Items.Add(mi);
}
+ if (sources != null)
+ foreach (var row in sources()) fly.Items.Add(SidechainSourcePicker.MenuItemFor(row, RefreshAll));
fly.ShowAt(box);
e.Handled = true;
};
return box;
}
- // Key source: Internal, or another track (the device's sidechain routing).
- string SrcName(int id) => TrackNames.Of(engine, id);
+ // Key source: Internal, another track, or one pad / chain / voice of it (the device's
+ // sidechain routing, specs/050).
int Src() => engine.DeviceSidechainSource(track, di);
bool ExtOn() => Src() >= 0;
- string KeyName() => ExtOn() ? SrcName(Src()) : "Internal";
+ string KeyName() => SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di));
Control KeyDrop() => Drop("SC", KeyName, ExtOn, () =>
{
- var list = new List<(string, bool, Action)>
+ return new List<(string, bool, Action)>
{
("Internal — this track", !ExtOn(), () => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); }),
};
- for (int i = 0; i < engine.TrackCount; i++)
- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track)
- {
- int id = ti.Id;
- list.Add((SrcName(id), Src() == id, () => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); }));
- }
- return list;
- }, "Key source — Internal limits on this track's own peaks; pick another track to duck this one when that one peaks");
+ }, "Key source — Internal limits on this track's own peaks; pick another track to duck this one when that one peaks",
+ sources: () => SidechainSourcePicker.MenuRows(engine, track, di, ctx.NotifyChanged));
Control TargetDrop() => Drop("", () => TargetF(P(Target)), () => false, () =>
{
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs
index 48880552..d1ccb982 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs
@@ -352,44 +352,28 @@ internal sealed class CompressorDeviceBody : IDeviceBody
// ======================================================================
// CENTRE — Sidechain
// ======================================================================
- var srcIds = new List<int> { -1 };
- var srcNames = new List<string> { "Internal" };
- for (int i = 0; i < engine.TrackCount; i++)
- {
- if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;
- srcIds.Add(ti.Id);
- srcNames.Add(TrackNames.Of(engine, ti));
- }
- string SourceName() { int k = srcIds.IndexOf(engine.DeviceSidechainSource(track, di)); return k > 0 ? srcNames[k] : "Internal"; }
+ // The key source: a track, or one pad / chain / voice of it (specs/050).
+ var picker = new SidechainSourcePicker(engine, track, () => engine.DeviceSidechainKey(track, di),
+ (src, part) => engine.SetDeviceSidechainKey(track, di, src, part));
+ string SourceName() => picker.SourceName();
bool ExtActive() => Sc(S_ExtKey) > 0.5;
Control SidechainTab()
{
- var combo = new ComboBox { FontSize = 8, Height = 18, MinHeight = 18, MinWidth = 92, Padding = new Thickness(6, 0), VerticalAlignment = VerticalAlignment.Center };
- foreach (var n in srcNames) combo.Items.Add(n);
- combo.SelectedIndex = Math.Max(0, srcIds.IndexOf(engine.DeviceSidechainSource(track, di)));
- bool syncing = false;
+ var combo = picker.Combo;
// The source can change elsewhere (MCP, undo): follow it while the list is closed.
- readouts.Add(() =>
- {
- if (combo.IsDropDownOpen) return;
- int want = Math.Max(0, srcIds.IndexOf(engine.DeviceSidechainSource(track, di)));
- if (combo.SelectedIndex != want) { syncing = true; combo.SelectedIndex = want; syncing = false; }
- });
- combo.SelectionChanged += (_, _) =>
+ readouts.Add(picker.Sync);
+ picker.Picked += k =>
{
- int s = combo.SelectedIndex;
- if (syncing || s < 0 || s >= srcIds.Count) return;
- engine.SetDeviceSidechainSource(track, di, srcIds[s]);
// Picking a source means using it.
- if (srcIds[s] >= 0 && !On(External)) SetP(External, 1);
+ if (k.Source >= 0 && !On(External)) SetP(External, 1);
ctx.NotifyChanged();
};
- ToolTip.SetTip(combo, "Key source — Internal keys off this track; pick another track to duck or pump against it");
+ ToolTip.SetTip(combo, "Key source — Internal keys off this track; pick another track, or one pad or chain of it, to duck or pump against it");
var tap = Segments(new[] { "Pre", "Post" }, () => engine.DeviceSidechainTapPre(track, di) ? 0 : 1,
i => { engine.SetDeviceSidechainTapPre(track, di, i == 0); ctx.NotifyChanged(); }, out var tapSync);
readouts.Add(tapSync);
- ToolTip.SetTip(tap, "Where the source track is tapped: before its effects and fader, or after");
+ ToolTip.SetTip(tap, "Where the source is tapped: before its effects and fader, or after — for a pad or chain, before its own effects, or after them and its level");
var info = Mono("", 7, TextTertiary); info.HorizontalAlignment = HorizontalAlignment.Right;
readouts.Add(() => info.Text = NotaNum.F($"HP {HpF(P(ScHP))} · LP {LpF(P(ScLP))} · Q {P(ScQ):0.0}"));
var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*"), ColumnSpacing = 6, Height = 18 };
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs
index 53aab6d7..eb6690af 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs
@@ -84,8 +84,9 @@ internal sealed class DynamicEqDeviceBody : IDeviceBody
static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
- // Key source: the device's sidechain routing (a track), picked from a menu.
- string SrcName(int id) => TrackNames.Of(engine, id);
+ // Key source: the device's sidechain routing (a track, or one pad / chain / voice of it,
+ // specs/050), picked from a menu.
+ string KeyName() => SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di), "none");
int Src() => engine.DeviceSidechainSource(track, di);
void ShowKeyMenu(Control at)
{
@@ -94,14 +95,8 @@ internal sealed class DynamicEqDeviceBody : IDeviceBody
none.Click += (_, _) => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); RefreshAll(); };
fly.Items.Add(none);
fly.Items.Add(new Separator());
- for (int i = 0; i < engine.TrackCount; i++)
- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track)
- {
- int id = ti.Id;
- var mi = new MenuItem { Header = SrcName(id), ToggleType = MenuItemToggleType.Radio, IsChecked = Src() == id };
- mi.Click += (_, _) => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); RefreshAll(); };
- fly.Items.Add(mi);
- }
+ foreach (var row in SidechainSourcePicker.MenuRows(engine, track, di, () => { ctx.NotifyChanged(); RefreshAll(); }))
+ fly.Items.Add(SidechainSourcePicker.MenuItemFor(row));
fly.ShowAt(at);
}
@@ -418,7 +413,7 @@ internal sealed class DynamicEqDeviceBody : IDeviceBody
parts.Add(band);
bool anyExt = false;
for (int b = 0; b < DynEq.Bands; b++) if (IsDyn(b) && KeyExt(b)) anyExt = true;
- if (anyExt) parts.Add("key " + (Src() >= 0 ? SrcName(Src()) : "none"));
+ if (anyExt) parts.Add("key " + KeyName());
return string.Join(" · ", parts);
}
var nowRead = Mono("", 8, TextTertiary);
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs
index 1e9a83d0..f153f7b8 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs
@@ -512,14 +512,14 @@ internal sealed class PrismDeviceBody : IDeviceBody
new StackPanel { Spacing = 2, Children = { meterR, Center(Caps("R")) } }, scale } };
var top = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { K(Output, "OUTPUT", v => DbF((v - 0.5) * 48), 38, 54), meters } };
- // Sidechain source (None + every other track).
+ // Sidechain source (None + every other track, and the pads / chains / voices of a
+ // track's instrument, specs/050).
var scName = new TextBlock { FontSize = 8, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
bool scOk = engine.DeviceAcceptsSidechain(track, di);
- string SrcName(int id) { string n = TrackNames.Of(engine, id); return n == "—" ? "None" : n; }
readouts.Add(() =>
{
int src = scOk ? engine.DeviceSidechainSource(track, di) : -1;
- scName.Text = !scOk ? "n/a in a rack" : src < 0 ? "None — own input" : SrcName(src);
+ scName.Text = !scOk ? "n/a in a rack" : src < 0 ? "None — own input" : SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di));
scName.Foreground = src >= 0 ? TxtC : Txt2;
});
var scBox = new Border { Height = 16, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 0),
@@ -530,18 +530,17 @@ internal sealed class PrismDeviceBody : IDeviceBody
{
if (!e.GetCurrentPoint(scBox).Properties.IsLeftButtonPressed || !scOk) return;
var fly = new MenuFlyout();
- int cur = engine.DeviceSidechainSource(track, di);
- void Item(string name, int id)
+ void Changed() { ctx.NotifyChanged(); foreach (var a in readouts) a(); }
+ void Item(string name, bool on, Action pick)
{
var mi = new MenuItem { Header = name };
- mi.ToggleType = MenuItemToggleType.Radio; mi.IsChecked = id == cur;
- mi.Click += (_, _) => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); foreach (var a in readouts) a(); };
+ mi.ToggleType = MenuItemToggleType.Radio; mi.IsChecked = on;
+ mi.Click += (_, _) => pick();
fly.Items.Add(mi);
}
- Item("None — own input", -1);
+ Item("None — own input", engine.DeviceSidechainSource(track, di) < 0, () => { engine.SetDeviceSidechainSource(track, di, -1); Changed(); });
fly.Items.Add(new Separator());
- for (int i = 0; i < engine.TrackCount; i++)
- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) Item(SrcName(ti.Id), ti.Id);
+ foreach (var row in SidechainSourcePicker.MenuRows(engine, track, di, Changed)) fly.Items.Add(SidechainSourcePicker.MenuItemFor(row));
fly.ShowAt(scBox);
e.Handled = true;
};
@@ -657,7 +656,7 @@ internal sealed class PrismDeviceBody : IDeviceBody
{
var autos = Enumerable.Range(0, 3).Where(b => BandActive(b) && On(BP(b, AutoRelease))).Select(b => PrismInk.Names[b]).ToList();
int src = engine.DeviceAcceptsSidechain(track, di) ? engine.DeviceSidechainSource(track, di) : -1;
- string sc = src >= 0 ? "sidechain: " + TrackNames.Of(engine, src) : "own input";
+ string sc = src >= 0 ? "sidechain: " + SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di)) : "own input";
return Inv($"{(On(Detect) ? "RMS" : "Peak")} detector · {(autos.Count > 0 ? "auto release on " + string.Join(", ", autos) : "fixed release")} · {sc}");
}
default:
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs
index 0f970af0..1043c927 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs
@@ -127,11 +127,11 @@ internal sealed class ShutterDeviceBody : IDeviceBody
int WindowIdx() { double s = Sc(S_WindowSec); return s <= 0 ? 1 : s < 0.5 ? 0 : s < 2 ? 1 : 2; }
int State() => Math.Clamp((int)Math.Round(Sc(S_State)), 0, 4);
- // Sidechain key: the source track and whether it is in use.
- string SrcName(int id) => TrackNames.Of(engine, id);
+ // Sidechain key: the source (a track, or one pad / chain / voice of it, specs/050) and
+ // whether it is in use.
int Src() => engine.DeviceSidechainSource(track, di);
bool ExtOn() => On(ExternalKey) && Src() >= 0;
- string KeyName() => ExtOn() ? SrcName(Src()) : "Internal";
+ string KeyName() => ExtOn() ? SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di)) : "Internal";
// ---- small builders ---------------------------------------------------------
static TextBlock Caps(string t, IBrush? c = null, double fs = NotaType.KnobLabel) => new()
@@ -279,28 +279,28 @@ internal sealed class ShutterDeviceBody : IDeviceBody
box.BorderBrush = ext ? NotaPalette.BorderStrong : BorderDef;
chev.Foreground = ext ? TextSecondary : TextTertiary;
});
- ToolTip.SetTip(box, "Key source — Internal keys off this track; pick another track to gate or duck against it");
+ ToolTip.SetTip(box, "Key source — Internal keys off this track; pick another track, or one pad or chain of it, to gate or duck against it");
Learn(box, ExternalKey);
box.PointerPressed += (_, e) =>
{
if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;
var fly = new MenuFlyout();
- void Item(string label, int id)
+ void Item(string label, bool cur, Action pick)
{
- bool cur = id < 0 ? !ExtOn() : ExtOn() && Src() == id;
var mi = new MenuItem { Header = label };
mi.ToggleType = MenuItemToggleType.Radio; mi.IsChecked = cur;
- mi.Click += (_, _) =>
- {
- engine.SetDeviceSidechainSource(track, di, id);
- if (id >= 0 && !On(ExternalKey)) SetP(ExternalKey, 1f);
- ctx.NotifyChanged(); RefreshAll();
- };
+ mi.Click += (_, _) => pick();
fly.Items.Add(mi);
}
- Item("Internal — this track", -1);
- for (int i = 0; i < engine.TrackCount; i++)
- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) Item(SrcName(ti.Id), ti.Id);
+ Item("Internal — this track", !ExtOn(), () => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); RefreshAll(); });
+ // Picking a source means using it.
+ void Picked()
+ {
+ if (Src() >= 0 && !On(ExternalKey)) SetP(ExternalKey, 1f);
+ ctx.NotifyChanged(); RefreshAll();
+ }
+ foreach (var row in SidechainSourcePicker.MenuRows(engine, track, di, Picked))
+ fly.Items.Add(SidechainSourcePicker.MenuItemFor(row with { Checked = row.Checked && ExtOn() }));
fly.ShowAt(box);
e.Handled = true;
};
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/VocoderDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/VocoderDeviceBody.cs
index 9c71b3ea..ae6c10ce 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/VocoderDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/VocoderDeviceBody.cs
@@ -204,7 +204,7 @@ internal sealed class VocoderDeviceBody : IDeviceBody
readouts.Add(() =>
{
bool has = HasTrack(), use = CarrierI() == 2;
- srcName.Text = has ? TrackNames.Of(engine, Source()) : "None";
+ srcName.Text = has ? SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di)) : "None";
srcName.Foreground = has && use ? TextPrimary : TextDisabled;
dot.Background = has ? ArrangementView.TrackBrush(ArrangementView.EffectiveColorIndex(engine, Source())) : NotaPalette.Rule;
});
@@ -214,21 +214,29 @@ internal sealed class VocoderDeviceBody : IDeviceBody
{
if (!e.GetCurrentPoint(picker).Properties.IsLeftButtonPressed) return;
var fly = new MenuFlyout();
- void Add(int id, string name)
+ var cur = HasTrack() ? engine.DeviceSidechainKey(track, di) : SidechainKey.None;
+ void Add(SidechainKey k, string name, bool enabled = true, string? tip = null)
{
- // The current source is ticked, like every choice menu (spec 034).
- var mi = new MenuItem { Header = name, ToggleType = MenuItemToggleType.Radio, IsChecked = id == (HasTrack() ? Source() : -1) };
+ // The current source is ticked, like every choice menu (spec 034); one the route
+ // pool can't take is shown disabled with the reason.
+ var mi = new MenuItem { Header = name, ToggleType = MenuItemToggleType.Radio, IsChecked = k == cur, IsEnabled = enabled };
+ if (tip != null) ToolTip.SetTip(mi, tip);
mi.Click += (_, _) =>
{
- engine.SetDeviceSidechainSource(track, di, id);
- if (id >= 0 && CarrierI() != 2) SetP(Carrier, 1); // picking a track means using it
+ if (!SidechainSourcePicker.SetDeviceKey(engine, track, di, k)) return; // no free route
+ if (k.Source >= 0 && CarrierI() != 2) SetP(Carrier, 1); // picking a track means using it
ctx.NotifyChanged(); RefreshAll();
};
fly.Items.Add(mi);
}
- Add(-1, "None");
+ Add(SidechainKey.None, "None");
fly.Items.Add(new Separator());
- foreach (var (id, name, _) in Candidates()) Add(id, name);
+ // The candidate tracks, each with its pads / chains / voices (specs/050).
+ var ok = new HashSet<int>();
+ foreach (var c in Candidates()) ok.Add(c.Id);
+ foreach (var en in SidechainSourcePicker.Entries(engine, track, cur))
+ if (ok.Contains(en.Key.Source))
+ Add(en.Key, SidechainSourcePicker.Name(engine, en.Key), en.Enabled, en.Tip);
fly.ShowAt(picker);
e.Handled = true;
};
diff --git a/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs b/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs
index 5a2ee026..fb97b091 100644
--- a/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs
+++ b/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs
@@ -76,25 +76,15 @@ internal static class DeviceParamControls
int di = index;
var label = new TextBlock { Text = "Sidechain", FontSize = 9, FontWeight = FontWeight.Medium, Foreground = TextTertiary };
- // Source: "None" first, then every track except this one.
- var ids = new List<int> { -1 };
- var combo = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch, FontSize = 9 };
- combo.Items.Add("None");
- int n = engine.TrackCount;
- for (int i = 0; i < n; i++)
- {
- if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;
- ids.Add(ti.Id);
- combo.Items.Add(TrackNames.Of(engine, ti));
- }
- combo.SelectedIndex = Math.Max(0, ids.IndexOf(engine.DeviceSidechainSource(track, di)));
- combo.SelectionChanged += (_, _) =>
- {
- int sel = combo.SelectedIndex;
- if (sel < 0 || sel >= ids.Count) return;
- engine.SetDeviceSidechainSource(track, di, ids[sel]);
- ctx.NotifyChanged();
- };
+ // Source: "None" first, then every track except this one, each with its pads / chains /
+ // voices (specs/050).
+ var picker = new SidechainSourcePicker(engine, track, () => engine.DeviceSidechainKey(track, di),
+ (src, part) => engine.SetDeviceSidechainKey(track, di, src, part), "None");
+ var combo = picker.Combo;
+ combo.HorizontalAlignment = HorizontalAlignment.Stretch;
+ combo.FontSize = 9;
+ picker.Picked += _ => ctx.NotifyChanged();
+ ctx.AddDeviceRefresher(picker.Sync); // follow MCP / project edits, and pads coming and going
// Tap point: a small two-state toggle (Post FX ⇄ Pre FX).
var tapText = new TextBlock { FontSize = 9, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center };
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs
index 6e5bf4a9..62e23bd7 100644
--- a/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs
@@ -231,10 +231,17 @@ internal sealed class FluxInstrumentCard : IInstrumentCard
Padding = new Thickness(6, 0, 5, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
Child = new DockPanel { Children = { Docked(srcChevron, Dock.Right), srcText } },
};
- ToolTip.SetTip(srcField, "Choose the track Flux listens to");
- void SetSource(int id)
+ ToolTip.SetTip(srcField, "Choose the track Flux listens to — or one pad, chain or voice of it");
+ // The source may be one pad / chain / voice of a track (specs/050); React always hears it
+ // after its effects (Post).
+ string KeyName()
{
- engine.SetInstrumentSidechainSource(track, id);
+ var k = engine.InstrumentSidechainKey(track);
+ return k.Source >= 0 && k.Part != SidechainKey.WholeTrack ? SidechainSourcePicker.Name(engine, k, "No source") : SourceName(k.Source);
+ }
+ void SetSource(SidechainKey k)
+ {
+ if (engine.SetInstrumentSidechainKey(track, k.Source, k.Part) == -2) return; // no free route
live = engine.InstrumentSidechainSource(track) >= 0;
onsetLog.Clear(); perBar = 0;
ctx.NotifyChanged();
@@ -244,17 +251,22 @@ internal sealed class FluxInstrumentCard : IInstrumentCard
{
if (!e.GetCurrentPoint(srcField).Properties.IsLeftButtonPressed) return;
e.Handled = true;
- int cur = engine.InstrumentSidechainSource(track);
+ var cur = engine.InstrumentSidechainKey(track);
var flyout = new MenuFlyout();
- var none = new MenuItem { Header = "No source", ToggleType = MenuItemToggleType.Radio, IsChecked = cur < 0 };
- none.Click += (_, _) => SetSource(-1);
+ var none = new MenuItem { Header = "No source", ToggleType = MenuItemToggleType.Radio, IsChecked = cur.Source < 0 };
+ none.Click += (_, _) => SetSource(SidechainKey.None);
flyout.Items.Add(none);
+ var number = new Dictionary<int, int>(); // track id → its row number
for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti)) number[ti.Id] = i + 1;
+ foreach (var en in SidechainSourcePicker.Entries(engine, track, cur))
{
- if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;
- int id = ti.Id;
- var mi = new MenuItem { Header = $"{i + 1} · {SourceName(id)}", ToggleType = MenuItemToggleType.Radio, IsChecked = id == cur };
- mi.Click += (_, _) => SetSource(id);
+ var k = en.Key;
+ string header = en.IsPart ? SidechainSourcePicker.Name(engine, k) : $"{number[k.Source]} · {SourceName(k.Source)}";
+ // No free route, or a frozen track's part: shown disabled with the reason.
+ var mi = new MenuItem { Header = header, ToggleType = MenuItemToggleType.Radio, IsChecked = k == cur, IsEnabled = en.Enabled };
+ if (en.Tip != null) ToolTip.SetTip(mi, en.Tip);
+ mi.Click += (_, _) => SetSource(k);
flyout.Items.Add(mi);
}
flyout.ShowAt(srcField);
@@ -294,8 +306,7 @@ internal sealed class FluxInstrumentCard : IInstrumentCard
listen.Knob.IsDim = !live;
reactCap.Foreground = live ? NotaPalette.TealBright : TextTertiary;
reactSub.Foreground = live ? NotaPalette.TextMuted : TextDisabled;
- int src = engine.InstrumentSidechainSource(track);
- srcText.Text = SourceName(src);
+ srcText.Text = KeyName();
srcText.Foreground = live ? TextPrimary : TextDisabled;
srcField.Background = live ? NotaPalette.SurfaceRaised : NotaPalette.BgSunken;
targetHint.Text = TargetLine();
@@ -389,7 +400,7 @@ internal sealed class FluxInstrumentCard : IInstrumentCard
for (int i = 0; i < 4; i++) parts.Add($"{WorldNames[i]} {Pct((float)w[i])}");
return $"Vector x {Coord(G("vecx"))} · y {Coord(G("vecy"))} → {string.Join(" · ", parts)} · react off";
}
- string src = SourceName(engine.InstrumentSidechainSource(track));
+ string src = KeyName();
string what = TargetIdx() switch
{
3 => $"vector x {Coord(G("vecx"))} → {Coord(effX)}",
diff --git a/src/managed/Nota.App/DeviceCards/PluginCard.cs b/src/managed/Nota.App/DeviceCards/PluginCard.cs
index 4522e0a7..a5f60df7 100644
--- a/src/managed/Nota.App/DeviceCards/PluginCard.cs
+++ b/src/managed/Nota.App/DeviceCards/PluginCard.cs
@@ -153,10 +153,7 @@ internal static class PluginCard
// S has no room for the sidechain controls: it names the source; L edits it.
private static Control SidechainLine(IAudioEngine e, int t, int di)
{
- int src = e.DeviceSidechainSource(t, di);
- string label = "None";
- for (int i = 0, n = e.TrackCount; i < n && src >= 0; i++)
- if (e.TryGetTrackInfo(i, out var ti) && ti.Id == src) { label = TrackNames.Of(e, ti); break; }
+ string label = SidechainSourcePicker.Name(e, e.DeviceSidechainKey(t, di), "None");
var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Margin = new Thickness(0, 0, 0, 3) };
Fact(g, 0, "Sidechain", label);
return g;
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
index 4bebdd42..d7008209 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
@@ -894,6 +894,8 @@ internal class RackChainDeviceEngineProxy : System.Reflection.DispatchProxy
case nameof(Nota.Application.IAudioEngine.DeviceAction): Access.ChainDeviceAction(Chain, Dev, (int)args![2]!, (int)args![3]!, (float)args![4]!); return null;
case nameof(Nota.Application.IAudioEngine.DeviceAcceptsSidechain): return false;
case nameof(Nota.Application.IAudioEngine.DeviceSidechainSource): return -1;
+ case nameof(Nota.Application.IAudioEngine.DeviceSidechainKey): return Nota.Application.SidechainKey.None;
+ case nameof(Nota.Application.IAudioEngine.SetDeviceSidechainKey): return -1;
case nameof(Nota.Application.IAudioEngine.DeviceSidechainGain): return 0f;
case nameof(Nota.Application.IAudioEngine.SetDeviceSidechainSource):
case nameof(Nota.Application.IAudioEngine.SetDeviceSidechainGain):
diff --git a/src/managed/Nota.App/DeviceCards/SidechainSourcePicker.cs b/src/managed/Nota.App/DeviceCards/SidechainSourcePicker.cs
new file mode 100644
index 00000000..dd6b551b
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/SidechainSourcePicker.cs
@@ -0,0 +1,237 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The sidechain key source dropdown every keyed card shares (specs/050). It lists "Internal"
+// (no key), then every other track — and, under a track whose instrument has parts (a Drum
+// Rack's pads, an Instrument Rack's chains, Nota Rhythm's voices), each part indented: the
+// tree "Drums ▸ Whole track / Kick / Snare …" as one flat list, so a pad is two clicks away.
+// While closed the list follows the key (MCP, project load) and rebuilds when the tracks, their
+// parts or the route pool change (pads come and go while the card is up). Sources the route
+// pool can't take are greyed.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Templates;
+using Avalonia.Input;
+using Avalonia.Interactivity;
+using Avalonia.Layout;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal sealed class SidechainSourcePicker
+{
+ private readonly IAudioEngine _engine;
+ private readonly int _ownTrack;
+ private readonly Func<SidechainKey> _get;
+ private readonly Func<int, int, int> _set;
+ private readonly string _none;
+ private readonly List<SidechainKey> _keys = new();
+ private string _shape = "";
+ private bool _syncing;
+
+ /// <summary>The dropdown, styled like the cards' other compact combos.</summary>
+ public ComboBox Combo { get; }
+
+ /// <summary>A source was picked (after it was set): the card's own follow-up, such as
+ /// switching External on.</summary>
+ public event Action<SidechainKey>? Picked;
+
+ /// <param name="get">The consumer's key now.</param>
+ /// <param name="set">Set (source, part); returns 0, or -2 when no route is free.</param>
+ /// <param name="none">The no-key entry ("Internal" for a detector, "None" for React).</param>
+ public SidechainSourcePicker(IAudioEngine engine, int ownTrack, Func<SidechainKey> get, Func<int, int, int> set,
+ string none = "Internal", double minWidth = 92)
+ {
+ _engine = engine;
+ _ownTrack = ownTrack;
+ _get = get;
+ _set = set;
+ _none = none;
+ Combo = new ComboBox
+ {
+ FontSize = 8, Height = 18, MinHeight = 18, MinWidth = minWidth, Padding = new Thickness(6, 0),
+ VerticalAlignment = VerticalAlignment.Center,
+ };
+ // The open list shows a part by its own name under its track; the closed box names the
+ // track too ("Drums · Kick"), since two tracks may both have a "Kick".
+ Combo.SelectionBoxItemTemplate = new FuncDataTemplate<Row>((row, _) => new TextBlock { Text = row?.Full ?? "" });
+ Rebuild();
+ // Rows hold a part by its index, so they must be current when the list opens: rebuild
+ // before the ComboBox sees the click or key that opens it (tunnel = ahead of it).
+ Combo.AddHandler(InputElement.PointerPressedEvent, (_, _) => RefreshIfStale(), RoutingStrategies.Tunnel);
+ Combo.AddHandler(InputElement.KeyDownEvent, (_, _) => RefreshIfStale(), RoutingStrategies.Tunnel);
+ Combo.SelectionChanged += (_, _) =>
+ {
+ int s = Combo.SelectedIndex;
+ if (_syncing || s < 0 || s >= _keys.Count) return;
+ if (Shape() != _shape) { Rebuild(); return; } // the rows went stale while open: pick again
+ var k = _keys[s];
+ if (k == _get()) return;
+ if (_set(k.Source, k.Part) == -2)
+ {
+ ToolTip.SetTip(Combo, "No free routes — every sidechain route is in use");
+ Sync();
+ return;
+ }
+ Picked?.Invoke(k);
+ };
+ }
+
+ /// <summary>"Internal", "Drums" or "Drums · Kick" (with "missing" for a deleted part).</summary>
+ public string SourceName() => Name(_engine, _get(), _none);
+
+ /// <summary>The name of a key's source, as the cards and readouts show it.</summary>
+ public static string Name(IAudioEngine engine, SidechainKey k, string none = "Internal")
+ {
+ if (k.Source < 0) return none;
+ string track = TrackNames.Of(engine, k.Source);
+ if (k.Part == SidechainKey.WholeTrack) return track;
+ if (k.Part == SidechainKey.Missing) return $"{track} · missing";
+ string part = engine.TrackPartName(k.Source, k.Part);
+ return $"{track} · {(part.Length > 0 ? part : $"Part {k.Part + 1}")}";
+ }
+
+ /// <summary>Follow the key while the list is closed — call from the card's readout tick.</summary>
+ private void RefreshIfStale()
+ {
+ if (!Combo.IsDropDownOpen && Shape() != _shape) Rebuild();
+ }
+
+ public void Sync()
+ {
+ if (Combo.IsDropDownOpen) return;
+ int want = _keys.IndexOf(_get());
+ if (want < 0 || Shape() != _shape) { Rebuild(); return; }
+ if (Combo.SelectedIndex != want) Select(want);
+ }
+
+ // What the list shows, as text: the tracks with their names and parts, frozen tracks, and —
+ // while the pool is full — which sources hold a route (that decides which rows are enabled).
+ // Cheap enough for the readout tick.
+ private string Shape()
+ {
+ var sb = new StringBuilder();
+ bool full = _engine.SidechainRoutesFree() == 0;
+ sb.Append(full ? 'F' : 'o');
+ for (int i = 0; i < _engine.TrackCount; i++)
+ {
+ if (!_engine.TryGetTrackInfo(i, out var ti) || ti.Id == _ownTrack) continue;
+ sb.Append('|').Append(ti.Id).Append(':').Append(TrackNames.Of(_engine, ti));
+ if (full && _engine.SidechainRouteInUse(ti.Id, SidechainKey.WholeTrack)) sb.Append('^');
+ int parts = _engine.TrackPartCount(ti.Id);
+ if (parts > 0 && _engine.IsTrackFrozen(ti.Id)) sb.Append('*');
+ for (int p = 0; p < parts; p++)
+ {
+ sb.Append('/').Append(_engine.TrackPartName(ti.Id, p));
+ if (full && _engine.SidechainRouteInUse(ti.Id, p)) sb.Append('^');
+ }
+ }
+ return sb.ToString();
+ }
+
+ private void Select(int i)
+ {
+ _syncing = true;
+ Combo.SelectedIndex = i;
+ _syncing = false;
+ }
+
+ /// <summary>One row of a source list: a track (Part false) or one of its parts, indented
+ /// under it. Disabled rows carry the reason as a tooltip.</summary>
+ public readonly record struct Entry(SidechainKey Key, string Label, bool IsPart, bool Enabled, string? Tip);
+
+ /// <summary>Every source a key on <paramref name="ownTrack"/> may pick, in track order, each
+ /// track followed by its parts — for the cards that list sources in their own flyout.
+ /// <paramref name="parts"/> false lists whole tracks only (a MIDI key has no parts).</summary>
+ public static List<Entry> Entries(IAudioEngine engine, int ownTrack, SidechainKey cur, bool parts = true)
+ {
+ var list = new List<Entry>();
+ bool full = engine.SidechainRoutesFree() == 0;
+ // A source is takeable when it already has a route, when it is the one this key holds
+ // (moving off it frees that route), or while any route is free.
+ bool Takeable(int src, int part) => !full || engine.SidechainRouteInUse(src, part) || cur == new SidechainKey(src, part);
+ const string NoRoute = "No free routes — every sidechain route is in use";
+ for (int i = 0; i < engine.TrackCount; i++)
+ {
+ if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == ownTrack) continue;
+ bool whole = Takeable(ti.Id, SidechainKey.WholeTrack);
+ list.Add(new Entry(new SidechainKey(ti.Id, SidechainKey.WholeTrack), TrackNames.Of(engine, ti), false, whole, whole ? null : NoRoute));
+ int n = parts ? engine.TrackPartCount(ti.Id) : 0;
+ bool frozen = n > 0 && engine.IsTrackFrozen(ti.Id);
+ for (int p = 0; p < n; p++)
+ {
+ string name = engine.TrackPartName(ti.Id, p);
+ bool ok = !frozen && Takeable(ti.Id, p);
+ list.Add(new Entry(new SidechainKey(ti.Id, p), name.Length > 0 ? name : $"Part {p + 1}", true, ok,
+ frozen ? "Frozen — its parts don't play until the track is unfrozen" : ok ? null : NoRoute));
+ }
+ if (parts && cur.Source == ti.Id && cur.Part == SidechainKey.Missing)
+ list.Add(new Entry(cur, "missing part", true, false, "The keyed part was deleted — undo brings it back"));
+ }
+ return list;
+ }
+
+ /// <summary>Key a device off a picked source; a full route pool leaves the key as it was.
+ /// Returns false then (the card may say so).</summary>
+ public static bool SetDeviceKey(IAudioEngine engine, int track, int di, SidechainKey k)
+ => engine.SetDeviceSidechainKey(track, di, k.Source, k.Part) != -2;
+
+ /// <summary>A device's key sources as menu rows for the cards whose pickers are plain menus:
+ /// each track, then its parts as "Track · Part". A row the route pool can't take (or a frozen
+ /// track's part) has no Pick and carries the reason in Tip — show it disabled.</summary>
+ public static List<(string Label, bool Checked, Action? Pick, string? Tip)> MenuRows(IAudioEngine engine, int track, int di,
+ Action changed, string prefix = "")
+ {
+ var cur = engine.DeviceSidechainKey(track, di);
+ var rows = new List<(string, bool, Action?, string?)>();
+ foreach (var en in Entries(engine, track, cur))
+ {
+ var k = en.Key;
+ Action? pick = en.Enabled ? () => { SetDeviceKey(engine, track, di, k); changed(); } : null;
+ rows.Add((prefix + Name(engine, k), cur == k, pick, en.Tip));
+ }
+ return rows;
+ }
+
+ /// <summary>A radio menu item for a source row: disabled with its reason when it can't be
+ /// picked. <paramref name="after"/> runs after a pick (the card's refresh).</summary>
+ public static MenuItem MenuItemFor((string Label, bool Checked, Action? Pick, string? Tip) row, Action? after = null)
+ {
+ var mi = new MenuItem { Header = row.Label, ToggleType = MenuItemToggleType.Radio, IsChecked = row.Checked, IsEnabled = row.Pick != null };
+ if (row.Tip != null) ToolTip.SetTip(mi, row.Tip);
+ if (row.Pick is { } pick) mi.Click += (_, _) => { pick(); after?.Invoke(); };
+ return mi;
+ }
+
+ // A list row: its label in the open list, and the full source name for the closed box.
+ private sealed record Row(string Short, string Full)
+ {
+ public override string ToString() => Short;
+ }
+
+ private void Rebuild()
+ {
+ var cur = _get();
+ _syncing = true;
+ _keys.Clear();
+ Combo.Items.Clear();
+ void Add(SidechainKey k, string label, bool indent, bool enabled, string? tip)
+ {
+ _keys.Add(k);
+ var row = new Row(label, k.Source < 0 ? label : Name(_engine, k, _none));
+ var item = new ComboBoxItem { Content = row, IsEnabled = enabled, Padding = new Thickness(indent ? 18 : 6, 2, 6, 2) };
+ if (tip != null) ToolTip.SetTip(item, tip);
+ Combo.Items.Add(item);
+ }
+ Add(SidechainKey.None, _none, false, true, null);
+ foreach (var e in Entries(_engine, _ownTrack, cur)) Add(e.Key, e.Label, e.IsPart, e.Enabled, e.Tip);
+ int at = _keys.IndexOf(cur);
+ Combo.SelectedIndex = at >= 0 ? at : 0;
+ _shape = Shape();
+ _syncing = false;
+ }
+}
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index cd8227a8..8ddd4066 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -270,6 +270,15 @@ public readonly record struct NestedCcDest(int Device, int Chain, int Slot, int
/// <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>A sidechain key (specs/050): the source track (-1 = none) and the part of its
+/// instrument — a Drum Rack pad, an Instrument Rack chain or a Rhythm voice — as its current
+/// index; -1 = the whole track, -2 = the keyed part is gone (the key is silent).</summary>
+public readonly record struct SidechainKey(int Source, int Part)
+{
+ public const int WholeTrack = -1, Missing = -2;
+ public static readonly SidechainKey None = new(-1, WholeTrack);
+}
+
/// <summary>Why nota_track_group_devices refused a run (specs/044).</summary>
public enum GroupRefusal
{
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 022eed73..770c5af3 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -608,7 +608,8 @@ public interface IAudioEngine : IDisposable
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);
+ /// <summary>0 = set, -1 = bad address, -2 = no free route (the key is left as it was).</summary>
+ int 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,
@@ -648,6 +649,31 @@ public interface IAudioEngine : IDisposable
int InstrumentSidechainSource(int trackId);
/// <summary>Whether a track's instrument listens to a sidechain (Nota Flux).</summary>
bool InstrumentAcceptsSidechain(int trackId);
+ // Sidechain sub-sources (specs/050): a key may name one part of the source track's
+ // instrument (a Drum Rack pad, an Instrument Rack chain, a Rhythm voice) by its current
+ // index; the engine keeps the key on that part through reorder / insert / delete of others.
+ /// <summary>Parts of the track's instrument (0 = not a multi-part instrument).</summary>
+ int TrackPartCount(int trackId);
+ /// <summary>Display name of a part: the chain name, else its instrument's.</summary>
+ string TrackPartName(int trackId, int index);
+ /// <summary>Key a device off a track (part -1) or one part of it. 0 = set, -1 = bad address
+ /// or part, -2 = no free route (the key is left as it was).</summary>
+ int SetDeviceSidechainKey(int trackId, int deviceIndex, int sourceTrackId, int part);
+ SidechainKey DeviceSidechainKey(int trackId, int deviceIndex);
+ /// <summary>The same for an instrument's React key (Nota Flux) — always the Post tap.</summary>
+ int SetInstrumentSidechainKey(int trackId, int sourceTrackId, int part);
+ SidechainKey InstrumentSidechainKey(int trackId);
+ /// <summary>The part of a rack chain child's key (save / load; after RackChainSetSidechain).</summary>
+ int RackChainSidechainPart(int trackId, int rackAddress, int chain, int slot);
+ int RackChainSetSidechainPart(int trackId, int rackAddress, int chain, int slot, int part); // 0 / -1 / -2 as above
+ /// <summary>A rack child's whole key in one step (source, part — -1 whole track — and shaping), so
+ /// only the final key meets the route check. 0 / -1 / -2 as above; on -2 nothing changes.</summary>
+ int RackChainSetSidechainKey(int trackId, int rackAddress, int chain, int slot, NestedSidechain sc, int part);
+ /// <summary>The route pool whole tracks and parts share: size, free now, and whether
+ /// (source, part) already has a route (a further key on it needs none).</summary>
+ int SidechainRouteCapacity();
+ int SidechainRoutesFree();
+ bool SidechainRouteInUse(int sourceTrackId, int part);
/// <summary>Sidechain detector gain in dB (Phase D): how hard the source drives the effect.</summary>
void SetDeviceSidechainGain(int trackId, int deviceIndex, float gainDb);
float DeviceSidechainGain(int trackId, int deviceIndex);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
index 4e150b78..a4c49155 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
@@ -232,6 +232,44 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_midi_effect_cc_depth")]
internal static partial float MidiEffectCcDepth(IntPtr engine, int trackId, int index);
+ // Sidechain sub-sources (specs/050).
+ [LibraryImport(Lib, EntryPoint = "nota_track_part_count")]
+ internal static partial int TrackPartCount(IntPtr engine, int trackId);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_part_name")]
+ internal static partial int TrackPartName(IntPtr engine, int trackId, int index, [Out] byte[]? outBytes, int cap);
+
+ [LibraryImport(Lib, EntryPoint = "nota_device_set_sidechain_key")]
+ internal static partial int DeviceSetSidechainKey(IntPtr engine, int trackId, int deviceIndex, int sourceTrackId, int part);
+
+ [LibraryImport(Lib, EntryPoint = "nota_device_sidechain_key")]
+ internal static partial int DeviceSidechainKey(IntPtr engine, int trackId, int deviceIndex, out int source, out int part);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_set_instrument_sidechain_key")]
+ internal static partial int TrackSetInstrumentSidechainKey(IntPtr engine, int trackId, int sourceTrackId, int part);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_instrument_sidechain_key")]
+ internal static partial int TrackInstrumentSidechainKey(IntPtr engine, int trackId, out int source, out int part);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_sidechain_part")]
+ internal static partial int RackChainSidechainPart(IntPtr engine, int trackId, int deviceIndex, int chain, int slot, out int part);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_set_sidechain_key")]
+ internal static partial int RackChainSetSidechainKey(IntPtr engine, int trackId, int deviceIndex, int chain, int slot,
+ int sourceTrack, int part, int tapPre, float gainDb, float mix);
+
+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_set_sidechain_part")]
+ internal static partial int RackChainSetSidechainPart(IntPtr engine, int trackId, int deviceIndex, int chain, int slot, int part);
+
+ [LibraryImport(Lib, EntryPoint = "nota_sidechain_route_capacity")]
+ internal static partial int SidechainRouteCapacity(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_sidechain_routes_free")]
+ internal static partial int SidechainRoutesFree(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_sidechain_route_in_use")]
+ internal static partial int SidechainRouteInUse(IntPtr engine, int sourceTrackId, int part);
+
[LibraryImport(Lib, EntryPoint = "nota_device_set_sidechain_source")]
internal static partial void DeviceSetSidechainSource(IntPtr engine, int trackId, int deviceIndex, int sourceTrackId);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
index 55537ee6..e7037999 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
@@ -287,11 +287,11 @@ public sealed partial class NotaEngine
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)
+ public int 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;
+ sc.GainDb, sc.Mix);
}
public float MidiEffectCcDepth(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDepth(_handle, trackId, index); }
@@ -304,6 +304,51 @@ public sealed partial class NotaEngine
public bool DeviceAcceptsSidechain(int trackId, int deviceIndex)
{ ThrowIfDisposed(); return NativeMethods.DeviceAcceptsSidechain(_handle, trackId, deviceIndex) != 0; }
+ // Sidechain sub-sources (specs/050).
+ public int TrackPartCount(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackPartCount(_handle, trackId); }
+ public string TrackPartName(int trackId, int index)
+ {
+ ThrowIfDisposed();
+ int n = NativeMethods.TrackPartName(_handle, trackId, index, null, 0);
+ if (n <= 0) return "";
+ var buf = new byte[n + 1];
+ NativeMethods.TrackPartName(_handle, trackId, index, buf, buf.Length);
+ return System.Text.Encoding.UTF8.GetString(buf, 0, n);
+ }
+ public int SetDeviceSidechainKey(int trackId, int deviceIndex, int sourceTrackId, int part)
+ { ThrowIfDisposed(); return NativeMethods.DeviceSetSidechainKey(_handle, trackId, deviceIndex, sourceTrackId, part); }
+ public SidechainKey DeviceSidechainKey(int trackId, int deviceIndex)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.DeviceSidechainKey(_handle, trackId, deviceIndex, out int src, out int part) == 0
+ ? new SidechainKey(src, part) : SidechainKey.None;
+ }
+ public int SetInstrumentSidechainKey(int trackId, int sourceTrackId, int part)
+ { ThrowIfDisposed(); return NativeMethods.TrackSetInstrumentSidechainKey(_handle, trackId, sourceTrackId, part); }
+ public SidechainKey InstrumentSidechainKey(int trackId)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.TrackInstrumentSidechainKey(_handle, trackId, out int src, out int part) == 0
+ ? new SidechainKey(src, part) : SidechainKey.None;
+ }
+ public int RackChainSidechainPart(int trackId, int rackAddress, int chain, int slot)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.RackChainSidechainPart(_handle, trackId, rackAddress, chain, slot, out int part) == 0 ? part : SidechainKey.WholeTrack;
+ }
+ public int RackChainSetSidechainKey(int trackId, int rackAddress, int chain, int slot, NestedSidechain sc, int part)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.RackChainSetSidechainKey(_handle, trackId, rackAddress, chain, slot, sc.SourceTrack, part,
+ sc.TapPre ? 1 : 0, sc.GainDb, sc.Mix);
+ }
+ public int RackChainSetSidechainPart(int trackId, int rackAddress, int chain, int slot, int part)
+ { ThrowIfDisposed(); return NativeMethods.RackChainSetSidechainPart(_handle, trackId, rackAddress, chain, slot, part); }
+ public int SidechainRouteCapacity() { ThrowIfDisposed(); return NativeMethods.SidechainRouteCapacity(_handle); }
+ public int SidechainRoutesFree() { ThrowIfDisposed(); return NativeMethods.SidechainRoutesFree(_handle); }
+ public bool SidechainRouteInUse(int sourceTrackId, int part)
+ { ThrowIfDisposed(); return NativeMethods.SidechainRouteInUse(_handle, sourceTrackId, part) != 0; }
+
public void SetInstrumentSidechainSource(int trackId, int sourceTrackId)
{ ThrowIfDisposed(); NativeMethods.TrackSetInstrumentSidechainSource(_handle, trackId, sourceTrackId); }
public int InstrumentSidechainSource(int trackId)
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index aab97c51..4aa0da6b 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -110,6 +110,11 @@ public static class ProjectMigrations
// v26 -> v27: hosted plug-ins and instruments gain Preview, the picture of their window
// (specs/046). Absent in v26 documents; null = no preview, the card stays plain — no-op.
new Migration(26, _ => { }),
+ // v27 -> v28: sidechain keys may name one part of the source's instrument (a Drum Rack
+ // pad, an Instrument Rack chain, a Rhythm voice; specs/050): DeviceDto / InstrumentDto
+ // SidechainPart and NestedSidechainDto.Part. Absent in v27 documents = -1, the whole
+ // track — no-op.
+ new Migration(27, _ => { }),
};
/// <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 e52a6967..a084a852 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -218,6 +218,9 @@ public sealed class NestedSidechainDto
public int Chain { get; set; }
public int Slot { get; set; }
public int Source { get; set; } = -1;
+ /// <summary>The part of the source's instrument (index at save time; -1 = the whole track).
+ /// Format v28, specs/050.</summary>
+ public int Part { get; set; } = -1;
public bool TapPre { get; set; }
public float GainDb { get; set; }
public float Mix { get; set; } = 1.0f;
@@ -331,6 +334,9 @@ public sealed class InstrumentDto
/// <summary>Sidechain source ("React", Nota Flux) as a track INDEX in this document
/// (-1 = none). Resolved to a live track id on load, since ids are reassigned.</summary>
public int SidechainSource { get; set; } = -1;
+ /// <summary>The part of the source React listens to (index at save time; -1 = the whole
+ /// track). Format v28, specs/050.</summary>
+ public int SidechainPart { get; set; } = -1;
/// <summary>Drawn as a narrow strip in the Devices panel (format v23, specs/022).</summary>
public bool Folded { get; set; }
/// <summary>Nota Rhythm (Kind == 12) per-voice one-shots (only sample-source voices).</summary>
@@ -456,6 +462,10 @@ public sealed class DeviceDto
/// <summary>Sidechain source as a track INDEX in this document (-1 = none). Resolved to a
/// live track id on load, since ids are reassigned. Phase B (format v15).</summary>
public int SidechainSource { get; set; } = -1;
+ /// <summary>The part of the source track's instrument the key listens to — a Drum Rack pad,
+ /// an Instrument Rack chain or a Rhythm voice — as its index at save time; -1 = the whole
+ /// track (format v28, specs/050).</summary>
+ public int SidechainPart { get; set; } = -1;
/// <summary>Sidechain detector gain in dB (Phase D, format v16).</summary>
public float SidechainGain { get; set; }
/// <summary>Sidechain dry/wet, 0..1 (Phase D, format v16). Default 1 = fully wet.</summary>
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index e4449331..21622bba 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -37,7 +37,7 @@ public sealed class ProjectService
/// chain children's sidechain keys / CC targets.
/// v26 (specs/048) adds Preset on instruments, devices and MIDI effects.
/// v27 (specs/046) adds Preview on hosted plug-ins: the picture of their window.
- public const int CurrentFormatVersion = 27;
+ public const int CurrentFormatVersion = 28;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -167,8 +167,12 @@ public sealed class ProjectService
if (vs.Count > 0) instDto.VoiceSamples = vs;
}
// React source (Nota Flux): store as a doc index, resolved on load.
- int instScSrc = engine.InstrumentSidechainSource(ti.Id);
- instDto.SidechainSource = instScSrc >= 0 && idToIndex.TryGetValue(instScSrc, out var isi) ? isi : -1;
+ // A key whose part is gone (Missing) saves as no key (specs/050).
+ var instKey = engine.InstrumentSidechainKey(ti.Id);
+ int isi = -1;
+ bool instKeyed = instKey.Source >= 0 && instKey.Part != SidechainKey.Missing && idToIndex.TryGetValue(instKey.Source, out isi);
+ instDto.SidechainSource = instKeyed ? isi : -1;
+ instDto.SidechainPart = instKeyed ? instKey.Part : -1;
instDto.Folded = engine.DeviceFolded(ti.Id, -1);
instDto.Bypassed = engine.DeviceBypassed(ti.Id, -1);
instDto.Preset = CapturePresetTag(engine, ti.Id, PresetSurface.Instrument, -1);
@@ -392,8 +396,13 @@ public sealed class ProjectService
{
int bk = engine.TrackDeviceBuiltinKind(trackId, d);
var dev = new DeviceDto { BuiltinKind = bk, Bypassed = engine.DeviceBypassed(trackId, d), Folded = engine.DeviceFolded(trackId, d) };
- int scSrc = engine.DeviceSidechainSource(trackId, d);
- dev.SidechainSource = scSrc >= 0 && idToIndex.TryGetValue(scSrc, out var si) ? si : -1;
+ // Source as a doc index, its part as an index on that track; a key whose part is
+ // gone (Missing) saves as no key (specs/050).
+ var key = engine.DeviceSidechainKey(trackId, d);
+ int si = -1;
+ bool keyed = key.Source >= 0 && key.Part != SidechainKey.Missing && idToIndex.TryGetValue(key.Source, out si);
+ dev.SidechainSource = keyed ? si : -1;
+ dev.SidechainPart = keyed ? key.Part : -1;
dev.SidechainGain = engine.DeviceSidechainGain(trackId, d);
dev.SidechainMix = engine.DeviceSidechainMix(trackId, d);
dev.SidechainTapPre = engine.DeviceSidechainTapPre(trackId, d);
@@ -448,8 +457,9 @@ public sealed class ProjectService
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 });
+ && idToIndex.TryGetValue(sc.SourceTrack, out int src)
+ && engine.RackChainSidechainPart(trackId, host, c, slot) is var part && part != SidechainKey.Missing)
+ scs.Add(new NestedSidechainDto { Host = host, Chain = c, Slot = slot, Source = src, Part = part, 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)
@@ -470,7 +480,7 @@ public sealed class ProjectService
}
private static void ApplyDevices(IAudioEngine engine, int trackId, IEnumerable<DeviceDto> devices,
- string bundleDir, List<(int track, int dev, int srcIndex)> scDeferred, List<string> warnings)
+ string bundleDir, List<(int track, int dev, int srcIndex, int part)> scDeferred, List<string> warnings)
{
foreach (var d in devices)
{
@@ -516,7 +526,7 @@ public sealed class ProjectService
if (d.Folded) engine.SetDeviceFolded(trackId, di, true);
ApplyPresetTag(engine, trackId, PresetSurface.Effect, di, d.Preset);
if (d.Preview is { } previewRel) engine.SetPluginPreview(trackId, di, ReadPreview(bundleDir, previewRel));
- if (d.SidechainSource >= 0) scDeferred.Add((trackId, di, d.SidechainSource));
+ if (d.SidechainSource >= 0) scDeferred.Add((trackId, di, d.SidechainSource, d.SidechainPart));
engine.SetDeviceSidechainGain(trackId, di, d.SidechainGain);
engine.SetDeviceSidechainMix(trackId, di, d.SidechainMix);
engine.SetDeviceSidechainTapPre(trackId, di, d.SidechainTapPre);
@@ -553,9 +563,9 @@ public sealed class ProjectService
// Doc index -> new live track id, and deferred sidechain wiring (a source may be
// 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 scDeferred = new List<(int track, int dev, int srcIndex, int part)>();
var nestedScDeferred = new List<(int track, NestedSidechainDto dto)>();
- var instScDeferred = new List<(int track, int srcIndex)>(); // instrument React source (Nota Flux)
+ var instScDeferred = new List<(int track, int srcIndex, int part)>(); // instrument React source (Nota Flux)
var recInputDeferred = new List<(int trackId, int encoded)>();
var monitorDeferred = new List<(int trackId, bool on)>();
var groupDeferred = new List<(int trackId, int parentDocIndex)>(); // group membership
@@ -687,7 +697,7 @@ public sealed class ProjectService
if (id > 0 && t.Instrument is { Bypassed: true })
engine.SetDeviceBypassed(id, -1, true); // the instrument card's switch is off (#148)
if (id > 0 && t.Instrument is { SidechainSource: >= 0 } insc)
- instScDeferred.Add((id, insc.SidechainSource)); // wire React source once every track exists
+ instScDeferred.Add((id, insc.SidechainSource, insc.SidechainPart)); // wire React source once every track exists
if (id > 0 && t.GroupId >= 0)
groupDeferred.Add((id, t.GroupId)); // reparent into its group once every track exists
newTrackIds.Add(id); // keep index aligned with doc.Tracks even on failure (id <= 0)
@@ -911,24 +921,31 @@ public sealed class ProjectService
}
// Sidechain wiring, now that every track exists (Phase B). Source is a doc index.
- foreach (var (track, dev, srcIndex) in scDeferred)
+ // A key may name a part of its source's instrument (specs/050); the route pool is shared,
+ // so a key past it is dropped and reported once.
+ int unrouted = 0;
+ foreach (var (track, dev, srcIndex, part) in scDeferred)
{
if (srcIndex < newTrackIds.Count && newTrackIds[srcIndex] > 0)
- engine.SetDeviceSidechainSource(track, dev, newTrackIds[srcIndex]);
+ if (engine.SetDeviceSidechainKey(track, dev, newTrackIds[srcIndex], part) == -2) unrouted++;
}
- // Keys of devices inside racks (specs/044), same deferral.
+ // Keys of devices inside racks (specs/044), same deferral and the same route check: a key
+ // the pool can't take is cleared and counted.
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));
+ if (n.Source >= newTrackIds.Count || newTrackIds[n.Source] <= 0) continue;
+ var sc = new NestedSidechain(newTrackIds[n.Source], n.TapPre, n.GainDb, n.Mix);
+ // Source and part together: only the saved key itself meets the route check.
+ if (engine.RackChainSetSidechainKey(track, n.Host, n.Chain, n.Slot, sc, n.Part) == -2) unrouted++;
}
// Instrument React source (Nota Flux), same deferral.
- foreach (var (track, srcIndex) in instScDeferred)
+ foreach (var (track, srcIndex, part) in instScDeferred)
{
if (srcIndex < newTrackIds.Count && newTrackIds[srcIndex] > 0)
- engine.SetInstrumentSidechainSource(track, newTrackIds[srcIndex]);
+ if (engine.SetInstrumentSidechainKey(track, newTrackIds[srcIndex], part) == -2) unrouted++;
}
+ if (unrouted > 0)
+ warnings.Add($"{unrouted} sidechain key{(unrouted == 1 ? " was" : "s were")} cleared: all {engine.SidechainRouteCapacity()} sidechain routes are in use.");
// Group membership (parent stored as a doc index), now that every track exists.
foreach (var (trackId, parentDocIndex) in groupDeferred)
{
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 75b0b5a1..39187dd3 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -153,22 +153,87 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
public Task DeviceAction(int trackId, int deviceIndex, [Description("Command id — see the device's list in this description")] int id,
int intArg = 0, float floatArg = 0) => Mutate(() => E.DeviceAction(trackId, deviceIndex, id, intArg, floatArg));
- public sealed record Sidechain(bool Accepts, int SourceTrackId, bool TapPre, float GainDb, float Mix);
+ public sealed record Sidechain(bool Accepts, int SourceTrackId, int SourcePart, string SourceName, bool TapPre, float GainDb, float Mix);
- [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, Nota Shutter, Nota Auto Shift — its MIDI source —, Nota Vocoder — its carrier track — and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1).")]
- public Task<Sidechain> GetDeviceSidechain(int trackId, int deviceIndex) => Read(() => new Sidechain(
- E.DeviceAcceptsSidechain(trackId, deviceIndex), E.DeviceSidechainSource(trackId, deviceIndex),
- E.DeviceSidechainTapPre(trackId, deviceIndex), E.DeviceSidechainGain(trackId, deviceIndex), E.DeviceSidechainMix(trackId, deviceIndex)));
+ // "Drums" / "Drums · Kick" / "Drums · missing" (specs/050).
+ private string KeyName(SidechainKey k)
+ {
+ if (k.Source < 0) return "none";
+ string track = E.GetTrackName(k.Source) is { Length: > 0 } nm ? nm : $"track {k.Source}";
+ return k.Part switch
+ {
+ SidechainKey.WholeTrack => track,
+ SidechainKey.Missing => track + " · missing",
+ _ => track + " · " + E.TrackPartName(k.Source, k.Part),
+ };
+ }
+
+ private static void ThrowOnKey(int r, int sourceTrackId, int part)
+ {
+ if (r == -1) throw new ArgumentException(part >= 0
+ ? $"Track {sourceTrackId} has no part {part} (see list_sidechain_sources), or the device keys on MIDI (Nota Auto Shift), which takes whole tracks only."
+ : $"No such device or source track {sourceTrackId}.");
+ if (r == -2) throw new InvalidOperationException("No free sidechain route: all of them are in use (see list_sidechain_sources). The key was left as it was.");
+ }
+
+ [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, Nota Shutter, Nota Auto Shift — its MIDI source —, Nota Vocoder — its carrier track — and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1). sourcePart is the pad / chain / voice of the source track's instrument the key listens to (-1 = the whole track, -2 = the keyed part was deleted and the key is silent); sourceName reads it as \"Drums · Kick\".")]
+ public Task<Sidechain> GetDeviceSidechain(int trackId, int deviceIndex) => Read(() =>
+ {
+ var k = E.DeviceSidechainKey(trackId, deviceIndex);
+ return new Sidechain(E.DeviceAcceptsSidechain(trackId, deviceIndex), E.DeviceSidechainSource(trackId, deviceIndex), k.Part, KeyName(k),
+ E.DeviceSidechainTapPre(trackId, deviceIndex), E.DeviceSidechainGain(trackId, deviceIndex), E.DeviceSidechainMix(trackId, deviceIndex));
+ });
- [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1), or make a pad speak with a vocal through Nota Vocoder (kind 26, on the vocal track, which is the modulator: set its Carrier param to Track (1.0) and pass the pad track here as the carrier; tapPre true takes the pad before its effects, gainDb trims it; with Carrier Saw or Noise it needs no source): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). Nota Shutter (kind 19) gates or ducks against a key the same way (Flip = 1 for Duck; Det HP / Det LP shape the key; External Key on, its default). Nota Auto Shift (kind 10) takes an instrument track here as its MIDI source: with Key Source = 1 (MIDI) the voice is pulled to that track's notes (its clips after its MIDI effects, even while muted). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain.")]
+ [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1), or make a pad speak with a vocal through Nota Vocoder (kind 26, on the vocal track, which is the modulator: set its Carrier param to Track (1.0) and pass the pad track here as the carrier; tapPre true takes the pad before its effects, gainDb trims it; with Carrier Saw or Noise it needs no source): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). Nota Shutter (kind 19) gates or ducks against a key the same way (Flip = 1 for Duck; Det HP / Det LP shape the key; External Key on, its default). Nota Auto Shift (kind 10) takes an instrument track here as its MIDI source: with Key Source = 1 (MIDI) the voice is pulled to that track's notes (its clips after its MIDI effects, even while muted). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain. To key off just one part of the source — a Drum Rack pad (duck the bass from the kick pad only), an Instrument Rack chain or a Nota Rhythm voice — pass its index as sourcePart (from list_sidechain_sources); for a part, tapPre true takes it before its own pad / chain effects, false after them and its level and pan. A muted pad still drives its key. Fails when all sidechain routes are in use.")]
public Task SetDeviceSidechain(int trackId, int deviceIndex, [Description("Key source track id, or -1 for none")] int sourceTrackId,
- bool? tapPre = null, float? gainDb = null) => Mutate(() =>
+ bool? tapPre = null, float? gainDb = null,
+ [Description("Part of the source track's instrument (pad / chain / voice index), -1 or omitted = the whole track")] int? sourcePart = null) => Mutate(() =>
{
- E.SetDeviceSidechainSource(trackId, deviceIndex, sourceTrackId);
+ int part = sourcePart ?? SidechainKey.WholeTrack;
+ if (sourceTrackId < 0) E.SetDeviceSidechainSource(trackId, deviceIndex, -1);
+ else ThrowOnKey(E.SetDeviceSidechainKey(trackId, deviceIndex, sourceTrackId, part), sourceTrackId, part);
if (tapPre is { } pre) E.SetDeviceSidechainTapPre(trackId, deviceIndex, pre);
if (gainDb is { } g) E.SetDeviceSidechainGain(trackId, deviceIndex, Math.Clamp(g, -24f, 24f));
});
+ public sealed record SidechainPart(int Index, string Name, bool RouteInUse);
+ public sealed record SidechainSource(int TrackId, string Name, bool Frozen, bool RouteInUse, SidechainPart[] Parts);
+ public sealed record SidechainSources(int RouteCapacity, int RoutesFree, SidechainSource[] Sources);
+
+ [McpServerTool(Name = "list_sidechain_sources"), Description("List what a sidechain key can listen to: every track, and for a track whose instrument has parts — a Drum Rack's pads, an Instrument Rack's chains, Nota Rhythm's eight voices — each part with its index (pass it as sourcePart to set_device_sidechain / set_instrument_sidechain). Whole tracks and parts share one pool of sidechain routes: routeInUse says a source already has one (a further key on it costs none); when routesFree is 0 only those can be picked. A frozen track's parts are silent until it is unfrozen.")]
+ public Task<SidechainSources> ListSidechainSources() => Read(() =>
+ {
+ var list = new List<SidechainSource>();
+ for (int i = 0; i < E.TrackCount; i++)
+ {
+ if (!E.TryGetTrackInfo(i, out var ti)) continue;
+ int n = E.TrackPartCount(ti.Id);
+ var parts = new SidechainPart[n];
+ for (int p = 0; p < n; p++) parts[p] = new SidechainPart(p, E.TrackPartName(ti.Id, p), E.SidechainRouteInUse(ti.Id, p));
+ list.Add(new SidechainSource(ti.Id, KeyName(new SidechainKey(ti.Id, SidechainKey.WholeTrack)), n > 0 && E.IsTrackFrozen(ti.Id),
+ E.SidechainRouteInUse(ti.Id, SidechainKey.WholeTrack), parts));
+ }
+ return new SidechainSources(E.SidechainRouteCapacity(), E.SidechainRoutesFree(), list.ToArray());
+ });
+
+ public sealed record InstrumentSidechain(bool Accepts, int SourceTrackId, int SourcePart, string SourceName);
+
+ [McpServerTool(Name = "get_instrument_sidechain"), Description("Read what a track's instrument listens to — Nota Flux's React (the synth moves with another track's level and onsets): whether the instrument listens at all, the source track id (-1 = none), the part of its instrument (-1 = the whole track, -2 = the part was deleted) and the source's name. React always hears the source after its effects.")]
+ public Task<InstrumentSidechain> GetInstrumentSidechain(int trackId) => Read(() =>
+ {
+ var k = E.InstrumentSidechainKey(trackId);
+ return new InstrumentSidechain(E.InstrumentAcceptsSidechain(trackId), k.Source, k.Part, KeyName(k));
+ });
+
+ [McpServerTool(Name = "set_instrument_sidechain"), Description("Point a track's listening instrument (Nota Flux's React) at another track, or at one pad / chain / voice of it with sourcePart (from list_sidechain_sources) — e.g. make Flux pulse with the kick pad of a Drum Rack. sourceTrackId -1 clears it. Fails when all sidechain routes are in use.")]
+ public Task SetInstrumentSidechain(int trackId, [Description("Source track id, or -1 for none")] int sourceTrackId,
+ [Description("Part of the source track's instrument, -1 or omitted = the whole track")] int? sourcePart = null) => Mutate(() =>
+ {
+ int part = sourcePart ?? SidechainKey.WholeTrack;
+ if (sourceTrackId < 0) E.SetInstrumentSidechainSource(trackId, -1);
+ else ThrowOnKey(E.SetInstrumentSidechainKey(trackId, sourceTrackId, part), sourceTrackId, part);
+ });
+
public sealed record DynamicsReading(string Summary, double GainReductionDb, double InputPeakDb, double InputRmsDb,
double OutputPeakDb, double OutputRmsDb, double KeyPeakDb, bool ExternalKey, double AttackMs, double ReleaseMs,
int LatencySamples, double SampleRate, int HitsLast2s, double DeepestReductionLast2sDb);
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 9fa9e394..bae9b599 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1773,6 +1773,48 @@ NOTA_API void nota_device_set_sidechain_mix(NotaEngine* engine, int32_t t
NOTA_API float nota_device_sidechain_mix(const NotaEngine* engine, int32_t track_id, int32_t device_index);
NOTA_API void nota_device_set_sidechain_tap_pre(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t pre);
NOTA_API int32_t nota_device_sidechain_tap_pre(const NotaEngine* engine, int32_t track_id, int32_t device_index);
+/* Sidechain sub-sources (specs/050): a key may name one part of the source track's
+ * instrument — a Drum Rack pad, an Instrument Rack chain (first level) or a Nota Rhythm voice.
+ * Parts are addressed by their CURRENT index; the engine keeps a key on the same part through
+ * reorder / insert / delete of the others. part -1 = the whole track. Pre on a part = before
+ * its own inserts; Post = after its inserts and its gain / pan, before the instrument sums it.
+ * A keyed part plays its key even while muted or solo-gated (it stays out of the mix). The
+ * whole-track setters above clear the part. Getters report part -2 when the keyed part is gone
+ * (the key is silent until an undo brings it back). */
+/* Parts of the track's instrument (0 = none), and part `index`'s display name (the chain name,
+ * else its instrument's): full UTF-8 length; copies up to cap-1 bytes + NUL when out is set. */
+NOTA_API int32_t nota_track_part_count(const NotaEngine* engine, int32_t track_id);
+NOTA_API int32_t nota_track_part_name(const NotaEngine* engine, int32_t track_id, int32_t index, char* out, int32_t cap);
+/* Set: 0 done, -1 bad address / part, -2 no free route (the key is left as it was).
+ * Get: 0 done, -1 bad address; *out_source -1 = none. */
+NOTA_API int32_t nota_device_set_sidechain_key(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t source_track_id, int32_t part);
+NOTA_API int32_t nota_device_sidechain_key(const NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t* out_source, int32_t* out_part);
+/* The same for an instrument's React key (Nota Flux) — always the Post tap. */
+NOTA_API int32_t nota_track_set_instrument_sidechain_key(NotaEngine* engine, int32_t track_id, int32_t source_track_id,
+ int32_t part);
+NOTA_API int32_t nota_track_instrument_sidechain_key(const NotaEngine* engine, int32_t track_id, int32_t* out_source,
+ int32_t* out_part);
+/* The part of a rack chain child's key (save / load; addresses as nota_rack_chain_sidechain;
+ * set it after nota_rack_chain_set_sidechain, which clears it). 0 = done, -1 not, -2 no free
+ * route (the key is left as it was). nota_rack_chain_set_sidechain likewise returns -2 when its
+ * source needs a route the pool can't give without pushing out another key's. */
+NOTA_API int32_t nota_rack_chain_sidechain_part(const NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t* out_part);
+NOTA_API int32_t nota_rack_chain_set_sidechain_part(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t part);
+/* A chain child's whole key in one step — source, part (-1 whole track), tap, gain, mix — so
+ * only the final key is checked against the route pool. 0 = done, -1 bad address / part, -2 no
+ * free route (key and shaping left as they were). Project load restores rack keys with this. */
+NOTA_API int32_t nota_rack_chain_set_sidechain_key(NotaEngine* engine, int32_t track_id, int32_t device_index,
+ int32_t chain, int32_t slot, int32_t source_track, int32_t part,
+ int32_t tap_pre, float gain_db, float mix);
+/* The route pool whole tracks and parts share: its size (16), the routes free now, and whether
+ * (source, part) already has one — a further key on it needs none. */
+NOTA_API int32_t nota_sidechain_route_capacity(const NotaEngine* engine);
+NOTA_API int32_t nota_sidechain_routes_free(const NotaEngine* engine);
+NOTA_API int32_t nota_sidechain_route_in_use(const NotaEngine* engine, int32_t source_track_id, int32_t part);
/* Deterministic DSP self-test of the built-in EQ + Compressor: 1 = sane. */
NOTA_API int32_t nota_fx_selftest(void);
/* Runs the EQ cards' spectrum analyzer (specs/046) over `n` mono samples on a fixed clock,
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 dddd95d2..95413305 100644
--- a/src/native/nota.engine/src/abi/nota_engine_device.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_device.cpp
@@ -129,7 +129,7 @@ int32_t nota_rack_chain_sidechain(const NotaEngine* e, int32_t t, int32_t di, in
}
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;
+ return e ? ENG(e)->rackChainSetSidechain(t, di, c, slot, src, pre, gain, mix) : -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;
@@ -358,6 +358,55 @@ void nota_device_set_sidechain_tap_pre(NotaEngine* e, int32_t track_id, int32_t
int32_t nota_device_sidechain_tap_pre(const NotaEngine* e, int32_t track_id, int32_t device_index) {
return e ? CENG(e)->deviceSidechainTapPre(track_id, device_index) : 0;
}
+
+// ---- sidechain sub-sources (specs/050) ----
+int32_t nota_track_part_count(const NotaEngine* e, int32_t track_id) {
+ return e ? CENG(e)->trackPartCount(track_id) : 0;
+}
+int32_t nota_track_part_name(const NotaEngine* e, int32_t track_id, int32_t index, char* out, int32_t cap) {
+ if (!e) return 0;
+ const std::string s = CENG(e)->trackPartName(track_id, index);
+ const int32_t n = static_cast<int32_t>(s.size());
+ if (out && cap > 0) {
+ const int32_t m = std::min(n, cap - 1);
+ std::memcpy(out, s.data(), static_cast<size_t>(m));
+ out[m] = '\0';
+ }
+ return n;
+}
+int32_t nota_device_set_sidechain_key(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t source_track_id,
+ int32_t part) {
+ return e ? ENG(e)->setDeviceSidechainKey(track_id, device_index, source_track_id, part) : -1;
+}
+int32_t nota_device_sidechain_key(const NotaEngine* e, int32_t track_id, int32_t device_index, int32_t* out_source,
+ int32_t* out_part) {
+ return e && CENG(e)->deviceSidechainKey(track_id, device_index, out_source, out_part) ? 0 : -1;
+}
+int32_t nota_track_set_instrument_sidechain_key(NotaEngine* e, int32_t track_id, int32_t source_track_id, int32_t part) {
+ return e ? ENG(e)->setInstrumentSidechainKey(track_id, source_track_id, part) : -1;
+}
+int32_t nota_track_instrument_sidechain_key(const NotaEngine* e, int32_t track_id, int32_t* out_source, int32_t* out_part) {
+ return e && CENG(e)->instrumentSidechainKey(track_id, out_source, out_part) ? 0 : -1;
+}
+int32_t nota_rack_chain_sidechain_part(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t slot, int32_t* out_part) {
+ return e && CENG(e)->rackChainSidechainPart(t, di, c, slot, out_part) ? 0 : -1;
+}
+int32_t nota_rack_chain_set_sidechain_key(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t slot, int32_t src,
+ int32_t part, int32_t pre, float gain, float mix) {
+ return e ? ENG(e)->rackChainSetKey(t, di, c, slot, src, part, pre, gain, mix) : -1;
+}
+int32_t nota_rack_chain_set_sidechain_part(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t slot, int32_t part) {
+ return e ? ENG(e)->rackChainSetSidechainPart(t, di, c, slot, part) : -1;
+}
+int32_t nota_sidechain_route_capacity(const NotaEngine* e) {
+ return e ? nota::Engine::kSidechainRoutes : 0;
+}
+int32_t nota_sidechain_routes_free(const NotaEngine* e) {
+ return e ? CENG(e)->sidechainRoutesFree() : 0;
+}
+int32_t nota_sidechain_route_in_use(const NotaEngine* e, int32_t source_track_id, int32_t part) {
+ return e && CENG(e)->sidechainRouteInUse(source_track_id, part) ? 1 : 0;
+}
int32_t nota_spectrum_analyze_offline(const float* mono, int32_t n, double sample_rate, int32_t hop,
double dt, float* curves, int32_t max_frames) {
using nota::dsp::SpectrumAnalyzer;
diff --git a/src/native/nota.engine/src/devices/Device.h b/src/native/nota.engine/src/devices/Device.h
index a0772be5..7c450036 100644
--- a/src/native/nota.engine/src/devices/Device.h
+++ b/src/native/nota.engine/src/devices/Device.h
@@ -230,6 +230,11 @@ class Device {
void setSidechainMix(float m) { scMix_.store(std::clamp(m, 0.0f, 1.0f), std::memory_order_relaxed); }
int32_t sidechainTapPre() const { return scTapPre_.load(std::memory_order_relaxed); }
void setSidechainTapPre(int32_t pre) { scTapPre_.store(pre ? 1 : 0, std::memory_order_relaxed); }
+ // - part (specs/050): which part of the source track's instrument the key comes from — a
+ // Drum Rack pad / Instrument Rack chain (its chain uid) or a Rhythm voice (voice + 1);
+ // 0 = the whole track. Read by the engine, not the device.
+ uint64_t sidechainPart() const { return scPart_.load(std::memory_order_relaxed); }
+ void setSidechainPart(uint64_t part) { scPart_.store(part, std::memory_order_relaxed); }
// Musical transport for tempo-synced devices (e.g. Beat Repeat). The engine calls
// this on the audio thread just before process() with the block's start position in
@@ -270,6 +275,7 @@ class Device {
std::atomic<float> scGainDb_{0.0f};
std::atomic<float> scMix_{1.0f};
std::atomic<int32_t> scTapPre_{0};
+ std::atomic<uint64_t> scPart_{0};
};
} // namespace nota
diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.h
index bc43411f..03d56f5a 100644
--- a/src/native/nota.engine/src/devices/Instrument.h
+++ b/src/native/nota.engine/src/devices/Instrument.h
@@ -8,6 +8,7 @@
#pragma once
+#include <algorithm>
#include <atomic>
#include <cstdint>
#include <limits>
@@ -134,6 +135,60 @@ class Instrument {
virtual int32_t sidechainSourceTrackId() const { return -1; }
virtual void setSidechainSourceTrackId(int32_t /*trackId*/) {}
virtual void setSidechain(const float* /*interleaved*/, int32_t /*frames*/) {}
+ // The part of the source track's instrument React listens to (specs/050), 0 = the whole
+ // track; see Device::sidechainPart. Read by the engine.
+ uint64_t sidechainPart() const { return scPart_.load(std::memory_order_relaxed); }
+ void setSidechainPart(uint64_t part) { scPart_.store(part, std::memory_order_relaxed); }
+
+ // --- Parts (specs/050): an instrument with several sounding parts — a Drum Rack's pads, an
+ // Instrument Rack's chains (first level), Nota Rhythm's voices — lets a sidechain key listen
+ // to one of them. A part has a stable id (survives reorder / insert / delete of others; 0 is
+ // never a part) and a current index. Message thread, except setPartTaps.
+ virtual int32_t partCount() const { return 0; }
+ virtual uint64_t partId(int32_t /*index*/) const { return 0; }
+ virtual int32_t partIndex(uint64_t /*id*/) const { return -1; }
+ virtual std::string partName(int32_t /*index*/) const { return {}; }
+ // Audio thread, right before a block's renders: the parts keys listen to this block and
+ // where their signal goes. pre = the part before its own inserts, post = after its inserts
+ // and its gain / pan, before the instrument sums it (stereo interleaved, the whole block,
+ // ADDED into). The instrument copies the table; the engine clears it with (nullptr, 0).
+ struct PartTap {
+ uint64_t part;
+ float* pre;
+ float* post;
+ };
+ virtual void setPartTaps(const PartTap* /*taps*/, int32_t /*n*/) {}
+
+ // The copy a multi-part instrument keeps. A block may render in several pieces (split at
+ // MIDI events), so it also tracks where in the block the next piece starts: take(frames)
+ // returns that offset and moves past the piece.
+ class PartTaps {
+ public:
+ static constexpr int32_t kMax = 16; // == the engine's route pool
+ void set(const PartTap* taps, int32_t n) {
+ n_ = taps ? std::min(n, kMax) : 0;
+ for (int32_t i = 0; i < n_; ++i) taps_[i] = taps[i];
+ pos_ = 0;
+ }
+ bool any() const { return n_ > 0; }
+ const PartTap* find(uint64_t part) const {
+ for (int32_t i = 0; i < n_; ++i)
+ if (taps_[i].part == part) return &taps_[i];
+ return nullptr;
+ }
+ int32_t count() const { return n_; }
+ const PartTap& at(int32_t i) const { return taps_[i]; }
+ int32_t take(int32_t frames) {
+ const int32_t p = pos_;
+ pos_ += frames;
+ return p;
+ }
+
+ private:
+ PartTap taps_[kMax] = {};
+ int32_t n_ = 0;
+ int32_t pos_ = 0;
+ };
// Reported processing latency, for PDC (M3-7). 0 for built-ins.
virtual int32_t latencySamples() const { return 0; }
@@ -260,6 +315,7 @@ class Instrument {
}
std::atomic<bool> bypassed_{false};
uint64_t uid_ = nextUid();
+ std::atomic<uint64_t> scPart_{0};
};
} // namespace nota
diff --git a/src/native/nota.engine/src/devices/instruments/RhythmMachine.cpp b/src/native/nota.engine/src/devices/instruments/RhythmMachine.cpp
index 1533d985..ee712e18 100644
--- a/src/native/nota.engine/src/devices/instruments/RhythmMachine.cpp
+++ b/src/native/nota.engine/src/devices/instruments/RhythmMachine.cpp
@@ -591,6 +591,7 @@ void RhythmMachine::allNotesOff() {
void RhythmMachine::render(float* out, int32_t frames) {
const SnapshotHistory<FxState>::RenderScope done(fxStates_);
+ const int32_t tapAt = taps_.take(frames); // this piece's first frame in the block's key buffers
if (idle_) {
// Mirror the sequencer clock over the skipped span (no step can trigger while
// idle — a sounding step would have kept us awake — but arming and the step
@@ -661,13 +662,25 @@ void RhythmMachine::render(float* out, int32_t frames) {
// Per-block voice param snapshots (floats cross into the voice DSP by value).
RhythmVoiceDsp::Params vp[kVoices];
for (int v = 0; v < kVoices; ++v) vp[v] = voiceParams(v);
+ // Voices a sidechain key listens to (specs/050): where their Pre / Post go this block.
+ // A keyed voice renders into its own buffer like a voice with FX does, and its Pre / Post
+ // are taken from that buffer once per chunk — the per-sample voice loop stays as it is.
+ const PartTap* tap[kVoices] = {};
+ bool own[kVoices] = {false};
+ bool anyOwn = anyFx;
+ for (int v = 0; v < kVoices; ++v) own[v] = hasFx[v];
+ for (int32_t t = 0; t < taps_.count(); ++t)
+ if (const int32_t v = partIndex(taps_.at(t).part); v >= 0) {
+ tap[v] = &taps_.at(t);
+ own[v] = anyOwn = true;
+ }
float ownPeak = 0.0f;
for (int32_t base = 0; base < frames; base += kChunk) {
const int32_t n = std::min<int32_t>(kChunk, frames - base);
std::memset(mix_, 0, sizeof(float) * n * 2);
- if (anyFx)
+ if (anyOwn)
for (int v = 0; v < kVoices; ++v)
- if (hasFx[v]) std::memset(vbuf_[v], 0, sizeof(float) * n * 2);
+ if (own[v]) std::memset(vbuf_[v], 0, sizeof(float) * n * 2);
for (int32_t j = 0; j < n; ++j) {
const int32_t i = base + j;
// --- sequencer clock ---
@@ -711,19 +724,26 @@ void RhythmMachine::render(float* out, int32_t frames) {
const float pan = std::clamp(get2(v, Pan) * 2.0f - 1.0f, -1.0f, 1.0f);
const float gl = (pan <= 0.0f ? 1.0f : 1.0f - pan);
const float gr = (pan >= 0.0f ? 1.0f : 1.0f + pan);
- float* dst = hasFx[v] ? vbuf_[v] : mix_;
+ float* dst = own[v] ? vbuf_[v] : mix_;
dst[j * 2] += sl * gl;
dst[j * 2 + 1] += sr * gr;
}
}
// --- voice FX: every chain runs each chunk, so its tail rings out after the hit ---
- if (anyFx)
+ // (and keyed voices: Pre before the FX, Post after them)
+ if (anyOwn)
for (int v = 0; v < kVoices; ++v) {
- if (!hasFx[v]) continue;
- for (auto& d : fx->chain[v])
- if (d && !d->bypassed()) d->process(vbuf_[v], n);
+ if (!own[v]) continue;
+ if (tap[v])
+ for (int32_t k = 0; k < n * 2; ++k) tap[v]->pre[(tapAt + base) * 2 + k] += vbuf_[v][k];
+ if (hasFx[v])
+ for (auto& d : fx->chain[v])
+ if (d && !d->bypassed()) d->process(vbuf_[v], n);
for (int32_t k = 0; k < n * 2; ++k) mix_[k] += std::isfinite(vbuf_[v][k]) ? vbuf_[v][k] : 0.0f;
+ if (tap[v])
+ for (int32_t k = 0; k < n * 2; ++k)
+ tap[v]->post[(tapAt + base) * 2 + k] += std::isfinite(vbuf_[v][k]) ? vbuf_[v][k] : 0.0f;
}
// --- bus: glue + volume ---
diff --git a/src/native/nota.engine/src/devices/instruments/RhythmMachine.h b/src/native/nota.engine/src/devices/instruments/RhythmMachine.h
index 859a4b2a..e0341ad2 100644
--- a/src/native/nota.engine/src/devices/instruments/RhythmMachine.h
+++ b/src/native/nota.engine/src/devices/instruments/RhythmMachine.h
@@ -200,6 +200,23 @@ class RhythmMachine final : public Instrument {
void render(float* out, int32_t frames) override;
+ // Parts (specs/050): each voice is a sidechain sub-source. A voice's id carries this
+ // instrument's identity (its uid, kept through undo) and the top bit, so a fresh Rhythm put
+ // in its place — or a rack chain uid — never answers to an old key. Pre = the voice (with
+ // its pan) before its voice FX, Post = after them, before Glue and Volume.
+ int32_t partCount() const override { return kVoices; }
+ uint64_t partId(int32_t index) const override {
+ return index >= 0 && index < kVoices ? kVoiceTag | (uid() << 4) | static_cast<uint64_t>(index + 1) : 0;
+ }
+ int32_t partIndex(uint64_t id) const override {
+ const int32_t v = static_cast<int32_t>(id & 0xF) - 1;
+ return v >= 0 && v < kVoices && id == partId(v) ? v : -1;
+ }
+ std::string partName(int32_t index) const override {
+ return index >= 0 && index < kVoices ? std::to_string(index + 1) + " " + kVoiceNames[index] : std::string{};
+ }
+ void setPartTaps(const PartTap* taps, int32_t n) override { taps_.set(taps, n); }
+
// Sleep contract: see the header note. noteOn/action/pluginParamSet wake, as does a
// transport start (a stopped machine with a pattern must not sleep through the downbeat).
bool hasTail() const override { return true; }
@@ -295,6 +312,8 @@ class RhythmMachine final : public Instrument {
std::string kit_; // factory kit label (message thread)
std::string macroNames_[kMacros]; // custom macro names ("" = "Macro N"; message thread)
float mix_[kChunk * 2]; // audio thread: the chunk's sum
+ static constexpr uint64_t kVoiceTag = 1ull << 63;
+ PartTaps taps_; // this block's keyed voices (specs/050); audio thread
float vbuf_[kVoices][kChunk * 2]; // audio thread: FX voices, pre-chain
// Auto-sleep hangover.
diff --git a/src/native/nota.engine/src/devices/racks/DrumRack.cpp b/src/native/nota.engine/src/devices/racks/DrumRack.cpp
index 0c478055..829341b8 100644
--- a/src/native/nota.engine/src/devices/racks/DrumRack.cpp
+++ b/src/native/nota.engine/src/devices/racks/DrumRack.cpp
@@ -49,6 +49,7 @@ void DrumRack::allNotesOff() {
void DrumRack::render(float* out, int32_t frames) {
const auto done = renderScope();
+ const int32_t tapAt = taps_.take(frames) * 2; // this piece's place in the block's key buffers
RackState* st = live();
if (!st || frames <= 0 || frames > kMaxBlock) return;
bool anySolo = false;
@@ -62,13 +63,18 @@ void DrumRack::render(float* out, int32_t frames) {
if (!c.instrument) continue;
const bool solo = c.ctl->solo.load(std::memory_order_relaxed);
const bool mute = c.ctl->mute.load(std::memory_order_relaxed);
- if (mute || (anySolo && !solo)) {
+ // A pad a sidechain key listens to (specs/050) renders even when muted or solo-gated:
+ // the "ghost kick" drives the key without being heard.
+ const PartTap* tap = taps_.any() ? taps_.find(c.uid) : nullptr;
+ const bool silent = mute || (anySolo && !solo);
+ if (silent && !tap) {
c.ctl->meter.store(0.0f, std::memory_order_relaxed);
c.ctl->retrig = false;
continue;
}
std::memset(scratch_, 0, sizeof(float) * frames * 2);
c.instrument->render(scratch_, frames);
+ if (tap) addTap(tap->pre + tapAt, scratch_, frames); // Pre: the raw hit, before inserts and decay
for (auto& d : c.devices)
if (d && !d->bypassed()) d->process(scratch_, frames);
const float g = c.ctl->gain.load(std::memory_order_relaxed);
@@ -91,6 +97,28 @@ void DrumRack::render(float* out, int32_t frames) {
coef = (float)std::exp(-1.0 / (tauMs * 0.001 * sampleRate_));
}
+ // Post for a keyed pad: after inserts, decay and the pad's own gain / pan, before the
+ // rack volume. Its own pass (the envelope run from the same start), so the sum loop
+ // below is the same code an unkeyed pad runs. A ghost pad (muted / solo-gated) stops
+ // here: its envelope moves on, nothing reaches the sum.
+ if (tap) {
+ const float pl = g * (pan > 0.0f ? 1.0f - pan : 1.0f);
+ const float pr = g * (pan < 0.0f ? 1.0f + pan : 1.0f);
+ float e = env;
+ float* post = tap->post + tapAt;
+ for (int32_t i = 0; i < frames; ++i) {
+ const float k = shaped ? e : 1.0f;
+ post[i * 2] += scratch_[i * 2] * k * pl;
+ post[i * 2 + 1] += scratch_[i * 2 + 1] * k * pr;
+ if (shaped) e *= coef;
+ }
+ if (silent) {
+ if (shaped) c.ctl->ampEnv.store(e, std::memory_order_relaxed);
+ c.ctl->meter.store(0.0f, std::memory_order_relaxed);
+ continue;
+ }
+ }
+
float peak = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
float l = scratch_[i * 2], r = scratch_[i * 2 + 1];
diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp b/src/native/nota.engine/src/devices/racks/RackInstrument.cpp
index 63b95f4e..05cd5e8a 100644
--- a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp
+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.cpp
@@ -338,6 +338,7 @@ bool RackInstrument::supportsMpe() const {
void RackInstrument::render(float* out, int32_t frames) {
const auto done = renderScope();
+ const int32_t tapAt = taps_.take(frames) * 2; // this piece's place in the block's key buffers
RackState* st = live();
if (!st || frames <= 0 || frames > kMaxBlock) return;
bool anySolo = false;
@@ -365,7 +366,11 @@ void RackInstrument::render(float* out, int32_t frames) {
if (!c.instrument) continue;
const bool solo = c.ctl->solo.load(std::memory_order_relaxed);
const bool mute = c.ctl->mute.load(std::memory_order_relaxed);
- if (mute || (anySolo && !solo)) {
+ // A chain a sidechain key listens to (specs/050) renders even when muted or solo-gated
+ // — the "ghost" chain feeds its key without being heard.
+ const PartTap* tap = taps_.any() ? taps_.find(c.uid) : nullptr;
+ const bool silent = mute || (anySolo && !solo);
+ if (silent && !tap) {
c.ctl->meter.store(0.0f, std::memory_order_relaxed);
// A silent MIDI chain still takes its notes, so a note held across an unmute ends.
const int32_t ci = static_cast<int32_t>(&c - st->chains.data());
@@ -399,12 +404,23 @@ void RackInstrument::render(float* out, int32_t frames) {
} else {
c.instrument->render(scratch_, frames);
}
+ if (tap) addTap(tap->pre + tapAt, scratch_, frames); // Pre: the chain before its inserts
for (auto& d : c.devices)
if (d && !d->bypassed()) d->process(scratch_, frames);
const float g = c.ctl->gain.load(std::memory_order_relaxed);
const float pan = c.ctl->pan.load(std::memory_order_relaxed);
- const float lg = g * rv * (pan > 0.0f ? 1.0f - pan : 1.0f);
- const float rg = g * rv * (pan < 0.0f ? 1.0f + pan : 1.0f);
+ const float pl = g * (pan > 0.0f ? 1.0f - pan : 1.0f); // the chain's own gain / pan
+ const float pr = g * (pan < 0.0f ? 1.0f + pan : 1.0f);
+ if (tap) // Post: after its inserts and gain / pan, before the rack volume and the sum
+ for (int32_t i = 0; i < frames; ++i) {
+ tap->post[tapAt + i * 2] += scratch_[i * 2] * pl;
+ tap->post[tapAt + i * 2 + 1] += scratch_[i * 2 + 1] * pr;
+ }
+ if (silent) {
+ c.ctl->meter.store(0.0f, std::memory_order_relaxed);
+ continue;
+ }
+ const float lg = pl * rv, rg = pr * rv;
float peak = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
const float l = scratch_[i * 2], r = scratch_[i * 2 + 1];
@@ -418,6 +434,27 @@ void RackInstrument::render(float* out, int32_t frames) {
blockPos_ += frames; // the next segment of this block starts here
}
+// ---- parts (specs/050) ------------------------------------------------------------------
+int32_t RackInstrument::partCount() const {
+ RackState* st = live();
+ return st ? static_cast<int32_t>(st->chains.size()) : 0;
+}
+
+int32_t RackInstrument::partIndex(uint64_t id) const {
+ RackState* st = live();
+ if (!st || id == 0) return -1;
+ for (size_t i = 0; i < st->chains.size(); ++i)
+ if (st->chains[i].uid == id) return static_cast<int32_t>(i);
+ return -1;
+}
+
+std::string RackInstrument::partName(int32_t index) const {
+ std::string n = chainName(index);
+ if (!n.empty()) return n;
+ Instrument* in = chainInstrument(index);
+ return in ? in->displayName() : std::string{};
+}
+
std::shared_ptr<Instrument> RackInstrument::clone() const {
auto r = std::make_shared<RackInstrument>();
r->setSampleRate(sampleRate_);
diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.h b/src/native/nota.engine/src/devices/racks/RackInstrument.h
index c5fbd2fc..1b7716c8 100644
--- a/src/native/nota.engine/src/devices/racks/RackInstrument.h
+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.h
@@ -61,6 +61,13 @@ class RackInstrument : public Instrument, public RackCore {
int32_t latencySamples() const override { return maxChainLatency(); }
+ // ---- parts (specs/050): each chain is a sidechain sub-source, by its chain uid ----------
+ int32_t partCount() const override;
+ uint64_t partId(int32_t index) const override { return chainBaseUid(index); }
+ int32_t partIndex(uint64_t id) const override;
+ std::string partName(int32_t index) const override; // the chain name, else its instrument's
+ void setPartTaps(const PartTap* taps, int32_t n) override { taps_.set(taps, n); }
+
// A fork for an undoable edit plays on with the same held keys, sounding note and glide.
void shareMonoWith(const RackInstrument& o) { mono_ = o.mono_; }
@@ -80,6 +87,13 @@ class RackInstrument : public Instrument, public RackCore {
protected:
float scratch_[kMaxBlock * 2]; // per-chain render buffer (DrumRack reuses it)
+ // Where this block's keyed chains go (specs/050): audio thread, set by the engine around a
+ // block's renders. A short scan — at most one entry per route slot.
+ static void addTap(float* dst, const float* src, int32_t frames) {
+ for (int32_t i = 0; i < frames * 2; ++i) dst[i] += src[i];
+ }
+ PartTaps taps_;
+
private:
// Fan a note-on out to the chains whose zone holds it; with glideFrom >= 0 the chains
// that take per-note bend start bent to the previous pitch and glide back (mono).
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index 6832eb6a..5f6f61dc 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -35,6 +35,8 @@ Engine::Engine()
for (auto& b : routeBusPre_) b.assign(kMaxBlock * 2, 0.0f); // Phase D pre-FX tap
for (auto& b : routeBusPreNext_) b.assign(kMaxBlock * 2, 0.0f);
for (auto& s : routeSlotTrackId_) s.store(-1, std::memory_order_relaxed);
+ for (auto& s : routeSlotPart_) s.store(0, std::memory_order_relaxed);
+ silentKey_.assign(kMaxBlock * 2, 0.0f); // the key of a part that is gone (specs/050)
ensureRenderScratch(authoring_->tracks.size());
liveGraph_.store(authoring_.get(), std::memory_order_release);
retired_.push_back(authoring_);
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index 101fefa2..37944938 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -294,8 +294,12 @@ class Engine {
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,
+ int32_t rackChainSetSidechain(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t src, int32_t tapPre,
float gainDb, float mix);
+ bool rackChainSidechainPart(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t* part) const;
+ int32_t rackChainSetSidechainPart(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t part);
+ int32_t rackChainSetKey(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t src, int32_t part,
+ 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) ---
@@ -881,6 +885,27 @@ class Engine {
int32_t instrumentSidechainSource(int32_t trackId) const;
bool instrumentAcceptsSidechain(int32_t trackId) const;
void recomputeRouting(); // message thread: assign route-bus slots to source tracks
+ // Sidechain sub-sources (specs/050). Parts are addressed by their current index on the
+ // source track's instrument (-1 = the whole track); the key keeps the part's stable id.
+ // Set: 0 done, -1 bad address / part, -2 no free route (the key is left as it was).
+ // Get: *part -1 whole track, -2 the keyed part is gone (the key is silent).
+ int32_t trackPartCount(int32_t trackId) const;
+ std::string trackPartName(int32_t trackId, int32_t index) const;
+ int32_t setDeviceSidechainKey(int32_t trackId, int32_t deviceIndex, int32_t sourceTrackId, int32_t part);
+ bool deviceSidechainKey(int32_t trackId, int32_t deviceIndex, int32_t* source, int32_t* part) const;
+ int32_t setInstrumentSidechainKey(int32_t trackId, int32_t sourceTrackId, int32_t part);
+ bool instrumentSidechainKey(int32_t trackId, int32_t* source, int32_t* part) const;
+ int32_t sidechainRoutesFree() const;
+ static constexpr int32_t kSidechainRoutes = 16; // == kMaxRoutes (private)
+ bool sidechainRouteInUse(int32_t sourceTrackId, int32_t part) const;
+ // A key's part as an index on its source track now (-1 whole track, -2 gone), and back
+ // (index -1 → 0; an index that isn't a part → no value). Message thread.
+ int32_t partIndexOf(int32_t sourceTrackId, uint64_t part) const;
+ bool partIdAt(int32_t sourceTrackId, int32_t index, uint64_t* part) const;
+ template <typename Consumer>
+ int32_t applySidechainKey(Consumer& c, int32_t src, uint64_t part, bool routed = true);
+ template <typename Fn>
+ void forEachRouteKey(Fn&& fn) const;
// Open/close a hosted plugin's native GUI. deviceIndex < 0 = the instrument;
// otherwise the effect at that chain position. Message thread only.
void openTrackEditor(int32_t trackId, int32_t deviceIndex);
@@ -2229,15 +2254,42 @@ class Engine {
// the cost of one block of detector latency — inaudible after attack/release.
// Each source slot mirrors two tap points so consumers can pick (Phase D):
// routeBus{Post,Pre}_ = post-FX post-fader and pre-FX pre-fader signal.
- static constexpr int32_t kMaxRoutes = 8;
+ // A slot may also mirror one part of the source's instrument (specs/050): a Drum Rack pad,
+ // an Instrument Rack chain or a Rhythm voice, filled from inside the instrument's render
+ // (Instrument::setPartTaps). For a part, Pre = the part before its own inserts and Post =
+ // after its inserts and gain / pan, before the instrument sums it. Whole tracks and parts
+ // share the pool.
+ static constexpr int32_t kMaxRoutes = kSidechainRoutes;
std::array<std::vector<float>, kMaxRoutes> routeBus_, routeBusNext_; // post-FX (post-fader)
std::array<std::vector<float>, kMaxRoutes> routeBusPre_, routeBusPreNext_; // pre-FX (pre-fader)
std::atomic<int32_t> routeSlotTrackId_[kMaxRoutes]; // which source track each slot mirrors (-1 = free)
- int32_t routeSlotForTrack(int32_t trackId) const { // audio + message thread; scan is tiny
- for (int32_t s = 0; s < kMaxRoutes; ++s)
- if (routeSlotTrackId_[s].load(std::memory_order_relaxed) == trackId) return s;
+ std::atomic<uint64_t> routeSlotPart_[kMaxRoutes]; // which part of it (0 = the whole track)
+ // recomputeRouting fills slots 0..count-1 in order, so lookups scan only the used ones — a
+ // project without sidechains pays one load per lookup, and these run several times per
+ // track per block. A reroute racing a block can mis-key that one block (as it always could:
+ // the table is cleared and refilled in place), never touch a buffer out of range.
+ std::atomic<int32_t> routeSlotCount_{0};
+ std::vector<float> silentKey_; // kMaxBlock stereo zeros: the key of a part that is gone
+ void feedPartTaps(const Track& t); // audio thread
+ const float* keyBuffer(int32_t src, uint64_t part, bool pre) const; // audio thread
+ // Audio + message thread.
+ int32_t routeSlotFor(int32_t trackId, uint64_t part) const {
+ const int32_t n = routeSlotCount_.load(std::memory_order_acquire);
+ for (int32_t s = 0; s < n; ++s)
+ if (routeSlotTrackId_[s].load(std::memory_order_relaxed) == trackId &&
+ routeSlotPart_[s].load(std::memory_order_relaxed) == part)
+ return s;
return -1;
}
+ int32_t routeSlotForTrack(int32_t trackId) const { return routeSlotFor(trackId, 0); }
+ // Whether any slot (whole track or one of its parts) mirrors this track: it keeps rendering
+ // while muted or solo-gated, for its taps.
+ bool trackFeedsRoute(int32_t trackId) const {
+ const int32_t n = routeSlotCount_.load(std::memory_order_acquire);
+ for (int32_t s = 0; s < n; ++s)
+ if (routeSlotTrackId_[s].load(std::memory_order_relaxed) == trackId) return true;
+ return false;
+ }
};
} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cpp
index eed2b1fe..e57e8d2e 100644
--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp
@@ -334,6 +334,7 @@ bool Engine::setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::str
auto sample = decodeAudioFile(path);
if (!sample || sample->empty()) return false;
auto fresh = std::static_pointer_cast<RhythmMachine>(rh->clone()); // copies params/patterns/samples
+ fresh->adoptUid(*rh); // an edit, not a new instrument: voice keys keep pointing here (specs/050)
fresh->setVoiceSample(voice, sample);
fresh->presetTag = rh->presetTag; // still the preset it was loaded from (specs/048)
auto nt = cloneTrack(*old);
@@ -696,6 +697,7 @@ std::shared_ptr<Device> Engine::cloneDevice(const Device& src) const {
d->setPresetTag(src.presetTag()); // the preset it was loaded from (specs/048)
d->setEditorPreview(src.editorPreview()); // shared bytes: the same picture (specs/046)
d->setSidechainSourceTrackId(src.sidechainSourceTrackId()); // a keyed device keeps its key
+ d->setSidechainPart(src.sidechainPart());
d->setSidechainTapPre(src.sidechainTapPre());
d->setSidechainGainDb(src.sidechainGainDb());
d->setSidechainMix(src.sidechainMix());
@@ -894,6 +896,7 @@ int32_t Engine::transferDevice(int32_t srcId, int32_t family, int32_t index, int
if (dev == sd) dev = cloneDevice(*sd);
if (!dev) return -3;
dev->setSidechainSourceTrackId(-1);
+ dev->setSidechainPart(0);
flags |= kTransferSidechainCleared;
}
if (ns) {
@@ -1090,7 +1093,10 @@ int32_t Engine::pasteDevices(int32_t trackId, int32_t midiAt, int32_t fxAt, int3
} else if (e.dev) {
auto c = cloneDevice(*e.dev);
if (!c) return -3;
- if (c->sidechainSourceTrackId() == trackId) c->setSidechainSourceTrackId(-1); // no key from itself
+ if (c->sidechainSourceTrackId() == trackId) { // no key from itself
+ c->setSidechainSourceTrackId(-1);
+ c->setSidechainPart(0);
+ }
devs.push_back(std::move(c));
}
}
@@ -1488,7 +1494,10 @@ std::string Engine::deviceText(int32_t trackId, int32_t deviceIndex, int32_t id)
}
void Engine::setDeviceSidechainSource(int32_t trackId, int32_t deviceIndex, int32_t sourceTrackId) {
- if (auto* d = deviceAt(trackId, deviceIndex)) d->setSidechainSourceTrackId(sourceTrackId);
+ if (auto* d = deviceAt(trackId, deviceIndex)) {
+ d->setSidechainSourceTrackId(sourceTrackId);
+ d->setSidechainPart(0); // a whole-track key
+ }
recomputeRouting();
}
@@ -1527,7 +1536,10 @@ int32_t Engine::deviceSidechainTapPre(int32_t trackId, int32_t deviceIndex) cons
// Instrument sidechain ("React", Nota Flux): route a listening instrument to a source track.
void Engine::setInstrumentSidechainSource(int32_t trackId, int32_t sourceTrackId) {
auto t = findTrackAuthoring(trackId);
- if (t && t->instrument) t->instrument->setSidechainSourceTrackId(sourceTrackId);
+ if (t && t->instrument) {
+ t->instrument->setSidechainSourceTrackId(sourceTrackId);
+ t->instrument->setSidechainPart(0); // a whole-track key
+ }
recomputeRouting();
}
int32_t Engine::instrumentSidechainSource(int32_t trackId) const {
@@ -1544,37 +1556,179 @@ bool Engine::instrumentAcceptsSidechain(int32_t trackId) const {
// instrument pointers are stable across snapshots, so the table the audio thread reads
// stays valid).
void Engine::recomputeRouting() {
- for (auto& s : routeSlotTrackId_) s.store(-1, std::memory_order_relaxed);
+ // Slots at and past the count are always free, so only the used ones need clearing.
+ const int32_t used = routeSlotCount_.load(std::memory_order_relaxed);
+ routeSlotCount_.store(0, std::memory_order_release);
+ for (int32_t s = 0; s < used; ++s) routeSlotTrackId_[s].store(-1, std::memory_order_relaxed);
int32_t next = 0;
// A source that is not in the graph (its track was deleted; undo brings it back) gets no
- // slot, so its consumers see no key at all rather than a silent one.
- auto exists = [&](int32_t id) {
+ // slot, so its consumers see no key at all rather than a silent one. A part key whose part
+ // is gone (the pad deleted, the rack replaced; specs/050) likewise.
+ auto exists = [&](int32_t id, uint64_t part) {
for (auto& t : authoring_->tracks)
- if (t->id() == id) return true;
+ if (t->id() == id) return part == 0 || (t->instrument && t->instrument->partIndex(part) >= 0);
return false;
};
- auto claim = [&](int32_t src) {
- if (src < 0 || routeSlotForTrack(src) >= 0 || !exists(src)) return; // none / already assigned / gone
- if (next < kMaxRoutes) routeSlotTrackId_[next++].store(src, std::memory_order_relaxed);
+ auto claim = [&](int32_t src, uint64_t part) {
+ if (src < 0 || routeSlotFor(src, part) >= 0 || !exists(src, part)) return; // none / already assigned / gone
+ if (next < kMaxRoutes) {
+ routeSlotPart_[next].store(part, std::memory_order_relaxed);
+ routeSlotTrackId_[next++].store(src, std::memory_order_relaxed);
+ routeSlotCount_.store(next, std::memory_order_release); // claim() looks up as it goes
+ }
};
+ forEachRouteKey([&](int32_t src, uint64_t part) { claim(src, part); });
+}
+
+// Every route a consumer asks for, in claim order: track instruments and devices (and keyed
+// children inside their racks, specs/044), then a monitoring audio track's input source.
+template <typename Fn>
+void Engine::forEachRouteKey(Fn&& fn) const {
for (auto& t : authoring_->tracks) {
- // 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()); });
+ auto children = [&](const RackCore& r) {
+ r.forEachChildDevice([&](Device& c) { fn(c.sidechainSourceTrackId(), c.sidechainPart()); });
+ r.forEachChildInstrument([&](Instrument& i) { fn(i.sidechainSourceTrackId(), i.sidechainPart()); });
};
if (t->instrument) {
- claim(t->instrument->sidechainSourceTrackId());
- if (auto* r = t->instrument->asRack()) claimChildren(*r);
+ fn(t->instrument->sidechainSourceTrackId(), t->instrument->sidechainPart());
+ if (auto* r = t->instrument->asRack()) children(*r);
}
for (auto& d : t->devices)
if (d) {
- claim(d->sidechainSourceTrackId());
- if (auto* r = d->asRack()) claimChildren(*r);
+ fn(d->sidechainSourceTrackId(), d->sidechainPart());
+ if (auto* r = d->asRack()) children(*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());
+ if (t->type() == TrackType::Audio && t->monitor() && t->recordInputSource() > 0) fn(t->recordInputSource(), uint64_t{0});
+ }
+}
+
+// ---- Sidechain sub-sources (specs/050) -------------------------------------------------
+
+int32_t Engine::trackPartCount(int32_t trackId) const {
+ auto t = findTrackAuthoring(trackId);
+ return t && t->instrument ? t->instrument->partCount() : 0;
+}
+
+std::string Engine::trackPartName(int32_t trackId, int32_t index) const {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || !t->instrument || index < 0 || index >= t->instrument->partCount()) return {};
+ return t->instrument->partName(index);
+}
+
+int32_t Engine::partIndexOf(int32_t sourceTrackId, uint64_t part) const {
+ if (part == 0) return -1;
+ auto t = findTrackAuthoring(sourceTrackId);
+ const int32_t i = t && t->instrument ? t->instrument->partIndex(part) : -1;
+ return i >= 0 ? i : -2;
+}
+
+bool Engine::partIdAt(int32_t sourceTrackId, int32_t index, uint64_t* part) const {
+ if (index == -1) {
+ *part = 0;
+ return true;
+ }
+ auto t = findTrackAuthoring(sourceTrackId);
+ if (!t || !t->instrument || index < 0 || index >= t->instrument->partCount()) return false;
+ *part = t->instrument->partId(index);
+ return *part != 0;
+}
+
+// Set a key, then keep it only if it got a route and took none from another listener: a full
+// pool leaves the previous key in place. Routes are claimed in track and chain order, so a new
+// source on an early device could otherwise push out a later device's. Re-deriving the table
+// (rather than counting free slots) lets a consumer move to another source while the pool is
+// full when it was its old source's only listener.
+template <typename Consumer>
+int32_t Engine::applySidechainKey(Consumer& c, int32_t src, uint64_t part, bool routed) {
+ if (!routed) { // the master's devices are never fed a key (their key is only kept): no route to check
+ c.setSidechainSourceTrackId(src);
+ c.setSidechainPart(part);
+ recomputeRouting();
+ return 0;
+ }
+ const int32_t oldSrc = c.sidechainSourceTrackId();
+ const uint64_t oldPart = c.sidechainPart();
+ std::pair<int32_t, uint64_t> before[kMaxRoutes];
+ const int32_t nBefore = routeSlotCount_.load(std::memory_order_relaxed);
+ for (int32_t s = 0; s < nBefore; ++s)
+ before[s] = {routeSlotTrackId_[s].load(std::memory_order_relaxed), routeSlotPart_[s].load(std::memory_order_relaxed)};
+ c.setSidechainSourceTrackId(src);
+ c.setSidechainPart(part);
+ recomputeRouting();
+ bool kept = routeSlotFor(src, part) >= 0;
+ bool oldHeld = false; // does anyone still listen to the old key?
+ forEachRouteKey([&](int32_t t, uint64_t p) { oldHeld = oldHeld || (t == oldSrc && p == oldPart); });
+ for (int32_t s = 0; kept && s < nBefore; ++s) {
+ const auto [t, p] = before[s];
+ // The old key's route may go when this was its only listener; every other must stay.
+ if (routeSlotFor(t, p) < 0 && (oldHeld || !(t == oldSrc && p == oldPart))) kept = false;
}
+ if (kept) return 0;
+ c.setSidechainSourceTrackId(oldSrc);
+ c.setSidechainPart(oldPart);
+ recomputeRouting();
+ return -2;
+}
+
+// Rack children (Engine_Rack.cpp) set their keys through the same check.
+template int32_t Engine::applySidechainKey<Device>(Device&, int32_t, uint64_t, bool);
+template int32_t Engine::applySidechainKey<Instrument>(Instrument&, int32_t, uint64_t, bool);
+
+int32_t Engine::setDeviceSidechainKey(int32_t trackId, int32_t deviceIndex, int32_t sourceTrackId, int32_t part) {
+ auto* d = deviceAt(trackId, deviceIndex);
+ if (!d) return -1;
+ if (sourceTrackId < 0) {
+ setDeviceSidechainSource(trackId, deviceIndex, -1);
+ return 0;
+ }
+ // A MIDI key (Nota Auto Shift) follows the source track's notes; a pad has none of its own.
+ if (part >= 0 && d->wantsMidiKey()) return -1;
+ uint64_t id = 0;
+ if (!findTrackAuthoring(sourceTrackId) || !partIdAt(sourceTrackId, part, &id)) return -1;
+ return applySidechainKey(*d, sourceTrackId, id, trackId != kMasterTrackId);
+}
+
+bool Engine::deviceSidechainKey(int32_t trackId, int32_t deviceIndex, int32_t* source, int32_t* part) const {
+ auto* d = deviceAt(trackId, deviceIndex);
+ if (!d) return false;
+ const int32_t src = d->sidechainSourceTrackId();
+ if (source) *source = src;
+ if (part) *part = src < 0 ? -1 : partIndexOf(src, d->sidechainPart());
+ return true;
+}
+
+int32_t Engine::setInstrumentSidechainKey(int32_t trackId, int32_t sourceTrackId, int32_t part) {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || !t->instrument) return -1;
+ if (sourceTrackId < 0) {
+ setInstrumentSidechainSource(trackId, -1);
+ return 0;
+ }
+ uint64_t id = 0;
+ if (!findTrackAuthoring(sourceTrackId) || !partIdAt(sourceTrackId, part, &id)) return -1;
+ return applySidechainKey(*t->instrument, sourceTrackId, id);
+}
+
+bool Engine::instrumentSidechainKey(int32_t trackId, int32_t* source, int32_t* part) const {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || !t->instrument) return false;
+ const int32_t src = t->instrument->sidechainSourceTrackId();
+ if (source) *source = src;
+ if (part) *part = src < 0 ? -1 : partIndexOf(src, t->instrument->sidechainPart());
+ return true;
+}
+
+int32_t Engine::sidechainRoutesFree() const {
+ int32_t n = 0;
+ for (auto& s : routeSlotTrackId_)
+ if (s.load(std::memory_order_relaxed) < 0) ++n;
+ return n;
+}
+
+bool Engine::sidechainRouteInUse(int32_t sourceTrackId, int32_t part) const {
+ uint64_t id = 0;
+ return partIdAt(sourceTrackId, part, &id) && routeSlotFor(sourceTrackId, id) >= 0;
}
void Engine::openTrackEditor(int32_t trackId, int32_t deviceIndex) {
diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cpp
index 12ac4500..25c16aef 100644
--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp
@@ -213,6 +213,7 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {
r->setFolded(src->folded());
r->setPresetTag(src->presetTag());
r->setSidechainSourceTrackId(src->sidechainSourceTrackId());
+ r->setSidechainPart(src->sidechainPart());
r->setSidechainTapPre(src->sidechainTapPre());
r->setSidechainGainDb(src->sidechainGainDb());
r->setSidechainMix(src->sidechainMix());
@@ -726,25 +727,80 @@ bool Engine::rackChainSidechain(int32_t t, int32_t host, int32_t chain, int32_t
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,
+// Keys go through the same route-pool check as a track device's (specs/050): one that would
+// need a route the pool can't give — or would push out another listener's — is refused with -2
+// and the key, tap, gain and mix are left as they were.
+int32_t Engine::rackChainSetSidechain(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t src,
int32_t tapPre, float gainDb, float mix) {
+ return rackChainSetKey(t, host, chain, slot, src, -1, tapPre, gainDb, mix);
+}
+// Source and part in one step, so only the final key is checked against the pool (a whole-track
+// key on the way to a part could be refused while the part itself already has a route).
+int32_t Engine::rackChainSetKey(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t src, int32_t part,
+ int32_t tapPre, float gainDb, float mix) {
+ auto* r = rackCoreAt(t, host);
+ if (!r || isNestedRack(host)) return -1;
+ Device* d = slot >= 0 ? r->chainDeviceAt(chain, slot) : nullptr;
+ Instrument* in = slot < 0 ? r->chainInstrument(chain) : nullptr;
+ if (!d && !in) return -1;
+ int32_t rc = 0;
+ if (src < 0) {
+ if (d) {
+ d->setSidechainSourceTrackId(-1);
+ d->setSidechainPart(0);
+ } else {
+ in->setSidechainSourceTrackId(-1);
+ in->setSidechainPart(0);
+ }
+ recomputeRouting();
+ } else {
+ uint64_t id = 0;
+ if (!findTrackAuthoring(src) || !partIdAt(src, part, &id)) return -1;
+ if (d && part >= 0 && d->wantsMidiKey()) return -1; // a MIDI key takes whole tracks only
+ const bool routed = t != kMasterTrackId;
+ rc = d ? applySidechainKey(*d, src, id, routed) : applySidechainKey(*in, src, id, routed);
+ }
+ if (rc == 0 && d) { // shaping follows the key only once the key is in
+ d->setSidechainTapPre(tapPre);
+ d->setSidechainGainDb(gainDb);
+ d->setSidechainMix(mix);
+ }
+ return rc;
+}
+// The part of a chain child's key (specs/050), as an index on its source track (-1 whole
+// track, -2 gone). For save / load, after rackChainSetSidechain.
+bool Engine::rackChainSidechainPart(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t* part) const {
auto* r = rackCoreAt(t, host);
if (!r || isNestedRack(host)) return false;
+ int32_t src = -1;
+ uint64_t id = 0;
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);
+ src = d->sidechainSourceTrackId();
+ id = d->sidechainPart();
} else {
Instrument* in = r->chainInstrument(chain);
if (!in) return false;
- in->setSidechainSourceTrackId(src);
+ src = in->sidechainSourceTrackId();
+ id = in->sidechainPart();
}
- recomputeRouting();
+ if (part) *part = src < 0 ? -1 : partIndexOf(src, id);
return true;
}
+int32_t Engine::rackChainSetSidechainPart(int32_t t, int32_t host, int32_t chain, int32_t slot, int32_t part) {
+ auto* r = rackCoreAt(t, host);
+ if (!r || isNestedRack(host)) return -1;
+ Device* d = slot >= 0 ? r->chainDeviceAt(chain, slot) : nullptr;
+ Instrument* in = slot < 0 ? r->chainInstrument(chain) : nullptr;
+ if (!d && !in) return -1;
+ const int32_t src = d ? d->sidechainSourceTrackId() : in->sidechainSourceTrackId();
+ uint64_t id = 0;
+ if (src < 0 || !partIdAt(src, part, &id)) return -1;
+ if (d && part >= 0 && d->wantsMidiKey()) return -1; // a MIDI key takes whole tracks only
+ const bool routed = t != kMasterTrackId;
+ return d ? applySidechainKey(*d, src, id, routed) : applySidechainKey(*in, src, id, routed);
+}
// ---- nested addresses follow rack edits (specs/044) -----------------------
void Engine::remapNestedAfterRackEdit(int32_t trackId, int32_t host, const NestedMap& map) {
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index 6a955249..6a7030e5 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -1963,7 +1963,9 @@ void Engine::renderLeafDry(Track& t, float* dst, const LeafWork& w, Graph* g, in
case LeafPath::Frozen: fillFrozen(t, dst, frames, blockStart, spb); break;
case LeafPath::Monitor: renderMonitorInput(g, t, dst, frames); break;
case LeafPath::SessionInst:
+ feedPartTaps(t); // a Session clip plays the same pads: their keys too (specs/050)
renderSessionSlotRaw(t, dst, frames, spb);
+ if (t.instrument) t.instrument->setPartTaps(nullptr, 0);
sessionPostRender(t, frames / spb);
break;
case LeafPath::SessionAudio:
@@ -1977,28 +1979,51 @@ void Engine::renderLeafDry(Track& t, float* dst, const LeafWork& w, Graph* g, in
// previous-block, post-fader signal just before it renders.
const int32_t iSc = t.instrument->sidechainSourceTrackId();
if (iSc >= 0) {
- const int32_t s = routeSlotForTrack(iSc);
- t.instrument->setSidechain(s < 0 ? nullptr : routeBus_[s].data(), frames);
+ t.instrument->setSidechain(keyBuffer(iSc, t.instrument->sidechainPart(), false), 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);
}
+ feedPartTaps(t);
renderInstrumentRaw(g, t, dst, frames, blockStart, spb, playing);
+ if (t.instrument) t.instrument->setPartTaps(nullptr, 0);
break;
case LeafPath::AudioClips: renderAudioClipsRaw(t.clips, dst, frames, blockStart, spb); break;
case LeafPath::Skip: break; // unreachable (pre-pass filters Skip out)
}
}
+// Parts of a track's instrument that keys listen to (specs/050): hand it where each one's Pre /
+// Post goes this block (it copies the table; a block may render in pieces). The Next buses are
+// written by this track alone, so the parallel leaf render stays race-free. Audio thread.
+void Engine::feedPartTaps(const Track& t) {
+ if (!t.instrument) return;
+ Instrument::PartTap taps[kMaxRoutes];
+ int32_t nTaps = 0;
+ for (int32_t s = 0, n = routeSlotCount_.load(std::memory_order_acquire); s < n; ++s) {
+ if (routeSlotTrackId_[s].load(std::memory_order_relaxed) != t.id()) continue;
+ const uint64_t part = routeSlotPart_[s].load(std::memory_order_relaxed);
+ if (part != 0) taps[nTaps++] = {part, routeBusPreNext_[s].data(), routeBusNext_[s].data()};
+ }
+ t.instrument->setPartTaps(taps, nTaps);
+}
+
+// The key buffer for a consumer: its route slot's tap, nullptr for none — or, for a part key
+// whose part is gone (specs/050), silence: a detector handed nullptr keys off its own input,
+// and the key is shown as missing, not as Internal.
+const float* Engine::keyBuffer(int32_t src, uint64_t part, bool pre) const {
+ const int32_t s = routeSlotFor(src, part);
+ if (s >= 0) return pre ? routeBusPre_[s].data() : routeBus_[s].data();
+ return part != 0 ? silentKey_.data() : nullptr;
+}
+
// 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);
+ d.setSidechain(keyBuffer(src, d.sidechainPart(), d.sidechainTapPre() != 0), frames);
if (d.wantsMidiKey()) feedMidiKey(g, d, src);
} else if (d.wantsOwnMidiKey())
feedMidiKey(g, d, ownTrackId); // no key track: this track's notes
@@ -2012,8 +2037,7 @@ void Engine::feedRackChildKeys(Graph* g, const RackCore& r, int32_t ownTrackId,
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);
+ i.setSidechain(keyBuffer(src, i.sidechainPart(), false), frames);
});
}
@@ -2113,7 +2137,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
for (int b = 0; b < numReturns; ++b) // clear send buses for this block (M6-1)
std::fill_n(returnBus_[b].data(), frames * 2, 0.0f);
// Phase B/D: clear this block's route-write buffers (post + pre) for active slots.
- for (int s = 0; s < kMaxRoutes; ++s)
+ for (int s = 0, n = routeSlotCount_.load(std::memory_order_acquire); s < n; ++s)
if (routeSlotTrackId_[s].load(std::memory_order_relaxed) >= 0) {
std::fill_n(routeBusNext_[s].data(), frames * 2, 0.0f);
std::fill_n(routeBusPreNext_[s].data(), frames * 2, 0.0f);
@@ -2212,7 +2236,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// console's pre-fader send outlives the channel mute: a vocoder's voice track can be
// muted (or the pad soloed) and still drive the bands. Its post-fader tap is silent
// while it is muted.
- const bool keying = !audible && routeSlotForTrack(t.id()) >= 0;
+ const bool keying = !audible && trackFeedsRoute(t.id()); // whole track or a part (specs/050)
const bool postTapMuted = keying && leafMute(t);
// Input monitoring (Monitor "In"): the track plays its record-input source live
// in place of its clips — hardware input this segment, or the source track's
@@ -2667,7 +2691,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
// Phase B/D: publish this block's route taps (post + pre) for next block.
- for (int s = 0; s < kMaxRoutes; ++s)
+ for (int s = 0, n = routeSlotCount_.load(std::memory_order_acquire); s < n; ++s)
if (routeSlotTrackId_[s].load(std::memory_order_relaxed) >= 0) {
routeBus_[s].swap(routeBusNext_[s]);
routeBusPre_[s].swap(routeBusPreNext_[s]);
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index aceb210f..0fede6c9 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -501,6 +501,14 @@ if (args.Length >= 1 && args[0] == "--preset-state")
Console.WriteLine(failures == 0 ? "PRESET STATE PASSED" : $"PRESET STATE FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Sidechain sub-sources alone: `--sidechain-parts` (specs/050). Also part of the full run.
+if (args.Length >= 1 && args[0] == "--sidechain-parts")
+{
+ Console.WriteLine("-- sidechain parts --");
+ foreach (var (ok, label) in SidechainPartTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "SIDECHAIN PARTS PASSED" : $"SIDECHAIN PARTS FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Plug-in card preview alone: `--preview`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--preview")
{
@@ -15272,6 +15280,9 @@ foreach (var (ok, label) in DeviceFoldTests.Run()) Check(ok, label);
Console.WriteLine("-- preset state --");
foreach (var (ok, label) in PresetStateTests.Run()) Check(ok, label);
+Console.WriteLine("-- sidechain parts --");
+foreach (var (ok, label) in SidechainPartTests.Run()) Check(ok, label);
+
Console.WriteLine("-- eq analyzer --");
foreach (var (ok, label) in EqAnalyzerTests.Run()) Check(ok, label);
Console.WriteLine("-- eq labels --");
diff --git a/tests/Nota.SmokeTest/SidechainPartTests.cs b/tests/Nota.SmokeTest/SidechainPartTests.cs
new file mode 100644
index 00000000..f644a678
--- /dev/null
+++ b/tests/Nota.SmokeTest/SidechainPartTests.cs
@@ -0,0 +1,711 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Sidechain sub-sources (specs/050, #190): a Compressor on one track keys off a single Drum Rack
+// pad (or Instrument Rack chain) on another, Pre or Post, and only that pad drives it. The key
+// stays on its pad through edits, sleeps while the pad is deleted and wakes on undo, survives a
+// save, and a muted "ghost" pad still drives it. Whole tracks and parts share a pool of 16 routes.
+// The pads play generated sine bursts, so levels are deterministic. Also runnable alone:
+// `--sidechain-parts`.
+
+using System.Text.Json.Nodes;
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class SidechainPartTests
+{
+ private const int CompKind = 1, Thresh = 0, Ratio = 1, Attack = 2, Release = 3;
+ private const int KickNote = 36, HatNote = 42;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in KickPad()) yield return r;
+ foreach (var r in StableKey()) yield return r;
+ foreach (var r in InstrumentRackChain()) yield return r;
+ foreach (var r in RhythmVoice()) yield return r;
+ foreach (var r in RoutePool()) yield return r;
+ foreach (var r in FluxReact()) yield return r;
+ foreach (var r in EveryConsumer()) yield return r;
+ foreach (var r in Mcp()) yield return r;
+ foreach (var r in FrozenSource()) yield return r;
+ foreach (var r in CopiesKeepTheKey()) yield return r;
+ foreach (var r in SegmentedBlocks()) yield return r;
+ foreach (var r in SessionClipKeys()) yield return r;
+ foreach (var r in NoEviction()) yield return r;
+ foreach (var r in FreshRhythm()) yield return r;
+ foreach (var r in RhythmSampleEditKeepsKeys()) yield return r;
+ foreach (var r in MissingPadIsSilent()) yield return r;
+ foreach (var r in AutoShiftWholeTrackOnly()) yield return r;
+ foreach (var r in RackChildPart()) yield return r;
+ foreach (var r in SaveReopen()) yield return r;
+ }
+
+ // A 0.25 s sine burst at half scale: a stand-in drum hit with a known level.
+ private static string Wav(float hz)
+ {
+ const int rate = 44100;
+ var path = Path.Combine(Path.GetTempPath(), $"nota-scpart-{Guid.NewGuid():N}.wav");
+ var x = new float[rate / 4 * 2];
+ for (int i = 0; i < x.Length / 2; i++) x[2 * i] = x[2 * i + 1] = 0.5f * (float)Math.Sin(2 * Math.PI * hz * i / rate);
+ using (var w = new Nota.Infrastructure.WavWriter(path, rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, x.Length / 2);
+ return path;
+ }
+
+ // Drums: a Drum Rack with a hat pad (chain 0) and a kick pad (chain 1). Bass: an empty audio
+ // track with a hard Compressor, so any reduction comes from the key alone.
+ private sealed class Rig : IDisposable
+ {
+ public readonly NotaEngine E = new();
+ public readonly int Drums, Bass, Comp;
+ public Rig()
+ {
+ E.SetBpm(120);
+ Drums = E.AddDrumRackTrack();
+ E.SetTrackName(Drums, "Drums");
+ int hat = E.RackAddSamplerChain(Drums, Wav(3000), HatNote, false);
+ E.RackSetChainTriggerNote(Drums, hat, HatNote);
+ E.RackSetChainName(Drums, hat, "Hat");
+ int kick = E.RackAddSamplerChain(Drums, Wav(60), KickNote, false);
+ E.RackSetChainTriggerNote(Drums, kick, KickNote);
+ E.RackSetChainName(Drums, kick, "Kick");
+ E.AddMidiClip(Drums, 0.0, 4.0);
+ Bass = E.AddAudioTrack();
+ Comp = E.AddBuiltinDevice(Bass, CompKind);
+ E.DeviceSetParam(Bass, Comp, Thresh, -40f);
+ E.DeviceSetParam(Bass, Comp, Ratio, 10f);
+ E.DeviceSetParam(Bass, Comp, Attack, 1f);
+ E.DeviceSetParam(Bass, Comp, Release, 50f);
+ }
+ public int Chain(string name)
+ {
+ for (int c = 0; c < E.RackChainCount(Drums); c++)
+ if (E.RackChainName(Drums, c) == name) return c;
+ return -1;
+ }
+ // Only these pads play: four quarter-beat hits.
+ public void Play(params int[] notes)
+ {
+ var ns = new List<NotaNote>();
+ foreach (int n in notes)
+ for (int b = 0; b < 4; b++) ns.Add(new NotaNote(n, b, 0.25, 1.0f));
+ E.SetClipNotes(Drums, 0, ns.ToArray());
+ }
+ // The deepest reduction over two seconds, read block by block, and the master's RMS.
+ public (float gr, double rms) Run()
+ {
+ const int block = 512, blocks = 172;
+ var buf = new float[block * 2];
+ float gr = 0;
+ double sum = 0;
+ E.Seek(0);
+ E.Play();
+ for (int i = 0; i < blocks; i++)
+ {
+ E.RenderOffline(buf, block);
+ gr = Math.Max(gr, E.DeviceGainReduction(Bass, Comp));
+ foreach (var v in buf) sum += v * v;
+ }
+ E.StopTransport();
+ return (gr, Math.Sqrt(sum / (blocks * block * 2)));
+ }
+ public void Dispose() => E.Dispose();
+ }
+
+ private static IEnumerable<(bool, string)> KickPad()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int kick = rig.Chain("Kick"), hat = rig.Chain("Hat");
+ yield return (e.SidechainRouteCapacity() == 16 && e.SidechainRoutesFree() == 16, "sc parts: a pool of 16 routes, all free");
+ yield return (e.TrackPartCount(rig.Drums) == 2 && e.TrackPartName(rig.Drums, kick) == "Kick" && e.TrackPartName(rig.Drums, hat) == "Hat"
+ && e.TrackPartCount(rig.Bass) == 0, "sc parts: a Drum Rack lists its pads by name; an audio track has none");
+
+ // Whole-track key, as before: the hat alone ducks the bass (and is loud enough to).
+ e.SetDeviceSidechainSource(rig.Bass, rig.Comp, rig.Drums);
+ rig.Play(HatNote);
+ var whole = rig.Run();
+ yield return (whole.gr > 3 && e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rig.Drums, -1),
+ $"sc parts: a whole-track key still ducks on the hat ({whole.gr:F1} dB)");
+
+ // Key off the kick pad: the hat no longer ducks, the kick does — Post and Pre.
+ foreach (bool pre in new[] { false, true })
+ {
+ string tap = pre ? "Pre" : "Post";
+ e.SetDeviceSidechainTapPre(rig.Bass, rig.Comp, pre);
+ yield return (e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, kick) == 0
+ && e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rig.Drums, kick),
+ $"sc parts: key the Compressor off the kick pad ({tap})");
+ rig.Play(HatNote);
+ var h = rig.Run();
+ rig.Play(KickNote);
+ var k = rig.Run();
+ yield return (h.gr < 0.1f && k.gr > 3, $"sc parts: {tap} — only the kick pad ducks (hat {h.gr:F2} dB, kick {k.gr:F1} dB)");
+ }
+ yield return (e.SidechainRouteInUse(rig.Drums, kick) && !e.SidechainRouteInUse(rig.Drums, -1) && e.SidechainRoutesFree() == 15,
+ "sc parts: the kick pad holds one route, the whole track none");
+
+ // Pre is before the pad's own level, Post after it.
+ e.RackSetChainGain(rig.Drums, kick, 0f);
+ rig.Play(KickNote);
+ e.SetDeviceSidechainTapPre(rig.Bass, rig.Comp, true);
+ var preSilent = rig.Run();
+ e.SetDeviceSidechainTapPre(rig.Bass, rig.Comp, false);
+ var postSilent = rig.Run();
+ yield return (preSilent.gr > 3 && postSilent.gr < 0.1f,
+ $"sc parts: a pad at zero gain still keys Pre ({preSilent.gr:F1} dB), not Post ({postSilent.gr:F2} dB)");
+ e.RackSetChainGain(rig.Drums, kick, 1f);
+
+ // Ghost kick: muted (or solo-gated) it leaves the mix but still drives the key.
+ var loud = rig.Run();
+ e.RackSetChainMute(rig.Drums, kick, true);
+ var ghost = rig.Run();
+ yield return (ghost.gr > 3 && ghost.rms < loud.rms * 0.05,
+ $"sc parts: a muted kick pad keeps ducking ({ghost.gr:F1} dB) but is not heard (rms {ghost.rms:E1} vs {loud.rms:E1})");
+ e.RackSetChainMute(rig.Drums, kick, false);
+ e.RackSetChainSolo(rig.Drums, hat, true);
+ var gated = rig.Run();
+ yield return (gated.gr > 3 && gated.rms < loud.rms * 0.05, $"sc parts: a solo-gated kick pad keeps ducking ({gated.gr:F1} dB)");
+ e.RackSetChainSolo(rig.Drums, hat, false);
+
+ // The whole-track setter clears the part.
+ e.SetDeviceSidechainSource(rig.Bass, rig.Comp, rig.Drums);
+ yield return (e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rig.Drums, -1), "sc parts: a whole-track key clears the part");
+ yield return (e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, 5) == -1 && e.SetDeviceSidechainKey(rig.Bass, rig.Comp, 9999, -1) == -1,
+ "sc parts: no such part or track is refused");
+ }
+
+ private static IEnumerable<(bool, string)> StableKey()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, rig.Chain("Kick"));
+ rig.Play(KickNote);
+
+ // Other pads come and go: the key follows the kick.
+ e.RackRemoveChain(rig.Drums, rig.Chain("Hat"));
+ yield return (e.DeviceSidechainKey(rig.Bass, rig.Comp).Part == 0 && rig.Run().gr > 3,
+ "sc parts: deleting the pad before it moves the key with the kick");
+ int dup = e.RackDuplicateChain(rig.Drums, 0);
+ int added = e.RackAddSamplerChain(rig.Drums, Wav(500), 50, false);
+ yield return (dup == 1 && added == 2 && e.DeviceSidechainKey(rig.Bass, rig.Comp).Part == 0,
+ "sc parts: a duplicated and an added pad leave the key on the original kick");
+ e.RackRemoveChain(rig.Drums, 2);
+ e.RackRemoveChain(rig.Drums, 1);
+ e.RackSetChainName(rig.Drums, 0, "Kick 909");
+ yield return (e.TrackPartName(rig.Drums, e.DeviceSidechainKey(rig.Bass, rig.Comp).Part) == "Kick 909",
+ "sc parts: a renamed pad keeps its key, under its new name");
+
+ // The kick goes: the key sleeps (no reduction); undo brings both back.
+ e.RackRemoveChain(rig.Drums, 0);
+ var gone = e.DeviceSidechainKey(rig.Bass, rig.Comp);
+ yield return (gone == new SidechainKey(rig.Drums, SidechainKey.Missing) && e.SidechainRoutesFree() == 16,
+ "sc parts: deleting the keyed pad leaves the key without a part or a route");
+ yield return (e.Undo() && e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rig.Drums, 0) && rig.Run().gr > 3,
+ "sc parts: undo brings the pad back and its key ducks again");
+
+ // The Drum Rack gives way to a synth: no pads, so the key sleeps the same way.
+ yield return (e.SetTrackBuiltinInstrument(rig.Drums, 0) && e.TrackPartCount(rig.Drums) == 0
+ && e.DeviceSidechainKey(rig.Bass, rig.Comp).Part == SidechainKey.Missing,
+ "sc parts: replacing the Drum Rack leaves the key without a part");
+ }
+
+ private static IEnumerable<(bool, string)> InstrumentRackChain()
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int rack = e.AddInstrumentRackTrack();
+ int lo = e.RackAddSamplerChain(rack, Wav(80), 48, false);
+ int hi = e.RackAddSamplerChain(rack, Wav(2000), 72, false);
+ e.RackSetChainZone(rack, lo, 0, 59, 0, 127);
+ e.RackSetChainZone(rack, hi, 60, 127, 0, 127);
+ e.RackSetChainName(rack, lo, "Sub");
+ e.AddMidiClip(rack, 0.0, 4.0);
+ int bass = e.AddAudioTrack();
+ int comp = e.AddBuiltinDevice(bass, CompKind);
+ e.DeviceSetParam(bass, comp, Thresh, -40f);
+ e.DeviceSetParam(bass, comp, Ratio, 10f);
+ e.DeviceSetParam(bass, comp, Attack, 1f);
+ float Gr(int note)
+ {
+ e.SetClipNotes(rack, 0, new[] { new NotaNote(note, 0, 0.5, 1f), new NotaNote(note, 2, 0.5, 1f) });
+ var buf = new float[512 * 2];
+ float g = 0;
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 172; i++) { e.RenderOffline(buf, 512); g = Math.Max(g, e.DeviceGainReduction(bass, comp)); }
+ e.StopTransport();
+ return g;
+ }
+ yield return (e.TrackPartCount(rack) == 2 && e.TrackPartName(rack, lo) == "Sub",
+ "sc parts: an Instrument Rack lists its chains (named, or by instrument)");
+ yield return (e.SetDeviceSidechainKey(bass, comp, rack, lo) == 0, "sc parts: key a Compressor off an Instrument Rack chain");
+ float high = Gr(72), low = Gr(48);
+ yield return (high < 0.1f && low > 3, $"sc parts: only the keyed chain ducks (other {high:F2} dB, keyed {low:F1} dB)");
+ e.RackSetChainMute(rack, lo, true);
+ yield return (Gr(48) > 3, "sc parts: a muted keyed chain still ducks");
+ }
+
+ // Nota Rhythm: voice 1 (Kick, note 36) and voice 5 (Closed Hat, note 42) from a clip, the
+ // default pattern cleared. A Utility on the kick voice turned all the way down mutes Post only.
+ private static IEnumerable<(bool, string)> RhythmVoice()
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int rh = e.AddRhythmTrack();
+ e.InstrumentAction(rh, 4, 0, 0); // A_ClearBank: no default pattern
+ e.AddMidiClip(rh, 0.0, 4.0);
+ int bass = e.AddAudioTrack();
+ int comp = e.AddBuiltinDevice(bass, CompKind);
+ e.DeviceSetParam(bass, comp, Thresh, -40f);
+ e.DeviceSetParam(bass, comp, Ratio, 10f);
+ e.DeviceSetParam(bass, comp, Attack, 1f);
+ float Gr(int note)
+ {
+ var ns = new List<NotaNote>();
+ for (int b = 0; b < 4; b++) ns.Add(new NotaNote(note, b, 0.25, 1f));
+ e.SetClipNotes(rh, 0, ns.ToArray());
+ var buf = new float[512 * 2];
+ float g = 0;
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 172; i++) { e.RenderOffline(buf, 512); g = Math.Max(g, e.DeviceGainReduction(bass, comp)); }
+ e.StopTransport();
+ return g;
+ }
+ yield return (e.TrackPartCount(rh) == 8 && e.TrackPartName(rh, 0) == "1 Kick" && e.TrackPartName(rh, 4) == "5 Closed Hat",
+ "sc parts: Nota Rhythm lists its eight voices");
+ yield return (e.SetDeviceSidechainKey(bass, comp, rh, 0) == 0, "sc parts: key a Compressor off Rhythm's kick voice");
+ float hat = Gr(HatNote), kick = Gr(KickNote);
+ yield return (hat < 0.1f && kick > 3, $"sc parts: only the kick voice ducks (hat {hat:F2} dB, kick {kick:F1} dB)");
+
+ int u = e.RhythmAddVoiceDevice(rh, 0, 4); // Utility on the kick voice
+ int gain = -1;
+ for (int p = 0; p < e.RhythmVoiceDeviceParamCount(rh, 0, u); p++)
+ if (e.RhythmVoiceDeviceParamName(rh, 0, u, p) == "Gain") gain = p;
+ if (gain >= 0) e.RhythmVoiceDeviceParamSet(rh, 0, u, gain, e.RhythmVoiceDeviceParamMin(rh, 0, u, gain));
+ float post = Gr(KickNote);
+ e.SetDeviceSidechainTapPre(bass, comp, true);
+ float pre = Gr(KickNote);
+ yield return (u >= 0 && gain >= 0 && post < pre - 10 && pre > 3,
+ $"sc parts: a voice FX turned down weakens Post ({post:F1} dB), not Pre ({pre:F1} dB)");
+ }
+
+ // Nota Flux's React keyed off the kick pad: its envelope follower moves on kicks only.
+ private static IEnumerable<(bool, string)> FluxReact()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int flux = e.AddFluxSynthTrack();
+ int kick = rig.Chain("Kick");
+ yield return (e.SetInstrumentSidechainKey(flux, rig.Drums, kick) == 0
+ && e.InstrumentSidechainKey(flux) == new SidechainKey(rig.Drums, kick) && e.InstrumentSidechainSource(flux) == rig.Drums,
+ "sc parts: key Flux's React off the kick pad");
+ float Env(int note)
+ {
+ rig.Play(note);
+ var buf = new float[512 * 2];
+ var sc = new float[9];
+ float env = 0;
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 172; i++)
+ {
+ e.RenderOffline(buf, 512);
+ if (e.InstrumentScope(flux, sc) >= 1) env = Math.Max(env, sc[0]);
+ }
+ e.StopTransport();
+ return env;
+ }
+ float hat = Env(HatNote), kickEnv = Env(KickNote);
+ yield return (hat < 1e-4f && kickEnv > 0.001f, $"sc parts: React follows only the kick pad (hat {hat:E1}, kick {kickEnv:F3})");
+ e.SetInstrumentSidechainSource(flux, rig.Drums);
+ yield return (e.InstrumentSidechainKey(flux) == new SidechainKey(rig.Drums, -1), "sc parts: a whole-track React source clears the part");
+ }
+
+ // Every built-in that takes a key can take a pad: the key round-trips and holds a route.
+ private static IEnumerable<(bool, string)> EveryConsumer()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int kick = rig.Chain("Kick");
+ var kinds = new List<int>();
+ int host = e.AddAudioTrack();
+ for (int kind = 0; kind < 40; kind++)
+ {
+ int d = e.AddBuiltinDevice(host, kind);
+ if (d < 0) continue;
+ if (!e.DeviceAcceptsSidechain(host, d) || kind == 10) { e.RemoveDevice(host, d); continue; } // Auto Shift keys on MIDI
+ if (e.SetDeviceSidechainKey(host, d, rig.Drums, kick) == 0 && e.DeviceSidechainKey(host, d) == new SidechainKey(rig.Drums, kick))
+ kinds.Add(kind);
+ else
+ yield return (false, $"sc parts: built-in kind {kind} takes a pad key");
+ }
+ yield return (kinds.Count >= 7 && e.SidechainRoutesFree() == 15,
+ $"sc parts: every keyed built-in takes the kick pad, sharing one route (kinds {string.Join(", ", kinds)})");
+ }
+
+ // MCP: list the pads, key a device off one, read it back by name.
+ private static IEnumerable<(bool, string)> Mcp()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int kick = rig.Chain("Kick");
+ var tools = new Nota.Mcp.Tools.DeviceTools(e, new SyncDispatch(), new NoRefresh());
+ var list = tools.ListSidechainSources().Result;
+ var drums = list.Sources.FirstOrDefault(x => x.TrackId == rig.Drums);
+ yield return (list.RouteCapacity == 16 && drums is { Parts.Length: 2 } && drums.Parts[kick].Name == "Kick",
+ "sc parts: list_sidechain_sources lists the Drum Rack's pads");
+ tools.SetDeviceSidechain(rig.Bass, rig.Comp, rig.Drums, tapPre: true, sourcePart: kick).Wait();
+ var got = tools.GetDeviceSidechain(rig.Bass, rig.Comp).Result;
+ yield return (got.SourceTrackId == rig.Drums && got.SourcePart == kick && got.SourceName == "Drums · Kick" && got.TapPre,
+ $"sc parts: set_device_sidechain keys a pad; get_device_sidechain reads \"{got.SourceName}\"");
+ bool threw = false;
+ try { tools.SetDeviceSidechain(rig.Bass, rig.Comp, rig.Drums, sourcePart: 7).Wait(); }
+ catch (Exception x) when (x is ArgumentException or AggregateException) { threw = true; }
+ yield return (threw && e.DeviceSidechainKey(rig.Bass, rig.Comp).Part == kick, "sc parts: a part that doesn't exist is an error and keeps the key");
+ tools.SetDeviceSidechain(rig.Bass, rig.Comp, rig.Drums).Wait();
+ yield return (e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rig.Drums, -1), "sc parts: set_device_sidechain without a part keys the whole track");
+ }
+
+ // A frozen Drum Rack plays its freeze buffer, not its pads: a pad key goes quiet while the
+ // whole-track key keeps working; unfreezing brings the pad key back.
+ private static IEnumerable<(bool, string)> FrozenSource()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int kick = rig.Chain("Kick");
+ rig.Play(KickNote);
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, kick);
+ float live = rig.Run().gr;
+ e.SetMetronome(false);
+ e.StopTransport();
+ long total = e.BeginFreeze(rig.Drums, 4.0);
+ e.Seek(0); e.Play();
+ var chunk = new float[4096 * 2];
+ for (long rem = total; rem > 0;) { int m = (int)Math.Min(4096, rem); e.RenderOffline(chunk, m); rem -= m; }
+ e.StopTransport();
+ e.EndFreeze(rig.Drums);
+ float frozenPart = rig.Run().gr;
+ e.SetDeviceSidechainSource(rig.Bass, rig.Comp, rig.Drums);
+ float frozenWhole = rig.Run().gr;
+ yield return (total > 0 && e.IsTrackFrozen(rig.Drums) && live > 3 && frozenPart < 0.1f && frozenWhole > 3,
+ $"sc parts: a frozen track's pad key is silent ({frozenPart:F2} dB), its whole-track key still ducks ({frozenWhole:F1} dB)");
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, kick);
+ e.UnfreezeTrack(rig.Drums);
+ float back = rig.Run().gr;
+ yield return (!e.IsTrackFrozen(rig.Drums) && back > 3, $"sc parts: unfrozen, the pad key ducks again ({back:F1} dB)");
+ }
+
+ // A keyed device copied and pasted, or its whole track duplicated, keeps the pad key.
+ private static IEnumerable<(bool, string)> CopiesKeepTheKey()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ var key = new SidechainKey(rig.Drums, rig.Chain("Kick"));
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, key.Source, key.Part);
+ bool copied = e.CopyDevice(rig.Bass, rig.Comp);
+ int pasted = e.PasteDevice(rig.Bass, -1);
+ yield return (copied && pasted > rig.Comp && e.DeviceSidechainKey(rig.Bass, pasted) == key,
+ "sc parts: a copied and pasted Compressor keeps its pad key");
+ int dup = e.DuplicateTrack(rig.Bass);
+ yield return (dup > 0 && e.DeviceSidechainKey(dup, rig.Comp) == key, "sc parts: a duplicated track's Compressor keeps its pad key");
+ yield return (e.SidechainRouteInUse(key.Source, key.Part) && e.SidechainRoutesFree() == 15,
+ "sc parts: all those keys share the pad's one route");
+ }
+
+ // Hits off the block grid split a block's render at each note: every piece must land at its
+ // own place in the key. With one pad, no pad effects and unity levels, the pad's Post equals
+ // the track's pre-FX tap, so Listen must print the same key either way.
+ private static IEnumerable<(bool, string)> SegmentedBlocks()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ const int ScListen = 15;
+ int kick = rig.Chain("Kick");
+ e.RackSetVolume(rig.Drums, 1f);
+ e.SetClipNotes(rig.Drums, 0, new[] { new NotaNote(KickNote, 0.13, 0.25, 1f), new NotaNote(KickNote, 1.37, 0.25, 1f), new NotaNote(KickNote, 2.71, 0.25, 1f) });
+ e.DeviceSetParam(rig.Bass, rig.Comp, ScListen, 1f);
+ float[] Listen()
+ {
+ var all = new List<float>();
+ var buf = new float[512 * 2];
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 172; i++) { e.RenderOffline(buf, 512); all.AddRange(buf); }
+ e.StopTransport();
+ return all.ToArray();
+ }
+ e.SetDeviceSidechainSource(rig.Bass, rig.Comp, rig.Drums);
+ e.SetDeviceSidechainTapPre(rig.Bass, rig.Comp, true);
+ var whole = Listen();
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, kick);
+ e.SetDeviceSidechainTapPre(rig.Bass, rig.Comp, false);
+ var pad = Listen();
+ double diff = 0, energy = 0;
+ for (int i = 0; i < whole.Length; i++) { diff = Math.Max(diff, Math.Abs(whole[i] - pad[i])); energy += whole[i] * whole[i]; }
+ yield return (energy > 1 && diff < 1e-4, $"sc parts: a pad key split at off-grid hits matches the track's own key (max diff {diff:E1})");
+ }
+
+ // A Session clip plays the same pads: a pad key hears them. The keyed track plays an empty
+ // clip in the same scene, so it runs in Session too.
+ private static IEnumerable<(bool, string)> SessionClipKeys()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int bass = e.AddInstrumentTrack();
+ int comp = e.AddBuiltinDevice(bass, CompKind);
+ e.DeviceSetParam(bass, comp, Thresh, -40f);
+ e.DeviceSetParam(bass, comp, Ratio, 10f);
+ e.DeviceSetParam(bass, comp, Attack, 1f);
+ e.SetDeviceSidechainKey(bass, comp, rig.Drums, rig.Chain("Kick"));
+ e.AddSessionMidiClip(bass, 0, 4.0);
+ e.AddSessionMidiClip(rig.Drums, 0, 4.0);
+ var ns = new List<NotaNote>();
+ for (int b = 0; b < 4; b++) ns.Add(new NotaNote(KickNote, b, 0.25, 1f));
+ e.SetSessionNotes(rig.Drums, 0, ns.ToArray());
+ e.SetLaunchQuant(0.0);
+ e.StopTransport();
+ e.Seek(0);
+ var buf = new float[512 * 2];
+ e.RenderOffline(buf, 64);
+ e.LaunchScene(0);
+ e.Seek(0);
+ float gr = 0;
+ for (int i = 0; i < 172; i++) { e.RenderOffline(buf, 512); gr = Math.Max(gr, e.DeviceGainReduction(bass, comp)); }
+ e.StopSlot(rig.Drums);
+ e.StopSlot(bass);
+ e.StopTransport();
+ yield return (gr > 3, $"sc parts: a Session clip on the Drum Rack drives the pad key ({gr:F1} dB)");
+ }
+
+ // With the pool full, keying an earlier device to a new source must not push out a later
+ // device's route; it is refused instead.
+ private static IEnumerable<(bool, string)> NoEviction()
+ {
+ using var e = new NotaEngine();
+ int host = e.AddAudioTrack();
+ int first = e.AddBuiltinDevice(host, CompKind); // earliest in the chain, no key yet
+ var srcs = new List<int>();
+ bool filled = true;
+ for (int i = 0; i < 16; i++)
+ {
+ int d = e.AddBuiltinDevice(host, CompKind);
+ srcs.Add(e.AddAudioTrack());
+ filled &= e.SetDeviceSidechainKey(host, d, srcs[i], -1) == 0;
+ }
+ int extra = e.AddAudioTrack();
+ int r = e.SetDeviceSidechainKey(host, first, extra, -1);
+ bool intact = srcs.TrueForAll(x => e.SidechainRouteInUse(x, -1));
+ yield return (filled && r == -2 && intact && e.DeviceSidechainKey(host, first).Source == -1,
+ "sc parts: a new key on an earlier device can't push out a later device's route");
+ r = e.SetDeviceSidechainKey(host, first, srcs[0], -1);
+ yield return (r == 0 && srcs.TrueForAll(x => e.SidechainRouteInUse(x, -1)), "sc parts: …and it can still share a route in use");
+ }
+
+ // A fresh Nota Rhythm in place of the keyed one is a different instrument: the key goes
+ // missing instead of following the new voice 1.
+ private static IEnumerable<(bool, string)> FreshRhythm()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int rh = e.AddRhythmTrack();
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rh, 0);
+ bool before = e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rh, 0);
+ bool swapped = e.SetTrackBuiltinInstrument(rh, 12);
+ yield return (before && swapped && e.TrackPartCount(rh) == 8 && e.DeviceSidechainKey(rig.Bass, rig.Comp).Part == SidechainKey.Missing,
+ "sc parts: a fresh Rhythm doesn't inherit the old voice key");
+ }
+
+ // Loading a sample into a Rhythm voice is an edit, not a new instrument: keys stay put.
+ private static IEnumerable<(bool, string)> RhythmSampleEditKeepsKeys()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int rh = e.AddRhythmTrack();
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rh, 0);
+ bool loaded = e.SetRhythmVoiceSample(rh, 1, Wav(200));
+ yield return (loaded && e.DeviceSidechainKey(rig.Bass, rig.Comp) == new SidechainKey(rh, 0) && e.SidechainRouteInUse(rh, 0),
+ "sc parts: loading a sample into another Rhythm voice keeps the voice key");
+ }
+
+ // The keyed pad deleted: the compressor hears a silent key, not its own input.
+ private static IEnumerable<(bool, string)> MissingPadIsSilent()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int synth = e.AddInstrumentTrack();
+ e.AddMidiClip(synth, 0.0, 4.0);
+ e.SetClipNotes(synth, 0, new[] { new NotaNote(48, 0.0, 4.0, 1f) });
+ int comp = e.AddBuiltinDevice(synth, CompKind);
+ e.DeviceSetParam(synth, comp, Thresh, -40f);
+ e.DeviceSetParam(synth, comp, Ratio, 10f);
+ // The deepest reduction after half a second — the release of the previous run is over.
+ float Gr()
+ {
+ var buf = new float[512 * 2];
+ float g = 0;
+ e.Seek(0); e.Play();
+ for (int i = 0; i < 172; i++) { e.RenderOffline(buf, 512); if (i >= 43) g = Math.Max(g, e.DeviceGainReduction(synth, comp)); }
+ e.StopTransport();
+ return g;
+ }
+ rig.Play(HatNote); // the kick pad stays quiet throughout
+ float own = Gr();
+ e.SetDeviceSidechainKey(synth, comp, rig.Drums, rig.Chain("Kick"));
+ float keyed = Gr();
+ e.RackRemoveChain(rig.Drums, rig.Chain("Kick"));
+ float missing = Gr();
+ yield return (own > 3 && keyed < 0.1f && missing < 0.1f,
+ $"sc parts: with its pad deleted the key stays silent (own input {own:F1} dB, keyed {keyed:F2}, pad gone {missing:F2})");
+ }
+
+ // Auto Shift follows the source's notes, so it takes whole tracks only.
+ private static IEnumerable<(bool, string)> AutoShiftWholeTrackOnly()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int d = e.AddBuiltinDevice(rig.Bass, 10);
+ yield return (d >= 0 && e.SetDeviceSidechainKey(rig.Bass, d, rig.Drums, rig.Chain("Kick")) == -1
+ && e.SetDeviceSidechainKey(rig.Bass, d, rig.Drums, -1) == 0,
+ "sc parts: Auto Shift refuses a pad and takes the whole track");
+ }
+
+ // A keyed Compressor grouped into a rack keeps its pad (the rack-child part calls), and so
+ // does a reopened project.
+ private static IEnumerable<(bool, string)> RackChildPart()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int kick = rig.Chain("Kick"), hat = rig.Chain("Hat");
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, kick);
+ e.GroupDevices(rig.Bass, 0, 0, false, rig.Comp, 1);
+ int rack = 0;
+ yield return (e.RackChainSidechainPart(rig.Bass, rack, 0, 0) == kick, "sc parts: a keyed device grouped into a rack keeps its pad");
+ yield return (e.RackChainSetSidechainPart(rig.Bass, rack, 0, 0, hat) == 0 && e.RackChainSidechainPart(rig.Bass, rack, 0, 0) == hat
+ && e.RackChainSetSidechainPart(rig.Bass, rack, 0, 0, 9) == -1,
+ "sc parts: a rack child's pad can be set and read; no such pad is refused");
+ // With the pool full, a rack child's new source is refused when its old route is still
+ // needed (another device shares the hat), and pushes nobody out.
+ int host = e.AddAudioTrack();
+ int sharer = e.AddBuiltinDevice(host, CompKind);
+ e.SetDeviceSidechainKey(host, sharer, rig.Drums, hat);
+ var srcs = new List<int>();
+ for (int i = 0; i < 15; i++)
+ {
+ int d = e.AddBuiltinDevice(host, CompKind);
+ srcs.Add(e.AddAudioTrack());
+ e.SetDeviceSidechainKey(host, d, srcs[i], -1);
+ }
+ int extra = e.AddAudioTrack();
+ float gainBefore = e.RackChainSidechain(rig.Bass, rack, 0, 0)?.GainDb ?? float.NaN;
+ int rc = e.RackChainSetSidechain(rig.Bass, rack, 0, 0, new NestedSidechain(extra, true, 12f, 0.5f));
+ yield return (e.SidechainRoutesFree() == 0 && rc == -2 && e.RackChainSidechainPart(rig.Bass, rack, 0, 0) == hat
+ && e.SidechainRouteInUse(rig.Drums, hat) && srcs.TrueForAll(x => e.SidechainRouteInUse(x, -1)),
+ "sc parts: with the pool full a rack child's new source is refused and keeps its pad");
+ yield return (e.RackChainSidechain(rig.Bass, rack, 0, 0) is { } kept && kept.GainDb == gainBefore && !kept.TapPre && kept.Mix == 1f,
+ "sc parts: a refused rack-child edit leaves its tap, gain and mix alone");
+
+ // Saved with the pool full: the rack child's pad shares a route already in use, so it
+ // reopens (the loader asks for source and part together, not the whole track first).
+ string full = Path.Combine(Path.GetTempPath(), "nota-scpart-full-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var warn = new List<string>();
+ ProjectService.Save(ProjectService.Capture(e, new TransportState(120, 1, false, false), warn), full, e);
+ using var e3 = new NotaEngine();
+ var w3 = ProjectService.Apply(ProjectService.Load(full), e3, full);
+ int bass3 = -1; // the track whose first device is the keyed rack
+ for (int i = 0; i < e3.TrackCount && bass3 < 0; i++)
+ if (e3.TryGetTrackInfo(i, out var ti) && e3.RackChainSidechain(ti.Id, 0, 0, 0) is { SourceTrack: >= 0 }) bass3 = ti.Id;
+ yield return (w3.Count == 0 && bass3 > 0 && e3.RackChainSidechainPart(bass3, 0, 0, 0) == hat && e3.SidechainRoutesFree() == 0,
+ $"sc parts: with the pool full a rack child's saved pad still reopens ({string.Join("; ", w3)})");
+ }
+ finally
+ {
+ try { if (Directory.Exists(full)) Directory.Delete(full, recursive: true); } catch (IOException) { }
+ }
+ e.RemoveTrack(host);
+ string dir = Path.Combine(Path.GetTempPath(), "nota-scpart-rack-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ ProjectService.Save(ProjectService.Capture(e, new TransportState(120, 1, false, false), new List<string>()), dir, e);
+ using var e2 = new NotaEngine();
+ ProjectService.Apply(ProjectService.Load(dir), e2, dir);
+ int drums = -1, bass = -1;
+ for (int i = 0; i < e2.TrackCount; i++)
+ if (e2.TryGetTrackInfo(i, out var ti))
+ {
+ if (e2.TrackPartCount(ti.Id) == 2) drums = ti.Id;
+ else if (e2.TrackDeviceCount(ti.Id) == 1) bass = ti.Id;
+ }
+ var sc = bass > 0 ? e2.RackChainSidechain(bass, 0, 0, 0) : null;
+ yield return (drums > 0 && sc is { } k && k.SourceTrack == drums && e2.RackChainSidechainPart(bass, 0, 0, 0) == hat,
+ "sc parts: a reopened rack child is keyed to the same pad");
+ }
+ finally
+ {
+ try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { }
+ }
+ }
+
+ private static IEnumerable<(bool, string)> RoutePool()
+ {
+ using var e = new NotaEngine();
+ int host = e.AddAudioTrack();
+ var comps = new List<int>();
+ var srcs = new List<int>();
+ for (int i = 0; i < 17; i++)
+ {
+ comps.Add(e.AddBuiltinDevice(host, CompKind));
+ srcs.Add(e.AddAudioTrack());
+ }
+ bool first16 = true;
+ for (int i = 0; i < 16; i++) first16 &= e.SetDeviceSidechainKey(host, comps[i], srcs[i], -1) == 0;
+ yield return (first16 && e.SidechainRoutesFree() == 0, "sc parts: 16 distinct sources fill the pool");
+ yield return (e.SetDeviceSidechainKey(host, comps[16], srcs[16], -1) == -2 && e.DeviceSidechainKey(host, comps[16]).Source == -1,
+ "sc parts: a 17th source is refused and leaves the key as it was");
+ yield return (e.SetDeviceSidechainKey(host, comps[16], srcs[0], -1) == 0 && e.SidechainRouteInUse(srcs[0], -1),
+ "sc parts: a further key on a source in use shares its route");
+ yield return (e.SetDeviceSidechainKey(host, comps[1], srcs[16], -1) == 0 && e.DeviceSidechainKey(host, comps[1]).Source == srcs[16],
+ "sc parts: with the pool full, a key can move to a new source when it was the old one's only listener");
+ }
+
+ private static IEnumerable<(bool, string)> SaveReopen()
+ {
+ using var rig = new Rig();
+ var e = rig.E;
+ int kick = rig.Chain("Kick");
+ e.SetDeviceSidechainKey(rig.Bass, rig.Comp, rig.Drums, kick);
+ e.SetDeviceSidechainTapPre(rig.Bass, rig.Comp, true);
+ int comp2 = e.AddBuiltinDevice(rig.Bass, CompKind);
+ e.SetDeviceSidechainSource(rig.Bass, comp2, rig.Drums);
+ string dir = Path.Combine(Path.GetTempPath(), "nota-scpart-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var doc = ProjectService.Capture(e, new TransportState(120, 1, false, false), new List<string>());
+ ProjectService.Save(doc, dir, e);
+ using var e2 = new NotaEngine();
+ var warnings = ProjectService.Apply(ProjectService.Load(dir), e2, dir);
+ int drums = -1, bass = -1;
+ for (int i = 0; i < e2.TrackCount; i++)
+ if (e2.TryGetTrackInfo(i, out var ti))
+ {
+ if (e2.RackChainCount(ti.Id) == 2) drums = ti.Id;
+ else if (e2.TrackDeviceCount(ti.Id) == 2) bass = ti.Id;
+ }
+ yield return (drums > 0 && bass > 0 && warnings.Count == 0, "sc parts: the project reopens");
+ yield return (e2.DeviceSidechainKey(bass, 0) == new SidechainKey(drums, kick) && e2.DeviceSidechainTapPre(bass, 0)
+ && e2.TrackPartName(drums, kick) == "Kick",
+ "sc parts: a reopened key is on the same pad, with its tap");
+ yield return (e2.DeviceSidechainKey(bass, 1) == new SidechainKey(drums, -1), "sc parts: a whole-track key reopens whole");
+ }
+ finally
+ {
+ try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { }
+ }
+
+ // A v27 project has no parts: it migrates on and every key stays on its whole track.
+ var old = ProjectMigrations.Migrate(new JsonObject { ["formatVersion"] = 27 });
+ yield return (old["formatVersion"]?.GetValue<int>() == ProjectService.CurrentFormatVersion
+ && new DeviceDto().SidechainPart == -1 && new InstrumentDto().SidechainPart == -1 && new NestedSidechainDto().Part == -1,
+ "sc parts: a v27 project migrates and its keys stay whole-track");
+ }
+}