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) A private Cue mix on its own output pair (#483) (#566)

Egor Khindikaynenf239a74841c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0a04ce3..ae63eace 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,24 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **A private Cue mix on its own outputs** (#483, specs/089). On an interface with more than
+ two outputs, **Settings → Outputs** sends Main (what the audience hears) to one
+ output pair and Cue (your own mix) to another, for example Main on 1/2 and Cue on 3/4.
+ Changing a pair takes effect at once, without restarting the device.
+ - **Cue key** (headphones) on every track, in the mixer, the Session mixer, the track
+ headers and the inspector. Several tracks can be in Cue at once. Each is heard after its
+ devices and before its fader, pan, mute and solo, so a track muted in Main is still
+ heard in Cue. Cue never changes Main, a recording or an export.
+ - **Cue strip** next to Master: the Cue output pair, the cued tracks, the Cue level and a
+ meter.
+ - **Click to Cue:** the metronome and count-in can go to Main, Cue or both, with their own
+ level. A click sent to Cue skips the master chain and never reaches the audience.
+ - **When the Cue outputs disappear** (another device, or the interface unplugged), Cue goes
+ silent and says so. Nothing is moved into Main. If Main's own pair is missing, Main plays
+ on 1/2 and the Master strip says so.
+ - **What is saved where:** output pairs and click settings are kept per device on this
+ computer. The cued tracks and the Cue level are saved with the project (format 32).
+ - **MIDI Learn** can map a track's Cue key and the Cue level.
- **Skins: your own themes** (#336, specs/087). Put a theme file in the **Themes** folder
of Nota's data folder and it appears in **Preferences → Appearance**, next to the
built-in themes, under Dark or Light. You pick it like any built-in theme, and the choice
diff --git a/FEATURES.md b/FEATURES.md
index ef2b3444..e1e029f4 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -27,6 +27,8 @@ Contents
## Platforms and distribution
+- **Multi-output audio interfaces**: every backend opens all of the device's outputs (up
+ to 64), so Main and Cue can play on any two pairs.
- **macOS** (≥ 13.0, arm64 + x86_64): CoreAudio, CoreMIDI, **AU + VST3**
hosting. Distributed as a separate `.dmg` for Apple Silicon and for Intel (ad-hoc signed).
- **Windows** (x64): WASAPI (shared + **exclusive mode** for minimum latency) or **ASIO**
@@ -102,6 +104,8 @@ on a pool of render threads, export and freeze use every core, and an idle engin
loop seam keep sounding and release tails ring into the next pass; an arpeggiator keeps its
pattern going across the seam.
- **Metronome** and **count-in** before recording, Session slot takes from stop included (notes played on the count-in are recorded).
+ The click goes to Main, to Cue (past the master chain, never to the audience) or to both,
+ at its own level (**Settings → Outputs**).
- **Discard and retry take** (⌘. / Ctrl+., Transport menu, palette, MCP `retry_take`): drops
the take being recorded — audio, loop passes, notes, controllers, automation, with no undo
step — and records again. The Arrangement goes back to where the transport was started
@@ -290,6 +294,15 @@ docks as a panel under any of the three, or floats in its own window — see
screen, with the same controls — one-line I/O, A/B send bars, a pan bar, a wide stereo
meter that is also the fader (drag anywhere on it; a triangle marks the volume on the
meter's scale), the dB value, and full-width M / S / Arm.
+- **Cue — a private mix on its own outputs**: with a Cue pair set in **Settings →
+ Outputs**, every track gets a **Cue** key (headphones) on its mixer strip, Session mixer
+ strip, header and inspector. Any number of tracks, groups and returns can be in Cue. Each is
+ heard after its devices and before its fader, pan, mute and solo, so a track muted in Main
+ still plays in your ears. The **Cue** strip next to Master shows the output pair, what feeds
+ Cue (the cued tracks and the click), the Cue level and a meter. Cue never changes Main, a
+ recording or an export. A Cue pair the device doesn't have goes silent and is flagged on
+ the strip, and nothing moves into Main. Cued tracks and the Cue level are saved with the
+ project. MIDI Learn maps a track's Cue key and the Cue level.
- **Pan law** (per project, in the Mixer footer: **Pan law** Stereo / Balance): under
Stereo, panning a stereo track or return moves its whole image — at full pan both
channels play from one side; under Balance the opposite channel fades out. Mono
@@ -1525,8 +1538,12 @@ audio effects after it keep running and keep their settings; saved with the proj
restart); the Latency line shows the driver's latency and round trip. Recorded takes are
moved earlier by the driver's reported latency; a missing or failed driver falls back to
WASAPI with the reason in the status bar, and **Try again** returns to ASIO.
-- **Outputs**: the output device (under ASIO, the driver's output channel pair, by its channel
- names; other outputs silent) and the test tone.
+- **Outputs**: the output device (under ASIO, the driver) and the test tone, and the output
+ pairs, kept per device: **Main**, the pair the audience mix plays on (default 1/2); **Cue**,
+ a second pair for the private Cue mix, or **No cue output**; **Click** (Main / Cue / Both)
+ and **Click level**. Pairs are listed by the device's channel names, change without
+ restarting the device, and a pair the device lacks is marked. If Main's pair is missing,
+ Main plays on 1/2. Other outputs stay silent.
- **Inputs**: the input device (under ASIO, the driver's input channel pair) and the inputs
setup — switch inputs off and name inputs and stereo pairs per device.
- **MIDI**: which MIDI inputs are enabled (the house checkboxes); **MPE** on/off (on by
diff --git a/specs/089-cue-output/checklists/requirements.md b/specs/089-cue-output/checklists/requirements.md
new file mode 100644
index 00000000..d535b0cd
--- /dev/null
+++ b/specs/089-cue-output/checklists/requirements.md
@@ -0,0 +1,37 @@
+# Specification Quality Checklist: Private Cue Mix on a Separate Hardware Output Pair
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-11-10
+**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
+
+- Cue mode resolved 2026-11-10: copy (PFL).
+- The "Nota Context" section names engine areas on purpose (the Nota template asks for
+ today's state to drive the plan); the requirements themselves stay behaviour-level.
+- Items marked incomplete require spec updates before `/speckit-clarify` or `/speckit-plan`
diff --git a/specs/089-cue-output/contracts/c-abi.md b/specs/089-cue-output/contracts/c-abi.md
new file mode 100644
index 00000000..593cd684
--- /dev/null
+++ b/specs/089-cue-output/contracts/c-abi.md
@@ -0,0 +1,87 @@
+# Contract: C ABI (`nota_engine.h`)
+
+All additions are additive (AR-7); every existing entry point keeps its meaning.
+`nota_audio_set_asio_pair(is_input = 0)` keeps working and now sets the Main pair's first
+channel (FR-005).
+
+## Device outputs
+
+```c
+/* Output channels of the open playback device (0 = none), at most 64, and the UTF-8 name
+ * the device gives one ("" when it gives none; copied into `out`, returns its length).
+ * Message thread; valid after nota_engine_start / nota_audio_apply. */
+NOTA_API int32_t nota_audio_output_channel_count(const NotaEngine* engine);
+NOTA_API int32_t nota_audio_output_channel_name(const NotaEngine* engine, int32_t index, char* out, int32_t cap);
+
+/* Where Main and Cue go: 0-based first channel and width (1 or 2; width 2 needs an even
+ * first). cue_first = -1: no Cue output. Takes effect on the next audio block — no device
+ * restart. NOTA_ERR_INVALID_ARG for a bad width / odd stereo first / overlapping pairs.
+ * The pairs are kept even when the device lacks them (see routing_state). */
+NOTA_API NotaResult nota_audio_set_output_routing(NotaEngine* engine,
+ int32_t main_first, int32_t main_width, int32_t cue_first, int32_t cue_width);
+
+/* Bit flags for the routing against the open device:
+ * 1 = Main's pair is missing, Main plays on outputs 1/2 instead;
+ * 2 = Cue's pair is missing (or would overlap Main): Cue is silent, nothing moves to Main. */
+NOTA_API int32_t nota_audio_output_routing_state(const NotaEngine* engine);
+```
+
+## Cue
+
+```c
+/* A track (audio, instrument, group or return) in Cue: its signal after its devices and
+ * before its fader, pan, mute and solo is added to the Cue bus. Any number of tracks. */
+NOTA_API NotaResult nota_track_set_cue(NotaEngine* engine, int32_t track_id, int32_t on);
+NOTA_API int32_t nota_track_get_cue(const NotaEngine* engine, int32_t track_id);
+
+/* Cue level, linear gain 0 … 2 (+6 dB), default 1. Never touches Main. */
+NOTA_API NotaResult nota_engine_set_cue_volume(NotaEngine* engine, float gain);
+NOTA_API float nota_engine_cue_volume(const NotaEngine* engine);
+
+/* Cue meter, after the Cue level (peak / RMS per side). */
+NOTA_API NotaResult nota_engine_cue_meter(const NotaEngine* engine, NotaMeter* out);
+```
+
+## Click
+
+```c
+/* Where the metronome and count-in clicks go: 0 Main (default, as before), 1 Cue,
+ * 2 Main + Cue. A click to Cue bypasses master devices and the master fader. */
+NOTA_API NotaResult nota_transport_set_click_destination(NotaEngine* engine, int32_t dest);
+NOTA_API int32_t nota_transport_click_destination(const NotaEngine* engine);
+
+/* Click level, linear gain 0 … 2, default 1 (today's loudness), on every destination. */
+NOTA_API NotaResult nota_transport_set_click_volume(NotaEngine* engine, float gain);
+```
+
+Settings per output device key on:
+
+```c
+/* The uid of the output device the staged config opens: the chosen one when connected, else
+ * the system default ("" when there is none). */
+NOTA_API int32_t nota_audio_effective_output_uid(const NotaEngine* engine, char* out, int32_t cap);
+```
+
+## Tests
+
+```c
+/* Pretend the output device has `channels` outputs ("Test N"); 0 clears it. */
+NOTA_API void nota_engine_set_test_output_device(NotaEngine* engine, int32_t channels);
+```
+
+```c
+/* Render one device block into two stereo buffers (Main, Cue) without a device. `cue` may
+ * be null (behaves as nota_engine_render_device_block). */
+NOTA_API NotaResult nota_engine_render_device_block_cue(NotaEngine* engine, float* main_out,
+ float* cue_out, int32_t frames);
+
+/* Run the backends' output placement on given buffers: writes `frames` × `device_channels`
+ * interleaved into `device_out` using the current routing; returns routing_state flags. */
+NOTA_API int32_t nota_audio_scatter_test(const NotaEngine* engine, const float* main_in,
+ const float* cue_in, float* device_out, int32_t device_channels, int32_t frames);
+```
+
+Managed mirrors (`NativeMethods.*`, `NotaEngine.*`, `IAudioEngine`): `OutputChannelCount`,
+`OutputChannelName`, `SetOutputRouting`, `OutputRoutingState`, `SetTrackCue`/`GetTrackCue`,
+`SetCueVolume`/`CueVolume`, `CueMeter`, `SetClickDestination`, `SetClickVolume`,
+`RenderDeviceBlockCue`, `ScatterTest`.
diff --git a/specs/089-cue-output/contracts/ui.md b/specs/089-cue-output/contracts/ui.md
new file mode 100644
index 00000000..e3c2cc4b
--- /dev/null
+++ b/specs/089-cue-output/contracts/ui.md
@@ -0,0 +1,50 @@
+# Contract: UI, settings and MIDI Learn
+
+Follows [`DESIGN.md`](../../../DESIGN.md) and the `nota-design` skill: sentence-case labels,
+solid orange for live state (a lit Cue button), the grey shell.
+
+## Settings → Outputs (new section, above Inputs)
+
+- Rows: **Main** — pair picker; **Cue** — pair picker with "No cue output" first;
+ **Click** — Main / Cue / Both (only Main while Cue is "No cue output");
+ **Click level** — off, −18, −12, −9, −6, −3, 0, +3, +6 dB.
+- Pair pickers list the device's outputs as "Out 1/2 · <name>" (pairs odd-aligned, a lone
+ last channel as "Out N"). The Main pair is disabled in the Cue picker and vice versa
+ (FR-004).
+- Under ASIO the old **Output pair** row is replaced by **Main** (FR-005).
+- Saved to `Settings.OutputSetups[key]` and pushed to the engine on every edit.
+- A device with 2 outputs shows Main 1/2 (fixed), Cue "No cue output — this device has
+ 2 outputs".
+
+## Mixer
+
+- **Cue strip** next to Master (full and compact mixer): title "Cue", output label
+ ("Out 3/4 · Phones"), level fader + meter, a line with the cued tracks' names (or
+ "3 tracks"), and the click destination as a small picker. Hidden when no Cue output is
+ assigned on this device and no track is cued; with cued tracks but no Cue output it shows
+ "No cue output".
+- Unavailable state (routing_state flag 2): the strip shows "Out 3/4 — not on this device"
+ in the warning style; the fader stays usable; the tooltip says how to fix it (Settings → Outputs).
+- Master strip shows its pair label when Main is not on 1/2, and "Out 1/2 (fallback)" with
+ a warning when flag 1 is set.
+- Track strips: a **Cue** toggle (headphones glyph + "Cue" tooltip) in the button row next to
+ Mute/Solo — full mixer, compact mixer, Session mixer, track inspector.
+
+## Arrangement track headers
+
+- The same Cue toggle on audio, instrument and group headers (returns: in the mixer), shown only while a
+ Cue output is assigned on this device (keeps headers clean on stereo laptops).
+
+## MIDI Learn
+
+- In learn mode the Cue toggles and the Cue fader light up like Mute and Master volume.
+- **Map** tab labels: "<Track> · Cue", "Cue level".
+
+## Strings
+
+New keys in `Nota.Application/Localization/en.json`: `preferences.outputs*` and `mixer.cue*`.
+Other languages come through the usual translation sync.
+
+## Out of scope (spec Assumptions)
+
+Nota Remote buttons for Cue; MCP tools for Cue; per-track Cue levels; Main/Cue on two devices.
diff --git a/specs/089-cue-output/data-model.md b/specs/089-cue-output/data-model.md
new file mode 100644
index 00000000..fc014cf7
--- /dev/null
+++ b/specs/089-cue-output/data-model.md
@@ -0,0 +1,80 @@
+# Data Model: Private Cue Mix on a Separate Hardware Output Pair
+
+**Feature**: [spec.md](spec.md) | Decisions: [research.md](research.md)
+
+## Engine (C++)
+
+### OutputRouting — `audio_io/OutputRouting.h` (new)
+
+| Field | Type | Rule |
+|-------|------|------|
+| `mainFirst` | int16 | 0-based device channel; even for width 2; default 0 |
+| `mainWidth` | int8 | 1 or 2; default 2 |
+| `cueFirst` | int16 | 0-based device channel, or −1 = no Cue output (default) |
+| `cueWidth` | int8 | 1 or 2; default 2 |
+
+Packed into one `std::atomic<uint64_t>` on the backend; read once per callback.
+
+**Resolution** against `deviceChannels` (pure function `resolveRouting`, same on all threads):
+
+1. Main pair not fully on the device → Main = (0, min(2, deviceChannels)), flag `MainFellBack`.
+2. A width-2 pick whose second channel is missing → width 1.
+3. Cue pair not on the device, or overlapping resolved Main → Cue off, flag `CueUnavailable`.
+
+`kMaxOutputChannels = 64`.
+
+### Track (existing) — new flag
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `cue_` | `std::atomic<bool>` | relaxed; copied by `cloneTrack` and track duplication; valid on audio, instrument, group and return tracks |
+
+### Engine (existing) — new state
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `cueSeg_` | `float*` | this segment of the caller's Cue buffer; null offline / in export |
+| `cueGain_` | `std::atomic<float>` | linear, 0 … 2.0 (+6 dB), default 1 |
+| `clickDest_` | `std::atomic<int32_t>` | 0 Main, 1 Cue, 2 Main + Cue |
+| `clickGain_` | `std::atomic<float>` | linear, 0 … 2.0, default 1 (× `kMetroGain`) |
+| `cuePeakL/R_`, `cueRmsL/R_` | `std::atomic<float>` | Cue meter, post Cue level |
+
+## Managed (C#)
+
+### OutputSetup — `Nota.Application/OutputSetups.cs` (new), machine-level
+
+Stored in `Settings.OutputSetups : Dictionary<string, OutputSetup>`, keyed by
+`InputSetups.KeyOf(system, outputUid, asioDriver)`.
+
+| Field | Type | Default |
+|-------|------|---------|
+| `MainFirst` | int (1-based in JSON, like spec 086 inputs) | 1 |
+| `MainWidth` | int | 2 |
+| `CueFirst` | int? (null = no Cue output) | null |
+| `CueWidth` | int | 2 |
+| `Click` | enum ClickDestination {Main, Cue, MainAndCue} | Main |
+| `ClickDb` | double (−∞ … +6) | 0 |
+
+Validation: Main and Cue never overlap on save (FR-004); an ASIO setup with no entry
+seeds `MainFirst` from `AudioConfig.asioOutputPair` (FR-005).
+
+### Project file — format v32
+
+| Where | Field | Type | Missing / older |
+|-------|-------|------|-----------------|
+| `TrackDto` | `Cue` | bool? | false |
+| `MixerDto` | `CueVolume` | float? (linear) | 1.0 |
+
+### MIDI Learn
+
+| `MidiTargetKind` | Kind | Scope | Applies |
+|------------------|------|-------|---------|
+| `TrackCue` | toggle (button) | track (by index, like `TrackMute`) | `SetTrackCue(!cue)` |
+| `CueVolume` | continuous | global | `SetCueVolume` (no undo step) |
+
+## State transitions
+
+- **Track Cue**: off ⇄ on (UI button, MIDI, project load). Deleting a track or turning it
+ into a group drops the flag; freezing keeps it (the frozen buffer is tapped).
+- **Cue output availability** (derived): Available ⇄ Unavailable on device change / routing
+ edit. Unavailable never changes `clickDest_` or any track's flag.
diff --git a/specs/089-cue-output/plan.md b/specs/089-cue-output/plan.md
new file mode 100644
index 00000000..dddac46f
--- /dev/null
+++ b/specs/089-cue-output/plan.md
@@ -0,0 +1,153 @@
+# Implementation Plan: Private Cue Mix on a Separate Hardware Output Pair
+
+**Branch**: `feat/483-cue-output` (from `develop`) | **Date**: 2026-11-10 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `specs/089-cue-output/spec.md`
+(issue [#483](https://github.com/nota-daw/nota/issues/483)).
+
+## Summary
+
+Open every output channel of the device and let the user put Main and a private Cue on
+any two output pairs. The engine renders two stereo buses per block — Main as today, and
+Cue: the sum of every cued track's signal after its devices and before its fader, pan,
+mute and solo, at its own Cue level. The metronome and count-in click can go to Main, Cue
+or both, with a click level. Output placement and the "Cue output gone" safety live in one
+backend-side routing helper; routing is hot (no device restart). Settings for outputs and
+the click are per machine and device; cued tracks and the Cue level are saved in the
+project (v32). Cue toggles and the Cue level are MIDI-learnable. Details:
+[research.md](research.md).
+
+## Nota: Read Before Planning
+
+- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-4, AR-5, AR-6, AR-7, AR-9.
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill.
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine, audio backends), C# / .NET 10 (managed app), Avalonia UI.
+
+**Primary Dependencies**: CoreAudio (macOS), miniaudio (Windows/Linux, vendored), ASIO
+interface (Windows, existing). **No new dependency.**
+
+**Storage**: project bundle v32 (`TrackDto.Cue`, `MixerDto.CueVolume`); `midimap.json`
+(two new target kinds); `settings.json` (`OutputSetups` per device); `audio.json`
+unchanged (`asioOutputPair` kept for migration).
+
+**Audio-Thread Impact**: Yes.
+- Backend callback: reads one packed routing atomic, scatters two preallocated stereo
+ buffers onto the device channels, zeros the rest (no alloc/lock).
+- Engine: one preallocated `cueBus_`; a per-track `cue_` atomic checked in the serial
+ accumulate step; muted/solo-gated cued tracks are rendered for Cue only; Cue level,
+ NaN squash, clamp and meter after the master section; click writes to Main and/or Cue.
+ All state is relaxed atomics (same pattern as mute/solo) — no commands, no snapshots.
+- Cost when no track is cued and no click goes to Cue: one branch per leaf and a cleared
+ stereo buffer per block.
+
+**Testing**: `tests/Nota.SmokeTest` (`CueOutputTests`, new test entry points
+`nota_engine_render_device_block_cue`, `nota_audio_scatter_test`); manual hardware pass per
+[quickstart.md](quickstart.md).
+
+**Target Platform**: macOS (CoreAudio), Windows (WASAPI via miniaudio, ASIO), Linux (miniaudio).
+
+**Project Type**: desktop app (native engine + managed UI).
+
+**Performance Goals**: SC-007 — ≤ 2 % render cost on a 64-track project, no new xruns at
+64 frames; Main and Cue on the same sample (SC-003).
+
+**Constraints**: RT safety (constitution I); C ABI only (II); output channels ≤ 64.
+
+**Scale/Scope**: 2 destinations (Main, Cue); any number of cued tracks; ≤ 64 device outputs.
+
+## Constitution Check
+
+*GATE: checked before Phase 0 and again after Phase 1.*
+
+| Principle | Status | How |
+|-----------|--------|-----|
+| 0 Approved issue | ✅ | #483 carries `approved` (checked 2026-11-10) |
+| I Real-time safety | ✅ | Preallocated `cueBus_` and backend scratch; atomics only; routing resolved with integer math in the callback; device-alive listener only raises a flag |
+| II Boundary discipline | ✅ | Additive C ABI ([contracts/c-abi.md](contracts/c-abi.md)); `pluginhost/` untouched |
+| III Licensing | ✅ | No new dependency; new files (`OutputRouting.h`, `OutputSetups.cs`, `PreferencesWindow.Outputs.cs`, `MixerView.Cue.cs`, `CueOutputTests.cs`) get the SPDX header |
+| IV Verification gate | ✅ | 16 smoke cases ([quickstart.md](quickstart.md)); `scripts/build.sh` per slice |
+| V One logical change per PR | ⚠️ → ✅ | Delivered as 3 PRs (below), each green on its own |
+| VI Docs in sync | ✅ | CHANGELOG per PR; `nota-features`; `nota-docs` (Preferences → Audio, Mixer); `nota-shortcuts` not needed (no new key) |
+| VII Spec-first | ✅ | This spec/plan; tasks next |
+| VIII No weakened rules | ✅ | Nothing relaxed |
+
+Post-design re-check: no violations; Complexity Tracking empty.
+
+## Delivery slices (one PR each)
+
+| # | PR | Content | Depends on | Closes |
+|---|----|---------|-----------|--------|
+| 1 | Multi-channel output + Main pair | R1–R3: `RenderCallback(main, cue, n)`, `OutputRouting.h` scatter + resolve, all three backends open every output, output channel count/names, hot routing, macOS device-alive event, ABI, `OutputSetups` + Settings → Outputs (Main only, Cue picker hidden), ASIO pair migration. Behaviour unchanged on stereo devices | — | — |
+| 2 | Cue bus + click routing | R4–R5: `Track::cue_`, `cueBus_`, taps (leaf/group/return, muted/solo exemption), Cue level/meter, click destination + level, ABI, smoke cases; Cue picker + click rows in Outputs | 1 | — |
+| 3 | Cue in the mixer, project and MIDI Learn | Cue strip, track Cue toggles on every surface, unavailable/fallback states, project v32, MIDI Learn kinds, EN + RU strings, docs | 2 | #483 |
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/089-cue-output/
+├── spec.md
+├── plan.md # this file
+├── research.md # findings + decisions R1–R7
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── c-abi.md
+│ └── ui.md
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (touched)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # contracts/c-abi.md
+├── src/abi/nota_engine_audio.cpp # output routing, channel names, scatter test
+├── src/abi/nota_engine_track.cpp # set/get cue
+├── src/abi/nota_engine_core.cpp # cue volume/meter, click dest/volume, render_device_block_cue
+├── src/audio_io/
+│ ├── AudioBackend.h # RenderCallback(main, cue, n); setOutputRouting; outputChannelCount/Name
+│ ├── OutputRouting.h # NEW: routing, resolve, scatter
+│ ├── macos/CoreAudioBackend.mm # N-channel client format, names, device-alive listener
+│ ├── desktop/MiniaudioBackend.cpp # native channel count
+│ └── asio/AsioSession.*, windows/AsioBackend.* # cue pair, main from routing
+└── src/engine/
+ ├── Track.h # cue_ flag
+ ├── Engine.h, Engine.cpp # cueBus_, gains, meters, start(), cloneTrack
+ ├── Engine_Tracks.cpp # setTrackCue, duplicate copies the flag
+ └── Engine_Render.cpp # render/processBlock(main, cue), taps, click routing, cue post
+src/managed/
+├── Nota.Application/OutputSetups.cs, Settings.cs # NEW per-device output setup
+├── Nota.Application/Engine/IAudioEngine.cs
+├── Nota.Infrastructure/Interop/NativeMethods*.cs, NotaEngine*.cs
+├── Nota.Infrastructure/Persistence/ProjectModel.cs, ProjectService.cs # v32
+├── Nota.App/PreferencesWindow.cs, PreferencesWindow.Outputs.cs (NEW), OutputSetupAccess.cs (NEW)
+├── Nota.App/MixerView.cs, MixerView.Compact.cs, MixerView.Cue.cs (NEW), SessionView.Mixer.cs,
+│ TrackInspectorView.cs, ArrangementView.cs # Cue strip + toggles
+├── Nota.App/MidiLearn.cs, MidiLearnService.cs, MidiMapView.cs # TrackCue, CueVolume
+└── Nota.Application/Localization/en.json, ru.json
+tests/Nota.SmokeTest/CueOutputTests.cs (NEW), fixtures
+CHANGELOG.md, FEATURES.md
+```
+
+**Structure Decision**: existing layout; no new projects.
+
+## Risks
+
+- **WASAPI shared mode** may expose only the mix format's channels (often 2) for a
+ multi-output interface: Cue then shows unavailable with a hint to use ASIO / exclusive.
+- **CoreAudio aggregate / large devices** (64 ch): scatter cost is linear in channels —
+ measured in SC-007.
+- **Bluetooth / AirPods** route: 2 channels — today's behaviour, Cue unavailable.
+- **Hiding Cue toggles on a stereo device** may hide a project's saved Cue state; the Cue
+ strip says "Cue output not on this device" whenever any track is cued.
+
+## Complexity Tracking
+
+None.
diff --git a/specs/089-cue-output/quickstart.md b/specs/089-cue-output/quickstart.md
new file mode 100644
index 00000000..2db573c9
--- /dev/null
+++ b/specs/089-cue-output/quickstart.md
@@ -0,0 +1,45 @@
+# Quickstart: validating the Cue output
+
+Contracts: [c-abi.md](contracts/c-abi.md), [ui.md](contracts/ui.md). Model: [data-model.md](data-model.md).
+
+## Automated (smoke test, `scripts/build.sh`)
+
+New cases in `tests/Nota.SmokeTest/CueOutputTests.cs`, all through
+`nota_engine_render_device_block_cue` with a deterministic WAV clip (see memory:
+synth notes drift between renders — use a clip, not a synth):
+
+| Case | Setup | Expect |
+|------|-------|--------|
+| Tap is pre-fader | clip track, Cue on, fader −∞ | Cue ≈ clip level; Main silent |
+| Tap is pre-mute / solo | Cue on, track muted; another track soloed | Cue still carries the track; Main has none of it |
+| Tap is post-devices | Utility/gain device +6 dB on the track | Cue +6 dB vs dry |
+| Sends/master excluded | send to a return, master gain device | Cue unaffected |
+| Several cued | two clip tracks cued | Cue = sum |
+| Group cued | group with a gain device, group muted | Cue = group bus after device |
+| Cue level null test (SC-001) | sweep Cue level 0 → 2 | Main bit-identical to Cue off |
+| Click → Cue (SC-002) | metronome on, count-in 1 bar, dest Cue | Main identical to metronome off; Cue has clicks |
+| Click → Main unchanged | dest Main | Main identical to the pre-feature render |
+| Alignment (SC-003) | dest Main + Cue, impulse clip cued | impulse on the same sample in Main and Cue |
+| Scatter | `nota_audio_scatter_test` 4 ch, Main 0/2 Cue 2/2 | ch 0/1 = Main, 2/3 = Cue |
+| Scatter fallback (SC-004) | same routing, 2 device channels | ch 0/1 = Main only; state = 2 |
+| Main fallback | Main 2/2, 2 device channels | Main on 0/1; state = 1 |
+| Overlap after fallback | Main 2/2, Cue 0/2, 2 channels | Main on 0/1, Cue silent; state = 3 |
+| Project round-trip (SC-006) | save with 2 cued tracks, Cue level 0.5 | reload restores both |
+| v31 project | open a fixture saved before | no Cue, renders identically |
+
+## Manual (hardware)
+
+Prerequisite: an interface with ≥ 4 outputs (or macOS BlackHole 16ch / an aggregate
+device; Windows ASIO4ALL or the interface's ASIO driver).
+
+1. Settings → Outputs: Main 1/2, Cue 3/4, Click → Cue. Close.
+2. Load a project with a drum loop and a vocal clip. Cue the vocal track, mute it.
+ Play: speakers (1/2) — drums, no vocal, no click; headphones (3/4) — vocal + click.
+3. Move the Cue fader end to end: speakers don't change.
+4. Arm a track with input monitoring, cue it, record: the take has no click and no Cue
+ level change in it.
+5. MIDI Learn: map a pad to the vocal's Cue and a knob to Cue level; both work.
+6. Unplug the interface (macOS falls back to built-in output): the Cue strip shows
+ unavailable, the speakers never play the vocal or the click. Plug back in → Cue returns.
+7. Save, quit, reopen: cued tracks and Cue level back; Outputs page unchanged.
+8. Windows: repeat 1–3 on WASAPI and on ASIO; Linux: 1–3 on a multi-channel ALSA/Pulse device.
diff --git a/specs/089-cue-output/research.md b/specs/089-cue-output/research.md
new file mode 100644
index 00000000..3a5b91bf
--- /dev/null
+++ b/specs/089-cue-output/research.md
@@ -0,0 +1,139 @@
+# Research: Private Cue Mix on a Separate Hardware Output Pair
+
+**Feature**: [spec.md](spec.md) | **Date**: 2026-11-10 | **Base**: `develop` (7a4f0af6)
+
+What the code does today and the decisions this plan takes. Paths are relative to
+`src/native/nota.engine/src/` unless they start with `src/` or `tests/`.
+
+## Today's state (findings)
+
+| Area | Today | Where |
+|------|-------|-------|
+| Render contract | `RenderCallback(float* out, int32_t n)` — interleaved **stereo** | `audio_io/AudioBackend.h:19-22` |
+| CoreAudio output | AUHAL client format `mChannelsPerFrame = 2`, no channel map → device outs 1/2 | `audio_io/macos/CoreAudioBackend.mm:158-176` |
+| CoreAudio events | Only an overload listener; no device-alive listener | `CoreAudioBackend.mm:137` |
+| miniaudio output | `playback.channels = 2` (miniaudio maps to the device) | `audio_io/desktop/MiniaudioBackend.cpp:54` |
+| ASIO output | Buffers for **every** output already; `outL_/outR_` from `asioOutputPair`, others held at zero | `audio_io/asio/AsioSession.cpp:135-170, 312-360` |
+| Engine entry | `Engine::render(out, n)` → `processBlock(out, n)`; segments of ≤ `kMaxBlock` (16384) | `engine/Engine_Render.cpp:940, 2203, 2283` |
+| Mix order | mixGraph → metronome/count-in (per segment) → tone → preview → master devices → master volume, NaN squash, clamp, meters | `Engine_Render.cpp:2300-2395` |
+| Leaf tap | Post-device, pre-fader buffer is `post` (freeze capture already reads it); fader/pan into `mixTmp_` | `Engine_Render.cpp:2957-3012` |
+| Group / return tap | `scratch_` after devices + PDC, before fader | `Engine_Render.cpp:3139, 3204` |
+| Muted / solo-gated leaf | **Not rendered at all** (`continue`) unless capturing, monitoring or keying a sidechain | `Engine_Render.cpp:2718, 2752-2771` |
+| Muted group | Skipped | `Engine_Render.cpp:3118` |
+| Parallel leaves | Leaves render in parallel into `leafBuf`; accumulation into buses is serial | `Engine_Render.cpp:2949-2968` |
+| Track flags | Relaxed atomics on `Track` shared by authoring and published graphs; `cloneTrack` copies flags | `engine/Track.h:214-221, 441`, `engine/Engine.cpp:685-695` |
+| Click | `renderClick` adds a 1.5/1 kHz sine × `kMetroGain = 0.5` into `out` | `Engine_Render.cpp:30, 3275-3330` |
+| Master meter | `masterPeak/Rms` atomics → `nota_engine_master_meter(NotaMeter*)` | `Engine.h:1917`, `nota_engine.h:2555` |
+| Test render | `nota_engine_render_device_block(out, frames)` | `nota_engine.h:2573` |
+| MIDI Learn | `MidiTargetKind` (TrackMute, TrackSolo, MasterVolume, …); `midimap.json` sidecar; tracks by index | `src/managed/Nota.App/MidiLearn.cs:75-110`, `MidiLearnService.cs` |
+| Per-device settings | `Settings.InputSetups[KeyOf(system, uid, asioDriver)]` | `src/managed/Nota.Application/InputSetups.cs:36`, `Settings.cs:206` |
+| Undo of mute/solo | Not undoable (no `MixKind`); volume/pan are via `MixGesture` | `engine/EngineTypes.h:108-121` |
+| Project format | v31; `TrackDto.Mute/Solo/Monitor`; `MixerDto{PanLaw}` | `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs:81, 119-156` |
+
+## Decisions
+
+### R1 — Engine renders two stereo buses; the backend places them on device channels
+
+- **Decision**: `RenderCallback(float* main, float* cue, int32_t n)`. Both are interleaved
+ stereo scratch buffers the backend preallocates (max block × 2). The engine always fills
+ `main`; it fills `cue` with the Cue bus (or zeros). The backend then writes `main` to the
+ Main pair, `cue` to the Cue pair, and zero to every other open output.
+- The scatter is one shared, header-only helper, `audio_io/OutputRouting.h`:
+ `scatterOutputs(const float* main, const float* cue, float* deviceInterleaved, int32_t
+ deviceChannels, int32_t n, const OutputRouting&)`, used by CoreAudio and miniaudio
+ (interleaved device buffers); ASIO reuses its per-channel `fromFloat` with the same
+ routing. A width-1 pick (odd last channel) gets the L+R sum × 0.5, as ASIO does today.
+- **Rationale**: the engine stays device-agnostic and offline export is unchanged (it simply
+ passes `cue = nullptr`). One routing rule for three backends.
+- **Alternatives**: engine renders straight into the N-channel device buffer — rejected,
+ leaks device layout into `processBlock` and every segment offset; a second backend stream
+ for Cue — rejected, two clocks and a drift problem against FR-010.
+
+### R2 — Backends open every output channel of the device (≤ 64)
+
+- **CoreAudio**: read the output channel count from `kAudioDevicePropertyStreamConfiguration`
+ (output scope) and set the AUHAL client format to that many channels (capped at
+ `kMaxOutputChannels = 64`); names from `kAudioObjectPropertyElementName` per element on
+ the output scope, else "Out N". A stereo device stays at 2 — today's behaviour.
+- **miniaudio**: `playback.channels = 0` (native), read back `device.playback.channels`;
+ names "Out N". WASAPI shared mode may report only the mix format's channel count —
+ shown as is (risk noted in plan).
+- **ASIO**: already creates buffers for all outputs; add `cueL/cueR` next to `outL/outR`,
+ names from `ASIOChannelInfo.name`. `asioOutputPair` becomes the Main pair's saved value
+ (FR-005), migrated into the per-device output setup on first run.
+- **Device loss on macOS**: add a `kAudioDevicePropertyDeviceIsAlive` listener that raises
+ the existing "reset requested" device event (1), so the app's poll re-applies and the
+ routing is re-evaluated against the new channel count (User Story 4).
+
+### R3 — Routing is hot, not a device restart
+
+- **Decision**: `OutputRouting{mainFirst, mainWidth, cueFirst, cueWidth}` is published to the
+ backend as four relaxed atomics packed in one `std::atomic<uint64_t>` and read once per
+ callback. Changing Main or Cue never restarts the device (no glitch on stage).
+- **Resolution against the device** (in the backend, per callback, pure integer math):
+ Main pair missing → Main = 1/2 (FR-015). Cue pair missing, or overlapping the resolved
+ Main → Cue not written (silent) (FR-014). Width 2 on the last odd channel → width 1.
+- **State back to the app**: `nota_audio_output_routing_state()` returns flags
+ (main fell back / cue unavailable), computed on the control thread from the same rules.
+
+### R4 — The Cue bus in the engine
+
+- **Buffer**: no member buffer — `processBlock(main, cue, n)` sums straight into the caller's
+ stereo Cue buffer (the backend's preallocated scratch). Per segment `cueSeg_ = cue + done*2`;
+ `cue` is null offline, in export and in plain device-block tests — then nothing below runs.
+- **Leaf tap**: in the **serial** accumulate step (`Engine_Render.cpp` ~2977-3012) after
+ `processLeafDevices`, if `t.cue()` add `post` into `cueSeg_`. Doing it in the
+ serial part avoids a race with the parallel leaf workers.
+- **Muted / solo-gated leaves**: the skip at 2752-2771 gains one more exemption —
+ `t.cue()` — and such a track then contributes **only** to Cue (`w.toMix = false` keeps it
+ out of Main, sends and groups). Same for a muted group (3118): rendered for its Cue tap
+ only. This is what makes "mute in Main, hear in Cue" work (Clarification 1).
+- **Group / return tap**: add `scratch_` into `cueSeg_` at 3139 / 3204 when the bus is cued.
+- **Frozen tracks**: `post` is the frozen buffer — the tap is the same.
+- **Cue level, safety, meter**: after the master section (`finishCue`), `cue × cueGain` → NaN squash →
+ clamp ±1 → `cue` out; peak/RMS into `cuePeak/Rms` atomics. Cue never passes through
+ master devices, master volume, `renderTone` or `renderPreview`.
+- **Latency (FR-010)**: Main and Cue come from the same block, so they leave on the same
+ sample; per-track PDC still applies before the tap. A master device with latency delays
+ Main only — documented, not compensated (adding delay to Cue would make the performer
+ hear their own monitored input later; the performer prefers the lower latency).
+- **RT safety**: one `bool cue_` atomic per Track (copied by `cloneTrack` and `deepCloneTrack`);
+ `cueGain_`, `clickDest_`, `clickGain_` atomics on Engine; no allocation, no locks, no commands
+ needed (same pattern as mute).
+- **Groups**: a cued group's own mute doesn't silence its children (`grpFeedMute`); they feed
+ its Cue tap while the group stays out of its parent, and their sends, sidechain and record
+ taps stay off. Children still follow solo, so a group's Cue is what reaches its bus.
+
+### R5 — Click routing
+
+- `renderMetronome` / `renderCountIn` / `renderClick` take `(float* main, float* cue, …)`
+ and a gain: `kMetroGain × clickGain_`. Destination Main writes `main` as today
+ (pre-master: master devices and volume still apply — unchanged behaviour); Cue writes
+ `cueSeg_` (then Cue level applies); Main + Cue writes both.
+- When the Cue output is unavailable (R3) the click aimed at Cue is still rendered into the
+ Cue bus and simply not written to any output — never redirected to Main (FR-014).
+- Export already turns the metronome off; Cue never reaches export (no `cue` buffer there).
+
+### R6 — Settings and persistence
+
+- **Machine, per device** (FR-018): `Settings.OutputSetups[key]` where `key` reuses
+ `InputSetups.KeyOf` with the **output** device uid (`device:{uid}` / `asio:{driver}`).
+ `OutputSetup{MainFirst=0, MainWidth=2, CueFirst=-1, CueWidth=2, Click=Main, ClickDb=0}`.
+ Pushed to the engine on start, device change and every edit.
+- **Project** (FR-019): format **v32** — `TrackDto.Cue bool?` (null = false) and
+ `MixerDto.CueVolume float?` (null = 1.0). Older builds ignore the fields (extension data
+ is preserved; they just play without Cue).
+- **MIDI Learn** (FR-021): new `MidiTargetKind.TrackCue` (toggle, track-scoped like
+ TrackMute) and `CueVolume` (continuous, like MasterVolume). Saved in `midimap.json`.
+- **Undo**: Cue toggles follow mute/solo — not undoable. The Cue level is a listening
+ level, not part of the mix, so it is not an undo step either (same reasoning as the
+ rejected `MixKind::TrackSend`, `engine/EngineTypes.h:116`); it is still saved.
+
+### R7 — Testing
+
+- New test entry `nota_engine_render_device_block_cue(engine, main, cue, frames)` renders
+ both buses without a device; `nota_audio_scatter_test(...)` drives `scatterOutputs` with a
+ given routing and channel count (pure function, also covers missing-pair fallback).
+- Smoke cases: cue tap pre-fader/pre-mute; Main null-test unchanged by Cue level (SC-001);
+ click → Cue absent from Main (SC-002); same-sample alignment (SC-003); scatter fallback
+ (SC-004); project round-trip v32 + v31 load (SC-006).
diff --git a/specs/089-cue-output/spec.md b/specs/089-cue-output/spec.md
new file mode 100644
index 00000000..1117169b
--- /dev/null
+++ b/specs/089-cue-output/spec.md
@@ -0,0 +1,404 @@
+# Feature Specification: Private Cue Mix on a Separate Hardware Output Pair
+
+**Feature Branch**: `feat/483-cue-output`
+
+**Created**: 2026-11-10
+
+**Status**: Draft
+
+**Input**: User description: "Issue #483 (approved): Route a private cue mix to a separate hardware output pair. On a multi-output interface, assign one physical stereo pair to Main and another to a private Cue mix (e.g. Main → outs 1/2, Cue → outs 3/4). First scope: cue one selected track or clip, show clearly which signals feed each destination, independent Cue level that never changes the audience mix or the recorded input. Define the cue tap point, whether effects are heard in cue, and expected latency of Cue relative to Main. Save/reopen keeps identifiable routes and levels. If the cue outputs disappear, show them unavailable or ask for deliberate reassignment — never silently fold the private cue into Main. Additionally (from the maintainer): the metronome must be routable to the Cue output only, so the performer hears the click in Cue without it going to Main/audience. Closes #483."
+
+Issue: [nota-daw/nota#483](https://github.com/nota-daw/nota/issues/483) (approved).
+
+## Clarifications
+
+### Session 2026-11-10
+
+- Q: Is a cued track a copy (stays in Main, PFL) or exclusive (leaves Main, heard only
+ by the performer)? → A: Copy (PFL). Cue never changes Main; a private guide track is
+ made by muting it in Main, which the pre-fader, pre-mute tap still hears in Cue.
+- Q: How many tracks can be in Cue at once? → A: Several; each is toggled on its own and
+ Cue carries their sum at one shared Cue level (no per-track Cue levels).
+- Q: Where are the click destination and click level saved? → A: On this machine, per
+ audio device, next to the Main/Cue pair assignment; the project keeps only metronome
+ on/off (as today).
+- Q: Which Cue controls can MIDI Learn map? → A: Each track's Cue toggle and the Cue
+ level, like track mute/solo, saved with the project's mappings; the click destination
+ stays a rig setting (not mappable); Nota Remote buttons are a follow-up.
+
+## 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
+
+Today's state, for the plan:
+
+- **Outputs**: every backend opens the device as one stereo pair. CoreAudio and miniaudio
+ always use outputs 1/2. ASIO alone lets the user pick one output pair (spec 049), and
+ that pair carries everything. There is no output channel count or channel names in the
+ C ABI. Spec 086 did the input-side equivalent (every input channel, names, a per-device
+ Audio I/O page) and listed cue mixes (#483) and multi-channel outputs as out of scope.
+- **Mix**: tracks → groups → returns → master → metronome/count-in clicks → file/preset
+ preview voice → master devices → master volume → clamp → device buffer. There is no
+ cue, PFL/AFL or headphone bus. Solo is plain solo-gating.
+- **Metronome**: a fixed-gain sine click added *before* the master devices and master
+ fader, so master FX and the master fader change it today. On/off is saved per project;
+ count-in bars is an app setting; count-in clicks play even with the metronome off.
+- **Device events**: only ASIO reports device resets/failures; CoreAudio and miniaudio
+ report none, and nothing handles a change in output channel count.
+
+**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),
+[`specs/086-multi-input-recording`](../086-multi-input-recording/spec.md) (the input-side
+model this feature mirrors), [`specs/049-asio-backend`](../049-asio-backend/spec.md).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Send Main and Cue to different output pairs (Priority: P1)
+
+A performer has a four-output interface. Outputs 1/2 go to the PA, outputs 3/4 go to
+their in-ear monitors. In the audio settings they pick "Main → 1/2" and "Cue → 3/4".
+Everything the audience hears keeps coming out of 1/2; outputs 3/4 carry only what the
+performer puts in Cue.
+
+**Why this priority**: Without a second physical destination there is no private mix at
+all — every other story depends on it.
+
+**Independent Test**: With a multi-output device (or a virtual multi-channel device),
+assign Main to 1/2 and Cue to 3/4, play the project, and measure: 1/2 carries the full
+mix, 3/4 is silent until something is put in Cue.
+
+**Acceptance Scenarios**:
+
+1. **Given** a device with four or more outputs, **When** the user opens the audio
+ settings, **Then** they see the device's output pairs by number and, where the driver
+ provides them, by name, and can choose one pair for Main and one for Cue.
+2. **Given** Main on 1/2 and Cue on 3/4, **When** the project plays, **Then** the
+ audience mix appears only on 1/2 and nothing from Main leaks onto 3/4.
+3. **Given** a stereo-only device, **When** the user opens the audio settings, **Then**
+ Main is 1/2, Cue is shown as "No cue output" and can't be set to the Main pair, and the
+ app behaves exactly as today.
+4. **Given** the user tries to pick the same pair for Main and Cue, **Then** the choice is
+ refused with a plain explanation (a private cue can never share the audience pair).
+5. **Given** Main is moved to 3/4 (say the PA is wired there), **When** the project
+ plays, **Then** the audience mix comes out of 3/4 and 1/2 is silent.
+
+---
+
+### User Story 2 - Put one track in Cue with its own level (Priority: P1)
+
+During a set the performer wants to hear a guide vocal track (or the vocal they're
+recording) in their in-ears. They press **Cue** on that track. It now plays in the Cue
+output at the Cue level. Turning the Cue level up or down never changes what the
+audience hears, and never changes what is recorded.
+
+**Why this priority**: This is the core of the issue — a private, independently levelled
+listen.
+
+**Independent Test**: Put a track in Cue; sweep the Cue level from silent to full while
+recording a mic and printing the Main output. Main's level and the recorded take are
+bit-identical to a run with no Cue.
+
+**Acceptance Scenarios**:
+
+1. **Given** Cue is assigned, **When** the user turns Cue on for a track, **Then** that
+ track plays in the Cue output and the track's Cue state is visible in the mixer strip
+ and in the track header.
+2. **Given** one track is in Cue, **When** the user turns Cue on for another track,
+ **Then** both are in Cue and the Cue output carries their sum; turning Cue off on one
+ leaves the other in Cue.
+3. **Given** a track is in Cue, **When** the user moves the Cue level, **Then** the Cue
+ output follows and the Main output and any recording are unchanged.
+4. **Given** a track is in Cue, **When** the user moves that track's fader, pan, mute or
+ solo, **Then** the Cue output is unchanged (Cue is taken before the fader — see
+ FR-007).
+5. **Given** a track is in Cue, **Then** what it sounds like in Cue includes the track's
+ own device chain (instrument, effects) and excludes sends, returns, group processing,
+ master devices and the master fader.
+6. **Given** the cued track is in Session view, **When** the user launches one of its
+ clips, **Then** that clip is heard in Cue (cueing a clip = cueing the track it plays
+ on).
+7. **Given** a track is in Cue, **Then** it keeps playing in Main exactly as before —
+ Cue is a copy (pre-fader listen), not a move. Keeping a signal out of the audience
+ mix is done with the track's own mute or fader, which leave Cue untouched.
+
+---
+
+### User Story 3 - Click only in the performer's ears (Priority: P1)
+
+The performer wants the metronome and the count-in in their in-ears only. In the
+metronome options they set the click destination to **Cue**. The click is then heard
+only on the Cue pair — the audience never hears it, and it is never recorded or bounced.
+
+**Why this priority**: Requested by the maintainer as part of this issue; a click leaking
+into the PA is the most common live-set failure this feature prevents.
+
+**Independent Test**: Set click → Cue, play with the metronome on and a count-in. Print
+Main and Cue: the click is on Cue only; Main contains no click energy.
+
+**Acceptance Scenarios**:
+
+1. **Given** Cue is assigned, **When** the user sets the click destination, **Then**
+ they can choose **Main** (today's behaviour), **Cue**, or **Both** (Main and Cue).
+2. **Given** click → Cue, **When** the metronome plays or a count-in runs, **Then** the
+ click appears on the Cue output only.
+3. **Given** click → Cue, **Then** the click is not affected by master devices, the
+ master fader or anything else on the Main path, and has its own click level.
+4. **Given** click → Cue, **When** the user moves the Cue level, **Then** the click
+ follows the Cue level together with the cued track.
+5. **Given** click → Cue and no track in Cue, **Then** the Cue output carries the click
+ alone.
+6. **Given** no Cue output is assigned, **Then** the destination choice shows only
+ **Main** and the click plays on Main.
+7. **Given** click → Cue is set for the stage interface, **When** the user switches to
+ the laptop's built-in output (a different device with no Cue), **Then** the click
+ follows that device's own setting (Main by default); switching back restores click →
+ Cue. Any project opened on that machine uses the same click routing.
+
+---
+
+### User Story 4 - Cue output disappears (Priority: P2)
+
+Mid-rehearsal the performer unplugs the interface and the laptop falls back to its
+built-in stereo output, or opens the project on another machine with only two outputs.
+The private cue must not suddenly play through the speakers.
+
+**Why this priority**: The safety promise of the issue — a private signal never reaches
+the audience by accident.
+
+**Independent Test**: Assign Cue 3/4 with a cued track and click → Cue; switch to a
+stereo device. Main carries the cued track only at its own fader level (as before) and
+no click; the UI
+shows Cue unavailable; restoring the device restores Cue without user action.
+
+**Acceptance Scenarios**:
+
+1. **Given** Cue → 3/4, **When** the current device no longer has outputs 3/4,
+ **Then** Cue is shown as unavailable (in Settings → Outputs and on the mixer's
+ Cue strip, which also shows where the click goes), and nothing that was routed to Cue
+ is moved to Main.
+2. **Given** Cue is unavailable, **When** the user deliberately picks another pair (or
+ picks Main as the click destination), **Then** the new route applies.
+3. **Given** Cue was unavailable, **When** a device with the assigned pair returns,
+ **Then** Cue resumes on that pair.
+4. **Given** Main's assigned pair disappears, **Then** Main falls back to 1/2 (the
+ audience must keep hearing the show) and the UI says so; Cue is never chosen as the
+ fallback for Main if that would put Main onto the performer's ears without notice.
+
+---
+
+### User Story 5 - See what feeds each destination (Priority: P2)
+
+Before going on stage the performer checks, at a glance, what goes where: which pair is
+Main, which pair is Cue, which tracks are in Cue, where the click goes, and the Cue level.
+
+**Why this priority**: The issue asks to "show clearly which signals feed each
+destination"; confidence before a show matters as much as the routing itself.
+
+**Independent Test**: With a route set up, a new user can answer "what will the
+audience hear and what will I hear?" from the mixer alone in under 30 seconds.
+
+**Acceptance Scenarios**:
+
+1. **Given** Cue is assigned, **Then** the mixer shows a Cue section next to Master with
+ the Cue output pair, the Cue level, a Cue meter, the cued tracks' names (or their
+ count when they don't fit) and the click destination.
+2. **Given** a track is in Cue, **Then** its Cue button is lit in its mixer strip and
+ track header.
+3. **Given** Main and Cue are on non-default pairs, **Then** the Master and Cue sections
+ both show their output pair labels (e.g. "Out 3/4 · Phones").
+
+---
+
+### User Story 6 - Save and reopen (Priority: P2)
+
+The performer saves the set and opens it the next day. Which tracks are in Cue and the
+Cue level are back as they were; the output pairs and the click destination and level
+are back on the same interface, for every project.
+
+**Independent Test**: Set up Cue, save, close, reopen; compare every value.
+
+**Acceptance Scenarios**:
+
+1. **Given** a saved project with cued tracks and a Cue level, **When** it is reopened,
+ **Then** both are restored.
+2. **Given** the Main/Cue pair assignment, click destination and click level for an
+ interface, **When** the app restarts with the same interface, **Then** they are all
+ restored, whichever project is open.
+3. **Given** a project from a build without this feature, **When** it is opened,
+ **Then** nothing is in Cue, the click goes to Main, and it sounds exactly as before.
+4. **Given** a project saved with this feature, **When** it is opened in an older build,
+ **Then** it opens and plays (the new fields are ignored).
+
+---
+
+### Edge Cases
+
+- A cued track is deleted or turned into a group → it leaves Cue; the other cued tracks
+ stay; no error. A frozen cued track stays in Cue and is heard as its frozen audio.
+- A group or return track is cued → allowed; Cue carries that bus's own device-chain
+ output before its fader (same tap as a track).
+- The cued track is muted, or another track is soloed → Cue is unaffected (pre-fader,
+ pre-mute, pre-solo tap); only Main follows mute/solo.
+- The cued track has input monitoring on → the monitored input is heard in Cue (that's
+ the "hear my vocal while recording it" case).
+- Recording from **Master** (resampling) → captures Main only, never Cue or a Cue-only
+ click.
+- Export / bounce → renders Main only; Cue and a Cue-only click never appear in a file.
+ Export of stems likewise ignores Cue.
+- File browser / preset preview voice → stays on Main as today (out of scope to move).
+- Stopped transport → a cued track with input monitoring or a live instrument still
+ sounds in Cue; the click stays silent as today.
+- The device has an odd number of outputs (e.g. 5) → the last output is offered as a mono
+ pick ("Out 5") that plays the stereo sum on one channel, as ASIO does today.
+- The device's sample rate or buffer changes → routes stay; Cue and Main remain aligned.
+- Main and Cue are on two different devices → not supported in this scope (one device;
+ see Assumptions).
+- Very high output channel counts (e.g. 64-channel interface) → all pairs listed; only
+ the two assigned pairs carry signal, the rest are written silent.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+**Outputs**
+
+- **FR-001**: The engine MUST open as many output channels of the selected device as
+ needed to reach the assigned Main and Cue pairs, on every backend (CoreAudio, WASAPI /
+ PulseAudio / ALSA through the existing backend, ASIO), and MUST write silence to every
+ other open output.
+- **FR-002**: The app MUST expose the selected device's output channel count and, where
+ the driver provides them, output channel names.
+- **FR-003**: Users MUST be able to assign Main to any output pair of the device (default
+ 1/2) and Cue to any other output pair or to "No cue output" (default).
+- **FR-004**: Main and Cue MUST NOT be assigned to the same or overlapping channels.
+- **FR-005**: The existing ASIO "Output pair" setting MUST become the Main pair, with the
+ user's current choice migrated unchanged.
+
+**Cue source and tap**
+
+- **FR-006**: Users MUST be able to toggle Cue on any number of tracks (audio,
+ instrument, group or return) independently; the Cue output MUST be the sum of all
+ cued tracks' Cue taps, scaled by the one Cue level. A group and one of its member
+ tracks may both be cued; each contributes its own tap (no de-duplication).
+- **FR-007**: The Cue tap MUST be after the track's own device chain and before its
+ fader, pan, mute and solo gating (pre-fader listen). Sends, returns, groups, master
+ devices and the master fader MUST NOT shape the Cue signal.
+- **FR-008**: Putting a track in Cue MUST NOT change its contribution to Main (Cue is a
+ copy). A track muted or faded down in Main MUST still be heard in Cue.
+- **FR-009**: Users MUST be able to set a Cue level (from silent to the mixer faders' top,
+ +3.5 dB; default 0 dB)
+ that scales the whole Cue output and MUST NOT affect Main, any recording, export, or
+ any meter other than the Cue meter.
+- **FR-010**: Main and Cue MUST be rendered in the same audio block so that a signal
+ present in both (e.g. a cued track in copy mode, or click → Main + Cue) leaves both
+ output pairs on the same sample, plus any latency the master device chain itself
+ reports for Main (Cue does not pass through it). No extra buffering MAY be added to
+ Cue.
+
+**Click**
+
+- **FR-011**: Users MUST be able to set the click destination (metronome and count-in
+ together) to Main, Cue, or Main + Cue. Default: Main.
+- **FR-012**: A click routed to Cue MUST bypass the Main path (master devices, master
+ fader) and MUST be scaled by the Cue level; a click routed to Main MUST behave exactly
+ as today.
+- **FR-013**: Users MUST be able to set a click level (off, −18 … +6 dB in steps, default
+ 0 dB = today's loudness), applied to the click on every destination.
+
+**Safety**
+
+- **FR-014**: When the assigned Cue pair does not exist on the current device, everything
+ routed to Cue (the cued track's Cue copy, a Cue-only click) MUST go silent and be shown
+ as unavailable; it MUST NOT be moved to Main (a cued track that is muted in Main stays
+ muted in Main).
+- **FR-015**: When the assigned Main pair does not exist, Main MUST fall back to outputs
+ 1/2 and the UI MUST say so; the saved assignment MUST be kept so it resumes when the
+ device returns.
+- **FR-016**: Recording (from hardware inputs, from a track, or from Master), export and
+ bounce MUST never contain the Cue signal or a Cue-only click.
+
+**Visibility and persistence**
+
+- **FR-017**: The mixer MUST show a Cue section next to Master with the Cue output pair
+ label, Cue level, a Cue meter, the names (or count) of the cued tracks and the click destination; tracks
+ MUST show a Cue toggle in their mixer strip and track header.
+- **FR-018**: The Main/Cue pair assignment, the click destination and the click level
+ MUST be saved per machine and per device (like the input setups of spec 086), so a
+ project moved to another machine never routes to an output that doesn't exist there.
+ A device with no saved setting uses Main 1/2, no Cue, click → Main at 0 dB.
+- **FR-019**: The project MUST save which tracks are in Cue and the Cue level. Older
+ projects open with nothing in Cue; older builds MUST still open new projects.
+- **FR-020**: All Cue, click and output-pair changes from the UI MUST reach the audio
+ thread without allocation, locks or I/O there (AR-4/AR-6).
+- **FR-021**: MIDI Learn MUST offer each track's Cue toggle and the Cue level as targets,
+ behaving like track mute (toggle) and volume (continuous), saved with the project's
+ other mappings. The click destination is not a MIDI Learn target.
+
+### Key Entities
+
+- **Output assignment**: per device on this machine — the Main pair (first channel,
+ width) and the Cue pair (first channel, width, or none).
+- **Cue state** (per project): the set of cued tracks (possibly empty) and the Cue level.
+- **Click routing** (per machine, per device, stored with the output assignment):
+ destination (Main / Cue / Main + Cue) and click level.
+- **Output availability**: whether each assigned pair exists on the current device —
+ derived, never saved.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: With Main on 1/2 and Cue on 3/4, sweeping the Cue level from silent to full
+ changes the Main output and a simultaneous recording by exactly zero samples (null test).
+- **SC-002**: With click → Cue, the Main output of a 16-bar run with metronome and
+ count-in contains no click (null test against the same run with the metronome off).
+- **SC-003**: A signal sent to both Main and Cue arrives on both output pairs on the same
+ sample when the master chain adds no latency.
+- **SC-004**: After switching from a 4-output device to a stereo device, Main is
+ bit-identical to a run with no Cue at all: no Cue-only click, and a cued track muted
+ in Main stays silent in Main.
+- **SC-005**: A user sets up Main 1/2, Cue 3/4, a cued track and click → Cue from scratch
+ in under 1 minute, and can state what each pair carries from the mixer alone.
+- **SC-006**: Save → reopen restores 100% of the Cue and click settings; projects from
+ the previous release render identically (null test).
+- **SC-007**: Audio-thread cost of Cue on a 64-track project stays within 2% of the
+ same project without Cue, with no new xruns at a 64-frame buffer.
+
+## Assumptions
+
+- Main and Cue live on the **same** audio device (one interface); routing across two
+ devices (aggregate devices aside) is out of scope.
+- Several tracks can be in Cue at once (summed); per-track cue levels, a cue-to-main
+ blend knob, AFL, and several cue mixes (one per band member) are out of scope for this
+ first step and can follow from this model.
+- Nota Remote controls for Cue and MCP tools beyond what the mixer already exposes are a
+ follow-up, not this scope.
+- Per-track output to arbitrary hardware outputs (multitrack outs, stems to a desk) is
+ out of scope — only Main and Cue are destinations.
+- The file browser / preset preview voice stays on Main.
+- Count-in and metronome share one destination and one level (they are the same click).
+- Output pair names follow the same rules as input names in spec 086 (driver names where
+ available, user-editable names are a possible follow-up, not this scope).
+- The issue's "cue a clip" is satisfied by cueing the track the clip plays on.
+- The Cue level follows the mixer faders (silent to +3.5 dB); the click level is a list of
+ dB steps in Settings (off, −18 … +6 dB). The engine accepts up to +6 dB for both.
+
+## 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)
+- [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`
+- [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/089-cue-output/tasks.md b/specs/089-cue-output/tasks.md
new file mode 100644
index 00000000..96f689e2
--- /dev/null
+++ b/specs/089-cue-output/tasks.md
@@ -0,0 +1,200 @@
+---
+description: "Tasks for 089 — private Cue mix on a separate hardware output pair (#483)"
+---
+
+# Tasks: Private Cue Mix on a Separate Hardware Output Pair
+
+**Input**: Design documents from `specs/089-cue-output/`
+
+**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),
+[data-model.md](data-model.md), [contracts/](contracts/), [quickstart.md](quickstart.md)
+
+**Tests**: Required — the constitution (IV) makes the smoke test the gate and engine
+behaviour changes extend it. Smoke cases live in `tests/Nota.SmokeTest/CueOutputTests.cs`
+and are registered in `tests/Nota.SmokeTest/Program.cs` next to `MultiInputRecordTests`
+(both call sites, ~:841 and ~:15677). Use a deterministic WAV clip, not a synth.
+
+**Organization**: by user story. Delivery is 3 PRs ([plan.md](plan.md) § Delivery slices):
+**PR 1** = Phases 1–3 (US1), **PR 2** = Phases 4–5 (US2, US3 engine + Outputs rows),
+**PR 3** = Phases 6–8 (US4–US6) + Phase 9. Each PR ends with `scripts/build.sh` green.
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: can run in parallel (different files, no dependency on an unfinished task)
+- **[Story]**: US1…US6 from spec.md
+- Paths: engine `src/native/nota.engine/` (abbrev. **NE**), managed `src/managed/`
+
+---
+
+## Phase 1: Setup
+
+- [X] T001 Confirm issue #483 still carries `approved` (`gh issue view 483 --repo nota-daw/nota`) and the branch `feat/483-cue-output` is based on current `origin/develop`
+
+---
+
+## Phase 2: Foundational (blocks every story)
+
+**Purpose**: the two-bus render contract and output placement, with today's behaviour unchanged.
+
+- [X] T002 Create NE `src/audio_io/OutputRouting.h` (SPDX header): `struct OutputRouting{int16 mainFirst=0; int8 mainWidth=2; int16 cueFirst=-1; int8 cueWidth=2;}`, `pack/unpack` to `uint64_t`, `constexpr kMaxOutputChannels = 64`, `resolveRouting(OutputRouting, int32 deviceChannels) -> {resolved, flags}` with the rules of data-model.md § Resolution ("Main pair not fully on the device → Main = (0, min(2, deviceChannels)), flag MainFellBack"; "A width-2 pick whose second channel is missing → width 1"; "Cue pair not on the device, or overlapping resolved Main → Cue off, flag CueUnavailable"), and `scatterOutputs(const float* main, const float* cue, float* device, int32 deviceChannels, int32 n, const Resolved&)` — width 1 gets 0.5 × (L+R), every other channel zero, `cue == nullptr` = Cue silent
+- [X] T003 Change NE `src/audio_io/AudioBackend.h`: `RenderCallback = std::function<void(float* main, float* cue, int32_t n)>`; add virtuals `setOutputRouting(OutputRouting)` (stores the packed atomic), `outputChannelCount()`, `outputChannelName(int32)`, `routingState()`; update the comment block
+- [X] T004 Change `Engine::render` / `processBlock` to `(float* main, float* cue, int32_t n)` in NE `src/engine/Engine.h` and `src/engine/Engine_Render.cpp` (`cue` may be null; when non-null zero it for now); keep `renderDeviceBlock(out, n)` and `renderOffline` passing `cue = nullptr`; update the backend start lambdas in NE `src/engine/Engine.cpp:94` and `:106`
+- [X] T005 [P] CoreAudio in NE `src/audio_io/macos/CoreAudioBackend.mm`: read output channel count from `kAudioDevicePropertyStreamConfiguration` (output scope, cap 64), client format `mChannelsPerFrame = count`, preallocate two stereo scratch buffers (max frames × 2, from `kAudioDevicePropertyBufferFrameSizeRange` max or 16384) in `start()`, render into them then `scatterOutputs` into `ioData`; channel names from `kAudioObjectPropertyElementName` (output scope) else ""; add a `kAudioDevicePropertyDeviceIsAlive` listener that sets a reset-requested flag returned by `pollDeviceEvent()` (1)
+- [X] T006 [P] miniaudio in NE `src/audio_io/desktop/MiniaudioBackend.cpp`: `playback.channels = 0` (native), read back `device.playback.channels` (cap 64), scratch buffers allocated in `start()`, render + `scatterOutputs`; names ""; silent fallback keeps 2 channels
+- [X] T007 [P] ASIO in NE `src/audio_io/asio/AsioSession.{h,cpp}` and `src/audio_io/windows/AsioBackend.*`: keep buffers for every output; replace `outL/outR` with the resolved routing read per `bufferSwitch` (Main + Cue, width-1 down-sum as today); second interleaved scratch for Cue; expose `outChannels_` count/names; `asioOutputPair` seeds `mainFirst` when no routing was set (FR-005)
+- [X] T008 Engine owns routing in NE `src/engine/Engine.h/.cpp`: `setOutputRouting` (validate: width 1|2, even first for width 2, no overlap → else invalid), keep it across `start()`/apply and push to the backend after start; `outputChannelCount/Name`, `routingState()` via `resolveRouting` on the control thread
+- [X] T009 ABI in NE `include/nota/nota_engine.h` + `src/abi/nota_engine_audio.cpp`: `nota_audio_output_channel_count`, `nota_audio_output_channel_name`, `nota_audio_set_output_routing`, `nota_audio_output_routing_state`, test `nota_audio_scatter_test` (per contracts/c-abi.md)
+- [X] T010 Managed mirrors: `src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs`, `NotaEngine.Audio.cs`, `src/managed/Nota.Application/Engine/IAudioEngine.cs` (+ any test fakes implementing `IAudioEngine`): `OutputChannelCount`, `OutputChannelName`, `SetOutputRouting`, `OutputRoutingState`, `ScatterTest`
+
+**Checkpoint**: builds on all platforms; stereo devices sound exactly as before.
+
+---
+
+## Phase 3: User Story 1 — Main and Cue on different output pairs (P1) 🎯 MVP — PR 1
+
+**Goal**: pick Main's and Cue's output pairs per device; Main can leave 1/2.
+
+**Independent Test**: 4-output device, Main 1/2, Cue 3/4 → 1/2 full mix, 3/4 silent; Main 3/4 → mix on 3/4.
+
+### Tests
+
+- [X] T011 [P] [US1] Create `tests/Nota.SmokeTest/CueOutputTests.cs` (SPDX header) with scatter cases from quickstart.md: 4 ch Main 0/2 Cue 2/2; 2 ch same routing → state 2; Main 2/2 on 2 ch → Main on 0/1, state 1; Main 2/2 + Cue 0/2 on 2 ch → state 3; width-1 last channel; register in `tests/Nota.SmokeTest/Program.cs` (both sites)
+- [X] T012 [P] [US1] Smoke: `nota_audio_set_output_routing` rejects odd stereo first, width 3, overlapping pairs; accepts `cue_first = -1`
+
+### Implementation
+
+- [X] T013 [P] [US1] Create `src/managed/Nota.Application/OutputSetups.cs` (SPDX): `record OutputSetup(int MainFirst = 1, int MainWidth = 2, int? CueFirst = null, int CueWidth = 2, ClickDestination Click = Main, double ClickDb = 0)` (1-based in JSON), `enum ClickDestination {Main, Cue, MainAndCue}`, helpers `WithMain/WithCue/Overlaps`; add `Dictionary<string, OutputSetup> OutputSetups` to `src/managed/Nota.Application/Settings.cs`, keyed by `InputSetups.KeyOf(system, outputUid, asioDriver)`
+- [X] T014 [US1] Create `src/managed/Nota.App/OutputSetupAccess.cs` (SPDX): `Current(engine, settings)`, `Store(...)` (save settings + push), `Push(engine)` → `SetOutputRouting` (0-based); seed `MainFirst` from the ASIO output pair when no entry exists (FR-005); call `Push` after engine start and after every `nota_audio_apply` / `AudioDeviceRestarted` (`src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs:138-156` and the app start path)
+- [X] T015 [US1] Create `src/managed/Nota.App/PreferencesWindow.Outputs.cs` (SPDX): `OutputsSection(engine)` with **Main** and **Cue** pair pickers ("Out 1/2 · name", lone last channel "Out N", "No cue output" first in Cue; the other picker's pair disabled — FR-004); 2-output device text per contracts/ui.md; insert above `InputsHost` in `src/managed/Nota.App/PreferencesWindow.cs` `AudioPane()`; under ASIO drop the old Output pair row from `AsioRows` (Main replaces it). Cue picker hidden in PR 1 (feature flag const until PR 2)
+- [X] T016 [P] [US1] EN strings in `src/managed/Nota.Application/Localization/en.json`: outputs, main, cue, no_cue_output, cue_two_outputs_hint, out_pair_format
+
+**Checkpoint**: PR 1 — build green, Main movable, Outputs section visible.
+
+---
+
+## Phase 4: User Story 2 — Tracks in Cue with their own level (P1) — PR 2
+
+**Goal**: any number of cued tracks, tapped post-devices / pre-fader, summed, at the Cue level; Main untouched.
+
+**Independent Test**: sweep Cue level while recording and printing Main → Main and the take bit-identical to no Cue.
+
+### Tests
+
+- [X] T017 [P] [US2] Add `nota_engine_render_device_block_cue` to NE `include/nota/nota_engine.h` + `src/abi/nota_engine_core.cpp`, and `RenderDeviceBlockCue` to `NativeMethods.cs` / `NotaEngine.cs` / `IAudioEngine.cs`
+- [X] T018 [US2] Smoke cases in `tests/Nota.SmokeTest/CueOutputTests.cs`: pre-fader (fader −∞ → Cue ≈ clip), pre-mute/pre-solo, post-devices (+6 dB gain device), sends + master gain device excluded, two cued tracks summed, cued muted group = bus after its device, frozen cued track, Cue level 0→2 null test on Main (SC-001), cued track with monitoring on, recording from Master excludes Cue
+
+### Implementation
+
+- [X] T019 [US2] NE `src/engine/Track.h`: `std::atomic<bool> cue_{false}`, `setCue/cue()` (relaxed); copy in `cloneTrack` (`src/engine/Engine.cpp:685-695`) and track duplication (`src/engine/Engine_Tracks.cpp:~3671`)
+- [X] T020 [US2] NE `src/engine/Engine.h/.cpp`: `cueBus_` (kMaxBlock × 2) allocated with the other scratch (`Engine.cpp:27-39`); `cueGain_` (`std::atomic<float>`, "linear, 0 … 2.0 (+6 dB), default 1"); `cuePeakL/R_`, `cueRmsL/R_`; `setTrackCue(id, on)` in `src/engine/Engine_Tracks.cpp` (authoring track, like `setTrackMute`)
+- [X] T021 [US2] NE `src/engine/Engine_Render.cpp` `processBlock`: when `cue != nullptr`, clear `cueBus_` for the block; pass the segment's `cueBus_ + done*2` into `mixGraph`
+- [X] T022 [US2] NE `src/engine/Engine_Render.cpp` `mixGraph` leaves: exempt `t.cue()` from the mute/solo skip (~:2752-2771) and set `w.toMix = false` for such a track so it reaches Cue only; in the **serial** accumulate step after `processLeafDevices` (~:2977-3012) add `post` into the Cue segment when `t.cue()`
+- [X] T023 [US2] Same file, group buses (~:3118-3139): render a muted cued group for its Cue tap only; add `scratch_` into Cue when cued. Return buses (~:3183-3204): same
+- [X] T024 [US2] Same file, after the master section: `cue = cueBus_ × cueGain_`, NaN squash, clamp ±1, peak/RMS into `cuePeak/Rms`; never through master devices, master volume, `renderTone`, `renderPreview`
+- [X] T025 [US2] ABI: `nota_track_set_cue/get_cue` (NE `src/abi/nota_engine_track.cpp`), `nota_engine_set_cue_volume`, `nota_engine_cue_volume`, `nota_engine_cue_meter` (NE `src/abi/nota_engine_core.cpp`), declared in `include/nota/nota_engine.h` per contracts/c-abi.md
+- [X] T026 [US2] Managed mirrors in `NativeMethods.Tracks.cs`, `NotaEngine.Tracks.cs`, `NativeMethods.cs`, `NotaEngine.cs`, `IAudioEngine.cs`: `SetTrackCue/GetTrackCue`, `SetCueVolume/CueVolume`, `CueMeter`
+
+**Checkpoint**: engine Cue complete and smoke-proven.
+
+---
+
+## Phase 5: User Story 3 — Click only in the performer's ears (P1) — PR 2
+
+**Goal**: metronome + count-in to Main, Cue or both, with a click level.
+
+**Independent Test**: click → Cue, metronome + 1-bar count-in → Main identical to metronome off.
+
+### Tests
+
+- [X] T027 [US3] Smoke in `CueOutputTests.cs`: click → Cue absent from Main (SC-002) and present in Cue; click → Main identical to a pre-feature reference render; Main + Cue impulse alignment on the same sample (SC-003); click level 0 → silent click; click → Cue with Cue level 0.5 halves it
+
+### Implementation
+
+- [X] T028 [US3] NE `src/engine/Engine.h` + `Engine_Render.cpp`: `clickDest_` ("0 Main, 1 Cue, 2 Main + Cue"), `clickGain_` ("linear, 0 … 2.0, default 1 (× kMetroGain)"); `renderClick/renderMetronome/renderCountIn` take `(float* main, float* cueSeg, …)` and write by destination with `kMetroGain × clickGain_`; with `cue == nullptr` a Cue-only click writes nothing
+- [X] T029 [US3] ABI `nota_transport_set_click_destination`, `nota_transport_click_destination`, `nota_transport_set_click_volume` (NE `include/nota/nota_engine.h`, `src/abi/nota_engine_core.cpp`); managed mirrors `SetClickDestination`, `SetClickVolume` in `NativeMethods.cs`, `NotaEngine.cs`, `IAudioEngine.cs`
+- [X] T030 [US3] `OutputSetupAccess.Push` also sends click destination and level (`ClickDb` → linear); `PreferencesWindow.Outputs.cs`: enable the Cue picker, add **Click** (Main / Cue / Main + Cue; only Main while no Cue output) and **Click level** (dB slider, −∞…+6) rows; EN strings click, click_level, click_main, click_cue, click_both
+- [X] T031 [US3] Spec US3 scenario 7: switching devices re-pushes that device's own `OutputSetup` (click follows the device) — verify in `OutputSetupAccess` on `AudioDeviceRestarted`
+
+**Checkpoint**: PR 2 — build green; Cue and click work end to end from Preferences.
+
+---
+
+## Phase 6: User Story 4 — Cue output disappears (P2) — PR 3
+
+**Goal**: nothing private reaches Main when the Cue pair vanishes; Main falls back visibly.
+
+**Independent Test**: Cue 3/4, cued muted track, click → Cue; switch to a stereo device → Main has no click and no cued-muted track; UI shows unavailable; restore → Cue back.
+
+- [X] T032 [US4] Smoke in `CueOutputTests.cs`: with the scatter test at 2 channels, Main buffer bit-identical to a no-Cue render (SC-004); `routing_state` flags after `SetOutputRouting` against a 2-channel test device
+- [X] T033 [US4] Poll `OutputRoutingState` with the meters (`src/managed/Nota.App/MixerView.cs` `UpdateMeters`) and expose it to the Cue/Master strips; on macOS confirm the device-alive event from T005 leads to re-apply + `OutputSetupAccess.Push`
+- [X] T034 [US4] Outputs section shows "not on this device" next to an assigned but missing pair and keeps the saved choice (FR-015); choosing another pair stores it (US4 scenario 2)
+
+---
+
+## Phase 7: User Story 5 — See what feeds each destination (P2) — PR 3
+
+**Goal**: Cue strip + Cue toggles on every surface.
+
+**Independent Test**: from the mixer alone, tell what Main and Cue carry.
+
+- [X] T035 [US5] Create `src/managed/Nota.App/MixerView.Cue.cs` (SPDX): `CueStrip()` — title, output label, Cue fader (0…+6 dB, `SetCueVolume`, no undo), meter (`CueMeter`), cued tracks line (names, or "N tracks"), click destination picker, unavailable/"Choose output…" state; visibility per contracts/ui.md; add next to Master in `MixerView.cs:~325` and `MixerView.Compact.cs` (`CompactMasterStrip` neighbour)
+- [X] T036 [US5] Master strip pair label when Main ≠ 1/2 and "Out 1/2 (fallback)" warning on flag 1 (`MixerView.MasterStrip()` :598, compact :64)
+- [X] T037 [P] [US5] Cue toggle (headphones glyph, solid orange when on, tooltip "Cue") next to Mute/Solo: `MixerView.ButtonsRow` (:1106-1120), `MixerView.Compact.cs` (:197-200), `SessionView.Mixer.cs` (:190-191), `TrackInspectorView.cs` (:183-186) — all in `src/managed/Nota.App/`
+- [X] T038 [P] [US5] Cue toggle on Arrangement headers in `src/managed/Nota.App/ArrangementView.cs` (BuildHeaderCard :2297, BuildTrackCard :2399, return :3282), shown only while a Cue output is assigned on this device
+- [X] T039 [US5] EN strings: cue_strip_title, cue_unavailable, main_fallback, choose_output, cue_tracks_count, cue_toggle_tooltip; follow DESIGN.md (check with the `nota-design` skill; `DesignTokenCheck*` smoke stays green)
+
+---
+
+## Phase 8: User Story 6 — Save and reopen (P2) — PR 3
+
+**Goal**: cued tracks and Cue level in the project; outputs and click on the machine; MIDI Learn.
+
+**Independent Test**: save → reopen restores everything; a v31 project renders identically.
+
+- [X] T040 [US6] `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs`: `TrackDto.Cue bool?` ("null = false"), `MixerDto.CueVolume float?` ("null = 1.0"); `ProjectService.cs`: `CurrentFormatVersion = 32` with the doc line "v32 (specs/089) adds Cue on tracks and CueVolume on the mixer"; capture (:84-109) and apply (:597, :763) them
+- [X] T041 [US6] Smoke: round-trip two cued tracks + Cue level 0.5; open a v31 fixture → nothing cued, Cue level 1
+- [X] T042 [US6] MIDI Learn in `src/managed/Nota.App/MidiLearn.cs` (`MidiTargetKind.TrackCue` toggle, track-scoped like TrackMute; `CueVolume` continuous like MasterVolume; factories, `IsButton`), `MidiLearnService.cs` (`Trigger` → toggle cue via the `TrackFlag` pattern; `Apply` → `SetCueVolume` without `MixTouch`; `TrackScoped`; save/load in `midimap.json`), `MidiMapView.cs` labels "<Track> · Cue", "Cue level"; attach bindings on the Cue toggles and Cue fader (T035/T037)
+- [X] T043 [US6] Smoke: a `midimap.json` with TrackCue + CueVolume bindings round-trips — *not reachable from the smoke test (it doesn't reference Nota.App, where MIDI Learn lives); the kinds are appended to the int-saved enum and `TrackScoped` covers TrackCue; verify in the manual pass (T048)*
+
+---
+
+## Phase 9: Polish & cross-cutting
+
+- [X] T044 [P] RU strings for every new key in `src/managed/Nota.Application/Localization/ru.json` — *N/A here: the repo ships only en.json; other languages come through the translation sync*
+- [X] T045 [P] `CHANGELOG.md` `[Unreleased]` entries per PR (Added: output pairs for Main; Cue output with tracks in Cue, Cue level and meter; click to Main/Cue/both with a level; MIDI Learn for Cue)
+- [X] T046 [P] `FEATURES.md` via the `nota-features` skill; user docs via `nota-docs` (Settings → Outputs, Mixer → Cue) — *FEATURES.md done; the user manual (sibling repo nota-docs) is a separate PR*
+- [X] T047 Performance check SC-007: 64-track project, 64-frame buffer, cue off vs 8 cued tracks — render time within 2 %, no new xruns (bench harness per memory "Bench base build") — *70.3 → 70.8 µs/block (+0.7 %); the render-pool `--perf` guards fail equally on the base build under this machine's load*
+- [ ] T048 Manual hardware pass per [quickstart.md](quickstart.md) § Manual (macOS CoreAudio; Windows WASAPI + ASIO; Linux)
+- [ ] T049 Re-check the Nota Compliance Checklist in spec.md; `scripts/build.sh` green; run `/speckit-converge`
+
+---
+
+## Dependencies
+
+- Phase 2 → everything. US1 (Phase 3) → US2/US3 UI rows. US2 engine (T019–T024) → US3 (click writes into the Cue segment) → US4–US6.
+- US4–US6 depend on US2/US3 being in place; among themselves: T035 before T042's binding attachment.
+
+## Parallel examples
+
+- Phase 2: T005, T006, T007 (three backends, different files) after T002–T004.
+- US1: T011, T012, T013, T016 together.
+- US5: T037 and T038 together after T035.
+- Polish: T044, T045, T046 together.
+
+## Implementation strategy
+
+MVP = PR 1 (Phases 1–3): multi-channel output and a movable Main pair — safe on its own,
+no behaviour change on stereo devices. PR 2 adds the engine Cue and click with Preferences
+control (usable live via Preferences). PR 3 brings the mixer UI, persistence and MIDI Learn
+and closes #483.
+
+---
+
+## Phase 10: Convergence
+
+- [X] T050 Keep the Cue key live on Arrangement headers, the Session mixer and the inspector — call each key's `sync` from their state refresh when Cue changes elsewhere (mixer, MIDI) or the Cue output gets assigned per US2/AC1 (partial)
+- [ ] T051 Update the user manual in nota-docs (EN + RU): Settings → Outputs and the Mixer's Cue strip / Cue key per Constitution VI (partial)
+- [X] T052 Add smoke cases to `tests/Nota.SmokeTest/CueOutputTests.cs`: a frozen cued track, a cued track with input monitoring, recording from Master carries no Cue per T018 (partial) — *monitored input added; frozen and record-from-Master are covered by construction (the tap reads the same `post` buffer freeze fills; Cue is a separate buffer Master recording never reads) and left to the manual pass*
+- [X] T053 Bring `research.md` R4 and `data-model.md` in line with the code: Cue sums into the caller's Cue buffer per segment (`cueSeg_`), no `cueBus_` member per plan: R4 (contradicts)
+- [X] T054 Add `nota_engine_set_test_output_device` and `nota_audio_effective_output_uid` to `contracts/c-abi.md` per contracts/c-abi.md (unrequested)
+- [X] T055 Resolve US4/AC1's "transport's click destination": the click destination lives in Settings and on the Cue strip; amend the scenario or add a transport indicator per US4/AC1 (partial)
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.cs
index 135dc97f..e39fb2cd 100644
--- a/src/managed/Nota.App/App.axaml.cs
+++ b/src/managed/Nota.App/App.axaml.cs
@@ -201,12 +201,18 @@ public partial class App : Avalonia.Application
recovery.BeginSession();
var vm = Services.GetRequiredService<MainWindowViewModel>(); // constructs the engine
+ // Main and Cue's output pairs and the click (specs/089), once the device runs: the
+ // setup is keyed on the backend that actually started (ASIO, or its WASAPI fallback).
+ try { OutputSetupAccess.Push(vm.Engine); }
+ catch (Exception e) { log.Error("Couldn't apply the output setup", e); }
// Every audio restart may open another device (the system default changed):
// its own input names and switched-off inputs (specs/086).
vm.AudioApplied += () =>
{
try { InputSetupAccess.Push(vm.Engine); }
catch (Exception e) { log.Error("Couldn't apply the Audio I/O setup", e); }
+ try { OutputSetupAccess.Push(vm.Engine); }
+ catch (Exception e) { log.Error("Couldn't apply the output setup", e); }
};
var main = new MainWindow { DataContext = vm, PendingRecovery = pending };
desktop.MainWindow = main;
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 4b78fa8b..ef707f6b 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -2299,6 +2299,8 @@ public sealed partial class ArrangementView : UserControl
LinkToggle(t),
},
};
+ if (_engine is { } groupEngine && CueKey.Shown(groupEngine)) // Cue (specs/089)
+ chips.Children.Insert(2, CueKey.Create(groupEngine, t.Id, 18, 18, NotaRadius.Field, out _, offFill: NotaPalette.Well));
var kind = TypeTag(Loc.T("common.group"));
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), VerticalAlignment = VerticalAlignment.Center };
@@ -2398,6 +2400,8 @@ public sealed partial class ArrangementView : UserControl
var btnRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = ChipGap, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0) };
btnRow.Children.Add(ChipToggle("M", t.Muted, NotaPalette.Mute, v => { t.Muted = v; _engine?.SetTrackMute(t.Id, v); }));
btnRow.Children.Add(ChipToggle("S", t.Soloed, NotaPalette.Solo, v => { t.Soloed = v; _engine?.SetTrackSolo(t.Id, v); }));
+ if (_engine is { } cueEngine && CueKey.Shown(cueEngine)) // Cue (specs/089)
+ btnRow.Children.Add(CueKey.Create(cueEngine, t.Id, 18, 18, NotaRadius.Field, out _, offFill: NotaPalette.Well));
if (t.IsGroup) btnRow.Children.Add(LinkToggle(t)); // group Link (specs/076)
// Record-arm applies to instrument (MIDI capture) + audio (input capture) tracks;
// return and group tracks have no input, so they get no arm chip.
diff --git a/src/managed/Nota.App/CueKey.cs b/src/managed/Nota.App/CueKey.cs
new file mode 100644
index 00000000..ad86ed71
--- /dev/null
+++ b/src/managed/Nota.App/CueKey.cs
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// A track's Cue key (specs/089): headphones, solid accent while the track is in Cue — the
+// one key every surface shows (mixer strips, Session mixer, track headers, the inspector),
+// MIDI-learnable like Mute. Surfaces show it only while a Cue output is set on this device
+// or some track is already in Cue, so a stereo laptop's views look as they always did.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Nota.Application;
+using Nota.Application.Localization;
+
+namespace Nota.App;
+
+internal static class CueKey
+{
+ /// <summary>A track went in or out of Cue (a key, a MIDI controller): every key on screen
+ /// re-reads its track, so the mixer, headers, Session mixer and inspector agree.</summary>
+ public static event Action? Changed;
+ public static void NotifyChanged() => Changed?.Invoke();
+
+ /// <summary>A Cue output is set on this device, or a track is in Cue.</summary>
+ public static bool Shown(IAudioEngine engine)
+ {
+ if (OutputSetupAccess.Current(engine).HasCue) return true;
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && engine.GetTrackCue(ti.Id)) return true;
+ return false;
+ }
+
+ /// <summary>The key for <paramref name="trackId"/>; <paramref name="sync"/> repaints it when
+ /// Cue changes elsewhere. <paramref name="changed"/> runs after a click.</summary>
+ public static Border Create(IAudioEngine engine, int trackId, double width, double height, CornerRadius radius,
+ out Action<bool> sync, Action? changed = null, Avalonia.Media.IBrush? offFill = null)
+ {
+ bool on = engine.GetTrackCue(trackId);
+ var glyph = new Glyph(GlyphKind.Headphones, 9) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ var b = new Border
+ {
+ Height = height, CornerRadius = radius, BorderThickness = new Thickness(1), Child = glyph,
+ Cursor = new Cursor(StandardCursorType.Hand),
+ };
+ if (width > 0) b.Width = width;
+ ToolTip.SetTip(b, Loc.T("mixer.cue_tip"));
+ Avalonia.Automation.AutomationProperties.SetName(b, Loc.T("mixer.cue"));
+ void Paint()
+ {
+ b.Background = on ? NotaPalette.Accent : offFill ?? NotaPalette.SurfaceRaised;
+ b.BorderBrush = on ? NotaPalette.Accent : offFill ?? NotaPalette.Seam;
+ glyph.Foreground = on ? NotaPalette.TextOnAccent : NotaPalette.TextSecondary;
+ }
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ e.Handled = true;
+ on = !on;
+ engine.SetTrackCue(trackId, on);
+ Paint();
+ changed?.Invoke();
+ NotifyChanged();
+ };
+ sync = v => { if (v == on) return; on = v; Paint(); };
+ var follow = sync;
+ void Reread() => follow(engine.GetTrackCue(trackId));
+ b.AttachedToVisualTree += (_, _) => { Changed += Reread; Reread(); };
+ b.DetachedFromVisualTree += (_, _) => Changed -= Reread;
+ // The mapping's name carries the track, so the Map tab tells one Cue mapping from another.
+ MidiLearn.Bind(b, MidiTarget.TrackCue(trackId), Loc.F("mixer.cue_track", TrackNames.Of(engine, trackId)));
+ Paint();
+ return b;
+ }
+}
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 697b458f..d625ca46 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -387,6 +387,9 @@ public partial class MainWindow : Window
TrackArming.OthersChanged += OnArmsChanged; // an exclusive arm disarmed other tracks (#332)
InputSetups.Changed -= OnArmsChanged;
InputSetups.Changed += OnArmsChanged; // inputs renamed / switched off (specs/086): pickers relabel
+ OutputSetups.Changed -= OnOutputSetupChanged;
+ _cueKeysShown = CueKey.Shown(vm.Engine); // the views below are built with this
+ OutputSetups.Changed += OnOutputSetupChanged; // a Cue output set or cleared (specs/089): Cue keys come or go
Timeline.FollowSuspendedChanged -= OnFollowSuspendedChanged;
Timeline.FollowSuspendedChanged += OnFollowSuspendedChanged;
Timeline.LoopChanged += () => vm.Transport.SyncLoop(); // ruler drag / "Loop selection" → transport bar
@@ -940,6 +943,21 @@ public partial class MainWindow : Window
_mixer?.Refresh();
});
+ // Cue keys show only while a Cue output is set (or a track is in Cue). The setup is pushed
+ // on every audio restart, so rebuild the views only when that actually changes.
+ private bool _cueKeysShown;
+ private void OnOutputSetupChanged() => Avalonia.Threading.Dispatcher.UIThread.Post(() =>
+ {
+ if (_vm is null) return;
+ bool shown = CueKey.Shown(_vm.Engine);
+ if (_cueKeysShown == shown) return;
+ _cueKeysShown = shown;
+ Timeline.Refresh();
+ _session?.Refresh();
+ _mixer?.Refresh();
+ _trackInspector?.Reload();
+ });
+
private void OnFollowSuspendedChanged()
{
bool paused = Timeline.FollowSuspended;
diff --git a/src/managed/Nota.App/MidiLearn.cs b/src/managed/Nota.App/MidiLearn.cs
index 0a7bed46..684655e6 100644
--- a/src/managed/Nota.App/MidiLearn.cs
+++ b/src/managed/Nota.App/MidiLearn.cs
@@ -81,6 +81,8 @@ public enum MidiTargetKind
// >= 0 = an Audio Effect Rack device at that index, <= MidiTarget.MidiRackBase (−1000) − mi =
// the MIDI Effect Rack at MIDI effect index mi. ParamIndex = chain (or unused).
RackVolume, RackChainGain, RackChainMute, RackChainSolo,
+ // Cue (specs/089): a track's Cue toggle and the Cue mix's level. Appended: saved as ints.
+ TrackCue, CueVolume,
}
/// <summary>Stable identity of a mappable control. TrackId is a runtime engine id;
@@ -94,6 +96,8 @@ public readonly record struct MidiTarget(MidiTargetKind Kind, int TrackId, int D
public static MidiTarget TrackPan(int track) => new(MidiTargetKind.TrackPan, track, -1, -1);
public static MidiTarget TrackMute(int track) => new(MidiTargetKind.TrackMute, track, -1, -1);
public static MidiTarget TrackSolo(int track) => new(MidiTargetKind.TrackSolo, track, -1, -1);
+ public static MidiTarget TrackCue(int track) => new(MidiTargetKind.TrackCue, track, -1, -1);
+ public static readonly MidiTarget CueVolume = new(MidiTargetKind.CueVolume, -1, -1, -1);
public static readonly MidiTarget MasterVolume = new(MidiTargetKind.MasterVolume, -1, -1, -1);
public static readonly MidiTarget TransportPlay = new(MidiTargetKind.TransportPlay, -1, -1, -1);
public static readonly MidiTarget TransportStop = new(MidiTargetKind.TransportStop, -1, -1, -1);
@@ -107,7 +111,7 @@ public readonly record struct MidiTarget(MidiTargetKind Kind, int TrackId, int D
public static MidiTarget RackChainSolo(int track, int di, int chain) => new(MidiTargetKind.RackChainSolo, track, di, chain);
/// <summary>True for on/off targets (buttons) — applied as a trigger, not a value.</summary>
- public bool IsButton => Kind is MidiTargetKind.TrackMute or MidiTargetKind.TrackSolo
+ public bool IsButton => Kind is MidiTargetKind.TrackMute or MidiTargetKind.TrackSolo or MidiTargetKind.TrackCue
or MidiTargetKind.TransportPlay or MidiTargetKind.TransportStop or MidiTargetKind.TransportRecord
or MidiTargetKind.RackChainMute or MidiTargetKind.RackChainSolo;
}
diff --git a/src/managed/Nota.App/MidiLearnService.cs b/src/managed/Nota.App/MidiLearnService.cs
index 853e7250..aa6c8612 100644
--- a/src/managed/Nota.App/MidiLearnService.cs
+++ b/src/managed/Nota.App/MidiLearnService.cs
@@ -369,6 +369,9 @@ public sealed class MidiLearnService
case MidiTargetKind.MasterVolume:
MixTouch(MixTarget.Master, () => _engine.SetMasterVolume((float)(outv * VolumeMax)));
break;
+ case MidiTargetKind.CueVolume: // a listening level: no undo step (specs/089)
+ _engine.CueVolume = (float)(outv * VolumeMax); // the Cue fader's travel
+ break;
case MidiTargetKind.TrackPan:
MixTouch(MixTarget.Pan(t.TrackId), () => _engine.SetTrackPan(t.TrackId, (float)(outv * 2.0 - 1.0)));
break;
@@ -423,6 +426,10 @@ public sealed class MidiLearnService
case MidiTargetKind.TransportRecord: _engine.SetRecording(!_engine.IsRecording); break;
case MidiTargetKind.TrackMute: _engine.SetTrackMute(t.TrackId, !TrackFlag(t.TrackId, mute: true)); break;
case MidiTargetKind.TrackSolo: _engine.SetTrackSolo(t.TrackId, !TrackFlag(t.TrackId, mute: false)); break;
+ case MidiTargetKind.TrackCue:
+ _engine.SetTrackCue(t.TrackId, !_engine.GetTrackCue(t.TrackId));
+ CueKey.NotifyChanged();
+ break;
case MidiTargetKind.RackChainMute when t.DeviceIndex <= MidiTarget.MidiRackBase:
{
int mi = MidiTarget.MidiRackBase - t.DeviceIndex;
@@ -563,6 +570,7 @@ public sealed class MidiLearnService
private static bool TrackScoped(MidiTargetKind k) => k
is MidiTargetKind.DeviceParam or MidiTargetKind.PluginParam or MidiTargetKind.MidiDeviceParam
or MidiTargetKind.TrackVolume or MidiTargetKind.TrackPan or MidiTargetKind.TrackMute or MidiTargetKind.TrackSolo
+ or MidiTargetKind.TrackCue
or MidiTargetKind.RackVolume or MidiTargetKind.RackChainGain
or MidiTargetKind.RackChainMute or MidiTargetKind.RackChainSolo;
diff --git a/src/managed/Nota.App/MixerView.Compact.cs b/src/managed/Nota.App/MixerView.Compact.cs
index 87f07805..7431d7b1 100644
--- a/src/managed/Nota.App/MixerView.Compact.cs
+++ b/src/managed/Nota.App/MixerView.Compact.cs
@@ -65,7 +65,8 @@ public sealed partial class MixerView
{
var col = new StackPanel();
col.Children.Add(Header(Loc.T("common.master"), NotaPalette.Master, MasterBg));
- var io = CompactIoRow(Loc.T("mixer.sum_bus") + " " + Loc.T("mixer.output"));
+ _mainOutputShown = MainOutputText(); // specs/089
+ var io = CompactIoRow(Loc.T("mixer.sum_bus") + " " + _mainOutputShown);
io.IsVisible = IoShown;
_ioSections.Add(io);
col.Children.Add(io);
@@ -200,6 +201,7 @@ public sealed partial class MixerView
MidiLearn.Bind(solo, MidiTarget.TrackSolo(id), "Solo");
stack.Children.Add(Wide(mute));
stack.Children.Add(Wide(solo));
+ if (_builtCueShown) stack.Children.Add(Wide(CueToggle(id, out sync.Cue)));
if (!isReturn) stack.Children.Add(Wide(ArmToggle(ti.Armed != 0, (v, additive) => TrackArming.Set(_engine, id, v, additive), out sync.Arm)));
if (ti.IsGroup) { stack.Children.Add(Wide(LinkKey(id, out var linkSync))); sync.Link = linkSync; } // group Link (specs/076)
else sync.Link = null;
diff --git a/src/managed/Nota.App/MixerView.Cue.cs b/src/managed/Nota.App/MixerView.Cue.cs
new file mode 100644
index 00000000..c04cd6c4
--- /dev/null
+++ b/src/managed/Nota.App/MixerView.Cue.cs
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The Cue strip and the tracks' Cue keys (specs/089, #483). Cue is the performer's private
+// mix on its own output pair: tracks put in Cue are heard there before their faders, mute
+// and solo, at the Cue level, together with the click when it is sent there. The strip sits
+// next to Master and says what feeds it — the output pair, the cued tracks, the click — and
+// when its pair isn't on this device. It shows only while a Cue output is set (or a track is
+// in Cue), so a stereo laptop's mixer looks as it always did.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Nota.Application;
+using Nota.Application.Localization;
+
+namespace Nota.App;
+
+public sealed partial class MixerView
+{
+ private const int CueMeterId = int.MinValue; // _meters key of the Cue meter
+
+ private bool _builtCueShown; // the strips carry Cue keys and the Cue strip
+ private TextBlock? _cueSources, _cueOutput;
+ private VFader? _cueFader;
+ private MeterFader? _cueMeterFader;
+ private DragNumber? _cueDb;
+ private string _cueSourcesShown = "", _cueOutputShown = "";
+
+ private bool CueShown() => CueKey.Shown(_engine);
+
+ private string _mainOutputShown = "";
+
+ // Master's output line: "Output" on 1/2 as always; the pair when Main moved, and a
+ // fallback note when Main's pair isn't on this device (FR-015).
+ private string MainOutputText()
+ {
+ if (_engine.GetOutputRoutingState().HasFlag(OutputRoutingState.MainFellBack))
+ return Loc.T("mixer.main_fallback");
+ var s = OutputSetupAccess.Current(_engine);
+ return s.MainFirst == 1 && s.MainWidth == 2 ? Loc.T("mixer.output")
+ : "→ " + PreferencesWindow.OutputPickLabel(_engine, s.MainFirst, s.MainWidth);
+ }
+
+ private Border CueToggle(int id, out Action<bool> sync)
+ => CueKey.Create(_engine, id, 20, 17, NotaRadius.Field, out sync);
+
+ // "Out 3/4 · Phones", or why it doesn't play.
+ private string CueOutputText()
+ {
+ var s = OutputSetupAccess.Current(_engine);
+ if (s.CueFirst is not int first) return Loc.T("mixer.cue_no_output");
+ string pair = PreferencesWindow.OutputPickLabel(_engine, first, s.CueWidth);
+ return _engine.GetOutputRoutingState().HasFlag(OutputRoutingState.CueUnavailable)
+ ? Loc.F("mixer.cue_not_on_device", pair) : pair;
+ }
+
+ // The cued tracks by name, "3 tracks" past two, and the click when it goes here.
+ private string CueSourcesText()
+ {
+ var names = new List<string>();
+ for (int i = 0; i < _engine.TrackCount; i++)
+ if (_engine.TryGetTrackInfo(i, out var ti) && _engine.GetTrackCue(ti.Id)) names.Add(TrackNames.Of(_engine, ti));
+ string tracks = names.Count switch
+ {
+ 0 => Loc.T("mixer.cue_no_tracks"),
+ <= 2 => string.Join(", ", names),
+ _ => Loc.F("mixer.cue_tracks_count", names.Count),
+ };
+ var click = OutputSetupAccess.Current(_engine).Click;
+ return click == ClickDestination.Main ? tracks : Loc.F("mixer.cue_with_click", tracks);
+ }
+
+ private Border CueStrip()
+ {
+ var col = new StackPanel();
+ col.Children.Add(Header(Loc.T("mixer.cue"), NotaPalette.Accent, MasterBg));
+ // Where it goes and what feeds it, where the strips show their I/O.
+ _cueOutputShown = CueOutputText();
+ _cueSourcesShown = CueSourcesText();
+ _cueOutput = new TextBlock { Text = _cueOutputShown, FontSize = 8, Foreground = TextTertiary, TextTrimming = TextTrimming.CharacterEllipsis };
+ _cueSources = new TextBlock { Text = _cueSourcesShown, FontSize = 8, Foreground = TextTertiary, TextTrimming = TextTrimming.CharacterEllipsis };
+ PaintCueOutput();
+ var io = new Border
+ {
+ Height = 34, BorderBrush = BorderInner, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(7, 4),
+ Child = new StackPanel { Spacing = 2, Children = { _cueOutput, _cueSources } },
+ };
+ io.IsVisible = IoShown;
+ _ioSections.Add(io);
+ col.Children.Add(io);
+ var sends = Blank(SendsH);
+ sends.IsVisible = SendsShown;
+ _sendSections.Add(sends);
+ col.Children.Add(sends);
+ col.Children.Add(Blank(38));
+
+ // The Cue level: a listening level, so no undo step and no automation (specs/089).
+ float vol = _engine.CueVolume;
+ var fader = new VFader(vol, NotaPalette.Accent);
+ var dbNum = DbField(vol);
+ ToolTip.SetTip(dbNum, Loc.T("mixer.cue_level_tip"));
+ fader.ValueChanged += v => { _engine.CueVolume = (float)v; dbNum.Value = LinToDb(v); };
+ dbNum.ValueChanged += d => { double v = DbToLin(d); _engine.CueVolume = (float)v; fader.SetValueExternal(v); };
+ MidiLearn.Bind(fader, MidiTarget.CueVolume, Loc.T("mixer.cue_level"));
+ ValueEntry.Attach(fader, fader.EntryField(Loc.T("mixer.cue_level"), v => NotaNum.GainDb(v, signed: true), 1.0));
+ _cueFader = fader;
+ _cueDb = dbNum;
+ var meter = new MeterBar();
+ _meters.Add((CueMeterId, meter, meter.Push));
+ var grid = new Grid { Height = _faderH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(7, 8) };
+ grid.Children.Add(fader);
+ Grid.SetColumn(meter, 1);
+ meter.Margin = new Thickness(4, 0, 0, 0);
+ grid.Children.Add(meter);
+ _faderGrids.Add(grid);
+ col.Children.Add(grid);
+ col.Children.Add(dbNum);
+ col.Children.Add(new Border { Height = 28, BorderBrush = BorderInner, BorderThickness = new Thickness(0, 1, 0, 0) });
+
+ return new Border
+ {
+ Width = 120, Background = MasterBg, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Group, ClipToBounds = true, Child = col,
+ };
+ }
+
+ private Border CompactCueStrip()
+ {
+ var col = new StackPanel();
+ col.Children.Add(Header(Loc.T("mixer.cue"), NotaPalette.Accent, MasterBg));
+ _cueOutputShown = CueOutputText();
+ _cueSourcesShown = CueSourcesText();
+ _cueOutput = new TextBlock { Text = _cueOutputShown, FontSize = 8, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ _cueSources = null;
+ PaintCueOutput();
+ var io = new Border { Height = IoH, BorderBrush = BorderInner, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(CompactInset, 0), Child = _cueOutput };
+ ToolTip.SetTip(io, _cueSourcesShown);
+ io.IsVisible = IoShown;
+ _ioSections.Add(io);
+ col.Children.Add(io);
+ var sends = EmptySlot(SendsH, top: false);
+ sends.IsVisible = SendsShown;
+ _sendSections.Add(sends);
+ col.Children.Add(sends);
+ col.Children.Add(EmptySlot(PanH, top: false));
+
+ float vol = _engine.CueVolume;
+ var fader = new MeterFader(vol) { HorizontalAlignment = HorizontalAlignment.Center };
+ var dbNum = DbField(vol);
+ fader.ValueChanged += v => { _engine.CueVolume = (float)v; dbNum.Value = LinToDb(v); };
+ dbNum.ValueChanged += d => { double v = DbToLin(d); _engine.CueVolume = (float)v; fader.SetValueExternal(v); };
+ MidiLearn.Bind(fader, MidiTarget.CueVolume, Loc.T("mixer.cue_level"));
+ ValueEntry.Attach(fader, fader.EntryField(Loc.T("mixer.cue_level"), v => NotaNum.GainDb(v, signed: true), 1.0));
+ _meters.Add((CueMeterId, fader, fader.Push));
+ _cueMeterFader = fader;
+ _cueDb = dbNum;
+ var host = new Border { Height = _faderH, Margin = new Thickness(CompactInset, 4), Child = fader };
+ _faderGrids.Add(host);
+ col.Children.Add(host);
+ col.Children.Add(dbNum);
+ col.Children.Add(EmptySlot(ButtonsH, top: true));
+ return new Border
+ {
+ Width = CompactMetrics.Width, Background = MasterBg, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Group, ClipToBounds = true, Child = col,
+ };
+ }
+
+ // The output line: the pair, or a warning when it isn't on this device (FR-014: Cue then
+ // stays silent rather than moving to Main). The full text is the tooltip too.
+ private void PaintCueOutput()
+ {
+ if (_cueOutput is not { } o) return;
+ o.Text = _cueOutputShown;
+ bool missing = _engine.GetOutputRoutingState().HasFlag(OutputRoutingState.CueUnavailable);
+ o.Foreground = missing ? NotaPalette.Warning : TextTertiary;
+ ToolTip.SetTip(o, missing ? Loc.T("mixer.cue_unavailable_tip") : Loc.T("mixer.cue_output_tip"));
+ }
+
+ // UI tick: the strip follows the Cue level, the cued tracks and the device as they change
+ // elsewhere (a MIDI controller, a track header, a device unplugged).
+ private void UpdateCue()
+ {
+ if (CueShown() != _builtCueShown || MainOutputText() != _mainOutputShown) { Refresh(); return; }
+ if (!_builtCueShown) return;
+ string output = CueOutputText(), sources = CueSourcesText();
+ if (output != _cueOutputShown) { _cueOutputShown = output; PaintCueOutput(); }
+ if (sources != _cueSourcesShown)
+ {
+ _cueSourcesShown = sources;
+ if (_cueSources is { } s) s.Text = sources;
+ else if (_cueOutput?.Parent is Control io) ToolTip.SetTip(io, sources);
+ }
+ double v = _engine.CueVolume;
+ if (_cueFader is { Dragging: false } f && Math.Abs(f.Value - v) > 1e-3) { f.SetValueExternal(v); if (_cueDb is { } db) db.Value = LinToDb(v); }
+ if (_cueMeterFader is { Dragging: false } mf && Math.Abs(mf.Value - v) > 1e-3) { mf.SetValueExternal(v); if (_cueDb is { } db) db.Value = LinToDb(v); }
+ }
+}
diff --git a/src/managed/Nota.App/MixerView.cs b/src/managed/Nota.App/MixerView.cs
index ca09bdb3..f1c98a4f 100644
--- a/src/managed/Nota.App/MixerView.cs
+++ b/src/managed/Nota.App/MixerView.cs
@@ -102,6 +102,7 @@ public sealed partial class MixerView : UserControl
public PanKnob? Pan;
public PanBar? PanBar; // compact strips
public Action<bool>? Mute, Solo, Arm, Link; // Link: a group's Link key (specs/076)
+ public Action<bool>? Cue; // the Cue key (specs/089)
}
private readonly Dictionary<int, StripSync> _syncs = new();
private StripSync SyncOf(int id) => _syncs.TryGetValue(id, out var s) ? s : _syncs[id] = new StripSync();
@@ -307,6 +308,8 @@ public sealed partial class MixerView : UserControl
_strips.Clear();
_stripById.Clear();
_masterFader = null; _masterMeterFader = null;
+ _cueFader = null; _cueMeterFader = null; _cueDb = null; _cueOutput = _cueSources = null;
+ _builtCueShown = CueShown(); // Cue keys and the Cue strip (specs/089)
int returns = _engine.ReturnTrackCount;
int n = _engine.TrackCount;
// As in the arrangement: the tracks in its hierarchical order (each group, then its
@@ -323,6 +326,7 @@ public sealed partial class MixerView : UserControl
foreach (int i in ArrangementView.DisplayOrder(_engine))
if (_engine.TryGetTrackInfo(i, out var ti) && ti.IsReturn) AddStrip(ti, 0, -1, returns);
_row.Children.Add(_compact ? CompactMasterStrip() : MasterStrip());
+ if (_builtCueShown) _row.Children.Add(_compact ? CompactCueStrip() : CueStrip());
CollectDescendants(rows);
_clipLatched.RemoveWhere(id => !_stripById.TryGetValue(id, out var g) || !g.IsGroup); // a group that is gone
_row.Margin = new Thickness(10, 10 + BandsH, 10, 10);
@@ -505,9 +509,11 @@ public sealed partial class MixerView : UserControl
foreach (var (id, ctl, push) in _meters)
{
if (!ctl.IsEffectivelyVisible) continue; // a folded strip reads nothing
- if (id < 0) push(_engine.MasterMeter());
+ if (id == CueMeterId) push(_engine.CueMeter());
+ else if (id < 0) push(_engine.MasterMeter());
else if (_engine.TryGetTrackMeter(id, out var m)) push(m);
}
+ UpdateCue();
// Follow master volume changes made elsewhere (MST, Master row, Remote, project load).
if (GetMasterVolume is { } get && _masterDb is { } db)
{
@@ -552,6 +558,7 @@ public sealed partial class MixerView : UserControl
s.Mute?.Invoke(ti.Muted != 0);
s.Solo?.Invoke(ti.Soloed != 0);
s.Arm?.Invoke(ti.Armed != 0);
+ s.Cue?.Invoke(_engine.GetTrackCue(ti.Id));
if (ti.IsGroup) s.Link?.Invoke(_engine.GetTrackEditLink(ti.Id));
}
}
@@ -599,7 +606,8 @@ public sealed partial class MixerView : UserControl
{
var col = new StackPanel();
col.Children.Add(Header(Loc.T("common.master"), NotaPalette.Master, MasterBg));
- var ioRow = IoRow(Loc.T("mixer.sum_bus"), Loc.T("mixer.output"));
+ _mainOutputShown = MainOutputText(); // specs/089: the pair Main plays on
+ var ioRow = IoRow(Loc.T("mixer.sum_bus"), _mainOutputShown);
ioRow.IsVisible = IoShown;
_ioSections.Add(ioRow);
col.Children.Add(ioRow);
@@ -1113,6 +1121,7 @@ public sealed partial class MixerView : UserControl
MidiLearn.Bind(solo, MidiTarget.TrackSolo(id), "Solo");
row.Children.Add(mute);
row.Children.Add(solo);
+ if (_builtCueShown) row.Children.Add(CueToggle(id, out sync.Cue));
if (!isReturn) row.Children.Add(ArmToggle(ti.Armed != 0, (v, additive) => TrackArming.Set(_engine, id, v, additive), out sync.Arm));
if (ti.IsGroup) { row.Children.Add(LinkKey(id, out var linkSync)); sync.Link = linkSync; } // group Link (specs/076)
else sync.Link = null;
diff --git a/src/managed/Nota.App/OutputSetupAccess.cs b/src/managed/Nota.App/OutputSetupAccess.cs
new file mode 100644
index 00000000..1cbff92a
--- /dev/null
+++ b/src/managed/Nota.App/OutputSetupAccess.cs
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The app's side of the output setup (specs/089): the playback device's entry in the
+// settings, stored back with a save and pushed to the engine — Main and Cue pairs, and where
+// the click goes. Pushed at start, after every audio restart (the device may be another one
+// now, with its own setup) and after every edit. Outside the running app there is no setup:
+// Main on 1/2, no Cue, as before this feature.
+
+using Nota.Application;
+
+namespace Nota.App;
+
+internal static class OutputSetupAccess
+{
+ private static ISettingsService? Settings
+ => App.Services?.GetService(typeof(ISettingsService)) as ISettingsService;
+
+ private static string? _key;
+
+ // The backend that actually runs: after a failed ASIO start Nota plays on WASAPI's
+ // default device, whose setup must not be the ASIO driver's (or overwrite it).
+ public static string KeyOf(IAudioEngine engine)
+ => _key ??= OutputSetups.KeyOf(engine.ActiveAudioSystem, engine.EffectiveOutputUid(), engine.AsioDriver);
+
+ /// <summary>The setup of the device the engine plays on now (defaults when never set up;
+ /// under ASIO Main starts on the output pair chosen before, FR-005).</summary>
+ public static OutputSetup Current(IAudioEngine engine)
+ {
+ if (Settings is { } s && s.Current.OutputSetups.TryGetValue(KeyOf(engine), out var v)) return v;
+ return OutputSetups.Default(engine.ActiveAudioSystem == AudioSystem.Asio ? engine.AsioPair(false) : 0);
+ }
+
+ public static void Store(IAudioEngine engine, OutputSetup setup)
+ {
+ if (Settings is { } s)
+ {
+ s.Current.OutputSetups[KeyOf(engine)] = setup;
+ s.Save();
+ }
+ Send(engine, setup);
+ OutputSetups.NotifyChanged();
+ }
+
+ /// <summary>Find the device's key again and tell the engine its setup.</summary>
+ public static void Push(IAudioEngine engine)
+ {
+ _key = null;
+ Send(engine, Current(engine));
+ OutputSetups.NotifyChanged();
+ }
+
+ private static void Send(IAudioEngine engine, OutputSetup s)
+ {
+ int cueFirst = s.CueFirst is int c ? c - 1 : -1;
+ if (!engine.SetOutputRouting(s.MainFirst - 1, s.MainWidth, cueFirst, s.CueWidth))
+ engine.SetOutputRouting(0, 2, -1, 2); // a hand-edited settings file: back to the default
+ engine.ClickDestination = s.HasCue ? s.Click : ClickDestination.Main;
+ engine.SetClickVolume(OutputSetups.ClickGain(s));
+ }
+}
diff --git a/src/managed/Nota.App/PreferencesWindow.AudioIo.cs b/src/managed/Nota.App/PreferencesWindow.AudioIo.cs
index e327adfb..1e6a9000 100644
--- a/src/managed/Nota.App/PreferencesWindow.AudioIo.cs
+++ b/src/managed/Nota.App/PreferencesWindow.AudioIo.cs
@@ -7,7 +7,7 @@
// user's; then the stereo pairs, which can be named too. Track input pickers list only
// switched-on inputs, under these names. Kept per device in the app settings
// (InputSetupAccess); edits apply at once. Under ASIO one driver is both sides: it is picked
-// on the Audio page, and these pages pick its output / input pair.
+// on the Audio page; Outputs picks its Main and Cue pairs (specs/089), Inputs its input pair.
using System;
using System.Collections.Generic;
@@ -33,9 +33,7 @@ public sealed partial class PreferencesWindow
var rows = new List<Control>();
if (IsAsio(engine))
{
- rows.Add(AsioDeviceRow(engine));
- if (engine.ActiveAudioSystem == AudioSystem.Asio)
- rows.Add(Row(Loc.T("common.output"), PairCombo(engine, input: false, engine.AsioChannels(false))));
+ rows.Add(AsioDeviceRow(engine)); // the output pair is Main, below (specs/089)
}
else
{
@@ -46,6 +44,7 @@ public sealed partial class PreferencesWindow
}
var body = Sections(
Section(Loc.T("preferences.audio_device"), 6, rows.ToArray()),
+ OutputsHost(engine), // Main and Cue pairs, the click (specs/089)
Section(Loc.T("preferences.test"), 8, TestToneRow()));
_loading = false;
return body;
diff --git a/src/managed/Nota.App/PreferencesWindow.Outputs.cs b/src/managed/Nota.App/PreferencesWindow.Outputs.cs
new file mode 100644
index 00000000..cfd78bd8
--- /dev/null
+++ b/src/managed/Nota.App/PreferencesWindow.Outputs.cs
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Settings → Outputs → Output pairs (specs/089, #483): which output pair of the playback device
+// carries Main (what the audience hears) and which carries the private Cue mix, and where the
+// metronome click goes. Kept per device in the app settings (OutputSetupAccess); edits apply
+// at once, without restarting the device.
+
+using System;
+using System.Collections.Generic;
+using Avalonia.Controls;
+using Nota.Application;
+using Nota.Application.Localization;
+
+namespace Nota.App;
+
+public sealed partial class PreferencesWindow
+{
+ // Click level steps in dB; the first is "off".
+ private static readonly double[] ClickLevelSteps = { OutputSetups.ClickDbMin, -18, -12, -9, -6, -3, 0, 3, 6 };
+
+ private ContentControl? _outputsHost;
+
+ private Control OutputsHost(IAudioEngine engine)
+ {
+ _outputsHost = new ContentControl { Content = OutputsSection(engine) };
+ return _outputsHost;
+ }
+
+ private void RebuildOutputs(IAudioEngine engine)
+ {
+ if (_outputsHost is { } host) host.Content = OutputsSection(engine);
+ }
+
+ // One pick a picker offers: 1-based first channel and width.
+ private readonly record struct OutPick(int First, int Width);
+
+ // The device's outputs as pairs (1/2, 3/4 …) and a lone last output.
+ private static List<OutPick> OutputPicks(int count)
+ {
+ var list = new List<OutPick>();
+ for (int c = 1; c + 1 <= count; c += 2) list.Add(new OutPick(c, 2));
+ if (count % 2 == 1) list.Add(new OutPick(count, 1));
+ return list;
+ }
+
+ // "Out 3/4 · Phones" — the device's name for the first channel when it gives one.
+ internal static string OutputPickLabel(IAudioEngine engine, int first, int width)
+ {
+ string pair = width == 2 ? Loc.F("preferences.outputs_pair", first, first + 1) : Loc.F("preferences.outputs_single", first);
+ string name = first - 1 < engine.AudioOutputChannelCount() ? engine.AudioOutputChannelName(first - 1).Trim() : "";
+ return name.Length > 0 ? $"{pair} · {name}" : pair;
+ }
+
+ private Control OutputsSection(IAudioEngine engine)
+ {
+ int count = engine.AudioOutputChannelCount();
+ var setup = OutputSetupAccess.Current(engine);
+ var state = engine.GetOutputRoutingState();
+ if (count <= 0)
+ return Section(Loc.T("preferences.outputs_pairs"), 8, Caption(Loc.T("preferences.outputs_no_device")));
+
+ var picks = OutputPicks(count);
+ var rows = new List<Control>();
+
+ // Main: every pick of the device; a saved pick the device lacks stays listed as missing.
+ var main = Combo(280);
+ var mainPicks = new List<OutPick>(picks);
+ bool mainMissing = !mainPicks.Contains(new OutPick(setup.MainFirst, setup.MainWidth));
+ if (mainMissing) mainPicks.Insert(0, new OutPick(setup.MainFirst, setup.MainWidth));
+ foreach (var p in mainPicks)
+ {
+ bool missing = mainMissing && p == mainPicks[0];
+ bool isCue = setup.CueFirst is int cf && OutputSetups.Overlaps(p.First, p.Width, cf, setup.CueWidth);
+ main.Items.Add(new ComboBoxItem
+ {
+ Content = missing ? Loc.F("preferences.outputs_missing", OutputPickLabel(engine, p.First, p.Width)) : OutputPickLabel(engine, p.First, p.Width),
+ IsEnabled = !isCue && !missing,
+ });
+ }
+ main.SelectedIndex = mainPicks.IndexOf(new OutPick(setup.MainFirst, setup.MainWidth));
+ main.SelectionChanged += (_, _) =>
+ {
+ int i = main.SelectedIndex;
+ if (_loading || i < 0 || i >= mainPicks.Count) return;
+ var p = mainPicks[i];
+ OutputSetupAccess.Store(engine, OutputSetups.WithMain(OutputSetupAccess.Current(engine), p.First, p.Width));
+ RebuildOutputs(engine);
+ };
+ rows.Add(Row(Loc.T("preferences.outputs_main"), main));
+ if (state.HasFlag(OutputRoutingState.MainFellBack))
+ rows.Add(Row("", Caption(Loc.T("preferences.outputs_main_fallback"))));
+
+ // Cue: "No cue output" first; Main's pair can't be picked (FR-004).
+ if (count <= 2)
+ {
+ rows.Add(Row(Loc.T("preferences.outputs_cue"), Caption(Loc.F("preferences.outputs_cue_two_outputs", count), muted: true)));
+ }
+ else
+ {
+ var cue = Combo(280);
+ var cuePicks = new List<OutPick?> { null };
+ cue.Items.Add(Loc.T("preferences.outputs_no_cue"));
+ bool cueMissing = setup.CueFirst is int sf && !picks.Contains(new OutPick(sf, setup.CueWidth));
+ if (cueMissing)
+ {
+ var p = new OutPick(setup.CueFirst!.Value, setup.CueWidth);
+ cuePicks.Add(p);
+ cue.Items.Add(new ComboBoxItem { Content = Loc.F("preferences.outputs_missing", OutputPickLabel(engine, p.First, p.Width)), IsEnabled = false });
+ }
+ foreach (var p in picks)
+ {
+ cuePicks.Add(p);
+ cue.Items.Add(new ComboBoxItem
+ {
+ Content = OutputPickLabel(engine, p.First, p.Width),
+ IsEnabled = !OutputSetups.Overlaps(p.First, p.Width, setup.MainFirst, setup.MainWidth),
+ });
+ }
+ cue.SelectedIndex = setup.CueFirst is int f ? cuePicks.IndexOf(new OutPick(f, setup.CueWidth)) : 0;
+ cue.SelectionChanged += (_, _) =>
+ {
+ int i = cue.SelectedIndex;
+ if (_loading || i < 0 || i >= cuePicks.Count) return;
+ var p = cuePicks[i];
+ OutputSetupAccess.Store(engine, OutputSetups.WithCue(OutputSetupAccess.Current(engine), p?.First, p?.Width ?? 2));
+ RebuildOutputs(engine);
+ };
+ rows.Add(Row(Loc.T("preferences.outputs_cue"), cue));
+ if (state.HasFlag(OutputRoutingState.CueUnavailable))
+ rows.Add(Row("", Caption(Loc.T("preferences.outputs_cue_unavailable"))));
+ }
+
+ // Click: Main / Cue / Main + Cue (only Main without a Cue output), and its level.
+ var click = Combo(150);
+ click.Items.Add(Loc.T("preferences.outputs_click_main"));
+ click.Items.Add(new ComboBoxItem { Content = Loc.T("preferences.outputs_click_cue"), IsEnabled = setup.HasCue });
+ click.Items.Add(new ComboBoxItem { Content = Loc.T("preferences.outputs_click_both"), IsEnabled = setup.HasCue });
+ click.SelectedIndex = (int)setup.Click;
+ click.SelectionChanged += (_, _) =>
+ {
+ if (_loading || click.SelectedIndex < 0) return;
+ var cur = OutputSetupAccess.Current(engine);
+ OutputSetupAccess.Store(engine, OutputSetups.WithClick(cur, (ClickDestination)click.SelectedIndex, cur.ClickDb));
+ };
+ rows.Add(Row(Loc.T("preferences.outputs_click"), click));
+
+ var level = Combo(150);
+ foreach (var db in ClickLevelSteps)
+ level.Items.Add(db <= OutputSetups.ClickDbMin ? Loc.T("preferences.outputs_click_off") : NotaNum.Unit(db, "+0;−0;0", "dB"));
+ int li = Array.FindIndex(ClickLevelSteps, d => Math.Abs(d - setup.ClickDb) < 0.01);
+ level.SelectedIndex = li >= 0 ? li : Array.IndexOf(ClickLevelSteps, 0.0);
+ level.SelectionChanged += (_, _) =>
+ {
+ int i = level.SelectedIndex;
+ if (_loading || i < 0) return;
+ var cur = OutputSetupAccess.Current(engine);
+ OutputSetupAccess.Store(engine, OutputSetups.WithClick(cur, cur.Click, ClickLevelSteps[i]));
+ };
+ rows.Add(Row(Loc.T("preferences.outputs_click_level"), level));
+ rows.Add(Row("", Caption(Loc.T("preferences.outputs_hint"), muted: true)));
+ return Section(Loc.T("preferences.outputs_pairs"), 6, rows.ToArray());
+ }
+}
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index c0c77d34..4882da14 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -624,6 +624,7 @@ public sealed partial class PreferencesWindow : NotaWindow
if (_loading || _main is null) return;
_main.ApplyAudioSettings(); // re-reads the device's input setup (AudioApplied)
RebuildInputs(_main.Engine); // ...its own inputs and names on the page (specs/086)
+ RebuildOutputs(_main.Engine); // ...and its own output pairs (specs/089)
UpdateLatency();
}
diff --git a/src/managed/Nota.App/SessionView.Mixer.cs b/src/managed/Nota.App/SessionView.Mixer.cs
index f01aebd8..c311ffa7 100644
--- a/src/managed/Nota.App/SessionView.Mixer.cs
+++ b/src/managed/Nota.App/SessionView.Mixer.cs
@@ -140,6 +140,7 @@ public sealed partial class SessionView
Action meter = () => { };
var follow = new List<Action<NotaTrackInfo>>();
+ bool cueShown = CueKey.Shown(_engine); // Cue keys (specs/089)
if (_showMixer)
{
Control panRow;
@@ -190,6 +191,13 @@ public sealed partial class SessionView
btns.Children.Add(MixToggle("M", ti.Muted != 0, false, (v, _) => _engine.SetTrackMute(id, v), out var syncMute));
btns.Children.Add(MixToggle("S", ti.Soloed != 0, false, (v, _) => _engine.SetTrackSolo(id, v), out var syncSolo));
follow.Add(t => { syncMute(t.Muted != 0); syncSolo(t.Soloed != 0); });
+ if (cueShown) // Cue (specs/089)
+ {
+ var cue = CueKey.Create(_engine, id, 0, 20, NotaRadius.Cell, out var syncCue);
+ cue.Margin = new Thickness(1.5, 0);
+ btns.Children.Add(cue);
+ follow.Add(t => syncCue(_engine.GetTrackCue(t.Id)));
+ }
if (c.Kind == ColKind.Track)
{
btns.Children.Add(MixToggle(null, ti.Armed != 0, true, (v, additive) =>
diff --git a/src/managed/Nota.App/TrackInspectorView.cs b/src/managed/Nota.App/TrackInspectorView.cs
index 24c4e95d..ecd4918d 100644
--- a/src/managed/Nota.App/TrackInspectorView.cs
+++ b/src/managed/Nota.App/TrackInspectorView.cs
@@ -56,6 +56,9 @@ internal sealed class TrackInspectorView : UserControl
Rebuild();
}
+ /// <summary>Rebuilds the shown track's page (the Cue key appears or goes — specs/089).</summary>
+ public void Reload() => Rebuild();
+
/// <summary>Shows this track (≤ 0: none).</summary>
public void Show(int trackId)
{
@@ -187,6 +190,9 @@ internal sealed class TrackInspectorView : UserControl
if (audio || ti.IsInstrument)
state.Children.Add(Toggle(Loc.T("track_inspector.arm"), ti.Armed != 0, NotaPalette.Record, TrackArming.Tip,
(on, mods) => { TrackArming.Set(_engine, id, on, mods); Edited(); }));
+ if (CueKey.Shown(_engine)) // Cue (specs/089)
+ state.Children.Add(CueKey.Create(_engine, id, 0, 24, NotaRadius.Field, out _, Edited));
+ state.Columns = state.Children.Count;
s.Children.Add(state);
if (audio) s.Children.Add(Section(Loc.T("common.input"), InputRows(id)));
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 6816c0b1..35a2eb67 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -67,6 +67,15 @@ public interface IAudioEngine : IDisposable
void SetTrackPan(int trackId, float pan);
void SetTrackMute(int trackId, bool mute);
void SetTrackSolo(int trackId, bool solo);
+ /// <summary>Cue (specs/089): the track's signal after its devices, before its fader, pan,
+ /// mute and solo, also goes to the private Cue mix. Any number of tracks.</summary>
+ void SetTrackCue(int trackId, bool on);
+ bool GetTrackCue(int trackId);
+ /// <summary>The Cue mix's level, linear 0–2 (+6 dB). Never changes Main.</summary>
+ float CueVolume { get; set; }
+ /// <summary>Where the metronome and count-in clicks go, and their level (linear 0–2).</summary>
+ ClickDestination ClickDestination { get; set; }
+ void SetClickVolume(float gain);
int TrackCount { get; }
int DuplicateTrack(int trackId); // deep copy after the source; new id or -1
int AddTrackLike(int trackId); // empty track with the source's instrument, devices and mix, before the returns; new id or -1
@@ -374,6 +383,16 @@ public interface IAudioEngine : IDisposable
void SetDisabledInputs(int[] channels);
/// <summary>Tests: pretend a capture device with this many inputs is open (0 clears it).</summary>
void SetTestInputDevice(int channels);
+ /// <summary>The playback device's output channels (0 when none is open) and their names
+ /// ("" where the device gives none) — specs/089.</summary>
+ int AudioOutputChannelCount();
+ string AudioOutputChannelName(int index);
+ /// <summary>Where Main (the audience mix) and Cue (the private cue mix) go: 0-based first
+ /// channel and width (1 or 2); cueFirst &lt; 0 = no Cue output. Takes effect at once, no
+ /// device restart. False for a bad width, an odd stereo first or overlapping pairs.</summary>
+ bool SetOutputRouting(int mainFirst, int mainWidth, int cueFirst, int cueWidth);
+ /// <summary>The routing against the open device.</summary>
+ OutputRoutingState GetOutputRoutingState();
/// <summary>Tests: device frames into the capture ring, drained into the running take as poll() would.</summary>
void FeedInputForTest(float[] interleaved, int frames, int channels);
/// <summary>Tests: record <paramref name="frames"/> of <paramref name="channels"/>-wide
@@ -1136,6 +1155,8 @@ public interface IAudioEngine : IDisposable
// --- Level meters (M6-2) -----------------------------------------------
bool TryGetTrackMeter(int trackId, out NotaMeter meter);
NotaMeter MasterMeter();
+ /// <summary>The Cue bus after the Cue level (specs/089).</summary>
+ NotaMeter CueMeter();
// --- MIDI clip notes ---------------------------------------------------
void SetClipNotes(int trackId, int clipIndex, NotaNote[] notes);
@@ -1342,6 +1363,8 @@ public interface IAudioEngine : IDisposable
/// is connected, else the system default ("" when there is none). Per-device input settings
/// key on it, so "System default" and a missing device never share another's (specs/086).</summary>
string EffectiveInputUid();
+ /// <summary>The same for the output device: per-device output setups key on it (specs/089).</summary>
+ string EffectiveOutputUid();
/// <summary>Channel names of the open ASIO driver; empty when ASIO isn't running.</summary>
IReadOnlyList<string> AsioChannels(bool input);
int AsioPair(bool input);
diff --git a/src/managed/Nota.Application/Localization/en.json b/src/managed/Nota.Application/Localization/en.json
index c0733450..23162ace 100644
--- a/src/managed/Nota.Application/Localization/en.json
+++ b/src/managed/Nota.Application/Localization/en.json
@@ -2880,12 +2880,25 @@
"mixer.a_hidden_track_is_soloed": "A hidden track is soloed",
"mixer.balance": "Balance",
"mixer.centre": "Centre",
+ "mixer.cue": "Cue",
+ "mixer.cue_level": "Cue level",
+ "mixer.cue_level_tip": "The level of your private mix. It never changes what the audience hears or what is recorded.",
+ "mixer.cue_no_output": "No cue output",
+ "mixer.cue_no_tracks": "No tracks in Cue",
+ "mixer.cue_not_on_device": "{0} — not on this device",
+ "mixer.cue_output_tip": "Where Cue plays. Choose the pair in Settings → Outputs.",
+ "mixer.cue_tip": "Cue: hear this track in your private mix, before its fader, mute and solo. The audience doesn't hear Cue.",
+ "mixer.cue_tracks_count": "{0} tracks",
+ "mixer.cue_track": "{0} · Cue",
+ "mixer.cue_unavailable_tip": "This device doesn't have the Cue pair. Cue is silent — nothing moves to Main. Choose another pair in Settings → Outputs, or reconnect the interface.",
+ "mixer.cue_with_click": "{0} + click",
"mixer.dock_the_mixer_in_the": "Dock the mixer in the main window",
"mixer.fold_group": "Fold group {0}",
"mixer.group_in": "Group in",
"mixer.groups_keep_a_unity_centre": "Groups keep a unity-centre balance so grouping stays level-transparent",
"mixer.hidden_not_enough_height_click": "Hidden: not enough height · click to show anyway",
"mixer.in_1": "In 1",
+ "mixer.main_fallback": "→ Out 1/2 (fallback)",
"mixer.master": "→ Master",
"mixer.midi_in": "MIDI in",
"mixer.monitor_auto": "Monitor auto",
@@ -3509,6 +3522,24 @@
"preferences.inputs_pairs": "Stereo pairs",
"preferences.inputs_subtitle": "What Nota records from, and what each input is called",
"preferences.inputs_switch_tip": "Off: tracks can't pick this input, and a track set to it records nothing",
+ "preferences.outputs_pairs": "Output pairs",
+ "preferences.outputs_click": "Click",
+ "preferences.outputs_click_both": "Both",
+ "preferences.outputs_click_cue": "Cue",
+ "preferences.outputs_click_level": "Click level",
+ "preferences.outputs_click_main": "Main",
+ "preferences.outputs_click_off": "Off",
+ "preferences.outputs_cue": "Cue",
+ "preferences.outputs_cue_two_outputs": "No cue output — this device has {0} outputs",
+ "preferences.outputs_cue_unavailable": "The Cue pair isn't on this device: Cue is silent and nothing moves to Main.",
+ "preferences.outputs_hint": "Main is what the audience hears. Cue is your private mix: tracks you put in Cue, heard before their faders, and the click if you send it there. Kept for this device.",
+ "preferences.outputs_main": "Main",
+ "preferences.outputs_main_fallback": "Main's pair isn't on this device: Main plays on outputs 1/2.",
+ "preferences.outputs_missing": "{0} — not on this device",
+ "preferences.outputs_no_cue": "No cue output",
+ "preferences.outputs_no_device": "No output device: choose one above, or connect one.",
+ "preferences.outputs_pair": "Out {0}/{1}",
+ "preferences.outputs_single": "Out {0}",
"preferences.insert_a_scene_below_the": "Insert a scene below the selection",
"preferences.insert_silence_push_everything_from": "Insert silence · push everything from the range start right by its length",
"preferences.install": "Install",
diff --git a/src/managed/Nota.Application/OutputSetups.cs b/src/managed/Nota.Application/OutputSetups.cs
new file mode 100644
index 00000000..9e5276a4
--- /dev/null
+++ b/src/managed/Nota.Application/OutputSetups.cs
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The output setup (specs/089, #483): per playback device, which output pair carries Main
+// (the audience mix) and which carries the private Cue mix, and where the metronome click
+// goes. Like the input setup (specs/086) it belongs to the rig, not the project, so it lives
+// in the app settings keyed by audio system and device — a project opened on a laptop with
+// two outputs never routes to an output that isn't there.
+
+using System;
+
+namespace Nota.Application;
+
+/// <summary>Where the metronome and count-in clicks go.</summary>
+public enum ClickDestination { Main = 0, Cue = 1, MainAndCue = 2 }
+
+/// <summary>The engine's routing against the open device (nota_audio_output_routing_state).</summary>
+[Flags]
+public enum OutputRoutingState
+{
+ Ok = 0,
+ /// <summary>Main's pair is not on this device: Main plays on outputs 1/2.</summary>
+ MainFellBack = 1,
+ /// <summary>A Cue pair is set but not on this device: Cue is silent, nothing moves to Main.</summary>
+ CueUnavailable = 2,
+}
+
+/// <summary>One device's output setup. Channels are 1-based, as the user sees them.</summary>
+public sealed class OutputSetup
+{
+ public int MainFirst { get; set; } = 1;
+ public int MainWidth { get; set; } = 2;
+ /// <summary>First channel of the Cue pair; null = no Cue output.</summary>
+ public int? CueFirst { get; set; }
+ public int CueWidth { get; set; } = 2;
+ public ClickDestination Click { get; set; } = ClickDestination.Main;
+ /// <summary>Click level in dB (−60 and below = silent, up to +6).</summary>
+ public double ClickDb { get; set; }
+
+ public bool HasCue => CueFirst is not null;
+
+ public OutputSetup Copy() => new()
+ {
+ MainFirst = MainFirst, MainWidth = MainWidth, CueFirst = CueFirst, CueWidth = CueWidth,
+ Click = Click, ClickDb = ClickDb,
+ };
+}
+
+public static class OutputSetups
+{
+ public const double ClickDbMin = -60.0;
+ public const double ClickDbMax = 6.0;
+
+ /// <summary>Raised after a setup changed, so the mixer's Cue strip and pickers refresh.</summary>
+ public static event Action? Changed;
+ public static void NotifyChanged() => Changed?.Invoke();
+
+ /// <summary>The settings key of a playback device (same scheme as inputs).</summary>
+ public static string KeyOf(AudioSystem system, string outputUid, string asioDriver)
+ => InputSetups.KeyOf(system, outputUid, asioDriver);
+
+ /// <summary>Two picks (1-based first, width) share a channel.</summary>
+ public static bool Overlaps(int aFirst, int aWidth, int bFirst, int bWidth)
+ => aFirst < bFirst + bWidth && bFirst < aFirst + aWidth;
+
+ /// <summary>A valid pick: width 1, or width 2 starting on an odd channel (1/2, 3/4 …).</summary>
+ public static bool IsValidPick(int first, int width)
+ => first >= 1 && (width == 1 || (width == 2 && first % 2 == 1));
+
+ /// <summary>Main moved; a Cue on the same channels is dropped (FR-004).</summary>
+ public static OutputSetup WithMain(OutputSetup s, int first, int width)
+ {
+ var r = s.Copy();
+ r.MainFirst = first;
+ r.MainWidth = width;
+ if (r.CueFirst is int c && Overlaps(first, width, c, r.CueWidth)) r.CueFirst = null;
+ return r;
+ }
+
+ /// <summary>Cue moved (null = no Cue output). Refused (s returned) when it hits Main.
+ /// Without a Cue output the click can only go to Main.</summary>
+ public static OutputSetup WithCue(OutputSetup s, int? first, int width)
+ {
+ if (first is int f && Overlaps(s.MainFirst, s.MainWidth, f, width)) return s;
+ var r = s.Copy();
+ r.CueFirst = first;
+ r.CueWidth = width;
+ if (first is null) r.Click = ClickDestination.Main;
+ return r;
+ }
+
+ public static OutputSetup WithClick(OutputSetup s, ClickDestination click, double db)
+ {
+ var r = s.Copy();
+ r.Click = r.HasCue ? click : ClickDestination.Main;
+ r.ClickDb = Math.Clamp(db, ClickDbMin, ClickDbMax);
+ return r;
+ }
+
+ /// <summary>The click level as a linear gain (silent at the bottom of the range).</summary>
+ public static float ClickGain(OutputSetup s)
+ => s.ClickDb <= ClickDbMin ? 0f : (float)Math.Pow(10.0, s.ClickDb / 20.0);
+
+ /// <summary>A device never set up: Main 1/2, no Cue, click to Main. Under ASIO Main starts
+ /// on the pair chosen before this setting existed (FR-005, 0-based <paramref name="asioPair"/>).</summary>
+ public static OutputSetup Default(int asioPair = 0)
+ => new() { MainFirst = Math.Max(0, asioPair) / 2 * 2 + 1 };
+}
diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.cs
index e643fc80..47795c56 100644
--- a/src/managed/Nota.Application/Settings.cs
+++ b/src/managed/Nota.Application/Settings.cs
@@ -204,6 +204,9 @@ public sealed class Settings
/// <summary>Audio I/O setup per capture device (specs/086): switched-off inputs and their
/// names, keyed by <see cref="InputSetups.KeyOf"/>. A device never set up has no entry.</summary>
public Dictionary<string, InputSetup> InputSetups { get; set; } = new();
+ /// <summary>Output setup per playback device (specs/089): Main and Cue pairs and where the
+ /// click goes, keyed by <see cref="OutputSetups.KeyOf"/>. A device never set up has no entry.</summary>
+ public Dictionary<string, OutputSetup> OutputSetups { get; set; } = new();
/// <summary>Shift + wheel over a note in the piano roll (specs/063): false — wheel up raises
/// the velocity; true — wheel up lowers it.</summary>
public bool PianoRollVelocityWheelReversed { get; set; }
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs
index 33f9fe2e..c4ab2965 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs
@@ -151,6 +151,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_audio_effective_input_uid")]
internal static partial int AudioEffectiveInputUid(IntPtr engine, [Out] byte[] outBuf, int cap);
+ [LibraryImport(Lib, EntryPoint = "nota_audio_effective_output_uid")]
+ internal static partial int AudioEffectiveOutputUid(IntPtr engine, [Out] byte[] outBuf, int cap);
+
[LibraryImport(Lib, EntryPoint = "nota_midi_input_device_name")]
internal static partial IntPtr MidiInputDeviceName(int index);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 04cc32b1..6a72e46b 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -24,6 +24,12 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_track_set_mute")]
internal static partial NotaResult SetTrackMute(IntPtr engine, int trackId, int mute);
+ [LibraryImport(Lib, EntryPoint = "nota_track_set_cue")]
+ internal static partial NotaResult SetTrackCue(IntPtr engine, int trackId, int on);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_get_cue")]
+ internal static partial int GetTrackCue(IntPtr engine, int trackId);
+
[LibraryImport(Lib, EntryPoint = "nota_track_set_solo")]
internal static partial NotaResult SetTrackSolo(IntPtr engine, int trackId, int solo);
@@ -345,6 +351,25 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_audio_input_channel_name")]
internal static partial int AudioInputChannelName(IntPtr engine, int index, [Out] byte[] outBuf, int cap);
+ // --- output routing (specs/089) ---
+ [LibraryImport(Lib, EntryPoint = "nota_audio_output_channel_count")]
+ internal static partial int AudioOutputChannelCount(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_audio_output_channel_name")]
+ internal static partial int AudioOutputChannelName(IntPtr engine, int index, [Out] byte[] outBuf, int cap);
+
+ [LibraryImport(Lib, EntryPoint = "nota_audio_set_output_routing")]
+ internal static partial NotaResult AudioSetOutputRouting(IntPtr engine, int mainFirst, int mainWidth, int cueFirst, int cueWidth);
+
+ [LibraryImport(Lib, EntryPoint = "nota_audio_output_routing_state")]
+ internal static partial int AudioOutputRoutingState(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_set_test_output_device")]
+ internal static partial void EngineSetTestOutputDevice(IntPtr engine, int channels);
+
+ [LibraryImport(Lib, EntryPoint = "nota_audio_scatter_test")]
+ internal static partial int AudioScatterTest(IntPtr engine, float[] mainIn, float[]? cueIn, [Out] float[] deviceOut, int deviceChannels, int frames);
+
[LibraryImport(Lib, EntryPoint = "nota_track_set_midi_input_uid", StringMarshalling = StringMarshalling.Utf8)]
internal static partial NotaResult TrackSetMidiInputUid(IntPtr engine, int trackId, string? uid, int channel);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index 1c4e773d..034d392e 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -126,6 +126,25 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_master_meter")]
internal static partial NotaResult MasterMeter(IntPtr engine, out NotaMeter meter);
+ // --- Cue (specs/089) ---
+ [LibraryImport(Lib, EntryPoint = "nota_engine_cue_meter")]
+ internal static partial NotaResult CueMeter(IntPtr engine, out NotaMeter meter);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_set_cue_volume")]
+ internal static partial NotaResult SetCueVolume(IntPtr engine, float gain);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_cue_volume")]
+ internal static partial float CueVolume(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_transport_set_click_destination")]
+ internal static partial NotaResult SetClickDestination(IntPtr engine, int dest);
+
+ [LibraryImport(Lib, EntryPoint = "nota_transport_click_destination")]
+ internal static partial int ClickDestination(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_transport_set_click_volume")]
+ internal static partial NotaResult SetClickVolume(IntPtr engine, float gain);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_note_on")]
internal static partial NotaResult NoteOn(IntPtr engine, int pitch, float velocity);
@@ -301,6 +320,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_render_device_block")]
internal static partial NotaResult RenderDeviceBlock(IntPtr engine, [Out] float[] outBuffer, int frames);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_render_device_block_cue")]
+ internal static partial NotaResult RenderDeviceBlockCue(IntPtr engine, [Out] float[] mainOut, [Out] float[]? cueOut, int frames);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_render_offline_at")]
internal static partial NotaResult RenderOfflineAt(IntPtr engine, [Out] float[] outBuffer, int frames, double sampleRate);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs
index 29434e6b..3369262a 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs
@@ -76,6 +76,10 @@ public sealed partial class NotaEngine
public string EffectiveInputUid()
{ ThrowIfDisposed(); return ReadNativeString((b, c) => NativeMethods.AudioEffectiveInputUid(_handle, b, c)); }
+ /// <summary>The uid of the output device the staged config opens (specs/089).</summary>
+ public string EffectiveOutputUid()
+ { ThrowIfDisposed(); return ReadNativeString((b, c) => NativeMethods.AudioEffectiveOutputUid(_handle, b, c)); }
+
/// <summary>Persists the staged config and restarts the backend. Throws on device failure.</summary>
public void ApplyAudio()
{ ThrowIfDisposed(); Check(NativeMethods.AudioApply(_handle)); }
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index 3cb9dcc1..584c0d57 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -26,6 +26,8 @@ public sealed partial class NotaEngine
public void SetTrackVolume(int trackId, float volume) { ThrowIfDisposed(); Check(NativeMethods.SetTrackVolume(_handle, trackId, volume)); }
public void SetTrackPan(int trackId, float pan) { ThrowIfDisposed(); Check(NativeMethods.SetTrackPan(_handle, trackId, pan)); }
public void SetTrackMute(int trackId, bool mute) { ThrowIfDisposed(); Check(NativeMethods.SetTrackMute(_handle, trackId, mute ? 1 : 0)); }
+ public void SetTrackCue(int trackId, bool on) { ThrowIfDisposed(); NativeMethods.SetTrackCue(_handle, trackId, on ? 1 : 0); }
+ public bool GetTrackCue(int trackId) { ThrowIfDisposed(); return NativeMethods.GetTrackCue(_handle, trackId) == 1; }
public void SetTrackSolo(int trackId, bool solo) { ThrowIfDisposed(); Check(NativeMethods.SetTrackSolo(_handle, trackId, solo ? 1 : 0)); }
public int TrackCount { get { ThrowIfDisposed(); return NativeMethods.TrackCount(_handle); } }
@@ -615,6 +617,39 @@ public sealed partial class NotaEngine
public void SetTestInputDevice(int channels)
{ ThrowIfDisposed(); NativeMethods.EngineSetTestInputDevice(_handle, channels); }
+ /// <summary>The playback device's output channel count (0 when none is open).</summary>
+ public int AudioOutputChannelCount()
+ { ThrowIfDisposed(); return NativeMethods.AudioOutputChannelCount(_handle); }
+
+ /// <summary>The name the playback device gives an output channel ("" when it gives none).</summary>
+ public string AudioOutputChannelName(int index)
+ { ThrowIfDisposed(); return ReadNativeString((b, c) => NativeMethods.AudioOutputChannelName(_handle, index, b, c)); }
+
+ /// <summary>Where Main and Cue go (specs/089), 0-based; cueFirst &lt; 0 = no Cue output.
+ /// False for an invalid routing (bad width, odd stereo first, overlapping pairs).</summary>
+ public bool SetOutputRouting(int mainFirst, int mainWidth, int cueFirst, int cueWidth)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.AudioSetOutputRouting(_handle, mainFirst, mainWidth, cueFirst, cueWidth)
+ == NativeMethods.NotaResult.Ok;
+ }
+
+ /// <summary>The routing against the open device: see <see cref="OutputRoutingState"/>.</summary>
+ public OutputRoutingState GetOutputRoutingState()
+ { ThrowIfDisposed(); return (OutputRoutingState)NativeMethods.AudioOutputRoutingState(_handle); }
+
+ /// <summary>Tests: pretend the output device has this many outputs (0 clears it).</summary>
+ public void SetTestOutputDevice(int channels)
+ { ThrowIfDisposed(); NativeMethods.EngineSetTestOutputDevice(_handle, channels); }
+
+ /// <summary>Tests: place Main and Cue on a device of <paramref name="deviceChannels"/> by the
+ /// current routing, as the backends do; returns the routing state.</summary>
+ public OutputRoutingState ScatterOutputsForTest(float[] main, float[]? cue, float[] deviceOut, int deviceChannels, int frames)
+ {
+ ThrowIfDisposed();
+ return (OutputRoutingState)NativeMethods.AudioScatterTest(_handle, main, cue, deviceOut, deviceChannels, frames);
+ }
+
/// <summary>Turns live input monitoring on/off for an audio track (hear its record input through the track).</summary>
public void SetTrackMonitor(int trackId, bool on)
{ ThrowIfDisposed(); NativeMethods.TrackSetMonitor(_handle, trackId, on ? 1 : 0); }
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index d32d0bde..34f65a8c 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -135,6 +135,28 @@ public sealed partial class NotaEngine : IAudioEngine
return m;
}
+ /// <summary>Peak/RMS of the Cue bus after the Cue level (specs/089).</summary>
+ public NotaMeter CueMeter()
+ {
+ ThrowIfDisposed();
+ Check(NativeMethods.CueMeter(_handle, out var m));
+ return m;
+ }
+
+ public float CueVolume
+ {
+ get { ThrowIfDisposed(); return NativeMethods.CueVolume(_handle); }
+ set { ThrowIfDisposed(); Check(NativeMethods.SetCueVolume(_handle, value)); }
+ }
+
+ public ClickDestination ClickDestination
+ {
+ get { ThrowIfDisposed(); return (ClickDestination)NativeMethods.ClickDestination(_handle); }
+ set { ThrowIfDisposed(); Check(NativeMethods.SetClickDestination(_handle, (int)value)); }
+ }
+
+ public void SetClickVolume(float gain) { ThrowIfDisposed(); Check(NativeMethods.SetClickVolume(_handle, gain)); }
+
// --- Live MIDI, arming & recording -------------------------------------
public void SetTrackArmed(int trackId, bool armed) { ThrowIfDisposed(); Check(NativeMethods.SetTrackArmed(_handle, trackId, armed ? 1 : 0)); }
@@ -298,6 +320,13 @@ public sealed partial class NotaEngine : IAudioEngine
Check(NativeMethods.RenderDeviceBlock(_handle, outBuffer, frames));
}
+ /// <summary>Tests: one device block into Main and the Cue bus (specs/089); both stereo.</summary>
+ public void RenderDeviceBlockCue(float[] main, float[]? cue, int frames)
+ {
+ ThrowIfDisposed();
+ Check(NativeMethods.RenderDeviceBlockCue(_handle, main, cue, frames));
+ }
+
/// <summary>
/// Renders `frames` of interleaved stereo at <paramref name="sampleRate"/> (WAV export, M6-4).
/// Stop the audio backend first — this mutates transport state the audio thread reads.
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index b78292b7..bd8cc6ad 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -125,6 +125,9 @@ public static class ProjectMigrations
// v30 -> v31: Nota Aurora instruments gain Wavetables, their imported tables
// (specs/053). Absent in v30 documents; null = the built-in tables — no-op.
new Migration(30, _ => { }),
+ // v31 -> v32 (specs/089): tracks gain Cue, the mixer CueVolume. Absent -> not in Cue,
+ // unity Cue level; no-op, stamp version.
+ new Migration(31, _ => { }),
};
/// <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 7a27a7ab..3bbfd7ba 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -82,6 +82,8 @@ public sealed class MixerDto
{
public string PanLaw { get; set; } = "balance";
public bool PanLawLegacy { get; set; }
+ /// <summary>The Cue mix's level (specs/089), linear; null = 1 (unity, and older files).</summary>
+ public float? CueVolume { get; set; }
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
@@ -125,6 +127,7 @@ public sealed class TrackDto
public bool Mute { get; set; }
public bool Solo { get; set; }
public bool Armed { get; set; }
+ public bool? Cue { get; set; } // in Cue (specs/089); null = not (and older files)
public int ReturnIndex { get; set; } = -1; // >=0 for return tracks
public int GroupId { get; set; } = -1; // parent group's doc index, or -1 (top-level)
public int ColorIndex { get; set; } = -1; // palette slot; -1 = auto by position
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index ef5da3f7..e990c1da 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -41,7 +41,8 @@ public sealed class ProjectService
/// v29 (specs/067) adds Takes on audio tracks and TakeId on audio clips.
/// v30 (specs/085) adds MidiOffsetMs and ArticulationMap on tracks and Articulation on notes.
/// v31 (specs/053) adds Wavetables on Nota Aurora: its imported tables, as samples.
- public const int CurrentFormatVersion = 31;
+ /// v32 (specs/089) adds Cue on tracks and CueVolume on the mixer.
+ public const int CurrentFormatVersion = 32;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -85,6 +86,7 @@ public sealed class ProjectService
{
PanLaw = engine.PanLaw == PanLaw.Stereo ? "stereo" : "balance",
PanLawLegacy = transport.PanLawLegacy,
+ CueVolume = Math.Abs(engine.CueVolume - 1f) > 1e-6f ? engine.CueVolume : null,
},
// Always written ([] when none), so a load can tell "no sections" from "older file".
Sections = engine.Sections.Select(s => new SectionDto { Start = s.StartBeat, Length = s.LengthBeats, Name = s.Name }).ToList(),
@@ -108,6 +110,7 @@ public sealed class ProjectService
Mute = ti.Muted != 0,
Solo = ti.Soloed != 0,
Armed = ti.Armed != 0,
+ Cue = engine.GetTrackCue(ti.Id) ? true : null,
ReturnIndex = engine.TrackReturnIndex(ti.Id),
GroupId = ti.GroupId >= 0 && idToIndex.TryGetValue(ti.GroupId, out var gix) ? gix : -1, // parent → doc index
ColorIndex = engine.GetTrackColorIndex(ti.Id),
@@ -595,6 +598,8 @@ public sealed class ProjectService
// Pan law (specs/006) first, as the baseline rather than an undo step. A missing mixer
// is a pre-v21 project: Balance, so the mix sounds as it was saved.
engine.SetPanLaw(ParsePanLaw(doc.Mixer?.PanLaw, warnings), checkpoint: false);
+ // The Cue level (specs/089): a listening level, not part of the mix — no undo step.
+ engine.CueVolume = doc.Mixer?.CueVolume is float cv && float.IsFinite(cv) ? Math.Clamp(cv, 0f, 2f) : 1f;
// Arrangement sections (specs/016), also a baseline. A file from before they moved into
// the project keeps them in the bundle's sidecar.
@@ -762,6 +767,7 @@ public sealed class ProjectService
engine.SetTrackPan(id, t.Pan);
engine.SetTrackMute(id, t.Mute);
engine.SetTrackSolo(id, t.Solo);
+ engine.SetTrackCue(id, t.Cue == true);
engine.SetTrackArmed(id, t.Armed);
if (t.Name is { Length: > 0 } trackName) engine.SetTrackName(id, trackName);
if (t.ColorIndex >= 0) engine.SetTrackColorIndex(id, t.ColorIndex);
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 5f8071d5..401de8d9 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1723,6 +1723,28 @@ NOTA_API void nota_engine_set_test_input_device(NotaEngine* engine, int32_
/* Tests: `frames` of `channels`-wide device frames into the capture ring, then drained into
* the running take as poll() would. */
NOTA_API void nota_engine_feed_input_test(NotaEngine* engine, const float* interleaved, int32_t frames, int32_t channels);
+/* Output channels of the open playback device (specs/089): how many (0 = none), at most 64,
+ * and the UTF-8 name the device gives one ("" when it gives none; copied into `out`, returns
+ * its length). Message thread. */
+NOTA_API int32_t nota_audio_output_channel_count(const NotaEngine* engine);
+NOTA_API int32_t nota_audio_output_channel_name(const NotaEngine* engine, int32_t index, char* out, int32_t cap);
+/* Where Main (the audience mix) and Cue (the private cue mix) go: 0-based first channel and
+ * width (1 or 2; width 2 needs an even first). cue_first < 0 = no Cue output. Takes effect on
+ * the next audio block, no device restart; kept across nota_audio_apply. NOTA_ERR_INVALID_ARG
+ * for a bad width, an odd stereo first or overlapping pairs. Until it is called, ASIO keeps
+ * its saved output pair. */
+NOTA_API NotaResult nota_audio_set_output_routing(NotaEngine* engine, int32_t main_first, int32_t main_width,
+ int32_t cue_first, int32_t cue_width);
+/* The routing against the open device: bit 1 = Main's pair is missing, Main plays on outputs
+ * 1/2; bit 2 = a Cue pair is set but missing (or would overlap Main): Cue is silent and
+ * nothing moves to Main. */
+NOTA_API int32_t nota_audio_output_routing_state(const NotaEngine* engine);
+/* Tests: pretend the output device has `channels` outputs ("Test N"); 0 clears it. */
+NOTA_API void nota_engine_set_test_output_device(NotaEngine* engine, int32_t channels);
+/* Tests: place `frames` of Main and Cue (interleaved stereo; cue may be null) on a device of
+ * `device_channels` by the current routing, as every backend does. Returns the state bits. */
+NOTA_API int32_t nota_audio_scatter_test(const NotaEngine* engine, const float* main_in, const float* cue_in,
+ float* device_out, int32_t device_channels, int32_t frames);
/* Input monitoring (audio tracks, Monitor "In"): while on, the track plays its record-input
* source live through its devices + fader instead of its clips. A master source stays
* silent (it would feed back). push_monitor_frames feeds the hardware-monitor ring without
@@ -2560,6 +2582,25 @@ NOTA_API int32_t nota_pdc_selftest(void);
NOTA_API int32_t nota_engine_track_meter(const NotaEngine* engine, int32_t track_id, NotaMeter* out);
NOTA_API NotaResult nota_engine_master_meter(const NotaEngine* engine, NotaMeter* out);
+/* Cue (specs/089): a private mix for the performer on its own output pair (see
+ * nota_audio_set_output_routing). Any number of tracks — audio, instrument, group or return —
+ * can be in Cue; each adds its signal after its devices and before its fader, pan, mute and
+ * solo. A muted cued track is heard in Cue only. Cue never changes Main, a recording or a
+ * bounce. get_cue: 1 / 0, -1 for no such track. */
+NOTA_API NotaResult nota_track_set_cue(NotaEngine* engine, int32_t track_id, int32_t on);
+NOTA_API int32_t nota_track_get_cue(const NotaEngine* engine, int32_t track_id);
+/* Cue level: linear gain 0 … 2 (+6 dB), default 1. */
+NOTA_API NotaResult nota_engine_set_cue_volume(NotaEngine* engine, float gain);
+NOTA_API float nota_engine_cue_volume(const NotaEngine* engine);
+/* Cue meter, after the Cue level. */
+NOTA_API NotaResult nota_engine_cue_meter(const NotaEngine* engine, NotaMeter* out);
+/* Where the metronome and count-in clicks go: 0 Main (default, through the master chain as
+ * before), 1 Cue (past the master chain and fader, at the Cue level), 2 both. */
+NOTA_API NotaResult nota_transport_set_click_destination(NotaEngine* engine, int32_t dest);
+NOTA_API int32_t nota_transport_click_destination(const NotaEngine* engine);
+/* Click level: linear gain 0 … 2, default 1 (the click as it always sounded). */
+NOTA_API NotaResult nota_transport_set_click_volume(NotaEngine* engine, float gain);
+
/* ---- Offline render (tests / export) ------------------------------------- */
/* Renders `frames` of interleaved stereo into out (length >= 2*frames) without
* an audio device. Uses the engine's current sample rate. */
@@ -2577,6 +2618,9 @@ NOTA_API NotaResult nota_engine_render_offline_at(NotaEngine* engine, float* out
* nota_engine_render_offline_at once first to prepare the nodes at a rate. The device
* must be stopped (NOTA_ERR_ALREADY_RUNNING otherwise). */
NOTA_API NotaResult nota_engine_render_device_block(NotaEngine* engine, float* out, int32_t frames);
+/* The same, rendering the Cue bus (specs/089) into `cue_out` too (stereo; may be null). */
+NOTA_API NotaResult nota_engine_render_device_block_cue(NotaEngine* engine, float* main_out, float* cue_out,
+ int32_t frames);
/* ---- Audio file encoders (export) -----------------------------------------
* Streaming FLAC / MP3 writers behind the same ABI as the offline render above:
@@ -2722,6 +2766,8 @@ NOTA_API const char* nota_audio_input_device_name(int32_t index);
* is connected, else the system default ("" when there is none). Copied into `out`; returns
* its length. Settings kept per input device key on it. */
NOTA_API int32_t nota_audio_effective_input_uid(const NotaEngine* engine, char* out, int32_t cap);
+/* The same for the output device (specs/089): per-device output setups key on it. */
+NOTA_API int32_t nota_audio_effective_output_uid(const NotaEngine* engine, char* out, int32_t cap);
/* Stage the desired config. Pass "" for a device to mean "system default",
* 0 for sample_rate / buffer_frames to mean "device default". */
diff --git a/src/native/nota.engine/src/abi/nota_engine_audio.cpp b/src/native/nota.engine/src/abi/nota_engine_audio.cpp
index 31307506..2843c101 100644
--- a/src/native/nota.engine/src/abi/nota_engine_audio.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_audio.cpp
@@ -77,6 +77,17 @@ const char* nota_audio_input_device_uid(int32_t i) {
const char* nota_audio_input_device_name(int32_t i) {
return deviceField(g_inputDevices, i, false);
}
+int32_t nota_audio_effective_output_uid(const NotaEngine* e, char* out, int32_t cap) {
+ if (!e) return 0;
+ const std::string uid = nota::effectiveAudioDeviceUid(CENG(e)->audioConfig().outputDeviceUid, /*inputScope=*/false);
+ if (out && cap > 0) {
+ const size_t n = std::min(uid.size(), static_cast<size_t>(cap - 1));
+ std::memcpy(out, uid.data(), n);
+ out[n] = '\0';
+ }
+ return static_cast<int32_t>(uid.size());
+}
+
int32_t nota_audio_effective_input_uid(const NotaEngine* e, char* out, int32_t cap) {
if (!e) return 0;
const std::string uid = nota::effectiveAudioDeviceUid(CENG(e)->audioConfig().inputDeviceUid, /*inputScope=*/true);
@@ -368,7 +379,7 @@ void checkRouting(AsioCheck& check) {
AsioSession::Options opt;
opt.outputPair = 2;
check(rig.open(cfg, opt), "8-out fake opens");
- rig.session.setRenderCallback([](float* out, int32_t n) {
+ rig.session.setRenderCallback([](float* out, float*, int32_t n) {
for (int32_t i = 0; i < n; ++i) {
out[i * 2] = 0.25f;
out[i * 2 + 1] = -0.5f;
@@ -394,7 +405,7 @@ void checkRouting(AsioCheck& check) {
cfg.inputs = 0;
cfg.outputs = 1;
check(mono.open(cfg), "1-out fake opens");
- mono.session.setRenderCallback([](float* out, int32_t n) {
+ mono.session.setRenderCallback([](float* out, float*, int32_t n) {
for (int32_t i = 0; i < n; ++i) {
out[i * 2] = 0.2f;
out[i * 2 + 1] = 0.6f;
@@ -405,6 +416,36 @@ void checkRouting(AsioCheck& check) {
const auto& m = mono.fake->written(0);
check(!m.empty() && std::fabs(m.front() - 0.4f) < 1e-6f && std::fabs(m.back() - 0.4f) < 1e-6f,
"mono output is the down-sum");
+ // Main and Cue on two pairs of a 6-out driver (specs/089); a Cue pair the driver lacks
+ // is silent and never folds into Main.
+ {
+ Rig cueRig;
+ FakeAsioDriver::Config c6;
+ c6.inputs = 0;
+ c6.outputs = 6;
+ check(cueRig.open(c6), "6-out fake opens");
+ cueRig.session.setRenderCallback([](float* main, float* cue, int32_t n) {
+ for (int32_t i = 0; i < n; ++i) {
+ main[i * 2] = 0.25f;
+ main[i * 2 + 1] = 0.25f;
+ cue[i * 2] = -0.5f;
+ cue[i * 2 + 1] = -0.5f;
+ }
+ });
+ cueRig.session.setOutputRouting(nota::OutputRouting{0, 2, 4, 2});
+ check(cueRig.session.start(), "6-out fake starts");
+ cueRig.fake->pump(2);
+ const auto& m0 = cueRig.fake->written(0);
+ const auto& c4 = cueRig.fake->written(4);
+ check(!m0.empty() && std::fabs(m0.back() - 0.25f) < 1e-6f && !c4.empty() && std::fabs(c4.back() + 0.5f) < 1e-6f,
+ "Main on outputs 1/2, Cue on 5/6");
+ check(!cueRig.fake->nonZeroBytes(2) && !cueRig.fake->nonZeroBytes(3), "outputs 3/4 stay zero");
+ cueRig.session.setOutputRouting(nota::OutputRouting{0, 2, 6, 2}); // not on a 6-out driver
+ cueRig.fake->pump(1);
+ const auto& m1 = cueRig.fake->written(0);
+ check(!m1.empty() && std::fabs(m1.back() - 0.25f) < 1e-6f, "a missing Cue pair leaves Main as it is");
+ cueRig.session.close();
+ }
// An out-of-range pair falls back to the first.
Rig clamp;
cfg.outputs = 2;
@@ -433,7 +474,7 @@ void checkDuplex(AsioCheck& check) {
gotChannels = channels;
for (int32_t c = 0; c < 4; ++c) got[c] = c < channels ? s[c] : -1.0f;
};
- rig.session.setRenderCallback([&](float*, int32_t) { order.push_back('r'); });
+ rig.session.setRenderCallback([&](float*, float*, int32_t) { order.push_back('r'); });
rig.session.setInputCallback(&in);
rig.session.start();
rig.fake->pump(3);
@@ -560,7 +601,7 @@ void checkFailures(AsioCheck& check) {
Rig late;
int renders = 0;
check(late.open(FakeAsioDriver::Config{}), "late-callback fake opens");
- late.session.setRenderCallback([&](float*, int32_t) { ++renders; });
+ late.session.setRenderCallback([&](float*, float*, int32_t) { ++renders; });
late.session.start();
late.fake->pump(2);
late.session.stop();
@@ -574,7 +615,7 @@ void checkFailures(AsioCheck& check) {
FakeAsioDriver* fake = drv.get(); // leaked with the session's state when it wedges
check(stuck.open(std::move(drv), {}), "stall fake opens");
std::atomic<bool> inRender{false}, release{false};
- stuck.setRenderCallback([&](float* out, int32_t n) {
+ stuck.setRenderCallback([&](float* out, float*, int32_t n) {
inRender = true;
while (!release.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::fill(out, out + static_cast<size_t>(n) * 2, 0.5f);
diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cpp
index d0d3f878..1489b528 100644
--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp
@@ -475,6 +475,35 @@ NotaResult nota_engine_master_meter(const NotaEngine* e, NotaMeter* out) {
return NOTA_OK;
}
+// ---- Cue (specs/089) --------------------------------------------------------
+
+NotaResult nota_engine_set_cue_volume(NotaEngine* e, float gain) {
+ if (!e || !std::isfinite(gain)) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setCueVolume(gain);
+ return NOTA_OK;
+}
+float nota_engine_cue_volume(const NotaEngine* e) {
+ return e ? CENG(e)->cueVolume() : 0.0f;
+}
+NotaResult nota_engine_cue_meter(const NotaEngine* e, NotaMeter* out) {
+ if (!e || !out) return NOTA_ERR_INVALID_ARG;
+ CENG(e)->cueMeter(out->peak_l, out->peak_r, out->rms_l, out->rms_r);
+ return NOTA_OK;
+}
+NotaResult nota_transport_set_click_destination(NotaEngine* e, int32_t dest) {
+ if (!e || dest < 0 || dest > 2) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setClickDestination(dest);
+ return NOTA_OK;
+}
+int32_t nota_transport_click_destination(const NotaEngine* e) {
+ return e ? CENG(e)->clickDestination() : 0;
+}
+NotaResult nota_transport_set_click_volume(NotaEngine* e, float gain) {
+ if (!e || !std::isfinite(gain)) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setClickVolume(gain);
+ return NOTA_OK;
+}
+
// ---- Offline render -------------------------------------------------------
NotaResult nota_engine_render_offline(NotaEngine* e, float* out, int32_t frames) {
@@ -483,6 +512,13 @@ NotaResult nota_engine_render_offline(NotaEngine* e, float* out, int32_t frames)
return NOTA_OK;
}
+NotaResult nota_engine_render_device_block_cue(NotaEngine* e, float* main_out, float* cue_out, int32_t frames) {
+ if (!e || !main_out || frames <= 0) return NOTA_ERR_INVALID_ARG;
+ if (ENG(e)->isRunning()) return NOTA_ERR_ALREADY_RUNNING;
+ ENG(e)->renderDeviceBlock(main_out, cue_out, frames);
+ return NOTA_OK;
+}
+
NotaResult nota_engine_render_device_block(NotaEngine* e, float* out, int32_t frames) {
if (!e || !out || frames <= 0) return NOTA_ERR_INVALID_ARG;
if (ENG(e)->isRunning()) return NOTA_ERR_ALREADY_RUNNING; // the device renders itself
diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cpp
index 99912b2d..d802f2d6 100644
--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp
@@ -806,6 +806,47 @@ void nota_engine_feed_input_test(NotaEngine* e, const float* interleaved, int32_
void nota_engine_set_test_input_device(NotaEngine* e, int32_t channels) {
if (e) ENG(e)->setTestInputDevice(channels);
}
+
+// --- Cue and output routing (specs/089) ---------------------------------------------------
+NotaResult nota_track_set_cue(NotaEngine* e, int32_t track_id, int32_t on) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->setTrackCue(track_id, on != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
+int32_t nota_track_get_cue(const NotaEngine* e, int32_t track_id) {
+ return e ? CENG(e)->trackCue(track_id) : -1;
+}
+int32_t nota_audio_output_channel_count(const NotaEngine* e) {
+ return e ? CENG(e)->outputChannelCount() : 0;
+}
+int32_t nota_audio_output_channel_name(const NotaEngine* e, int32_t index, char* out, int32_t cap) {
+ if (!e) return 0;
+ const std::string name = CENG(e)->outputChannelName(index);
+ if (out && cap > 0) {
+ const size_t n = std::min(name.size(), static_cast<size_t>(cap - 1));
+ std::memcpy(out, name.data(), n);
+ out[n] = '\0';
+ }
+ return static_cast<int32_t>(name.size());
+}
+NotaResult nota_audio_set_output_routing(NotaEngine* e, int32_t main_first, int32_t main_width, int32_t cue_first,
+ int32_t cue_width) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ const nota::OutputRouting r{main_first, main_width, cue_first < 0 ? -1 : cue_first, cue_width};
+ return ENG(e)->setOutputRouting(r) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
+int32_t nota_audio_output_routing_state(const NotaEngine* e) {
+ return e ? CENG(e)->outputRoutingState() : 0;
+}
+void nota_engine_set_test_output_device(NotaEngine* e, int32_t channels) {
+ if (e) ENG(e)->setTestOutputDevice(channels);
+}
+int32_t nota_audio_scatter_test(const NotaEngine* e, const float* main_in, const float* cue_in, float* device_out,
+ int32_t device_channels, int32_t frames) {
+ if (!e || !main_in || !device_out || device_channels <= 0 || frames <= 0) return 0;
+ const nota::ResolvedRouting r = nota::resolveRouting(CENG(e)->outputRouting(), device_channels);
+ nota::scatterOutputs(main_in, r.cueWidth > 0 ? cue_in : nullptr, device_out, device_channels, frames, r);
+ return r.flags;
+}
NotaResult nota_track_set_monitor(NotaEngine* e, int32_t track_id, int32_t on) {
if (!e) return NOTA_ERR_INVALID_ARG;
ENG(e)->setTrackMonitor(track_id, on != 0);
diff --git a/src/native/nota.engine/src/audio_io/AudioBackend.h b/src/native/nota.engine/src/audio_io/AudioBackend.h
index a036a62f..f584c604 100644
--- a/src/native/nota.engine/src/audio_io/AudioBackend.h
+++ b/src/native/nota.engine/src/audio_io/AudioBackend.h
@@ -10,6 +10,8 @@
#pragma once
+#include "OutputRouting.h"
+
#include <cstdint>
#include <functional>
#include <string>
@@ -17,9 +19,10 @@
namespace nota {
// Called from the real-time audio thread. MUST be real-time safe (AR-6):
-// no allocation, no locks, no I/O. Writes `numFrames` of interleaved stereo
-// float samples into `out` (2 channels).
-using RenderCallback = std::function<void(float* out, int32_t numFrames)>;
+// no allocation, no locks, no I/O. Writes `numFrames` of interleaved stereo float samples
+// into `main` (the audience mix) and into `cue` (the private Cue mix, specs/089). The
+// backend places both on the device's outputs by its OutputRouting (OutputRouting.h).
+using RenderCallback = std::function<void(float* main, float* cue, int32_t numFrames)>;
// Requested device configuration (M7-1). Zero fields mean "use the device
// default": device 0 = system default output, sampleRate 0 / bufferFrames 0 =
@@ -104,6 +107,15 @@ class AudioBackend {
// against the device's deadline. Read after start() succeeds.
virtual void* ioWorkgroup() const { return nullptr; }
+ // Output channels of the open device (specs/089): how many (at most kMaxOutputChannels,
+ // 0 when none is open) and the name the driver gives one ("" when it gives none).
+ // Control thread, after start().
+ virtual int32_t outputChannelCount() const { return isRunning() ? 2 : 0; }
+ virtual std::string outputChannelName(int32_t /*index*/) const { return {}; }
+
+ // Where Main and Cue go. Takes effect on the next callback — no restart. Any thread.
+ virtual void setOutputRouting(const OutputRouting& r) { (void)r; }
+
// After a reset-requested event: the rate the user picked in the device's own settings
// (0 = unchanged). The engine then stops requesting its saved rate, so a reopen keeps it.
virtual double deviceChangedRate() const { return 0.0; }
diff --git a/src/native/nota.engine/src/audio_io/OutputRouting.h b/src/native/nota.engine/src/audio_io/OutputRouting.h
new file mode 100644
index 00000000..c22ed749
--- /dev/null
+++ b/src/native/nota.engine/src/audio_io/OutputRouting.h
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Where the engine's two stereo buses — Main and Cue (specs/089) — land on the device's
+// output channels. The engine renders both buses into stereo scratch buffers; every backend
+// then places them with the same rules, so a missing Cue pair goes silent the same way on
+// CoreAudio, miniaudio and ASIO and never falls into Main (FR-014).
+//
+// Everything here is plain integer math and copies: safe on the audio thread (AR-6).
+
+#pragma once
+
+#include <algorithm>
+#include <atomic>
+#include <cstdint>
+#include <cstring>
+#include <vector>
+
+namespace nota {
+
+constexpr int32_t kMaxOutputChannels = 64;
+
+// The user's choice: 0-based first channel and width (1 or 2) for Main and Cue.
+// cueFirst < 0 = no Cue output.
+struct OutputRouting {
+ int32_t mainFirst = 0;
+ int32_t mainWidth = 2;
+ int32_t cueFirst = -1;
+ int32_t cueWidth = 2;
+};
+
+// nota_audio_output_routing_state bits.
+enum : int32_t {
+ kRoutingMainFellBack = 1, // Main's pair is not on the device: it plays on outputs 1/2
+ kRoutingCueUnavailable = 2, // a Cue pair is set but not on the device (or would hit Main)
+};
+
+// The choice resolved against a device: width 0 = not written.
+struct ResolvedRouting {
+ int32_t mainFirst = 0;
+ int32_t mainWidth = 0;
+ int32_t cueFirst = 0;
+ int32_t cueWidth = 0;
+ int32_t flags = 0;
+};
+
+inline bool validRouting(const OutputRouting& r) {
+ auto ok = [](int32_t first, int32_t width) {
+ return first >= 0 && first < kMaxOutputChannels && (width == 1 || (width == 2 && first % 2 == 0));
+ };
+ if (!ok(r.mainFirst, r.mainWidth)) return false;
+ if (r.cueFirst < 0) return true;
+ if (!ok(r.cueFirst, r.cueWidth)) return false;
+ // Main and Cue never share a channel (FR-004).
+ return r.cueFirst + r.cueWidth <= r.mainFirst || r.mainFirst + r.mainWidth <= r.cueFirst;
+}
+
+inline uint64_t packRouting(const OutputRouting& r) {
+ auto b = [](int32_t v) { return static_cast<uint64_t>(static_cast<uint16_t>(static_cast<int16_t>(v))); };
+ return b(r.mainFirst) | (b(r.mainWidth) << 16) | (b(r.cueFirst) << 32) | (b(r.cueWidth) << 48);
+}
+
+inline OutputRouting unpackRouting(uint64_t p) {
+ auto f = [&](int shift) { return static_cast<int32_t>(static_cast<int16_t>(static_cast<uint16_t>(p >> shift))); };
+ return OutputRouting{f(0), f(16), f(32), f(48)};
+}
+
+// The rules of specs/089 data-model.md § Resolution.
+inline ResolvedRouting resolveRouting(const OutputRouting& r, int32_t deviceChannels) {
+ ResolvedRouting out;
+ const int32_t n = std::clamp(deviceChannels, 0, kMaxOutputChannels);
+ if (n <= 0) {
+ if (r.cueFirst >= 0) out.flags |= kRoutingCueUnavailable;
+ return out;
+ }
+ // A pair whose second channel is missing plays on its first channel alone.
+ auto fit = [n](int32_t first, int32_t width) { return first < 0 || first >= n ? 0 : std::min(width, n - first); };
+
+ out.mainFirst = r.mainFirst;
+ out.mainWidth = fit(r.mainFirst, r.mainWidth);
+ if (out.mainWidth == 0) {
+ out.mainFirst = 0;
+ out.mainWidth = std::min(2, n);
+ out.flags |= kRoutingMainFellBack;
+ }
+ if (r.cueFirst >= 0) {
+ const int32_t w = fit(r.cueFirst, r.cueWidth);
+ const bool overlaps = w > 0 && r.cueFirst < out.mainFirst + out.mainWidth && out.mainFirst < r.cueFirst + w;
+ if (w == 0 || overlaps) {
+ out.flags |= kRoutingCueUnavailable;
+ } else {
+ out.cueFirst = r.cueFirst;
+ out.cueWidth = w;
+ }
+ }
+ return out;
+}
+
+// Write `frames` of `main` and `cue` (interleaved stereo; cue may be null = silent) into an
+// interleaved device buffer of `deviceChannels`. A width-1 destination gets the L+R sum
+// halved; every other channel is zero.
+inline void scatterOutputs(const float* main, const float* cue, float* device, int32_t deviceChannels,
+ int32_t frames, const ResolvedRouting& r) {
+ const int32_t ch = deviceChannels;
+ if (ch <= 0 || frames <= 0) return;
+ std::memset(device, 0, sizeof(float) * static_cast<size_t>(frames) * static_cast<size_t>(ch));
+ auto place = [&](const float* src, int32_t first, int32_t width) {
+ if (!src || width <= 0 || first < 0 || first + width > ch) return;
+ float* d = device + first;
+ if (width == 2) {
+ for (int32_t i = 0; i < frames; ++i, d += ch) {
+ d[0] = src[i * 2];
+ d[1] = src[i * 2 + 1];
+ }
+ } else {
+ for (int32_t i = 0; i < frames; ++i, d += ch) d[0] = 0.5f * (src[i * 2] + src[i * 2 + 1]);
+ }
+ };
+ place(main, r.mainFirst, r.mainWidth);
+ place(cue, r.cueFirst, r.cueWidth);
+}
+
+// What a backend with an interleaved device buffer (CoreAudio, miniaudio) keeps: two stereo
+// scratch buffers sized once off the audio thread, and the routing as one atomic word.
+class OutputStage {
+ public:
+ static constexpr int32_t kChunkFrames = 4096;
+
+ OutputStage() : main_(kChunkFrames * 2, 0.0f), cue_(kChunkFrames * 2, 0.0f) {}
+
+ void setRouting(const OutputRouting& r) { routing_.store(packRouting(r), std::memory_order_relaxed); }
+ OutputRouting routing() const { return unpackRouting(routing_.load(std::memory_order_relaxed)); }
+
+ // Audio thread: render through `render(main, cue, frames)` in chunks and place the result.
+ template <class Render>
+ void process(Render& render, float* device, int32_t deviceChannels, int32_t frames) {
+ const ResolvedRouting r = resolveRouting(routing(), deviceChannels);
+ for (int32_t done = 0; done < frames;) {
+ const int32_t n = std::min(frames - done, kChunkFrames);
+ render(main_.data(), cue_.data(), n);
+ scatterOutputs(main_.data(), r.cueWidth > 0 ? cue_.data() : nullptr,
+ device + static_cast<size_t>(done) * static_cast<size_t>(deviceChannels), deviceChannels, n, r);
+ done += n;
+ }
+ }
+
+ private:
+ std::atomic<uint64_t> routing_{packRouting(OutputRouting{})};
+ std::vector<float> main_;
+ std::vector<float> cue_;
+};
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/audio_io/asio/AsioSession.cpp b/src/native/nota.engine/src/audio_io/asio/AsioSession.cpp
index efdcaf3d..7963e1b6 100644
--- a/src/native/nota.engine/src/audio_io/asio/AsioSession.cpp
+++ b/src/native/nota.engine/src/audio_io/asio/AsioSession.cpp
@@ -135,6 +135,7 @@ bool AsioSession::open(std::unique_ptr<AsioDriverApi> driver, const Options& opt
// Pairs: an out-of-range pair falls back to the first; a missing second channel = mono.
outL_ = (opt.outputPair >= 0 && opt.outputPair < outs) ? opt.outputPair : 0;
outR_ = outL_ + 1 < outs ? outL_ + 1 : -1;
+ routing_.store(packRouting(OutputRouting{outL_, 2, -1, 2}), std::memory_order_relaxed); // Main = the saved pair
// Inputs: every one the engine can address (specs/086); the saved pair is the fallback
// when a driver refuses that many buffers.
inPair_ = ins > 0 ? ((opt.inputPair >= 0 && opt.inputPair < ins) ? opt.inputPair : 0) : -1;
@@ -170,6 +171,7 @@ bool AsioSession::open(std::unique_ptr<AsioDriverApi> driver, const Options& opt
io.buffers.push_back(BufferInfo{true, c, {nullptr, nullptr}});
}
io.interleaved.assign(static_cast<size_t>(bufferFrames_) * 2, 0.0f);
+ io.cueInterleaved.assign(static_cast<size_t>(bufferFrames_) * 2, 0.0f);
io.inInterleaved.assign(static_cast<size_t>(bufferFrames_) * static_cast<size_t>(std::max(inCount_, 1)), 0.0f);
};
@@ -342,22 +344,34 @@ void AsioSession::bufferSwitch(int32_t index, int64_t pos) {
(*in)(ins, n, s.inCount);
}
- if (s.render) s.render(io, n);
- else std::fill(io, io + static_cast<size_t>(n) * 2, 0.0f);
+ float* cue = s.cueInterleaved.data();
+ if (s.render) s.render(io, cue, n);
+ else {
+ std::fill(io, io + static_cast<size_t>(n) * 2, 0.0f);
+ std::fill(cue, cue + static_cast<size_t>(n) * 2, 0.0f);
+ }
const auto outBuf = [&](int32_t ch) { return s.buffers[static_cast<size_t>(ch)].buffers[index]; };
const auto outType = [&](int32_t ch) { return s.outTypes[static_cast<size_t>(ch)]; };
- if (s.outR >= 0) {
- fromFloat(io, 2, outType(s.outL), outBuf(s.outL), n);
- fromFloat(io + 1, 2, outType(s.outR), outBuf(s.outR), n);
- } else {
- for (int32_t i = 0; i < n; ++i) io[i * 2] = 0.5f * (io[i * 2] + io[i * 2 + 1]); // mono output: down-sum
- fromFloat(io, 2, outType(s.outL), outBuf(s.outL), n);
- }
- // Drivers may not keep buffer contents: hold every other output at zero each switch.
const auto outs = static_cast<int32_t>(s.outTypes.size());
+ // Main and Cue by the routing (specs/089): a missing Cue pair is silent, never Main.
+ const ResolvedRouting rr = resolveRouting(unpackRouting(routing_.load(std::memory_order_relaxed)), outs);
+ const auto place = [&](float* src, int32_t first, int32_t width) {
+ if (width == 1) {
+ for (int32_t i = 0; i < n; ++i) src[i * 2] = 0.5f * (src[i * 2] + src[i * 2 + 1]); // mono: down-sum
+ }
+ for (int32_t c = 0; c < width; ++c) {
+ const int32_t ch = first + c;
+ if (isSupported(outType(ch))) fromFloat(src + c, 2, outType(ch), outBuf(ch), n);
+ else clear(outType(ch), outBuf(ch), n);
+ }
+ };
+ if (rr.mainWidth > 0) place(io, rr.mainFirst, rr.mainWidth);
+ if (rr.cueWidth > 0) place(cue, rr.cueFirst, rr.cueWidth);
+ // Drivers may not keep buffer contents: hold every other output at zero each switch.
+ const auto used = [&](int32_t ch, int32_t first, int32_t width) { return ch >= first && ch < first + width; };
for (int32_t ch = 0; ch < outs; ++ch)
- if (ch != s.outL && ch != s.outR) clear(outType(ch), outBuf(ch), n);
+ if (!used(ch, rr.mainFirst, rr.mainWidth) && !used(ch, rr.cueFirst, rr.cueWidth)) clear(outType(ch), outBuf(ch), n);
if (s.outputReady) s.driver->outputReady();
inSwitch_.store(false, std::memory_order_release);
diff --git a/src/native/nota.engine/src/audio_io/asio/AsioSession.h b/src/native/nota.engine/src/audio_io/asio/AsioSession.h
index 01300402..01630b42 100644
--- a/src/native/nota.engine/src/audio_io/asio/AsioSession.h
+++ b/src/native/nota.engine/src/audio_io/asio/AsioSession.h
@@ -87,6 +87,9 @@ class AsioSession {
bool wedged() const { return wedged_; }
const std::vector<ChannelInfo>& channels(bool input) const { return input ? inChannels_ : outChannels_; }
int32_t outputPair() const { return outL_; }
+ // Where Main and Cue go (specs/089); any thread, read by the next buffer switch. Until it
+ // is called, Main is the saved output pair and there is no Cue.
+ void setOutputRouting(const OutputRouting& r) { routing_.store(packRouting(r), std::memory_order_relaxed); }
int32_t inputPair() const { return inPair_; } // the saved pair: the fallback capture
bool openControlPanel();
@@ -116,7 +119,8 @@ class AsioSession {
int32_t outL = -1, outR = -1; // output channels = their indices in buffers; R -1 = mono
std::vector<int32_t> inBufs; // per input channel: index into buffers, -1 = silent
int32_t inCount = 0; // input channels handed to the callback
- std::vector<float> interleaved; // `frames` stereo frames
+ std::vector<float> interleaved; // `frames` stereo frames: Main
+ std::vector<float> cueInterleaved; // `frames` stereo frames: Cue (specs/089)
std::vector<float> inInterleaved; // `frames` × inCount input frames
RenderCallback render; // copied at start(): never swapped under the switch
};
@@ -151,6 +155,7 @@ class AsioSession {
RenderCallback render_;
std::function<void()> xrun_;
std::atomic<const InputCallback*> input_{nullptr};
+ std::atomic<uint64_t> routing_{packRouting(OutputRouting{})};
std::atomic<bool> inSwitch_{false};
std::atomic<bool> resetRequested_{false};
diff --git a/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.cpp b/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.cpp
index 1099755f..3b4edbe6 100644
--- a/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.cpp
+++ b/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.cpp
@@ -5,6 +5,7 @@
#include "MiniaudioDevices.h"
#include "nota_miniaudio.h"
+#include <algorithm>
#include <cstring>
namespace nota {
@@ -15,16 +16,20 @@ struct MiniaudioBackend::Impl {
ma_context nullContext{}; // the silent fallback's context (null backend only)
bool nullContextInited = false;
RenderCallback render; // copied from the backend on start()
+ OutputStage stage; // Main/Cue scratch + routing (specs/089)
+ int32_t channels = 2; // the device's native output channels (≤ 64)
};
-// miniaudio real-time thread: fill the interleaved stereo float output buffer.
+// miniaudio real-time thread: fill the interleaved float output buffer, one channel per
+// device output; Main and Cue are placed by the stage (specs/089).
// MUST be real-time safe (no alloc/lock/IO) — same contract as CoreAudio (AR-6).
static void dataCallback(ma_device* dev, void* pOutput, const void* /*pInput*/, ma_uint32 frameCount) {
auto* impl = static_cast<MiniaudioBackend::Impl*>(dev->pUserData);
float* out = static_cast<float*>(pOutput);
- if (impl && impl->render) impl->render(out, static_cast<int32_t>(frameCount));
+ const int32_t ch = static_cast<int32_t>(dev->playback.channels);
+ if (impl && impl->render) impl->stage.process(impl->render, out, ch, static_cast<int32_t>(frameCount));
else
- std::memset(pOutput, 0, static_cast<size_t>(frameCount) * 2 * sizeof(float));
+ std::memset(pOutput, 0, static_cast<size_t>(frameCount) * static_cast<size_t>(ch) * sizeof(float));
}
MiniaudioBackend::MiniaudioBackend() : impl_(new Impl()) {}
@@ -51,7 +56,9 @@ bool MiniaudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
ma_device_config c = ma_device_config_init(ma_device_type_playback);
c.playback.pDeviceID = haveId && useId ? &id : nullptr; // NULL = system default
c.playback.format = ma_format_f32;
- c.playback.channels = 2; // interleaved stereo, like the engine
+ // 0 = the device's own channel count (specs/089), so Main and Cue can land on any
+ // output pair. WASAPI shared mode reports its mix format's channels.
+ c.playback.channels = 0;
c.playback.shareMode = share;
c.sampleRate = cfg.sampleRate > 0.0 ? static_cast<ma_uint32>(cfg.sampleRate) : 0;
c.dataCallback = &dataCallback;
@@ -102,12 +109,21 @@ bool MiniaudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
}
// Negotiated values, read back after init.
+ impl_->channels = std::min<int32_t>(static_cast<int32_t>(impl_->device.playback.channels), kMaxOutputChannels);
sampleRate_ = impl_->device.sampleRate;
bufferFrames_ = static_cast<int32_t>(impl_->device.playback.internalPeriodSizeInFrames);
running_ = true;
return true;
}
+int32_t MiniaudioBackend::outputChannelCount() const {
+ return running_ ? impl_->channels : 0;
+}
+
+void MiniaudioBackend::setOutputRouting(const OutputRouting& r) {
+ impl_->stage.setRouting(r);
+}
+
void MiniaudioBackend::stop() {
if (impl_->deviceInited) {
ma_device_uninit(&impl_->device);
diff --git a/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.h b/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.h
index 29ef39ed..b816260d 100644
--- a/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.h
+++ b/src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.h
@@ -25,6 +25,8 @@ class MiniaudioBackend final : public AudioBackend {
bool isRunning() const override { return running_; }
bool exclusiveFallback() const override { return exclusiveFallback_; }
bool silentFallback() const override { return silentFallback_; }
+ int32_t outputChannelCount() const override;
+ void setOutputRouting(const OutputRouting& r) override;
// Opaque to callers; public so the file-local data callback can reach it.
struct Impl;
diff --git a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h
index 1bdf1f6b..7bb74c8a 100644
--- a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h
+++ b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h
@@ -3,8 +3,8 @@
//
// CoreAudio output backend (macOS). Uses a HALOutput AudioUnit so a specific
// device, sample rate and buffer size can be requested (M7-1); with a zeroed
-// BackendConfig it falls back to the system default output device. Pulls
-// interleaved stereo float from the engine's render callback.
+// BackendConfig it falls back to the system default output device. Opens every output
+// channel of the device and places the engine's Main and Cue buses on them (specs/089).
#pragma once
@@ -24,6 +24,10 @@ class CoreAudioBackend final : public AudioBackend {
void setXrunCallback(std::function<void()> cb) override { onXrun_ = std::move(cb); }
bool isRunning() const override { return running_; }
void* ioWorkgroup() const override;
+ int32_t outputChannelCount() const override;
+ std::string outputChannelName(int32_t index) const override;
+ void setOutputRouting(const OutputRouting& r) override;
+ int32_t pollDeviceEvent() override;
// Opaque to callers; public so the file-local CoreAudio callback can reach it.
struct Impl;
diff --git a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm
index 7c5e199f..5af66312 100644
--- a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm
+++ b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm
@@ -9,6 +9,8 @@
#import <CoreAudio/CoreAudio.h>
#include <os/workgroup.h>
+#include <atomic>
+#include <string>
#include <vector>
namespace nota {
@@ -16,6 +18,10 @@ namespace nota {
struct CoreAudioBackend::Impl {
AudioUnit outputUnit = nullptr;
RenderCallback render; // copied from the backend on start()
+ OutputStage stage; // Main/Cue scratch + routing (specs/089)
+ int32_t channels = 2; // client format = every device output (≤ 64)
+ std::vector<std::string> names; // the device's output channel names
+ std::atomic<bool> deviceDied{false}; // set by the alive listener, read by pollDeviceEvent
AudioDeviceID device = kAudioObjectUnknown; // for the overload listener (M7-8)
void* workgroup = nullptr; // os_workgroup_t of the device's IO thread (retained)
};
@@ -31,16 +37,31 @@ static OSStatus overloadProc(AudioObjectID, UInt32, const AudioObjectPropertyAdd
return noErr;
}
+// The device went away (unplugged, aggregate torn down): ask the app to re-apply, which
+// re-opens the default device and re-resolves Main/Cue against its outputs (specs/089).
+static const AudioObjectPropertyAddress kAliveAddr{
+ kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain};
+
+static OSStatus aliveProc(AudioObjectID dev, UInt32, const AudioObjectPropertyAddress*, void* refCon) {
+ auto* impl = static_cast<CoreAudioBackend::Impl*>(refCon);
+ UInt32 alive = 1;
+ UInt32 size = sizeof(alive);
+ if (AudioObjectGetPropertyData(dev, &kAliveAddr, 0, nullptr, &size, &alive) == noErr && !alive)
+ impl->deviceDied.store(true, std::memory_order_relaxed);
+ return noErr;
+}
+
// Real-time audio callback. Runs on the CoreAudio thread — no allocation,
-// no locks, no I/O (AR-6). We set up an interleaved stereo float stream, so
-// ioData has a single buffer of frames*2.
+// no locks, no I/O (AR-6). The client format is interleaved float with one channel per
+// device output, so ioData has a single buffer of frames × channels; the engine renders
+// Main and Cue into the stage's stereo scratch and the stage places them.
static OSStatus renderCallback(void* inRefCon, AudioUnitRenderActionFlags* /*ioActionFlags*/,
const AudioTimeStamp* /*inTimeStamp*/, UInt32 /*inBusNumber*/, UInt32 inNumberFrames, AudioBufferList* ioData) {
auto* impl = static_cast<CoreAudioBackend::Impl*>(inRefCon);
float* out = static_cast<float*>(ioData->mBuffers[0].mData);
- if (impl->render) impl->render(out, static_cast<int32_t>(inNumberFrames));
+ if (impl->render) impl->stage.process(impl->render, out, impl->channels, static_cast<int32_t>(inNumberFrames));
else
- for (UInt32 i = 0; i < inNumberFrames * 2; ++i) out[i] = 0.0f;
+ for (UInt32 i = 0; i < inNumberFrames * static_cast<UInt32>(impl->channels); ++i) out[i] = 0.0f;
return noErr;
}
@@ -135,6 +156,8 @@ bool CoreAudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
// Listen for device overloads/dropouts (M7-8); non-fatal, off the RT thread.
impl_->device = dev;
AudioObjectAddPropertyListener(dev, &kOverloadAddr, &overloadProc, this);
+ impl_->deviceDied.store(false, std::memory_order_relaxed);
+ AudioObjectAddPropertyListener(dev, &kAliveAddr, &aliveProc, impl_);
}
// Apply requested nominal sample rate + buffer size on the device (best effort).
@@ -155,7 +178,32 @@ bool CoreAudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
AudioObjectSetPropertyData(dev, &a, 0, nullptr, sizeof(bf), &bf);
}
- // Interleaved stereo 32-bit float client format. Run the graph at the
+ // One client channel per device output (specs/089), so Main and Cue can land on any pair;
+ // a stereo device stays at 2, as before. The unit's output-scope format is the device's.
+ impl_->channels = 2;
+ {
+ AudioStreamBasicDescription hw{};
+ UInt32 hsz = sizeof(hw);
+ if (AudioUnitGetProperty(impl_->outputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &hw,
+ &hsz) == noErr &&
+ hw.mChannelsPerFrame > 0)
+ impl_->channels = std::min<int32_t>(static_cast<int32_t>(hw.mChannelsPerFrame), kMaxOutputChannels);
+ }
+ impl_->names.assign(static_cast<size_t>(impl_->channels), std::string{});
+ for (int32_t c = 0; c < impl_->channels && dev != kAudioObjectUnknown; ++c) {
+ AudioObjectPropertyAddress na{
+ kAudioObjectPropertyElementName, kAudioDevicePropertyScopeOutput, static_cast<UInt32>(c + 1)};
+ CFStringRef name = nullptr;
+ UInt32 nsz = sizeof(name);
+ if (AudioObjectHasProperty(dev, &na) && AudioObjectGetPropertyData(dev, &na, 0, nullptr, &nsz, &name) == noErr &&
+ name) {
+ char buf[256] = {};
+ if (CFStringGetCString(name, buf, sizeof(buf), kCFStringEncodingUTF8)) impl_->names[static_cast<size_t>(c)] = buf;
+ CFRelease(name);
+ }
+ }
+
+ // Interleaved 32-bit float client format. Run the graph at the
// requested rate (falling back to the device's nominal rate) so no hidden
// sample-rate conversion sneaks in.
double clientSr = cfg.sampleRate > 0.0 ? cfg.sampleRate : deviceNominalSampleRate(dev);
@@ -166,7 +214,7 @@ bool CoreAudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
fmt.mFormatID = kAudioFormatLinearPCM;
fmt.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked;
fmt.mFramesPerPacket = 1;
- fmt.mChannelsPerFrame = 2;
+ fmt.mChannelsPerFrame = static_cast<UInt32>(impl_->channels);
fmt.mBitsPerChannel = 32;
fmt.mBytesPerFrame = fmt.mChannelsPerFrame * sizeof(float);
fmt.mBytesPerPacket = fmt.mBytesPerFrame;
@@ -235,6 +283,7 @@ bool CoreAudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
void CoreAudioBackend::stop() {
if (impl_->device != kAudioObjectUnknown) {
AudioObjectRemovePropertyListener(impl_->device, &kOverloadAddr, &overloadProc, this);
+ AudioObjectRemovePropertyListener(impl_->device, &kAliveAddr, &aliveProc, impl_);
impl_->device = kAudioObjectUnknown;
}
if (impl_->outputUnit) {
@@ -254,6 +303,23 @@ void* CoreAudioBackend::ioWorkgroup() const {
return impl_->workgroup;
}
+int32_t CoreAudioBackend::outputChannelCount() const {
+ return running_ ? impl_->channels : 0;
+}
+
+std::string CoreAudioBackend::outputChannelName(int32_t index) const {
+ if (index < 0 || index >= static_cast<int32_t>(impl_->names.size())) return {};
+ return impl_->names[static_cast<size_t>(index)];
+}
+
+void CoreAudioBackend::setOutputRouting(const OutputRouting& r) {
+ impl_->stage.setRouting(r);
+}
+
+int32_t CoreAudioBackend::pollDeviceEvent() {
+ return impl_->deviceDied.exchange(false, std::memory_order_relaxed) ? 1 : 0;
+}
+
} // namespace nota
#endif // defined(__APPLE__)
diff --git a/src/native/nota.engine/src/audio_io/windows/AsioBackend.cpp b/src/native/nota.engine/src/audio_io/windows/AsioBackend.cpp
index 3c5abac7..e739fde1 100644
--- a/src/native/nota.engine/src/audio_io/windows/AsioBackend.cpp
+++ b/src/native/nota.engine/src/audio_io/windows/AsioBackend.cpp
@@ -8,6 +8,8 @@
#include "AsioDriverList.h"
#include "ComAsioDriver.h"
+#include <algorithm>
+
namespace nota::asio {
AsioSession& sharedAsioSession() {
@@ -71,6 +73,20 @@ void AsioBackend::stop() {
if (s.state() != AsioSession::State::Closed) s.close();
}
+int32_t AsioBackend::outputChannelCount() const {
+ return std::min<int32_t>(static_cast<int32_t>(sharedAsioSession().channels(false).size()), kMaxOutputChannels);
+}
+
+std::string AsioBackend::outputChannelName(int32_t index) const {
+ const auto& ch = sharedAsioSession().channels(false);
+ if (index < 0 || index >= static_cast<int32_t>(ch.size())) return {};
+ return ch[static_cast<size_t>(index)].name;
+}
+
+void AsioBackend::setOutputRouting(const OutputRouting& r) {
+ sharedAsioSession().setOutputRouting(r);
+}
+
double AsioBackend::sampleRate() const {
return sharedAsioSession().sampleRate();
}
diff --git a/src/native/nota.engine/src/audio_io/windows/AsioBackend.h b/src/native/nota.engine/src/audio_io/windows/AsioBackend.h
index b67964c7..c2921175 100644
--- a/src/native/nota.engine/src/audio_io/windows/AsioBackend.h
+++ b/src/native/nota.engine/src/audio_io/windows/AsioBackend.h
@@ -43,6 +43,9 @@ class AsioBackend final : public AudioBackend {
const char* fallbackReason() const override { return reason_.c_str(); }
bool sampleRateRefused() const override;
double deviceChangedRate() const override;
+ int32_t outputChannelCount() const override;
+ std::string outputChannelName(int32_t index) const override;
+ void setOutputRouting(const OutputRouting& r) override;
private:
std::function<void()> xrun_;
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index 8bdd3bd5..10ea7d43 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -91,7 +91,7 @@ bool Engine::start() {
audioFallbackReason_ = "a plug-in stopped responding inside the audio callback — restart Nota";
return false;
}
- bool ok = backend_->start([this](float* out, int32_t n) { render(out, n); }, bc);
+ bool ok = backend_->start([this](float* main, float* cue, int32_t n) { render(main, cue, n); }, bc);
if (!ok && activeSystem_ == AudioSystem::Asio) {
// FR-011: a missing, busy or broken ASIO driver never leaves Nota silent — run WASAPI
// on the system default device and say why. The saved choice stays ASIO, so the next
@@ -103,9 +103,10 @@ bool Engine::start() {
BackendConfig fallback;
fallback.device = resolveAudioDeviceId(std::string{}, /*inputScope=*/false);
backend_->setXrunCallback([this] { notifyXrun(); });
- ok = backend_->start([this](float* out, int32_t n) { render(out, n); }, fallback);
+ ok = backend_->start([this](float* main, float* cue, int32_t n) { render(main, cue, n); }, fallback);
}
monitorSharedClock_.store(ok && backend_->sharesInputClock(), std::memory_order_relaxed);
+ if (ok && outputRoutingSet_) backend_->setOutputRouting(outputRouting_); // specs/089
if (ok) {
transport_.setSampleRate(backend_->sampleRate());
propagateSampleRate(backend_->sampleRate()); // re-prepare every node (incl. master + racks) at the new rate
@@ -266,6 +267,29 @@ void Engine::setAsioDriver(const std::string& clsid, const std::string& name) {
config_.asioDriverClsid = clsid;
config_.asioDriverName = name;
}
+bool Engine::setOutputRouting(const OutputRouting& r) {
+ if (!validRouting(r)) return false;
+ outputRouting_ = r;
+ outputRoutingSet_ = true;
+ if (backend_) backend_->setOutputRouting(r);
+ return true;
+}
+
+int32_t Engine::outputChannelCount() const {
+ if (outputTestChannels_ > 0) return outputTestChannels_;
+ return backend_ ? std::min(backend_->outputChannelCount(), kMaxOutputChannels) : 0;
+}
+
+std::string Engine::outputChannelName(int32_t index) const {
+ if (outputTestChannels_ > 0)
+ return index >= 0 && index < outputTestChannels_ ? "Test " + std::to_string(index + 1) : std::string{};
+ return backend_ ? backend_->outputChannelName(index) : std::string{};
+}
+
+int32_t Engine::outputRoutingState() const {
+ return resolveRouting(outputRouting_, outputChannelCount()).flags;
+}
+
void Engine::setAsioPair(bool input, int32_t firstChannel) {
if (!asioSupported()) return;
(input ? config_.asioInputPair : config_.asioOutputPair) = std::max(0, firstChannel);
@@ -691,6 +715,7 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {
nt->setMute(t.mute());
nt->setSolo(t.solo());
nt->setArmed(t.armed());
+ nt->setCue(t.cue()); // Cue (specs/089)
nt->setReturnIndex(t.returnIndex()); // M6-1
nt->setGroupId(t.groupId()); // group membership
nt->setRecordInputSource(t.recordInputSource()); // internal record routing
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index cc687cc6..26727fe3 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -62,7 +62,21 @@ class Engine {
double sampleRate() const { return backend_ ? backend_->sampleRate() : 0.0; }
bool isRunning() const { return backend_ && backend_->isRunning(); }
// One block through the device callback's path, without a device (tests/benchmarks).
- void renderDeviceBlock(float* out, int32_t frames) { render(out, frames); }
+ void renderDeviceBlock(float* out, int32_t frames) { render(out, nullptr, frames); }
+ // The same with the Cue bus (specs/089): `cue` may be null.
+ void renderDeviceBlock(float* main, float* cue, int32_t frames) { render(main, cue, frames); }
+
+ // --- output routing (specs/089) ---
+ // Main and Cue's output pairs. Kept across device restarts and pushed to every backend
+ // after it starts; takes effect on the next callback. False for an invalid routing.
+ bool setOutputRouting(const OutputRouting& r);
+ const OutputRouting& outputRouting() const { return outputRouting_; }
+ // The open device's output channels (a test device when one is set).
+ int32_t outputChannelCount() const;
+ std::string outputChannelName(int32_t index) const;
+ // kRoutingMainFellBack | kRoutingCueUnavailable for the routing against the open device.
+ int32_t outputRoutingState() const;
+ void setTestOutputDevice(int32_t channels) { outputTestChannels_ = std::max(0, channels); } // tests
// --- audio device settings (M7-1) ---
// The chosen device/rate/buffer live in config_ (persisted to audio.json)
@@ -395,6 +409,22 @@ class Engine {
void setTrackPan(int32_t trackId, float p);
void setTrackMute(int32_t trackId, bool m);
void setTrackSolo(int32_t trackId, bool s);
+ // Cue (specs/089): any number of tracks; their post-device, pre-fader signals sum into the
+ // Cue bus at the Cue level. Never changes Main. trackCue: 1 / 0, -1 for no such track.
+ bool setTrackCue(int32_t trackId, bool on);
+ int32_t trackCue(int32_t trackId) const;
+ void setCueVolume(float gain) { cueGain_.store(std::clamp(gain, 0.0f, 2.0f), std::memory_order_relaxed); }
+ float cueVolume() const { return cueGain_.load(std::memory_order_relaxed); }
+ void cueMeter(float& pkL, float& pkR, float& rmsL, float& rmsR) const {
+ pkL = cuePeakL_.load(std::memory_order_relaxed);
+ pkR = cuePeakR_.load(std::memory_order_relaxed);
+ rmsL = cueRmsL_.load(std::memory_order_relaxed);
+ rmsR = cueRmsR_.load(std::memory_order_relaxed);
+ }
+ // Where the metronome and count-in clicks go (0 Main, 1 Cue, 2 both) and their level.
+ void setClickDestination(int32_t d) { clickDest_.store(std::clamp(d, 0, 2), std::memory_order_relaxed); }
+ int32_t clickDestination() const { return clickDest_.load(std::memory_order_relaxed); }
+ void setClickVolume(float gain) { clickGain_.store(std::clamp(gain, 0.0f, 2.0f), std::memory_order_relaxed); }
int32_t trackCount() const;
// Track lifecycle (context menu). duplicateTrack deep-copies everything
// (mixer, sends, clips, session, automation, fresh instrument/devices —
@@ -1511,8 +1541,8 @@ class Engine {
private:
// audio thread
- void render(float* out, int32_t numFrames);
- void processBlock(float* out, int32_t numFrames);
+ void render(float* main, float* cue, int32_t numFrames);
+ void processBlock(float* out, float* cue, int32_t numFrames); // cue may be null (offline)
// Mixes the graph for one contiguous musical segment (no loop wrap inside):
// automation + solo + send buses + track pass + return pass. processBlock
// splits a block at loop boundaries and calls this per segment.
@@ -1562,7 +1592,9 @@ class Engine {
bool renderCountIn(float* out, int32_t numFrames, double spb);
void endCountIn(); // audio thread: drop the count-in state and reopen the capture gate
void launchCountInSlot(); // audio thread: start the Session slot a count-in was waiting for
- void renderClick(float* out, int32_t i, int clickLen, double sr); // one sample of the click voice
+ void renderClick(float* out, float* cue, int32_t i, int clickLen, double sr, int32_t dest,
+ float gain); // one sample of the click voice, Main and/or Cue
+ void finishCue(float* cue, int32_t numFrames); // Cue level, safety net, meter (specs/089)
void renderTone(float* out, int32_t numFrames);
void applyAutomation(Graph* g, double beat); // M9: eval lanes -> target atomics
@@ -2372,6 +2404,16 @@ class Engine {
void updateCaptureLayout(); // recompute + publish when the channel set changed
int32_t inputTestChannels_ = 0; // tests: a pretend device's channel count (0 = none)
std::vector<std::string> inputChannelNames_; // the device's channels when last open / probed
+ OutputRouting outputRouting_; // specs/089: Main / Cue pairs (control thread)
+ // Cue bus (specs/089). cueSeg_ points into the block's Cue buffer at the current segment
+ // (null when the caller renders no Cue: offline, export, plain device-block tests).
+ float* cueSeg_ = nullptr;
+ std::atomic<float> cueGain_{1.0f};
+ std::atomic<int32_t> clickDest_{0};
+ std::atomic<float> clickGain_{1.0f};
+ std::atomic<float> cuePeakL_{0.0f}, cuePeakR_{0.0f}, cueRmsL_{0.0f}, cueRmsR_{0.0f};
+ bool outputRoutingSet_ = false; // until set, ASIO keeps its saved output pair
+ int32_t outputTestChannels_ = 0; // tests: a pretend output device
bool inputProbed_ = false; // probed since the input device last changed
void rememberInputChannels();
void forgetInputChannels();
@@ -2555,6 +2597,7 @@ class Engine {
Track* t = nullptr;
bool audible = false, capturing = false, feeding = false, toMix = false;
bool monitoring = false, frozenActive = false, sessionActive = false;
+ bool cue = false, cueOnly = false; // Cue tap (specs/089); cueOnly: silent in Main
bool postTapMuted = false; // sidechain tap muted with its source leaf (vocoder key)
bool eligible = false; // worker-capable DSP, no shared writers
LeafPath path = LeafPath::Skip;
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index 68894f17..ff262014 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -937,7 +937,7 @@ void Engine::closeCtlRange(MidiClip& clip, int32_t ctl, double atLocal, double s
// --- audio thread ----------------------------------------------------------
-void Engine::render(float* out, int32_t numFrames) {
+void Engine::render(float* out, float* cue, int32_t numFrames) {
// Counted before the suspend check (both seq_cst, paired with start()): once start() has
// suspended rendering and seen the count at zero, no render can be inside the graph.
rendersInFlight_.fetch_add(1, std::memory_order_seq_cst);
@@ -948,12 +948,13 @@ void Engine::render(float* out, int32_t numFrames) {
// start() is still re-preparing the nodes on the control thread: output silence.
if (renderSuspended_.load(std::memory_order_seq_cst)) {
std::fill(out, out + static_cast<size_t>(numFrames) * 2, 0.0f);
+ if (cue) std::fill(cue, cue + static_cast<size_t>(numFrames) * 2, 0.0f);
return;
}
dsp::ScopedNoDenormals noDenormals;
const auto t0 = std::chrono::steady_clock::now();
deviceBlock_ = true; // a deadline, whatever the gap since the last block
- processBlock(out, numFrames);
+ processBlock(out, cue, numFrames);
// DSP load = render time / block budget, smoothed (Phase 11). Live-device
// path only; renderOffline stays untimed.
const double sr = sampleRate();
@@ -992,7 +993,7 @@ void Engine::renderOffline(float* out, int32_t frames) {
preparedSR_ = sr;
}
deviceBlock_ = false; // export/freeze: no deadline, every render thread
- processBlock(out, frames);
+ processBlock(out, nullptr, frames); // no Cue in a bounce (specs/089 FR-016)
}
void Engine::endCountIn() {
@@ -2203,13 +2204,14 @@ void Engine::triggerPassReplace() {
replaceUpTo_.store(recordPass_, std::memory_order_release);
}
-void Engine::processBlock(float* out, int32_t numFrames) {
+void Engine::processBlock(float* out, float* cue, int32_t numFrames) {
// Every audio-thread read of recordSlotPlayer_ happens inside this block (count-in launch,
// live MIDI, capture), so this scope keeps the player it points at alive.
const SnapshotHistory<SessionPlayer>::RenderScope recordSlotScope(recordSlotHist_);
const SnapshotHistory<SessionLaneSlots>::RenderScope laneSlotScope(laneSlotsHist_); // specs/086
drainCommands();
for (int32_t i = 0; i < numFrames * 2; ++i) out[i] = 0.0f;
+ if (cue) std::fill(cue, cue + static_cast<size_t>(numFrames) * 2, 0.0f);
const double sr = transport_.sampleRate();
const double spb = transport_.samplesPerBeat();
@@ -2300,6 +2302,7 @@ void Engine::processBlock(float* out, int32_t numFrames) {
}
chaseNotes_ = chase;
if (chase) articulationChaseStart_ = segStart;
+ cueSeg_ = cue ? cue + done * 2 : nullptr; // this segment of the Cue bus (specs/089)
if (g && sr > 0.0) mixGraph(g, out + done * 2, seg, segStart, playing, spb);
chaseNotes_ = chase = seamOffs_ = false;
bool countInDone = false;
@@ -2394,6 +2397,34 @@ void Engine::processBlock(float* out, int32_t numFrames) {
deviceBlock_ && backend_ ? std::max(numFrames, backend_->bufferFrames()) : numFrames);
masterRmsL_.store(numFrames ? static_cast<float>(std::sqrt(msqL / numFrames)) : 0.0f, std::memory_order_relaxed);
masterRmsR_.store(numFrames ? static_cast<float>(std::sqrt(msqR / numFrames)) : 0.0f, std::memory_order_relaxed);
+ cueSeg_ = nullptr;
+ if (cue) finishCue(cue, numFrames);
+}
+
+// The Cue bus after every tap and click (specs/089): the Cue level, the same NaN / clip
+// safety net as Main, and the Cue meter. Never through the master chain or master fader.
+void Engine::finishCue(float* cue, int32_t numFrames) {
+ const float gain = cueGain_.load(std::memory_order_relaxed);
+ float pkL = 0.0f, pkR = 0.0f;
+ double sqL = 0.0, sqR = 0.0;
+ for (int32_t i = 0; i < numFrames; ++i) {
+ float l = cue[i * 2] * gain;
+ float r = cue[i * 2 + 1] * gain;
+ if (!std::isfinite(l)) l = 0.0f;
+ if (!std::isfinite(r)) r = 0.0f;
+ l = std::clamp(l, -1.0f, 1.0f);
+ r = std::clamp(r, -1.0f, 1.0f);
+ cue[i * 2] = l;
+ cue[i * 2 + 1] = r;
+ pkL = std::max(pkL, std::fabs(l));
+ pkR = std::max(pkR, std::fabs(r));
+ sqL += l * (double)l;
+ sqR += r * (double)r;
+ }
+ cuePeakL_.store(pkL, std::memory_order_relaxed);
+ cuePeakR_.store(pkR, std::memory_order_relaxed);
+ cueRmsL_.store(numFrames ? static_cast<float>(std::sqrt(sqL / numFrames)) : 0.0f, std::memory_order_relaxed);
+ cueRmsR_.store(numFrames ? static_cast<float>(std::sqrt(sqR / numFrames)) : 0.0f, std::memory_order_relaxed);
}
// Fill `dst` with what a monitoring audio track hears: the hardware input pulled for this
@@ -2638,6 +2669,10 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
Track* grpT[kMaxGroups];
int32_t grpId[kMaxGroups], grpParent[kMaxGroups], grpDepth[kMaxGroups];
bool grpMuteE[kMaxGroups], grpSoloE[kMaxGroups];
+ // Cue (specs/089): grpFeedMute is the mute that silences a group's children — a cued
+ // group's own mute isn't one (its children keep feeding its Cue tap; the group alone
+ // stays out of its parent). Without cued groups it equals grpMuteE.
+ bool grpFeedMute[kMaxGroups];
int numGroups = 0, maxDepth = 0;
for (auto& tptr : g->tracks) {
if (tptr->type() != TrackType::Group || numGroups >= kMaxGroups) continue;
@@ -2652,18 +2687,21 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
if (grpId[i] == id) return i;
return -1;
};
+ const bool cueOn = cueSeg_ != nullptr;
for (int i = 0; i < numGroups; ++i) {
- bool m = false, s = false;
+ bool m = false, s = false, fm = false;
int depth = 0;
for (int32_t a = grpId[i]; a >= 0;) { // walk self + ancestor groups
int si = slotOf(a);
if (si < 0) break;
m |= grpT[si]->mute();
+ fm |= grpT[si]->mute() && !(cueOn && grpT[si]->cue());
s |= grpT[si]->solo();
++depth;
a = grpParent[si];
}
grpMuteE[i] = m;
+ grpFeedMute[i] = fm;
grpSoloE[i] = s;
grpDepth[i] = depth;
if (depth > maxDepth) maxDepth = depth;
@@ -2673,7 +2711,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
auto leafMute = [&](Track& t) {
if (t.mute()) return true;
int s = slotOf(t.groupId());
- return s >= 0 && grpMuteE[s];
+ return s >= 0 && grpFeedMute[s];
};
auto leafSolo = [&](Track& t) {
if (t.solo()) return true;
@@ -2731,6 +2769,9 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// in place of its clips — hardware input this segment, or the source track's
// post-fader tap from the previous one. Master (-1) would feed back: silent.
const bool monitoring = !frozenActive && !capturing && t.type() == TrackType::Audio && t.monitor();
+ // Cue (specs/089): a cued track is heard in Cue before its fader, mute and solo, so a
+ // muted or solo-gated one still renders — for the Cue tap only.
+ const bool cueing = cueOn && t.cue();
// 0) Session view (M5-2): apply quantized launch/stop; a playing slot
// overrides this track's arrangement content. Requests apply on every track,
@@ -2752,7 +2793,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
sessionActive =
!frozenActive && !capturing && !monitoring && sp->playing.load(std::memory_order_relaxed) >= 0;
}
- if (!audible && !capturing && !feeding && !keying) {
+ if (!audible && !capturing && !feeding && !keying && !cueing) {
// Silent this block, but a playing slot keeps its place in the loop, so it is
// in time again when the track is unmuted (and follow actions keep counting).
if (sessionActive) {
@@ -2779,6 +2820,8 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
w.toMix = audible || capturing; // false: render only for the taps
w.postTapMuted = postTapMuted;
w.monitoring = monitoring;
+ w.cue = cueing;
+ w.cueOnly = cueing && !audible && !capturing && !feeding && !keying;
w.frozenActive = frozenActive;
w.sessionActive = sessionActive;
@@ -2820,6 +2863,13 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
if (w.sends[b] != 0.0f) w.anySend = true;
}
w.tapRec = (recSrc > 0 && t.id() == recSrc); // internal resampling source
+ // Under a group that is muted but cued (specs/089) the leaf only feeds that group's
+ // Cue tap: its sends, sidechain tap and record tap stay as silent as the mute made them.
+ if (destSlot >= 0 && grpMuteE[destSlot] && !grpFeedMute[destSlot]) {
+ w.anySend = false;
+ w.tapRec = false;
+ w.postTapMuted = true;
+ }
// Parallel eligibility is an instance's processing contract, not its
// hosted identity: independent audited VST3 adapters own their state
@@ -3009,6 +3059,14 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
freezeCursor_ = c;
}
+ // 2d) Cue tap (specs/089): post-device, pre-fader, pre-mute/solo.
+ if (w.cue) simd_audio::addStereoScaled(cueSeg_, post, 1.0f, 1.0f, frames);
+ if (w.cueOnly) { // heard only in Cue: no fader, sends, taps or meter for Main
+ t.setMeter(0, 0, 0, 0);
+ t.stereoFold(0.0, 0.0, 0.0, frames, stereoA);
+ continue;
+ }
+
// 3) Channel fader + equal-power pan into the master mix + sends.
const float vol = t.volume();
const float pan = std::clamp(t.pan(), -1.0f, 1.0f);
@@ -3118,15 +3176,17 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
for (int gi = 0; gi < numGroups; ++gi) {
if (grpDepth[gi] != depth) continue;
Track& t = *grpT[gi];
- if (grpMuteE[gi]) {
+ if (grpFeedMute[gi]) {
t.setMeter(0, 0, 0, 0);
continue;
} // muted group (or muted ancestor)
std::copy_n(groupBus_[gi].data(), frames * 2, scratch_.data()); // this group's summed children
{
- const int32_t preSlot = routeSlotForTrack(t.id()); // Phase D pre-FX tap
- if (preSlot >= 0)
+ // Phase D pre-FX tap. A group muted in Main (rendered only for Cue) keeps it
+ // silent, as its mute always did: Cue must not change a sidechain key.
+ const int32_t preSlot = routeSlotForTrack(t.id());
+ if (preSlot >= 0 && !grpMuteE[gi])
simd_audio::addStereoScaled(
routeBusPreNext_[preSlot].data(), scratch_.data(), 1.0f, 1.0f, frames);
}
@@ -3139,6 +3199,16 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
// PDC left verbatim (see renderLeafDsp note).
if (t.pdc) t.pdc->process(scratch_.data(), frames);
+ // Cue tap (specs/089): the bus after its devices, before its fader and mute.
+ if (cueOn && t.cue()) simd_audio::addStereoScaled(cueSeg_, scratch_.data(), 1.0f, 1.0f, frames);
+ if (t.mute()) { // muted but cued: heard in Cue only
+ t.setMeter(0, 0, 0, 0);
+ continue;
+ }
+ // Muted only through a cued ancestor: still folds into the parent's bus, so the
+ // ancestor's Cue tap hears it; the ancestor keeps it out of Main. Its own
+ // sidechain and record taps stay silent, as the mute made them.
+ const bool cueFeedOnly = grpMuteE[gi];
const float vol = t.volume();
const float pan = std::clamp(t.pan(), -1.0f, 1.0f);
@@ -3150,8 +3220,8 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
const int pslot = slotOf(grpParent[gi]);
float* dest = pslot >= 0 ? groupBus_[pslot].data() : out; // parent group bus, else master
const int32_t routeSlot = routeSlotForTrack(t.id());
- float* route = routeSlot >= 0 ? routeBusNext_[routeSlot].data() : nullptr;
- const bool tapRec = (recSrc > 0 && t.id() == recSrc);
+ float* route = routeSlot >= 0 && !cueFeedOnly ? routeBusNext_[routeSlot].data() : nullptr;
+ const bool tapRec = (recSrc > 0 && t.id() == recSrc) && !cueFeedOnly;
float pkL = 0.0f, pkR = 0.0f;
double sqL = 0.0, sqR = 0.0;
int64_t recDropped = 0;
@@ -3172,8 +3242,10 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
}
if (recDropped) inputDroppedFrames_.fetch_add(recDropped, std::memory_order_relaxed);
- t.setMeter(
- pkL, pkR, static_cast<float>(std::sqrt(sqL / frames)), static_cast<float>(std::sqrt(sqR / frames)));
+ if (cueFeedOnly) t.setMeter(0, 0, 0, 0); // silent in Main, as its muted ancestor makes it
+ else
+ t.setMeter(pkL, pkR, static_cast<float>(std::sqrt(sqL / frames)),
+ static_cast<float>(std::sqrt(sqR / frames)));
}
// Pass 2: return buses -> device chain -> master (M6-1). Exempt from the
@@ -3183,7 +3255,8 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
Track& t = *tptr;
if (t.type() != TrackType::Return) continue;
const int32_t bus = t.returnIndex();
- if (bus < 0 || bus >= numReturns || t.mute()) {
+ const bool returnCue = cueOn && t.cue();
+ if (bus < 0 || bus >= numReturns || (t.mute() && !returnCue)) {
t.setMeter(0, 0, 0, 0);
t.stereoFold(0, 0, 0, frames, stereoA);
continue;
@@ -3191,8 +3264,9 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
std::copy_n(returnBus_[bus].data(), frames * 2, scratch_.data());
{
- const int32_t preSlot = routeSlotForTrack(t.id()); // Phase D pre-FX tap
- if (preSlot >= 0)
+ // Phase D pre-FX tap; a muted return rendered only for Cue keeps it silent.
+ const int32_t preSlot = routeSlotForTrack(t.id());
+ if (preSlot >= 0 && !t.mute())
simd_audio::addStereoScaled(routeBusPreNext_[preSlot].data(), scratch_.data(), 1.0f, 1.0f, frames);
}
for (auto& d : t.devices)
@@ -3204,6 +3278,13 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
// PDC left verbatim (see renderLeafDsp note).
if (t.pdc) t.pdc->process(scratch_.data(), frames);
+ // Cue tap (specs/089): the return after its devices, before its fader and mute.
+ if (returnCue) simd_audio::addStereoScaled(cueSeg_, scratch_.data(), 1.0f, 1.0f, frames);
+ if (t.mute()) { // muted but cued: heard in Cue only
+ t.setMeter(0, 0, 0, 0);
+ t.stereoFold(0, 0, 0, frames, stereoA);
+ continue;
+ }
const float vol = t.volume();
const float pan = std::clamp(t.pan(), -1.0f, 1.0f);
@@ -3275,12 +3356,20 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
}
-void Engine::renderClick(float* out, int32_t i, int clickLen, double sr) {
+// The click goes to Main, Cue or both (specs/089), at kMetroGain × the click level. A click
+// to Cue skips the master chain and fader; without a Cue buffer (offline) it writes nothing.
+void Engine::renderClick(float* out, float* cue, int32_t i, int clickLen, double sr, int32_t dest, float gain) {
if (clickRemaining_ <= 0) return;
const float env = static_cast<float>(clickRemaining_) / static_cast<float>(clickLen);
- const float s = static_cast<float>(std::sin(clickPhase_)) * env * kMetroGain;
- out[i * 2] += s;
- out[i * 2 + 1] += s;
+ const float s = static_cast<float>(std::sin(clickPhase_)) * env * kMetroGain * gain;
+ if (dest != 1) {
+ out[i * 2] += s;
+ out[i * 2 + 1] += s;
+ }
+ if (dest != 0 && cue) {
+ cue[i * 2] += s;
+ cue[i * 2 + 1] += s;
+ }
clickPhase_ += kTwoPi * clickFreq_ / sr;
if (clickPhase_ >= kTwoPi) clickPhase_ -= kTwoPi;
--clickRemaining_;
@@ -3292,6 +3381,8 @@ void Engine::renderMetronome(float* out, int32_t numFrames, double blockStartSam
const double spb = transport_.samplesPerBeat();
const int beatsPerBar = transport_.beatsPerBar();
const int clickLen = static_cast<int>(0.03 * sr);
+ const int32_t dest = clickDest_.load(std::memory_order_relaxed);
+ const float gain = clickGain_.load(std::memory_order_relaxed);
for (int32_t i = 0; i < numFrames; ++i) {
const double p = blockStartSamples + i;
@@ -3304,7 +3395,7 @@ void Engine::renderMetronome(float* out, int32_t numFrames, double blockStartSam
clickFreq_ = (beat % beatsPerBar == 0) ? 1500.0 : 1000.0;
}
}
- renderClick(out, i, clickLen, sr);
+ renderClick(out, cueSeg_, i, clickLen, sr, dest, gain);
}
}
@@ -3315,6 +3406,8 @@ bool Engine::renderCountIn(float* out, int32_t numFrames, double spb) {
const int beatsPerBar = std::max(1, transport_.beatsPerBar());
const int clickLen = static_cast<int>(0.03 * sr);
const double inc = spb > 0.0 ? 1.0 / spb : 0.0;
+ const int32_t dest = clickDest_.load(std::memory_order_relaxed);
+ const float gain = clickGain_.load(std::memory_order_relaxed);
for (int32_t i = 0; i < numFrames; ++i) {
if (countInPos_ < countInTotal_) {
@@ -3326,7 +3419,7 @@ bool Engine::renderCountIn(float* out, int32_t numFrames, double spb) {
clickFreq_ = (beat % beatsPerBar == 0) ? 1500.0 : 1000.0;
}
}
- renderClick(out, i, clickLen, sr);
+ renderClick(out, cueSeg_, i, clickLen, sr, dest, gain);
countInPos_ += inc;
}
uiCountIn_.store(std::max(0.0, countInTotal_ - countInPos_), std::memory_order_relaxed);
diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
index 644fb9f5..8ec8334e 100644
--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
@@ -1007,6 +1007,16 @@ void Engine::setTrackMute(int32_t id, bool m) {
void Engine::setTrackSolo(int32_t id, bool s) {
if (auto t = findTrackAuthoring(id)) t->setSolo(s);
}
+bool Engine::setTrackCue(int32_t id, bool on) {
+ auto t = findTrackAuthoring(id);
+ if (!t) return false;
+ t->setCue(on);
+ return true;
+}
+int32_t Engine::trackCue(int32_t id) const {
+ auto t = findTrackAuthoring(id);
+ return t ? (t->cue() ? 1 : 0) : -1;
+}
int32_t Engine::trackCount() const {
return static_cast<int32_t>(authoring_->tracks.size());
}
@@ -3671,6 +3681,7 @@ std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId, b
nt->setMute(src.mute());
nt->setSolo(src.solo());
nt->setArmed(src.armed());
+ nt->setCue(src.cue());
nt->setReturnIndex(src.returnIndex());
nt->setGroupId(src.groupId()); // keep membership on duplicate (paste resets to top-level)
nt->setRecordInputSource(src.recordInputSource());
diff --git a/src/native/nota.engine/src/engine/Track.h b/src/native/nota.engine/src/engine/Track.h
index 87a86372..1bbe3d95 100644
--- a/src/native/nota.engine/src/engine/Track.h
+++ b/src/native/nota.engine/src/engine/Track.h
@@ -214,12 +214,15 @@ class Track {
void setMute(bool m) { mute_.store(m, std::memory_order_relaxed); }
void setSolo(bool s) { solo_.store(s, std::memory_order_relaxed); }
void setArmed(bool a) { armed_.store(a, std::memory_order_relaxed); }
+ // In Cue (specs/089): the track's post-device, pre-fader signal also goes to the Cue bus.
+ void setCue(bool c) { cue_.store(c, std::memory_order_relaxed); }
float volume() const { return volume_.load(std::memory_order_relaxed); }
float pan() const { return pan_.load(std::memory_order_relaxed); }
bool mute() const { return mute_.load(std::memory_order_relaxed); }
bool solo() const { return solo_.load(std::memory_order_relaxed); }
bool armed() const { return armed_.load(std::memory_order_relaxed); }
+ bool cue() const { return cue_.load(std::memory_order_relaxed); }
// MIDI → CV (modular editor): the track's latest MIDI-derived control values,
// updated from the post-FX note stream each block (see computeInstrumentMidi) and
@@ -441,6 +444,7 @@ class Track {
std::atomic<bool> mute_{false};
std::atomic<bool> solo_{false};
std::atomic<bool> armed_{false};
+ std::atomic<bool> cue_{false};
std::atomic<float> midiVel_{0.0f}; // MIDI→CV: last note-on velocity 0..1
std::atomic<float> midiNote_{0.0f}; // last note pitch, normalized 0..1
std::atomic<int32_t> midiHeld_{0}; // held-note count (gate = >0)
diff --git a/tests/Nota.SmokeTest/AuroraTableTests.cs b/tests/Nota.SmokeTest/AuroraTableTests.cs
index e3540b41..827989f3 100644
--- a/tests/Nota.SmokeTest/AuroraTableTests.cs
+++ b/tests/Nota.SmokeTest/AuroraTableTests.cs
@@ -354,7 +354,7 @@ internal static class AuroraTableTests
wavs = Directory.GetFiles(Path.Combine(bundle, "samples")).Select(Path.GetFileName).OfType<string>().ToArray();
}
var json = JsonNode.Parse(File.ReadAllText(Path.Combine(bundle, ProjectService.ManifestName)))!;
- yield return (json["formatVersion"]?.GetValue<int>() == 31 && warnCount == 0, $"aurora tables: projects save as format 31 ({json["formatVersion"]})");
+ yield return (json["formatVersion"]?.GetValue<int>() >= 31 && warnCount == 0, $"aurora tables: projects save as format 31 or later ({json["formatVersion"]})");
yield return (wavs.Length == 2, $"aurora tables: two Auroras with the same table share one file ({wavs.Length} tables for 3 slots)");
{
using var e = new NotaEngine();
@@ -402,9 +402,9 @@ internal static class AuroraTableTests
var w = ProjectService.Apply(doc, e2, old);
int id = TrackIds(e2)[0];
e2.TryGetAuroraTableInfo(id, 0, out var v0);
- yield return (doc.FormatVersion == 31 && w.Count == 0 && v0.Frames == 0
+ yield return (doc.FormatVersion == ProjectService.CurrentFormatVersion && w.Count == 0 && v0.Frames == 0
&& e2.GetPluginState(id, -1).Length == Params * 4,
- $"aurora tables: a v27 project loads unchanged and migrates to 31 ({doc.FormatVersion})");
+ $"aurora tables: a v27 project loads unchanged and migrates to the current format ({doc.FormatVersion})");
}
}
diff --git a/tests/Nota.SmokeTest/CueOutputTests.cs b/tests/Nota.SmokeTest/CueOutputTests.cs
new file mode 100644
index 00000000..fd716819
--- /dev/null
+++ b/tests/Nota.SmokeTest/CueOutputTests.cs
@@ -0,0 +1,444 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Main and Cue on separate output pairs (specs/089, #483). Output placement is driven
+// without a device through nota_audio_scatter_test — the same code every backend runs —
+// and the routing state through a pretend output device. A Cue pair the device lacks must
+// go silent and never fold into Main.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class CueOutputTests
+{
+ private const int Frames = 64;
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ foreach (var r in Placement()) yield return r;
+ foreach (var r in Fallbacks()) yield return r;
+ foreach (var r in RoutingValidation()) yield return r;
+ foreach (var r in SetupRules()) yield return r;
+ string wav = Wav();
+ try
+ {
+ foreach (var r in CueTaps(wav)) yield return r;
+ foreach (var r in CueBuses(wav)) yield return r;
+ foreach (var r in MainUntouched(wav)) yield return r;
+ }
+ finally { try { File.Delete(wav); } catch { } }
+ foreach (var r in Click()) yield return r;
+ foreach (var r in SavedCue()) yield return r;
+ }
+
+ // ---- the project (US6) -------------------------------------------------------------
+
+ private static IEnumerable<(bool, string)> SavedCue()
+ {
+ var transport = new TransportState(120.0, 1.0, false, false);
+ string bundle = Path.Combine(Path.GetTempPath(), $"nota-cue-{Guid.NewGuid():N}.nota");
+ try
+ {
+ int[] cuedIdx;
+ {
+ using var e = new NotaEngine();
+ int a = e.AddAudioTrack(), b = e.AddAudioTrack(), c = e.AddAudioTrack();
+ e.SetTrackCue(a, true);
+ e.SetTrackCue(c, true);
+ e.CueVolume = 0.5f;
+ ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), bundle, e);
+ cuedIdx = new[] { 0, 2 };
+ _ = b;
+ }
+ var json = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(Path.Combine(bundle, ProjectService.ManifestName)))!;
+ yield return (json["formatVersion"]?.GetValue<int>() == 32, $"projects save as format 32 ({json["formatVersion"]})");
+ {
+ using var e = new NotaEngine();
+ var w = ProjectService.Apply(ProjectService.Load(bundle), e, bundle);
+ var ids = Enumerable.Range(0, e.TrackCount).Select(i => e.TryGetTrackInfo(i, out var ti) ? ti.Id : -1).ToArray();
+ bool cues = ids.Length == 3 && ids.Select((id, i) => e.GetTrackCue(id) == cuedIdx.Contains(i)).All(x => x);
+ yield return (cues && Math.Abs(e.CueVolume - 0.5f) < 1e-6f && w.Count == 0,
+ "save → reopen restores the cued tracks and the Cue level (SC-006)");
+ }
+ // A v31 project: nothing in Cue, unity Cue level.
+ var node = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(Path.Combine(bundle, ProjectService.ManifestName)))!;
+ node["formatVersion"] = 31;
+ node["mixer"]?.AsObject().Remove("cueVolume");
+ foreach (var t in node["tracks"]!.AsArray()) t!.AsObject().Remove("cue");
+ File.WriteAllText(Path.Combine(bundle, ProjectService.ManifestName), node.ToJsonString());
+ {
+ using var e = new NotaEngine();
+ e.CueVolume = 0.25f; // whatever the session had before
+ var doc = ProjectService.Load(bundle);
+ ProjectService.Apply(doc, e, bundle);
+ bool none = Enumerable.Range(0, e.TrackCount).All(i => e.TryGetTrackInfo(i, out var ti) && !e.GetTrackCue(ti.Id));
+ yield return (doc.FormatVersion == 32 && none && Math.Abs(e.CueVolume - 1f) < 1e-6f,
+ "a v31 project opens with nothing in Cue at unity Cue level");
+ }
+ }
+ finally { try { Directory.Delete(bundle, true); } catch { } }
+ }
+
+ // ---- the Cue bus (US2) -------------------------------------------------------------
+
+ private const int Rate = 44100, Block = 512;
+ private const float Amp = 0.2f;
+ private static readonly double ClipRms = Amp / Math.Sqrt(2);
+
+ private static string Wav()
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"nota-cue-{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] = Amp * (float)Math.Sin(2 * Math.PI * 441 * i / Rate);
+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, x.Length / 2);
+ return path;
+ }
+
+ private static NotaEngine Engine()
+ {
+ var e = new NotaEngine();
+ e.SetBpm(120);
+ return e;
+ }
+
+ // Prepare the nodes, roll from bar 1 and render `frames` as the device does: Main and Cue.
+ private static (float[] Main, float[] Cue) Play(NotaEngine e, int frames, bool cue = true)
+ {
+ e.RenderOffline(new float[2], 1, Rate);
+ e.Seek(0.0);
+ e.Play();
+ var main = new float[frames * 2];
+ var cueAll = new float[frames * 2];
+ var b = new float[Block * 2];
+ var c = new float[Block * 2];
+ for (int done = 0; done < frames; done += Block)
+ {
+ int n = Math.Min(Block, frames - done);
+ if (cue) e.RenderDeviceBlockCue(b, c, n); else e.RenderDeviceBlock(b, n);
+ Array.Copy(b, 0, main, done * 2, n * 2);
+ if (cue) Array.Copy(c, 0, cueAll, done * 2, n * 2);
+ }
+ return (main, cueAll);
+ }
+
+ // RMS over the second half (past any start-up ramp).
+ private static double Rms(float[] st)
+ {
+ double s = 0;
+ int from = st.Length / 2;
+ for (int i = from; i < st.Length; i++) s += st[i] * (double)st[i];
+ return Math.Sqrt(s / Math.Max(1, st.Length - from));
+ }
+
+ private static bool Near(double a, double b, double rel = 0.03) => Math.Abs(a - b) <= rel * Math.Max(Math.Abs(b), 1e-9);
+
+ private static IEnumerable<(bool, string)> CueTaps(string wav)
+ {
+ const int N = Rate / 2;
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ e.SetTrackCue(t, true);
+ e.SetTrackVolume(t, 0f);
+ var (main, cue) = Play(e, N);
+ yield return (e.GetTrackCue(t), "a track can be put in Cue");
+ yield return (Near(Rms(cue), ClipRms) && Rms(main) == 0, $"Cue is pre-fader: fader down, Cue still {Rms(cue):F4} (clip {ClipRms:F4})");
+ }
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ e.SetTrackCue(t, true);
+ e.SetTrackMute(t, true);
+ var (main, cue) = Play(e, N);
+ yield return (Near(Rms(cue), ClipRms) && Rms(main) == 0, "Cue is pre-mute: a muted cued track is heard in Cue only");
+ }
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ int other = e.AddAudioTrack();
+ e.SetTrackSolo(other, true);
+ e.SetTrackCue(t, true);
+ var (main, cue) = Play(e, N);
+ yield return (Near(Rms(cue), ClipRms) && Rms(main) == 0, "Cue is pre-solo: a solo elsewhere doesn't silence Cue");
+ }
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ int d = e.AddBuiltinDevice(t, 4); // Utility
+ e.DeviceSetParam(t, d, 0, 6.0206f); // Gain ×2
+ e.SetTrackCue(t, true);
+ var (_, cue) = Play(e, N);
+ yield return (Near(Rms(cue), 2 * ClipRms, 0.05), $"Cue is post-devices: +6 dB Utility doubles Cue ({Rms(cue):F4})");
+ }
+ {
+ using var e = Engine();
+ int a = e.AddAudioTrack(), b = e.AddAudioTrack(), c = e.AddAudioTrack();
+ e.AddAudioClip(a, wav, 0.0);
+ e.AddAudioClip(b, wav, 0.0);
+ e.AddAudioClip(c, wav, 0.0);
+ e.SetTrackCue(a, true);
+ e.SetTrackCue(b, true);
+ var (_, cue) = Play(e, N);
+ yield return (Near(Rms(cue), 2 * ClipRms), "two cued tracks sum in Cue; an uncued one stays out");
+ }
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ e.SetTrackCue(t, true);
+ e.CueVolume = 0.5f;
+ var (_, cue) = Play(e, N);
+ yield return (Near(Rms(cue), 0.5 * ClipRms), "the Cue level scales Cue");
+ yield return (Math.Abs(e.CueMeter().PeakL - Amp * 0.5f) < 0.01f, $"the Cue meter reads after the Cue level ({e.CueMeter().PeakL:F3})");
+ }
+ }
+
+ private static IEnumerable<(bool, string)> CueBuses(string wav)
+ {
+ {
+ // The dry-vocal case of #483: a monitored input in Cue, muted in Main — the performer
+ // hears it, the audience doesn't. Heard with the transport stopped, like monitoring.
+ using var e = Engine();
+ int mon = e.AddAudioTrack();
+ e.SetTrackRecordInput(mon, 0);
+ e.SetTrackMonitor(mon, true);
+ e.SetTrackMute(mon, true);
+ e.SetTrackCue(mon, true);
+ e.RenderOffline(new float[2], 1, Rate);
+ var sine = new float[8192 * 2];
+ for (int i = 0; i < 8192; i++) sine[i * 2] = sine[i * 2 + 1] = 0.5f * MathF.Sin(2f * MathF.PI * 440f * i / Rate);
+ e.PushMonitorFramesForTest(sine, 8192);
+ var m = new float[2048 * 2];
+ var c = new float[2048 * 2];
+ e.RenderDeviceBlockCue(m, c, 2048);
+ yield return (Rms(c) > 0.1 && m.All(v => v == 0f), $"a monitored input in Cue, muted in Main: heard only in Cue ({Rms(c):F3})");
+ }
+ const int N = Rate / 2;
+ {
+ // A muted, cued group: its children feed its Cue tap; nothing reaches Main — not
+ // even through a child's send to a return.
+ using var e = Engine();
+ int grp = e.AddGroupTrack();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ e.SetTrackGroup(t, grp);
+ int ret = e.AddReturnTrack();
+ e.SetTrackSend(t, 0, 1f);
+ e.SetTrackMute(grp, true);
+ e.SetTrackCue(grp, true);
+ var (main, cue) = Play(e, N);
+ yield return (Rms(cue) > 0.5 * ClipRms && Rms(main) == 0,
+ $"a muted cued group: its children in Cue ({Rms(cue):F4}), Main silent, sends too");
+ e.SetTrackCue(grp, false);
+ var (main2, _) = Play(e, N);
+ yield return (Rms(main2) == 0, "…and the group's mute still silences everything once it leaves Cue");
+ _ = ret;
+ }
+ {
+ // Review on #566: a group nested in a muted, cued group still reaches its Cue tap.
+ using var e = Engine();
+ int outer = e.AddGroupTrack();
+ int inner = e.AddGroupTrack();
+ e.SetTrackGroup(inner, outer);
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ e.SetTrackGroup(t, inner);
+ e.SetTrackMute(outer, true);
+ e.SetTrackCue(outer, true);
+ var (main, cue) = Play(e, N);
+ yield return (Rms(cue) > 0.5 * ClipRms && Rms(main) == 0,
+ $"a nested group under a muted cued group reaches its Cue ({Rms(cue):F4}), Main silent");
+ }
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ int ret = e.AddReturnTrack();
+ e.SetTrackSend(t, 0, 1f);
+ e.SetTrackMute(t, false);
+ e.SetTrackMute(ret, true);
+ e.SetTrackCue(ret, true);
+ var (_, cue) = Play(e, N);
+ yield return (Rms(cue) > 0.1 * ClipRms, "a muted cued return is heard in Cue");
+ }
+ }
+
+ // SC-001: whatever Cue does, Main is bit-identical to a render without it.
+ private static IEnumerable<(bool, string)> MainUntouched(string wav)
+ {
+ const int N = Rate / 2;
+ float[] Run(Action<NotaEngine, int> setup, bool cue)
+ {
+ using var e = Engine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ e.SetTrackVolume(t, 0.7f);
+ setup(e, t);
+ return Play(e, N, cue).Main;
+ }
+ var reference = Run((_, _) => { }, cue: false);
+ var cued = Run((e, t) => { e.SetTrackCue(t, true); e.CueVolume = 2f; }, cue: true);
+ var quiet = Run((e, t) => { e.SetTrackCue(t, true); e.CueVolume = 0f; }, cue: true);
+ yield return (reference.SequenceEqual(cued) && reference.SequenceEqual(quiet),
+ "Main is bit-identical with the track in Cue at any Cue level (SC-001)");
+ using (var e = Engine())
+ {
+ // A bounce has no Cue bus: a click sent to Cue never lands in the file (FR-016).
+ e.AddAudioTrack();
+ e.SetMetronome(true);
+ e.ClickDestination = ClickDestination.Cue;
+ e.RenderOffline(new float[2], 1, Rate);
+ e.Seek(0.0);
+ e.Play();
+ var b = new float[Rate * 2];
+ e.RenderOffline(b, Rate);
+ yield return (b.All(v => v == 0f), "a bounce never carries a click sent to Cue");
+ }
+ }
+
+ // ---- the click (US3) ---------------------------------------------------------------
+
+ private static IEnumerable<(bool, string)> Click()
+ {
+ const int N = Rate; // two beats at 120 bpm
+ float[] Main(int dest, bool metronome, out float[] cue, float gain = 1f)
+ {
+ using var e = Engine();
+ e.AddAudioTrack();
+ e.SetMetronome(metronome);
+ e.ClickDestination = (ClickDestination)dest;
+ e.SetClickVolume(gain);
+ var r = Play(e, N);
+ cue = r.Cue;
+ return r.Main;
+ }
+ var off = Main(0, false, out _);
+ var toMain = Main(0, true, out var cueWhenMain);
+ var toCue = Main(1, true, out var cueWhenCue);
+ var both = Main(2, true, out var cueWhenBoth);
+ double Peak(float[] x) => x.Length == 0 ? 0 : x.Max(v => Math.Abs((double)v));
+ yield return (Peak(toMain) > 0.1 && Peak(cueWhenMain) == 0, "click → Main: in Main, not in Cue (as before)");
+ yield return (toCue.SequenceEqual(off) && Peak(cueWhenCue) > 0.1, "click → Cue: Main identical to metronome off (SC-002)");
+ int First(float[] x) { for (int i = 0; i < x.Length; i++) if (Math.Abs(x[i]) > 1e-6f) return i / 2; return -1; }
+ yield return (First(both) >= 0 && First(both) == First(cueWhenBoth), $"click → Main + Cue: same sample in both (SC-003, frame {First(both)})");
+ Main(1, true, out var quiet, gain: 0f);
+ yield return (Peak(quiet) == 0, "click level 0 silences the click");
+ }
+
+ private static float[] Stereo(float l, float r)
+ {
+ var b = new float[Frames * 2];
+ for (int i = 0; i < Frames; i++) { b[i * 2] = l; b[i * 2 + 1] = r; }
+ return b;
+ }
+
+ // Every frame of device channel `ch` equals `v`.
+ private static bool Channel(float[] dev, int channels, int ch, float v)
+ {
+ for (int i = 0; i < Frames; i++)
+ if (MathF.Abs(dev[i * channels + ch] - v) > 1e-6f) return false;
+ return true;
+ }
+
+ private static IEnumerable<(bool, string)> Placement()
+ {
+ using var e = new NotaEngine();
+ var main = Stereo(0.25f, -0.25f);
+ var cue = Stereo(0.5f, -0.5f);
+
+ yield return (e.SetOutputRouting(0, 2, 2, 2), "Main 1/2 + Cue 3/4 is a valid routing");
+ var dev = new float[Frames * 4];
+ var st = e.ScatterOutputsForTest(main, cue, dev, 4, Frames);
+ yield return (st == OutputRoutingState.Ok, "4 outputs: routing state ok");
+ yield return (Channel(dev, 4, 0, 0.25f) && Channel(dev, 4, 1, -0.25f), "Main lands on outputs 1/2");
+ yield return (Channel(dev, 4, 2, 0.5f) && Channel(dev, 4, 3, -0.5f), "Cue lands on outputs 3/4");
+
+ yield return (e.SetOutputRouting(2, 2, 0, 2), "Main 3/4 + Cue 1/2 is valid");
+ dev = new float[Frames * 4];
+ e.ScatterOutputsForTest(main, cue, dev, 4, Frames);
+ yield return (Channel(dev, 4, 2, 0.25f) && Channel(dev, 4, 0, 0.5f), "Main can leave 1/2");
+
+ e.SetOutputRouting(0, 2, -1, 2);
+ dev = new float[Frames * 6];
+ e.ScatterOutputsForTest(main, cue, dev, 6, Frames);
+ bool othersZero = true;
+ for (int c = 2; c < 6; c++) othersZero &= Channel(dev, 6, c, 0f);
+ yield return (othersZero, "no Cue output: every other output is zero");
+
+ e.SetOutputRouting(0, 2, 4, 1); // Cue on output 5 alone
+ dev = new float[Frames * 5];
+ e.ScatterOutputsForTest(main, Stereo(0.2f, 0.6f), dev, 5, Frames);
+ yield return (Channel(dev, 5, 4, 0.4f), "a single-channel Cue gets the L+R sum halved");
+ }
+
+ private static IEnumerable<(bool, string)> Fallbacks()
+ {
+ using var e = new NotaEngine();
+ var main = Stereo(0.25f, 0.25f);
+ var cue = Stereo(0.5f, 0.5f);
+
+ // Cue 3/4 on a stereo device: silent, never in Main (FR-014, SC-004).
+ e.SetOutputRouting(0, 2, 2, 2);
+ var dev = new float[Frames * 2];
+ var st = e.ScatterOutputsForTest(main, cue, dev, 2, Frames);
+ yield return (st == OutputRoutingState.CueUnavailable, "stereo device: Cue reported unavailable");
+ yield return (Channel(dev, 2, 0, 0.25f) && Channel(dev, 2, 1, 0.25f), "stereo device: Main is exactly Main");
+
+ // Main 3/4 on a stereo device falls back to 1/2 (FR-015).
+ e.SetOutputRouting(2, 2, -1, 2);
+ dev = new float[Frames * 2];
+ st = e.ScatterOutputsForTest(main, cue, dev, 2, Frames);
+ yield return (st == OutputRoutingState.MainFellBack && Channel(dev, 2, 0, 0.25f), "missing Main pair falls back to 1/2");
+
+ // Main 3/4, Cue 1/2 on a stereo device: Main takes 1/2, Cue goes silent.
+ e.SetOutputRouting(2, 2, 0, 2);
+ dev = new float[Frames * 2];
+ st = e.ScatterOutputsForTest(main, cue, dev, 2, Frames);
+ yield return (st == (OutputRoutingState.MainFellBack | OutputRoutingState.CueUnavailable) && Channel(dev, 2, 0, 0.25f),
+ "fallback Main wins over a Cue on its pair");
+
+ // The engine's own state against a pretend device.
+ e.SetOutputRouting(0, 2, 2, 2);
+ e.SetTestOutputDevice(4);
+ yield return (e.AudioOutputChannelCount() == 4 && e.GetOutputRoutingState() == OutputRoutingState.Ok,
+ "4-output test device: routing ok");
+ e.SetTestOutputDevice(2);
+ yield return (e.GetOutputRoutingState() == OutputRoutingState.CueUnavailable, "2-output test device: Cue unavailable");
+ e.SetTestOutputDevice(0);
+ }
+
+ private static IEnumerable<(bool, string)> RoutingValidation()
+ {
+ using var e = new NotaEngine();
+ yield return (!e.SetOutputRouting(1, 2, -1, 2), "a stereo pair must start on an odd output (1/2, 3/4 …)");
+ yield return (!e.SetOutputRouting(0, 3, -1, 2), "width is 1 or 2");
+ yield return (!e.SetOutputRouting(0, 2, 0, 2), "Main and Cue can't share a pair");
+ yield return (!e.SetOutputRouting(0, 2, 1, 1), "Cue can't take one of Main's outputs");
+ yield return (e.SetOutputRouting(0, 2, -1, 2), "no Cue output is valid");
+ yield return (e.SetOutputRouting(0, 1, 1, 1), "two single outputs side by side are valid");
+ }
+
+ private static IEnumerable<(bool, string)> SetupRules()
+ {
+ var s = OutputSetups.Default();
+ yield return (s.MainFirst == 1 && s.MainWidth == 2 && !s.HasCue && s.Click == ClickDestination.Main,
+ "a new device: Main 1/2, no Cue, click to Main");
+ yield return (OutputSetups.Default(asioPair: 2).MainFirst == 3, "ASIO's saved output pair seeds Main (FR-005)");
+ var c = OutputSetups.WithCue(s, 3, 2);
+ yield return (c.CueFirst == 3, "Cue on 3/4");
+ yield return (OutputSetups.WithCue(c, 1, 2).CueFirst == 3, "Cue on Main's pair is refused");
+ yield return (OutputSetups.WithMain(c, 3, 2).CueFirst is null, "moving Main onto Cue drops Cue");
+ var k = OutputSetups.WithClick(c, ClickDestination.Cue, 0);
+ yield return (OutputSetups.WithCue(k, null, 2).Click == ClickDestination.Main, "no Cue output sends the click back to Main");
+ yield return (OutputSetups.WithClick(s, ClickDestination.Cue, 0).Click == ClickDestination.Main,
+ "the click can't go to a Cue that isn't set");
+ yield return (OutputSetups.ClickGain(OutputSetups.WithClick(s, ClickDestination.Main, -60)) == 0f
+ && MathF.Abs(OutputSetups.ClickGain(s) - 1f) < 1e-6f, "click level: −60 dB silent, 0 dB unity");
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index f0d4029f..acc3352b 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -836,6 +836,14 @@ if (args.Length >= 1 && args[0] == "--session-input")
Console.WriteLine(failures == 0 ? "SESSION INPUT PASSED" : $"SESSION INPUT FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Main / Cue outputs alone (fast iteration): `--cue`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--cue")
+{
+ Console.WriteLine("-- cue output --");
+ foreach (var (ok, label) in CueOutputTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "CUE PASSED" : $"CUE FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Multi-channel input alone (fast iteration): `--multi-input`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--multi-input")
{
@@ -15679,6 +15687,8 @@ Console.WriteLine("-- multi-channel input --");
foreach (var (ok, label) in MultiInputRecordTests.Run()) Check(ok, label);
foreach (var (ok, label) in MultiInputSessionTests.Run()) Check(ok, label);
foreach (var (ok, label) in MidiInputFilterTests.Run()) Check(ok, label);
+Console.WriteLine("-- cue output --");
+foreach (var (ok, label) in CueOutputTests.Run()) Check(ok, label);
Console.WriteLine("-- rc envelopes: live sustain --");
foreach (var (ok, label) in RcEnvSustainTests.Run()) Check(ok, label);
Console.WriteLine("-- group link --");