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/mixer v2 (#28)

Egor Khindikaynen3f9dae2d422d
diff --git a/.specify/bugs/linux-plugin-black-window/assessment.md b/.specify/bugs/linux-plugin-black-window/assessment.md
new file mode 100644
index 00000000..8edcf776
--- /dev/null
+++ b/.specify/bugs/linux-plugin-black-window/assessment.md
@@ -0,0 +1,122 @@
+# Bug Assessment: Linux — hosted plugins show a black window and make no sound
+
+- **Slug**: linux-plugin-black-window
+- **Created**: 2026-10-14
+- **Source**: pasted text (maintainer report)
+- **Verdict**: valid (symptoms match the code; fix still to be verified on Linux)
+- **Severity**: high
+
+## Report (verbatim or summarized)
+
+> Нашел проблемы на линуксе. Качаю любой плагин из реестра, ни один не работает. Просто окно с логотипом X,
+> черный фон, звука нет.
+
+(Linux: every plugin installed from the registry fails. The editor window shows only an X logo on a black
+background, and there's no sound.)
+
+## Symptom
+
+On Linux, any VST3 installed through Get Plug-ins loads: a track is created and an editor window opens. The window
+is never painted, though. It stays black, with the X server's default "X" icon/decoration. The plugin also produces
+no audio. Expected: the plugin's GUI draws and notes play, as on macOS and Windows.
+
+## Reproduction
+
+1. Linux x64 build of Nota (current `develop` / latest release). [NEEDS CLARIFICATION: distro, X11 vs Wayland
+ (XWayland), Nota version]
+2. Get Plug-ins → install any registry plugin (e.g. Surge XT) → it's scanned and listed.
+3. Add it as an instrument and open its editor → a black window appears.
+4. Play notes from the piano roll / keyboard → silence. [NEEDS CLARIFICATION: silent even with the editor never
+ opened? Is a locally built/installed (non-registry) VST3 also affected? Expected yes.]
+
+## Suspected Code Paths
+
+- `src/native/nota.engine/pluginhost/PluginHost.cpp:9-13`: the design note states the integration
+ premise: *"JUCE piggybacks on the already-running CFRunLoop"* (Avalonia's NSApp on macOS). On Windows the same
+ works implicitly, because JUCE's hidden message HWND is pumped by Avalonia's Win32 loop. **On Linux JUCE has its
+ own event loop** (an internal fd/poll loop over the X11 display fd and its message pipe). Something must call
+ `MessageManager::runDispatchLoop` / `dispatchNextMessageOnSystemQueue`. Nothing in Nota does.
+- `PluginHost.cpp:921-930` `instantiate()`: creates `ScopedJuceInitialiser_GUI` and the plugin on the Avalonia UI
+ thread, then returns. No dispatching anywhere afterwards (grep: no `runDispatchLoop`, `dispatchNextMessage`,
+ or a pump C ABI; no managed timer calling one).
+- `PluginHost.cpp:416-449` `PluginEditorWindow`: a `DocumentWindow` with `juce::Colours::black` background. The X
+ window is created and mapped, but the Expose/paint events and JUCE's repaint messages are never dispatched →
+ exactly "black window with an X". The `JUCE_MAC` keyboard monitor has no Linux counterpart either (secondary).
+- `src/native/nota.engine/CMakeLists.txt:192-197`: `JUCE_MODAL_LOOPS_PERMITTED=0`, so
+ `runDispatchLoopUntil()` isn't available. Any pump has to use `dispatchNextMessageOnSystemQueue(true)`.
+
+## Root Cause Hypothesis
+
+The JUCE message loop never runs on Linux. **High confidence for the black window.** Nota relies on the host app's
+native run loop to drive JUCE. That holds on macOS (shared CFRunLoop) and on Windows (shared Win32 message queue).
+On Linux, Avalonia's X11 backend runs its own loop on its own `Display*` connection, so JUCE's X11 connection and
+message pipe are never serviced. **Medium confidence for the silence.** VST3 plugins on Linux (JUCE-built ones in
+particular: most of the registry) don't spin their own message thread. They register timers and fds with the host
+through `Steinberg::Linux::IRunLoop`, which JUCE's host implements on the same never-pumped loop. Their
+`AsyncUpdater`/`Timer`/`callAsync` work never fires: deferred init, patch loading, `prepareToPlay`-follow-ups. The
+plugin therefore processes silence even though the audio thread calls `processBlock`. It matches "any plugin" and
+"Linux only". This is not tied to the registry. A locally installed VST3 should behave the same.
+
+## Proposed Remediation
+
+**Preferred**: add a pump to the C ABI and drive it from the UI thread on Linux only.
+- Native: `extern "C" NOTA_API void nota_pluginhost_pump(void)`. It is a no-op unless `JUCE_LINUX` and
+ `g_juceGui != nullptr`; otherwise it loops `juce::dispatchNextMessageOnSystemQueue(true)` until it returns false
+ (with a small per-call cap so a chatty plugin can't starve Avalonia). Declare it in `nota_engine.h`.
+- Managed: P/Invoke in `NativeMethods.PluginHost.cs` and a wrapper in `NotaEngine.PluginHost.cs`. In the app, on
+ `OperatingSystem.IsLinux()`, start an Avalonia `DispatcherTimer` (~10 ms, `DispatcherPriority.Background` or
+ higher) once the first plugin is instantiated (or at startup). That keeps JUCE on the same thread that already
+ owns the `MessageManager` (instantiate/open/close all happen on the UI thread), so no threading model changes.
+- Also Linux: drop the `[NSApp …]`-only foreground handling assumptions. Check that
+ `setAlwaysOnTop`/`toFront` behave, and that computer-keyboard MIDI reaches the editor (on Windows JUCE key events
+ reach it natively; on Linux they should too once events are dispatched).
+
+**Alternatives**:
+- *Dedicated JUCE message thread on Linux* (what JUCE plugin wrappers do: `MessageThread` +
+ `runDispatchLoop`). No 10 ms timer latency, but every `instantiate`/`openEditor`/`clone`/state call must be
+ marshalled to that thread, and Xlib must be thread-safe (`XInitThreads`) with two X connections in one process.
+ More invasive; consider it only if timer pumping proves janky.
+- *Hook JUCE's fds into Avalonia's loop*. Avalonia's X11 platform has no public fd-watch API; brittle.
+
+**Files likely to change**:
+- `src/native/nota.engine/pluginhost/PluginHost.cpp`
+- `src/native/nota.engine/include/nota/nota_engine.h` (new export)
+- `src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs`
+- `src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs`
+- `src/managed/Nota.App/…` (where the engine/plugin host is wired up, e.g. `MainWindow.axaml.cs`)
+- `CHANGELOG.md` ([Unreleased] → Fixed)
+
+**Tests to add or update**:
+- Smoke/native test (Linux CI): instantiate the in-tree `NotaPentad` test plugin, call `nota_pluginhost_pump`
+ (must not crash and must return even with no display activity), render a note and assert non-silent output.
+- Managed unit test that the pump timer is only started on Linux (or that the call is a safe no-op elsewhere).
+- Manual Linux check: Surge XT (or another registry plugin) editor paints, responds to mouse, and notes sound.
+
+## Risks & Considerations
+
+- Re-entrancy: dispatching JUCE messages inside an Avalonia timer tick could re-enter Nota through plugin callbacks
+ (`audioProcessorParameterChanged`, host-notify). Those already only touch atomics. Keep it that way.
+- Headless/CI Linux with no `DISPLAY`: `ScopedJuceInitialiser_GUI` and the pump must stay safe. The pump must be a
+ no-op before GUI init.
+- Wayland sessions: JUCE is X11-only and needs XWayland. Worth a clear message if `DISPLAY` is unset.
+- Two Xlib connections in one process (Avalonia's + JUCE's), on the same thread with the timer approach. That is
+ fine; it gets riskier with the dedicated-thread alternative.
+- Audio thread is untouched. No allocation/locking added there (CONTRIBUTING audio-thread rules).
+
+## Clarifications (2026-10-14, reporter)
+
+- **Silent even when the editor is never opened.** So the silence isn't a side effect of a frozen editor. It is
+ consistent with plugin init/async work waiting on the never-pumped loop (the IRunLoop half of the hypothesis).
+ `/speckit-bug-test` must still confirm audio once the pump lands. If it stays silent, look at the audio path next
+ (bus layout / `pluginChannelPtrs`, `prepareToPlay`).
+- **The editor window can't be closed**, only by quitting Nota. That fits the root cause: the close-button
+ ClientMessage (`WM_DELETE_WINDOW`) is an X event JUCE never dispatches, so `closeButtonPressed()` never runs.
+ The black window, the dead close button and the silence all have one cause.
+- **Wayland session, any distro.** JUCE is X11-only, so it runs through XWayland while Avalonia may be on native
+ Wayland or XWayland. The pump fix applies either way. Verify on a Wayland session (GNOME/KDE) specifically.
+- Non-registry plugin: not checked. Expected to behave the same, because nothing in the hosting path depends on
+ where the plugin came from.
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: Nota version. Assumed current release / `develop`.]
diff --git a/.specify/bugs/linux-plugin-black-window/fix.md b/.specify/bugs/linux-plugin-black-window/fix.md
new file mode 100644
index 00000000..7a3d286a
--- /dev/null
+++ b/.specify/bugs/linux-plugin-black-window/fix.md
@@ -0,0 +1,84 @@
+# Bug Fix: Linux — hosted plugins show a black window and make no sound
+
+- **Slug**: linux-plugin-black-window
+- **Fixed**: 2026-10-14
+- **Assessment**: ./assessment.md
+- **Status**: applied (not yet verified on Linux)
+
+## Summary
+
+Added a C ABI entry `nota_pluginhost_pump()` that services JUCE's Linux event loop. The app ticks it from a 10 ms
+Avalonia `DispatcherTimer` on Linux only. With the loop serviced, plugin editors get their X11 events (paint, close
+button), and hosted plugins run their timers and async work again, which they hand to our `IRunLoop` when they are
+created.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/native/nota.engine/pluginhost/PluginHost.cpp` | modified | `nota_pluginhost_pump()`. On Linux/BSD it loops `juce::detail::dispatchNextMessageOnSystemQueue(true)` (non-blocking `poll(0)`), at most 64 batches per call. It is a no-op before JUCE GUI init and off the message thread. It returns 0 on macOS/Windows. |
+| `src/native/nota.engine/include/nota/nota_engine.h` | modified | Declares and documents the export. `nota_exports.txt` / `.map` already export `nota_*`. |
+| `src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs` | modified | `PluginHostPump` P/Invoke. |
+| `src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs` | modified | `NotaEngine.PumpPluginHost()`. |
+| `src/managed/Nota.App/App.axaml.cs` | modified | On `OperatingSystem.IsLinux()`, starts a 10 ms `DispatcherTimer` (Normal priority) that calls the pump. |
+| `tests/Nota.SmokeTest/Program.cs` | added test | "plugin host pump" check. |
+| `CHANGELOG.md` | modified | `[Unreleased] → Fixed`: plug-ins work on Linux. |
+
+## Diff Highlights
+
+```cpp
+extern "C" NOTA_API int32_t nota_pluginhost_pump(void) {
+#if JUCE_LINUX || JUCE_BSD
+ if (g_juceGui == nullptr) return 0;
+ auto* mm = juce::MessageManager::getInstanceWithoutCreating();
+ if (mm == nullptr || !mm->isThisTheMessageThread()) return 0;
+ int n = 0;
+ while (n < kMaxPerPump && juce::detail::dispatchNextMessageOnSystemQueue(true)) ++n;
+ return n;
+#else
+ return 0;
+#endif
+}
+```
+
+## Tests Added or Updated
+
+- `tests/Nota.SmokeTest/Program.cs` "plugin host pump" check: the export resolves on every platform, and with no
+ plugin loaded it returns 0 without blocking. This also runs on headless Linux CI, so a missing symbol or an
+ accidental block is caught.
+- Not added: an end-to-end "instantiate a VST3 on Linux, pump, render, assert non-silent" test. The smoke test has
+ no hosted-plugin fixture yet. `NotaPentad` is an opt-in build. See Follow-ups.
+
+## Local Verification
+
+- Commands run: `bash scripts/build.sh` (macOS arm64) → build OK, `SMOKE TEST PASSED` (3291 PASS, 0 FAIL), including
+ `[PASS] plugin host pump: exported, non-blocking no-op with no plugin loaded`.
+- Not verified: the `JUCE_LINUX` branch was **not compiled** here (macOS host; Docker daemon not running). The
+ `juce::detail::dispatchNextMessageOnSystemQueue` declaration was matched against the vendored JUCE
+ (`juce_events/messages/juce_MessageManager.cpp:96-99`, `juce_events/native/juce_Messaging_linux.cpp:341`). Linux
+ CI (`scripts/build-linux.sh`) will compile it.
+- Not verified: behaviour on a real Linux desktop (Wayland + XWayland). That is `/speckit-bug-test`.
+
+## Deviations from Assessment
+
+- **Root cause of the silence, refined (strengthens the assessment).** The assessment said hosted plugins get
+ `IRunLoop` through the editor window. They actually get it earlier. JUCE's VST3 host context exposes
+ `Linux::IRunLoop` (`juce_VST3PluginFormatImpl.h:682`), and a JUCE-built plugin's component and controller pick it
+ up when they are created (`juce_audio_plugin_client_VST3.cpp:776-779` → `registerHandlerForRunLoop` →
+ `updateCurrentMessageThread`). The plugin then **stops its own message thread** and adopts our UI thread. So
+ everything async in the plugin depended on the never-pumped loop from the moment of instantiation. That explains
+ the reporter's "silent even without opening the editor". The same pump fixes it, and no code change follows from
+ the refinement.
+- The pump timer starts at app startup on Linux, not lazily at first instantiation. It is cheap: `poll(0)` plus an
+ early return before JUCE init. This avoids threading the "first plugin" event into the App layer.
+
+## Follow-ups
+
+- Run `/speckit-bug-test` on a Linux machine (Wayland session): a registry plugin (e.g. Surge XT) should sound with
+ the editor closed, the editor should paint and take mouse input, the close button should close it, and reopening
+ should work.
+- Linux editor polish, outside this fix: `PluginEditorWindow` has a macOS-only key monitor. Check that the
+ computer-keyboard note map reaches the plugin window on Linux. Also check that `setAlwaysOnTop` behaves under
+ XWayland.
+- Consider a Linux CI smoke test that builds `NotaPentad` and instantiates it in-process with a pump + render
+ assert.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10dc25ed..be6fdb6c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,8 +26,30 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
- **Note length and velocity from the keyboard:** in the piano roll, **⇧← / ⇧→** shorten
or lengthen every selected note by one grid step (starts stay put), and **⌥↑ / ⌥↓**
raise or lower their velocity by 10 — **⌥⇧↑ / ⌥⇧↓** by 1. Each press is one undo step.
+- **Stereo pan law:** panning a stereo track or return now moves its whole image instead
+ of dropping a channel — at full left, both channels play from the left speaker. Mono
+ material and centred tracks sound exactly as before. New projects use it; the Mixer
+ footer shows the project's **PAN LAW** (Stereo / Balance) and switches it during
+ playback without a click, as one undo step. Group strips are marked **BAL**: groups keep
+ their balance so grouping stays level-transparent.
+- **Undo for volume and pan:** fader, pan and master-volume moves can now be undone and
+ redone (**⌘Z** / **⌘⇧Z**) — from the Mixer, the track headers, the Return and Master
+ rows, the Session mixer, the transport's **MST**, Nota Remote, a MIDI controller and the
+ AI assistant. One move is one step, in the same history as every other edit; a reset or a
+ typed dB value is a step too, and a MIDI controller's movement ends after a 1 s pause.
+ While recording automation, the recorded lane and the value undo together. Automation
+ playback, opening a project and freezing never add steps.
+- **Stereo Map:** the Mixer window has a new **Stereo Map** view (switch it in the window's
+ title bar). Every track, return and the master is a dot at its pan and fader, with a cloud
+ showing where its sound really is, how wide it is and how loud — a mono sound draws a narrow
+ cloud on its dot, a wide pad spans the map — plus the master's phase correlation. Drag a dot
+ to set pan and volume together (one undo step), double-click to centre it, ⌥ double-click
+ for 0 dB; hover for the numbers; click to select the track.
### Changed
+- **Existing projects keep the Balance pan law** and sound exactly as before; the Mixer
+ marks them **Older project** until you switch them to Stereo. Projects are saved in
+ format v21 — earlier Nota versions can't open them.
- **Notes replace the notes they land on:** a note moved, stretched, drawn or pasted onto
a note of the same pitch no longer stacks on top of it. The note underneath is cut where
the new one starts, or removed if its start is covered. This happens when you let the
@@ -41,6 +63,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
- **Return tracks can be deleted in the arrangement:** the Return row's context menu has
Delete track, and Delete / Backspace removes a selected Return, in one undo step. The
Returns that stay keep sounding, and every track's sends stay on the same Returns.
+- **Plug-ins work on Linux:** VST3 plug-ins (including those from Get Plug-ins) play sound
+ again, and their windows draw their interface and close with the close button. Before,
+ they stayed silent behind a black window that only closed when Nota quit.
## [0.52.1] — 2026-10-13
diff --git a/FEATURES.md b/FEATURES.md
index 94a89995..befabd18 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -44,7 +44,10 @@ JUCE module; the engine core is JUCE-free.
## Project and transport
- **Project**: create / open / save (`.nota`), autosaves, undo/redo for every editing
- operation.
+ operation — including volume, pan and master-volume moves from any source (Mixer, track
+ headers, Session mixer, **MST**, Nota Remote, a MIDI controller, MCP), one step per move;
+ a recorded automation pass undoes with its value. Mute, solo and sends are not in the
+ history; automation playback, opening a project and freezing add no steps.
- **New project template**: a new project (and the workspace Nota opens with) starts with an
instrument track (Nota Synth), an audio track and two returns — **Reverb** (Nota Reverb)
and **Delay** (Nota Delay), both Wet Only — ready to send to; it opens unmodified, with
@@ -159,6 +162,19 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).
pasted tracks land after the selected track, in its group.
- **Per track**: volume, pan (bipolar bar), mute, solo, arm (ready to record).
Double-click resets to the default.
+- **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
+ material and centred tracks sound the same either way. New projects use Stereo; projects
+ from earlier versions keep Balance and are marked **Older project**. Switching is
+ click-free during playback and one undo step. Groups keep their balance (marked **BAL**).
+- **Stereo Map** (Mixer window, **Strips | Stereo Map** in its title bar): every track,
+ return and the master as a dot at its pan (left–right) and fader (up–down), with a measured
+ cloud — where the sound really sits, how wide it is (from the phase correlation) and how
+ loud — and the master correlation under the map. Drag a dot to set pan and volume at once
+ (one undo step), double-click for centre, ⌥ double-click for 0 dB; hover shows pan, volume,
+ balance, width, correlation and level and flags a source whose image is off its pan; click
+ selects the track. Muted tracks show no cloud, solo dims the rest.
- **Reordering** by dragging the name row (with an accent insertion line); returns stay
after regular tracks; the group hierarchy is saved with the project.
- **Routing**:
diff --git a/specs/006-stereo-pan-law/checklists/requirements.md b/specs/006-stereo-pan-law/checklists/requirements.md
new file mode 100644
index 00000000..56098512
--- /dev/null
+++ b/specs/006-stereo-pan-law/checklists/requirements.md
@@ -0,0 +1,41 @@
+# Specification Quality Checklist: Stereo Pan Law
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-13
+**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
+
+- Resolved 2026-10-13: the pan-law switch lives in the Mixer footer (PAN LAW
+ segmented control), per the design mock `nota-design/Nota Mixer v2.html`.
+- FR-009a…e quote UI copy and placement from the mock — deliberate: the design is the
+ agreed source, so the copy is part of the requirement, not an implementation detail.
+- The "Current state" block names engine behaviour (cos/sin balance, group law) as
+ context for the planner, not as requirements; requirements stay behavioural.
+- FR-005 bound is 3.5 dB, not 3 dB: exact-for-mono folding (FR-004) costs unrelated
+ left/right material ~3.01 dB at the edge.
diff --git a/specs/006-stereo-pan-law/contracts/c-abi-pan-law.md b/specs/006-stereo-pan-law/contracts/c-abi-pan-law.md
new file mode 100644
index 00000000..7f0ea4cb
--- /dev/null
+++ b/specs/006-stereo-pan-law/contracts/c-abi-pan-law.md
@@ -0,0 +1,49 @@
+# Contract: C ABI — project pan law
+
+Added to `src/native/nota.engine/include/nota/nota_engine.h` (AR-7), implemented in
+`nota_engine_core.cpp`.
+
+```c
+/* ---- Pan law (006) ------------------------------------------------------- */
+/* How a track's or return's pan is applied to a stereo signal. Project-wide, part of
+ * the graph snapshot (undo/redo restore it). BALANCE (the default, and every project
+ * before format v21): the opposite channel is attenuated. STEREO: the whole image
+ * moves — the far channel is folded into the near side, a mono fold at full pan.
+ * Identical for mono material and at centre. Groups, clip pan envelopes and rack-chain
+ * pans are not affected. */
+#define NOTA_PAN_LAW_BALANCE 0
+#define NOTA_PAN_LAW_STEREO 1
+
+/* Set the law. checkpoint = 1: one undo step (user edit); 0: no undo entry (project
+ * load / new-project baseline). A change while playing crossfades over 10 ms.
+ * NOTA_ERR_INVALID_ARG for an unknown law; NOTA_OK (no-op, no undo step) if unchanged.
+ * Message thread only. */
+NOTA_API NotaResult nota_engine_set_pan_law(NotaEngine* engine, int32_t law, int32_t checkpoint);
+
+/* Current law (authoring graph). NOTA_PAN_LAW_BALANCE for a null engine. */
+NOTA_API int32_t nota_engine_pan_law(const NotaEngine* engine);
+```
+
+## Behaviour guarantees (tested by the smoke test)
+
+| Call | Expect |
+|---|---|
+| fresh engine / after `nota_engine_reset` | `nota_engine_pan_law == BALANCE` |
+| `set_pan_law(STEREO, 1)` then `nota_engine_undo` | law back to `BALANCE`; `redo` → `STEREO` |
+| `set_pan_law(STEREO, 0)` | `nota_engine_can_undo` unchanged |
+| `set_pan_law(same, 1)` | no new undo step |
+| `set_pan_law(7, 1)` | `NOTA_ERR_INVALID_ARG`, law unchanged |
+| any structural edit after `set_pan_law(STEREO)` | law still `STEREO` |
+
+## Managed mirror
+
+`Nota.Application/Engine/IAudioEngine.cs`:
+
+```csharp
+/// <summary>Project pan law (graph-level, undoable). See nota_engine_set_pan_law.</summary>
+PanLaw PanLaw { get; }
+void SetPanLaw(PanLaw law, bool checkpoint = true);
+```
+
+`public enum PanLaw { Balance = 0, Stereo = 1 }` in `Nota.Application`.
+P/Invoke in `Nota.Infrastructure/Interop/NativeMethods.cs`, wrapper in `NotaEngine.cs`.
diff --git a/specs/006-stereo-pan-law/contracts/project-format-v21.md b/specs/006-stereo-pan-law/contracts/project-format-v21.md
new file mode 100644
index 00000000..3aceb51a
--- /dev/null
+++ b/specs/006-stereo-pan-law/contracts/project-format-v21.md
@@ -0,0 +1,39 @@
+# Contract: project format v21 — `mixer`
+
+`ProjectService.CurrentFormatVersion` 20 → **21**.
+
+## Shape
+
+```json
+{
+ "formatVersion": 21,
+ "mixer": { "panLaw": "stereo", "panLawLegacy": false },
+ ...
+}
+```
+
+## Migration (append to `ProjectMigrations.Registered`)
+
+```text
+v20 -> v21: projects gain a pan law. Every earlier project mixed with the balance law,
+so the step writes mixer = { panLaw: "balance", panLawLegacy: true } when `mixer` is
+absent (keeps an existing object untouched).
+```
+
+## Capture / apply (`ProjectService`)
+
+| Direction | Rule |
+|---|---|
+| Capture | `doc.Mixer = new MixerDto { PanLaw = engine.PanLaw == Stereo ? "stereo" : "balance", PanLawLegacy = transport.PanLawLegacy }` |
+| Apply | after `engine.Reset()` and before tracks: `engine.SetPanLaw(parsed, checkpoint: false)`; `ProjectLoadResult.Transport.PanLawLegacy = doc.Mixer.PanLawLegacy` |
+| Fingerprint | includes `mixer` (it is part of the manifest) → a law switch marks the project unsaved |
+
+## Version history (`VersionDiff`)
+
+A change of `mixer.panLaw` between two versions is listed under the *sound* changes as
+"Pan law".
+
+## Compatibility
+
+- Older Nota builds refuse v21 files (existing rule: "older builds refuse newer files").
+- Every pre-v21 file opens as Balance + legacy → renders bit-identical (SC-002).
diff --git a/specs/006-stereo-pan-law/contracts/ui-mixer-footer.md b/specs/006-stereo-pan-law/contracts/ui-mixer-footer.md
new file mode 100644
index 00000000..c0ee6f59
--- /dev/null
+++ b/specs/006-stereo-pan-law/contracts/ui-mixer-footer.md
@@ -0,0 +1,39 @@
+# Contract: Mixer footer — PAN LAW, OLDER PROJECT, BAL
+
+Source of truth: `nota-design/Nota Mixer v2.html` (footer and strip pan block). Built
+in `src/managed/Nota.App/MixerView.cs` with Ember tokens (`DESIGN.md`, `nota-design`
+skill); both themes.
+
+## Footer layout (left → right)
+
+`Show [Sends] [I/O]` · 1 px divider · **PAN LAW** group · (flex) · A/B crossfader
+placeholder (unchanged).
+
+Footer height grows from 34 to 44 px to fit a 26 px segmented control (mock).
+
+## PAN LAW group
+
+| Element | Spec |
+|---|---|
+| Label | "PAN LAW" — 10 px, bold, letter-spacing .14em, `TextTertiary` |
+| Segmented control | The existing shell segmented control (`Border.segmented` + `ToggleButton.seg`, 11 px — `DESIGN.md` § components): sunken `BgSunken` well, `BorderDefault`; two segments "Stereo", "Balance". Selected = solid `Accent` with `TextOnAccent`; unselected = `TextSecondary` |
+| Tooltips | Stereo — "Panning moves the whole stereo image; nothing is dropped"; Balance — "Panning attenuates the opposite channel (legacy behaviour)" |
+| Hint (11 px, `TextTertiary`) | Stereo — "Pan moves the whole image of stereo tracks and returns"; Balance — "Pan attenuates the opposite channel, as in earlier versions" |
+| OLDER PROJECT badge | Mono 9 px, letter-spacing .18em, 18 px tall, 1 px `BorderDefault`, radius 3, `TextTertiary`. Tooltip: "Projects saved before stereo pan law open with Balance so existing mixes do not change". Visible ⇔ `PanLawLegacy && law == Balance` |
+
+Interaction: clicking the unselected segment calls `SetPanLaw(law, checkpoint: true)`;
+clicking the selected one does nothing. The control re-reads `engine.PanLaw` in
+`Refresh()` and on the UI tick, so undo/redo (from any window) and project load
+update it.
+
+## BAL badge on group strips
+
+Under the PAN read-out of every group strip, when law == Stereo: "BAL", Mono 7 px,
+letter-spacing .12em, 11 px tall, 1 px `BorderDefault`, radius 3, `TextTertiary`.
+Tooltip: "Groups keep a unity-centre balance so grouping stays level-transparent".
+Hidden under Balance. Track, return and master strips never show it.
+
+## Not in this contract
+
+The mock's Strips | Stereo Map tabs, the map itself, the strip redesign and the
+"Undo pan law" toast — Stereo Map spec / not a Nota pattern.
diff --git a/specs/006-stereo-pan-law/data-model.md b/specs/006-stereo-pan-law/data-model.md
new file mode 100644
index 00000000..09ed56a2
--- /dev/null
+++ b/specs/006-stereo-pan-law/data-model.md
@@ -0,0 +1,54 @@
+# Data Model: Stereo Pan Law
+
+## PanLaw (engine, graph-level)
+
+| Field | Type | Where | Default |
+|---|---|---|---|
+| `panLaw` | `enum class PanLaw : int32_t { Balance = 0, Stereo = 1 }` | `Graph` (`Graph.h`) | `Balance` |
+
+- Part of the immutable graph snapshot → undo/redo restore it with the graph.
+- Carried to every fresh graph by `inheritGraphLevel()` (with `sceneCount`, `scenes`,
+ `masterVolume`, `masterTrack`).
+- Read by the audio thread from the live graph at the track and return pan stages.
+
+## Render state (engine, audio-thread-owned)
+
+| Field | Type | Meaning |
+|---|---|---|
+| `panLawFrom_` / `panLawTo_` | `PanLaw` | the law being faded from / to (`panLawTo_` = the live law once a fade starts) |
+| `panLawPos_` | `float` | fade position, 0 = from … 1 = to; 1 = no fade running |
+| `panLawSnap_` | `std::atomic<bool>` | set by the message thread on reset and on a no-checkpoint `setPanLaw` (load, new-project baseline) |
+
+Per `mixGraph` call: if `panLawSnap_` was set → `from = to = live law`, `pos = 1` (no fade);
+else if the live law ≠ `panLawTo_` → start a fade (`from = to`, `to = live`, `pos = 0`), or,
+if it flipped back to `panLawFrom_` mid-fade, swap them and continue from `1 − pos`. The
+track/return stages lerp the two laws' gains per sample with `pos + i·step`
+(`step = 1 / 10 ms` in samples); after the segment `pos += frames·step`, clamped to 1.
+
+## Project document (`project.json`, format v21)
+
+```json
+"mixer": { "panLaw": "stereo", "panLawLegacy": false }
+```
+
+| Field | Type | Rules |
+|---|---|---|
+| `mixer` | object, optional | absent (pre-v21 or damaged) ⇒ `{ balance, legacy: true }` |
+| `mixer.panLaw` | `"stereo"` \| `"balance"` | unknown string ⇒ `balance` + load warning |
+| `mixer.panLawLegacy` | bool | default `false`; written by the v20 → v21 migration as `true` |
+
+`MixerDto` keeps `[JsonExtensionData]` like the other DTOs (forward-compat, NFR-8).
+
+## Managed state
+
+| Name | Owner | Lifetime |
+|---|---|---|
+| `IAudioEngine.PanLaw` (get) / `SetPanLaw(law, checkpoint)` | `Nota.Application` port, `NotaEngine` impl | engine |
+| `PanLawLegacy` | `TransportState` (persistence boundary record) → `MainWindow` field | per open project; set on load, `false` on New |
+
+UI derivation (`MixerView`, re-read in `Refresh()` and on the UI tick):
+
+- PAN LAW segment = `engine.PanLaw`
+- hint line = text for that law (contract `ui-mixer-footer.md`)
+- OLDER PROJECT badge visible ⇔ `PanLawLegacy && PanLaw == Balance`
+- BAL badge on each group strip visible ⇔ `PanLaw == Stereo`
diff --git a/specs/006-stereo-pan-law/plan.md b/specs/006-stereo-pan-law/plan.md
new file mode 100644
index 00000000..4da0a3f0
--- /dev/null
+++ b/specs/006-stereo-pan-law/plan.md
@@ -0,0 +1,221 @@
+# Implementation Plan: Stereo Pan Law
+
+**Branch**: `006-stereo-pan-law` | **Date**: 2026-10-13 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `/specs/006-stereo-pan-law/spec.md`
+
+## Summary
+
+A project-wide pan law, **Stereo** or **Balance**, decides how track and return pan
+is applied to a stereo signal. Stereo folds the far channel into the near side
+(a mono fold at full pan), and is identical to today's Balance at centre and for
+mono material. The law is a field of the engine's `Graph` snapshot, so undo/redo
+and the audio thread get it for free; a flip during playback crossfades over 10 ms.
+Projects get format v21 with a `mixer` object; the v20 → v21 migration marks every
+older project as Balance + legacy, so old mixes render unchanged. New projects start
+with Stereo. The Mixer footer gets the **PAN LAW** control, the **OLDER PROJECT**
+badge and a **BAL** badge on group strips, per `nota-design/Nota Mixer v2.html`.
+See [research.md](research.md).
+
+## Nota: Read Before Planning
+
+- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-5 (the law travels
+ in the immutable graph snapshot), AR-6 (crossfade state is preallocated
+ audio-thread members, no alloc/lock), AR-7 (two new C ABI functions).
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) (shell segmented control, badges) and
+ the `nota-design` skill.
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (managed app)
+
+**Primary Dependencies**: Avalonia (existing); no new dependency
+
+**Storage**: `project.json` format v20 → **v21** (`mixer.panLaw`, `mixer.panLawLegacy`);
+migration via `ProjectMigrations`
+
+**Audio-Thread Impact**: The track and return pan stages in `Engine_Render.cpp`
+switch from two gains to a 2×2 matrix (two extra multiply-adds per sample, only
+for the side being folded toward). The law is read from the live graph (AR-5).
+A law flip runs a 10 ms crossfade using three preallocated `Engine` members
+(`renderedPanLaw_`, `panLawXfadeLeft_`, `panLawXfadeLen_`). No allocation, lock or
+I/O (AR-6). With no flip and law = Balance, the inner loop is unchanged →
+bit-identical renders.
+
+**Testing**: `scripts/build.sh` → smoke test gains `PanLawTests` (deterministic stereo
+WAV, Goertzel per channel); UI via the headless/in-app harness
+([quickstart.md](quickstart.md))
+
+**Target Platform**: macOS / Windows / Linux desktop app
+
+**Project Type**: desktop-app (engine + managed UI)
+
+**Performance Goals**: pan stage cost ≤ +5 % of today's per-track post-fader loop;
+no measurable change in total render time on the smoke-test project
+
+**Constraints**: Balance output bit-identical to 0.52.x (SC-002); law flip click-free
+(SC-004); mono exact (FR-004)
+
+**Scale/Scope**: engine ~150 lines + 15 mechanical call-site edits; managed ~200
+lines; smoke test ~250 lines
+
+## Constitution Check
+
+| Principle | Status |
+|---|---|
+| I. Real-time audio safety | ✅ Law delivered by snapshot (AR-5); crossfade state preallocated; no alloc/lock/I/O on the audio thread |
+| II. Boundary discipline | ✅ Two new functions in `nota_engine.h` (`nota_engine_set_pan_law`, `nota_engine_pan_law`), C types only |
+| III. Licensing hygiene | ✅ One new source file (`tests/Nota.SmokeTest/PanLawTests.cs`) with the SPDX header; no new dependency |
+| IV. Verification gate | ✅ Engine behaviour change → smoke test extended (`PanLawTests`); new C ABI covered |
+| V. One logical change | ✅ The pan law end to end. The `inheritGraphLevel` helper is the minimum needed to add a graph field safely — kept in this change, not a separate refactor |
+| VI. Docs in sync | ⏳ CHANGELOG `[Unreleased]`, `nota-features`, `nota-docs` (Mixer page, EN + RU) |
+| VII. Spec-first | ✅ This run |
+| VIII. Rules not weakened | ✅ |
+
+Post-design re-check: unchanged — all gates pass.
+
+## Design
+
+### 1. Engine — the law in the graph
+
+- `Graph.h`: `enum class PanLaw : int32_t { Balance = 0, Stereo = 1 };` and
+ `PanLaw panLaw = PanLaw::Balance;` on `Graph`.
+- `Graph.h`: `inline void inheritGraphLevel(Graph& dst, const Graph& src)` copying
+ `sceneCount`, `scenes`, `masterVolume`, `masterTrack`, `panLaw`; update the
+ footgun comment to point at it.
+- Replace the hand-copied graph-level lines with `inheritGraphLevel(*g, *authoring_)`
+ at every production fresh-graph site (15):
+ `Engine.cpp:520` (republishWithTrackRaw — keep its `masterTrack` override after the
+ call), `Engine_Modulation.cpp:309`, `Engine_Session.cpp:113` (keep its `sceneCount
+ = newCount` after the call), `Engine_Session.cpp:861`, `Engine_Tracks.cpp:461, 1382,
+ 1502, 1534, 1564, 1619, 1754, 1896, 2439, 2491, 2686`. Self-test graphs in
+ `Engine_Automation.cpp` (75, 377, 430) and the reset graph (`Engine.cpp:570`) stay
+ default (Balance).
+- `Engine`: `bool setPanLaw(PanLaw law, bool checkpoint)` — no-op if equal; else
+ `auto g = make_shared<Graph>(*authoring_); g->panLaw = law;` then `publish(g)`
+ (checkpoint) or `publishRaw(g)`. `PanLaw panLaw() const`.
+
+### 2. Engine — render ([research R1, R4](research.md))
+
+- One `static inline` helper in `Engine_Render.cpp`:
+ `PanMatrix panMatrix(float pan, float vol, PanLaw law)` → `{ll, lr, rl, rr}` per R1.
+- Track stage (`Engine_Render.cpp:1264`) and return stage (`:1403`): build the
+ matrix from the live graph's law; inner loop computes
+ `l = ll*inL + lr*inR; r = rl*inL + rr*inR`. When `lr == 0 && rl == 0` (Balance, or
+ Stereo at C) use the existing two-gain loop so Balance stays bit-identical.
+- Crossfade: at the start of the block, if `g->panLaw != renderedPanLaw_` and no
+ fade is running, start one (`panLawXfadeLen_` = 10 ms at the current rate, recomputed
+ wherever the engine's sample rate is set). During a fade each stage builds both matrices and lerps per sample;
+ after the last stage of the block, advance `panLawXfadeLeft_` by `frames` and,
+ at 0, set `renderedPanLaw_`. The fade progress is per block-sample, shared by all
+ stages, so every track crosses at the same moment.
+- Group stage (`:1337`) untouched (FR-010).
+- Freeze, export, resampling, route taps and sends already read `l`/`r` after the
+ pan stage → covered (FR-011).
+
+### 3. C ABI ([contract](contracts/c-abi-pan-law.md))
+
+`nota_engine.h` + `nota_engine_core.cpp`: `NOTA_PAN_LAW_*`, `nota_engine_set_pan_law`,
+`nota_engine_pan_law`.
+
+### 4. Managed — engine port and persistence ([contract](contracts/project-format-v21.md))
+
+- `Nota.Application`: `enum PanLaw`, `IAudioEngine.PanLaw` / `SetPanLaw`;
+ `TransportState` gains `bool PanLawLegacy = false` (it is the App-owned values
+ record that crosses the persistence boundary).
+- `Nota.Infrastructure`: P/Invoke (`NativeMethods.cs`), `NotaEngine` wrapper,
+ `MixerDto` + `ProjectDocument.Mixer`, `CurrentFormatVersion = 21`, migration
+ v20 → v21, capture/apply in `ProjectService` (apply right after `engine.Reset()`,
+ `checkpoint: false`), `ProjectStore` maps `PanLawLegacy` into
+ `ProjectLoadResult.Transport`, `VersionDiff` lists a pan-law change as "Pan law".
+- `ProjectTemplate.ApplyDefault`: `engine.SetPanLaw(PanLaw.Stereo, checkpoint: false)`
+ before `ClearUndoHistory()` (FR-007).
+- `MainWindow`: `_panLawLegacy` field — set from the load result, `false` on New and
+ recovery-from-template; `TransportSnapshot()` passes it; `MixerView` reads it via a
+ `Func<bool> IsOlderProject` callback.
+
+### 5. Managed — Mixer UI ([contract](contracts/ui-mixer-footer.md))
+
+- `MixerView.Footer()`: height 34 → 44; after the Show toggles, a 1 px divider and
+ the PAN LAW group (label, shell segmented control, hint, OLDER PROJECT badge).
+ Crossfader placeholder stays right.
+- `PanRow` for group strips: a BAL badge under the PAN label, kept in
+ `_balBadges`.
+- `SyncPanLaw()` — sets the segment, hint, badge and BAL visibility from
+ `_engine.PanLaw` and `IsOlderProject()`; called from `Refresh()` and
+ `UpdateMeters()` (cheap getter; only touches controls when the value changed).
+
+### 6. Smoke test ([quickstart](quickstart.md) § 1)
+
+- New `tests/Nota.SmokeTest/PanLawTests.cs` (SPDX header), wired in `Program.cs` in
+ the main run and behind `--panlaw`, with the checks listed in quickstart § 1.
+- A v20 fixture JSON is built in code (no binary fixture file).
+
+### 7. Docs
+
+- `CHANGELOG.md` `[Unreleased]`: **Added** — Stereo pan law: panning a stereo track
+ or return moves its whole image instead of dropping a channel; new projects use
+ it; the Mixer footer shows and switches the project's pan law. **Changed** —
+ nothing for existing projects: they keep the Balance law (marked "Older project").
+- `nota-features` (FEATURES.md, Tracks and mixer), `nota-docs` (Mixer page, EN + RU,
+ footer screenshot in both themes).
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/006-stereo-pan-law/
+├── spec.md
+├── plan.md # this file
+├── research.md
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── c-abi-pan-law.md
+│ ├── project-format-v21.md
+│ └── ui-mixer-footer.md
+├── checklists/
+│ └── requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (repository root)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # NOTA_PAN_LAW_*, set/get
+└── src/
+ ├── Graph.h # PanLaw, Graph::panLaw, inheritGraphLevel()
+ ├── Engine.h / Engine.cpp # setPanLaw/panLaw, crossfade members, :520 site
+ ├── Engine_Render.cpp # panMatrix, track + return stages, crossfade
+ ├── Engine_Tracks.cpp # 11 fresh-graph sites → inheritGraphLevel
+ ├── Engine_Session.cpp # 2 sites
+ ├── Engine_Modulation.cpp # 1 site
+ └── nota_engine_core.cpp # C ABI
+src/managed/
+├── Nota.Application/Engine/IAudioEngine.cs, Ports/IProjectStore.cs (TransportState)
+├── Nota.Infrastructure/Interop/NativeMethods.cs, NotaEngine.cs
+├── Nota.Infrastructure/Persistence/ProjectModel.cs, ProjectService.cs,
+│ ProjectMigrations.cs, ProjectStore.cs, ProjectTemplate.cs, VersionDiff.cs
+└── Nota.App/MixerView.cs, MainWindow.Files.cs, MainWindow.Recovery.cs
+tests/Nota.SmokeTest/PanLawTests.cs, Program.cs
+CHANGELOG.md, FEATURES.md
+```
+
+**Structure Decision**: Engine + managed changes in existing projects; one new test
+file. No new projects.
+
+## Out of Scope / Known Gaps
+
+- Ramping ordinary pan/volume changes (zipper on fast automation) — research R4.
+- Group pan law, clip pan envelopes, rack-chain pans (FR-010).
+- MCP / Remote exposure of the law (pan values and display are unchanged; an MCP
+ `set_pan_law` tool can follow with the Stereo Map spec).
+- The mock's Strips | Stereo Map tabs and strip redesign — Stereo Map spec.
+- A pan-law preference for new projects (always Stereo).
+
+## Complexity Tracking
+
+No constitution violations.
diff --git a/specs/006-stereo-pan-law/quickstart.md b/specs/006-stereo-pan-law/quickstart.md
new file mode 100644
index 00000000..d62bf4d8
--- /dev/null
+++ b/specs/006-stereo-pan-law/quickstart.md
@@ -0,0 +1,46 @@
+# Quickstart: validating Stereo Pan Law
+
+## 1. Automated (the PR gate)
+
+```bash
+scripts/build.sh
+```
+
+Runs the smoke test, which now includes `PanLawTests` (also alone:
+`dotnet run --project tests/Nota.SmokeTest -- --panlaw`). Expected passes:
+
+| Check | Spec |
+|---|---|
+| Fresh engine law = Balance; set Stereo → undo → Balance → redo → Stereo; same-law set adds no undo step; `checkpoint 0` adds none | FR-001, FR-009, contract `c-abi-pan-law.md` |
+| L=440 Hz / R=1 kHz WAV, Stereo, pan L100: R output < −90 dBFS; each tone on L at half its source amplitude (−6.0 dB ±0.5 re source) | FR-002, FR-012, SC-001 |
+| Same at R100 (mirror) | FR-002 |
+| Stereo at C ≡ Balance at C, sample-exact | FR-003 |
+| Mono (440 Hz both channels): Stereo vs Balance at p ∈ {−1, −0.6, −0.25, 0.3, 0.8, 1}, per-channel level within 0.1 dB | FR-004, SC-003 |
+| Unrelated L/R, Stereo at L100: total power within 3.5 dB of centre | FR-005 |
+| Return panned L100 under Stereo keeps both channels of its input | Edge: returns |
+| Group panned under Stereo renders identical to Balance | FR-010 |
+| Law flip mid-playback on the L/R WAV at L100: no sample step larger than the signal's own maximum step | FR-009, SC-004 |
+| Law survives: add/remove/move track, group, scene add/remove, automation point, CV link, clip edit, undo/redo | R2 footgun |
+| Project save → load round-trips `stereo` / `balance` / `panLawLegacy` | FR-008, `project-format-v21.md` |
+| A v20 document (fixture JSON, no `mixer`) with an audio track panned L50 loads as Balance + legacy, and each output tone matches the Balance law (`cos θ`, `sin θ`, no cross-feed) within 0.01 dB | FR-006, SC-002 |
+| `ProjectTemplate.ApplyDefault` → Stereo, not undoable | FR-007 |
+
+## 2. In the app (UI, by agent via the headless/in-app harness — see memory "Nota UI verify recipe")
+
+Isolate data with `NOTA_DATA_DIR`.
+
+1. **New project** → Mixer (⌘⇧M): footer shows `PAN LAW [Stereo|Balance]` with Stereo
+ selected, hint "Pan moves the whole image…", no OLDER PROJECT badge. Group a track:
+ the group strip shows **BAL**.
+2. **Open a project saved by 0.52.x**: Balance selected, OLDER PROJECT badge visible,
+ no BAL badges. Hover each element: tooltips per `contracts/ui-mixer-footer.md`.
+3. Click **Stereo** during playback: the badge disappears, BAL appears on groups,
+ panned stereo tracks audibly widen, no click. ⌘Z (in the main window and in the
+ Mixer): back to Balance, badge back. Save, reopen: law and badge kept.
+4. Screenshot the footer in Ember Graphite and Ember Paper; compare with
+ `nota-design/Nota Mixer v2.html`.
+
+## 3. Docs
+
+`CHANGELOG.md` `[Unreleased]`, `FEATURES.md` (nota-features), user docs EN + RU
+(nota-docs: Mixer page — pan law section with a footer screenshot).
diff --git a/specs/006-stereo-pan-law/research.md b/specs/006-stereo-pan-law/research.md
new file mode 100644
index 00000000..02b34166
--- /dev/null
+++ b/specs/006-stereo-pan-law/research.md
@@ -0,0 +1,147 @@
+# Research: Stereo Pan Law
+
+## R1. The Stereo pan curve
+
+**Decision**: per track/return, a 2×2 gain matrix applied after the fader. For pan
+`p ∈ [−1, 1]`, `θ = (p + 1)·π/4`, `h = cos(π/4)`:
+
+| | out L | out R |
+|---|---|---|
+| **Balance** (today) | `cos θ · L` | `sin θ · R` |
+| **Stereo**, `p ≤ 0` | `(cos θ − b)·L + b·R` | `sin θ · R` |
+| **Stereo**, `p ≥ 0` | `cos θ · L` | `b·L + (sin θ − b)·R` |
+
+with `b = 0.5·|p|` (the share of the far channel folded into the near side). All
+multiplied by the fader volume, as today.
+
+Checks against the spec:
+
+- **FR-003 (centre identical)**: `p = 0 → b = 0`, `cos θ = sin θ = h` → exactly
+ Balance.
+- **FR-004 (mono exact)**: with `L = R = x`, the near side is `(cos θ − b + b)·x =
+ cos θ·x` and the far side is `sin θ·x` → exactly Balance at every `p` (not
+ merely within 0.1 dB — the identity is algebraic; float rounding only).
+- **FR-002 (nothing dropped)**: at `p = −1`: out L = `0.5·L + 0.5·R` (mono fold),
+ out R = 0. Both channels' content is present at −6 dB each on the left.
+- **FR-005 (≤ 3.5 dB)**: unrelated L/R of equal power P. Centre total = P. At
+ `p = −1`: `0.25P + 0.25P = 0.5P` → −3.01 dB. At `p = −0.5`: `(0.674² + 0.25²)P +
+ 0.383²P ≈ 0.663P` → −1.8 dB. Worst case is the edge, −3.01 dB.
+- **Image narrows toward the edge**: the cross term grows linearly with `|p|` until
+ the image is a mono fold at the edge.
+
+**Rationale**: the only free choice under FR-003 + FR-004 is how the near-side gain
+`cos θ` is split between the near and far channels. A linear far-share reaching ½ at
+the edge gives the textbook mono fold `(L+R)/2` at hard pan (what Logic's and
+Ableton's stereo-pan modes converge to) and stays inside FR-005 everywhere.
+
+**Alternatives considered**:
+
+- *Complement fold* `near = h·L + (cos θ − h)·R` (the curve the design mock uses
+ for its meter estimate): also exact for mono and centre, and loses only −2.3 dB at
+ the edge, but the far channel arrives at only `1 − h ≈ 0.29` (−10.7 dB) — the
+ image never collapses, the far material stays audibly buried. Rejected.
+- *Width-then-balance* (narrow with M/S first, then balance-pan the result): extra
+ M/S stage per track, and it is not exact for mono under the balance step (mono
+ through a balance at `p ≠ 0` is fine, but the width stage then changes nothing —
+ equivalent, more arithmetic). Rejected as more code for the same result.
+- *Constant-power for unrelated material* (scale so unrelated L/R keep P): breaks
+ FR-004 for mono (+3 dB at the edge). Rejected by the spec.
+
+## R2. Where the law lives in the engine
+
+**Decision**: a graph-level field `PanLaw panLaw` on `Graph` (`Graph.h`), next to
+`masterVolume`. Setting it copies the authoring graph (`make_shared<Graph>(*authoring_)`)
+and publishes it — with an undo checkpoint for user edits, without one for load.
+
+**Rationale**:
+
+- The engine's undo restores retained `Graph` snapshots (M6-6) and explicitly does
+ *not* cover atomic params. FR-009 needs the switch to be one undo step → the law
+ must be snapshot data. Undo/redo then flip it for free, including interleaved
+ with structural edits.
+- The audio thread already reads `liveGraph_` per block, so the law reaches the
+ render with no new command and no lock (AR-5).
+
+**Alternatives considered**: an `std::atomic<int>` on `Engine` (like volume/pan).
+Simpler to set, but undo would need a managed-side undo stack interleaved with the
+engine's — Nota has none. Rejected.
+
+**Risk — the fresh-graph footgun**: ~20 edit sites build a *fresh* `Graph` and copy
+graph-level fields by hand (`sceneCount`, `scenes`, `masterVolume`, `masterTrack`);
+`Graph.h` warns about it. A site that forgets `panLaw` would silently reset the law
+to its default on that edit. **Mitigation**: add one helper,
+`inheritGraphLevel(Graph& dst, const Graph& src)` in `Graph.h`, copying all four
+existing fields plus `panLaw`; replace the hand-copied lines at every
+`make_shared<Graph>()` site with it (mechanical; the list is in the plan). The smoke
+test then proves the law survives one edit of each kind (add/remove/move track,
+group, scene add/remove, automation, modulation, clip edit, undo/redo).
+
+## R3. Engine default and app defaults
+
+**Decision**: the engine's default law is **Balance** (empty graph, `nota_engine_reset`).
+The app sets **Stereo** in `ProjectTemplate.ApplyDefault` (both File → New and the
+launch/recovery workspace go through it) *before* `ClearUndoHistory`, so the law is
+part of the baseline and not an undoable step.
+
+**Rationale**: keeps every existing C ABI consumer — the smoke test, MCP golden
+tests, offline audition rigs — bit-identical without touching them, and makes
+"absent = Balance" true at every layer.
+
+## R4. Click-free switching (FR-009, SC-004)
+
+**Decision**: the render keeps `renderedPanLaw_` (audio-thread-owned, plain member).
+When the live graph's law differs from it, the track and return pan stages run a
+**10 ms linear crossfade** between the old-law and new-law matrices (per-sample
+`lerp` of four coefficients; the pan value itself is unchanged), counted by
+`panLawXfadeLeft_` across blocks; when it reaches 0, `renderedPanLaw_` takes the new
+law. No allocation, no lock.
+
+**Rationale**: a law flip changes gains for every panned stereo track at once — up
+to −6 dB → 0 dB steps on the far channel at hard pan, which clicks on sustained
+material. 10 ms is below perceptual smearing and above one block at any supported
+buffer size. With no flip the code path is the existing constant-gain loop, so
+Balance renders stay bit-identical (FR-006, SC-002).
+
+**Alternatives considered**: ramping every pan change (also fixes zipper on pan
+automation) — changes legacy renders by tiny amounts and breaks the bit-identical
+guarantee. Out of scope; could be its own change.
+
+## R5. Groups, clip envelopes, rack chains
+
+**Decision**: unchanged (FR-010). Groups keep the unity-centre balance at
+`Engine_Render.cpp` (group stage); clip pan envelopes and rack-chain pans are their
+own stages and never read the project law.
+
+## R6. Persistence
+
+**Decision**: format **v21**. New top-level `mixer` object in `project.json`:
+`{ "panLaw": "stereo" | "balance", "panLawLegacy": bool }`. Migration v20 → v21 writes
+`{ "panLaw": "balance", "panLawLegacy": true }` when `mixer` is absent. The DTO
+treats a missing `mixer` (defensive) the same way.
+
+**Rationale**: follows the project's migration pipeline (`ProjectMigrations`), and
+makes "older project" an explicit, saved fact rather than an inference from
+absence — so it survives save + reopen (FR-009c) and project history restores.
+
+**`panLawLegacy`** is managed-only state (it never changes sound, so the engine
+does not hold it). It is set by migration, cleared only by creating a new project;
+the OLDER PROJECT badge shows when `panLawLegacy && law == Balance`, so switching to
+Stereo hides it and undoing back shows it again.
+
+**Alternatives considered**: no format bump, infer "older" from a missing field.
+Breaks after the first save (the field is then written). Rejected.
+
+## R7. Undo routing for the switch
+
+**Decision**: `nota_engine_set_pan_law(engine, law, checkpoint)`; the Mixer control
+calls it with `checkpoint = 1`. The engine's undo has no labels; the mock's
+"Undo pan law" toast is not a Nota pattern today and is not required by the spec.
+
+## R8. Smoke-test signal
+
+**Decision**: a deterministic stereo WAV written with `WavWriter` — a 440 Hz sine
+on L and a 1 000 Hz sine on R, −12 dBFS, 2 s — on an audio track, rendered with
+`RenderOffline`. Per-tone level is measured with a Goertzel filter per output
+channel, so "both materials on the left" is a number, not a guess. Mono case: the
+same file with one 440 Hz sine on both channels. (Memory note: synth notes drift
+±2 dB between renders; WAV clips are deterministic.)
diff --git a/specs/006-stereo-pan-law/spec.md b/specs/006-stereo-pan-law/spec.md
new file mode 100644
index 00000000..84fe8ef8
--- /dev/null
+++ b/specs/006-stereo-pan-law/spec.md
@@ -0,0 +1,259 @@
+# Feature Specification: Stereo Pan Law
+
+**Feature Branch**: `006-stereo-pan-law`
+
+**Created**: 2026-10-13
+
+**Status**: Draft
+
+## Clarifications
+
+### Session 2026-10-13
+
+- Q: Where does the pan-law switch live — there is no Project Settings window? → A: In
+ the Mixer window's bottom bar, as a **PAN LAW** segmented control (Stereo | Balance),
+ per the design mock `nota-design/Nota Mixer v2.html`.
+
+### Session 2026-10-14 (convergence)
+
+- Q: FR-009 asked for the undo step to be labelled "pan law", but Nota's undo has no step
+ labels anywhere. Add labels or drop the wording? → A: Drop it — the switch is one plain
+ undo step like every other; labelled undo would be its own feature.
+
+**Design reference**: [`Nota Mixer v2.html`](../../../nota-design/Nota%20Mixer%20v2.html)
+(sibling repo `nota-design`). The same mock also covers the Stereo Map (separate spec);
+only its pan-law parts belong here: the PAN LAW control with its hint line, the
+OLDER PROJECT badge, the BAL badge on group strips, and undo of the law.
+
+**Input**: User description: "Stereo pan law for tracks and returns. Today the track/return pan stage in the engine is an equal-power balance: L is scaled by cos, R by sin, so a stereo track panned hard left loses its right channel. Change it to a true stereo pan: panning a stereo signal moves the whole image (both channels are folded toward the pan side, nothing is lost, the image narrows toward the edge); mono signals sound identical to today. The pan law is stored per project: new projects use stereo pan; projects saved without the field open with the legacy balance law so existing mixes do not change; Project Settings lets the user switch the law. Applies to tracks and returns (groups keep their level-transparent behaviour unless the spec decides otherwise). Smoke test: a stereo WAV at pan L100 gives ~zero right-channel energy with total energy preserved. This is a prerequisite for the Stereo Map feature (a separate spec)."
+
+## 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
+- [ ] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [ ] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Ember) — secondary: the Mixer bottom-bar control and badges
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+**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).
+
+**Current state (for reference)**:
+
+- A track's and a return's pan control is applied after the fader as an equal-power
+ *balance*: the left channel is attenuated as the control moves right and vice versa.
+ At centre both channels sit at −3 dB. Panning a stereo source hard left silences its
+ right channel — that half of the material is lost, not moved.
+- Groups use a different, unity-centre balance so that grouping stays level-transparent.
+- Per-clip pan envelopes and rack-chain pans are separate balance stages.
+- There is no "Project Settings" window today; project-level values (key, sections,
+ graph layout…) are edited where they are shown and saved with the project. The pan
+ law follows that pattern: it is edited in the Mixer, where pan lives.
+- The Mixer window has a footer (Show Sends / I/O toggles and a disabled A/B
+ crossfader placeholder); the PAN LAW control joins it between the two.
+- This spec is the prerequisite of the Stereo Map feature, which visualises where each
+ track really sits in the stereo field: with a balance law a panned stereo track's
+ image does not follow its pan control, which makes such a map misleading.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Panning a stereo track moves its whole image (Priority: P1)
+
+A producer in a new project has a stereo pad (or a stereo drum loop) and pans it to
+L60 to make room for a guitar on the right. Both the left and the right parts of the
+pad stay audible; the whole image moves to the left and becomes narrower. At hard left
+the pad is fully in the left speaker, folded to mono, with nothing missing.
+
+**Why this priority**: It is the core change — today panning a stereo source throws
+away half of it, which is what producers coming from other DAWs do not expect.
+
+**Independent Test**: In a new project, play a stereo file whose left and right
+channels carry different material; sweep pan from C to L100 and listen/measure that
+both materials remain present and move left.
+
+**Acceptance Scenarios**:
+
+1. **Given** a new project and a stereo audio track whose channels carry different
+ sounds, **When** pan is set to L100, **Then** the right output is silent and both
+ sounds are heard in the left output.
+2. **Given** the same track, **When** pan is set to L50, **Then** both sounds are heard,
+ the image is shifted left and is narrower than at centre.
+3. **Given** the same track at C, **When** playing, **Then** the output is identical to
+ what the legacy law produces at C (switching laws does not change a centred track).
+4. **Given** a mono source (left and right identical), **When** pan is set to any
+ position, **Then** its left and right output levels match the legacy law at that
+ position.
+
+---
+
+### User Story 2 - Existing projects sound exactly as before (Priority: P1)
+
+A producer opens a project they mixed with an earlier Nota version. Every track sounds
+exactly as it did; nothing in the mix shifts. The project reports that it uses the
+legacy (balance) pan law.
+
+**Why this priority**: Silently changing finished mixes is unacceptable; this is the
+safety net for the P1 change above.
+
+**Independent Test**: Render a legacy project before and after the change; the renders
+are bit-identical (or null-test below −120 dBFS).
+
+**Acceptance Scenarios**:
+
+1. **Given** a project saved before this feature, **When** it is opened, **Then** its
+ pan law is Balance and an offline render matches the previous version's render.
+2. **Given** that legacy project, **When** it is saved and reopened, **Then** it still
+ uses Balance (the law is now stored explicitly).
+3. **Given** a new project (blank or from the default template), **When** it is
+ created, **Then** its pan law is Stereo.
+
+---
+
+### User Story 3 - Switching the pan law of a project (Priority: P2)
+
+A producer wants an old project to behave like new ones (or a new one to behave like
+old ones) and switches the project's pan law. The change is audible immediately during
+playback, is undoable, and is saved with the project.
+
+**Why this priority**: Gives control to users who want consistency, but the defaults
+of Stories 1–2 already cover most users.
+
+**Independent Test**: Open a legacy project, switch the law to Stereo during playback,
+hear the panned stereo tracks change, undo, hear them return.
+
+**Acceptance Scenarios**:
+
+1. **Given** a project using Balance, **When** the user switches to Stereo, **Then**
+ panned stereo tracks and returns change immediately without clicks or dropouts.
+2. **Given** that switch, **When** the user undoes, **Then** the law returns to Balance.
+3. **Given** a switched project, **When** it is saved and reopened, **Then** the chosen
+ law is kept.
+4. **Given** the Mixer window is open, **When** the user looks at its footer, **Then**
+ a **PAN LAW** control shows the current law (Stereo | Balance) with a one-line hint
+ next to it, in both the Strips and the Stereo Map views.
+5. **Given** a project created before this feature that still uses Balance, **When**
+ the Mixer is open, **Then** an **OLDER PROJECT** badge sits next to the hint and
+ explains on hover why the project uses Balance; switching to Stereo removes it.
+6. **Given** a project using Stereo, **When** the user looks at a group strip, **Then**
+ a **BAL** badge under its pan read-out explains on hover that groups keep a
+ unity-centre balance.
+
+### Edge Cases
+
+- **Automated pan**: pan automation and modulation keep their values; only how the
+ value is applied to stereo signals changes. Moving through positions must not click.
+- **Returns**: a return's pan uses the project law just like a track's pan; a reverb
+ return panned left keeps both reverb channels.
+- **Groups**: groups keep their own unity-centre balance (level-transparent grouping);
+ they do not follow the project law.
+- **Clip pan envelopes and rack-chain pans**: unchanged (they stay balance stages).
+- **Sends**: post-fader sends receive the signal after the pan stage, as today; under
+ Stereo they receive the folded image.
+- **Exports, freeze, resampling, sidechain routing**: use the same law as playback, so
+ a render matches what was heard.
+- **Remote, MCP, Mixer, arrangement headers**: the pan value range and display (L100…C…R100)
+ do not change; only the sound does.
+- **Project templates**: a new project made from any template uses Stereo, even if the
+ template file was saved before this feature.
+- **Mono-only material in a stereo track**: behaves as the mono case (Scenario 1.4).
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: A project MUST have a pan law with two values: **Stereo** and **Balance**
+ (the current behaviour).
+- **FR-002**: Under **Stereo**, the pan of a track or a return MUST move the whole
+ stereo image: as the control moves toward one side, the opposite channel is folded
+ into that side, so no channel's content is dropped at any position; at full left
+ (right) the output is the source folded into the left (right) channel only.
+- **FR-003**: Under **Stereo**, a centred pan MUST produce exactly the same output as
+ **Balance** at centre.
+- **FR-004**: Under **Stereo**, a source whose two channels are identical MUST produce
+ the same left/right levels as **Balance** at every pan position (within 0.1 dB).
+- **FR-005**: Under **Stereo**, at full left or right, the loudness of a source whose
+ channels carry unrelated material MUST stay within 3.5 dB of its loudness at centre (a fold that is exact for mono costs unrelated material about 3 dB at the edge).
+- **FR-006**: Projects saved without a pan law MUST open with **Balance**; their output
+ MUST not change in any way.
+- **FR-007**: New projects (blank or from any template) MUST start with **Stereo**.
+- **FR-008**: The pan law MUST be saved with the project and restored on open.
+- **FR-009**: The user MUST be able to see and switch the project's pan law; the
+ switch is one undo step and takes effect during playback
+ without clicks, dropouts or interrupting the transport.
+- **FR-009a**: The switch MUST be a **PAN LAW** segmented control (Stereo | Balance) in
+ the Mixer window footer, between the Show Sends / I/O toggles and the A/B
+ crossfader, visible in every Mixer view. Each segment has a tooltip:
+ Stereo — "Panning moves the whole stereo image; nothing is dropped";
+ Balance — "Panning attenuates the opposite channel (legacy behaviour)".
+- **FR-009b**: Next to the control a hint line MUST describe the current law:
+ Stereo — "Pan moves the whole image of stereo tracks and returns";
+ Balance — "Pan attenuates the opposite channel, as in earlier versions".
+- **FR-009c**: While a project created before this feature uses Balance, an
+ **OLDER PROJECT** badge MUST follow the hint, with the tooltip "Projects saved
+ before stereo pan law open with Balance so existing mixes do not change". The badge
+ survives save and reopen and disappears once the law is Stereo.
+- **FR-009d**: Under Stereo, every group strip MUST show a **BAL** badge under its pan
+ read-out, with the tooltip "Groups keep a unity-centre balance so grouping stays
+ level-transparent". Under Balance the badge is hidden (all pans are balances then).
+- **FR-009e**: The control, hint and badges MUST follow the Ember design language
+ (`DESIGN.md`) in both themes, matching the design reference.
+- **FR-010**: Group pan, clip pan envelopes and rack-chain pans MUST keep their current
+ behaviour regardless of the project law.
+- **FR-011**: Every path that renders the mix (playback, exports, freeze, resampling,
+ routing taps, sends) MUST use the project's law.
+- **FR-012**: The automated smoke test MUST cover: a stereo file with different
+ left/right material at L100 under Stereo gives silence on the right (below −90 dBFS)
+ and both materials on the left; a mono source matches Balance at several positions;
+ a project without a law field renders identically to Balance.
+- **FR-013**: The change MUST be listed in the changelog and the user documentation
+ (EN + RU) with a short explanation of the two laws and why old projects keep Balance.
+
+### Key Entities
+
+- **Pan law** (project property): `Stereo` | `Balance`. Absent in older project
+ files, which means `Balance`. Applies to every track and return pan in the project.
+- **Older-project mark** (project property): whether the project predates the pan law
+ (opened without a stored law). Drives the OLDER PROJECT badge only; it never
+ changes sound.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: In a new project, a stereo source panned to L100 keeps 100 % of its
+ material audible (right output silent, both channels' content present on the left).
+- **SC-002**: 100 % of projects saved before this feature render identically after it
+ (null test below −120 dBFS on the smoke-test project set).
+- **SC-003**: Mono sources match the previous law within 0.1 dB at every pan position.
+- **SC-004**: Switching the law during playback causes no audible click and no dropout
+ (no sample-to-sample jump larger than the signal's own on the smoke test).
+- **SC-005**: A user can find and change the project's pan law in under 30 seconds
+ without the documentation.
+
+## Assumptions
+
+- The pan value, its range, its display and its automation stay as they are; only how
+ the value is applied to a stereo signal changes under Stereo.
+- "Total energy preserved" from the request is read as FR-005 (within 3.5 dB): a fold
+ that is exact for mono sources (FR-004) cannot also keep the exact power of unrelated
+ left/right material — the plan picks the curve that meets both bounds.
+- Groups stay out of scope: their unity-centre balance exists to keep grouping
+ level-transparent, and changing it would alter every grouped mix.
+- No master pan exists, so nothing changes on the master.
+- The Stereo Map feature (separate spec) depends on this one and is not part of it.
+
+## 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` (Ember design language)
diff --git a/specs/006-stereo-pan-law/tasks.md b/specs/006-stereo-pan-law/tasks.md
new file mode 100644
index 00000000..81d5fe73
--- /dev/null
+++ b/specs/006-stereo-pan-law/tasks.md
@@ -0,0 +1,197 @@
+---
+
+description: "Task list for 006 Stereo Pan Law"
+---
+
+# Tasks: Stereo Pan Law
+
+**Input**: Design documents from `/specs/006-stereo-pan-law/`
+
+**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**: Requested — FR-012 requires smoke-test coverage, and the constitution
+(IV) requires it for an engine behaviour change. All tests live in one new file,
+`tests/Nota.SmokeTest/PanLawTests.cs`, so test tasks touching it are sequential.
+
+**Organization**: Grouped by user story (spec.md): US1 stereo image (P1), US2 older
+projects unchanged (P1), US3 switching the law (P2).
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
+- **[Story]**: US1 / US2 / US3
+
+---
+
+## Phase 1: Setup
+
+- [X] T001 Run `scripts/build.sh` on the untouched tree and note that it is green (baseline for the bit-identical checks); if it is red, stop and report — do not start the feature on a red baseline
+
+---
+
+## Phase 2: Foundational (Blocking Prerequisites)
+
+**Purpose**: the law exists as graph data, survives every edit, and is reachable
+from C ABI and C#. No sound change yet.
+
+**⚠️ CRITICAL**: No user story work can begin until this phase is complete
+
+- [X] T002 In `src/native/nota.engine/src/Graph.h` add `enum class PanLaw : int32_t { Balance = 0, Stereo = 1 };` and the field `PanLaw panLaw = PanLaw::Balance;` on `Graph` (comment: project pan law, 006; graph-level so undo/redo restore it), and add `inline void inheritGraphLevel(Graph& dst, const Graph& src)` that copies `sceneCount`, `scenes`, `masterVolume`, `masterTrack` and `panLaw`; rewrite the existing "fresh-graph builds must carry it forward" comment to say "use inheritGraphLevel()"
+- [X] T003 Replace the hand-copied graph-level lines (`g->sceneCount = authoring_->sceneCount; g->scenes = …; g->masterVolume = …; g->masterTrack = …;`) with `inheritGraphLevel(*g, *authoring_);` at every production fresh-graph site: `src/native/nota.engine/src/Engine.cpp` (`republishWithTrackRaw`, ~line 520 — keep the `masterTrack` override for `kMasterTrackId` *after* the call), `src/native/nota.engine/src/Engine_Modulation.cpp` (~309), `src/native/nota.engine/src/Engine_Session.cpp` (~113 — keep `g->sceneCount = newCount` *after* the call; ~861), `src/native/nota.engine/src/Engine_Tracks.cpp` (~461, 1382, 1502, 1534, 1564, 1619, 1754, 1896, 2439, 2491, 2686). Leave the self-test graphs in `Engine_Automation.cpp` (~75, 377, 430) and the reset graph in `Engine.cpp` (~570) as they are. Afterwards `grep -n "make_shared<Graph>()" src/native/nota.engine/src/*.cpp` and confirm every remaining hit is either followed by `inheritGraphLevel` or is one of the listed exceptions
+- [X] T004 In `src/native/nota.engine/src/Engine.h` / `Engine.cpp` add `bool setPanLaw(PanLaw law, bool checkpoint)` (return false for a value outside Balance/Stereo; no-op returning true if equal to `authoring_->panLaw`; else `auto g = std::make_shared<Graph>(*authoring_); g->panLaw = law;` then `publish(g)` when `checkpoint`, `publishRaw(g)` otherwise) and `PanLaw panLaw() const` (reads `authoring_`, Balance if null). Message thread only
+- [X] T005 Add to `src/native/nota.engine/include/nota/nota_engine.h` the block from [contracts/c-abi-pan-law.md](contracts/c-abi-pan-law.md) verbatim (`NOTA_PAN_LAW_BALANCE 0`, `NOTA_PAN_LAW_STEREO 1`, `nota_engine_set_pan_law(engine, law, checkpoint)`, `nota_engine_pan_law(engine)` with their comments) and implement both in `src/native/nota.engine/src/nota_engine_core.cpp`: unknown law → `NOTA_ERR_INVALID_ARG`, null engine → `NOTA_ERR_INVALID_ARG` / `NOTA_PAN_LAW_BALANCE`
+- [X] T006 [P] In `src/managed/Nota.Application/Engine/IAudioEngine.cs` add `public enum PanLaw { Balance = 0, Stereo = 1 }` (or in a sibling file of the same folder, SPDX header if new) and the members `PanLaw PanLaw { get; }` and `void SetPanLaw(PanLaw law, bool checkpoint = true);` with the doc comment "Project pan law (graph-level, undoable). See nota_engine_set_pan_law."; update every other `IAudioEngine` implementation the compiler reports (test fakes in `tests/Nota.SmokeTest`, MCP abstractions) with a trivial implementation
+- [X] T007 [P] Add the P/Invokes `SetPanLaw(IntPtr engine, int law, int checkpoint)` → `nota_engine_set_pan_law` and `PanLaw(IntPtr engine)` → `nota_engine_pan_law` in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs`, and the wrapper members in `src/managed/Nota.Infrastructure/Interop/NotaEngine.cs` (`ThrowIfDisposed(); Check(...)` like `SetTrackPan` in `NotaEngine.Tracks.cs`)
+- [X] T008 Create `tests/Nota.SmokeTest/PanLawTests.cs` (two-line SPDX header; file comment: "Project pan law (specs/006-stereo-pan-law): …; also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --panlaw`") with `internal static class PanLawTests { public static IEnumerable<(bool ok, string label)> Run() }` and shared helpers: `WriteStereoWav(float[] l, float[] r)` via `Nota.Infrastructure.WavWriter` (48 kHz, Float32, temp path), `Sine(hz, seconds, amp)`, `Render(NotaEngine eng, double seconds)` via `Seek(0); Play(); RenderOffline(...); Stop()`, `Goertzel(float[] interleaved, int channel, double hz, int from, int to)` returning linear amplitude, and `Db(x)`. Wire it in `tests/Nota.SmokeTest/Program.cs`: in the full run next to `ReturnDeleteTests.Run()` (~line 14566) and as a `--panlaw` branch modelled on `--returns` (~line 251)
+- [X] T009 In `tests/Nota.SmokeTest/PanLawTests.cs` add the C ABI checks from [contracts/c-abi-pan-law.md](contracts/c-abi-pan-law.md) § Behaviour guarantees: fresh engine = Balance; `Reset()` → Balance; set Stereo (checkpoint) → `Undo()` → Balance → `Redo()` → Stereo; `SetPanLaw(same)` adds no undo step (`CanUndo` count unchanged — compare by undoing once and checking the previous edit is what comes back); `checkpoint: false` adds none; invalid value (cast `(PanLaw)7`) throws/returns error and leaves the law unchanged
+- [X] T010 In `tests/Nota.SmokeTest/PanLawTests.cs` add "law survives every edit kind": set Stereo, then one each of add instrument track, add audio track, add return, remove a track, move a track, group tracks, add scene, remove scene, add a volume automation point, add a CV link (if a modulator kind is available without assets; else skip with a label), add + edit a MIDI clip, duplicate a track, undo, redo — after each assert `eng.PanLaw == PanLaw.Stereo` with a label naming the edit
+
+**Checkpoint**: `scripts/build.sh` green; the law is stored, undoable and survives edits; nothing sounds different yet.
+
+---
+
+## Phase 3: User Story 1 — Panning a stereo track moves its whole image (Priority: P1) 🎯 MVP
+
+**Goal**: under Stereo, track and return pan fold the far channel in; new projects start with Stereo.
+
+**Independent Test**: new project, stereo file with different L/R material, sweep pan C → L100: both materials stay, right side goes silent at L100.
+
+### Tests for User Story 1
+
+- [X] T011 [US1] In `tests/Nota.SmokeTest/PanLawTests.cs` add the render checks (write them before T013 and confirm they fail): audio track with a 2 s WAV, L = 440 Hz sine, R = 1 000 Hz sine, both −12 dBFS. Under Stereo at pan −1: R output both tones < −90 dBFS; L output each tone at half its source amplitude (−6.0 dB ±0.5 re source). Mirror at pan +1. At pan 0: Stereo render equals Balance render sample-for-sample (FR-003). Mono WAV (440 Hz on both channels): for p ∈ {−1, −0.6, −0.25, 0.3, 0.8, 1} the per-channel 440 Hz level under Stereo matches Balance within 0.1 dB (FR-004). Unrelated L/R (the two-tone WAV): total power (L²+R² of both tones) at pan −1 within 3.5 dB of pan 0 (FR-005)
+- [X] T012 [US1] In `tests/Nota.SmokeTest/PanLawTests.cs` add: a return (Utility device, unity) fed by a send from the two-tone track, return panned −1 under Stereo → both tones present on the return's L output, R silent; a group containing the two-tone track, group panned −0.5: render identical under Stereo and Balance (FR-010); `ProjectTemplate.ApplyDefault(eng)` on a reset engine → `eng.PanLaw == Stereo` and `CanUndo == false` (FR-007)
+
+### Implementation for User Story 1
+
+- [X] T013 [US1] In `src/native/nota.engine/src/Engine_Render.cpp` add `struct PanMatrix { float ll, lr, rl, rr; };` and `static inline PanMatrix panMatrix(float pan, float vol, PanLaw law)` implementing [research.md](research.md) R1 exactly: `θ = (pan + 1)·π/4`, `c = cos θ`, `s = sin θ`, `b = 0.5·|pan|`; Balance → `{c, 0, 0, s}`; Stereo with `pan ≤ 0` → `{c − b, b, 0, s}`; Stereo with `pan > 0` → `{c, 0, b, s − b}`; every coefficient × `vol`. Use the file's existing `kTwoPi / 8` form for θ so Balance coefficients are bit-identical to today's `cos(theta)`/`sin(theta)` (compute in double, cast to float as today)
+- [X] T014 [US1] In `src/native/nota.engine/src/Engine_Render.cpp` track stage ("3) Channel fader + equal-power pan", ~line 1264) and return stage (~line 1403): replace `gl`/`gr` with `const PanMatrix m = panMatrix(pan, vol, g->panLaw)` (the live graph pointer already used by the render); if `m.lr == 0 && m.rl == 0` keep the existing loop body unchanged (`l = in_l * m.ll; r = in_r * m.rr`) so Balance renders stay bit-identical; else `l = m.ll*in_l + m.lr*in_r; r = m.rl*in_l + m.rr*in_r`. Everything downstream (record tap, route bus, dest, sends, peak/RMS meters) keeps using `l`/`r`. Do NOT touch the group stage (~line 1337)
+- [X] T015 [US1] In `src/managed/Nota.Infrastructure/Persistence/ProjectTemplate.cs` `ApplyDefault`: call `engine.SetPanLaw(PanLaw.Stereo, checkpoint: false);` before `engine.ClearUndoHistory();`, and extend the file comment with one line: new projects use the Stereo pan law (specs/006)
+
+**Checkpoint**: US1 tests pass; a new project pans stereo tracks as whole images.
+
+---
+
+## Phase 4: User Story 2 — Existing projects sound exactly as before (Priority: P1)
+
+**Goal**: format v21 stores the law; every older project opens as Balance and is marked legacy.
+
+**Independent Test**: load a v20 document with a panned stereo track → Balance + legacy, output matches the Balance law; save/reopen keeps both.
+
+### Tests for User Story 2
+
+- [X] T016 [US2] In `tests/Nota.SmokeTest/PanLawTests.cs` add persistence checks via `ProjectStore` into a temp dir: save with Stereo → load → Stereo, `PanLawLegacy == false`; save with Balance + `PanLawLegacy = true` in the `TransportState` → load → Balance, legacy true; and the migration: build a v20 `project.json` in code (take a freshly captured v21 document's JSON, remove `mixer`, set `formatVersion` 20; one audio track with the two-tone WAV, pan −0.5), load it → law Balance, `ProjectLoadResult.Transport.PanLawLegacy == true`, and each output tone matches the Balance law (L tone × cos θ on L, R tone × sin θ on R, no cross-feed) within 0.01 dB (FR-006, SC-002); `ProjectMigrations.Migrate` on a v20 tree yields `mixer = { panLaw: "balance", panLawLegacy: true }` and leaves an existing `mixer` untouched
+
+### Implementation for User Story 2
+
+- [X] T017 [P] [US2] In `src/managed/Nota.Application/Ports/IProjectStore.cs` add `bool PanLawLegacy = false` as the last positional parameter of `TransportState` and extend its doc comment: "PanLawLegacy marks a project made before the pan law (specs/006); it only drives the Mixer's OLDER PROJECT badge"
+- [X] T018 [P] [US2] In `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs` add `public MixerDto? Mixer { get; set; }` to `ProjectDocument` and `public sealed class MixerDto { public string PanLaw { get; set; } = "balance"; public bool PanLawLegacy { get; set; } [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; } }` with a comment: absent `mixer` = a pre-v21 project = Balance + legacy
+- [X] T019 [US2] In `src/managed/Nota.Infrastructure/Persistence/ProjectService.cs` set `CurrentFormatVersion = 21`, and in `src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs` append `new Migration(20, root => { if (root["mixer"] is null) root["mixer"] = new JsonObject { ["panLaw"] = "balance", ["panLawLegacy"] = true }; })` with the comment from [contracts/project-format-v21.md](contracts/project-format-v21.md) § Migration (check the JSON naming policy used by the serializer — camelCase — and match it)
+- [X] T020 [US2] In `src/managed/Nota.Infrastructure/Persistence/ProjectService.cs` capture: `doc.Mixer = new MixerDto { PanLaw = engine.PanLaw == PanLaw.Stereo ? "stereo" : "balance", PanLawLegacy = transport.PanLawLegacy }` (thread `TransportState` into capture the same way `Transport` is filled, ~line 61); apply: right after `engine.Reset()` (~line 436) call `engine.SetPanLaw(law, checkpoint: false)` where `law` = Stereo for `"stereo"`, Balance for `"balance"` or a null `Mixer`; any other string → Balance plus a load warning "Unknown pan law '…' — using Balance"
+- [X] T021 [US2] In `src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs` map `doc.Mixer?.PanLawLegacy ?? true` into `ProjectLoadResult.Transport.PanLawLegacy` (~line 25, where the transport is built)
+- [X] T022 [P] [US2] In `src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs` list a change of `mixer.panLaw` between two versions as the sound change "Pan law" (pattern: the `master.devices` comparison ~line 82)
+- [X] T023 [US2] In `src/managed/Nota.App/MainWindow.Recovery.cs` / `MainWindow.Files.cs`: add `private bool _panLawLegacy;` to `MainWindow`; set it from `ProjectLoadResult.Transport.PanLawLegacy` wherever a project or autosave is loaded; set `false` where a new project is built (`MainWindow.Files.cs` ~line 187 and `MainWindow.Recovery.cs` ~line 97, both after `ProjectTemplate.ApplyDefault`); pass it as the last argument in `TransportSnapshot()`
+
+**Checkpoint**: US2 tests pass; a 0.52.x project opens, sounds the same, and stays marked after save.
+
+---
+
+## Phase 5: User Story 3 — Switching the pan law of a project (Priority: P2)
+
+**Goal**: the Mixer footer shows and switches the law, click-free, undoable, with the OLDER PROJECT and BAL badges.
+
+**Independent Test**: open a legacy project, switch to Stereo while playing, hear the change without a click, undo, save/reopen — per [quickstart.md](quickstart.md) § 2.
+
+### Tests for User Story 3
+
+- [X] T024 [US3] In `tests/Nota.SmokeTest/PanLawTests.cs` add the click test (write before T025, confirm it fails): two-tone WAV track at pan −1, render 1 s under Balance into a buffer in blocks of 256 frames via repeated `RenderOffline` calls (keep transport playing), call `SetPanLaw(Stereo)` between two blocks, continue 0.5 s; assert the largest sample-to-sample step on each channel across the switch ≤ 1.5 × the largest step of the same channel in the steady state before it (SC-004); also flip back within 5 ms of the first flip and assert the same bound
+
+### Implementation for User Story 3
+
+- [X] T025 [US3] In `src/native/nota.engine/src/Engine.h` add audio-thread-owned members `PanLaw renderedPanLaw_ = PanLaw::Balance; int32_t panLawXfadeLeft_ = 0; int32_t panLawXfadeLen_ = 0; float panLawXfadeFrom_ = 0.f;` (comment: law crossfade state, render thread only, 006) and in `src/native/nota.engine/src/Engine_Render.cpp` implement the crossfade from [data-model.md](data-model.md) § Render state: at the start of each block in `processBlock` compute `panLawXfadeLen_ = max(1, int(0.010 * sampleRate))` from the rate this block renders at; if `g->panLaw != renderedPanLaw_` and no fade runs, start one; if the law flips back mid-fade, restart from the current mix point (`panLawXfadeFrom_`). In the track and return stages, while a fade runs build `mOld = panMatrix(pan, vol, renderedPanLaw_)` and `mNew = panMatrix(pan, vol, g->panLaw)` and lerp the four coefficients per sample with `t = from + (1 − from) · (done + i) / len`; after all stages of the block advance the counter by `frames` and, at 0, set `renderedPanLaw_ = g->panLaw`. No allocation, no lock; the no-fade path is the T014 code unchanged. Also set `renderedPanLaw_` directly (no fade) when the graph is replaced by `nota_engine_reset` or a project load while stopped, so a load never fades
+- [X] T026 [US3] In `src/managed/Nota.App/MixerView.cs` `Footer()`: height 34 → 44; between the Show toggles and the crossfader add a 1 px divider (20 px tall, `BorderDefault`) and the PAN LAW group per [contracts/ui-mixer-footer.md](contracts/ui-mixer-footer.md): label "PAN LAW" (10 px, bold, letter-spacing .14em, `TextTertiary`), the shell segmented control (`Border.segmented` + `ToggleButton.seg` classes from `Theme/NotaTheme.axaml`) with "Stereo" / "Balance" and the tooltips "Panning moves the whole stereo image; nothing is dropped" / "Panning attenuates the opposite channel (legacy behaviour)", the hint `TextBlock` (11 px, `TextTertiary`) "Pan moves the whole image of stereo tracks and returns" / "Pan attenuates the opposite channel, as in earlier versions", and the OLDER PROJECT badge (Mono 9 px, letter-spacing .18em, 18 px tall, 1 px `BorderDefault`, radius 3, `TextTertiary`, tooltip "Projects saved before stereo pan law open with Balance so existing mixes do not change"). Clicking the unselected segment calls `_engine.SetPanLaw(law, checkpoint: true)`; the selected one does nothing
+- [X] T027 [US3] In `src/managed/Nota.App/MixerView.cs` `PanRow`: for group strips (`ti.IsGroup`) add the BAL badge under the "PAN" label (Mono 7 px, letter-spacing .12em, 11 px tall, 1 px `BorderDefault`, radius 3, `TextTertiary`, tooltip "Groups keep a unity-centre balance so grouping stays level-transparent"), collected in a `List<Control> _balBadges` cleared in `Refresh()`
+- [X] T028 [US3] In `src/managed/Nota.App/MixerView.cs` add `public Func<bool>? IsOlderProject { get; set; }` and `SyncPanLaw()` that reads `_engine.PanLaw` and sets the selected segment, the hint text, OLDER PROJECT visibility (`IsOlderProject?.Invoke() == true && law == Balance`) and every `_balBadges` visibility (`law == Stereo`), touching controls only when the law or the legacy flag changed since the last call; call it at the end of `Refresh()` and in `UpdateMeters()`. In `src/managed/Nota.App/MainWindow.axaml.cs` (where `_mixer` is constructed) set `_mixer.IsOlderProject = () => _panLawLegacy;`
+
+**Checkpoint**: US3 tests pass; the footer works per quickstart § 2.
+
+---
+
+## Phase 6: Polish & Cross-Cutting Concerns
+
+- [X] T029 UI verification per [quickstart.md](quickstart.md) § 2 with the headless/in-app harness (isolate with `NOTA_DATA_DIR`): new project → Stereo + BAL on a group; a 0.52.x project → Balance + OLDER PROJECT; switch during playback, ⌘Z from the main window and from the Mixer, save/reopen; screenshots of the footer in Ember Graphite and Ember Paper compared with `nota-design/Nota Mixer v2.html`
+- [X] T030 [P] Performance sanity: time `RenderOffline` of the smoke-test project with 32 stereo tracks panned −0.5 under Balance vs Stereo; Stereo within +5 % (plan § Performance Goals). Record the numbers in the PR description, not in code
+
+### Nota closing tasks
+
+- [X] T031 Run `scripts/build.sh` until native + managed + smoke test are green (and `scripts/build-linux.sh` / `scripts/build-win.ps1` if available on this machine; otherwise note CI covers them)
+- [X] T032 AGPL-3.0-only SPDX two-line header on every new source file — `tests/Nota.SmokeTest/PanLawTests.cs` (and the `PanLaw` enum file if T006 created one)
+- [X] T033 New dependency: N/A
+- [X] T034 `CHANGELOG.md` `[Unreleased]`: Added — "Stereo pan law: panning a stereo track or return moves its whole image instead of dropping a channel. New projects use it; the Mixer footer shows and switches the project's pan law." Changed — "Existing projects keep the Balance pan law and sound exactly as before (marked Older project in the Mixer)." Follow the repo's entry style
+- [X] T035 FEATURES.md via the `nota-features` skill (Tracks and mixer: pan law); user docs EN + RU via the `nota-docs` skill (Mixer page: a "Pan law" section — the two laws, why older projects keep Balance, the BAL badge on groups — with the footer screenshot in both themes); shortcuts: N/A
+- [X] T036 Engine behaviour change → smoke test extended: done in T008–T012, T016, T024 — confirm all `PanLawTests` labels appear and pass in the full run and with `--panlaw`
+
+---
+
+## Dependencies & Execution Order
+
+### Phase Dependencies
+
+- **Setup (T001)** → **Foundational (T002–T010)** → user stories → **Polish (T029–T036)**
+- **US1 (T011–T015)** and **US2 (T016–T023)** both depend only on Foundational
+- **US3 (T024–T028)** depends on Foundational and on T014 (the crossfade wraps the
+ matrix pan stage); its UI (T026–T028) uses `_panLawLegacy` from T023
+
+### Within the phases
+
+- T002 → T003 → T004 → T005 → T007; T006 ∥ T007 after T005
+- T008 → T009 → T010 (same file)
+- Tests in one file are sequential: T011 → T012 → T016 → T024
+- T013 → T014; T015 after T006
+- T017 ∥ T018 ∥ T022; T019 → T020 → T021; T023 after T017 + T021
+- T025 after T014; T026 → T027 → T028 (same file)
+
+### Parallel Opportunities
+
+- T006 and T007 (Application vs Infrastructure)
+- After Foundational: engine work for US1 (T013–T014) alongside managed persistence for US2 (T017–T022)
+- T017, T018, T022 touch different files
+- T030 alongside T029
+
+## Parallel Example: after Foundational
+
+```bash
+Task: "T013–T014 Stereo pan matrix in src/native/nota.engine/src/Engine_Render.cpp"
+Task: "T017 TransportState.PanLawLegacy in src/managed/Nota.Application/Ports/IProjectStore.cs"
+Task: "T018 MixerDto in src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs"
+Task: "T022 Pan law in src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs"
+```
+
+## Implementation Strategy
+
+### MVP
+
+US1 alone changes how every new project sounds, but without US2 an *old* project
+would also open with the engine default — which is Balance, so old projects are
+already safe after Foundational + US1. US2 adds the explicit format and the legacy
+mark; US3 adds the switch. Ship **all three together** (one PR, constitution V):
+US1 without US3 would leave users unable to see or change the law.
+
+### Incremental order
+
+1. T001–T010 → build green, nothing audible changed
+2. US1 → new projects pan in stereo
+3. US2 → format v21, older-project mark
+4. US3 → crossfade + Mixer footer
+5. Polish → UI verification, docs, final build
+
+## Notes
+
+- Do not commit or push — the user reviews and commits.
+- `.specify/feature.json` points at `specs/007-midi-note-editing` (another session); run any spec-kit script for this feature with `SPECIFY_FEATURE_DIRECTORY=specs/006-stereo-pan-law SPECIFY_FEATURE_NO_PERSIST=1`.
+
+## Phase 7: Convergence
+
+- [X] T037 Reconcile the undo label in FR-009 ("one undo step (labelled "pan law")"): Nota's engine undo has no step labels (`nota_engine_undo`, research R7), so either drop the label from the spec via `/speckit-clarify` or record it as out of scope — no code change unless a labelled-undo system is specified separately per FR-009 (partial)
+- [X] T038 Make a project load / `nota_engine_reset` take the new pan law without the 10 ms crossfade (in `src/native/nota.engine/src/Engine_Render.cpp` / `Engine.cpp`: when the graph is replaced by reset or load, set `panLawFrom_ = panLawTo_ = law` and `panLawPos_ = 1` on the audio side), or record in `specs/006-stereo-pan-law/research.md` R4 why the fade on load is kept per T025 / data-model § Render state (partial)
+- [X] T039 Add a sample-exact null test to `tests/Nota.SmokeTest/PanLawTests.cs`: render the v20 fixture project and compare it per sample with the Balance law computed from the source WAV (`cos θ·L`, `sin θ·R` × track volume), asserting the residual is below −120 dBFS per SC-002 (partial)
diff --git a/specs/008-stereo-map/checklists/requirements.md b/specs/008-stereo-map/checklists/requirements.md
new file mode 100644
index 00000000..ba0711b3
--- /dev/null
+++ b/specs/008-stereo-map/checklists/requirements.md
@@ -0,0 +1,40 @@
+# Specification Quality Checklist: Stereo Map (MVP)
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-14
+**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
+
+- Resolved 2026-10-14 (option C): volume/pan become undoable everywhere through a separate
+ prerequisite spec; FR-017 only requires a map gesture to be one step of it.
+- FR-001…FR-004 and FR-019 quote layout and copy from the design mock — deliberate: the
+ mock is the agreed source.
+- FR-005's measurement definitions (balance, width, correlation) are stated as what is
+ measured, not how; formulas are left to the plan.
+- Y range follows the Mixer fader (≈ +3.5 dB top), not the mock's +6 dB — see Assumptions.
diff --git a/specs/008-stereo-map/contracts/c-abi-stereo-measures.md b/specs/008-stereo-map/contracts/c-abi-stereo-measures.md
new file mode 100644
index 00000000..4a054a32
--- /dev/null
+++ b/specs/008-stereo-map/contracts/c-abi-stereo-measures.md
@@ -0,0 +1,35 @@
+# Contract: C ABI — stereo measurements
+
+Added to `src/native/nota.engine/include/nota/nota_engine.h` (AR-7), implemented in
+`nota_engine_core.cpp` (or `nota_engine_track.cpp`, next to the meter getters).
+
+```c
+/* ---- Stereo measurements (008) ------------------------------------------- */
+/* What each track, return and the master sends to the master, post-fader and post-pan,
+ * averaged over ~300 ms: level, where it sits (balance on the pan scale: a mono source
+ * panned to p measures p), how wide it is (1 - correlation, clamped 0..1) and the
+ * correlation. Groups are not measured. Message thread; lock-free reads. */
+typedef struct NotaStereoMeasure {
+ int32_t track_id; /* a track / return id, or nota_engine_master_track_id() */
+ float level_db; /* RMS of the pair, dBFS; -200 for silence */
+ float balance; /* -1 (left) .. +1 (right) */
+ float width; /* 0 (mono) .. 1 (unrelated or anti-phase) */
+ float correlation; /* -1 .. +1; 0 when either side is silent */
+} NotaStereoMeasure;
+
+/* Fills up to cap rows (tracks and returns in track order, the master last) and returns
+ * the number available (call again with a bigger buffer if it exceeds cap). */
+NOTA_API int32_t nota_engine_stereo_measures(const NotaEngine* engine, NotaStereoMeasure* out, int32_t cap);
+```
+
+## Guarantees (smoke test, WAV material at 48 kHz, Stereo pan law, after ≥ 1.5 s of play)
+
+| Material | Expect |
+|---|---|
+| mono 440 Hz, pan L50 | balance −0.50 ± 0.05, width < 0.05, correlation > 0.95 |
+| L 440 Hz / R 1 kHz (unrelated), pan C | balance 0 ± 0.05, width > 0.95, \|correlation\| < 0.05 |
+| L = sine, R = −sine | correlation < −0.95, width = 1 |
+| silence | level_db < −60 |
+| the unrelated pair as the only track | the master row matches the track row (± 0.05) |
+| muted track | its level drops ≥ 20 dB within 1.5 s (τ = 0.3 s; the map hides a muted cloud at once from the mute flag) |
+| unmuted again | within 3 dB of the steady level after 0.5 s (SC-005) |
diff --git a/specs/008-stereo-map/contracts/ui-stereo-map.md b/specs/008-stereo-map/contracts/ui-stereo-map.md
new file mode 100644
index 00000000..4ff79ea2
--- /dev/null
+++ b/specs/008-stereo-map/contracts/ui-stereo-map.md
@@ -0,0 +1,47 @@
+# Contract: UI — Mixer window views and the Stereo Map
+
+Source of truth: `nota-design/Nota Mixer v2.html` (title bar, map panel, footer). Ember tokens
+(`DESIGN.md`, `nota-design` skill), both themes. Only the MVP parts below.
+
+## Mixer window title bar (`MixerWindow.cs`)
+
+36 px own title bar (macOS/Windows; Linux: a 32 px row at the top of the body):
+"Mixer" caption left (as other windows), the shell segmented control **Strips | Stereo
+Map** centred, nothing else. Selecting a segment sets `MixerView.View` and
+`Settings.MixerView`.
+
+## Layout in the Stereo Map view (`MixerView.cs`)
+
+`Grid` columns `*, Auto`: the map panel (min 520 px) | the strips scroller (max 440 px,
+horizontal scroll). Gap 8 px, outer padding 8 px. The footer (Show, PAN LAW, crossfader)
+stays under both. In the Strips view the map panel is removed and the strips take the width.
+
+## Map panel
+
+| Part | Spec |
+|---|---|
+| Panel | `SurfaceCard`, 1 px `BorderDefault`, radius 6 |
+| Header row (36 px, bottom hairline) | "STEREO MAP" — 10 px bold, letter-spacing 1.4, `TextPrimary` (MVP: no Y switch, filters or tools) |
+| Plane well | `BgSunken`, 1 px `BorderDefault`, radius 4, inner padding 14 / 18 / 22 / 40 (top / right / bottom / left) |
+| Vertical grid | at L100, L50, C, R50, R100; C line `BorderDefault`, others `GridBeat`; labels under the plane, Mono 8 px, `TextTertiary` |
+| Horizontal grid | at the fader positions of +3.5 (top), 0, −6, −12, −24 dB; 0 dB line `BorderDefault`; labels left of the plane, right-aligned, Mono 8 px, `TextTertiary` ("+3.5", "0 dB", "−6", "−12", "−24") |
+| Cloud | ellipse at the handle's Y, height 22 px; X from `balance − width` to `balance + width` on the pan scale (min width 1.6 % of the plane); fill = track colour at opacity `0.10 + 0.32 × clamp((level + 60) / 54, 0, 1)` (× 0.35 when dimmed by solo); 1 px outline in the track colour, `Danger` when correlation < −0.05; none when silent or muted |
+| Handle | 16 px circle, track colour fill, 2 px ring `BgSunken` (`Danger` when correlation < −0.05); muted or solo-dimmed: fill `SurfaceHover`; cursor grab (master: pointer) |
+| Selected | 22 px ring, 2 px `Accent`, around the handle; drawn on top |
+| Label | 10 px medium, right of the handle (+13, −7), max 84 px, ellipsis; `TextSecondary`, selected `TextPrimary`, dimmed `TextDisabled`; hidden if it would overlap a placed label |
+| Tooltip | 188 px, `TooltipBg`, 1 px `BorderStrong`, radius 4, padding 8 / 10; name row (8 px colour dot + 11 px semibold `TextPrimary`); rows PAN, VOLUME, BALANCE, WIDTH, CORRELATION, LEVEL — key 7 px bold `TextTertiary` 62 px wide, value Mono 9 px (correlation < −0.05 in `Danger`); notes separated by a hairline: "Image is off the pan" (title `Accent`), "Muted", "Silent" (title `TextSecondary`), body 9 px `TextTertiary`; placed right/below the handle, flipped left/up near the edges |
+| Bottom row (32 px, top hairline) | "MASTER CORR" 8 px bold `TextTertiary`; "−1"; a 180 × 6 well with a centre tick and a bar from centre to the value (`Success` ≥ −0.05, `Danger` < −0.05); "+1"; the value Mono 10 px (`Danger` when < −0.05); right-aligned hint 10 px `TextTertiary`: "Drag: pan + volume · Shift locks axis · double-click centres pan · ⌥ double-click 0 dB" |
+
+## Texts (exact)
+
+- Tooltip notes: **Image is off the pan** — "The pan is at {pan}, but the signal measures
+ {balance}. The source itself is unbalanced."; **Muted** — "No cloud while the track is
+ muted."; **Silent** — "Below −60 dBFS, so the cloud is hidden."
+- LEVEL reads "below −60 dBFS" when silent; pan reads "C" / "L40" / "R25"; volume "−3.0 dB",
+ "−∞".
+
+## Not in the MVP
+
+The mock's Y switch (Volume / Frequency), the All/Tracks/Returns/Selected filter, Conflicts,
+Hold, Mono, Export PNG, the REMOTE indicator, marquee / multi-select, the WRITE badge and
+the phone panel.
diff --git a/specs/008-stereo-map/data-model.md b/specs/008-stereo-map/data-model.md
new file mode 100644
index 00000000..dfe6bdd9
--- /dev/null
+++ b/specs/008-stereo-map/data-model.md
@@ -0,0 +1,40 @@
+# Data Model: Stereo Map (MVP)
+
+## Engine — stereo energies (audio thread writes, message thread reads)
+
+| Where | Fields | Rules |
+|---|---|---|
+| `Track` (tracks and returns) | `std::atomic<float> stereoL_, stereoR_, stereoLR_` | exponential averages of L², R², L·R of the post-fader post-pan signal, τ = 0.3 s; fed zeros while muted / solo-gated |
+| `Engine` (master) | `std::atomic<float> masterStereoL_, …R_, …LR_` | same, after the master volume |
+
+## C ABI — one measurement row ([contract](contracts/c-abi-stereo-measures.md))
+
+| Field | Type | Range |
+|---|---|---|
+| `track_id` | `int32_t` | track / return id, or the master track id |
+| `level_db` | `float` | ≤ 0 typically; −∞ (−200) for silence |
+| `balance` | `float` | −1 … +1, pan scale (research R2) |
+| `width` | `float` | 0 … 1 |
+| `correlation` | `float` | −1 … +1 |
+
+`silent` = `level_db < −60` (derived by the caller).
+
+## Managed
+
+| Name | Layer | Role |
+|---|---|---|
+| `StereoMeasure` (record struct, mirrors the native row) | Nota.Application | |
+| `IAudioEngine.GetStereoMeasures(Span<StereoMeasure>)` → count | Nota.Application port | one call per frame |
+| `Settings.MixerView` | Nota.Application | `"strips"` (default) \| `"map"` |
+| `MixerView.View` | Nota.App | Strips / StereoMap; switches layout |
+| `StereoMapView` | Nota.App | the map control (render + input) |
+
+### Map handle (per frame, view-local)
+
+| Field | From |
+|---|---|
+| id, name, colour index | track list (`TryGetTrackInfo`, `TrackNames`, `EffectiveColorIndex`) |
+| x = pan, y = fader position | `TrackInfo.Pan`, `TrackInfo.Volume` (master: x = 0, y = master volume) |
+| muted, dimmed (solo active and not soloed, not a return / master) | `TrackInfo` |
+| selected | `Timeline.SelectedTrackId` |
+| cloud | the measurement row for the id |
diff --git a/specs/008-stereo-map/plan.md b/specs/008-stereo-map/plan.md
new file mode 100644
index 00000000..9a34071f
--- /dev/null
+++ b/specs/008-stereo-map/plan.md
@@ -0,0 +1,173 @@
+# Implementation Plan: Stereo Map (MVP)
+
+**Branch**: `008-stereo-map` | **Date**: 2026-10-14 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `/specs/008-stereo-map/spec.md`
+
+## Summary
+
+The Mixer window gets a **Strips | Stereo Map** switch in its own title bar. The Stereo Map
+is one custom-drawn control: every track, return and the master as a handle at (pan, fader)
+with a cloud showing where its sound really is (balance), how wide (1 − correlation) and how
+loud, plus a master correlation bar. The engine measures each track's post-fader, post-pan
+signal in the existing meter pass — one extra multiply-add per sample (`ΣL·R`) and three
+running averages — and hands all rows over in one C ABI call per frame. Dragging a handle is
+one mix gesture over pan and volume (spec 009), with the same automation rules as the strip
+controls; clicking selects the track everywhere. See [research.md](research.md).
+
+## Nota: Read Before Planning
+
+- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-6 (the audio thread only
+ adds a sum and updates three atomics per track per segment), AR-7 (one new C ABI call).
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill; the design
+ reference `nota-design/Nota Mixer v2.html`.
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (managed app)
+
+**Primary Dependencies**: Avalonia (existing); no new dependency
+
+**Storage**: `Settings.MixerView` (user preference); nothing in the project file
+
+**Audio-Thread Impact**: the track, return and master loops in `Engine_Render.cpp` add
+`sLR += l·r` next to the existing `sqL`/`sqR`; after each loop, three exponential averages
+are updated with one `exp` per segment (cached per sample rate / frame count where possible)
+and stored in atomics. No allocation, no lock, no extra pass over the buffer.
+
+**Testing**: `scripts/build.sh` → `StereoMeasureTests` (WAV material); headless UI harness
+for the map ([quickstart.md](quickstart.md))
+
+**Target Platform**: macOS / Windows / Linux desktop app
+
+**Project Type**: desktop-app (engine + managed UI)
+
+**Performance Goals**: 60 fps with 128 tracks (SC-003): one custom `Render`, one native call
+per frame; ≤ 1 % of the audio block time added with 64 tracks (SC-004)
+
+**Constraints**: map Y equals the strip fader's mapping (linear gain 0…1.5); exact text and
+tokens from [contracts/ui-stereo-map.md](contracts/ui-stereo-map.md)
+
+**Scale/Scope**: engine ~80 lines; managed ~700 lines (map control ~500, Mixer layout and
+title bar, settings, selection hook); smoke ~200 lines
+
+## Constitution Check
+
+| Principle | Status |
+|---|---|
+| I. Real-time audio safety | ✅ One sum per sample + three atomics per segment; no alloc / lock / I/O |
+| II. Boundary discipline | ✅ `NotaStereoMeasure` + `nota_engine_stereo_measures` |
+| III. Licensing hygiene | ✅ New files with SPDX; no dependency |
+| IV. Verification gate | ✅ Engine behaviour added → `StereoMeasureTests` |
+| V. One logical change | ✅ The map MVP; V2/V3 are separate specs |
+| VI. Docs in sync | ⏳ CHANGELOG, `nota-features`, `nota-docs` (Mixer page + shots) |
+| VII. Spec-first | ✅ |
+| VIII. Rules not weakened | ✅ |
+
+Post-design re-check: unchanged — all gates pass.
+
+## Design
+
+### 1. Engine — measuring ([research R1, R2](research.md))
+
+- `Track.h`: `std::atomic<float> stereoL_{0}, stereoR_{0}, stereoLR_{0}` + `setStereo(…)` /
+ getters. `Engine.h`: master counterparts.
+- `Engine_Render.cpp`: in the track stage, the return stage and the master loop add
+ `sLR += l * (double)r`; after each loop update the averages with
+ `a = 1 − exp(−frames / (0.3 · sr))`; a track that is `!toMix` (muted / solo-gated) feeds
+ zeros. Groups untouched.
+- C ABI ([contract](contracts/c-abi-stereo-measures.md)): `NotaStereoMeasure`,
+ `nota_engine_stereo_measures` — derives level / balance / width / correlation (R2) from the
+ authoring graph's tracks (not groups) in track order, the master last.
+
+### 2. Managed port
+
+`StereoMeasure` record struct (blittable) in `EngineContracts.cs`;
+`IAudioEngine.GetStereoMeasures(StereoMeasure[] buffer)` → count; P/Invoke + wrapper.
+`Settings.MixerView` (`"strips"` | `"map"`).
+
+### 3. Mixer window and layout ([contract](contracts/ui-stereo-map.md))
+
+- `MixerWindow`: own 36 px title bar (`base(36)` like `DeviceWindow`), caption left, the
+ Strips | Stereo Map segments centred (`ClipEditorKit.Segments`); Linux: the same row at the
+ top of the body.
+- `MixerView.View` (enum): rebuilds the content grid — Strips: strips only; Stereo Map:
+ `StereoMapView` (`*`) + strips scroller (max 440 px). Reads/writes `Settings.MixerView`.
+
+### 4. `StereoMapView` (new, `Nota.App/StereoMapView.cs`)
+
+- Pulls per frame: track infos (id, name, colour, pan, volume, mute, solo, return/group flags),
+ `GetStereoMeasures`, `MasterVolume`, the selected id (callback from `MainWindow`).
+- Renders grid, clouds, handles, labels (greedy, R7), selection ring, tooltip, master
+ correlation bar, per the UI contract; `RequestAnimationFrame` loop while attached and visible.
+- Input: hit-test handles (16 px + 4 px slop, topmost first); drag → `MixGesture(Volume, Pan)`
+ begin → `BeginAutomationWrite` (volume + pan) → live `SetTrackPan` / `SetTrackVolume` from
+ the deltas (Shift: dominant axis) → `EndAutomationWrite` → gesture end; double-click /
+ ⌥ double-click → one-shot reset; click without moving → `SelectTrack(id)` callback.
+ Master: select only.
+- Callbacks set by `MainWindow`: `SelectedTrackId` (`() => Timeline.SelectedTrackId`),
+ `SelectTrack` (`id => Timeline.SelectTrackFromOutside(id)`).
+
+### 5. Selection hook
+
+`ArrangementView.SelectTrackFromOutside(int id)`: `Select(id, -1)` + `TrackSelected?.Invoke(id)`.
+
+### 6. Smoke test + docs
+
+- `tests/Nota.SmokeTest/StereoMeasureTests.cs` (new, SPDX) per the contract + SC-004 check;
+ `Program.cs` full run + `--stereomap`.
+- `CHANGELOG.md`, `nota-features`, `nota-docs` (Mixer page "Stereo Map" section, the `mixer`
+ shots scene gains `view: map`).
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/008-stereo-map/
+├── spec.md
+├── plan.md
+├── research.md
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── c-abi-stereo-measures.md
+│ └── ui-stereo-map.md
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (repository root)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # NotaStereoMeasure, nota_engine_stereo_measures
+└── src/
+ ├── Track.h # stereo energy atomics
+ ├── Engine.h # master energies
+ ├── Engine_Render.cpp # ΣL·R + averages in track / return / master loops
+ └── nota_engine_core.cpp # C ABI (derivation)
+src/managed/
+├── Nota.Application/Engine/EngineContracts.cs, IAudioEngine.cs; Settings.cs
+├── Nota.Infrastructure/Interop/NativeMethods.cs, NotaEngine.cs
+└── Nota.App/StereoMapView.cs (new), MixerView.cs, MixerWindow.cs, ArrangementView.cs,
+ MainWindow.axaml.cs (callbacks)
+tests/Nota.SmokeTest/StereoMeasureTests.cs (new), Program.cs
+CHANGELOG.md, FEATURES.md
+```
+
+**Structure Decision**: existing projects; two new source files.
+
+## Out of Scope / Known Gaps
+
+- Everything listed as V2 / V3 in the spec.
+- The Y axis is linear in gain to match the fader (research R3): quiet tracks bunch near the
+ bottom. A dB taper for both the fader and the map would be its own change.
+- Width and balance formulas differ from the feature description (research R2) — flagged
+ for review.
+- Pre-fader views are not offered.
+
+## Complexity Tracking
+
+No constitution violations.
diff --git a/specs/008-stereo-map/quickstart.md b/specs/008-stereo-map/quickstart.md
new file mode 100644
index 00000000..2ff69ad4
--- /dev/null
+++ b/specs/008-stereo-map/quickstart.md
@@ -0,0 +1,35 @@
+# Quickstart: validating the Stereo Map (MVP)
+
+## 1. Automated (the PR gate)
+
+```bash
+scripts/build.sh
+```
+
+The smoke test gains `StereoMeasureTests` (alone: `dotnet run --project tests/Nota.SmokeTest -- --stereomap`):
+every row of [contracts/c-abi-stereo-measures.md](contracts/c-abi-stereo-measures.md) §
+Guarantees, plus the measuring-cost check (SC-004).
+
+## 2. In the app (headless harness — memory "Nota UI verify recipe", `NOTA_DATA_DIR`)
+
+1. New project, Mixer (⌘⇧M), title bar **Stereo Map**: the map shows the instrument and audio
+ tracks, both returns and the master; strips in the right column; the choice is remembered
+ after closing and reopening the window.
+2. Play a mono WAV panned L50 and a wide stereo WAV at C: the first cloud is narrow and
+ centred on its handle near L50; the second spans nearly the full width; tooltips read the
+ values from § 1 (± 0.05).
+3. Drag a handle left-down with real mouse input: pan and volume change together, the strip
+ follows; ⌘Z restores both in one step. Shift-drag moves one axis. Double-click → C;
+ ⌥ double-click → 0 dB. The master handle does not move.
+4. Mute a track → dimmed handle, no cloud; solo another → the rest dimmed.
+5. Click a handle → the arrangement selects that track; select another track in the
+ arrangement → the ring moves on the map.
+6. 20 tracks stacked at C / 0 dB: no two labels overlap; the selected one is on top.
+7. Screenshots of the Mixer in the Stereo Map view in both themes, compared with
+ `nota-design/Nota Mixer v2.html`; frame time with 128 tracks under 16 ms.
+
+## 3. Docs
+
+`CHANGELOG.md` `[Unreleased]`; FEATURES.md (Tracks and mixer); user docs EN + RU — the Mixer
+page gets a "Stereo Map" section with screenshots in both themes (`nota-docs`, new shots in
+`shots/manifest.yml`, the `mixer` scene gains a `view: map` arg).
diff --git a/specs/008-stereo-map/research.md b/specs/008-stereo-map/research.md
new file mode 100644
index 00000000..1707c4ee
--- /dev/null
+++ b/specs/008-stereo-map/research.md
@@ -0,0 +1,122 @@
+# Research: Stereo Map (MVP)
+
+## R1. What is measured, and where
+
+**Decision**: the engine already accumulates, per segment, `ΣL²` and `ΣR²` of every track's
+and return's post-fader, post-pan signal (the meter pass in `Engine_Render.cpp`) and of the
+master (after master volume). Add one more sum, `ΣL·R`, in the same three loops — one
+multiply-add per sample, no extra pass (FR-007). Per segment, fold the three block means
+into exponential averages on the track (`Track`: three `std::atomic<float>`) and on the
+engine for the master:
+
+```text
+a = 1 − exp(−frames / (τ · sampleRate)), τ = 0.3 s
+eL += a (ΣL²/n − eL); eR += a (ΣR²/n − eR); eLR += a (ΣLR/n − eLR)
+```
+
+A muted / solo-gated track feeds zeros, so its averages decay (FR-010). Groups are not
+measured (not drawn). Torn reads across the three atomics are harmless for a display.
+
+**Rationale**: three running energies are all the map needs — every displayed value is
+derived from them on the message thread (R2), so the audio-thread cost is the minimum.
+τ = 0.3 s matches the requested ~300 ms window and reacts within SC-005 (63 % in 0.3 s,
+95 % in 0.9 s; a cloud appears/disappears within 0.5 s of a change at its threshold).
+
+**Alternatives**: ring buffers of samples per track for the UI to analyse — memory per track
+and a copy per block; needed only for V2's spectrum. Rejected for the MVP.
+
+## R2. The displayed values
+
+Computed in the C ABI getter from `eL`, `eR`, `eLR` (message thread):
+
+| Value | Formula | Why |
+|---|---|---|
+| **level** (dBFS) | `10·log10((eL + eR) / 2)` | RMS of the pair |
+| **silent** | level < −60 dBFS | FR-006 |
+| **balance** (−1…+1, on the pan scale) | `(4/π) · atan2(√eR, √eL) − 1` | the pan that would put a mono source at this energy balance — so a mono track panned L50 measures exactly −0.5 and its cloud sits on its handle |
+| **correlation** (−1…+1) | `eLR / √(eL · eR)` (0 if either side is silent) | |
+| **width** (0…1) | `clamp(1 − correlation, 0, 1)` | mono (panned or not) → 0; unrelated channels → 1; anti-phase → 1 (and a red outline) |
+
+**Decisions that differ from the feature description** (recorded for review):
+
+- *Balance as `(R²−L²)/(L²+R²)`* (the description's formula) puts a mono source panned L50
+ at −0.71 under the equal-power law, i.e. its cloud would sit visibly left of its own handle
+ and trigger the "Image is off the pan" note for every panned mono track. The inverse-pan
+ form keeps the same information (energy left vs right) on the X axis's own scale.
+- *Width as `S/(M+S)`* gives 0.5 for unrelated left/right material (not "nearly the full
+ width", US1 scenario 2 / FR-021) and a non-zero width for a panned mono source (a point
+ source drawn as a smear). `1 − correlation` is 0 for any mono source, wherever it is
+ panned, and 1 for unrelated or anti-phase material — what the cloud is meant to show.
+
+## R3. Y axis = the Mixer fader's scale
+
+**Decision**: Y is the Mixer `VFader`'s mapping — **linear in gain**, 0 … 1.5 (≈ +3.5 dB) —
+so a handle and its strip fader always sit at the same height (spec FR-003, assumption).
+Grid lines are drawn at the linear positions of +3.5 (top), 0, −6, −12, −24 dB.
+
+**Consequence (flag for the user)**: on a linear-gain scale 0 dB sits at 67 % of the height
+and −24 dB at 4 %, so quiet tracks bunch near the bottom; the mock's dB-curved axis spreads
+them out. Matching the fader was the spec's choice; a dB taper for *both* the Mixer fader and
+the map is a separate, small change worth considering later.
+
+## R4. Rendering at 60 fps
+
+**Decision**: `StereoMapView` is one custom-drawn control (`Render` override: grid, clouds,
+handles, labels, tooltip, master correlation bar) — no control per track. While it is visible
+it requests animation frames (`TopLevel.RequestAnimationFrame`), and each frame pulls all
+measurements in one C ABI call and the track list from the engine. The app's 33 ms UI tick
+is too slow for SC-003.
+
+**Rationale**: 128 tracks × (ellipse + circle + text) per frame is a few hundred draw calls —
+cheap for Skia; one native call per frame instead of 128.
+
+## R5. Mixer window: Strips | Stereo Map
+
+**Decision**: `MixerWindow` switches to its own 36 px title bar (as `DeviceWindow` does):
+"Mixer" left, the shell segmented control **Strips | Stereo Map** centred (FR-001). On
+Linux (native frame) the switch sits at the top of the body. `MixerView` gets a `View`
+property: in **Stereo Map** the map fills the left (`*`) and the strips scroll in a right
+column capped at 440 px (FR-002); the footer stays. The choice is a user preference,
+`Settings.MixerView` (`"strips"` default | `"map"`), remembered across openings.
+
+## R6. Interaction
+
+- Drag a handle: one `MixGesture(engine, Volume(id), Pan(id))` (spec 009) — pan from the
+ X delta (`2 / plotWidth` per px), volume from the Y delta on the fader scale, clamped;
+ Shift locks to the axis with the larger movement so far (FR-014); one undo step (FR-017).
+- Automation: the drag opens the volume and pan automation writes like the strip controls
+ (`BeginAutomationWrite` after the mix gesture opens, `EndAutomationWrite` before it ends),
+ so recording and read/override rules are the same (FR-016).
+- Double-click → pan C; ⌥ + double-click → volume 1.0; each a one-shot step (FR-015).
+- The master handle is fixed (no drag, no reset).
+- Click → select the track app-wide: a new `ArrangementView.SelectTrackFromOutside(id)`
+ (selects and raises `TrackSelected`); the map draws the ring from `Timeline.SelectedTrackId`
+ each frame, so selections made elsewhere follow (FR-018).
+
+## R7. Labels, order, tooltip
+
+Draw order: by level ascending, selected last (on top). Labels: greedy — try each handle's
+label rect (right of the dot, ≤ 84 px, truncated) from the top of the draw order down; skip
+any that overlaps an already placed one (FR-011). Tooltip after 300 ms hover, not while
+dragging; rows and notes per FR-019; "Image is off the pan" when `|balance − pan| > 0.15`.
+
+## R8. Tests
+
+- **Smoke** (`StereoMeasureTests`): WAV clips (deterministic): mono 440 Hz panned L50 under
+ Stereo → balance −0.50 ± 0.05, width < 0.05; unrelated L/R tones at C → width > 0.95,
+ |correlation| < 0.05; L = −R → correlation < −0.95; silence → level < −60; master
+ correlation of the unrelated pair ≈ 0; measuring cost: render time with 64 tracks within
+ 1 % of the same render with measurement disabled via a test-only switch, or (if a switch
+ is not worth adding) within the run-to-run noise of two plain renders (SC-004).
+- **SC-004, measured (2026-10-14, implementation)**: no test-only switch was added to the
+ engine, so the cost was measured once as an A/B of two engine builds — the committed tree
+ before the Stereo Map sums (built in a temporary `git worktree`, `vendor/` linked from the main
+ checkout) against the tree with them — on the same render: 64 stereo audio tracks (unrelated
+ 440 Hz / 1 kHz WAV), Stereo law, 8 s in 512-frame blocks at 48 kHz, best of 6 runs, two rounds:
+ **169.2 / 170.1 µs per block with the sums vs 171.0 / 171.8 µs without** — a difference inside
+ the run-to-run noise, far below 1 % of the 10.7 ms block budget (SC-004). To repeat: build the
+ engine at the two commits, run the same render through `NotaEngine.RenderOffline` with each
+ `libnota_engine.dylib`, compare the best times.
+- **Headless UI** (harness): handles at the right positions, drag = one undo step moving pan
+ and volume, Shift lock, resets, master fixed, selection both ways, labels never overlap,
+ screenshots in both themes vs the mock.
diff --git a/specs/008-stereo-map/spec.md b/specs/008-stereo-map/spec.md
new file mode 100644
index 00000000..fa89cb38
--- /dev/null
+++ b/specs/008-stereo-map/spec.md
@@ -0,0 +1,306 @@
+# Feature Specification: Stereo Map (MVP)
+
+**Feature Branch**: `008-stereo-map`
+
+**Created**: 2026-10-14
+
+**Status**: Draft
+
+## Clarifications
+
+### Session 2026-10-14
+
+- Q: Should a map drag be undoable, given that volume and pan are not undoable anywhere in
+ Nota today? → A: Option C — make volume and pan edits undoable everywhere (Mixer, track
+ headers, the map), one gesture = one step. That capability is its own prerequisite spec
+ (volume/pan undo), done before this one, like the Stereo pan law (specs/006); this spec
+ only requires that a map drag uses it as one step.
+- Q: At what correlation should the map mark a track red (cloud outline, handle ring, master
+ correlation bar)? → A: Below −0.05 — a small tolerance so unrelated stereo material, whose
+ correlation hovers around 0, doesn't flicker red; real phase problems (well below 0) still
+ show.
+
+**Input**: User description: "Stereo Map — MVP (first of three specs: MVP, then V2 diagnostics, then V3 Remote/automation). A "Stereo Map" tab in the Mixer window (title-bar switch Strips | Stereo Map, per nota-design/Nota Mixer v2.html) that shows where every track really sits in the stereo field. Plane: X = pan L100…C…R100, Y = fader volume. Each track, return and the master gets a handle (the control) and a measured cloud (centre = measured balance, width = measured stereo width, opacity = measured level), measured post-fader and post-pan. Master: fixed handle, master correlation bar. Drag a handle = pan + volume, Shift locks the axis, double-click resets pan, ⌥+double-click resets volume; click selects; hover tooltip with the measurements. Requires the Stereo pan law (specs/006). Out of scope for MVP: Frequency axis, warnings, Conflicts, Hold, Mono, filters, Export PNG, Remote, automation write from the map, multi-select, MCP."
+
+## Nota Context *(fill in — drives plan and tasks)*
+
+**Feature area** *(pick the main one)*:
+
+- [ ] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table
+- [ ] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Ember) — plus a small engine part: stereo measurements per track
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+**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).
+
+**Design reference**: [`Nota Mixer v2.html`](../../../nota-design/Nota%20Mixer%20v2.html)
+(sibling repo `nota-design`). The mock shows the MVP **and** the later versions on one
+screen; only the parts listed in this spec belong to the MVP (see Out of Scope).
+
+**Current state (for reference)**:
+
+- The Mixer is its own window (**View ▸ Mixer**, ⌘⇧M): a row of channel strips with a
+ footer (Show Sends / I/O, PAN LAW from specs/006, a disabled crossfader placeholder).
+ It has no tabs and no track selection of its own; the app's selected track lives in the
+ arrangement.
+- Every track, return and the master already has a live peak/RMS meter per channel. There
+ is no measure of stereo balance, width or correlation anywhere.
+- Volume and pan changes are **not undoable** anywhere in Nota today (Mixer knobs, faders,
+ track headers): the engine's undo covers structural edits only. A separate prerequisite
+ spec makes them undoable (clarification 2026-10-14); this spec depends on it.
+- The Stereo pan law (specs/006) is implemented: under Stereo, a panned stereo track's
+ image follows its pan, so a measured cloud lines up with its handle.
+
+**Later specs (not this one)**: V2 diagnostics — Frequency Y-axis, wide-bass and phase
+warnings, Conflicts lines, Hold, Mono, the All / Tracks / Returns / Selected filter.
+V3 — Nota Remote mirror of the map, automation write from the map, multi-select
+(⌘-click, marquee) with ⌥-drag spread, Export PNG, MCP access.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - See where every track really sits (Priority: P1)
+
+A producer's chorus sounds crowded. They open the Mixer, switch to **Stereo Map** and,
+while the song plays, see every track as a dot on a plane — left/right by pan, up/down by
+volume — with a coloured cloud showing where its sound actually is and how wide it is. Five
+clouds pile up in the centre at the same height; the pad's cloud spans the whole width even
+though its pan is centred; the lead's cloud sits right of its dot because the source itself
+leans right.
+
+**Why this priority**: Seeing the real stereo picture is the whole point of the feature;
+without it nothing else on the map matters.
+
+**Independent Test**: Play a project with a centred mono track, a hard-panned mono track
+and a wide stereo pad; open the Stereo Map and compare each cloud's position and width
+with the known material.
+
+**Acceptance Scenarios**:
+
+1. **Given** a mono track panned L50 and playing, **When** the Stereo Map is open,
+ **Then** its cloud is narrow and centred near L50, at the height of its fader.
+2. **Given** a stereo track whose channels carry unrelated material, panned C,
+ **When** playing, **Then** its cloud spans nearly the full width and the tooltip
+ shows correlation near 0.
+3. **Given** a track that is silent (below −60 dBFS) or muted, **When** the map is open,
+ **Then** its dot stays and its cloud is hidden; a muted track's dot is dimmed.
+4. **Given** one track soloed, **When** the map is open, **Then** the other tracks'
+ dots and clouds are dimmed.
+5. **Given** the song plays, **When** the user looks under the map, **Then** a master
+ correlation bar (−1 … +1) moves with the mix, red when below −0.05.
+
+---
+
+### User Story 2 - Place tracks by dragging them (Priority: P1)
+
+The producer drags the guitar's dot to the left and down: its pan moves to L40 and its
+volume drops by 3 dB, and the channel strip, the track header and the arrangement show the
+same values. Holding Shift keeps the drag horizontal so only the pan changes.
+Double-clicking a dot centres its pan; ⌥+double-click returns its volume to 0 dB.
+
+**Why this priority**: The map becomes a faster way to make a rough mix, not just a
+display — the second half of the MVP's value.
+
+**Independent Test**: Drag a dot with and without Shift and check the pan and volume in
+the channel strip; double-click and ⌥+double-click it.
+
+**Acceptance Scenarios**:
+
+1. **Given** a track at C / 0 dB, **When** the user drags its dot left and down,
+ **Then** its pan and volume change together, live, and the Mixer strip, track header
+ and any other view show the same values.
+2. **Given** a drag in progress, **When** Shift is held, **Then** only the axis with the
+ larger movement changes.
+3. **Given** a dot, **When** double-clicked, **Then** pan returns to C; **When**
+ ⌥+double-clicked, **Then** volume returns to 0 dB.
+4. **Given** pan or volume automation in read mode on that track, **When** the user drags
+ its dot, **Then** the behaviour matches dragging the Mixer knob/fader of that track
+ (same automation rules).
+5. **Given** the master dot, **When** the user drags it, **Then** nothing moves (the
+ master has no pan; its volume stays on its fader).
+6. **Given** a drag has finished, **When** the user presses ⌘Z, **Then** the track's pan
+ and volume both return to where the drag started — one undo step for the whole drag,
+ the same as one gesture on its Mixer knob or fader; ⌘⇧Z redoes it.
+7. **Given** a double-click or ⌥+double-click reset, **When** the user presses ⌘Z,
+ **Then** the previous pan / volume returns (one step).
+
+---
+
+### User Story 3 - Inspect a track (Priority: P2)
+
+The producer hovers the lead's dot and reads its pan, volume, measured balance, width,
+correlation and level, plus a note: "Image is off the pan — the pan is at C, but the signal
+measures R25. The source itself is unbalanced." Clicking the dot selects the lead
+everywhere in Nota.
+
+**Why this priority**: Turns the picture into numbers and connects the map to the rest
+of the app, but the map is useful without it.
+
+**Independent Test**: Hover dots of known material and compare the tooltip values; click
+a dot and check the arrangement selection.
+
+**Acceptance Scenarios**:
+
+1. **Given** a dot, **When** hovered (and not dragging), **Then** a tooltip shows name,
+ PAN, VOLUME, BALANCE, WIDTH, CORRELATION and LEVEL ("below −60 dBFS" when silent).
+2. **Given** a track whose measured balance differs from its pan by more than 0.15,
+ **When** hovered, **Then** the tooltip adds the "Image is off the pan" note.
+3. **Given** a muted or silent track, **When** hovered, **Then** the tooltip says why
+ there is no cloud ("Muted" / "Silent").
+4. **Given** a dot, **When** clicked, **Then** that track becomes the selected track in
+ the arrangement, and the map shows it with a selection ring; selecting a track
+ elsewhere moves the ring.
+
+### Edge Cases
+
+- **Many tracks in one spot**: the selected dot is drawn on top, then louder over
+ quieter; a label that would overlap another is hidden (the name stays in the tooltip).
+- **Groups**: group tracks are not drawn; their child tracks are. The group's own pan and
+ volume still affect the children's measured clouds (measurements are of what reaches
+ the master).
+- **Returns**: drawn like tracks, with their own fader and pan; their cloud is what the
+ return sends to the master.
+- **Pan law Balance (older project)**: the map still works; clouds then show the balance
+ law's behaviour (a hard-panned stereo track's cloud collapses to one side with its far
+ channel gone).
+- **Transport stopped**: clouds fade out (silent) unless something still sounds (tails,
+ monitoring, preview into a track); dots stay and stay draggable.
+- **Track added, removed, renamed or recoloured while the map is open**: the map follows
+ within one refresh.
+- **Window too small**: the map keeps its aspect; labels drop first, dots never.
+- **Automation driving pan/volume**: dots move with the automated values during playback.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+**View**
+
+- **FR-001**: The Mixer window MUST offer two views, **Strips** and **Stereo Map**,
+ switched by a segmented control centred in its title bar (design reference); the
+ choice is remembered between openings of the window. First opening shows Strips.
+- **FR-002**: In the Stereo Map view the map takes the main area and the channel strips
+ stay visible beside it in a narrower, horizontally scrolling column (design reference);
+ the footer (Show, PAN LAW, crossfader) stays.
+- **FR-003**: The map MUST be a plane with X = pan (L100 … C … R100, grid lines and labels
+ at L100, L50, C, R50, R100) and Y = fader volume on the same scale as the Mixer fader
+ (grid lines and labels at its top, 0 dB, −6, −12, −24), C and 0 dB lines emphasised.
+- **FR-004**: The map header MUST read **STEREO MAP**. A hint line under the map MUST read
+ "Drag: pan + volume · Shift locks axis · double-click centres pan · ⌥ double-click 0 dB".
+
+**Measurement**
+
+- **FR-005**: For every track, return and the master, Nota MUST measure, from the signal
+ that reaches the master (after fader and pan), over a window of about 300 ms with
+ smoothing: **balance** (−1 … +1, energy left vs right), **width** (0 = mono … 1 =
+ fully side), **correlation** (−1 … +1) and **level** (RMS, dBFS).
+- **FR-006**: A signal below −60 dBFS counts as silent.
+- **FR-007**: Measuring MUST NOT add audible load: no dropouts, and the audio cost stays
+ within the existing meters' budget (see SC-004).
+
+**Drawing**
+
+- **FR-008**: Every non-group track and every return MUST have a **handle** (dot in the
+ track colour) at (its pan, its fader volume), and the master a fixed handle at
+ (C, master volume).
+- **FR-009**: Each handle with sound MUST have a **cloud** at the handle's height: a
+ horizontal ellipse centred on the measured balance, half as wide as the measured width
+ spans the map (a minimum visible width for mono), in the track colour, more opaque the
+ louder the measured level; a cloud whose correlation is below −0.05 (negative beyond a small
+ tolerance) gets a red outline, and so does its handle's ring.
+- **FR-010**: Silent tracks MUST show no cloud; muted tracks MUST show a dimmed handle and
+ no cloud; with any solo active, non-soloed tracks (not returns or master) MUST be dimmed.
+- **FR-011**: Each handle MUST carry its track name as a label (truncated), unless the
+ label would overlap another; drawing order is selected first, then by level.
+- **FR-012**: A **MASTER CORR** bar (−1 … +1, centre mark, value as a number) under the map
+ MUST show the master correlation, green at or above −0.05 and red below it.
+- **FR-013**: The map MUST update at the display rate and follow track list changes,
+ renames, recolours, mute/solo, automation and edits made elsewhere.
+
+**Interaction**
+
+- **FR-014**: Dragging a non-master handle MUST change that track's pan (horizontal) and
+ volume (vertical) together, live; Shift locks to the dominant axis.
+- **FR-015**: Double-click on a handle MUST centre its pan; ⌥+double-click MUST set its
+ volume to 0 dB. The master handle ignores both.
+- **FR-016**: Map edits MUST behave exactly like the same edits on the track's Mixer knob /
+ fader, including automation recording/read rules; Nota Remote and every other view show
+ the new values.
+- **FR-017**: Each map gesture (one drag, one reset) MUST be exactly one undo step covering
+ everything it changed, through Nota's volume/pan undo (prerequisite spec), interleaved
+ correctly with structural undo steps.
+- **FR-018**: Clicking a handle MUST select that track app-wide (the arrangement's selected
+ track); the selected track shows a brass ring on the map and stays drawn on top.
+- **FR-019**: Hovering a handle MUST show the tooltip of US3 (rows PAN, VOLUME, BALANCE,
+ WIDTH, CORRELATION, LEVEL; notes "Image is off the pan" when |balance − pan| > 0.15,
+ "Muted", "Silent").
+
+**Quality**
+
+- **FR-020**: Ember design language, both themes, matching the design reference.
+- **FR-021**: The automated smoke test MUST cover the measurements: a mono source panned
+ L50 measures balance ≈ the Stereo law's balance at L50 and width ≈ 0; a stereo source
+ with unrelated channels at C measures width ≈ 1 and correlation ≈ 0; an inverted-polarity
+ pair measures correlation ≈ −1; silence measures below −60 dBFS.
+- **FR-022**: The change MUST be listed in the changelog, FEATURES.md and the user docs
+ (EN + RU, Mixer page: a Stereo Map section with screenshots in both themes).
+
+### Key Entities
+
+- **Stereo measurement** (per track / return / master, live): balance, width, correlation,
+ level; silent flag.
+- **Map handle**: a track's pan and fader volume as a point; colour, name, selected /
+ muted / dimmed state.
+- **Mixer view choice**: Strips or Stereo Map; remembered per user (not per project).
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: For reference material (mono at L50, unrelated stereo at C, inverted pair),
+ the measured balance is within ±0.05, width within ±0.05 and correlation within ±0.05 of
+ the expected values.
+- **SC-002**: A user can place a track at a target pan and volume (±5 % pan, ±1 dB) with
+ one drag on the map.
+- **SC-003**: The map stays smooth (60 frames per second) with 128 tracks while playing.
+- **SC-004**: With 64 tracks playing, measuring adds no more than 1 % of the audio block
+ time, and no dropouts occur.
+- **SC-005**: Clouds react to a change in the signal within 0.5 s.
+
+## Assumptions
+
+- The map shows what reaches the master (after fader and pan), for returns as well —
+ decided in the feature discussion; pre-fader views are not offered.
+- The Y axis uses the Mixer fader's scale and range (its top is the fader's maximum,
+ about +3.5 dB), not the mock's +6 dB, so a handle and its fader always agree.
+- Depends on two prerequisites: the Stereo pan law (specs/006, done) and volume/pan undo
+ (its own spec, to be done first).
+- Pan is the Stereo pan law's pan (specs/006); under Balance the map still works and
+ simply shows that law's result.
+- The Strips / Stereo Map choice is a user preference, like the Show Sends / I/O toggles,
+ not saved in the project.
+- Clouds use measured level only for opacity; their height is the handle's (fader) height,
+ as in the design reference.
+- Multi-selection, marquee and ⌥-drag spread are V3; the MVP selects one track.
+
+## Out of Scope (MVP)
+
+Frequency Y-axis; wide-bass and phase warnings; Conflicts lines; Hold (ghost clouds); Mono
+button; All / Tracks / Returns / Selected filter; Export PNG; the REMOTE indicator and the
+Nota Remote mirror; writing automation from the map; multi-select, marquee and ⌥-spread;
+MCP tools; the strip redesign shown in the mock.
+
+## 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` (Ember design language)
diff --git a/specs/008-stereo-map/tasks.md b/specs/008-stereo-map/tasks.md
new file mode 100644
index 00000000..fc36efba
--- /dev/null
+++ b/specs/008-stereo-map/tasks.md
@@ -0,0 +1,172 @@
+---
+
+description: "Task list for 008 Stereo Map (MVP)"
+---
+
+# Tasks: Stereo Map (MVP)
+
+**Input**: Design documents from `/specs/008-stereo-map/`
+
+**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);
+specs 006 (Stereo pan law) and 009 (volume/pan undo) implemented.
+
+**Tests**: Requested — FR-021 lists the smoke-test coverage of the measurements, and the
+constitution (IV) requires it for an engine change. UI behaviour is verified with the
+headless harness (quickstart § 2).
+
+**Organization**: US1 see the real picture (P1), US2 drag to place (P1), US3 inspect and
+select (P2).
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
+- **[Story]**: US1 / US2 / US3
+
+---
+
+## Phase 1: Setup
+
+- [X] T001 Run `scripts/build.sh` on the current tree and confirm it is green (baseline); if red, stop and report
+
+---
+
+## Phase 2: Foundational (Blocking Prerequisites)
+
+**Purpose**: the engine measures, the measurements reach C#, and the Mixer window can show a
+(still empty) map view.
+
+**⚠️ CRITICAL**: No user story work can begin until this phase is complete
+
+- [X] T002 In `src/native/nota.engine/src/Track.h` add `std::atomic<float> stereoL_{0.0f}, stereoR_{0.0f}, stereoLR_{0.0f};` with `void setStereo(float l, float r, float lr)` and getters (comment: running averages of L², R², L·R of the post-fader post-pan signal, τ = 0.3 s, specs/008); in `src/native/nota.engine/src/Engine.h` add the master counterparts `masterStereoL_`, `masterStereoR_`, `masterStereoLR_` (audio thread writes, message thread reads)
+- [X] T003 In `src/native/nota.engine/src/Engine_Render.cpp` (research R1): in the track stage loop (`3) Channel fader + …pan`) and the return stage loop add `double sLR = 0.0; … sLR += l * (double)r;` next to `sqL`/`sqR`; after each loop update the track's averages with `a = 1 − exp(−frames / (0.3 · sr))` (`sr` = the block's sample rate; one `exp` per segment) from the block means `sqL/frames`, `sqR/frames`, `sLR/frames` — a `!toMix` track (muted / solo-gated) feeds zeros; in the master loop (after master volume, ~`masterPeakL_.store`) do the same into the master atomics. Groups untouched. No allocation, no lock
+- [X] T004 Add the C ABI from [contracts/c-abi-stereo-measures.md](contracts/c-abi-stereo-measures.md) verbatim to `src/native/nota.engine/include/nota/nota_engine.h` and implement `nota_engine_stereo_measures` in `src/native/nota.engine/src/nota_engine_core.cpp`: rows for the authoring graph's non-group tracks in track order, then the master (`kMasterTrackId`); derive per research R2 — `level_db = 10·log10((eL+eR)/2)` (−200 when ≤ 1e-20), `balance = (4/π)·atan2(√eR, √eL) − 1` (0 when silent), `correlation = eLR/√(eL·eR)` (0 when either < 1e-12), `width = clamp(1 − correlation, 0, 1)`; return the total row count, fill up to `cap`
+- [X] T005 [P] In `src/managed/Nota.Application/Engine/EngineContracts.cs` add `[StructLayout(LayoutKind.Sequential)] public struct StereoMeasure { public int TrackId; public float LevelDb, Balance, Width, Correlation; public bool Silent => LevelDb < -60f; }`; in `IAudioEngine.cs` add `int GetStereoMeasures(StereoMeasure[] buffer)` (fills, returns the total); P/Invoke in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs` and the wrapper in `NotaEngine.cs`
+- [X] T006 [P] In `src/managed/Nota.Application/Settings.cs` add `public string MixerView { get; set; } = "strips";` with a comment ("strips" | "map", specs/008, remembered per user)
+- [X] T007 Create `tests/Nota.SmokeTest/StereoMeasureTests.cs` (SPDX; comment "Stereo measurements for the Stereo Map (specs/008-stereo-map); also `--stereomap`") with WAV helpers (reuse the pattern of `PanLawTests`: 48 kHz Float32 WAVs, `RenderOffline(buf, frames, 48000)`), wired in `tests/Nota.SmokeTest/Program.cs` (full run after `MixUndoTests`, plus a `--stereomap` branch)
+- [X] T008 In `src/managed/Nota.App/MixerWindow.cs` switch to an own 36 px title bar (`base(36)`, as `DeviceWindow`): "Mixer" caption left, the shell segmented control **Strips | Stereo Map** (`ClipEditorKit.Segments`) centred; Linux: the same row at the top of the body. Expose an event/callback the hosting `MainWindow` wires to `MixerView.View`
+- [X] T009 In `src/managed/Nota.App/MixerView.cs` add `public enum MixerViewMode { Strips, StereoMap }` and a `View` property that rebuilds the content: Strips → the strips scroller alone; StereoMap → a `Grid` (`*, Auto`, gap 8, padding 8) with a `StereoMapView` placeholder (min 520 px) and the strips scroller capped at 440 px; the footer stays. In `src/managed/Nota.App/MainWindow.Mixer.cs` / `MainWindow.axaml.cs`: initialise `View` from `Settings.MixerView`, persist changes, and keep the title-bar segments in sync
+- [X] T010 Create `src/managed/Nota.App/StereoMapView.cs` (SPDX; file comment) as a custom `Control` with the panel frame, header "STEREO MAP", the plane well and the grid per [contracts/ui-stereo-map.md](contracts/ui-stereo-map.md) (vertical lines L100 / L50 / C / R50 / R100; horizontal lines at the `VFader` positions of the fader top, 0, −6, −12, −24 dB on the linear-gain 0…1.5 scale — reuse the fader's value↔y mapping in one shared helper), the bottom row (empty correlation bar, hint text), and a `RequestAnimationFrame` loop that runs only while attached and visible
+
+**Checkpoint**: build green; the Mixer switches between Strips and an empty Stereo Map; the engine reports measurements.
+
+---
+
+## Phase 3: User Story 1 — See where every track really sits (Priority: P1) 🎯 MVP
+
+**Goal**: handles and measured clouds for every track, return and the master; mute / solo /
+silence states; master correlation.
+
+**Independent Test**: quickstart § 2 steps 1, 2 and 4.
+
+### Tests for User Story 1
+
+- [X] T011 [US1] In `tests/Nota.SmokeTest/StereoMeasureTests.cs` add every Guarantees row of [contracts/c-abi-stereo-measures.md](contracts/c-abi-stereo-measures.md) (write before T013 and confirm they fail): mono 440 Hz at L50 under Stereo → balance −0.50 ± 0.05, width < 0.05, correlation > 0.95; L 440 / R 1 kHz at C → balance 0 ± 0.05, width > 0.95, |correlation| < 0.05; L = −R → correlation < −0.95, width = 1; silence → level < −60; that pair as the only track → master row within ± 0.05 of the track row; muting a track → its level < −60 within 1.5 s of rendering. Render ≥ 1.5 s before reading
+- [X] T012 [US1] In `tests/Nota.SmokeTest/StereoMeasureTests.cs` add the cost check (SC-004): render 3 s with 64 audio tracks of the unrelated pair three times and take the best; compare with the best of three renders of the same project before T003's averages — if a clean A/B is not possible without a switch, assert the time is within the run-to-run spread of two plain renders and print both numbers
+
+### Implementation for User Story 1
+
+- [X] T013 [US1] Make T011 pass in `src/native/nota.engine/src/Engine_Render.cpp` / `nota_engine_core.cpp` (fix the averages / derivation as the tests show)
+- [X] T014 [US1] In `src/managed/Nota.App/StereoMapView.cs` draw per frame (contract): for every non-group track and return a handle at (pan, fader position) in its colour (`ArrangementView.TrackBrush(EffectiveColorIndex)`), the master handle at (C, master volume); clouds from `GetStereoMeasures` (ellipse 22 px tall at the handle's Y, `balance ± width` on the pan scale, min 1.6 % wide, fill opacity `0.10 + 0.32 × clamp((level + 60) / 54, 0, 1)`, outline `Danger` when correlation < 0); no cloud when silent or muted; muted handle fill `SurfaceHover`; with any solo, non-soloed tracks (not returns or master) dimmed (cloud opacity × 0.35, handle `SurfaceHover`); draw order by level, master last
+- [X] T015 [US1] In `StereoMapView.cs` draw labels (10 px medium, right of the handle, ≤ 84 px with ellipsis, colours per contract) with the greedy no-overlap placement of research R7, and the MASTER CORR bar (180 × 6 well, centre tick, bar from centre to the value, `Success` / `Danger`, value text)
+- [X] T016 [US1] Headless harness (`/tmp/stereomapharness`, `NOTA_DATA_DIR`): new project + a mono WAV track panned L50 + a wide stereo WAV track, play, switch the Mixer to Stereo Map; assert handle positions, that the L50 cloud is centred within 2 % of the plane width of its handle and narrow, that the wide cloud spans > 90 % of the width, mute → no cloud and dimmed handle, solo → others dimmed, 20 tracks at C/0 dB → no overlapping labels; screenshots in both themes; record the frame time with 128 tracks (< 16 ms)
+
+**Checkpoint**: US1 tests pass; the map shows the real picture.
+
+---
+
+## Phase 4: User Story 2 — Place tracks by dragging them (Priority: P1)
+
+**Goal**: drag handles to change pan + volume as one undo step; resets; Shift lock.
+
+**Independent Test**: quickstart § 2 step 3.
+
+- [X] T017 [US2] In `src/managed/Nota.App/StereoMapView.cs` handle input: hit-test handles (16 px + 4 px slop, topmost first); pointer down on a non-master handle → `new MixGesture(engine, MixTarget.Volume(id), MixTarget.Pan(id)).Begin()` then `BeginAutomationWrite` for Volume and Pan; move → pan += dx · 2 / plotWidth, volume from the y delta via the shared fader mapping, clamped (pan −1…1, volume 0…1.5); Shift locks to the axis with the larger total movement so far; release → `EndAutomationWrite` ×2 then the gesture `End()`; the strips follow live (FR-014, FR-016, FR-017)
+- [X] T018 [US2] In `StereoMapView.cs`: double-click a handle → pan 0 as a one-shot (`MixEdit.Step`), ⌥ + double-click → volume 1.0 one-shot; the master handle ignores drag and resets (FR-015)
+- [X] T019 [US2] Headless harness: real mouse drag on a handle → pan and volume changed together, the Mixer strip shows them, one `Undo` restores both exactly; Shift-drag changes one axis only; double-click → C; ⌥ double-click → 0 dB, each one step; the master handle does not move
+
+**Checkpoint**: dragging works and undoes as one step.
+
+---
+
+## Phase 5: User Story 3 — Inspect a track (Priority: P2)
+
+**Goal**: hover tooltip with the numbers and notes; click selects app-wide; selection ring.
+
+**Independent Test**: quickstart § 2 step 5; tooltip values.
+
+- [X] T020 [P] [US3] In `src/managed/Nota.App/ArrangementView.cs` add `public void SelectTrackFromOutside(int trackId)` — `Select(trackId, -1)` then `TrackSelected?.Invoke(trackId)` (comment: used by the Stereo Map, specs/008)
+- [X] T021 [US3] In `src/managed/Nota.App/StereoMapView.cs` add `Func<int> SelectedTrackId` and `Action<int> SelectTrack` callbacks; a click without movement on a handle (master included) → `SelectTrack(id)`; draw the 22 px `Accent` ring on the selected handle and draw it on top; wire both in `src/managed/Nota.App/MainWindow.axaml.cs` / `MainWindow.Mixer.cs` (`() => Timeline.SelectedTrackId`, `id => Timeline.SelectTrackFromOutside(id)`)
+- [X] T022 [US3] In `StereoMapView.cs` the tooltip per [contracts/ui-stereo-map.md](contracts/ui-stereo-map.md): after 300 ms hover and not while dragging; rows PAN, VOLUME, BALANCE, WIDTH, CORRELATION, LEVEL (formats: "C" / "L40", "−3.0 dB" / "−∞", "below −60 dBFS"); notes "Image is off the pan" when `|balance − pan| > 0.15` (exact texts in the contract), "Muted", "Silent"; flipped near the edges
+- [X] T023 [US3] Headless harness: click a handle → `Timeline.SelectedTrackId` is that track; select another track in the arrangement → the ring moves; hover a handle with a known measurement → the tooltip rows and the off-pan note show the expected values
+
+**Checkpoint**: all three stories work.
+
+---
+
+## Phase 6: Polish & Cross-Cutting Concerns
+
+- [X] T024 Compare screenshots of the Stereo Map view (both themes) with `nota-design/Nota Mixer v2.html` and fix spacing / token mismatches in `StereoMapView.cs` / `MixerView.cs` / `MixerWindow.cs`
+
+### Nota closing tasks
+
+- [X] T025 Run `scripts/build.sh` until native + managed + smoke test are green
+- [X] T026 AGPL-3.0-only SPDX header on `StereoMapView.cs` and `StereoMeasureTests.cs`
+- [X] T027 New dependency: N/A
+- [X] T028 `CHANGELOG.md` `[Unreleased]` Added: "**Stereo Map:** the Mixer window's new **Stereo Map** view (switch in its title bar) shows every track, return and the master as a dot at its pan and fader, with a cloud for where its sound really is and how wide it is, plus the master correlation. Drag a dot to set pan and volume together (one undo step), double-click to centre, ⌥ double-click for 0 dB; hover for the numbers; click to select."
+- [X] T029 FEATURES.md via `nota-features` (Tracks and mixer: Stereo Map); user docs EN + RU via `nota-docs` (Mixer page: "Stereo Map" section; the `mixer` shots scene gains a `view: map` arg; new shots in both themes); shortcuts: N/A (no new key bindings — mouse gestures documented on the page)
+- [X] T030 Engine behaviour change → smoke test extended: confirm all `StereoMeasureTests` labels pass in the full run and with `--stereomap`
+
+---
+
+## Dependencies & Execution Order
+
+- **Setup (T001)** → **Foundational (T002–T010)** → stories → **Polish (T024–T030)**
+- T002 → T003 → T004 → T005; T006 ∥ T005; T007 after T005; T008 → T009 → T010
+- **US1 (T011–T016)** needs Foundational; T011 before T013; T014 → T015 (same file); T016 last
+- **US2 (T017–T019)** needs US1's drawing (handles) — T014
+- **US3 (T020–T023)**: T020 ∥ US1/US2 work (different file); T021–T022 after T017 (same file)
+- `StereoMapView.cs` tasks are sequential: T010 → T014 → T015 → T017 → T018 → T021 → T022
+
+### Parallel Opportunities
+
+- T005 ∥ T006 (Application files) while the engine work lands
+- T020 (ArrangementView) alongside any `StereoMapView.cs` task
+- Engine (T002–T004) and the Mixer window/layout (T008–T009) are independent until T010
+
+## Parallel Example: Foundational
+
+```bash
+Task: "T002–T004 engine measurements + C ABI"
+Task: "T008–T009 Mixer window title bar + view switch"
+Task: "T006 Settings.MixerView"
+```
+
+## Implementation Strategy
+
+### MVP
+
+US1 alone already delivers the feature's main value (seeing the real stereo picture); US2
+makes the map a mixing tool; US3 adds the numbers and selection. Ship all three in one PR
+— the spec's MVP is the three together; V2/V3 follow as their own specs.
+
+### Incremental order
+
+1. T001–T010 → measurements + empty map view
+2. US1 → clouds, handles, labels, correlation
+3. US2 → dragging with undo
+4. US3 → tooltip and selection
+5. Polish → design pass, docs, final build
+
+## Notes
+
+- Do not commit or push — the user reviews and commits.
+- `.specify/feature.json` points at `specs/007-midi-note-editing`; run spec-kit scripts for
+ this feature with `SPECIFY_FEATURE_DIRECTORY=specs/008-stereo-map SPECIFY_FEATURE_NO_PERSIST=1`.
+
+## Phase 7: Convergence
+
+- [X] T031 Reconcile the red-outline threshold: the spec says "negative correlation" / "red below 0" (FR-009, FR-012, US1 scenario 5) while `src/managed/Nota.App/StereoMapView.cs` uses `PhaseAlarm = -0.05` so unrelated material near 0 doesn't flicker red — either record the tolerance in the spec via `/speckit-clarify` or set the threshold back to 0, per FR-009 / FR-012 (contradicts)
+- [X] T032 Extend the headless Stereo Map harness: hover a handle with a known measurement and assert the tooltip rows (PAN, VOLUME, BALANCE, WIDTH, CORRELATION, LEVEL); a mono source whose measured balance differs from its pan by more than 0.15 shows "Image is off the pan"; a muted track shows "Muted", a silent one "Silent" — reading the drawn content through a test hook in `StereoMapView.cs` (e.g. the last tooltip's rows/notes kept like `_placedLabels`), per FR-019 / US3 scenarios 1–3 (partial)
+- [X] T033 Extend the harness: with automation recording on and the transport playing, a map drag creates (or writes) the track's volume and pan lanes like a strip-control drag, and one ⌘Z removes the recorded lanes and restores pan and volume together, per US2 scenario 4 / FR-016 (partial)
+- [X] T034 Record the SC-004 measurement in `specs/008-stereo-map/research.md` (A/B of the engine with and without the Stereo Map sums, 64 tracks: 169–170 vs 171–172 µs per 512-frame block, i.e. within noise) with how to repeat it, or add a budget check for 64 tracks to `tests/Nota.SmokeTest/StereoMeasureTests.cs`, per T012 / plan: Performance Goals (partial)
diff --git a/specs/009-mix-param-undo/checklists/requirements.md b/specs/009-mix-param-undo/checklists/requirements.md
new file mode 100644
index 00000000..d3b93962
--- /dev/null
+++ b/specs/009-mix-param-undo/checklists/requirements.md
@@ -0,0 +1,37 @@
+# Specification Quality Checklist: Undo for Volume and Pan
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-14
+**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
+
+- Resolved 2026-10-14: scope is volume + pan + master volume (no sends/mute/solo);
+ MIDI-controller movement groups into one step per 1 s pause.
+- MCP tool names `set_track_volume` / `set_track_pan` appear only as the names users and
+ the AI see, not as implementation.
diff --git a/specs/009-mix-param-undo/contracts/c-abi-mix-undo.md b/specs/009-mix-param-undo/contracts/c-abi-mix-undo.md
new file mode 100644
index 00000000..93f3ddbe
--- /dev/null
+++ b/specs/009-mix-param-undo/contracts/c-abi-mix-undo.md
@@ -0,0 +1,48 @@
+# Contract: C ABI — mix gestures
+
+Added to `src/native/nota.engine/include/nota/nota_engine.h` (AR-7), next to the undo block.
+
+```c
+/* ---- Mix undo (009) ------------------------------------------------------ */
+/* Volume / pan / master volume changes become undo steps through gestures. A gesture
+ * records its targets' values at begin and, at end, pushes ONE undo step with the values
+ * that changed (none changed → no step). If a structural checkpoint was pushed during the
+ * gesture (automation recording) the step merges into it. The plain setters never record:
+ * automation playback, loads and internal edits make no steps. Message thread only. */
+#define NOTA_MIX_TRACK_VOLUME 0
+#define NOTA_MIX_TRACK_PAN 1
+#define NOTA_MIX_MASTER_VOLUME 2
+
+typedef struct NotaMixTarget {
+ int32_t kind; /* NOTA_MIX_* */
+ int32_t track_id; /* ignored for NOTA_MIX_MASTER_VOLUME */
+} NotaMixTarget;
+
+/* Returns a handle > 0, or 0 if no target is valid. */
+NOTA_API int32_t nota_mix_gesture_begin(NotaEngine* engine, const NotaMixTarget* targets, int32_t count);
+/* Ends the gesture; unknown / already-ended handles are ignored. */
+NOTA_API void nota_mix_gesture_end(NotaEngine* engine, int32_t handle);
+
+/* The master volume (linear), as set by nota_engine_set_master_volume or undo/redo. */
+NOTA_API float nota_engine_master_volume(const NotaEngine* engine);
+```
+
+`nota_engine_undo` / `nota_engine_redo` keep their signatures; their comment changes from
+"atomic params … are not covered" to "volume, pan and master volume steps from mix gestures
+are covered; mute, solo, sends, device params and the transport are not".
+
+## Guarantees (smoke test)
+
+| Sequence | Expect |
+|---|---|
+| begin(vol t) · set ×50 · end · undo | volume exactly the begin value; redo → exactly the last value |
+| begin · end (no set) | `can_undo` unchanged |
+| begin · set back to the start value · end | no step |
+| add track · gesture vol · set pan law · gesture pan · undo ×4 | reverts in exactly reverse order; redo ×4 forward |
+| automation lane in read mode, render 2 s | no step |
+| record on · begin · begin_automation_write · set ×n · end_automation_write · end · undo | lane edit and value both reverted by one undo |
+| begin(vol t) · set · remove t · end | target dropped, no mix step (the removal is the only new step) |
+| gesture vol t · remove t · undo · undo | first undo restores t, second restores its volume (order keeps the track alive) |
+| two gestures open at once on different tracks | two steps, in end order |
+| begin(master) · set_master_volume · end · undo | `nota_engine_master_volume` = begin value |
+| reset with a gesture open · end(handle) | no-op, no step |
diff --git a/specs/009-mix-param-undo/contracts/sources.md b/specs/009-mix-param-undo/contracts/sources.md
new file mode 100644
index 00000000..02f9834f
--- /dev/null
+++ b/specs/009-mix-param-undo/contracts/sources.md
@@ -0,0 +1,32 @@
+# Contract: where gestures begin and end (managed)
+
+Every user source of a volume/pan/master-volume change maps to one gesture rule. Internal
+callers keep the plain setters (never a step).
+
+| Source | File | Target(s) | Begin | End |
+|---|---|---|---|---|
+| Mixer pan knob | `Nota.App/MixerView.cs` `PanRow` | track pan | `PanKnob.GestureBegin` | `GestureEnd` |
+| Mixer fader + dB number | `MixerView.cs` `FaderRow` | track volume | `VFader` / `DragNumber` `GestureBegin` | `GestureEnd` |
+| Mixer master strip | `MixerView.cs` `MasterStrip` | master volume | same | same |
+| Header mini fader / pan bar | `Nota.App/ArrangementView.cs` (~1848–1862) | track volume / pan | `GestureBegin` | `GestureEnd` |
+| Return / Master rows | `ArrangementView.cs` (~2425–2466) | track volume / master volume | `MiniFader.GestureBegin` | `GestureEnd` |
+| Session mixer | `Nota.App/SessionView.Mixer.cs` | track pan / volume | control gesture events | |
+| Transport MST | the MST control in `MainWindow` | master volume | its gesture events | |
+| Any of the above without an open gesture (double-click reset, typed value) | — | its target | one-shot | |
+| Nota Remote | `Nota.Remote/RemoteHub.Apply.cs` `vol` / `pan` / `mvol` | track volume / pan / master | first command of a touch | `cmd.Phase == 2` |
+| MIDI Learn | `Nota.App/MidiLearnService.cs` (~348–350) | track volume / pan / master | first CC | 1 s without a CC on that mapping |
+| MCP | `Nota.Mcp/Tools/TrackTools.cs` `set_track_volume` / `set_track_pan` | track volume / pan | one-shot inside `Mutate` | |
+| Stereo Map (spec 008) | — | track volume **and** pan | pointer down | pointer up |
+
+**Never a gesture**: `ProjectService.Apply` (load), `ProjectTemplate`, freeze / live freeze
+(`MainWindow.Freeze.cs`, `MainWindow.LiveFreeze.cs`), `MainWindow.Files.cs` resets,
+automation playback (engine audio thread).
+
+The wiring helper used by every control row:
+
+```text
+Wire(control, target):
+ GestureBegin → h = engine.BeginMixGesture(target)
+ GestureEnd → engine.EndMixGesture(h); h = 0
+ ValueChanged while h == 0 → one-shot: h1 = Begin; set; End(h1)
+```
diff --git a/specs/009-mix-param-undo/data-model.md b/specs/009-mix-param-undo/data-model.md
new file mode 100644
index 00000000..dc1a473e
--- /dev/null
+++ b/specs/009-mix-param-undo/data-model.md
@@ -0,0 +1,44 @@
+# Data Model: Undo for Volume and Pan
+
+## Engine (message thread)
+
+### MixChange
+
+| Field | Type | Rules |
+|---|---|---|
+| `kind` | `TrackVolume = 0` \| `TrackPan = 1` \| `MasterVolume = 2` | |
+| `trackId` | `int32_t` | ignored for `MasterVolume` |
+| `before`, `after` | `float` | exact values, never rounded; `before != after` (else dropped) |
+
+### UndoEntry (replaces `shared_ptr<Graph>` in `undoStack_` / `redoStack_`)
+
+| Field | Type | Rules |
+|---|---|---|
+| `graph` | `shared_ptr<Graph>` | the state to restore; null for a mix-only step |
+| `mix` | `vector<MixChange>` | empty for a structural step; at most one change per target |
+
+Merge rule (group collapse, automation merge): same target → keep the older `before`,
+the newer `after`; a target whose merged `before == after` is dropped.
+
+### Open gesture
+
+| Field | Type | Rules |
+|---|---|---|
+| `handle` | `int32_t` | > 0, unique while open |
+| `targets` | `vector<{kind, trackId, before}>` | `before` captured at begin |
+| `pushCountAtBegin` | `uint64_t` | value of the engine's checkpoint counter at begin |
+| `stackSizeAtBegin` | `size_t` | undo stack size at begin — entries above it collapse into one if a checkpoint was pushed during the gesture |
+
+Lifecycle: `begin` → (values change through setters) → `end` (step pushed, merged or
+dropped). `nota_engine_reset` and `clearUndoHistory` drop all open gestures; an `end` for a
+dropped or unknown handle is a no-op.
+
+## Managed
+
+| Name | Layer | Role |
+|---|---|---|
+| `MixTarget` (record struct: kind, trackId) | Nota.Application | mirrors `NotaMixTarget` |
+| `IAudioEngine.BeginMixGesture(params MixTarget[])` → `int`, `EndMixGesture(int)`, `MasterVolume` (get) | Nota.Application port | |
+| `MixEdit` static helpers: `Step(engine, target, Action set)` (one-shot) | Nota.Application | MCP, resets, typed values |
+| `MixGesture(engine, targets)` — `Begin` / `End` / `Change(value, setter)` | Nota.Application | a control's gesture; a value with no open gesture is a one-off step; no allocation per value |
+| `MixMovement(engine, target, pause)` — `Touch(set, nowMs)` / `Poll(nowMs)` | Nota.Application | MIDI Learn: one step per movement, ended on the tick after a 1 s pause (time passed in, so the smoke test drives it) |
diff --git a/specs/009-mix-param-undo/plan.md b/specs/009-mix-param-undo/plan.md
new file mode 100644
index 00000000..d3eade5c
--- /dev/null
+++ b/specs/009-mix-param-undo/plan.md
@@ -0,0 +1,181 @@
+# Implementation Plan: Undo for Volume and Pan
+
+**Branch**: `009-mix-param-undo` | **Date**: 2026-10-14 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `/specs/009-mix-param-undo/spec.md`
+
+## Summary
+
+The engine's single undo history learns a second kind of step: a **mix step** that holds
+volume / pan / master-volume values before and after a gesture, next to today's graph
+snapshots. A small gesture API (`begin(targets)` → handle, `end(handle)`) on the message
+thread records a gesture's start values and pushes one step for whatever changed; the
+plain setters stay as they are and never record, so automation playback, loads, freeze and
+the template make no steps by construction. Every user source (Mixer, headers,
+Return/Master rows, Session mixer, MST, Remote, MIDI Learn, MCP) is wired to begin/end at
+its natural gesture boundary; resets and typed values become one-shot gestures. A gesture
+that overlaps an automation-recording checkpoint merges into it, so the recorded lane and
+the value undo together. See [research.md](research.md).
+
+## Nota: Read Before Planning
+
+- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): undo stays message-thread
+ only; the audio thread keeps reading the same atomics (AR-6 untouched); AR-7 for the new
+ C ABI.
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (managed app)
+
+**Primary Dependencies**: Avalonia (existing); no new dependency
+
+**Storage**: N/A — undo history is in memory, not saved
+
+**Audio-Thread Impact**: None. History, gestures and undo/redo run on the message thread;
+undo writes values through the existing atomic setters, exactly like a hand move. No new
+audio-thread code.
+
+**Testing**: `scripts/build.sh` → smoke test gains `MixUndoTests` (engine-level gestures,
+MCP one-shot, debounced MIDI); headless harness for the UI sources ([quickstart.md](quickstart.md))
+
+**Target Platform**: macOS / Windows / Linux desktop app
+
+**Project Type**: desktop-app (engine + managed)
+
+**Performance Goals**: gesture begin/end O(targets); undo of a mix step O(changes); no
+per-frame allocation during a drag (values are only read at begin and end)
+
+**Constraints**: exact values (no rounding, FR-004); depth limit 128 shared with
+structural steps
+
+**Scale/Scope**: engine ~200 lines (UndoEntry, gestures, merge, getter); managed helper
+~120 lines; ~12 call sites wired; smoke test ~250 lines
+
+## Constitution Check
+
+| Principle | Status |
+|---|---|
+| I. Real-time audio safety | ✅ No audio-thread change; history is message-thread only |
+| II. Boundary discipline | ✅ New C ABI: `NotaMixTarget`, `nota_mix_gesture_begin/end`, `nota_engine_master_volume` |
+| III. Licensing hygiene | ✅ New files get the SPDX header; no dependency |
+| IV. Verification gate | ✅ Engine undo behaviour changes → `MixUndoTests` in the smoke test |
+| V. One logical change | ✅ Volume/pan undo end to end; sources wired in the same change because the spec requires all of them (FR-007) |
+| VI. Docs in sync | ⏳ CHANGELOG, `nota-features`, `nota-docs` (undo section) |
+| VII. Spec-first | ✅ |
+| VIII. Rules not weakened | ✅ |
+
+Post-design re-check: unchanged — all gates pass.
+
+## Design
+
+### 1. Engine — history entries ([research R1](research.md), [data model](data-model.md))
+
+- `Engine.h`: `struct MixChange`, `struct UndoEntry { shared_ptr<Graph> graph; vector<MixChange> mix; }`;
+ `undoStack_` / `redoStack_` become `vector<UndoEntry>`; `canUndo/canRedo` unchanged.
+- `pushUndo()` pushes `{authoring_, {}}` and bumps `undoPushCount_` (new `uint64_t`).
+- `undo()` / `redo()`: graph part as today (`publishRaw`), then apply `before` / `after`
+ of each change via `setVolume` / `setPan` on the authoring track (skip missing) or the
+ master volume setter; an entry that applied nothing and had no graph → continue with
+ the next entry (R3).
+- `endUndoGroup()`: when dropping entries, merge their `mix` into the kept entry (data
+ model merge rule).
+- `clearUndoHistory()` / `reset()`: also clear open gestures.
+
+### 2. Engine — gestures ([research R2](research.md), [contract](contracts/c-abi-mix-undo.md))
+
+- `Engine`: `int32_t beginMixGesture(const MixTarget*, int32_t)`, `void endMixGesture(int32_t)`,
+ `float masterVolume() const`; open gestures in a small `vector<OpenGesture>` (message
+ thread), handles from a counter.
+- `end`: build changes (exact compare, drop vanished tracks); none → return; if
+ `undoPushCount_ != g.pushCountAtBegin` and the stack is non-empty → merge into
+ `undoStack_.back()`; else push `{nullptr, changes}`, trim to depth, clear redo.
+- C ABI in `nota_engine.h` / `nota_engine_core.cpp`; update the undo block comment.
+
+### 3. Managed port + helpers
+
+- `Nota.Application/Engine/EngineContracts.cs`: `enum MixKind { TrackVolume, TrackPan, MasterVolume }`,
+ `readonly record struct MixTarget(MixKind Kind, int TrackId)` (blittable layout).
+- `IAudioEngine`: `int BeginMixGesture(params MixTarget[] targets)`,
+ `void EndMixGesture(int handle)`, `float MasterVolume { get; }`; `NotaEngine` + P/Invoke.
+- `Nota.Application/Editing/MixEdit.cs` (new): `Step(engine, Action set, params MixTarget[])`
+ — one-shot begin → set → end.
+- In the same file: `MixGesture` (a control's Begin / End / `Change(value, setter)`, one-off
+ step when no gesture is open, no allocation per value) and `MixMovement` (MIDI Learn: one
+ step per movement, ended by a 1 s pause checked on the learn service's tick — time passed in,
+ so the smoke test drives it). *(Implementation: these replaced a planned
+ `Nota.App/MixGestureWiring.cs` with a `DispatcherTimer`, which headless tests can't fire.)*
+
+### 4. Sources ([contracts/sources.md](contracts/sources.md))
+
+Wire, in this order: `MixerView` (pan knob, fader, dB number, master strip), `ArrangementView`
+(header mini fader + pan bar, Return/Master rows), `SessionView.Mixer`, the transport MST,
+`RemoteHub.Apply` (`vol` / `pan` / `mvol` — begin on the first command of a touch, end on
+`Phase == 2`; keep a per-client open-gesture map), `MidiLearnService` (debounced),
+`TrackTools` MCP (`MixEdit.Step`). Leave load / template / freeze callers on the plain setters.
+
+### 5. Views after undo/redo
+
+`MainWindow.RefreshAfterUndoRedo`: also `vm.Transport.MasterVolume = Engine.MasterVolume`
+(R4). Everything else already rebuilds from the engine.
+
+### 6. Smoke test + docs
+
+- `tests/Nota.SmokeTest/MixUndoTests.cs` (new, SPDX): every Guarantees row of the C ABI
+ contract, MCP one-shot via `McpTestSupport`, debounced MIDI (simulated clock or a short
+ timeout); wired in `Program.cs` (full run + `--mixundo`).
+- `CHANGELOG.md` (Added: volume and pan undo), `nota-features`, `nota-docs`.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/009-mix-param-undo/
+├── spec.md
+├── plan.md
+├── research.md
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── c-abi-mix-undo.md
+│ └── sources.md
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (repository root)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # NotaMixTarget, gesture begin/end, master volume getter
+└── src/
+ ├── Engine.h / Engine.cpp # UndoEntry, gestures, undo/redo/group merge
+ └── nota_engine_core.cpp # C ABI
+src/managed/
+├── Nota.Application/Engine/EngineContracts.cs, IAudioEngine.cs
+├── Nota.Application/Editing/MixEdit.cs (new)
+├── Nota.Infrastructure/Interop/NativeMethods.cs, NotaEngine.cs
+├── Nota.App/MixerView.cs, ArrangementView.cs, SessionView.Mixer.cs, MainWindow.*.cs (MST, RefreshAfterUndoRedo)
+├── Nota.App/MidiLearnService.cs
+├── Nota.Remote/RemoteHub.Apply.cs
+└── Nota.Mcp/Tools/TrackTools.cs
+tests/Nota.SmokeTest/MixUndoTests.cs (new), Program.cs
+CHANGELOG.md, FEATURES.md
+```
+
+**Structure Decision**: existing projects; two new files (`MixEdit.cs`, `MixUndoTests.cs`).
+
+## Out of Scope / Known Gaps
+
+- Sends, mute, solo, device params, transport values (clarified).
+- Scroll-wheel bursts: no mix control handles the wheel today (research R5) — N/A until one does.
+- A structural edit made by another source *during* an open gesture (e.g. an MCP edit while
+ dragging) merges with that gesture's step (the automation-merge rule cannot tell them
+ apart). Rare; documented rather than solved.
+- Undo step labels (none in Nota).
+- The Stereo Map's own wiring belongs to spec 008 (two targets in one gesture — supported).
+
+## Complexity Tracking
+
+No constitution violations.
diff --git a/specs/009-mix-param-undo/quickstart.md b/specs/009-mix-param-undo/quickstart.md
new file mode 100644
index 00000000..5725fad1
--- /dev/null
+++ b/specs/009-mix-param-undo/quickstart.md
@@ -0,0 +1,29 @@
+# Quickstart: validating Undo for Volume and Pan
+
+## 1. Automated (the PR gate)
+
+```bash
+scripts/build.sh
+```
+
+The smoke test gains `MixUndoTests` (alone: `dotnet run --project tests/Nota.SmokeTest -- --mixundo`)
+running every row of [contracts/c-abi-mix-undo.md](contracts/c-abi-mix-undo.md) § Guarantees,
+plus: MCP `set_track_volume` through the MCP test support is one step; a debounced MIDI
+gesture (two CC bursts 1.5 s apart) makes two steps.
+
+## 2. In the app (headless harness — memory "Nota UI verify recipe")
+
+Isolate data with `NOTA_DATA_DIR`. Drive controls with synthetic pointer events.
+
+1. Mixer: drag a fader, ⌘Z → exact old value in the fader, the dB field, the track header
+ and the arrangement Return/Master row; ⌘⇧Z → new value.
+2. Double-click a pan knob (reset), type −12 in a dB field: each is one ⌘Z.
+3. Move MST, ⌘Z: MST, the Master strip and the Master row all show the old value.
+4. Play a project with volume automation for 10 s: the Edit ▸ Undo item stays disabled.
+5. Turn on automation recording, drag a fader: one ⌘Z removes the recorded points and
+ restores the value.
+
+## 3. Docs
+
+`CHANGELOG.md` `[Unreleased]`, `FEATURES.md` (Project and transport: undo), user docs EN + RU
+(where undo is described — `basics/…` page found via coverage.yml).
diff --git a/specs/009-mix-param-undo/research.md b/specs/009-mix-param-undo/research.md
new file mode 100644
index 00000000..b7e6eb44
--- /dev/null
+++ b/specs/009-mix-param-undo/research.md
@@ -0,0 +1,122 @@
+# Research: Undo for Volume and Pan
+
+## R1. One history for graph snapshots and mix values
+
+**Decision**: the engine's undo/redo stacks change from `vector<shared_ptr<Graph>>` to
+`vector<UndoEntry>`:
+
+```text
+UndoEntry { shared_ptr<Graph> graph; // null for a mix-only step
+ vector<MixChange> mix; } // empty for a structural step
+MixChange { kind: TrackVolume | TrackPan | MasterVolume; trackId; before; after }
+```
+
+- **Undo** pops an entry: if it has a graph, push `{authoring_, mix}` onto redo and
+ `publishRaw(graph)` (exactly today's behaviour); a mix-only entry is pushed to redo as is.
+ Then every `MixChange` writes its `before` value through the normal setter.
+- **Redo** is symmetric and writes `after`.
+- `pushUndo()` (every structural checkpoint) pushes `{authoring_, {}}` — unchanged meaning.
+- **Group collapse** (`endUndoGroup`) keeps the first entry's graph, as today, and merges
+ the mix changes of the dropped entries into it: per target, the earliest `before` and the
+ latest `after`.
+- The depth limit (`kMaxUndoDepth` = 128) counts entries of both kinds.
+
+**Rationale**: volume, pan and master volume live in atomics outside the graph (shared
+`Track` objects across snapshots), so a snapshot cannot carry them; a value delta can, and
+putting it in the same stack gives strict ordering with structural edits and the pan law
+(FR-002) for free. A deleted-then-restored track is the same `Track` object, so its value
+history stays valid.
+
+**Alternatives considered**:
+- *Managed-side mix history interleaved with the engine's* — two stacks that must agree
+ on order; every structural undo would need to ask the managed side. Rejected.
+- *Put volume/pan into the graph snapshot* — every fader move would publish a new graph
+ (allocation per frame of a drag, AR-5 churn) and the audio thread reads them as atomics
+ anyway. Rejected.
+
+## R2. Gestures in the engine
+
+**Decision**: an explicit gesture API on the message thread:
+
+- `begin(targets[])` → handle: records each target's current value (`before`) and the
+ undo-push counter.
+- Value changes during the gesture go through the existing setters (unchanged, live).
+- `end(handle)`: reads each target's current value (`after`); targets with
+ `after == before` (exact float compare) are dropped (FR-005); a vanished track is dropped.
+ If nothing is left → no step. Otherwise, **if a structural checkpoint was pushed since
+ `begin`** (counter moved), every entry stacked since `begin` is collapsed into the first
+ of them (as an undo group would) and the changes are merged into it — automation
+ recording on a new lane pushes two checkpoints (the lane's creation, then the pre-write
+ state), and lane + value must still be one step (FR-009); else a new mix-only entry is
+ pushed and redo is cleared. (Implementation finding: merging into the top entry only left
+ the lane creation as a second step.)
+
+Plain setters (`nota_track_set_volume`, `…_pan`, `…_set_master_volume`) never record
+anything. Automation playback (audio thread), project load, freeze/live freeze and the
+template use them → never a step (FR-008) by construction.
+
+**Rationale**: makes "one gesture = one step" explicit at the source that knows the
+gesture (mouse down/up, Remote phase, MIDI pause, MCP call) and keeps the engine
+attribution-free (a setter call does not need to know which gesture it belongs to).
+Several gestures can be open at once (mouse + phone); each ends as its own step (spec edge
+case). Overlapping gestures on the *same* parameter each record their own `before`.
+
+**Alternatives considered**:
+- *Undo groups around each gesture* — overlapping gestures would merge into one step,
+ contradicting the spec's "each gesture its own step". Rejected (merge happens only for
+ the automation checkpoint case above).
+- *Record every setter call and coalesce by time* — automation playback and loads would
+ have to be excluded by flags everywhere; fragile. Rejected.
+
+## R3. Skipping steps of deleted tracks (FR-010)
+
+A track removal is itself a step above any earlier volume step of that track, so undo
+always brings the track back first; a dangling mix step arises only when a track is removed
+while a gesture on it is open (its target is then dropped at `end`) or after history edits
+that bypass that order. FR-010 is therefore a defensive rule:
+
+**Decision**: on undo/redo, a `MixChange` whose track is not in the current authoring graph
+is skipped. If an entry ends up applying nothing (mix-only, every track gone), undo/redo
+continue with the next entry in the same call, so the user never presses ⌘Z "for nothing".
+
+## R4. Master volume
+
+**Decision**: add `nota_engine_master_volume(engine)` (getter; there is only a setter
+today). `TransportViewModel.MasterVolume` stays the single owner in the app: after an
+undo/redo, `RefreshAfterUndoRedo` reads the engine value back into the view model (its
+setter re-sends the same value — harmless), so MST, the Master row, the Mixer and Remote
+follow (FR-006).
+
+## R5. Sources and their gesture boundaries
+
+| Source | Begin | End |
+|---|---|---|
+| Mixer `PanKnob`, `VFader`, `DragNumber` (drag) | existing `GestureBegin` | `GestureEnd` |
+| Header `PanBar`, `MiniFader`; Return/Master rows | existing `GestureBegin` / pointer down | `GestureEnd` / pointer up |
+| Session mixer knob/fader | same controls' gesture events | |
+| Double-click reset, typed dB value (no gesture open) | one-shot: begin → set → end | |
+| Transport MST | its control's gesture events | |
+| Nota Remote | first `vol`/`pan`/`mvol` command of a touch (phase 0/1 without an open gesture) | `phase == 2` |
+| MIDI Learn | first CC of a movement | 1 s without a CC for that mapping (checked on the learn service's UI tick) |
+| MCP `set_track_volume` / `set_track_pan` | one-shot inside the existing `Mutate` | |
+
+A shared managed helper wires a control: `GestureBegin` → begin, `GestureEnd` → end, a
+`ValueChanged` with no gesture open → one-shot. So every reset or typed value is covered
+without touching each call site's logic.
+
+**Scroll wheel**: none of the mix controls handle the wheel today, so FR-003's wheel rule
+has no source yet; when wheel support is added it uses the same one-shot-or-debounce
+helper with a 0.5 s pause. Recorded as N/A, not built.
+
+## R6. Threading
+
+All history work (gesture begin/end, undo/redo) is message-thread only, as the existing
+undo is. Every source already runs there: UI controls, MIDI Learn (dispatched), Remote
+apply (dispatched), MCP `Mutate` (`InvokeAsync` on the UI dispatcher). The audio thread
+only reads the atomics — no new audio-thread code, nothing allocated there (AR-6).
+
+## R7. Views after undo/redo
+
+`RefreshAfterUndoRedo` already rebuilds the arrangement, Mixer and Session from the engine;
+extend it with the master-volume read-back (R4). Remote is refreshed by `host.Refresh()`;
+the Stereo Map (spec 008) reads values every frame.
diff --git a/specs/009-mix-param-undo/spec.md b/specs/009-mix-param-undo/spec.md
new file mode 100644
index 00000000..485d81e9
--- /dev/null
+++ b/specs/009-mix-param-undo/spec.md
@@ -0,0 +1,250 @@
+# Feature Specification: Undo for Volume and Pan
+
+**Feature Branch**: `009-mix-param-undo`
+
+**Created**: 2026-10-14
+
+**Status**: Draft
+
+## Clarifications
+
+### Session 2026-10-14
+
+- Q: Should sends, mute and solo become undoable in the same change? → A: No — volume and
+ pan only (plus the master volume); sends, mute and solo can follow in a later spec on the
+ same mechanism.
+- Q: How should continuous MIDI-controller movement be grouped into undo steps? → A: One
+ step per movement, ended by a 1 s pause in that control's messages.
+
+### Session 2026-10-14 (convergence)
+
+- Q: The spec asks for scroll-wheel bursts to be one step, but no volume/pan control reacts
+ to the wheel. Add wheel support or drop the rule? → A: Drop it — wheel control of faders is
+ a feature of its own; when it arrives it uses the same pause-based gesture.
+
+**Input**: User description: "Undo for volume and pan, everywhere (prerequisite of specs/008-stereo-map, clarified 2026-10-14 option C). Today track/return volume and pan (and the master volume) are not undoable anywhere in Nota. Make every user change of a track's or return's volume or pan, and of the master volume, undoable and redoable with ⌘Z / ⌘⇧Z, interleaved in one history with all other edits. One gesture = one step: a fader/knob drag from press to release; a double-click reset; a typed or dragged dB value; a scroll-wheel burst; a Stereo Map drag (pan + volume together, one step). Sources: Mixer strips, track headers, Return/Master rows, Session mixer, the transport MST, MIDI controller via MIDI Learn, Nota Remote, MCP tools. Never an undo step: automation playback, project load, freeze/live-freeze internals, the new-project template. While recording automation, the lane edit and the value change undo together. Undo restores the exact previous value and every view follows."
+
+## Nota Context *(fill in — drives plan and tasks)*
+
+**Feature area** *(pick the main one)*:
+
+- [ ] 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 — plus the engine's undo history, which today covers structural edits only
+- [ ] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Ember)
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+**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).
+
+**Current state (for reference)**:
+
+- One history (⌘Z / ⌘⇧Z, Edit menu, the command palette's undo) covers structural edits:
+ tracks, clips, notes, device chains, session slots, automation lanes, the pan law. It
+ explicitly does not cover volume, pan, mute, solo, sends, device parameters or the
+ transport.
+- Volume and pan of tracks and returns, and the master volume, are changed from: the Mixer
+ window (knob, fader, dB field — typed or dragged), the arrangement track headers (pan bar,
+ mini fader), the Return and Master rows under the tracks, the Session-view mixer, the
+ transport's **MST** control, a MIDI controller mapped with MIDI Learn, Nota Remote (phone),
+ and the MCP tools `set_track_volume` / `set_track_pan` (AI control).
+- Internal operations also set them: project load, freeze / live freeze, the new-project
+ template, automation playback.
+- Prerequisite of the Stereo Map (specs/008), which requires a map drag to be one undo step.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Take back a fader move (Priority: P1)
+
+A producer drags the vocal fader up by 6 dB, listens, and does not like it. ⌘Z puts the
+fader back exactly where it was; ⌘⇧Z brings the 6 dB back. The same works for a pan knob, a
+double-click reset and a value typed into the dB field.
+
+**Why this priority**: The basic expectation of any DAW; today a slip on a fader cannot be
+taken back at all.
+
+**Independent Test**: In the Mixer, drag a fader, turn a pan knob, reset one with a
+double-click and type a dB value; undo each and redo each.
+
+**Acceptance Scenarios**:
+
+1. **Given** a track at 0 dB, **When** the user drags its fader to +6 dB in one press and
+ release and presses ⌘Z, **Then** it is back at exactly 0 dB, and ⌘⇧Z returns it to +6 dB.
+2. **Given** a pan knob at C, **When** the user turns it to L40 and presses ⌘Z, **Then** it is
+ at C again.
+3. **Given** a track at −8 dB, **When** the user double-clicks its fader (reset to 0 dB) and
+ presses ⌘Z, **Then** it is at −8 dB again.
+4. **Given** the dB field, **When** the user types −12 and confirms, **Then** that is one undo
+ step; **When** they drag the dB number, **Then** the whole drag is one step.
+
+---
+
+### User Story 2 - One history for everything (Priority: P1)
+
+The producer adds a track, moves the bass fader, switches the pan law to Stereo, pans the
+guitar, then presses ⌘Z four times: the guitar pan, the pan law, the bass fader and the new
+track come back one by one, in reverse order. Every view — Mixer, track headers, Remote,
+Stereo Map — shows the restored values.
+
+**Why this priority**: Undo that skips some edits or jumps out of order is worse than no
+undo; mixing and structural edits must share one timeline.
+
+**Independent Test**: Alternate structural edits and volume/pan edits, undo and redo the
+whole chain and check each intermediate state.
+
+**Acceptance Scenarios**:
+
+1. **Given** a sequence of edits mixing structure, pan law and volume/pan, **When** the user
+ undoes repeatedly, **Then** each step reverts exactly the most recent remaining edit, in
+ reverse order, and redo replays them in order.
+2. **Given** a new edit after some undos, **When** it is made, **Then** the redo history is
+ dropped (as for any edit today).
+3. **Given** an undone volume change, **When** the user looks at the Mixer, the track header,
+ the Session mixer and a connected phone, **Then** they all show the restored value.
+4. **Given** a track deleted after its volume was changed, **When** the user undoes the delete
+ and then the volume change, **Then** both come back correctly.
+
+---
+
+### User Story 3 - Every way of mixing is undoable (Priority: P2)
+
+The producer moves a volume from the Session mixer, a pan from a track header, the master
+from the transport's MST, a fader from Nota Remote on the phone, a knob on a MIDI controller,
+and asks the AI assistant (MCP) to set a level. Each of those is undoable from the computer.
+
+**Why this priority**: Consistency across sources; the main sources (US1) already give most
+of the value.
+
+**Independent Test**: Change volume/pan once from each source and undo each.
+
+**Acceptance Scenarios**:
+
+1. **Given** each source listed in Current state, **When** the user changes a volume or pan
+ with it, **Then** ⌘Z reverts that change.
+2. **Given** a touch on Nota Remote, **When** the finger moves a fader and lifts, **Then** the
+ whole touch is one step.
+3. **Given** a MIDI controller knob turned continuously, **When** the user stops turning,
+ **Then** the movement up to a 1 s pause in that control's messages is one step; turning
+ it again after the pause starts a new step.
+4. **Given** an MCP call that sets a volume, **When** it completes, **Then** it is one step.
+
+---
+
+### User Story 4 - Things that are not edits stay out of the history (Priority: P1)
+
+While a song with volume automation plays, the faders move by themselves — that never
+fills the undo history. Opening a project, freezing a track or starting a new project does
+not leave undoable volume steps behind either.
+
+**Why this priority**: Without it a playing song would flood the history and undo would
+become useless.
+
+**Independent Test**: Play a song with volume and pan automation for a minute, freeze a
+track, open a project; the history gains no volume/pan steps.
+
+**Acceptance Scenarios**:
+
+1. **Given** automation in read mode, **When** the song plays, **Then** no undo steps appear.
+2. **Given** a project is opened or a new project created, **When** the user presses ⌘Z,
+ **Then** nothing about volume or pan is undone (there is nothing to undo).
+3. **Given** a freeze or live freeze, **When** it completes, **Then** any internal volume
+ changes it made leave no undo step of their own.
+4. **Given** automation recording (write/touch/latch), **When** the user moves a fader in one
+ gesture, **Then** ⌘Z reverts the recorded automation and the value together, one step.
+
+### Edge Cases
+
+- **Undo during playback**: the value jumps back immediately; with automation in read mode
+ on that parameter, the automation keeps winning, as it does for a manual move today.
+- **A gesture with no net change** (press and release without moving, or a drag back to the
+ start value): no undo step.
+- **Gesture interrupted** (window loses focus, track deleted mid-drag): the change so far is
+ one step; nothing is left half-open.
+- **Two sources at once** (mouse on the fader while the phone moves the same fader): each
+ gesture is its own step, in the order they finished.
+- **The master volume** shares the history with track edits even though it is shown in the
+ transport.
+- **Undo a volume change of a track that no longer exists** (deleted, not undone): that step
+ is skipped quietly; the next step is undone instead.
+- **Group tracks**: their volume and pan are covered like any track's.
+- **History depth**: volume/pan steps count against the existing history limit like any
+ other step.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Every user change of a track's, return's or group's **volume** or **pan**, and
+ of the **master volume**, MUST be undoable and redoable through the existing history
+ (⌘Z / ⌘⇧Z, Edit menu, command palette).
+- **FR-002**: These steps MUST share one ordered history with all existing undoable edits;
+ undo and redo MUST always act on the most recent step, whatever its kind.
+- **FR-003**: One gesture MUST be exactly one step: a mouse drag from press to release; a
+ double-click reset; a confirmed typed value; a drag of a dB number; one touch on Nota Remote from finger-down to
+ lift; one MIDI-controller movement ended by a 1 s pause; one MCP call; a Stereo Map drag (its pan and volume together).
+- **FR-004**: A step MUST restore the exact value from before the gesture (no rounding) and
+ redo the exact value after it.
+- **FR-005**: A gesture that ends at its starting value MUST NOT add a step.
+- **FR-006**: All views and connected devices (Mixer, track headers, Return/Master rows,
+ Session mixer, transport MST, Nota Remote, Stereo Map) MUST show the restored value at once.
+- **FR-007**: The sources MUST all be covered: Mixer window, track headers, Return/Master
+ rows, Session mixer, transport MST, Nota Remote, MCP, and a MIDI controller through MIDI
+ Learn (grouping per US3 scenario 3).
+- **FR-008**: Automation playback, project load, a new project, freeze / live freeze and
+ any other internal setting of volume or pan MUST NOT create steps.
+- **FR-009**: While recording automation, one gesture's lane edit and value change MUST undo
+ and redo together as one step.
+- **FR-010**: A step whose track no longer exists MUST be skipped without error.
+- **FR-011**: Undo/redo of volume and pan MUST be click-free during playback no worse than
+ moving the same control by hand.
+- **FR-012**: The scope is volume and pan (tracks, returns, groups) and the master volume
+ only; sends, mute and solo stay out of the history, as today.
+- **FR-013**: The automated smoke test MUST cover: a drag-like change (begin, many values,
+ end) is one step and restores exactly; a no-change gesture adds no step; volume/pan steps
+ interleave in order with structural edits and the pan law switch; automation playback adds
+ no steps; a step for a deleted track is skipped; MCP set_track_volume is one step.
+- **FR-014**: The change MUST be listed in the changelog, FEATURES.md and the user docs
+ (EN + RU) where undo is described.
+
+### Key Entities
+
+- **Mix step** (one undo step): which parameter (track id + volume or pan, or master
+ volume), the value before and the value after; a Stereo Map step carries two parameters.
+- **Gesture**: a begin–end span from one source in which value changes merge into one step.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: 100 % of volume/pan changes made by the user from any listed source can be
+ undone and redone, landing on the exact previous value.
+- **SC-002**: Playing a song with volume and pan automation for 10 minutes adds 0 undo steps.
+- **SC-003**: Undo/redo of a volume/pan step takes effect within one screen refresh in every
+ open view.
+- **SC-004**: A mixed sequence of 50 structural and volume/pan edits undoes and redoes in
+ exactly the reverse/forward order, every intermediate state matching.
+
+## Assumptions
+
+- Group tracks are covered like tracks; the master volume is covered although the history
+ never covered the transport before (it is a fader the user mixes with).
+- Undo steps have no labels (Nota's history has none; specs/006 clarification).
+- MCP calls run one at a time; each call is one step.
+- History depth stays as it is today; mix steps count toward it.
+- Device parameters, sends, mute, solo, arm, tempo and the other transport values are out
+ of scope (clarified).
+- Volume/pan controls have no scroll-wheel input; wheel bursts are out of scope (clarified).
+
+## 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` (Ember design language)
diff --git a/specs/009-mix-param-undo/tasks.md b/specs/009-mix-param-undo/tasks.md
new file mode 100644
index 00000000..7e9c8937
--- /dev/null
+++ b/specs/009-mix-param-undo/tasks.md
@@ -0,0 +1,186 @@
+---
+
+description: "Task list for 009 Undo for Volume and Pan"
+---
+
+# Tasks: Undo for Volume and Pan
+
+**Input**: Design documents from `/specs/009-mix-param-undo/`
+
+**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**: Requested — FR-013 lists the smoke-test coverage, and the constitution (IV)
+requires it for an engine behaviour change. Engine-level tests live in one new file,
+`tests/Nota.SmokeTest/MixUndoTests.cs`, so tasks touching it are sequential.
+
+**Organization**: by user story — US1 take back a move (P1), US2 one history (P1), US4
+non-edits stay out (P1), US3 every source (P2).
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
+- **[Story]**: US1 / US2 / US3 / US4
+
+---
+
+## Phase 1: Setup
+
+- [X] T001 Run `scripts/build.sh` on the untouched tree and confirm it is green (baseline); if red, stop and report
+
+---
+
+## Phase 2: Foundational (Blocking Prerequisites)
+
+**Purpose**: the history can hold mix steps and the gesture API exists end to end. No
+source is wired yet, so the app behaves as before.
+
+**⚠️ CRITICAL**: No user story work can begin until this phase is complete
+
+- [X] T002 In `src/native/nota.engine/src/Engine.h` add `enum class MixKind : int32_t { TrackVolume = 0, TrackPan = 1, MasterVolume = 2 };`, `struct MixChange { MixKind kind; int32_t trackId; float before; float after; };` and `struct UndoEntry { std::shared_ptr<Graph> graph; std::vector<MixChange> mix; };` ("graph: the state to restore; null for a mix-only step"; "mix: empty for a structural step; at most one change per target"), change `undoStack_` / `redoStack_` to `std::vector<UndoEntry>`, and add `uint64_t undoPushCount_ = 0;`
+- [X] T003 In `src/native/nota.engine/src/Engine.cpp` adapt the history to `UndoEntry`: `pushUndo()` pushes `{authoring_, {}}` and increments `undoPushCount_`; `undo()` pops an entry, pushes `{graph ? authoring_ : nullptr, mix}` onto redo, `publishRaw(graph)` when it has one, then applies every change's `before` (track volume/pan via the authoring track's setter, skipping a missing track; master volume via the master setter) — if the entry has no graph and applied nothing, continue with the next entry (research R3); `redo()` symmetric with `after`; `endUndoGroup()` merges the dropped entries' `mix` into the kept first entry (same target → keep the older `before`, the newer `after`; drop a target whose merged `before == after`); `canUndo/canRedo/clearUndoHistory` keep working; update the undo comment block in `Engine.h` ("volume, pan and master volume steps from mix gestures are covered; mute, solo, sends, device params and the transport are not")
+- [X] T004 In `Engine.h` / `Engine.cpp` add the gesture API (research R2, data-model § Open gesture): `int32_t beginMixGesture(const MixTarget* targets, int32_t count)` (records each valid target's current value as `before` and `pushCountAtBegin = undoPushCount_`; returns a handle > 0, or 0 if no target is valid), `void endMixGesture(int32_t handle)` (unknown handle → no-op; builds changes with exact float compare, dropping unchanged targets and vanished tracks; none → return; if `undoPushCount_ != pushCountAtBegin` and the undo stack is not empty → merge into `undoStack_.back()` by the merge rule; else push `{nullptr, changes}`, trim to `kMaxUndoDepth`, clear redo), `float masterVolume() const`; `reset()` and `clearUndoHistory()` drop all open gestures. Message thread only, no audio-thread code
+- [X] T005 Add the C ABI from [contracts/c-abi-mix-undo.md](contracts/c-abi-mix-undo.md) verbatim to `src/native/nota.engine/include/nota/nota_engine.h` (`NOTA_MIX_*`, `NotaMixTarget`, `nota_mix_gesture_begin`, `nota_mix_gesture_end`, `nota_engine_master_volume`, updated undo comment) and implement it in `src/native/nota.engine/src/nota_engine_core.cpp` (null engine → 0 / no-op / 1.0f)
+- [X] T006 [P] In `src/managed/Nota.Application/Engine/EngineContracts.cs` add `public enum MixKind { TrackVolume = 0, TrackPan = 1, MasterVolume = 2 }` and `[StructLayout(LayoutKind.Sequential)] public readonly record struct MixTarget(MixKind Kind, int TrackId)` with static helpers `Volume(id)`, `Pan(id)`, `Master`; in `src/managed/Nota.Application/Engine/IAudioEngine.cs` add `int BeginMixGesture(params MixTarget[] targets)`, `void EndMixGesture(int handle)`, `float MasterVolume { get; }`
+- [X] T007 [P] P/Invokes in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs` (`MixGestureBegin(IntPtr, MixTarget[], int)`, `MixGestureEnd(IntPtr, int)`, `MasterVolume(IntPtr)`) and wrappers in `src/managed/Nota.Infrastructure/Interop/NotaEngine.cs`
+- [X] T008 [P] Create `src/managed/Nota.Application/Editing/MixEdit.cs` (SPDX header; file comment: one-shot undoable volume/pan edits, specs/009) with `public static void Step(IAudioEngine engine, Action set, params MixTarget[] targets)` — begin, run `set`, end (end runs even if `set` throws)
+- [X] T009 Create `src/managed/Nota.App/MixGestureWiring.cs` (SPDX header) per [contracts/sources.md](contracts/sources.md): `Wire(IAudioEngine engine, Action<Action> onBegin, Action<Action> onEnd, Action<Action<double>> onValue, Func<MixTarget[]> targets)` style helper (adapt the signature to the controls' events) — `GestureBegin` → open a handle, `GestureEnd` → end it, a value change while no handle is open → one-shot via `MixEdit.Step`; and `DebouncedMixGesture` (DispatcherTimer, configurable pause, default 1 s) whose `Touch()` opens a gesture if none is open and restarts the timer, ending the gesture when it fires
+- [X] T010 Create `tests/Nota.SmokeTest/MixUndoTests.cs` (SPDX header; comment "Undo for volume and pan (specs/009-mix-param-undo); also `--mixundo`") with `Run()` and wire it in `tests/Nota.SmokeTest/Program.cs` (full run next to `PanLawTests`, plus a `--mixundo` branch like `--panlaw`); first checks: begin(vol t) · 50 sets · end · undo → exactly the begin value, redo → exactly the last value; begin · end with no set → `CanUndo` unchanged; set back to the start value → no step; master gesture → `MasterVolume` restored; `Reset()` with an open gesture then `EndMixGesture` → no step
+
+**Checkpoint**: `scripts/build.sh` green; the engine API works; no source wired yet.
+
+---
+
+## Phase 3: User Story 1 — Take back a fader move (Priority: P1) 🎯 MVP
+
+**Goal**: fader/knob drags, resets and typed values in the Mixer, the track headers and the
+Return/Master rows are one undo step each.
+
+**Independent Test**: quickstart § 2 steps 1–2.
+
+- [X] T011 [US1] In `src/managed/Nota.App/MixerView.cs` wire with `MixGestureWiring`: `PanRow` knob (target pan), `FaderRow` `VFader` and the dB `DragNumber` (target volume) — keep the existing `BeginAutomationWrite`/`EndAutomationWrite` calls, opening the mix gesture *before* the automation write and ending it *after*; the master strip fader (target `MixTarget.Master`); double-click resets and typed dB values arrive with no gesture open → one-shot
+- [X] T012 [US1] In `src/managed/Nota.App/ArrangementView.cs` wire the header mini fader and pan bar (~lines 1848–1862, same ordering with the automation write) and the Return/Master footer rows (~2425–2466; the master row targets `MixTarget.Master`)
+- [X] T013 [US1] In `src/managed/Nota.App/MainWindow.Menu.cs` `RefreshAfterUndoRedo()`: set `vm.Transport.MasterVolume = Engine.MasterVolume` when it differs (research R4) so MST, the Master strip and the Master row follow an undo; check the MST `MiniFader` in `MainWindow.axaml.cs` (~line 223) follows `vm.Transport.MasterVolume` changes — if it does not, make it follow (skip while dragging)
+- [X] T014 [US1] Headless UI check (memory "Nota UI verify recipe", `NOTA_DATA_DIR`): drive a Mixer fader drag, a pan knob drag, a double-click reset and a typed dB value with synthetic events; after each, `Undo()` restores the exact value in the engine and in the fader/dB field, `Redo()` re-applies; record results in the PR, not in code
+
+**Checkpoint**: US1 works in the Mixer, headers and Return/Master rows.
+
+---
+
+## Phase 4: User Story 2 — One history for everything (Priority: P1)
+
+**Goal**: mix steps and structural steps share one strictly ordered history.
+
+**Independent Test**: contract Guarantees rows on ordering and deleted tracks.
+
+- [X] T015 [US2] In `tests/Nota.SmokeTest/MixUndoTests.cs`: add track · volume gesture · `SetPanLaw(Stereo)` · pan gesture · undo ×4 → each intermediate state matches in reverse order; redo ×4 forward; a new edit after two undos drops redo
+- [X] T016 [US2] In `tests/Nota.SmokeTest/MixUndoTests.cs`: begin(vol t) · set · `RemoveTrack(t)` · end → no mix step (the removal is the top step); volume gesture on t · remove t · undo · undo → t back, then its volume back; two gestures open at once on different tracks → two steps in end order; an undo group (`BeginUndoGroup`/`EndUndoGroup`) containing two volume gestures on the same track → one step from the first `before` to the last `after`
+- [X] T017 [US2] Fix whatever T015–T016 expose in `src/native/nota.engine/src/Engine.cpp` (ordering, merge, skip) until they pass
+
+**Checkpoint**: ordering guarantees hold.
+
+---
+
+## Phase 5: User Story 4 — Things that are not edits stay out (Priority: P1)
+
+**Goal**: automation playback, loads, the template and freeze make no steps; automation
+recording merges with its gesture.
+
+**Independent Test**: quickstart § 2 steps 4–5; contract rows on automation.
+
+- [X] T018 [US4] In `tests/Nota.SmokeTest/MixUndoTests.cs`: a volume + pan automation lane in read mode, clear history, render 2 s while playing → `CanUndo == false`; `ProjectTemplate.ApplyDefault` and a project save → load → `CanUndo == false` for mix steps (no volume/pan values change on undo); `TrackFreezer.Freeze` on a track → undo does not touch its volume
+- [X] T019 [US4] In `tests/Nota.SmokeTest/MixUndoTests.cs`: `SetAutomationRecord(true)` · `BeginMixGesture(vol t)` · `BeginAutomationWrite` · sets while rendering · `EndAutomationWrite` · `EndMixGesture` · one `Undo()` → both the lane points and the volume are back; one `Redo()` → both again (FR-009)
+- [X] T020 [US4] Confirm (grep) that `ProjectService.Apply`, `ProjectTemplate`, `MainWindow.Freeze.cs`, `MainWindow.LiveFreeze.cs` and `MainWindow.Files.cs` resets use only the plain setters, never `BeginMixGesture`/`MixEdit.Step`; fix any that do
+
+**Checkpoint**: non-edits make no steps; recording merges.
+
+---
+
+## Phase 6: User Story 3 — Every way of mixing is undoable (Priority: P2)
+
+**Goal**: Session mixer, MST, Remote, MIDI Learn and MCP changes are undoable.
+
+**Independent Test**: one change from each source, undo each.
+
+- [X] T021 [P] [US3] In `src/managed/Nota.App/SessionView.Mixer.cs` wire the pan knob (~line 117) and the volume fader (~126) with `MixGestureWiring` (sends stay unwired — out of scope)
+- [X] T022 [P] [US3] In `src/managed/Nota.App/MainWindow.axaml.cs` wire the MST `MiniFader` (~line 223) to `MixTarget.Master` via `MixGestureWiring`
+- [X] T023 [P] [US3] In `src/managed/Nota.Remote/RemoteHub.Apply.cs` (`vol`, `pan`, `mvol`): keep a per-client map `(kind, id) → handle`; open a gesture on the first command of a touch when none is open, end it when `cmd.Phase == 2`, and end any open handles when the client disconnects
+- [X] T024 [P] [US3] In `src/managed/Nota.App/MidiLearnService.cs` (~lines 348–350): route `TrackVolume`, `TrackPan`, `MasterVolume` through one `DebouncedMixGesture` per mapping (1 s pause)
+- [X] T025 [P] [US3] In `src/managed/Nota.Mcp/Tools/TrackTools.cs` wrap `set_track_volume` and `set_track_pan` bodies in `MixEdit.Step` (inside the existing `Mutate`)
+- [X] T026 [US3] In `tests/Nota.SmokeTest/MixUndoTests.cs`: `TrackTools.SetTrackVolume` through `McpTestSupport` (`SyncDispatch`, `NoRefresh`) is one undo step; the Remote `vol` command sequence phase 0 → 1 → 2 through the hub (or its apply method) is one step
+
+**Checkpoint**: every listed source is undoable.
+
+---
+
+## Phase 7: Polish & Cross-Cutting Concerns
+
+- [X] T027 Headless UI pass of quickstart § 2 (steps 3–5: MST, automation playback, recording merge) in both themes; nothing visual changes, so no screenshots needed beyond confirmation
+- [X] T028 [P] Performance sanity: a 2 s fader drag (≈120 value changes) allocates nothing per change on the managed side beyond today's (values are only read at begin/end); note it in the PR
+
+### Nota closing tasks
+
+- [X] T029 Run `scripts/build.sh` until native + managed + smoke test are green
+- [X] T030 AGPL-3.0-only SPDX header on every new source file (`MixEdit.cs`, `MixGestureWiring.cs`, `MixUndoTests.cs`)
+- [X] T031 New dependency: N/A
+- [X] T032 `CHANGELOG.md` `[Unreleased]` Added: "**Undo for volume and pan:** fader, pan and master-volume moves can be undone and redone (⌘Z / ⌘⇧Z) from the Mixer, track headers, Session mixer, transport, Nota Remote, a MIDI controller and the AI assistant; one move is one step. Automation playback never adds steps."
+- [X] T033 FEATURES.md via `nota-features` (Project and transport: what undo covers); user docs EN + RU via `nota-docs` (the page that describes undo); shortcuts: N/A
+- [X] T034 Engine behaviour change → smoke test extended: confirm all `MixUndoTests` labels pass in the full run and with `--mixundo`
+
+---
+
+## Dependencies & Execution Order
+
+- **Setup (T001)** → **Foundational (T002–T010)** → stories → **Polish (T027–T034)**
+- T002 → T003 → T004 → T005 → (T006 ∥ T007) → T008 → T009; T010 after T007
+- **US1 (T011–T014)**, **US2 (T015–T017)**, **US4 (T018–T020)** depend only on Foundational
+- **US3 (T021–T026)** depends on Foundational (T009 for the wiring helper)
+- Tests in `MixUndoTests.cs` are sequential: T010 → T015 → T016 → T018 → T019 → T026
+
+### Parallel Opportunities
+
+- T006 ∥ T007 (Application vs Infrastructure)
+- T021 ∥ T022 ∥ T023 ∥ T024 ∥ T025 (five different files)
+- US1 wiring (App) alongside US2 test work (smoke test) once Foundational is done
+
+## Parallel Example: User Story 3
+
+```bash
+Task: "T021 Session mixer wiring in src/managed/Nota.App/SessionView.Mixer.cs"
+Task: "T022 MST wiring in src/managed/Nota.App/MainWindow.axaml.cs"
+Task: "T023 Remote gestures in src/managed/Nota.Remote/RemoteHub.Apply.cs"
+Task: "T024 MIDI Learn debounce in src/managed/Nota.App/MidiLearnService.cs"
+Task: "T025 MCP one-shot in src/managed/Nota.Mcp/Tools/TrackTools.cs"
+```
+
+## Implementation Strategy
+
+### MVP
+
+Foundational + US1 + US2 + US4 is the minimum shippable: the Mixer and headers become
+undoable without corrupting the history or flooding it during playback. US3 completes the
+spec's promise of every source (FR-007); ship all four together in one PR — a partial set
+would make undo behave differently depending on where the user moved a fader.
+
+### Incremental order
+
+1. T001–T010 → engine + API, build green, no visible change
+2. US1 → Mixer / headers / Return-Master undoable
+3. US2 → ordering verified
+4. US4 → playback/loads excluded, recording merges
+5. US3 → Session, MST, Remote, MIDI, MCP
+6. Polish → UI pass, docs, final build
+
+## Notes
+
+- Do not commit or push — the user reviews and commits.
+- `.specify/feature.json` points at `specs/007-midi-note-editing`; run spec-kit scripts for
+ this feature with `SPECIFY_FEATURE_DIRECTORY=specs/009-mix-param-undo SPECIFY_FEATURE_NO_PERSIST=1`.
+- Spec 008 (Stereo Map) waits for this one: a map drag is one gesture with two targets.
+
+## Phase 8: Convergence
+
+- [X] T035 Reconcile the scroll-wheel rule (US1 scenario 5, FR-003 "a burst of scroll-wheel notches…"): no volume/pan control handles the wheel today, so either drop the scenario from the spec via `/speckit-clarify` or add wheel support to `PanKnob`, `VFader`, `MiniFader`, `PanBar` (`src/managed/Nota.App/Controls/`) driven through a 0.5 s `DebouncedMixGesture` per control per US1/AC5 (partial)
+- [X] T036 Add an engine self-test (pattern of the existing `*SelfTest` functions in `src/native/nota.engine/src/`, exposed through `nota_engine.h` and called from `tests/Nota.SmokeTest/MixUndoTests.cs`) that pushes a mix-only undo entry for a track id not in the graph above a valid step and checks that one `undo()` skips it and undoes the valid step, and `redo()` mirrors it, per FR-010 / FR-013 (partial)
+- [X] T037 Make the MIDI-controller pause testable without a UI timer — let `DebouncedMixGesture` (`src/managed/Nota.App/MixGestureWiring.cs`) take the pause timer through a small abstraction, or move the debounce logic into `Nota.Application` with an injected clock — and add a smoke-test check that two movements separated by more than the pause are two steps and a continuous one is one, per US3 scenario 3 / quickstart § 1 (partial)
+- [X] T038 Remove the per-move closure allocation in the wired controls (`src/managed/Nota.App/MixerView.cs`, `ArrangementView.cs`, `SessionView.Mixer.cs`, `MainWindow.axaml.cs`): when the control's `MixGesture` is open call the setter directly and only fall back to `Change(...)` for one-off values, or record in `plan.md` Performance Goals that one small closure per move is accepted, per plan: Performance Goals (partial)
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.cs
index 75c62cc8..27801e1c 100644
--- a/src/managed/Nota.App/App.axaml.cs
+++ b/src/managed/Nota.App/App.axaml.cs
@@ -106,6 +106,16 @@ public partial class App : Avalonia.Application
try { PluginScan.EnsureStoreScanPath(Services.GetRequiredService<IPluginCatalog>(), Services.GetRequiredService<IPluginStore>()); }
catch (Exception e) { log.Error("Couldn't register the Get Plug-ins folder", e); }
+ // Linux: JUCE's message loop isn't shared with Avalonia's (it is on macOS/Windows),
+ // so hosted plugins' editors and timers only run when we service it. Without this,
+ // plugin windows stay black and unclosable and plugins stay silent.
+ if (OperatingSystem.IsLinux())
+ {
+ var pump = new Avalonia.Threading.DispatcherTimer(TimeSpan.FromMilliseconds(10),
+ Avalonia.Threading.DispatcherPriority.Normal, (_, _) => NotaEngine.PumpPluginHost());
+ pump.Start();
+ }
+
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
// A downloaded update installs once the app is gone (see AppUpdater).
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 450beb33..93d46a38 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -1229,6 +1229,14 @@ public sealed partial class ArrangementView : UserControl
ItemDropped?.Invoke(items[i], i == 0 ? trackId : -1, beat);
e.Handled = true;
}
+ /// <summary>Select a track from another view (the Stereo Map, specs/008): the same as a
+ /// header click — the device panel and the other views follow.</summary>
+ public void SelectTrackFromOutside(int trackId)
+ {
+ Select(trackId, -1);
+ TrackSelected?.Invoke(trackId);
+ }
+
internal void Select(int trackId, int clipIndex, bool keepTrackSet = false)
{
if (HasTimeSelection) ClearTimeSelection(); // clip- and time-selection are exclusive (1.2.5)
@@ -1845,9 +1853,15 @@ public sealed partial class ArrangementView : UserControl
};
void ShowDb(double v) => db.Text = VolumeDbText(v);
ShowDb(t.Volume);
- fader.ValueChanged += v => { _engine?.SetTrackVolume(volTrackId, (float)v); ShowDb(v); };
+ // One undo step per drag / reset (specs/009): opened before the automation write so a
+ // recorded lane and the value undo together, closed after it.
+ var volUndo = _engine is { } ve ? new MixGesture(ve, MixTarget.Volume(volTrackId)) : null;
+ fader.GestureBegin += () => volUndo?.Begin();
+ Action<double> setHdrVol = v => _engine?.SetTrackVolume(volTrackId, (float)v);
+ fader.ValueChanged += v => { Change(volUndo, v, setHdrVol); ShowDb(v); };
fader.GestureBegin += () => _engine?.BeginAutomationWrite(volTrackId, AutomationTarget.Volume, -1, -1, "");
fader.GestureEnd += () => _engine?.EndAutomationWrite(volTrackId, AutomationTarget.Volume, -1, -1, "");
+ fader.GestureEnd += () => volUndo?.End();
_volFaders[t.Id] = fader; _volDb[t.Id] = db;
var volCell = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
@@ -1857,9 +1871,13 @@ public sealed partial class ArrangementView : UserControl
volCell.Children.Add(db);
var pan = new PanBar(t.Pan) { VerticalAlignment = VerticalAlignment.Center };
- pan.PanChanged += p => _engine?.SetTrackPan(volTrackId, (float)p);
+ var panUndo = _engine is { } pe ? new MixGesture(pe, MixTarget.Pan(volTrackId)) : null;
+ pan.GestureBegin += () => panUndo?.Begin();
+ Action<double> setHdrPan = p => _engine?.SetTrackPan(volTrackId, (float)p);
+ pan.PanChanged += p => Change(panUndo, p, setHdrPan);
pan.GestureBegin += () => _engine?.BeginAutomationWrite(volTrackId, AutomationTarget.Pan, -1, -1, "");
pan.GestureEnd += () => _engine?.EndAutomationWrite(volTrackId, AutomationTarget.Pan, -1, -1, "");
+ pan.GestureEnd += () => panUndo?.End();
_panBars[t.Id] = pan;
var volRow = new Grid { ColumnDefinitions = new ColumnDefinitions("2*,*"), ColumnSpacing = 6, Margin = new Thickness(0, 6, 0, 0) };
@@ -2411,6 +2429,13 @@ public sealed partial class ArrangementView : UserControl
}
// ---- Return / Master pinned footer -----------------------------------
+ // A value from a control: inside its open undo gesture just set, otherwise a one-off step
+ // (specs/009); no engine (design-time) → just set.
+ private static void Change(MixGesture? undo, double value, Action<double> set)
+ {
+ if (undo is null) set(value); else undo.Change(value, set);
+ }
+
private void RebuildFooterHeaders()
{
_footerHeaders.Children.Clear();
@@ -2463,7 +2488,11 @@ public sealed partial class ArrangementView : UserControl
};
db = dbText;
fader = new MiniFader(volume) { VerticalAlignment = VerticalAlignment.Center, Default = 1.0 };
- fader.ValueChanged += v => { setVolume(v); dbText.Text = VolumeDbText(v); };
+ // One undo step per drag / reset (specs/009): the master row targets the master volume.
+ var undo = _engine is { } ue ? new MixGesture(ue, masterSpine ? MixTarget.Master : MixTarget.Volume(trackId)) : null;
+ fader.GestureBegin += () => undo?.Begin();
+ fader.GestureEnd += () => undo?.End();
+ fader.ValueChanged += v => { Change(undo, v, setVolume); dbText.Text = VolumeDbText(v); };
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), RowDefinitions = new RowDefinitions("*,*") };
Grid.SetColumn(name, 0);
diff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.cs
index ebbf33f2..f0ea7a5f 100644
--- a/src/managed/Nota.App/MainWindow.Files.cs
+++ b/src/managed/Nota.App/MainWindow.Files.cs
@@ -181,6 +181,7 @@ public partial class MainWindow
_vm.Transport.TimeSigNumerator = 4;
_vm.Transport.TimeSigDenominator = 4;
_vm.Transport.KeyCode = -1;
+ _panLawLegacy = false; // new projects use the Stereo pan law (set by the template)
_projectPath = null;
_learn?.Clear(); // start with a clean MIDI-map for the new project
Timeline.ClearSections(); // …and a clean song structure
@@ -216,6 +217,10 @@ public partial class MainWindow
// opens another project before it finished (both loops run on the UI thread).
private int _warpBuildGen;
+ // The open project predates the pan law (specs/006): only drives the Mixer's OLDER PROJECT
+ // badge and is saved back as is.
+ private bool _panLawLegacy;
+
/// <summary>Loads a .nota bundle and applies it to the engine (menu + browser). M7-4b.</summary>
private void OpenProject(string dir)
{
@@ -239,6 +244,7 @@ public partial class MainWindow
_vm.Transport.TimeSigNumerator = result.Transport.TimeSigNumerator;
_vm.Transport.TimeSigDenominator = result.Transport.TimeSigDenominator;
_vm.Transport.KeyCode = result.Transport.Key;
+ _panLawLegacy = result.Transport.PanLawLegacy;
_projectPath = dir;
_learn?.LoadMappings(dir); // MIDI-learn mappings ride in the bundle sidecar
_modular?.LoadLayout(dir); // modular-editor node/island positions (sidecar)
diff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.cs
index 1f078724..1b8f7578 100644
--- a/src/managed/Nota.App/MainWindow.Menu.cs
+++ b/src/managed/Nota.App/MainWindow.Menu.cs
@@ -66,6 +66,11 @@ public partial class MainWindow
if (_deviceChain?.IsVisible == true && Timeline.SelectedTrackId > 0)
_deviceChain.Show(Timeline.SelectedTrackId); // reflect device-chain edits
ReloadEditorNotes(); // reflect clip/note edits
+ // Volume / pan / master steps (specs/009): the master volume lives on the view model
+ // (MST, Master row, Mixer and Remote follow it), the track strips in the Mixer rebuild.
+ if (_vm is { } vm && Math.Abs(vm.Transport.MasterVolume - Engine.MasterVolume) > 1e-6)
+ vm.Transport.MasterVolume = Engine.MasterVolume;
+ if (_mixer?.IsVisible == true) _mixer.Refresh();
}
private void OnMenuImport(object? sender, EventArgs e) => _ = DoImportAsync();
diff --git a/src/managed/Nota.App/MainWindow.Mixer.cs b/src/managed/Nota.App/MainWindow.Mixer.cs
index 79c1cdf1..b98c5cf4 100644
--- a/src/managed/Nota.App/MainWindow.Mixer.cs
+++ b/src/managed/Nota.App/MainWindow.Mixer.cs
@@ -5,6 +5,8 @@
// The single MixerView instance is hosted in the window while it's open and detached on close.
using System;
+using Microsoft.Extensions.DependencyInjection;
+using Nota.Application;
namespace Nota.App;
@@ -20,7 +22,17 @@ public partial class MainWindow
if (_mixerWindow is not null) { _mixerWindow.Close(); return; }
if (_mixer is null) return;
- var win = new MixerWindow(this);
+ // The view (Strips / Stereo Map, specs/008) is a per-user preference.
+ var settings = App.Services.GetRequiredService<ISettingsService>();
+ var view = settings.Current.MixerView == "map" ? MixerViewMode.StereoMap : MixerViewMode.Strips;
+ _mixer.View = view;
+ var win = new MixerWindow(this, view);
+ win.ViewPicked += v =>
+ {
+ if (_mixer is not null) _mixer.View = v;
+ settings.Current.MixerView = v == MixerViewMode.StereoMap ? "map" : "strips";
+ settings.Save();
+ };
win.EnableMidiLearn(_learn); // faders/knobs stay MIDI-mappable in the window
win.WindowClosed += () => { if (_mixer is not null) _mixer.IsVisible = false; _mixerWindow = null; };
_mixerWindow = win;
diff --git a/src/managed/Nota.App/MainWindow.Recovery.cs b/src/managed/Nota.App/MainWindow.Recovery.cs
index d66761dc..d1597b86 100644
--- a/src/managed/Nota.App/MainWindow.Recovery.cs
+++ b/src/managed/Nota.App/MainWindow.Recovery.cs
@@ -26,7 +26,8 @@ public partial class MainWindow
private TransportState TransportSnapshot()
=> new((double)_vm!.Transport.Bpm, _vm.Transport.MasterVolume,
_vm.Transport.MetronomeOn, _vm.Transport.LoopOn,
- _vm.Transport.TimeSigNumerator, _vm.Transport.TimeSigDenominator, _vm.Transport.KeyCode);
+ _vm.Transport.TimeSigNumerator, _vm.Transport.TimeSigDenominator, _vm.Transport.KeyCode,
+ _panLawLegacy);
private void OnAutosaveTick()
{
@@ -95,6 +96,7 @@ public partial class MainWindow
if (_vm is null) return;
// The launch workspace starts from the same template as File → New.
Nota.Infrastructure.ProjectTemplate.ApplyDefault(Engine);
+ _panLawLegacy = false;
RefreshAfterLoad();
MarkProjectClean(); // the fresh startup project counts as unmodified
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 5d431915..4de48d27 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -18,6 +18,7 @@ using Avalonia.Threading;
using Avalonia.VisualTree;
using Microsoft.Extensions.DependencyInjection;
using Nota.Application;
+using Nota.Application.Editing;
using Nota.Presentation;
using System.Runtime.InteropServices;
@@ -221,7 +222,11 @@ public partial class MainWindow : Window
// Thin master volume fader (mockup 1b) — MiniFader instead of a stock Slider. It
// sits over the master meter inside the MST module, with the gain printed in dB.
var masterVol = new MiniFader((double)vm.Transport.MasterVolume, 1.5);
- masterVol.ValueChanged += v => vm.Transport.MasterVolume = v;
+ var masterUndo = new MixGesture(vm.Engine, MixTarget.Master); // one undo step per drag (specs/009)
+ masterVol.GestureBegin += masterUndo.Begin;
+ masterVol.GestureEnd += masterUndo.End;
+ Action<double> setMaster = v => vm.Transport.MasterVolume = v;
+ masterVol.ValueChanged += v => masterUndo.Change(v, setMaster);
MasterVolHost.Children.Add(masterVol);
MidiLearn.Bind(masterVol, MidiTarget.MasterVolume, "Master Volume");
@@ -373,6 +378,13 @@ public partial class MainWindow : Window
IsVisible = false,
GetMasterVolume = () => (float)vm.Transport.MasterVolume,
SetMasterVolume = v => vm.Transport.MasterVolume = v,
+ IsOlderProject = () => _panLawLegacy,
+ // The Stereo Map (specs/008) selects through the arrangement and follows its selection.
+ MapCreated = map =>
+ {
+ map.SelectedTrackId = () => Timeline.SelectedTrackId;
+ map.SelectTrack = id => Timeline.SelectTrackFromOutside(id);
+ },
};
// Modular: signal-graph view of the selected track (mockup 1a). Follows track
diff --git a/src/managed/Nota.App/MidiLearnService.cs b/src/managed/Nota.App/MidiLearnService.cs
index d5d1e915..aa545200 100644
--- a/src/managed/Nota.App/MidiLearnService.cs
+++ b/src/managed/Nota.App/MidiLearnService.cs
@@ -17,6 +17,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Nota.Application;
+using Nota.Application.Editing;
namespace Nota.App;
@@ -26,6 +27,15 @@ public sealed class MidiLearnService
private const float RackGainMax = 2.0f; // rack out / chain gain travel (matches the rack faders)
private readonly IAudioEngine _engine;
+ // One undo step per controller movement on a mapped volume / pan target, ended by a 1 s
+ // pause (specs/009); the pause is checked on every Tick.
+ private static readonly TimeSpan MixPause = TimeSpan.FromSeconds(1);
+ private readonly Dictionary<MixTarget, MixMovement> _mixUndo = new();
+ private void MixTouch(MixTarget target, Action set)
+ {
+ if (!_mixUndo.TryGetValue(target, out var m)) _mixUndo[target] = m = new MixMovement(_engine, target, MixPause);
+ m.Touch(set, Environment.TickCount64);
+ }
private readonly ILogSink? _log;
private readonly List<MidiMapping> _mappings = new();
private readonly int[] _buf = new int[256 * 4]; // reused each tick — up to 256 events
@@ -242,6 +252,8 @@ public sealed class MidiLearnService
public void Tick()
{
+ long nowMs = Environment.TickCount64;
+ foreach (var m in _mixUndo.Values) m.Poll(nowMs); // end controller movements after their pause
int n = _engine.PollMidiControlEvents(_buf);
EventCount += n;
for (int i = 0; i < n; i++)
@@ -345,9 +357,16 @@ public sealed class MidiLearnService
_engine.MidiEffectSetParam(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)(min + outv * (max - min)));
break;
}
- case MidiTargetKind.TrackVolume: _engine.SetTrackVolume(t.TrackId, (float)(outv * VolumeMax)); break;
- case MidiTargetKind.MasterVolume: _engine.SetMasterVolume((float)(outv * VolumeMax)); break;
- case MidiTargetKind.TrackPan: _engine.SetTrackPan(t.TrackId, (float)(outv * 2.0 - 1.0)); break;
+ // Volume / pan: one undo step per movement, ended by a 1 s pause (specs/009).
+ case MidiTargetKind.TrackVolume:
+ MixTouch(MixTarget.Volume(t.TrackId), () => _engine.SetTrackVolume(t.TrackId, (float)(outv * VolumeMax)));
+ break;
+ case MidiTargetKind.MasterVolume:
+ MixTouch(MixTarget.Master, () => _engine.SetMasterVolume((float)(outv * VolumeMax)));
+ break;
+ case MidiTargetKind.TrackPan:
+ MixTouch(MixTarget.Pan(t.TrackId), () => _engine.SetTrackPan(t.TrackId, (float)(outv * 2.0 - 1.0)));
+ break;
case MidiTargetKind.RackVolume:
if (t.DeviceIndex < 0) _engine.RackSetVolume(t.TrackId, (float)(outv * RackGainMax));
else _engine.RackDevSetVolume(t.TrackId, t.DeviceIndex, (float)(outv * RackGainMax));
diff --git a/src/managed/Nota.App/MixerView.cs b/src/managed/Nota.App/MixerView.cs
index 3bf366c8..1bb84880 100644
--- a/src/managed/Nota.App/MixerView.cs
+++ b/src/managed/Nota.App/MixerView.cs
@@ -5,7 +5,8 @@
// per track (+ returns + master): name with a 2px colour top, I/O rows, A/B
// sends, a pan knob, a 190px vertical fader with a stereo meter, a dB read-out
// and M/S/Arm. All strips ride the existing engine ops (vol/pan/mute/solo/send/
-// meter); meters are pushed each UI tick by MainWindow. Crossfader is M7+.
+// meter); meters are pushed each UI tick by MainWindow. Crossfader is M7+. The footer
+// also shows and switches the project pan law (specs/006).
using System;
using System.Collections.Generic;
@@ -17,9 +18,13 @@ using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Nota.Application;
+using Nota.Application.Editing;
namespace Nota.App;
+/// <summary>The Mixer window's two views (specs/008).</summary>
+public enum MixerViewMode { Strips, StereoMap }
+
public sealed class MixerView : UserControl
{
private static readonly IBrush Card = NotaPalette.SurfaceCard;
@@ -50,11 +55,31 @@ public sealed class MixerView : UserControl
public Action<float>? SetMasterVolume { get; set; }
private VFader? _masterFader;
private DragNumber? _masterDb;
+ // Project pan law (specs/006): the footer's PAN LAW control, its hint, the OLDER PROJECT
+ // badge and a BAL badge on every group strip — all re-synced from the engine, so undo/redo
+ // and project load show up without a rebuild.
+ public Func<bool>? IsOlderProject { get; set; }
+ private Action<int>? _setLawSegment;
+ private TextBlock? _lawHint;
+ private Control? _olderBadge;
+ private readonly List<Control> _balBadges = new();
+ private PanLaw? _shownLaw;
+ private bool _shownOlder;
+
+ // Strips or the Stereo Map beside a narrower strip column (specs/008). The strips scroller
+ // is one instance moved between the two layouts.
+ private readonly ScrollViewer _stripsScroller;
+ private readonly ContentControl _main = new();
+ private MixerViewMode _view = MixerViewMode.Strips;
+ /// <summary>The Stereo Map, created the first time the view is shown.</summary>
+ public StereoMapView? Map { get; private set; }
+ /// <summary>Called once when the map is created, to wire its callbacks.</summary>
+ public Action<StereoMapView>? MapCreated { get; set; }
public MixerView(IAudioEngine engine)
{
_engine = engine;
- var scroller = new ScrollViewer
+ _stripsScroller = new ScrollViewer
{
Content = _row,
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
@@ -64,8 +89,38 @@ public sealed class MixerView : UserControl
var footer = Footer();
DockPanel.SetDock(footer, Dock.Bottom);
dock.Children.Add(footer);
- dock.Children.Add(scroller);
+ dock.Children.Add(_main);
Content = dock;
+ ApplyView();
+ }
+
+ public MixerViewMode View
+ {
+ get => _view;
+ set { if (_view == value) return; _view = value; ApplyView(); }
+ }
+
+ private void ApplyView()
+ {
+ // Detach the scroller from whichever layout held it before re-parenting.
+ if (_stripsScroller.Parent is Panel p) p.Children.Remove(_stripsScroller);
+ else if (_stripsScroller.Parent is ContentControl c) c.Content = null;
+ if (Map?.Parent is Panel mp) mp.Children.Remove(Map);
+ _main.Content = null;
+
+ if (_view == MixerViewMode.Strips)
+ {
+ _stripsScroller.MaxWidth = double.PositiveInfinity;
+ _main.Content = _stripsScroller;
+ return;
+ }
+ if (Map is null) { Map = new StereoMapView(_engine) { MinWidth = 520 }; MapCreated?.Invoke(Map); }
+ _stripsScroller.MaxWidth = 440;
+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8, Margin = new Thickness(8) };
+ grid.Children.Add(Map);
+ Grid.SetColumn(_stripsScroller, 1);
+ grid.Children.Add(_stripsScroller);
+ _main.Content = grid;
}
public void Refresh()
@@ -74,6 +129,7 @@ public sealed class MixerView : UserControl
_meters.Clear();
_sendSections.Clear();
_ioSections.Clear();
+ _balBadges.Clear();
int returns = _engine.ReturnTrackCount;
int n = _engine.TrackCount;
for (int i = 0; i < n; i++)
@@ -83,6 +139,8 @@ public sealed class MixerView : UserControl
_row.Children.Add(Strip(ti, c, returns));
}
_row.Children.Add(MasterStrip());
+ _shownLaw = null; // the strips are new: repaint the law state onto them
+ SyncPanLaw();
}
/// <summary>Pushes fresh meter readings to every strip (called at the UI clock).</summary>
@@ -99,6 +157,7 @@ public sealed class MixerView : UserControl
double v = get();
if (Math.Abs(f.Value - v) > 1e-3) { f.SetValueExternal(v); db.Value = LinToDb(v); }
}
+ SyncPanLaw(); // undo/redo or a load elsewhere may have changed it
}
// ---- strips -----------------------------------------------------------
@@ -129,7 +188,7 @@ public sealed class MixerView : UserControl
col.Children.Add(sends);
}
- col.Children.Add(PanRow(id, ti.Pan));
+ col.Children.Add(PanRow(id, ti.Pan, ti.IsGroup));
col.Children.Add(FaderRow(id, ti.Volume, color, out var db, out var meter));
_meters.Add((id, meter));
col.Children.Add(db);
@@ -167,7 +226,7 @@ public sealed class MixerView : UserControl
};
}
- // ---- footer: section toggles + crossfader placeholder ----------------
+ // ---- footer: section toggles + pan law + crossfader placeholder -------
private Control Footer()
{
@@ -179,12 +238,19 @@ public sealed class MixerView : UserControl
Children = { new TextBlock { Text = "Show", FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center }, sendsToggle, ioToggle },
};
+ var divider = new Border { Width = 1, Height = 20, Background = BorderDef, VerticalAlignment = VerticalAlignment.Center };
+ var leftSide = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 14, VerticalAlignment = VerticalAlignment.Center,
+ Children = { left, divider, PanLawGroup() },
+ };
+
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };
- grid.Children.Add(left);
+ grid.Children.Add(leftSide);
var xf = Crossfader();
Grid.SetColumn(xf, 2);
grid.Children.Add(xf);
- return new Border { Height = 34, Background = MasterBg, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(12, 0), Child = grid };
+ return new Border { Height = 44, Background = MasterBg, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(12, 0), Child = grid };
}
private Border SectionToggle(string label, bool initial, Action<bool> set)
@@ -199,6 +265,65 @@ public sealed class MixerView : UserControl
return b;
}
+ // PAN LAW: the project's pan law as shell segments, a one-line hint, and the OLDER PROJECT
+ // badge for projects made before the law existed (they keep Balance until switched).
+ private Control PanLawGroup()
+ {
+ var label = new TextBlock { Text = "PAN LAW", FontSize = 10, FontWeight = FontWeight.Bold, LetterSpacing = 1.4, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ var seg = ClipEditorKit.Segments(new[] { "Stereo", "Balance" }, _engine.PanLaw == PanLaw.Stereo ? 0 : 1, i =>
+ {
+ var law = i == 0 ? PanLaw.Stereo : PanLaw.Balance;
+ if (_engine.PanLaw != law) _engine.SetPanLaw(law); // one undo step
+ SyncPanLaw();
+ }, out var set);
+ seg.VerticalAlignment = VerticalAlignment.Center;
+ _setLawSegment = set;
+ if (seg.Child is Panel buttons)
+ {
+ string[] tips = { "Panning moves the whole stereo image; nothing is dropped", "Panning attenuates the opposite channel (legacy behaviour)" };
+ for (int i = 0; i < buttons.Children.Count && i < tips.Length; i++) ToolTip.SetTip(buttons.Children[i], tips[i]);
+ }
+ _lawHint = new TextBlock { FontSize = 11, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ _olderBadge = Tag("OLDER PROJECT", 9, 1.6, 18, "Projects saved before stereo pan law open with Balance so existing mixes do not change");
+ return new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center,
+ Children = { label, seg, _lawHint, _olderBadge },
+ };
+ }
+
+ // Repaints the law state (segment, hint, badges) when the engine's law or the
+ // older-project mark changed since the last call.
+ private void SyncPanLaw()
+ {
+ var law = _engine.PanLaw;
+ bool older = IsOlderProject?.Invoke() == true;
+ if (law == _shownLaw && older == _shownOlder) return;
+ _shownLaw = law;
+ _shownOlder = older;
+ bool stereo = law == PanLaw.Stereo;
+ _setLawSegment?.Invoke(stereo ? 0 : 1);
+ if (_lawHint is not null)
+ _lawHint.Text = stereo ? "Pan moves the whole image of stereo tracks and returns"
+ : "Pan attenuates the opposite channel, as in earlier versions";
+ if (_olderBadge is not null) _olderBadge.IsVisible = older && !stereo;
+ foreach (var b in _balBadges) b.IsVisible = stereo;
+ }
+
+ // A small mono tag in a hairline frame (OLDER PROJECT, BAL), with a tooltip.
+ private static Border Tag(string text, double size, double tracking, double height, string tip)
+ {
+ var t = new TextBlock { Text = text, FontSize = size, LetterSpacing = tracking, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ t.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ var b = new Border
+ {
+ Height = height, Padding = new Thickness(size >= 9 ? 6 : 3, 0), BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Badge, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Child = t,
+ };
+ ToolTip.SetTip(b, tip);
+ return b;
+ }
+
// Crossfader is not in the engine yet — a disabled A/B track with an M7+ badge.
private Control Crossfader()
{
@@ -314,17 +439,31 @@ public sealed class MixerView : UserControl
return new Border { Height = 42, BorderBrush = BorderInner, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(7, 5), Child = body };
}
- private Control PanRow(int id, float pan)
+ private Control PanRow(int id, float pan, bool isGroup = false)
{
var knob = new PanKnob(pan);
- knob.PanChanged += p => _engine.SetTrackPan(id, (float)p);
+ // One undo step per gesture (specs/009); opened before the automation write so a
+ // recorded lane and the value undo together, closed after it.
+ var undo = new MixGesture(_engine, MixTarget.Pan(id));
+ knob.GestureBegin += undo.Begin;
+ Action<double> setPan = p => _engine.SetTrackPan(id, (float)p);
+ knob.PanChanged += p => undo.Change(p, setPan);
if (id > 0) // M9-C: record pan moves (master pan isn't an automation target)
{
knob.GestureBegin += () => _engine.BeginAutomationWrite(id, AutomationTarget.Pan, -1, -1, "");
knob.GestureEnd += () => _engine.EndAutomationWrite(id, AutomationTarget.Pan, -1, -1, "");
MidiLearn.Bind(knob, MidiTarget.TrackPan(id), "Track Pan");
}
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = { knob, Mono("PAN", TextTertiary) } };
+ knob.GestureEnd += undo.End;
+ Control label = Mono("PAN", TextTertiary);
+ if (isGroup) // groups keep their unity-centre balance whatever the project law (specs/006)
+ {
+ var bal = Tag("BAL", 7, 0.84, 11, "Groups keep a unity-centre balance so grouping stays level-transparent");
+ bal.IsVisible = _engine.PanLaw == PanLaw.Stereo;
+ _balBadges.Add(bal);
+ label = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Children = { label, bal } };
+ }
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = { knob, label } };
return new Border { Height = 38, BorderBrush = BorderInner, BorderThickness = new Thickness(0, 0, 0, 1), Child = row };
}
@@ -347,13 +486,21 @@ public sealed class MixerView : UserControl
ToolTip.SetTip(dbNum, "Set the gain — drag, or double-click to type");
void SetVolume(double v) { if (id < 0) SetMasterVolume?.Invoke((float)v); else _engine.SetTrackVolume(id, (float)v); }
if (id < 0) { _masterFader = fader; _masterDb = dbNum; }
- fader.ValueChanged += v => { SetVolume(v); dbNum.Value = LinToDb(v); };
- dbNum.ValueChanged += d => { double v = DbToLin(d); SetVolume(v); fader.SetValueExternal(v); };
+ // One undo step per drag of the fader or the dB number, and per reset / typed value
+ // (specs/009). Opened before the automation write, closed after it.
+ var undo = new MixGesture(_engine, id < 0 ? MixTarget.Master : MixTarget.Volume(id));
+ fader.GestureBegin += undo.Begin;
+ dbNum.GestureBegin += undo.Begin;
+ Action<double> setVol = SetVolume;
+ fader.ValueChanged += v => { undo.Change(v, setVol); dbNum.Value = LinToDb(v); };
+ dbNum.ValueChanged += d => { double v = DbToLin(d); undo.Change(v, setVol); fader.SetValueExternal(v); };
if (id > 0) // M9-C: record volume moves (master volume isn't a track target)
{
fader.GestureBegin += () => _engine.BeginAutomationWrite(id, AutomationTarget.Volume, -1, -1, "");
fader.GestureEnd += () => _engine.EndAutomationWrite(id, AutomationTarget.Volume, -1, -1, "");
}
+ fader.GestureEnd += undo.End;
+ dbNum.GestureEnd += undo.End;
MidiLearn.Bind(fader, id > 0 ? MidiTarget.TrackVolume(id) : MidiTarget.MasterVolume, id > 0 ? "Track Volume" : "Master Volume");
db = dbNum;
diff --git a/src/managed/Nota.App/MixerWindow.cs b/src/managed/Nota.App/MixerWindow.cs
index 7fbcbaf5..38733540 100644
--- a/src/managed/Nota.App/MixerWindow.cs
+++ b/src/managed/Nota.App/MixerWindow.cs
@@ -4,6 +4,7 @@
// The Mixer in its own window (opened from View → Mixer). It hosts the single MixerView
// instance the main window owns (reparented, not rebuilt), so meters/state carry over and
// the tick loop keeps updating it while the window is open. Closing detaches the mixer.
+// Its own title bar carries the Strips | Stereo Map switch (specs/008).
using System;
using Avalonia;
@@ -19,10 +20,17 @@ internal sealed class MixerWindow : NotaWindow
{
public ContentControl Host { get; }
public event Action? WindowClosed;
+ /// <summary>The user picked a view in the title bar.</summary>
+ public event Action<MixerViewMode>? ViewPicked;
+ private readonly Action<int> _setViewSegment;
+
+ private const double BarH = 36;
+ private static readonly double LeftInset = !NativeFrame && OperatingSystem.IsMacOS() ? 76 : 12;
+ private static readonly double RightInset = !NativeFrame && OperatingSystem.IsWindows() ? 8 + 138 : 8;
private readonly MainWindow _owner;
- public MixerWindow(MainWindow owner)
+ public MixerWindow(MainWindow owner, MixerViewMode view) : base(BarH)
{
_owner = owner;
@@ -39,9 +47,38 @@ internal sealed class MixerWindow : NotaWindow
Background = NotaPalette.BgApp;
Host = new ContentControl { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch };
- SetBody(Host);
+
+ // Title bar: caption left, the view switch centred; empty bar area drags the window.
+ var caption = new TextBlock
+ {
+ Text = "Mixer", FontSize = NotaType.Name, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary,
+ VerticalAlignment = VerticalAlignment.Center,
+ };
+ var seg = ClipEditorKit.Segments(new[] { "Strips", "Stereo Map" }, view == MixerViewMode.StereoMap ? 1 : 0,
+ i => ViewPicked?.Invoke(i == 1 ? MixerViewMode.StereoMap : MixerViewMode.Strips), out _setViewSegment);
+ seg.HorizontalAlignment = HorizontalAlignment.Center;
+ seg.VerticalAlignment = VerticalAlignment.Center;
+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,*") };
+ grid.Children.Add(caption);
+ Grid.SetColumn(seg, 1);
+ grid.Children.Add(seg);
+ var bar = new Border
+ {
+ Height = BarH, Background = NotaPalette.Panel, BorderBrush = NotaPalette.GraphBorder,
+ BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(LeftInset, 0, RightInset, 0), Child = grid,
+ };
+ if (!NativeFrame) bar.PointerPressed += OnChromePressed;
+
+ var dock = new DockPanel();
+ DockPanel.SetDock(bar, Dock.Top);
+ dock.Children.Add(bar);
+ dock.Children.Add(Host);
+ SetBody(dock);
}
+ /// <summary>Repaints the title-bar switch (the view changed elsewhere).</summary>
+ public void ShowView(MixerViewMode view) => _setViewSegment(view == MixerViewMode.StereoMap ? 1 : 0);
+
protected override void OnClosing(WindowClosingEventArgs e)
{
base.OnClosing(e);
diff --git a/src/managed/Nota.App/SessionView.Mixer.cs b/src/managed/Nota.App/SessionView.Mixer.cs
index 49d52c1f..4949a436 100644
--- a/src/managed/Nota.App/SessionView.Mixer.cs
+++ b/src/managed/Nota.App/SessionView.Mixer.cs
@@ -14,6 +14,7 @@ using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Nota.Application;
+using Nota.Application.Editing;
using Nota.Presentation;
namespace Nota.App;
@@ -114,7 +115,11 @@ public sealed partial class SessionView
{
int id = c.TrackId;
var pan = new PanBar(ti.Pan) { VerticalAlignment = VerticalAlignment.Center }; // draws its own C / 12L readout
- pan.PanChanged += p => _engine.SetTrackPan(id, (float)p);
+ var panUndo = new MixGesture(_engine, MixTarget.Pan(id)); // one undo step per drag (specs/009)
+ pan.GestureBegin += panUndo.Begin;
+ pan.GestureEnd += panUndo.End;
+ Action<double> setPan = p => _engine.SetTrackPan(id, (float)p);
+ pan.PanChanged += p => panUndo.Change(p, setPan);
panRow = FaderRow(pan, ReadoutText());
}
else panRow = new Border { Height = FaderRowH };
@@ -123,12 +128,15 @@ public sealed partial class SessionView
var vol = new MiniFader(vol0, 1.5) { Default = 1.0 };
var db = ReadoutText();
void ShowDb() => db.Text = vol.Value <= 1e-4 ? "−∞" : NotaNum.Db(AudioMath.LinToDb(vol.Value), signed: true);
- vol.ValueChanged += v =>
+ var volUndo = new MixGesture(_engine, hasTrack ? MixTarget.Volume(c.TrackId) : MixTarget.Master);
+ vol.GestureBegin += volUndo.Begin;
+ vol.GestureEnd += volUndo.End;
+ Action<double> setVol = v =>
{
if (hasTrack) _engine.SetTrackVolume(c.TrackId, (float)v);
else SetMasterVolume?.Invoke((float)v);
- ShowDb();
};
+ vol.ValueChanged += v => { volUndo.Change(v, setVol); ShowDb(); };
ShowDb();
var mL = new MeterLine(); var mR = new MeterLine();
diff --git a/src/managed/Nota.App/StereoMapView.cs b/src/managed/Nota.App/StereoMapView.cs
new file mode 100644
index 00000000..6c78dbc4
--- /dev/null
+++ b/src/managed/Nota.App/StereoMapView.cs
@@ -0,0 +1,491 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The Stereo Map (specs/008-stereo-map): the Mixer's second view. Every track, return and the
+// master is a handle at (pan, fader) — the control — with a cloud for where its sound really
+// is (measured balance on the pan scale), how wide (1 − correlation) and how loud, plus the
+// master correlation. One custom-drawn control, refreshed on every animation frame while it is
+// visible: one native call per frame brings all measurements. Dragging a handle is one undo
+// step over pan and volume (specs/009), with the automation rules of the strip controls;
+// a click selects the track everywhere. Layout, tokens and texts: specs/008 contracts.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Nota.Application;
+using Nota.Application.Editing;
+
+namespace Nota.App;
+
+/// <summary>The Mixer fader's value ↔ position mapping (linear gain, 0 … <see cref="Max"/>),
+/// shared by the strip fader and the Stereo Map so a handle and its fader always agree.</summary>
+internal static class FaderScale
+{
+ public const double Max = 1.5;
+ public static double Frac(double gain) => Math.Clamp(gain / Max, 0, 1);
+ public static double Gain(double frac) => Math.Clamp(frac, 0, 1) * Max;
+}
+
+public sealed class StereoMapView : Control
+{
+ // Panel geometry (contract): header and bottom rows, the well's inset and the plot padding.
+ private const double HeaderH = 36, BottomH = 32, Inset = 8, Radius = 6;
+ private const double PadTop = 14, PadRight = 18, PadBottom = 22, PadLeft = 40;
+ private const double HandleR = 8, HitSlop = 4, CloudH = 22, LabelMaxW = 84;
+ private const double OffPanNote = 0.15;
+ private const int TooltipDelayMs = 300;
+ // "Negative" correlation for the red outline: below this, not at 0 — unrelated material
+ // hovers around 0 and would flicker red on every block.
+ private const float PhaseAlarm = -0.05f;
+
+ private readonly IAudioEngine _engine;
+
+ /// <summary>The app's selected track id (the ring follows it).</summary>
+ public Func<int>? SelectedTrackId { get; set; }
+ /// <summary>Select a track everywhere (arrangement, device panel).</summary>
+ public Action<int>? SelectTrack { get; set; }
+
+ private struct Item
+ {
+ public int Id;
+ public string Name;
+ public IBrush Color;
+ public float Pan, Volume;
+ public bool Muted, Dimmed, Master;
+ public StereoMeasure M;
+ public bool Has;
+ public double Level => Has ? M.LevelDb : -200;
+ }
+
+ private readonly List<Item> _items = new();
+ private readonly List<int> _order = new(); // draw order: indices into _items
+ private StereoMeasure[] _measures = new StereoMeasure[64];
+ private readonly Dictionary<int, int> _measureAt = new();
+ private readonly Dictionary<int, (string name, IBrush color)> _looks = new();
+ private readonly Dictionary<int, (string text, IBrush brush, FormattedText ft)> _labels = new();
+ private readonly List<Rect> _placedLabels = new(); // this frame's label boxes (no two overlap)
+ // The last tooltip drawn: its rows and note titles (read by the UI checks).
+ private readonly List<(string key, string value)> _tooltipRows = new();
+ private readonly List<string> _tooltipNotes = new();
+ private int _frame;
+ private bool _frameRequested;
+
+ // Interaction state.
+ private int _dragId = -1;
+ private MixGesture? _drag;
+ private Point _dragStart;
+ private float _dragPan0, _dragVol0;
+ private bool _dragMoved;
+ private int _hoverId = -1;
+ private long _hoverSince;
+
+ public StereoMapView(IAudioEngine engine)
+ {
+ _engine = engine;
+ ClipToBounds = true;
+ Focusable = false;
+ }
+
+ // ---- frame loop ---------------------------------------------------------------------
+
+ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
+ {
+ base.OnAttachedToVisualTree(e);
+ RequestFrame();
+ }
+
+ private void RequestFrame()
+ {
+ if (_frameRequested) return;
+ if (TopLevel.GetTopLevel(this) is not { } top) return;
+ _frameRequested = true;
+ top.RequestAnimationFrame(_ =>
+ {
+ _frameRequested = false;
+ if (TopLevel.GetTopLevel(this) is null) return; // detached: the loop ends
+ if (IsEffectivelyVisible) { Pull(); InvalidateVisual(); }
+ RequestFrame();
+ });
+ }
+
+ /// <summary>Re-reads tracks and measurements now (the frame loop does this every frame).</summary>
+ public void Pull()
+ {
+ _frame++;
+ bool refreshLooks = _frame % 30 == 1; // names / colours: twice a second is plenty
+ _items.Clear();
+ int n = _engine.TrackCount;
+ bool anySolo = false;
+ for (int i = 0; i < n; i++)
+ if (_engine.TryGetTrackInfo(i, out var t) && !t.IsGroup && t.Soloed != 0) { anySolo = true; break; }
+
+ int rows = _engine.GetStereoMeasures(_measures);
+ if (rows > _measures.Length) { _measures = new StereoMeasure[rows + 16]; rows = _engine.GetStereoMeasures(_measures); }
+ _measureAt.Clear();
+ for (int i = 0; i < Math.Min(rows, _measures.Length); i++) _measureAt[_measures[i].TrackId] = i;
+
+ for (int i = 0; i < n; i++)
+ {
+ if (!_engine.TryGetTrackInfo(i, out var t) || t.IsGroup) continue;
+ if (refreshLooks || !_looks.ContainsKey(t.Id))
+ _looks[t.Id] = (TrackNames.Of(_engine, t), ArrangementView.TrackBrush(ArrangementView.EffectiveColorIndex(_engine, t.Id)));
+ var look = _looks[t.Id];
+ var item = new Item
+ {
+ Id = t.Id, Name = look.name, Color = look.color, Pan = t.Pan, Volume = t.Volume,
+ Muted = t.Muted != 0, Dimmed = anySolo && t.Soloed == 0 && !t.IsReturn,
+ };
+ if (_measureAt.TryGetValue(t.Id, out int mi)) { item.M = _measures[mi]; item.Has = true; }
+ _items.Add(item);
+ }
+ int masterId = _engine.MasterTrackId;
+ var master = new Item
+ {
+ Id = masterId, Name = _engine.GetTrackName(masterId) is { Length: > 0 } mn ? mn : "Master",
+ Color = NotaPalette.Accent, Pan = 0, Volume = _engine.MasterVolume, Master = true,
+ };
+ if (_measureAt.TryGetValue(masterId, out int mm)) { master.M = _measures[mm]; master.Has = true; }
+ _items.Add(master);
+
+ // Draw order: the master first (under everything — it shares C / 0 dB with every new
+ // track, and only tracks can be dragged), then quiet to loud, the selected handle last
+ // (on top). Hit-testing walks it backwards, so the master is picked only when alone.
+ int sel = SelectedTrackId?.Invoke() ?? -1;
+ _order.Clear();
+ for (int i = 0; i < _items.Count; i++) _order.Add(i);
+ _order.Sort((a, b) =>
+ {
+ bool ma = _items[a].Master, mb = _items[b].Master;
+ if (ma != mb) return ma ? -1 : 1;
+ bool sa = _items[a].Id == sel, sb = _items[b].Id == sel;
+ if (sa != sb) return sa ? 1 : -1;
+ return _items[a].Level.CompareTo(_items[b].Level);
+ });
+ }
+
+ // ---- geometry -----------------------------------------------------------------------
+
+ private Rect Plot()
+ {
+ var b = Bounds;
+ double left = Inset + PadLeft, top = HeaderH + Inset + PadTop;
+ double right = b.Width - Inset - PadRight, bottom = b.Height - BottomH - Inset - PadBottom;
+ return new Rect(left, top, Math.Max(1, right - left), Math.Max(1, bottom - top));
+ }
+
+ private static double PanX(Rect p, double pan) => p.Left + (Math.Clamp(pan, -1, 1) + 1) / 2 * p.Width;
+ private static double VolY(Rect p, double gain) => p.Bottom - FaderScale.Frac(gain) * p.Height;
+ private static Point HandleAt(Rect p, in Item it) => new(PanX(p, it.Pan), VolY(p, it.Volume));
+
+ // ---- rendering ----------------------------------------------------------------------
+
+ public override void Render(DrawingContext ctx)
+ {
+ var b = Bounds;
+ var plot = Plot();
+ // Panel, header, well.
+ ctx.DrawRectangle(NotaPalette.SurfaceCard, new Pen(NotaPalette.BorderDefault, 1), new Rect(0.5, 0.5, b.Width - 1, b.Height - 1), Radius, Radius);
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, HeaderH), new Point(b.Width, HeaderH));
+ DrawText(ctx, "STEREO MAP", NotaFonts.SansBold, 10, NotaPalette.TextPrimary, new Point(12, HeaderH / 2), vCenter: true, tracking: true);
+ var well = new Rect(Inset, HeaderH + Inset, b.Width - 2 * Inset, b.Height - HeaderH - BottomH - 2 * Inset);
+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), well, 4, 4);
+ DrawGrid(ctx, plot);
+
+ // Clouds, then handles and labels, in draw order.
+ using (ctx.PushClip(well))
+ {
+ foreach (int i in _order) DrawCloud(ctx, plot, _items[i]);
+ int sel = SelectedTrackId?.Invoke() ?? -1;
+ foreach (int i in _order) DrawHandle(ctx, plot, _items[i], _items[i].Id == sel);
+ DrawLabels(ctx, plot, sel);
+ }
+ DrawBottom(ctx, b);
+ DrawTooltip(ctx, plot, b);
+ }
+
+ private void DrawGrid(DrawingContext ctx, Rect p)
+ {
+ var strong = new Pen(NotaPalette.BorderDefault, 1);
+ var weak = new Pen(NotaPalette.GridBeat, 1);
+ foreach (var (pan, label) in new[] { (-1.0, "L100"), (-0.5, "L50"), (0.0, "C"), (0.5, "R50"), (1.0, "R100") })
+ {
+ double x = Math.Round(PanX(p, pan)) + 0.5;
+ ctx.DrawLine(pan == 0 ? strong : weak, new Point(x, p.Top), new Point(x, p.Bottom));
+ DrawText(ctx, label, NotaFonts.Mono, 8, NotaPalette.TextTertiary, new Point(x, p.Bottom + 6), hCenter: true);
+ }
+ foreach (var (db, label) in new[] { (20 * Math.Log10(FaderScale.Max), "+3.5"), (0.0, "0 dB"), (-6.0, "−6"), (-12.0, "−12"), (-24.0, "−24") })
+ {
+ double y = Math.Round(VolY(p, Math.Pow(10, db / 20))) + 0.5;
+ ctx.DrawLine(db == 0 ? strong : weak, new Point(p.Left, y), new Point(p.Right, y));
+ DrawText(ctx, label, NotaFonts.Mono, 8, NotaPalette.TextTertiary, new Point(p.Left - 6, y), vCenter: true, rightAlign: true);
+ }
+ }
+
+ private static void DrawCloud(DrawingContext ctx, Rect p, in Item it)
+ {
+ if (!it.Has || it.M.Silent || it.Muted) return;
+ if (it.Color is not SolidColorBrush tint) return;
+ double width = Math.Max(0.016 * p.Width, it.M.Width * p.Width); // ±width on the pan scale = width × plot width
+ double cx = PanX(p, it.M.Balance), cy = VolY(p, it.Volume);
+ double opacity = 0.10 + 0.32 * Math.Clamp((it.M.LevelDb + 60) / 54, 0, 1);
+ if (it.Dimmed) opacity *= 0.35;
+ byte alpha = (byte)(Math.Round(opacity * 255 / 8) * 8); // quantized: a small Wash cache
+ var outline = it.M.Correlation < PhaseAlarm ? NotaPalette.Danger : tint;
+ ctx.DrawEllipse(NotaPalette.Wash(tint, alpha), new Pen(outline, 1), new Point(cx, cy), width / 2, CloudH / 2);
+ }
+
+ private static void DrawHandle(DrawingContext ctx, Rect p, in Item it, bool selected)
+ {
+ var c = HandleAt(p, it);
+ bool dim = it.Muted || it.Dimmed;
+ if (selected) ctx.DrawEllipse(null, new Pen(NotaPalette.Accent, 2), c, 11, 11);
+ var ring = it.Has && !it.M.Silent && !dim && it.M.Correlation < PhaseAlarm ? NotaPalette.Danger : NotaPalette.BgSunken;
+ ctx.DrawEllipse(dim ? NotaPalette.SurfaceHover : it.Color, new Pen(ring, 2), c, HandleR - 1, HandleR - 1);
+ }
+
+ private void DrawLabels(DrawingContext ctx, Rect p, int sel)
+ {
+ // Greedy: from the top of the draw order down, skip a label that would overlap one placed.
+ var placed = _placedLabels;
+ placed.Clear();
+ for (int k = _order.Count - 1; k >= 0; k--)
+ {
+ var it = _items[_order[k]];
+ var brush = it.Muted || it.Dimmed ? NotaPalette.TextDisabled : it.Id == sel ? NotaPalette.TextPrimary : NotaPalette.TextSecondary;
+ var ft = Label(it.Id, it.Name, brush);
+ var c = HandleAt(p, it);
+ var r = new Rect(c.X + 13, c.Y - 7, Math.Min(LabelMaxW, ft.Width), ft.Height);
+ bool hit = false;
+ foreach (var q in placed) if (q.Intersects(r)) { hit = true; break; }
+ if (hit) continue;
+ placed.Add(r);
+ using (ctx.PushClip(r)) ctx.DrawText(ft, r.TopLeft);
+ }
+ }
+
+ private FormattedText Label(int id, string name, IBrush brush)
+ {
+ if (_labels.TryGetValue(id, out var l) && l.text == name && ReferenceEquals(l.brush, brush)) return l.ft;
+ var ft = new FormattedText(name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.SansMedium, 10, brush)
+ {
+ MaxTextWidth = LabelMaxW, MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis,
+ };
+ _labels[id] = (name, brush, ft);
+ return ft;
+ }
+
+ private void DrawBottom(DrawingContext ctx, Rect b)
+ {
+ double y0 = b.Height - BottomH, cy = y0 + BottomH / 2;
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, y0), new Point(b.Width, y0));
+ double x = 10;
+ x += DrawText(ctx, "MASTER CORR", NotaFonts.SansBold, 8, NotaPalette.TextTertiary, new Point(x, cy), vCenter: true, tracking: true) + 10;
+ x += DrawText(ctx, "−1", NotaFonts.Mono, 8, NotaPalette.TextTertiary, new Point(x, cy), vCenter: true) + 6;
+ var bar = new Rect(x, cy - 3, 180, 6);
+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), bar, 2, 2);
+ double mid = bar.Left + bar.Width / 2;
+ float corr = 1f;
+ foreach (var it in _items) if (it.Master && it.Has && !it.M.Silent) corr = it.M.Correlation;
+ double w = Math.Abs(corr) * bar.Width / 2;
+ var fill = corr < PhaseAlarm ? NotaPalette.Danger : NotaPalette.Success;
+ ctx.DrawRectangle(fill, null, new Rect(corr < 0 ? mid - w : mid, bar.Top + 1, w, bar.Height - 2));
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1), new Point(mid, bar.Top - 2), new Point(mid, bar.Bottom + 2));
+ x = bar.Right + 6;
+ x += DrawText(ctx, "+1", NotaFonts.Mono, 8, NotaPalette.TextTertiary, new Point(x, cy), vCenter: true) + 10;
+ DrawText(ctx, Signed(corr, 2), NotaFonts.Mono, 10, corr < PhaseAlarm ? NotaPalette.Danger : NotaPalette.TextSecondary, new Point(x, cy), vCenter: true);
+ DrawText(ctx, "Drag: pan + volume · Shift locks axis · double-click centres pan · ⌥ double-click 0 dB",
+ NotaFonts.Sans, 10, NotaPalette.TextTertiary, new Point(b.Width - 10, cy), vCenter: true, rightAlign: true);
+ }
+
+ private void DrawTooltip(DrawingContext ctx, Rect p, Rect b)
+ {
+ if (_dragId >= 0 || _hoverId < 0 || Environment.TickCount64 - _hoverSince < TooltipDelayMs) return;
+ int idx = _items.FindIndex(x => x.Id == _hoverId);
+ if (idx < 0) return;
+ var it = _items[idx];
+ var rows = new List<(string k, string v, IBrush ink)>
+ {
+ ("PAN", it.Master ? "—" : PanText(it.Pan), NotaPalette.TextPrimary),
+ ("VOLUME", DbText(it.Volume), NotaPalette.TextPrimary),
+ };
+ if (it.Has)
+ {
+ rows.Add(("BALANCE", Signed(it.M.Balance, 2), NotaPalette.TextSecondary));
+ rows.Add(("WIDTH", it.M.Width.ToString("0.00", NotaNum.Culture), NotaPalette.TextSecondary));
+ rows.Add(("CORRELATION", Signed(it.M.Correlation, 2), it.M.Correlation < PhaseAlarm ? NotaPalette.Danger : NotaPalette.TextSecondary));
+ rows.Add(("LEVEL", it.M.Silent ? "below −60 dBFS" : Signed(it.M.LevelDb, 1) + NotaNum.Thin + "dBFS", NotaPalette.TextSecondary));
+ }
+ var notes = new List<(string title, string body, IBrush ink)>();
+ if (it.Has && !it.M.Silent && !it.Muted && !it.Master && Math.Abs(it.M.Balance - it.Pan) > OffPanNote)
+ notes.Add(("Image is off the pan", $"The pan is at {PanText(it.Pan)}, but the signal measures {PanText(it.M.Balance)}. The source itself is unbalanced.", NotaPalette.Accent));
+ if (it.Muted) notes.Add(("Muted", "No cloud while the track is muted.", NotaPalette.TextSecondary));
+ else if (!it.Has || it.M.Silent) notes.Add(("Silent", "Below −60 dBFS, so the cloud is hidden.", NotaPalette.TextSecondary));
+
+ _tooltipRows.Clear();
+ foreach (var (k, v, _) in rows) _tooltipRows.Add((k, v));
+ _tooltipNotes.Clear();
+ foreach (var n in notes) _tooltipNotes.Add(n.title);
+
+ const double W = 188, Pad = 10, RowH = 13;
+ var bodies = new List<FormattedText>();
+ double h = 8 + 16 + rows.Count * RowH;
+ foreach (var n in notes)
+ {
+ var ft = new FormattedText(n.body, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.Sans, 9, NotaPalette.TextTertiary) { MaxTextWidth = W - 2 * Pad };
+ bodies.Add(ft);
+ h += 6 + 13 + ft.Height;
+ }
+ h += 8;
+ var c = HandleAt(p, it);
+ double x = c.X + 16 + W > b.Width ? c.X - 16 - W : c.X + 16;
+ double y = c.Y - 8 + h > b.Height ? c.Y + 8 - h : c.Y - 8;
+ var r = new Rect(x, Math.Max(0, y), W, h);
+ ctx.DrawRectangle(NotaPalette.TooltipBg, new Pen(NotaPalette.BorderStrong, 1), r, 4, 4);
+ double ty = r.Top + 8;
+ ctx.DrawEllipse(it.Color, null, new Point(r.Left + Pad + 4, ty + 7), 4, 4);
+ DrawText(ctx, it.Name, NotaFonts.SansSemiBold, 11, NotaPalette.TextPrimary, new Point(r.Left + Pad + 14, ty + 7), vCenter: true);
+ ty += 18;
+ foreach (var (k, v, ink) in rows)
+ {
+ DrawText(ctx, k, NotaFonts.SansBold, 7, NotaPalette.TextTertiary, new Point(r.Left + Pad, ty + 6), vCenter: true, tracking: true);
+ DrawText(ctx, v, NotaFonts.Mono, 9, ink, new Point(r.Left + Pad + 62, ty + 6), vCenter: true);
+ ty += RowH;
+ }
+ for (int i = 0; i < notes.Count; i++)
+ {
+ ty += 4;
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(r.Left + Pad, ty), new Point(r.Right - Pad, ty));
+ ty += 4;
+ DrawText(ctx, notes[i].title, NotaFonts.SansSemiBold, 9, notes[i].ink, new Point(r.Left + Pad, ty + 6), vCenter: true);
+ ty += 13;
+ ctx.DrawText(bodies[i], new Point(r.Left + Pad, ty));
+ ty += bodies[i].Height;
+ }
+ }
+
+ // Draws `text` anchored at `at`; returns its width.
+ private static double DrawText(DrawingContext ctx, string text, Typeface face, double size, IBrush brush, Point at,
+ bool vCenter = false, bool hCenter = false, bool rightAlign = false, bool tracking = false)
+ {
+ var ft = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, face, size, brush);
+ double x = hCenter ? at.X - ft.Width / 2 : rightAlign ? at.X - ft.Width : at.X;
+ double y = vCenter ? at.Y - ft.Height / 2 : at.Y;
+ ctx.DrawText(ft, new Point(x, y));
+ return ft.Width;
+ }
+
+ // ---- input --------------------------------------------------------------------------
+
+ private int HitTest(Point pos)
+ {
+ var p = Plot();
+ for (int k = _order.Count - 1; k >= 0; k--) // topmost first
+ {
+ var it = _items[_order[k]];
+ var c = HandleAt(p, it);
+ double dx = pos.X - c.X, dy = pos.Y - c.Y;
+ if (dx * dx + dy * dy <= (HandleR + HitSlop) * (HandleR + HitSlop)) return _order[k];
+ }
+ return -1;
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ int idx = HitTest(e.GetPosition(this));
+ if (idx < 0) return;
+ var it = _items[idx];
+ e.Handled = true;
+ if (it.Master) { SelectTrack?.Invoke(it.Id); return; } // fixed: select only
+ int id = it.Id;
+ if (e.ClickCount == 2) // reset: pan to C, ⌥ volume to 0 dB — one step each
+ {
+ if ((e.KeyModifiers & KeyModifiers.Alt) != 0) MixEdit.Step(_engine, () => _engine.SetTrackVolume(id, 1f), MixTarget.Volume(id));
+ else MixEdit.Step(_engine, () => _engine.SetTrackPan(id, 0f), MixTarget.Pan(id));
+ return;
+ }
+ _dragId = id;
+ _dragStart = e.GetPosition(this);
+ _dragPan0 = it.Pan;
+ _dragVol0 = it.Volume;
+ _dragMoved = false;
+ // One undo step for the drag; opened before the automation writes so a recorded lane
+ // and the values undo together (specs/009), closed after them.
+ _drag = new MixGesture(_engine, MixTarget.Volume(id), MixTarget.Pan(id));
+ _drag.Begin();
+ _engine.BeginAutomationWrite(id, AutomationTarget.Volume, -1, -1, "");
+ _engine.BeginAutomationWrite(id, AutomationTarget.Pan, -1, -1, "");
+ e.Pointer.Capture(this);
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ var pos = e.GetPosition(this);
+ if (_dragId < 0)
+ {
+ int idx = HitTest(pos);
+ int id = idx >= 0 ? _items[idx].Id : -1;
+ if (id != _hoverId) { _hoverId = id; _hoverSince = Environment.TickCount64; }
+ Cursor = idx < 0 ? Cursor.Default : new Cursor(_items[idx].Master ? StandardCursorType.Hand : StandardCursorType.SizeAll);
+ return;
+ }
+ var p = Plot();
+ double dx = pos.X - _dragStart.X, dy = pos.Y - _dragStart.Y;
+ if (!_dragMoved && Math.Abs(dx) + Math.Abs(dy) < 3) return;
+ _dragMoved = true;
+ if ((e.KeyModifiers & KeyModifiers.Shift) != 0) // lock to the axis with the larger movement
+ {
+ if (Math.Abs(dx) * 2 / p.Width > Math.Abs(dy) / p.Height) dy = 0; else dx = 0;
+ }
+ float pan = (float)Math.Clamp(_dragPan0 + dx * 2 / p.Width, -1, 1);
+ float vol = (float)FaderScale.Gain(FaderScale.Frac(_dragVol0) - dy / p.Height);
+ _engine.SetTrackPan(_dragId, pan);
+ _engine.SetTrackVolume(_dragId, vol);
+ Pull();
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (_dragId < 0) return;
+ int id = _dragId;
+ _engine.EndAutomationWrite(id, AutomationTarget.Volume, -1, -1, "");
+ _engine.EndAutomationWrite(id, AutomationTarget.Pan, -1, -1, "");
+ _drag?.End();
+ _drag = null;
+ _dragId = -1;
+ e.Pointer.Capture(null);
+ if (!_dragMoved) SelectTrack?.Invoke(id); // a click without a move selects
+ }
+
+ protected override void OnPointerExited(PointerEventArgs e)
+ {
+ base.OnPointerExited(e);
+ _hoverId = -1;
+ }
+
+ // ---- formatting ---------------------------------------------------------------------
+
+ private static string PanText(double pan)
+ {
+ int n = (int)Math.Round(pan * 100);
+ return n == 0 ? "C" : (n < 0 ? "L" : "R") + Math.Abs(n).ToString(NotaNum.Culture);
+ }
+
+ private static string DbText(double gain)
+ => gain <= 1e-5 ? "−∞" : Signed(20 * Math.Log10(gain), 1) + " dB";
+
+ private static string Signed(double v, int decimals)
+ {
+ double r = Math.Round(v, decimals);
+ string s = Math.Abs(r).ToString("F" + decimals, NotaNum.Culture);
+ return r < 0 ? "−" + s : r > 0 ? "+" + s : s;
+ }
+}
diff --git a/src/managed/Nota.Application/Editing/MixEdit.cs b/src/managed/Nota.Application/Editing/MixEdit.cs
new file mode 100644
index 00000000..da268957
--- /dev/null
+++ b/src/managed/Nota.Application/Editing/MixEdit.cs
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Volume / pan / master-volume edits that land in the undo history (specs/009-mix-param-undo).
+// A gesture is opened on the engine, the value is set through the plain setter, and the
+// gesture is closed — one undo step for whatever changed. Used for one-off edits that have no
+// press/release of their own: an MCP call, a reset, a typed value. Internal callers (load,
+// freeze, the template, automation) keep using the plain setters and never make steps.
+
+using System;
+
+namespace Nota.Application.Editing;
+
+public static class MixEdit
+{
+ /// <summary>Runs <paramref name="set"/> as one undo step over <paramref name="targets"/>.</summary>
+ public static void Step(IAudioEngine engine, Action set, params MixTarget[] targets)
+ {
+ int handle = engine.BeginMixGesture(targets);
+ try { set(); }
+ finally { engine.EndMixGesture(handle); }
+ }
+}
+
+/// <summary>A gesture held by one control or source: <see cref="Begin"/> on press,
+/// <see cref="End"/> on release, and <see cref="Change"/> for every value — inside an open
+/// gesture it just sets, outside one (double-click reset, typed value) it is a one-off step.</summary>
+public sealed class MixGesture(IAudioEngine engine, Func<MixTarget[]> targets)
+{
+ private int _handle;
+
+ public MixGesture(IAudioEngine engine, params MixTarget[] targets) : this(engine, () => targets) { }
+
+ public bool IsOpen => _handle != 0;
+
+ public void Begin() { if (_handle == 0) _handle = engine.BeginMixGesture(targets()); }
+
+ public void End()
+ {
+ if (_handle == 0) return;
+ engine.EndMixGesture(_handle);
+ _handle = 0;
+ }
+
+ public void Change(Action set)
+ {
+ if (_handle != 0) set();
+ else MixEdit.Step(engine, set, targets());
+ }
+
+ /// <summary><see cref="Change(Action)"/> without a closure per value: pass the value and a
+ /// setter delegate made once — a fader drag then allocates nothing per move.</summary>
+ public void Change<T>(T value, Action<T> set)
+ {
+ if (_handle != 0) { set(value); return; }
+ int handle = engine.BeginMixGesture(targets());
+ try { set(value); }
+ finally { engine.EndMixGesture(handle); }
+ }
+}
+
+/// <summary>A stream of values with no press/release (a MIDI controller knob): the first
+/// <see cref="Touch"/> opens a gesture and <see cref="Poll"/> ends it once no touch came for
+/// <c>pause</c> — one undo step per movement. Time is passed in (milliseconds, any monotonic
+/// clock), so the caller's tick drives it and a test can too.</summary>
+public sealed class MixMovement(IAudioEngine engine, MixTarget target, TimeSpan pause)
+{
+ private readonly MixGesture _gesture = new(engine, target);
+ private long _lastMs;
+
+ public bool IsOpen => _gesture.IsOpen;
+
+ public void Touch(Action set, long nowMs)
+ {
+ _gesture.Begin();
+ set();
+ _lastMs = nowMs;
+ }
+
+ public void Poll(long nowMs)
+ {
+ if (_gesture.IsOpen && nowMs - _lastMs >= (long)pause.TotalMilliseconds) _gesture.End();
+ }
+
+ public void End() => _gesture.End();
+}
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index a3ecc1d4..ee10611c 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -239,6 +239,38 @@ public struct NotaMeter
/// <summary>What a parameter-automation lane drives (M9). Matches native AutomationTarget.</summary>
public enum AutomationTarget { Volume = 0, Pan = 1, DeviceParam = 2, PluginParam = 3, MidiDeviceParam = 4 }
+/// <summary>Project pan law (specs/006). Matches NOTA_PAN_LAW_*: Balance drops the far
+/// channel as a track pans, Stereo folds it into the near side.</summary>
+public enum PanLaw { Balance = 0, Stereo = 1 }
+
+/// <summary>One Stereo Map row (specs/008), laid out like native NotaStereoMeasure: what a
+/// track / return / the master sends to the master, averaged over ~300 ms. Balance is on the
+/// pan scale (a mono source panned to p reads p); width = 1 − correlation, clamped 0..1.</summary>
+[StructLayout(LayoutKind.Sequential)]
+public struct StereoMeasure
+{
+ public int TrackId;
+ public float LevelDb;
+ public float Balance;
+ public float Width;
+ public float Correlation;
+ /// <summary>Below −60 dBFS: no cloud is drawn.</summary>
+ public readonly bool Silent => LevelDb < -60f;
+}
+
+/// <summary>What a mix gesture targets (specs/009). Matches NOTA_MIX_*.</summary>
+public enum MixKind { TrackVolume = 0, TrackPan = 1, MasterVolume = 2 }
+
+/// <summary>One parameter a mix gesture records for undo; laid out like native NotaMixTarget.
+/// <see cref="TrackId"/> is ignored for the master volume.</summary>
+[StructLayout(LayoutKind.Sequential)]
+public readonly record struct MixTarget(MixKind Kind, int TrackId)
+{
+ public static MixTarget Volume(int trackId) => new(MixKind.TrackVolume, trackId);
+ public static MixTarget Pan(int trackId) => new(MixKind.TrackPan, trackId);
+ public static MixTarget Master => new(MixKind.MasterVolume, -1);
+}
+
/// <summary>MIDI clip envelope target (M9 follow-up). Velocity scales note velocities;
/// Volume scales the instrument output during the clip.</summary>
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 63edf031..8776d462 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -826,6 +826,27 @@ public interface IAudioEngine : IDisposable
/// <summary>Forget the undo/redo history; the current state becomes the baseline.</summary>
void ClearUndoHistory();
+ // --- Pan law (specs/006) ---------------------------------------------
+ /// <summary>Project pan law (graph-level, undoable). See nota_engine_set_pan_law.</summary>
+ PanLaw PanLaw { get; }
+ /// <summary>Sets the project pan law; <paramref name="checkpoint"/> = false adds no undo
+ /// step (project load, the new-project baseline). No-op if unchanged.</summary>
+ void SetPanLaw(PanLaw law, bool checkpoint = true);
+
+ // --- Mix undo (specs/009) --------------------------------------------
+ /// <summary>Starts a gesture on volume / pan / master volume: their values now are what
+ /// undo returns to. Returns a handle (0 = no valid target).</summary>
+ int BeginMixGesture(params MixTarget[] targets);
+ /// <summary>Ends the gesture: one undo step for whatever it changed (none → no step).</summary>
+ void EndMixGesture(int handle);
+ /// <summary>The engine's master volume (linear) — follows undo/redo.</summary>
+ float MasterVolume { get; }
+
+ // --- Stereo Map (specs/008) ------------------------------------------
+ /// <summary>Fills <paramref name="buffer"/> with one row per non-group track (track order)
+ /// and the master last; returns the total row count (grow the buffer if larger).</summary>
+ int GetStereoMeasures(StereoMeasure[] buffer);
+
// --- Project load (M7-6) -----------------------------------------------
void Reset();
int TrackInstrumentKind(int trackId);
diff --git a/src/managed/Nota.Application/Ports/IProjectStore.cs b/src/managed/Nota.Application/Ports/IProjectStore.cs
index 8cfa0c33..1857d95d 100644
--- a/src/managed/Nota.Application/Ports/IProjectStore.cs
+++ b/src/managed/Nota.Application/Ports/IProjectStore.cs
@@ -5,9 +5,10 @@ namespace Nota.Application;
/// <summary>Transport values the App owns, passed across the persistence boundary
/// so the on-disk model stays UI-framework-free. <paramref name="Key"/> is the project key
-/// as a <see cref="Samples.MusicalKey.Code"/> (−1 = none set).</summary>
+/// as a <see cref="Samples.MusicalKey.Code"/> (−1 = none set). <paramref name="PanLawLegacy"/> marks a
+/// project made before the pan law (specs/006); it only drives the Mixer's OLDER PROJECT badge.</summary>
public readonly record struct TransportState(double Bpm, double MasterVolume, bool MetronomeOn, bool LoopOn,
- int TimeSigNumerator = 4, int TimeSigDenominator = 4, int Key = -1);
+ int TimeSigNumerator = 4, int TimeSigDenominator = 4, int Key = -1, bool PanLawLegacy = false);
/// <summary>Outcome of loading a project: the transport to restore + any items that
/// were downgraded/skipped (referential-integrity warnings).</summary>
diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.cs
index e8207f34..e2235004 100644
--- a/src/managed/Nota.Application/Settings.cs
+++ b/src/managed/Nota.Application/Settings.cs
@@ -34,6 +34,9 @@ public sealed class Settings
/// <summary>Show the welcome screen (recent projects launcher) on startup. On by default;
/// toggled from the welcome screen's "Show on startup" checkbox.</summary>
public bool ShowWelcomeOnStartup { get; set; } = true;
+ /// <summary>The Mixer window's view: "strips" or "map" (the Stereo Map, specs/008).
+ /// A per-user preference, remembered between openings.</summary>
+ public string MixerView { get; set; } = "strips";
/// <summary>Record a project version on every save (the History tab). On by default.</summary>
public bool KeepVersionHistory { get; set; } = true;
/// <summary>Bars of metronome count-in before Play / Record from stop (0 = off). Set from
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs
index 220e8781..15d6acbd 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs
@@ -12,6 +12,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_pluginhost_open_test_window")]
internal static partial NotaResult PluginHostOpenTestWindow();
+ [LibraryImport(Lib, EntryPoint = "nota_pluginhost_pump")]
+ internal static partial int PluginHostPump();
+
[LibraryImport(Lib, EntryPoint = "nota_pluginhost_scan", StringMarshalling = StringMarshalling.Utf8)]
internal static partial int PluginHostScan(string workerPath);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index 98a4859c..fe89a5d3 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -180,6 +180,27 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_clear_undo_history")]
internal static partial void ClearUndoHistory(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_set_pan_law")]
+ internal static partial NotaResult SetPanLaw(IntPtr engine, int law, int checkpoint);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_pan_law")]
+ internal static partial int PanLaw(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_mix_gesture_begin")]
+ internal static partial int MixGestureBegin(IntPtr engine, [In] MixTarget[] targets, int count);
+
+ [LibraryImport(Lib, EntryPoint = "nota_mix_gesture_end")]
+ internal static partial void MixGestureEnd(IntPtr engine, int handle);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_master_volume")]
+ internal static partial float MasterVolume(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_stereo_measures")]
+ internal static partial int StereoMeasures(IntPtr engine, [Out] StereoMeasure[] rows, int cap);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_mix_undo_selftest")]
+ internal static partial int MixUndoSelfTest(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_reset")]
internal static partial void Reset(IntPtr engine);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs
index d99bf1df..7482f1cb 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs
@@ -15,6 +15,14 @@ public sealed partial class NotaEngine
/// </summary>
public static void OpenPluginHostTestWindow() => Check(NativeMethods.PluginHostOpenTestWindow());
+ /// <summary>
+ /// Services JUCE's message loop (plugin editor windows, hosted plugins' timers).
+ /// Needed on Linux only, where JUCE's loop isn't shared with Avalonia's; a no-op
+ /// elsewhere. Non-blocking; call from the UI thread every ~10 ms. Returns the
+ /// number of message batches dispatched.
+ /// </summary>
+ public static int PumpPluginHost() => NativeMethods.PluginHostPump();
+
// --- Plugin scanning & catalog (M3-1) ----------------------------------
/// <summary>
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index d133c598..5426ef04 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -158,6 +158,21 @@ public sealed partial class NotaEngine : IAudioEngine
public void EndUndoGroup() { ThrowIfDisposed(); NativeMethods.UndoGroupEnd(_handle); }
public void ClearUndoHistory() { ThrowIfDisposed(); NativeMethods.ClearUndoHistory(_handle); }
+ // --- Pan law (specs/006) -------------------------------------------------
+ public PanLaw PanLaw { get { ThrowIfDisposed(); return (PanLaw)NativeMethods.PanLaw(_handle); } }
+ public void SetPanLaw(PanLaw law, bool checkpoint = true)
+ { ThrowIfDisposed(); Check(NativeMethods.SetPanLaw(_handle, (int)law, checkpoint ? 1 : 0)); }
+
+ // --- Mix undo (specs/009) --------------------------------------------------
+ public int BeginMixGesture(params MixTarget[] targets)
+ { ThrowIfDisposed(); return targets.Length == 0 ? 0 : NativeMethods.MixGestureBegin(_handle, targets, targets.Length); }
+ public void EndMixGesture(int handle) { ThrowIfDisposed(); if (handle > 0) NativeMethods.MixGestureEnd(_handle, handle); }
+ public float MasterVolume { get { ThrowIfDisposed(); return NativeMethods.MasterVolume(_handle); } }
+ public int GetStereoMeasures(StereoMeasure[] buffer)
+ { ThrowIfDisposed(); return NativeMethods.StereoMeasures(_handle, buffer, buffer.Length); }
+ /// <summary>Device-free: undo/redo pass over a step whose track is gone. Clears the history.</summary>
+ public bool MixUndoSelfTest() { ThrowIfDisposed(); return NativeMethods.MixUndoSelfTest(_handle) != 0; }
+
// --- Project load (M7-6) -----------------------------------------------
/// <summary>Clears the session to an empty project (used by File → New / Open).</summary>
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index e9019535..e7e9a6bb 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -83,6 +83,14 @@ public static class ProjectMigrations
// v19 -> v20: audio clips gain an ADSR amplitude shape (AudioClipDto.Adsr). Absent in
// v19 documents; null = identity (full length, full level) matches old behaviour — no-op.
new Migration(19, _ => { }),
+ // v20 -> v21: projects gain a pan law (specs/006). Every earlier project mixed with the
+ // balance law, so the step writes mixer = { panLaw: "balance", panLawLegacy: true } when
+ // `mixer` is absent (keeps an existing object untouched).
+ new Migration(20, root =>
+ {
+ if (root["mixer"] is null)
+ root["mixer"] = new JsonObject { ["panLaw"] = "balance", ["panLawLegacy"] = true };
+ }),
};
/// <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 176526d4..af1577fb 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -32,6 +32,9 @@ public sealed class ProjectDocument
public List<AutomationPointDto> MasterVolumeAutomation { get; set; } = new();
/// <summary>Master effect chain (devices on the master bus) + its name/colour.</summary>
public MasterDto Master { get; set; } = new();
+ /// <summary>Mixer-wide settings: the project pan law (format v21). Null = a pre-v21 project
+ /// (migration fills it in) = Balance + older project.</summary>
+ public MixerDto? Mixer { get; set; }
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
@@ -60,6 +63,17 @@ public sealed class MasterDto
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
+/// <summary>Mixer-wide settings (specs/006). <see cref="PanLaw"/> is "stereo" or "balance";
+/// <see cref="PanLawLegacy"/> marks a project made before the pan law (only drives the
+/// Mixer's OLDER PROJECT badge, never the sound).</summary>
+public sealed class MixerDto
+{
+ public string PanLaw { get; set; } = "balance";
+ public bool PanLawLegacy { get; set; }
+
+ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
+}
+
public sealed class TransportDto
{
public double Bpm { get; set; } = 120.0;
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 8ab15bfa..571f7d16 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -30,7 +30,7 @@ public sealed class ProjectService
/// per-segment curvature (automationPoint.curve). v5 adds audio-clip pitch + warp
/// (pitchSemitones / warpEnabled / warpMode / warpBeats). v6 adds warp markers.</summary>
/// v18 (Phase 3) adds CV modulation: per-track LFO modulators + CV links to device params.
- public const int CurrentFormatVersion = 20;
+ public const int CurrentFormatVersion = 21;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -68,6 +68,11 @@ public sealed class ProjectService
TimeSigDenominator = transport.TimeSigDenominator,
Key = Nota.Application.Samples.MusicalKey.FromCode(transport.Key)?.Short,
},
+ Mixer = new MixerDto
+ {
+ PanLaw = engine.PanLaw == PanLaw.Stereo ? "stereo" : "balance",
+ PanLawLegacy = transport.PanLawLegacy,
+ },
};
int trackCount = engine.TrackCount;
@@ -435,6 +440,10 @@ public sealed class ProjectService
var warnings = new List<string>();
engine.Reset();
+ // 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);
+
// Restore the scene count before tracks so their session slots size to it (the doc may
// hold more/fewer scenes than the fresh default after add/remove-scene edits).
while (engine.SceneCount < doc.SceneCount) engine.AddScene();
@@ -874,6 +883,18 @@ public sealed class ProjectService
// --- helpers -----------------------------------------------------------
+ private static PanLaw ParsePanLaw(string? value, List<string> warnings)
+ {
+ switch (value)
+ {
+ case null or "balance": return PanLaw.Balance;
+ case "stereo": return PanLaw.Stereo;
+ default:
+ warnings.Add($"Unknown pan law '{value}' — using Balance.");
+ return PanLaw.Balance;
+ }
+ }
+
// Records `sampleId` under a bundle-relative path named by its content hash
// (identical audio shares one file) and returns that path, or null if the sample
// is missing from the live graph.
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs
index c74925d5..024064f9 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs
@@ -25,7 +25,8 @@ public sealed class ProjectStore : IProjectStore
doc.Transport.Bpm, doc.Transport.MasterVolume,
doc.Transport.MetronomeOn, doc.Transport.LoopOn,
doc.Transport.TimeSigNumerator, doc.Transport.TimeSigDenominator,
- Nota.Application.Samples.MusicalKey.Parse(doc.Transport.Key)?.Code ?? -1);
+ Nota.Application.Samples.MusicalKey.Parse(doc.Transport.Key)?.Code ?? -1,
+ PanLawLegacy: doc.Mixer?.PanLawLegacy ?? true);
return new ProjectLoadResult(transport, warnings) { MissingPlugins = MissingPlugins(doc) };
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectTemplate.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectTemplate.cs
index 0cb4e4da..79d22c9d 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectTemplate.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectTemplate.cs
@@ -6,6 +6,7 @@
// "Reverb" and "Delay" — so a user can play and send at once. Built from the same
// structural edits as adding tracks by hand, then made the undo baseline so the
// template is the starting point rather than a stack of undoable edits.
+// New projects use the Stereo pan law (specs/006-stereo-pan-law); older projects keep Balance.
namespace Nota.Infrastructure;
@@ -28,6 +29,7 @@ public static class ProjectTemplate
AddReturn(engine, "Reverb", ReverbKind, ReverbWetOnly);
AddReturn(engine, "Delay", DelayKind, DelayWetOnly);
+ engine.SetPanLaw(PanLaw.Stereo, checkpoint: false);
engine.ClearUndoHistory();
return inst;
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs b/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs
index 5ba818f4..a0a70621 100644
--- a/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs
@@ -82,6 +82,9 @@ internal static class VersionDiff
if (!JsonNode.DeepEquals(before?["master"]?["devices"], after?["master"]?["devices"])) sound.Add("Master");
if (!Same(before?["transport"]?["masterVolume"], after?["transport"]?["masterVolume"])) mix.Add("Master");
if (!JsonNode.DeepEquals(before?["masterVolumeAutomation"], after?["masterVolumeAutomation"])) edited.Add("Master");
+ // The project pan law (specs/006); a version from before v21 has none = Balance.
+ static string Law(JsonNode? doc) => (string?)doc?["mixer"]?["panLaw"] ?? "balance";
+ if (Law(before) != Law(after)) sound.Add("Pan law");
double? bpmBefore = Num(before?["transport"]?["bpm"]), bpmAfter = Num(after?["transport"]?["bpm"]);
bool tempo = bpmBefore is { } b && bpmAfter is { } a && Math.Abs(a - b) > 1e-6;
diff --git a/src/managed/Nota.Mcp/Tools/TrackTools.cs b/src/managed/Nota.Mcp/Tools/TrackTools.cs
index 42009e6f..359488c0 100644
--- a/src/managed/Nota.Mcp/Tools/TrackTools.cs
+++ b/src/managed/Nota.Mcp/Tools/TrackTools.cs
@@ -6,6 +6,7 @@
using System.ComponentModel;
using ModelContextProtocol.Server;
using Nota.Application;
+using Nota.Application.Editing;
namespace Nota.Mcp.Tools;
@@ -32,10 +33,12 @@ public sealed class TrackTools(IAudioEngine engine, IEngineDispatch dispatch, IA
public Task SetTrackColor(int trackId, int colorIndex) => Mutate(() => E.SetTrackColorIndex(trackId, colorIndex));
[McpServerTool(Name = "set_track_volume"), Description("Set a track's fader level (0..1 linear).")]
- public Task SetTrackVolume(int trackId, [Description("Linear gain 0..1")] float volume) => Mutate(() => E.SetTrackVolume(trackId, Math.Clamp(volume, 0f, 1f)));
+ public Task SetTrackVolume(int trackId, [Description("Linear gain 0..1")] float volume)
+ => Mutate(() => MixEdit.Step(E, () => E.SetTrackVolume(trackId, Math.Clamp(volume, 0f, 1f)), MixTarget.Volume(trackId))); // one undo step
[McpServerTool(Name = "set_track_pan"), Description("Set a track's pan (-1 left .. 0 centre .. +1 right).")]
- public Task SetTrackPan(int trackId, [Description("-1..1")] float pan) => Mutate(() => E.SetTrackPan(trackId, Math.Clamp(pan, -1f, 1f)));
+ public Task SetTrackPan(int trackId, [Description("-1..1")] float pan)
+ => Mutate(() => MixEdit.Step(E, () => E.SetTrackPan(trackId, Math.Clamp(pan, -1f, 1f)), MixTarget.Pan(trackId))); // one undo step
[McpServerTool(Name = "set_track_mute"), Description("Mute or unmute a track.")]
public Task SetTrackMute(int trackId, bool mute) => Mutate(() => E.SetTrackMute(trackId, mute));
diff --git a/src/managed/Nota.Remote/RemoteHub.Apply.cs b/src/managed/Nota.Remote/RemoteHub.Apply.cs
index 226e0e0b..b538561e 100644
--- a/src/managed/Nota.Remote/RemoteHub.Apply.cs
+++ b/src/managed/Nota.Remote/RemoteHub.Apply.cs
@@ -81,22 +81,28 @@ public sealed partial class RemoteHub
// ---- mixer ----------------------------------------------------------
case "vol":
if (!TrackExists(cmd.Id)) break;
- _engine.BeginAutomationWrite(cmd.Id, AutomationTarget.Volume, -1, -1, "", latch: true);
- _engine.SetTrackVolume(cmd.Id, (float)Math.Clamp(cmd.V, 0, VolumeMax));
+ MixTouch(c, MixTarget.Volume(cmd.Id), cmd.Phase, () => // opened before the automation write
+ {
+ _engine.BeginAutomationWrite(cmd.Id, AutomationTarget.Volume, -1, -1, "", latch: true);
+ _engine.SetTrackVolume(cmd.Id, (float)Math.Clamp(cmd.V, 0, VolumeMax));
+ });
HoldFader(c, cmd.Id, cmd.Phase);
if (cmd.Phase == 2) host.Refresh();
break;
case "pan":
if (!TrackExists(cmd.Id)) break;
- _engine.BeginAutomationWrite(cmd.Id, AutomationTarget.Pan, -1, -1, "", latch: true);
- _engine.SetTrackPan(cmd.Id, (float)Math.Clamp(cmd.V, -1, 1));
+ MixTouch(c, MixTarget.Pan(cmd.Id), cmd.Phase, () =>
+ {
+ _engine.BeginAutomationWrite(cmd.Id, AutomationTarget.Pan, -1, -1, "", latch: true);
+ _engine.SetTrackPan(cmd.Id, (float)Math.Clamp(cmd.V, -1, 1));
+ });
if (cmd.Phase == 2) host.Refresh();
break;
case "mute": if (TrackExists(cmd.Id)) { _engine.SetTrackMute(cmd.Id, cmd.On); host.Refresh(); } break;
case "solo": if (TrackExists(cmd.Id)) { _engine.SetTrackSolo(cmd.Id, cmd.On); host.Refresh(); } break;
case "arm": if (TrackExists(cmd.Id)) { _engine.SetTrackArmed(cmd.Id, cmd.On); host.Refresh(); } break;
case "mvol":
- host.MasterVolume = Math.Clamp(cmd.V, 0, VolumeMax);
+ MixTouch(c, MixTarget.Master, cmd.Phase, () => host.MasterVolume = Math.Clamp(cmd.V, 0, VolumeMax));
HoldFader(c, MasterFaderId, cmd.Phase);
break;
@@ -134,8 +140,34 @@ public sealed partial class RemoteHub
_heldFaders[faderId] = (c.ConnectionId, ShortName(c.Name), DateTime.UtcNow.Add(FaderHold).Ticks);
}
+ // Undo (specs/009): one step per touch on a volume / pan / master fader — opened by the
+ // touch's first command, closed by its phase-2 command, by the phone going away, or after
+ // FaderHold without a command (a lost finger-up never leaves a gesture open).
+ private readonly Dictionary<(int Conn, MixTarget Target), (int Handle, long Until)> _mixUndo = new();
+
+ private void MixTouch(RemoteClient c, MixTarget target, int phase, Action set)
+ {
+ var key = (c.ConnectionId, target);
+ int handle = _mixUndo.TryGetValue(key, out var open) ? open.Handle : _engine.BeginMixGesture(target);
+ set();
+ if (phase == 2) { _engine.EndMixGesture(handle); _mixUndo.Remove(key); }
+ else _mixUndo[key] = (handle, DateTime.UtcNow.Add(FaderHold).Ticks);
+ }
+
+ private void ExpireMixUndo()
+ {
+ if (_mixUndo.Count == 0) return;
+ long now = DateTime.UtcNow.Ticks;
+ foreach (var kv in _mixUndo.Where(kv => kv.Value.Until < now || !_clients.ContainsKey(kv.Key.Conn)).ToList())
+ {
+ _engine.EndMixGesture(kv.Value.Handle);
+ _mixUndo.Remove(kv.Key);
+ }
+ }
+
private void ExpireHeldFaders()
{
+ ExpireMixUndo();
if (_heldFaders.Count == 0) return;
long now = DateTime.UtcNow.Ticks;
foreach (var k in _heldFaders.Where(kv => kv.Value.Until < now || !_clients.ContainsKey(kv.Value.Conn)).Select(kv => kv.Key).ToList())
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index a216021d..8d408b72 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -790,9 +790,10 @@ NOTA_API NotaResult nota_engine_poll(NotaEngine* engine);
/* ---- Undo / redo (M6-6) -------------------------------------------------- */
/* Undo/redo of structural edits (tracks, clips, notes, device chains, session
- * slots). Restores a retained Graph snapshot. Returns NOTA_OK if a step was
- * applied, NOTA_ERR_UNKNOWN if there was nothing to undo/redo. Atomic params
- * (volume/pan/mute/bypass/device params) and transport are not covered. */
+ * slots) — restores a retained Graph snapshot — and of volume / pan / master volume
+ * steps made through mix gestures (009). Returns NOTA_OK if a step was applied,
+ * NOTA_ERR_UNKNOWN if there was nothing to undo/redo. Mute, solo, sends, bypass,
+ * device params and the transport are not covered. */
NOTA_API NotaResult nota_engine_undo(NotaEngine* engine);
NOTA_API NotaResult nota_engine_redo(NotaEngine* engine);
NOTA_API int32_t nota_engine_can_undo(const NotaEngine* engine);
@@ -806,6 +807,69 @@ NOTA_API void nota_engine_undo_group_end(NotaEngine* engine);
* closed. Message thread only. No-op for a null engine. */
NOTA_API void nota_engine_clear_undo_history(NotaEngine* engine);
+/* ---- Mix undo (009) ------------------------------------------------------ */
+/* Volume / pan / master volume changes become undo steps through gestures. A gesture
+ * records its targets' values at begin and, at end, pushes ONE undo step with the values
+ * that changed (none changed → no step). If a structural checkpoint was pushed during the
+ * gesture (automation recording) the step merges into it. The plain setters never record:
+ * automation playback, loads and internal edits make no steps. Message thread only. */
+#define NOTA_MIX_TRACK_VOLUME 0
+#define NOTA_MIX_TRACK_PAN 1
+#define NOTA_MIX_MASTER_VOLUME 2
+
+typedef struct NotaMixTarget {
+ int32_t kind; /* NOTA_MIX_* */
+ int32_t track_id; /* ignored for NOTA_MIX_MASTER_VOLUME */
+} NotaMixTarget;
+
+/* Returns a handle > 0, or 0 if no target is valid. */
+NOTA_API int32_t nota_mix_gesture_begin(NotaEngine* engine, const NotaMixTarget* targets, int32_t count);
+/* Ends the gesture; unknown / already-ended handles are ignored. */
+NOTA_API void nota_mix_gesture_end(NotaEngine* engine, int32_t handle);
+
+/* ---- Stereo measurements (008) ------------------------------------------- */
+/* What each track, return and the master sends to the master, post-fader and post-pan,
+ * averaged over ~300 ms: level, where it sits (balance on the pan scale: a mono source
+ * panned to p measures p), how wide it is (1 - correlation, clamped 0..1) and the
+ * correlation. Groups are not measured. Message thread; lock-free reads. */
+typedef struct NotaStereoMeasure {
+ int32_t track_id; /* a track / return id, or nota_engine_master_track_id() */
+ float level_db; /* RMS of the pair, dBFS; -200 for silence */
+ float balance; /* -1 (left) .. +1 (right) */
+ float width; /* 0 (mono) .. 1 (unrelated or anti-phase) */
+ float correlation; /* -1 .. +1; 0 when either side is silent */
+} NotaStereoMeasure;
+
+/* Fills up to cap rows (tracks and returns in track order, the master last) and returns
+ * the number available (call again with a bigger buffer if it exceeds cap). */
+NOTA_API int32_t nota_engine_stereo_measures(const NotaEngine* engine, NotaStereoMeasure* out, int32_t cap);
+
+/* Device-free: a mix step whose track no longer exists is passed over by undo/redo.
+ * Clears the history. Returns 1 on success. */
+NOTA_API int32_t nota_engine_mix_undo_selftest(NotaEngine* engine);
+
+/* The master volume (linear), as set by nota_engine_set_master_volume or undo/redo. */
+NOTA_API float nota_engine_master_volume(const NotaEngine* engine);
+
+/* ---- Pan law (006) ------------------------------------------------------- */
+/* How a track's or return's pan is applied to a stereo signal. Project-wide, part of
+ * the graph snapshot (undo/redo restore it). BALANCE (the default, and every project
+ * before format v21): the opposite channel is attenuated. STEREO: the whole image
+ * moves — the far channel is folded into the near side, a mono fold at full pan.
+ * Identical for mono material and at centre. Groups, clip pan envelopes and rack-chain
+ * pans are not affected. */
+#define NOTA_PAN_LAW_BALANCE 0
+#define NOTA_PAN_LAW_STEREO 1
+
+/* Set the law. checkpoint = 1: one undo step (user edit); 0: no undo entry (project
+ * load / new-project baseline). A change while playing crossfades over 10 ms.
+ * NOTA_ERR_INVALID_ARG for an unknown law; NOTA_OK (no-op, no undo step) if unchanged.
+ * Message thread only. */
+NOTA_API NotaResult nota_engine_set_pan_law(NotaEngine* engine, int32_t law, int32_t checkpoint);
+
+/* Current law (authoring graph). NOTA_PAN_LAW_BALANCE for a null engine. */
+NOTA_API int32_t nota_engine_pan_law(const NotaEngine* engine);
+
/* ---- Project load (M7-6) ------------------------------------------------- */
/* Clear the session to an empty project: stop transport, drop all tracks,
* reset the track-id counter and undo/redo history. Message thread only. */
@@ -1623,6 +1687,14 @@ NOTA_API void nota_encoder_discard(NotaEncoder* enc);
* is idempotent; repeated calls just re-show the window. Temporary entry point. */
NOTA_API NotaResult nota_pluginhost_open_test_window(void);
+/* Services JUCE's message loop: plugin editor windows (X11 events, repaints) and
+ * hosted plugins' timers / async work registered through the host IRunLoop. Only
+ * needed on Linux, where JUCE's loop is not shared with the app's run loop; a
+ * no-op (returns 0) on macOS / Windows, before any plugin is instantiated, and off
+ * the message (UI) thread. Non-blocking; call often (~10 ms) from the UI thread.
+ * Returns the number of message batches dispatched. */
+NOTA_API int32_t nota_pluginhost_pump(void);
+
/* ---- Plugin scanning & catalog (M3-1, FR-33/NFR-5) ----------------------- */
/* Scans installed plugins out-of-process, AudioUnit first then VST3. Each
* candidate is probed in a separate `worker_path` child process with a timeout,
diff --git a/src/native/nota.engine/pluginhost/PluginHost.cpp b/src/native/nota.engine/pluginhost/PluginHost.cpp
index 53764b3d..7b614dc3 100644
--- a/src/native/nota.engine/pluginhost/PluginHost.cpp
+++ b/src/native/nota.engine/pluginhost/PluginHost.cpp
@@ -74,6 +74,34 @@ extern "C" NOTA_API NotaResult nota_pluginhost_open_test_window(void) {
return NOTA_OK;
}
+// ---- JUCE message pump (Linux) ---------------------------------------------
+// The spike premise above holds on macOS (shared CFRunLoop) and Windows (JUCE's
+// message HWND is serviced by Avalonia's Win32 loop), but on Linux JUCE runs its
+// own poll()-based loop over the X11 display fd, its message pipe and any fds a
+// hosted VST3 registers through the host IRunLoop. Nothing services that loop
+// unless we do: editor windows stay black and unclosable, and plugins — which
+// hand their message thread to the host's IRunLoop on creation — never run their
+// timers/async work and stay silent. The app calls this from a UI-thread timer.
+
+#if JUCE_LINUX || JUCE_BSD
+namespace juce::detail { bool dispatchNextMessageOnSystemQueue(bool returnIfNoPendingMessages); }
+#endif
+
+extern "C" NOTA_API int32_t nota_pluginhost_pump(void) {
+#if JUCE_LINUX || JUCE_BSD
+ if (g_juceGui == nullptr) return 0; // no plugin/editor yet: nothing to service
+ auto* mm = juce::MessageManager::getInstanceWithoutCreating();
+ if (mm == nullptr || !mm->isThisTheMessageThread()) return 0;
+ // Bounded so a plugin that keeps re-posting messages can't starve Avalonia.
+ constexpr int kMaxPerPump = 64;
+ int n = 0;
+ while (n < kMaxPerPump && juce::detail::dispatchNextMessageOnSystemQueue(true)) ++n;
+ return n;
+#else
+ return 0;
+#endif
+}
+
// ---- Plugin scanning & catalog (M3-1) --------------------------------------
namespace {
diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cpp
index 8375d3ee..50fdddb8 100644
--- a/src/native/nota.engine/src/Engine.cpp
+++ b/src/native/nota.engine/src/Engine.cpp
@@ -492,7 +492,8 @@ void Engine::publishRaw(std::shared_ptr<Graph> g) {
void Engine::pushUndo() {
if (!authoring_) return;
- undoStack_.push_back(authoring_); // authoring_ is immutable after publish
+ undoStack_.push_back({authoring_, {}}); // authoring_ is immutable after publish
+ ++undoPushCount_;
if (undoStack_.size() > kMaxUndoDepth) {
undoStack_.erase(undoStack_.begin());
if (undoGroupDepth_ > 0 && undoGroupBase_ > 0) --undoGroupBase_; // keep the group's anchor
@@ -506,9 +507,16 @@ void Engine::beginUndoGroup() {
void Engine::endUndoGroup() {
if (undoGroupDepth_ <= 0 || --undoGroupDepth_ > 0) return;
- // Keep only the first checkpoint the group pushed (the pre-group state).
- if (undoStack_.size() > undoGroupBase_ + 1)
- undoStack_.erase(undoStack_.begin() + static_cast<std::ptrdiff_t>(undoGroupBase_ + 1), undoStack_.end());
+ // Collapse the group into its first entry: the pre-group graph (the first snapshot any
+ // entry of the group holds — a mix-only entry holds none) plus all mix changes merged.
+ if (undoStack_.size() > undoGroupBase_ + 1) {
+ auto first = undoStack_.begin() + static_cast<std::ptrdiff_t>(undoGroupBase_);
+ for (auto it = first + 1; it != undoStack_.end(); ++it) {
+ if (!first->graph) first->graph = it->graph;
+ mergeMix(first->mix, it->mix);
+ }
+ undoStack_.erase(first + 1, undoStack_.end());
+ }
}
void Engine::publish(std::shared_ptr<Graph> g) {
@@ -518,10 +526,8 @@ void Engine::publish(std::shared_ptr<Graph> g) {
void Engine::republishWithTrackRaw(int32_t trackId, std::shared_ptr<Track> nt) {
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount; // preserve scene count across the swap
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume; // carry master automation (M9 follow-up)
- g->masterTrack = (trackId == kMasterTrackId) ? nt : authoring_->masterTrack; // master chain edit or carry
+ inheritGraphLevel(*g, *authoring_);
+ if (trackId == kMasterTrackId) g->masterTrack = nt; // master chain edit
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks)
g->tracks.push_back(t->id() == trackId ? nt : t);
@@ -533,21 +539,176 @@ void Engine::republishWithTrack(int32_t trackId, std::shared_ptr<Track> nt) {
republishWithTrackRaw(trackId, std::move(nt));
}
+// Undo/redo: a snapshot entry swaps the graph (the current state becomes the opposite
+// stack's target); then its mix changes write their before (undo) / after (redo) values —
+// after the graph, so a restored track gets its value. An entry that changes nothing (all
+// of its tracks gone) is passed over, so one call always does something if it can.
bool Engine::undo() {
- if (undoStack_.empty()) return false;
- redoStack_.push_back(authoring_); // current state becomes the redo target
- auto g = undoStack_.back();
- undoStack_.pop_back();
- publishRaw(std::move(g)); // restore without a new checkpoint
- return true;
+ while (!undoStack_.empty()) {
+ UndoEntry e = std::move(undoStack_.back());
+ undoStack_.pop_back();
+ bool applied = false;
+ redoStack_.push_back({e.graph ? authoring_ : nullptr, e.mix});
+ if (e.graph) { publishRaw(std::move(e.graph)); applied = true; } // restore without a new checkpoint
+ for (const auto& c : e.mix) applied |= applyMix(c, false);
+ if (applied) return true;
+ }
+ return false;
}
bool Engine::redo() {
- if (redoStack_.empty()) return false;
- undoStack_.push_back(authoring_);
- auto g = redoStack_.back();
- redoStack_.pop_back();
- publishRaw(std::move(g));
+ while (!redoStack_.empty()) {
+ UndoEntry e = std::move(redoStack_.back());
+ redoStack_.pop_back();
+ bool applied = false;
+ undoStack_.push_back({e.graph ? authoring_ : nullptr, e.mix});
+ if (e.graph) { publishRaw(std::move(e.graph)); applied = true; }
+ for (const auto& c : e.mix) applied |= applyMix(c, true);
+ if (applied) return true;
+ }
+ return false;
+}
+
+// --- mix gestures (specs/009) ----------------------------------------------
+
+bool Engine::mixValue(const MixTarget& t, float& v) const {
+ if (t.kind == MixKind::MasterVolume) { v = masterVolume(); return true; }
+ auto tr = findTrackAuthoring(t.trackId);
+ if (!tr) return false;
+ v = t.kind == MixKind::TrackVolume ? tr->volume() : tr->pan();
+ return true;
+}
+
+bool Engine::applyMix(const MixChange& c, bool after) {
+ const float v = after ? c.after : c.before;
+ if (c.kind == MixKind::MasterVolume) { setMasterVolume(v); return true; }
+ auto tr = findTrackAuthoring(c.trackId);
+ if (!tr) return false; // the track is gone: skip quietly
+ if (c.kind == MixKind::TrackVolume) tr->setVolume(v); else tr->setPan(v);
+ return true;
+}
+
+// Fold `later` into `into`: per target the older before, the newer after; a target that
+// ends where it started is no change at all.
+void Engine::mergeMix(std::vector<MixChange>& into, const std::vector<MixChange>& later) {
+ for (const auto& c : later) {
+ auto it = std::find_if(into.begin(), into.end(), [&](const MixChange& m) {
+ return m.kind == c.kind && (c.kind == MixKind::MasterVolume || m.trackId == c.trackId);
+ });
+ if (it == into.end()) into.push_back(c); else it->after = c.after;
+ }
+ into.erase(std::remove_if(into.begin(), into.end(), [](const MixChange& m) { return m.before == m.after; }),
+ into.end());
+}
+
+// --- Stereo Map measurements (specs/008) ------------------------------------
+
+namespace {
+// Level, balance (on the pan scale — the equal-power pan that gives this energy split, so a
+// mono source panned to p reads p), correlation, and width = 1 - correlation (0 for any mono
+// source wherever it's panned, 1 for unrelated or anti-phase material). specs/008 research R2.
+NotaStereoMeasure deriveStereo(int32_t id, float eL, float eR, float eLR) {
+ NotaStereoMeasure m{ id, -200.0f, 0.0f, 0.0f, 0.0f };
+ const double l = std::max(0.0f, eL), r = std::max(0.0f, eR), sum = l + r;
+ if (sum > 1e-20) m.level_db = static_cast<float>(10.0 * std::log10(sum * 0.5));
+ if (sum > 1e-20)
+ m.balance = static_cast<float>(std::atan2(std::sqrt(r), std::sqrt(l)) * (4.0 / 3.14159265358979323846) - 1.0);
+ if (l > 1e-12 && r > 1e-12)
+ m.correlation = static_cast<float>(std::clamp(eLR / std::sqrt(l * r), -1.0, 1.0));
+ m.width = std::clamp(1.0f - m.correlation, 0.0f, 1.0f);
+ return m;
+}
+}
+
+int32_t Engine::stereoMeasures(NotaStereoMeasure* out, int32_t cap) const {
+ int32_t n = 0;
+ auto put = [&](const NotaStereoMeasure& m) { if (out && n < cap) out[n] = m; ++n; };
+ if (authoring_)
+ for (const auto& t : authoring_->tracks)
+ if (t && t->type() != TrackType::Group)
+ put(deriveStereo(t->id(), t->stereoL(), t->stereoR(), t->stereoLR()));
+ put(deriveStereo(kMasterTrackId, masterStereoL_.load(std::memory_order_relaxed),
+ masterStereoR_.load(std::memory_order_relaxed),
+ masterStereoLR_.load(std::memory_order_relaxed)));
+ return n;
+}
+
+bool Engine::mixUndoSelfTest() {
+ clearUndoHistory();
+ const float m0 = masterVolume();
+ undoStack_.push_back({ nullptr, { { MixKind::MasterVolume, -1, m0, 0.25f } } }); // a valid step…
+ setMasterVolume(0.25f);
+ undoStack_.push_back({ nullptr, { { MixKind::TrackVolume, 0x7fff0001, 1.0f, 0.5f } } }); // …under a dangling one
+ const bool undid = undo() && masterVolume() == m0 && undoStack_.empty() && redoStack_.size() == 2;
+ const bool redid = redo() && masterVolume() == 0.25f; // the valid step is on top of redo
+ const bool rest = !redo() && redoStack_.empty(); // the dangling one applies nothing
+ clearUndoHistory();
+ setMasterVolume(m0);
+ return undid && redid && rest;
+}
+
+int32_t Engine::beginMixGesture(const MixTarget* targets, int32_t count) {
+ if (!targets || count <= 0) return 0;
+ OpenMixGesture g{ nextMixGesture_, {}, undoPushCount_, undoStack_.size() };
+ for (int32_t i = 0; i < count; ++i) {
+ float v = 0.0f;
+ if (mixValue(targets[i], v)) g.targets.push_back({ targets[i].kind, targets[i].trackId, v, v });
+ }
+ if (g.targets.empty()) return 0;
+ if (++nextMixGesture_ <= 0) nextMixGesture_ = 1;
+ mixGestures_.push_back(std::move(g));
+ return mixGestures_.back().handle;
+}
+
+void Engine::endMixGesture(int32_t handle) {
+ auto it = std::find_if(mixGestures_.begin(), mixGestures_.end(),
+ [&](const OpenMixGesture& g) { return g.handle == handle; });
+ if (it == mixGestures_.end()) return;
+ OpenMixGesture g = std::move(*it);
+ mixGestures_.erase(it);
+ std::vector<MixChange> changes;
+ for (auto& c : g.targets) {
+ float v = 0.0f;
+ if (!mixValue({ c.kind, c.trackId }, v)) continue; // the track went away mid-gesture
+ if (v == c.before) continue; // exact: no net change, no step
+ c.after = v;
+ changes.push_back(c);
+ }
+ if (changes.empty()) return;
+ // Checkpoints pushed during the gesture (automation recording: the lane's creation and
+ // the pre-write state) and this value change are one user action: collapse everything
+ // the gesture stacked into its first entry, as an undo group would, and add the values.
+ if (undoPushCount_ != g.pushCountAtBegin && !undoStack_.empty()) {
+ const size_t base = std::min(g.stackSizeAtBegin, undoStack_.size() - 1);
+ auto first = undoStack_.begin() + static_cast<std::ptrdiff_t>(base);
+ for (auto it = first + 1; it != undoStack_.end(); ++it) {
+ if (!first->graph) first->graph = it->graph;
+ mergeMix(first->mix, it->mix);
+ }
+ undoStack_.erase(first + 1, undoStack_.end());
+ mergeMix(first->mix, changes);
+ return;
+ }
+ undoStack_.push_back({ nullptr, std::move(changes) });
+ if (undoStack_.size() > kMaxUndoDepth) {
+ undoStack_.erase(undoStack_.begin());
+ if (undoGroupDepth_ > 0 && undoGroupBase_ > 0) --undoGroupBase_;
+ }
+ redoStack_.clear();
+}
+
+// --- project pan law (specs/006) -------------------------------------------
+
+bool Engine::setPanLaw(PanLaw law, bool checkpoint) {
+ if (law != PanLaw::Balance && law != PanLaw::Stereo) return false;
+ if (!authoring_ || authoring_->panLaw == law) return true;
+ auto g = std::make_shared<Graph>(*authoring_); // copy: tracks shared, graph-level fields kept
+ g->panLaw = law;
+ if (checkpoint) publish(std::move(g));
+ else { // load / baseline: no crossfade from the previous project's law
+ publishRaw(std::move(g));
+ panLawSnap_.store(true, std::memory_order_release);
+ }
return true;
}
@@ -570,6 +731,7 @@ void Engine::reset() {
auto empty = std::make_shared<Graph>();
empty->masterTrack = std::make_shared<Track>(kMasterTrackId, TrackType::Audio);
publishRaw(std::move(empty));
+ panLawSnap_.store(true, std::memory_order_release); // a new project takes its law at once
nextTrackId_ = 1;
clearUndoHistory();
}
@@ -580,6 +742,7 @@ void Engine::clearUndoHistory() {
// them here frees nothing the audio thread can still be reading.
undoStack_.clear();
redoStack_.clear();
+ mixGestures_.clear(); // a gesture can't outlive the history it would land in
undoGroupDepth_ = 0; undoGroupBase_ = 0;
}
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index cc0d9263..99bfea11 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -70,6 +70,17 @@ using MonitorQueue = SpscRingBuffer<InputFrame, 1u << 14>; // input thread -> au
// For CC, number is the controller and value its 0..127 data; for notes, number
// is the pitch and value the velocity. The engine still routes notes to instruments.
struct ControlEvent { int32_t kind; int32_t channel; int32_t number; int32_t value; };
+
+// Mix undo (specs/009): volume / pan / master volume live in atomics outside the graph, so
+// their undo steps carry values instead of a snapshot. They share one history with the
+// structural snapshots (UndoEntry), which keeps the order of all edits.
+enum class MixKind : int32_t { TrackVolume = 0, TrackPan = 1, MasterVolume = 2 };
+struct MixTarget { MixKind kind; int32_t trackId; }; // trackId ignored for MasterVolume
+struct MixChange { MixKind kind; int32_t trackId; float before; float after; };
+struct UndoEntry {
+ std::shared_ptr<Graph> graph; // the state to restore; null for a mix-only step
+ std::vector<MixChange> mix; // empty for a structural step; one change per target
+};
using ControlEventQueue = SpscRingBuffer<ControlEvent, 1024>;
class Engine {
@@ -988,8 +999,9 @@ public:
// previous authoring_ is already a complete restore point. Undo/redo just
// swap the authoring/live pointer between retained snapshots (audio sample
// buffers are shared via shared_ptr, so a snapshot costs only metadata).
- // Scope: structural graph edits. Atomic params (volume/pan/mute/bypass/
- // device params) and transport live outside the Graph and are not covered.
+ // Scope: structural graph edits, plus volume / pan / master volume steps made through
+ // mix gestures (specs/009). Mute, solo, sends, bypass, device params and the transport
+ // live outside the Graph and are not covered.
bool undo();
bool redo();
bool canUndo() const { return !undoStack_.empty(); }
@@ -1004,6 +1016,29 @@ public:
// built default project). Message thread only.
void clearUndoHistory();
+ // --- mix gestures (specs/009) ---
+ // begin records the targets' values; end pushes ONE undo step with the values that
+ // changed (none → no step), merged into a structural checkpoint pushed meanwhile
+ // (automation recording). The plain setters never record. Message thread only.
+ int32_t beginMixGesture(const MixTarget* targets, int32_t count); // handle > 0, or 0
+ void endMixGesture(int32_t handle); // unknown handle: no-op
+ float masterVolume() const { return masterVolume_.load(std::memory_order_relaxed); }
+ // Device-free: a mix step for a track that no longer exists is passed over — undo/redo
+ // continue with the next step (FR-010; unreachable through the public edits, which keep
+ // a removal above the steps of its track). Clears the history.
+ bool mixUndoSelfTest();
+
+ // --- Stereo Map measurements (specs/008) ---
+ // Rows for every non-group track (track order) and the master, derived from the running
+ // L², R², L·R averages. Returns the total row count; fills up to `cap`. Message thread.
+ int32_t stereoMeasures(NotaStereoMeasure* out, int32_t cap) const;
+
+ // --- project pan law (specs/006) ---
+ // Graph-level, so undo/redo restore it. checkpoint = false for load / the new-project
+ // baseline. False for an unknown law; a no-op (no undo step) if unchanged. Message thread.
+ bool setPanLaw(PanLaw law, bool checkpoint);
+ PanLaw panLaw() const { return authoring_ ? authoring_->panLaw : PanLaw::Balance; }
+
// --- offline render (tests / export) ---
void renderOffline(float* out, int32_t frames);
// Render at a specific sample rate (WAV export, M6-4). Sets the transport
@@ -1260,10 +1295,17 @@ private:
std::atomic<int64_t> previewScopeW_{0}; // samples written so far
std::list<std::pair<std::string, std::shared_ptr<SampleBuffer>>> auditionCache_; // MRU first
- // Undo/redo snapshot stacks (M6-6). Hold retained Graph snapshots; entries
- // are cheap (metadata only — sample buffers are shared via shared_ptr).
- std::vector<std::shared_ptr<Graph>> undoStack_;
- std::vector<std::shared_ptr<Graph>> redoStack_;
+ // Undo/redo stacks (M6-6, specs/009). Entries hold retained Graph snapshots (cheap —
+ // sample buffers are shared via shared_ptr) and/or mix value changes.
+ std::vector<UndoEntry> undoStack_;
+ std::vector<UndoEntry> redoStack_;
+ uint64_t undoPushCount_ = 0; // bumped by every structural checkpoint (gesture merge)
+ struct OpenMixGesture { int32_t handle; std::vector<MixChange> targets; uint64_t pushCountAtBegin; size_t stackSizeAtBegin; };
+ std::vector<OpenMixGesture> mixGestures_; // message thread; `before` filled at begin
+ int32_t nextMixGesture_ = 1;
+ bool mixValue(const MixTarget& t, float& v) const; // current value; false = gone
+ bool applyMix(const MixChange& c, bool after); // write before/after; false = gone
+ static void mergeMix(std::vector<MixChange>& into, const std::vector<MixChange>& later);
static constexpr size_t kMaxUndoDepth = 128;
int32_t undoGroupDepth_ = 0; // open beginUndoGroup() calls
size_t undoGroupBase_ = 0; // undoStack_ size when the outermost group began
@@ -1273,6 +1315,8 @@ private:
std::atomic<float> masterPeakR_{0.0f};
std::atomic<float> masterRmsL_{0.0f};
std::atomic<float> masterRmsR_{0.0f};
+ // Master stereo measurement (specs/008): running L², R², L·R after the master volume.
+ std::atomic<float> masterStereoL_{0.0f}, masterStereoR_{0.0f}, masterStereoLR_{0.0f};
std::atomic<bool> recording_{false};
std::atomic<int32_t> xruns_{0}; // device dropouts since launch (M7-8)
std::atomic<float> cpuLoad_{0.0f}; // smoothed RT DSP load 0..1 (Phase 11)
@@ -1340,6 +1384,13 @@ private:
std::vector<OverrideTarget> overrides_;
bool wasPlaying_ = false; // poll() edge detection: stop ends latched writes
bool renderWasPlaying_ = false; // audio-thread play→stop edge (flush stuck notes)
+ // Pan-law crossfade (specs/006), audio thread only: when the live graph's law changes, the
+ // track/return pan stages blend from panLawFrom_'s gains to panLawTo_'s over 10 ms.
+ PanLaw panLawFrom_ = PanLaw::Balance, panLawTo_ = PanLaw::Balance;
+ float panLawPos_ = 1.0f; // 0 = from … 1 = to (1 = no fade running)
+ // Set by the message thread when the law comes from a load / reset / the new-project
+ // baseline rather than a user switch: the audio thread then takes it at once, no fade.
+ std::atomic<bool> panLawSnap_{false};
bool seekedThisBlock_ = false; // a Seek command was drained this block (audio thread)
bool seekedWhileRolling_ = false; // ...and it arrived while the transport was rolling
bool chaseNotes_ = false; // this segment starts at a discontinuity: re-trigger held clip notes
diff --git a/src/native/nota.engine/src/Engine_Modulation.cpp b/src/native/nota.engine/src/Engine_Modulation.cpp
index 25211dab..e79464f9 100644
--- a/src/native/nota.engine/src/Engine_Modulation.cpp
+++ b/src/native/nota.engine/src/Engine_Modulation.cpp
@@ -307,10 +307,7 @@ void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex,
if (!authoring_) return;
bool anyChange = false;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& ot : authoring_->tracks) {
const bool ownerIsEdited = ot->id() == track;
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index 29eb5ebe..20863a0f 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -52,6 +52,63 @@ struct ScopedNoDenormals {
constexpr double kTwoPi = 6.283185307179586;
constexpr float kToneGain = 0.2f;
constexpr float kMetroGain = 0.5f;
+// Track / return pan as a 2×2 matrix (specs/006): out L = ll·L + lr·R, out R = rl·L + rr·R,
+// fader volume included. Balance is the equal-power law Nota always had (cross terms 0, the
+// far channel fades out). Stereo folds a share b = |pan|/2 of the far channel into the near
+// side and takes it off the near channel's own gain, so a mono source (L = R) gets exactly
+// the Balance gains, centre is identical, and full pan is the mono fold (L+R)/2.
+struct PanGains { float ll, lr, rl, rr; };
+inline PanGains panGains(float pan, float vol, PanLaw law) {
+ const double theta = (pan + 1.0) * (kTwoPi / 8.0); // 0..pi/2
+ const double c = std::cos(theta), s = std::sin(theta);
+ if (law == PanLaw::Balance)
+ return { static_cast<float>(c) * vol, 0.0f, 0.0f, static_cast<float>(s) * vol };
+ const double b = 0.5 * std::fabs(pan);
+ if (pan <= 0.0f)
+ return { static_cast<float>(c - b) * vol, static_cast<float>(b) * vol, 0.0f, static_cast<float>(s) * vol };
+ return { static_cast<float>(c) * vol, 0.0f, static_cast<float>(b) * vol, static_cast<float>(s - b) * vol };
+}
+
+// One track's pan for one segment. Without cross terms or a law crossfade it is the plain
+// two-gain multiply (so Balance renders stay bit-identical); during a crossfade the gains
+// blend from the old law's to the new law's per sample.
+struct PanStage {
+ PanGains to, from;
+ bool cross, fade;
+ float pos, step;
+ PanStage(float pan, float vol, PanLaw toLaw, PanLaw fromLaw, float fadePos, float fadeStep)
+ : to(panGains(pan, vol, toLaw)), from(to), fade(fadePos < 1.0f), pos(fadePos), step(fadeStep) {
+ if (fade) from = panGains(pan, vol, fromLaw);
+ cross = fade || to.lr != 0.0f || to.rl != 0.0f;
+ }
+ void apply(int32_t i, float inL, float inR, float& l, float& r) const {
+ if (!cross) { l = inL * to.ll; r = inR * to.rr; return; }
+ PanGains k = to;
+ if (fade) {
+ const float x = std::min(1.0f, pos + step * static_cast<float>(i));
+ k = { from.ll + (to.ll - from.ll) * x, from.lr + (to.lr - from.lr) * x,
+ from.rl + (to.rl - from.rl) * x, from.rr + (to.rr - from.rr) * x };
+ }
+ l = k.ll * inL + k.lr * inR;
+ r = k.rl * inL + k.rr * inR;
+ }
+};
+
+// Stereo measurement (specs/008): fold one block's mean L², R², L·R into a track's running
+// averages; `a` is the per-block smoothing step for τ = 0.3 s at this block length.
+inline float stereoBlockStep(int32_t frames, double sr) {
+ return static_cast<float>(1.0 - std::exp(-frames / (0.3 * (sr > 0.0 ? sr : 44100.0))));
+}
+inline void stereoFold(std::atomic<float>& eL, std::atomic<float>& eR, std::atomic<float>& eLR,
+ double sqL, double sqR, double sLR, int32_t frames, float a) {
+ const double n = frames > 0 ? frames : 1;
+ auto fold = [a](std::atomic<float>& e, double mean) {
+ const float cur = e.load(std::memory_order_relaxed);
+ e.store(cur + a * (static_cast<float>(mean) - cur), std::memory_order_relaxed);
+ };
+ fold(eL, sqL / n); fold(eR, sqR / n); fold(eLR, sLR / n);
+}
+
// Sort note events by sample offset; at ties, note-offs before note-ons so a
// same-block same-pitch retrigger releases the old voice before the new one.
inline bool midiEvLess(const MidiEv& a, const MidiEv& b) {
@@ -1008,7 +1065,7 @@ void Engine::processBlock(float* out, int32_t numFrames) {
const float mv = masterVolume_.load(std::memory_order_relaxed);
float mpkL = 0.0f, mpkR = 0.0f;
- double msqL = 0.0, msqR = 0.0;
+ double msqL = 0.0, msqR = 0.0, msLR = 0.0; // msLR: Stereo Map (specs/008)
for (int32_t i = 0; i < numFrames; ++i) {
// Master safety net: a NaN slips straight through std::clamp (every compare
// with NaN is false, so clamp returns it unchanged) and hits the speakers as
@@ -1024,8 +1081,10 @@ void Engine::processBlock(float* out, int32_t numFrames) {
const float al = std::fabs(l), ar = std::fabs(r);
if (al > mpkL) mpkL = al;
if (ar > mpkR) mpkR = ar;
- msqL += l * (double)l; msqR += r * (double)r;
+ msqL += l * (double)l; msqR += r * (double)r; msLR += l * (double)r;
}
+ stereoFold(masterStereoL_, masterStereoR_, masterStereoLR_, msqL, msqR, msLR, numFrames,
+ stereoBlockStep(numFrames, transport_.sampleRate()));
masterPeakL_.store(mpkL, std::memory_order_relaxed);
masterPeakR_.store(mpkR, std::memory_order_relaxed);
masterRmsL_.store(numFrames ? static_cast<float>(std::sqrt(msqL / numFrames)) : 0.0f, std::memory_order_relaxed);
@@ -1052,6 +1111,26 @@ void Engine::renderMonitorInput(Graph* g, const Track& t, float* dst, int32_t fr
void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, bool playing, double spb) {
{
+ // Pan law (specs/006): a change of the live law starts a 10 ms crossfade of the pan
+ // gains; flipping back mid-fade reverses it from where it is, so nothing jumps. A law
+ // that came with a load / reset is taken at once (nothing of the old project sounds).
+ if (panLawSnap_.exchange(false, std::memory_order_acq_rel)) {
+ panLawFrom_ = panLawTo_ = g->panLaw;
+ panLawPos_ = 1.0f;
+ } else if (g->panLaw != panLawTo_) {
+ if (panLawPos_ < 1.0f && g->panLaw == panLawFrom_) {
+ std::swap(panLawFrom_, panLawTo_);
+ panLawPos_ = 1.0f - panLawPos_;
+ } else {
+ panLawFrom_ = panLawTo_;
+ panLawTo_ = g->panLaw;
+ panLawPos_ = 0.0f;
+ }
+ }
+ const double srLaw = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;
+ const float panLawStep = static_cast<float>(1.0 / (0.010 * srLaw));
+ const float stereoA = stereoBlockStep(frames, srLaw); // Stereo Map averages (specs/008)
+
// Automation (M9): read-mode block-rate eval — write each active lane's
// value into its target atomic before the mix reads it. Always runs (also
// when stopped: the playhead is static, so scrub shows automation too).
@@ -1162,7 +1241,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
const bool audible = !leafMute(t) && (!anySolo || leafSolo(t));
// Soloing a monitoring (or recording) track must not silence what it listens to.
const bool feeding = !audible && !leafMute(t) && feedsMonitor(t.id());
- if (!audible && !capturing && !feeding) { t.setMeter(0, 0, 0, 0); continue; }
+ if (!audible && !capturing && !feeding) { t.setMeter(0, 0, 0, 0); t.stereoFold(0, 0, 0, frames, stereoA); continue; }
const bool toMix = audible || capturing; // false: render only for the taps
// Destination: this leaf's parent group's submix bus, else the master mix.
const int destSlot = slotOf(t.groupId());
@@ -1189,7 +1268,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// 1) Render the track's dry stereo (pre-fader) into scratch_.
if (frozenActive) {
- if (!playing) { t.setMeter(0, 0, 0, 0); continue; } // frozen sounds only while rolling
+ if (!playing) { t.setMeter(0, 0, 0, 0); t.stereoFold(0, 0, 0, frames, stereoA); continue; } // frozen sounds only while rolling
fillFrozen(t, scratch_.data(), frames, blockStart, spb);
} else {
if (t.instrument) {
@@ -1213,7 +1292,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
else if (playing && arrangementActive)
renderAudioClipsRaw(t.clips, scratch_.data(), frames, blockStart, spb);
else
- { t.setMeter(0, 0, 0, 0); continue; } // stopped / session-only audio track: nothing to do
+ { t.setMeter(0, 0, 0, 0); t.stereoFold(0, 0, 0, frames, stereoA); continue; } // stopped / session-only audio track: nothing to do
}
// 1b) Pre-FX tap (Phase D): if this track feeds a sidechain, capture its
@@ -1264,20 +1343,18 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// 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);
- const double theta = (pan + 1.0) * (kTwoPi / 8.0); // 0..pi/2
- const float gl = static_cast<float>(std::cos(theta)) * vol;
- const float gr = static_cast<float>(std::sin(theta)) * vol;
+ const PanStage ps(pan, vol, panLawTo_, panLawFrom_, panLawPos_, panLawStep); // project pan law
float sends[kMaxReturns]; bool anySend = false; // post-fader send taps (M6-1)
for (int b = 0; b < numReturns; ++b) { sends[b] = t.send(b); if (sends[b] != 0.0f) anySend = true; }
const int32_t routeSlot = routeSlotForTrack(t.id()); // Phase B: this track is a sidechain source?
float* route = routeSlot >= 0 ? routeBusNext_[routeSlot].data() : nullptr;
const bool tapRec = (recSrc > 0 && t.id() == recSrc); // internal resampling source
float pkL = 0.0f, pkR = 0.0f;
- double sqL = 0.0, sqR = 0.0;
+ double sqL = 0.0, sqR = 0.0, sLR = 0.0; // sLR: Stereo Map (specs/008)
int64_t recDropped = 0;
for (int32_t i = 0; i < frames; ++i) {
- const float l = scratch_[i * 2] * gl;
- const float r = scratch_[i * 2 + 1] * gr;
+ float l, r;
+ ps.apply(i, scratch_[i * 2], scratch_[i * 2 + 1], l, r);
if (tapRec && !inputQueue_.push(InputFrame{ l, r })) ++recDropped; // record this track's output
if (route) { route[i * 2] += l; route[i * 2 + 1] += r; } // tap post-fader → route bus
if (!toMix) continue; // solo-gated feeder: taps only
@@ -1293,9 +1370,15 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
if (ar > pkR) pkR = ar;
sqL += l * (double)l;
sqR += r * (double)r;
+ sLR += l * (double)r;
}
if (recDropped) inputDroppedFrames_.fetch_add(recDropped, std::memory_order_relaxed);
- if (!toMix) { t.setMeter(0, 0, 0, 0); continue; }
+ if (!toMix) { // muted / solo-gated: nothing reaches the master, the averages decay
+ t.setMeter(0, 0, 0, 0);
+ t.stereoFold(0.0, 0.0, 0.0, frames, stereoA);
+ continue;
+ }
+ t.stereoFold(sqL, sqR, sLR, frames, stereoA);
t.setMeter(pkL, pkR,
static_cast<float>(std::sqrt(sqL / frames)),
static_cast<float>(std::sqrt(sqR / frames)));
@@ -1374,7 +1457,7 @@ 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()) { t.setMeter(0, 0, 0, 0); continue; }
+ if (bus < 0 || bus >= numReturns || t.mute()) { t.setMeter(0, 0, 0, 0); t.stereoFold(0, 0, 0, frames, stereoA); continue; }
std::copy_n(returnBus_[bus].data(), frames * 2, scratch_.data());
{
@@ -1402,18 +1485,16 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
const float vol = t.volume();
const float pan = std::clamp(t.pan(), -1.0f, 1.0f);
- const double theta = (pan + 1.0) * (kTwoPi / 8.0);
- const float gl = static_cast<float>(std::cos(theta)) * vol;
- const float gr = static_cast<float>(std::sin(theta)) * vol;
+ const PanStage ps(pan, vol, panLawTo_, panLawFrom_, panLawPos_, panLawStep); // project pan law
const int32_t routeSlot = routeSlotForTrack(t.id());
float* route = routeSlot >= 0 ? routeBusNext_[routeSlot].data() : nullptr;
const bool tapRec = (recSrc > 0 && t.id() == recSrc); // internal resampling source (a return)
float pkL = 0.0f, pkR = 0.0f;
- double sqL = 0.0, sqR = 0.0;
+ double sqL = 0.0, sqR = 0.0, sLR = 0.0; // sLR: Stereo Map (specs/008)
int64_t recDropped = 0;
for (int32_t i = 0; i < frames; ++i) {
- const float l = scratch_[i * 2] * gl;
- const float r = scratch_[i * 2 + 1] * gr;
+ float l, r;
+ ps.apply(i, scratch_[i * 2], scratch_[i * 2 + 1], l, r);
out[i * 2] += l;
out[i * 2 + 1] += r;
if (tapRec && !inputQueue_.push(InputFrame{ l, r })) ++recDropped;
@@ -1423,8 +1504,10 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
if (ar > pkR) pkR = ar;
sqL += l * (double)l;
sqR += r * (double)r;
+ sLR += l * (double)r;
}
if (recDropped) inputDroppedFrames_.fetch_add(recDropped, std::memory_order_relaxed);
+ t.stereoFold(sqL, sqR, sLR, frames, stereoA);
t.setMeter(pkL, pkR,
static_cast<float>(std::sqrt(sqL / frames)),
static_cast<float>(std::sqrt(sqR / frames)));
@@ -1444,6 +1527,8 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
routeBus_[s].swap(routeBusNext_[s]);
routeBusPre_[s].swap(routeBusPreNext_[s]);
}
+
+ if (panLawPos_ < 1.0f) panLawPos_ = std::min(1.0f, panLawPos_ + panLawStep * static_cast<float>(frames));
}
}
diff --git a/src/native/nota.engine/src/Engine_Session.cpp b/src/native/nota.engine/src/Engine_Session.cpp
index ddce7b27..c05d789c 100644
--- a/src/native/nota.engine/src/Engine_Session.cpp
+++ b/src/native/nota.engine/src/Engine_Session.cpp
@@ -111,10 +111,8 @@ bool Engine::clearSessionSlot(int32_t trackId, int32_t scene) {
std::shared_ptr<Graph> Engine::rebuildScenes(int32_t newCount,
const std::function<void(std::vector<SessionSlot>&)>& mutate) {
auto g = std::make_shared<Graph>();
- g->sceneCount = newCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
+ g->sceneCount = newCount;
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
auto nt = cloneTrack(*t);
@@ -859,10 +857,8 @@ int32_t Engine::insertSceneRow(int32_t at, int32_t copyFrom, bool capturePlaying
const int32_t count = authoring_->sceneCount;
if (at < 0 || at > count || copyFrom >= count) return -1;
auto g = std::make_shared<Graph>();
- g->sceneCount = count + 1;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
+ g->sceneCount = count + 1;
if (static_cast<int32_t>(g->scenes.size()) < count) g->scenes.resize(count);
g->scenes.insert(g->scenes.begin() + at, copyFrom >= 0 ? g->scenes[copyFrom] : SceneInfo{});
g->tracks.reserve(authoring_->tracks.size());
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index 0e70c3fd..5ab24293 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -459,10 +459,7 @@ void Engine::reconfigureAllWarpStreams(double spb, double devSR) {
if (devSR <= 0.0 || spb <= 0.0) return;
bool any = false;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
bool warped = false;
@@ -1380,10 +1377,7 @@ bool Engine::moveClipToTrack(int32_t srcTrackId, int32_t clipIndex, int32_t sour
// Atomic two-track swap in a single publish (one undo checkpoint).
pushUndo();
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
if (t->id() == srcTrackId) g->tracks.push_back(nsrc);
@@ -1500,10 +1494,7 @@ bool Engine::moveClipBlock(const std::vector<ClipMoveReq>& moves) {
// Publish every touched track at once — a single undo checkpoint for the whole group.
pushUndo();
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
auto it = clones.find(t->id());
@@ -1532,10 +1523,7 @@ bool Engine::deleteClipsInRange(const std::vector<int32_t>& trackIds, double sta
auto listed = [&](int32_t id){ return std::find(trackIds.begin(), trackIds.end(), id) != trackIds.end(); };
bool any = false;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
if (t->type() != TrackType::Return && listed(t->id()) && rangeTouchesTrack(*t, start, end, spb, devSR)) {
@@ -1562,10 +1550,7 @@ bool Engine::splitClipsAtRange(const std::vector<int32_t>& trackIds, double star
auto listed = [&](int32_t id){ return std::find(trackIds.begin(), trackIds.end(), id) != trackIds.end(); };
bool any = false;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
if (t->type() == TrackType::Return || !listed(t->id()) || !rangeTouchesTrack(*t, start, end, spb, devSR))
@@ -1617,10 +1602,7 @@ double Engine::duplicateRange(const std::vector<int32_t>& trackIds, double start
auto listed = [&](int32_t id){ return std::find(trackIds.begin(), trackIds.end(), id) != trackIds.end(); };
bool any = false;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
if (t->type() == TrackType::Return || !listed(t->id()) || !rangeTouchesTrack(*t, start, end, spb, devSR))
@@ -1752,10 +1734,7 @@ bool Engine::insertTime(double at, double len, bool duplicate) {
bool any = false;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
any |= shiftLane(g->masterVolume);
if (g->masterTrack)
if (auto nm = shiftTrack(*g->masterTrack)) { g->masterTrack = nm; any = true; }
@@ -1894,10 +1873,7 @@ bool Engine::consolidateRange(const std::vector<int32_t>& trackIds, double start
auto listed = [&](int32_t id){ return std::find(trackIds.begin(), trackIds.end(), id) != trackIds.end(); };
std::vector<std::pair<int32_t,int32_t>> placed;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
const bool clipTrack = t->type() == TrackType::Instrument || t->type() == TrackType::Audio;
@@ -2437,10 +2413,7 @@ void Engine::placeBlock(const std::vector<BlockClip>& items, double placedStart,
// Publish all touched tracks at once — a single undo checkpoint for the whole block.
pushUndo();
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
auto it = clones.find(t->id());
@@ -2489,10 +2462,7 @@ bool Engine::cutClipBlock(const std::vector<std::pair<int32_t,int32_t>>& sel) {
if (clones.empty()) return true;
pushUndo();
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
auto it = clones.find(t->id());
@@ -2684,10 +2654,7 @@ int32_t Engine::duplicateTrack(int32_t trackId) {
// Insert the copy right after the source (new snapshot; checkpoints undo).
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size() + 1);
for (auto& t : authoring_->tracks) {
g->tracks.push_back(t);
@@ -2708,10 +2675,7 @@ bool Engine::removeTrack(int32_t trackId) {
if (rt->instrument) rt->instrument->closeEditor();
for (auto& d : rt->devices) if (d) d->closeEditor();
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks)
if (t->id() != trackId) g->tracks.push_back(t);
@@ -2740,10 +2704,7 @@ bool Engine::moveTrack(int32_t trackId, int32_t toIndex) {
regular.erase(regular.begin() + from);
regular.insert(regular.begin() + to, tr);
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(regular.size() + returns.size());
for (auto& t : regular) g->tracks.push_back(t);
for (auto& t : returns) g->tracks.push_back(t);
@@ -2778,10 +2739,7 @@ int32_t Engine::createGroup(const int32_t* ids, int32_t n) {
auto isMember = [&](int32_t id) { return std::find(members.begin(), members.end(), id) != members.end(); };
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size() + 1);
bool placed = false;
for (auto& t : authoring_->tracks) {
@@ -2804,10 +2762,7 @@ bool Engine::ungroup(int32_t groupId) {
for (auto& d : grp->devices) if (d) d->closeEditor(); // its plugin windows shouldn't linger
const int32_t parent = grp->groupId(); // children reparent up one level
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
if (t->id() == groupId) continue; // drop the group track
@@ -2834,10 +2789,7 @@ bool Engine::setTrackGroup(int32_t trackId, int32_t groupId) {
}
}
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& tt : authoring_->tracks) {
if (tt->id() == trackId) { auto nt = cloneTrack(*tt); nt->setGroupId(groupId); g->tracks.push_back(nt); }
@@ -2918,10 +2870,7 @@ std::vector<int32_t> Engine::insertTrackClones(const std::vector<std::shared_ptr
if (clones.empty()) return newIds;
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size() + clones.size());
for (auto& t : authoring_->tracks) g->tracks.push_back(t);
int32_t insertAt = -1;
@@ -2964,10 +2913,7 @@ bool Engine::removeTracks(const int32_t* ids, int32_t n) {
drop.insert(t->id());
}
auto g = std::make_shared<Graph>();
- g->sceneCount = authoring_->sceneCount;
- g->scenes = authoring_->scenes;
- g->masterVolume = authoring_->masterVolume;
- g->masterTrack = authoring_->masterTrack;
+ inheritGraphLevel(*g, *authoring_);
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks)
if (!drop.count(t->id())) g->tracks.push_back(t);
diff --git a/src/native/nota.engine/src/Graph.h b/src/native/nota.engine/src/Graph.h
index e66d0184..32e05a5d 100644
--- a/src/native/nota.engine/src/Graph.h
+++ b/src/native/nota.engine/src/Graph.h
@@ -18,6 +18,11 @@
namespace nota {
+// How a track's / return's pan is applied to a stereo signal (specs/006). Balance drops
+// the far channel as the pan moves; Stereo folds it into the near side. Identical for
+// mono material and at centre. Groups, clip pan envelopes and rack chains ignore it.
+enum class PanLaw : int32_t { Balance = 0, Stereo = 1 };
+
struct Graph {
std::vector<std::shared_ptr<Track>> tracks;
int32_t sceneCount = 8; // Session view rows (M5)
@@ -26,13 +31,26 @@ struct Graph {
std::vector<SceneInfo> scenes;
// Master-volume automation (M9 follow-up): a graph-level lane (not tied to a
// track), applied to the master gain in applyAutomation. Undo-free via the
- // snapshot, like track lanes. NB: fresh-graph builds must carry it forward
- // (same footgun as sceneCount) — copy it wherever sceneCount is copied.
+ // snapshot, like track lanes.
AutomationLane masterVolume;
// Master effect chain: a dedicated track (id kMasterTrackId) that isn't in `tracks`,
// so it stays out of the arrangement/mixer track lists. The render runs the full mix
- // through its device chain before the master fader. Carried forward like masterVolume.
+ // through its device chain before the master fader.
std::shared_ptr<Track> masterTrack;
+ // Project pan law (specs/006). In the snapshot so undo/redo restore it; Balance is the
+ // engine default (and every project before format v21).
+ PanLaw panLaw = PanLaw::Balance;
};
+// Graph-level fields (everything except `tracks`). A fresh graph built from scratch must
+// carry them forward or the edit silently resets them — so every such build calls this,
+// and a new graph-level field is added here.
+inline void inheritGraphLevel(Graph& dst, const Graph& src) {
+ dst.sceneCount = src.sceneCount;
+ dst.scenes = src.scenes;
+ dst.masterVolume = src.masterVolume;
+ dst.masterTrack = src.masterTrack;
+ dst.panLaw = src.panLaw;
+}
+
} // namespace nota
diff --git a/src/native/nota.engine/src/Track.h b/src/native/nota.engine/src/Track.h
index c973d87b..5b74b866 100644
--- a/src/native/nota.engine/src/Track.h
+++ b/src/native/nota.engine/src/Track.h
@@ -212,6 +212,27 @@ public:
float meterRmsL() const { return mRmsL_.load(std::memory_order_relaxed); }
float meterRmsR() const { return mRmsR_.load(std::memory_order_relaxed); }
+ // Stereo measurement (specs/008): running averages (τ ≈ 0.3 s) of L², R² and L·R of
+ // the post-fader, post-pan signal — the Stereo Map derives level, balance, width and
+ // correlation from them. Audio thread writes, UI reads; transient like the meter.
+ void setStereo(float l, float r, float lr) {
+ stereoL_.store(l, std::memory_order_relaxed);
+ stereoR_.store(r, std::memory_order_relaxed);
+ stereoLR_.store(lr, std::memory_order_relaxed);
+ }
+ float stereoL() const { return stereoL_.load(std::memory_order_relaxed); }
+ float stereoR() const { return stereoR_.load(std::memory_order_relaxed); }
+ float stereoLR() const { return stereoLR_.load(std::memory_order_relaxed); }
+ // Fold one block (sums of L², R², L·R over `frames`) in with step `a` (τ ≈ 0.3 s).
+ void stereoFold(double sqL, double sqR, double sLR, int32_t frames, float a) {
+ const double n = frames > 0 ? frames : 1;
+ auto fold = [a](std::atomic<float>& e, double mean) {
+ const float cur = e.load(std::memory_order_relaxed);
+ e.store(cur + a * (static_cast<float>(mean) - cur), std::memory_order_relaxed);
+ };
+ fold(stereoL_, sqL / n); fold(stereoR_, sqR / n); fold(stereoLR_, sLR / n);
+ }
+
// Send levels to return buses (M6-1), post-fader. `bus` is a return slot
// 0..kMaxReturns-1. Atomic (continuous UI control, like the fader).
void setSend(int32_t bus, float level) {
@@ -308,6 +329,7 @@ private:
std::atomic<float> mPeakR_{0.0f};
std::atomic<float> mRmsL_{0.0f};
std::atomic<float> mRmsR_{0.0f};
+ std::atomic<float> stereoL_{0.0f}, stereoR_{0.0f}, stereoLR_{0.0f}; // specs/008
std::atomic<float> send_[kMaxReturns] = {}; // per-return send levels (0 default)
int32_t returnIndex_ = -1; // >=0 for return tracks
int32_t groupId_ = -1; // parent Group track id, or -1 (top-level)
diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cpp
index f19af664..d8e0f673 100644
--- a/src/native/nota.engine/src/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/nota_engine_core.cpp
@@ -249,6 +249,39 @@ void nota_engine_undo_group_begin(NotaEngine* e) { if (e) ENG(e)->beginUndoGroup
void nota_engine_undo_group_end(NotaEngine* e) { if (e) ENG(e)->endUndoGroup(); }
void nota_engine_clear_undo_history(NotaEngine* e) { if (e) ENG(e)->clearUndoHistory(); }
+// ---- Mix undo (009) ---------------------------------------------------------
+
+int32_t nota_mix_gesture_begin(NotaEngine* e, const NotaMixTarget* targets, int32_t count) {
+ if (!e || !targets || count <= 0 || count > 64) return 0;
+ nota::MixTarget t[64];
+ int32_t n = 0;
+ for (int32_t i = 0; i < count; ++i) {
+ const int32_t k = targets[i].kind;
+ if (k < NOTA_MIX_TRACK_VOLUME || k > NOTA_MIX_MASTER_VOLUME) continue;
+ t[n++] = { static_cast<nota::MixKind>(k), targets[i].track_id };
+ }
+ return n > 0 ? ENG(e)->beginMixGesture(t, n) : 0;
+}
+void nota_mix_gesture_end(NotaEngine* e, int32_t handle) { if (e) ENG(e)->endMixGesture(handle); }
+float nota_engine_master_volume(const NotaEngine* e) { return e ? CENG(e)->masterVolume() : 1.0f; }
+int32_t nota_engine_mix_undo_selftest(NotaEngine* e) { return (e && ENG(e)->mixUndoSelfTest()) ? 1 : 0; }
+
+// ---- Stereo measurements (008) ---------------------------------------------
+
+int32_t nota_engine_stereo_measures(const NotaEngine* e, NotaStereoMeasure* out, int32_t cap) {
+ return e ? CENG(e)->stereoMeasures(out, cap < 0 ? 0 : cap) : 0;
+}
+
+// ---- Pan law (006) ---------------------------------------------------------
+
+NotaResult nota_engine_set_pan_law(NotaEngine* e, int32_t law, int32_t checkpoint) {
+ if (!e || (law != NOTA_PAN_LAW_BALANCE && law != NOTA_PAN_LAW_STEREO)) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->setPanLaw(static_cast<nota::PanLaw>(law), checkpoint != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
+int32_t nota_engine_pan_law(const NotaEngine* e) {
+ return e ? static_cast<int32_t>(CENG(e)->panLaw()) : NOTA_PAN_LAW_BALANCE;
+}
+
// ---- Project reset (M7-6) -------------------------------------------------
void nota_engine_reset(NotaEngine* e) {
diff --git a/tests/Nota.SmokeTest/MixUndoTests.cs b/tests/Nota.SmokeTest/MixUndoTests.cs
new file mode 100644
index 00000000..d8a66e55
--- /dev/null
+++ b/tests/Nota.SmokeTest/MixUndoTests.cs
@@ -0,0 +1,325 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Undo for volume and pan (specs/009-mix-param-undo): a gesture is one exact undo step, a
+// no-change gesture is none, mix steps keep their place among structural steps, automation
+// playback and loads never add steps, automation recording undoes with its value, and the
+// MCP / Remote / MIDI sources each make one step. Also runnable alone:
+// `dotnet run --project tests/Nota.SmokeTest -- --mixundo`.
+
+using Nota.Application;
+using Nota.Application.Editing;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class MixUndoTests
+{
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in Gestures()) yield return r;
+ foreach (var r in OneHistory()) yield return r;
+ foreach (var r in NotEdits()) yield return r;
+ foreach (var r in Mcp()) yield return r;
+ }
+
+ // ---- US3: an MCP call is one step -------------------------------------------------
+
+ private static IEnumerable<(bool, string)> Mcp()
+ {
+ using var eng = new NotaEngine();
+ int t = eng.AddAudioTrack();
+ eng.ClearUndoHistory();
+ float v0 = Vol(eng, t), p0 = Pan(eng, t);
+ var tools = new Nota.Mcp.Tools.TrackTools(eng, new SyncDispatch(), new NoRefresh());
+ tools.SetTrackVolume(t, 0.3f).GetAwaiter().GetResult();
+ tools.SetTrackPan(t, -0.5f).GetAwaiter().GetResult();
+ eng.Undo(); bool panBack = Pan(eng, t) == p0 && Vol(eng, t) == 0.3f;
+ eng.Undo();
+ yield return (panBack && Vol(eng, t) == v0 && !eng.CanUndo, "mix undo: each MCP set_track_volume / set_track_pan call is one step");
+ }
+
+ // ---- US4: playback, loads, freeze make no steps; recording merges --------------------
+
+
+ private static IEnumerable<(bool, string)> NotEdits()
+ {
+ var buf = new float[512 * 2];
+
+ // Automation playback (read mode) moves volume and pan without a single step.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddInstrumentTrack();
+ int lv = eng.AddAutomationLane(t, AutomationTarget.Volume, -1, -1);
+ eng.SetAutomationPoints(t, lv, new[] { new AutomationPoint(0, 0.1f), new AutomationPoint(8, 0.5f) });
+ int lp = eng.AddAutomationLane(t, AutomationTarget.Pan, -1, -1);
+ eng.SetAutomationPoints(t, lp, new[] { new AutomationPoint(0, -1f), new AutomationPoint(4, 1f) });
+ eng.ClearUndoHistory();
+ eng.Seek(0); eng.Play();
+ float vStart = Vol(eng, t);
+ for (int i = 0; i < 200; i++) eng.RenderOffline(buf, 512, 48000); // ≈ 2 s
+ eng.StopTransport();
+ yield return (!eng.CanUndo && Vol(eng, t) != vStart,
+ $"mix undo: 2 s of automation playback moves the fader ({vStart} → {Vol(eng, t)}) and adds no step");
+ }
+
+ // A new project and a project load leave no volume/pan steps behind.
+ using (var eng = new NotaEngine())
+ {
+ ProjectTemplate.ApplyDefault(eng);
+ yield return (!eng.CanUndo, "mix undo: a new project has nothing to undo");
+ int t = eng.AddAudioTrack();
+ eng.SetTrackVolume(t, 0.42f);
+ eng.SetTrackPan(t, 0.3f);
+ string dir = Path.Combine(Path.GetTempPath(), "nota-mixundo-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var store = new ProjectStore();
+ store.Save(eng, new TransportState(120, 1, false, false), dir);
+ using var e2 = new NotaEngine();
+ store.Load(e2, dir);
+ var vols = Enumerable.Range(0, e2.TrackCount).Select(i => e2.TryGetTrackInfo(i, out var ti) ? (ti.Id, ti.Volume, ti.Pan) : default).ToList();
+ bool same = true;
+ for (int i = 0; i < 300 && e2.CanUndo; i++)
+ {
+ e2.Undo();
+ foreach (var (id, v, pn) in vols)
+ if (Info(e2, id).Id == id && (Vol(e2, id) != v || Pan(e2, id) != pn)) same = false;
+ }
+ yield return (same, "mix undo: undoing after a load never changes a loaded volume or pan");
+ }
+ finally { try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { } }
+ }
+
+ // Freezing a track makes no volume step.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddInstrumentTrack();
+ int c = eng.AddMidiClip(t, 0, 2);
+ eng.SetClipNotes(t, c, new[] { new NotaNote(60, 0, 2, 0.9f) });
+ eng.SetTrackVolume(t, 0.6f);
+ eng.ClearUndoHistory();
+ new TrackFreezer().Freeze(eng, t, 2.0, restoreLoop: false, restoreMetronome: false);
+ bool same = true;
+ for (int i = 0; i < 20 && eng.CanUndo; i++) { eng.Undo(); if (Info(eng, t).Id == t && Vol(eng, t) != 0.6f) same = false; }
+ yield return (same, "mix undo: freezing a track adds no volume step");
+ }
+
+ // Automation recording: the lane edit and the value are one step (FR-009). Offline
+ // rendering doesn't sample live writes (that needs the audio clock), but starting the
+ // write already creates the lane — the structural checkpoint the value must join.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddInstrumentTrack();
+ eng.ClearUndoHistory();
+ float v0 = Vol(eng, t);
+ int p0 = eng.AutomationLaneCount(t);
+ eng.SetAutomationRecord(true);
+ eng.Seek(0); eng.Play();
+ int h = eng.BeginMixGesture(MixTarget.Volume(t)); // before the automation write, as the UI does
+ eng.BeginAutomationWrite(t, AutomationTarget.Volume, -1, -1, "");
+ for (int i = 0; i < 40; i++) { eng.SetTrackVolume(t, 0.2f + i * 0.01f); eng.RenderOffline(buf, 512, 48000); }
+ eng.EndAutomationWrite(t, AutomationTarget.Volume, -1, -1, "");
+ eng.EndMixGesture(h);
+ eng.StopTransport();
+ eng.SetAutomationRecord(false);
+ int p1 = eng.AutomationLaneCount(t);
+ float v1 = Vol(eng, t);
+ eng.Undo();
+ bool undone = eng.AutomationLaneCount(t) == p0 && Vol(eng, t) == v0 && !eng.CanUndo;
+ eng.Redo();
+ yield return (p1 > p0 && undone && eng.AutomationLaneCount(t) == p1 && Vol(eng, t) == v1,
+ $"mix undo: the recorded lane and the value undo and redo together ({p0}→{p1} lanes, {v0}→{v1})");
+ }
+ }
+
+ // ---- US2: one ordered history (contracts/c-abi-mix-undo.md) --------------------------
+
+ private static void Gesture(NotaEngine e, MixTarget t, Action set)
+ {
+ int h = e.BeginMixGesture(t);
+ set();
+ e.EndMixGesture(h);
+ }
+
+ private static IEnumerable<(bool, string)> OneHistory()
+ {
+ using var eng = new NotaEngine();
+ int a = eng.AddAudioTrack();
+ eng.ClearUndoHistory();
+ // State 0 → add track (1) → volume a (2) → pan law (3) → pan a (4)
+ float vol0 = Vol(eng, a), pan0 = Pan(eng, a);
+ int b = eng.AddAudioTrack();
+ Gesture(eng, MixTarget.Volume(a), () => eng.SetTrackVolume(a, 0.3f));
+ eng.SetPanLaw(PanLaw.Stereo);
+ Gesture(eng, MixTarget.Pan(a), () => eng.SetTrackPan(a, -0.7f));
+ bool s4 = eng.TrackCount == 2 && Vol(eng, a) == 0.3f && eng.PanLaw == PanLaw.Stereo && Pan(eng, a) == -0.7f;
+ eng.Undo(); bool s3 = Pan(eng, a) == pan0 && eng.PanLaw == PanLaw.Stereo && Vol(eng, a) == 0.3f;
+ eng.Undo(); bool s2 = eng.PanLaw == PanLaw.Balance && Vol(eng, a) == 0.3f && eng.TrackCount == 2;
+ eng.Undo(); bool s1 = Vol(eng, a) == vol0 && eng.TrackCount == 2;
+ eng.Undo(); bool s0 = eng.TrackCount == 1 && !eng.CanUndo;
+ yield return (s4 && s3 && s2 && s1 && s0, $"mix undo: four mixed edits undo in reverse order ({s4},{s3},{s2},{s1},{s0})");
+ eng.Redo(); eng.Redo(); eng.Redo(); eng.Redo();
+ yield return (eng.TrackCount == 2 && Vol(eng, a) == 0.3f && eng.PanLaw == PanLaw.Stereo && Pan(eng, a) == -0.7f && !eng.CanRedo,
+ "mix undo: …and redo replays them in order");
+ eng.Undo(); eng.Undo();
+ Gesture(eng, MixTarget.Volume(a), () => eng.SetTrackVolume(a, 0.9f));
+ yield return (!eng.CanRedo, "mix undo: a new edit after undos drops the redo branch");
+ GC.KeepAlive(b);
+
+ // A track removed while a gesture on it is open: no mix step, the removal is the step.
+ using var e2 = new NotaEngine();
+ int t = e2.AddAudioTrack(), keep = e2.AddAudioTrack();
+ e2.ClearUndoHistory();
+ int h = e2.BeginMixGesture(MixTarget.Volume(t));
+ e2.SetTrackVolume(t, 0.2f);
+ e2.RemoveTrack(t);
+ e2.EndMixGesture(h);
+ e2.Undo();
+ yield return (e2.TrackCount == 2 && !e2.CanUndo, "mix undo: a track removed mid-gesture leaves only the removal step");
+
+ // Volume of t, then remove t: undo brings t back first, then its volume.
+ e2.ClearUndoHistory();
+ float tv0 = Vol(e2, t);
+ Gesture(e2, MixTarget.Volume(t), () => e2.SetTrackVolume(t, 0.4f));
+ e2.RemoveTrack(t);
+ e2.Undo(); bool back = e2.TrackCount == 2 && Vol(e2, t) == 0.4f;
+ e2.Undo();
+ yield return (back && Vol(e2, t) == tv0, $"mix undo: undo restores a removed track, then its volume ({Vol(e2, t)})");
+
+ // Two gestures open at once on different tracks: two steps, in end order.
+ e2.ClearUndoHistory();
+ float k0 = Vol(e2, keep), t0 = Vol(e2, t);
+ int h1 = e2.BeginMixGesture(MixTarget.Volume(t));
+ int h2 = e2.BeginMixGesture(MixTarget.Volume(keep));
+ e2.SetTrackVolume(t, 0.11f); e2.SetTrackVolume(keep, 0.22f);
+ e2.EndMixGesture(h2); e2.EndMixGesture(h1);
+ e2.Undo(); bool firstUndo = Vol(e2, t) == t0 && Vol(e2, keep) == 0.22f;
+ e2.Undo();
+ yield return (firstUndo && Vol(e2, keep) == k0, "mix undo: overlapping gestures make two steps, undone in reverse end order");
+
+ // An undo group around two gestures on the same track: one step, first before → last after.
+ e2.ClearUndoHistory();
+ float g0 = Vol(e2, t);
+ e2.BeginUndoGroup();
+ Gesture(e2, MixTarget.Volume(t), () => e2.SetTrackVolume(t, 0.6f));
+ Gesture(e2, MixTarget.Volume(t), () => e2.SetTrackVolume(t, 0.7f));
+ e2.EndUndoGroup();
+ e2.Undo();
+ bool grouped = Vol(e2, t) == g0 && !e2.CanUndo;
+ e2.Redo();
+ yield return (grouped && Vol(e2, t) == 0.7f, "mix undo: an undo group of two gestures is one step");
+
+ // A group that starts with a gesture and then makes a structural edit keeps the graph.
+ e2.ClearUndoHistory();
+ int n0 = e2.TrackCount;
+ e2.BeginUndoGroup();
+ Gesture(e2, MixTarget.Volume(t), () => e2.SetTrackVolume(t, 0.33f));
+ e2.AddAudioTrack();
+ e2.EndUndoGroup();
+ e2.Undo();
+ yield return (e2.TrackCount == n0 && Vol(e2, t) == 0.7f && !e2.CanUndo,
+ $"mix undo: a group of a gesture then a track add undoes both ({e2.TrackCount} tracks, vol {Vol(e2, t)})");
+ }
+
+ private static NotaTrackInfo Info(NotaEngine e, int id)
+ {
+ for (int i = 0; i < e.TrackCount; i++)
+ if (e.TryGetTrackInfo(i, out var t) && t.Id == id) return t;
+ return default;
+ }
+ private static float Vol(NotaEngine e, int id) => Info(e, id).Volume;
+ private static float Pan(NotaEngine e, int id) => Info(e, id).Pan;
+
+ // ---- the engine API (contracts/c-abi-mix-undo.md) ---------------------------------
+
+ private static IEnumerable<(bool, string)> Gestures()
+ {
+ using var eng = new NotaEngine();
+ int t = eng.AddAudioTrack();
+ eng.ClearUndoHistory();
+ eng.SetTrackVolume(t, 0.8f); // a plain set: never a step
+ yield return (!eng.CanUndo, "mix undo: a plain volume set makes no step");
+
+ float start = Vol(eng, t);
+ int h = eng.BeginMixGesture(MixTarget.Volume(t));
+ for (int i = 1; i <= 50; i++) eng.SetTrackVolume(t, 0.8f + i * 0.0137f);
+ float last = Vol(eng, t);
+ eng.EndMixGesture(h);
+ bool one = eng.CanUndo;
+ eng.Undo();
+ bool back = Vol(eng, t) == start && !eng.CanUndo;
+ eng.Redo();
+ yield return (h > 0 && one && back && Vol(eng, t) == last,
+ $"mix undo: a 50-value drag is one step, undo restores exactly {start}, redo exactly {last} (now {Vol(eng, t)})");
+
+ eng.ClearUndoHistory();
+ eng.EndMixGesture(eng.BeginMixGesture(MixTarget.Pan(t)));
+ yield return (!eng.CanUndo, "mix undo: a gesture without a change makes no step");
+
+ float pan0 = Pan(eng, t);
+ h = eng.BeginMixGesture(MixTarget.Pan(t));
+ eng.SetTrackPan(t, 0.4f);
+ eng.SetTrackPan(t, pan0);
+ eng.EndMixGesture(h);
+ yield return (!eng.CanUndo, "mix undo: a drag back to the start value makes no step");
+
+ eng.SetMasterVolume(1f);
+ h = eng.BeginMixGesture(MixTarget.Master);
+ eng.SetMasterVolume(0.5f);
+ eng.EndMixGesture(h);
+ eng.Undo();
+ bool masterBack = eng.MasterVolume == 1f;
+ eng.Redo();
+ yield return (masterBack && eng.MasterVolume == 0.5f, $"mix undo: master volume undoes and redoes ({eng.MasterVolume})");
+
+ eng.ClearUndoHistory();
+ h = eng.BeginMixGesture(MixTarget.Volume(t));
+ eng.SetTrackVolume(t, 0.3f);
+ eng.Reset();
+ eng.EndMixGesture(h);
+ yield return (!eng.CanUndo, "mix undo: ending a gesture after a reset makes no step");
+
+ yield return (eng.BeginMixGesture(MixTarget.Volume(9999)) == 0, "mix undo: a gesture on a missing track is refused");
+ yield return (eng.MixUndoSelfTest(), "mix undo: undo/redo pass over a step whose track is gone (FR-010)");
+
+ int t2 = eng.AddAudioTrack();
+ eng.ClearUndoHistory();
+ float v2 = Vol(eng, t2);
+ MixEdit.Step(eng, () => eng.SetTrackVolume(t2, 0.25f), MixTarget.Volume(t2));
+ bool stepped = eng.CanUndo;
+ eng.Undo();
+ yield return (stepped && Vol(eng, t2) == v2 && !eng.CanUndo, $"mix undo: MixEdit.Step is one step (back to {Vol(eng, t2)}, want {v2})");
+
+ // A drag allocates nothing per move (plan: performance): 1000 values inside an open gesture.
+ var drag = new MixGesture(eng, MixTarget.Volume(t2));
+ Action<double> setter = v => eng.SetTrackVolume(t2, (float)v);
+ drag.Begin();
+ drag.Change(0.5, setter); // warm up the path (JIT, P/Invoke stub)
+ long bytes0 = GC.GetAllocatedBytesForCurrentThread();
+ for (int i = 0; i < 1000; i++) drag.Change(0.4 + i * 1e-4, setter);
+ long allocated = GC.GetAllocatedBytesForCurrentThread() - bytes0;
+ drag.End();
+ eng.Undo();
+ yield return (allocated == 0, $"mix undo: 1000 values in an open gesture allocate {allocated} bytes");
+
+ // A controller stream: one step per movement, ended by the pause (US3 scenario 3).
+ eng.ClearUndoHistory();
+ float c0 = Vol(eng, t2);
+ var knob = new MixMovement(eng, MixTarget.Volume(t2), TimeSpan.FromSeconds(1));
+ knob.Touch(() => eng.SetTrackVolume(t2, 0.3f), 0);
+ knob.Touch(() => eng.SetTrackVolume(t2, 0.35f), 400);
+ knob.Poll(1300); // 900 ms since the last touch: still moving
+ bool stillOpen = knob.IsOpen && !eng.CanUndo;
+ knob.Poll(1400); // 1 s: the movement ends → one step
+ knob.Touch(() => eng.SetTrackVolume(t2, 0.6f), 3000);
+ knob.Poll(4100);
+ eng.Undo(); bool first = Vol(eng, t2) == 0.35f;
+ eng.Undo();
+ yield return (stillOpen && first && Vol(eng, t2) == c0 && !eng.CanUndo,
+ $"mix undo: two controller movements 1.6 s apart are two steps, a continuous one is one ({Vol(eng, t2)}, want {c0})");
+ }
+}
diff --git a/tests/Nota.SmokeTest/PanLawTests.cs b/tests/Nota.SmokeTest/PanLawTests.cs
new file mode 100644
index 00000000..d2b3bdc0
--- /dev/null
+++ b/tests/Nota.SmokeTest/PanLawTests.cs
@@ -0,0 +1,475 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Project pan law (specs/006-stereo-pan-law): the law is graph data (undoable, survives every
+// edit), Stereo folds the far channel in while Balance drops it, both agree at centre and
+// for mono, groups ignore it, projects round-trip it and older ones open as Balance, and a
+// switch mid-playback does not click. Rendered from deterministic WAV clips (synth notes
+// drift between renders). Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --panlaw`.
+
+using System.Text.Json.Nodes;
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class PanLawTests
+{
+ private const int Rate = 48000;
+ private const int Utility = 4; // built-in Utility: unity gain, no tail
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in Abi()) yield return r;
+ foreach (var r in SurvivesEdits()) yield return r;
+ foreach (var r in StereoImage()) yield return r;
+ foreach (var r in ReturnsGroupsTemplate()) yield return r;
+ foreach (var r in Persistence()) yield return r;
+ foreach (var r in SwitchWithoutClick()) yield return r;
+ foreach (var r in LoadTakesLawAtOnce()) yield return r;
+ }
+
+ // What the pan stage must output for a source sample pair under `law` (research R1, the
+ // same float steps as the engine), for sample-exact comparisons.
+ private static (float l, float r) LawOut(float inL, float inR, float pan, float vol, PanLaw law)
+ {
+ double theta = (pan + 1.0) * (2 * Math.PI / 8.0), c = Math.Cos(theta), s = Math.Sin(theta);
+ if (law == PanLaw.Balance) return (inL * ((float)c * vol), inR * ((float)s * vol));
+ double b = 0.5 * Math.Abs(pan);
+ return pan <= 0
+ ? (((float)(c - b) * vol) * inL + ((float)b * vol) * inR, ((float)s * vol) * inR)
+ : (((float)c * vol) * inL, ((float)b * vol) * inL + ((float)(s - b) * vol) * inR);
+ }
+
+ // Largest per-sample error of `buf` (frames [from, to), output frame i = source frame
+ // i + offset) against LawOut of the source — in dBFS.
+ private static double NullDb(float[] buf, int from, int to, int offset, float[] srcL, float[] srcR, float pan, float vol, PanLaw law)
+ {
+ double worst = 0;
+ for (int i = from; i < to; i++)
+ {
+ var (l, r) = LawOut(srcL[i + offset], srcR[i + offset], pan, vol, law);
+ worst = Math.Max(worst, Math.Max(Math.Abs(buf[2 * i] - l), Math.Abs(buf[2 * i + 1] - r)));
+ }
+ return Db(worst);
+ }
+
+ private static float TrackVolume(NotaEngine eng, int id)
+ {
+ for (int i = 0; i < eng.TrackCount; i++)
+ if (eng.TryGetTrackInfo(i, out var t) && t.Id == id) return t.Volume;
+ return float.NaN;
+ }
+
+ // A law set without a checkpoint (project load, the new-project baseline) applies at once —
+ // no crossfade from the previous project's law (T038).
+ private static IEnumerable<(bool, string)> LoadTakesLawAtOnce()
+ {
+ var srcL = Sine(440, 1.5, Amp); var srcR = Sine(1000, 1.5, Amp);
+ var two = WriteStereoWav(srcL, srcR);
+ try
+ {
+ using var eng = new NotaEngine();
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, two, 0);
+ eng.SetTrackPan(t, -1);
+ float vol = TrackVolume(eng, t);
+ const int lead = Rate / 5, block = 256;
+ var pre = new float[lead * 2];
+ var buf = new float[block * 2];
+ eng.Seek(0);
+ eng.Play();
+ eng.RenderOffline(pre, lead, Rate); // Balance
+ eng.SetPanLaw(PanLaw.Stereo, checkpoint: false);
+ eng.RenderOffline(buf, block, Rate);
+ eng.StopTransport();
+ double err = NullDb(buf, 0, block, lead, srcL, srcR, -1, vol, PanLaw.Stereo);
+ yield return (err < -100, $"pan law: a law set by a load applies at once, no crossfade (residual {err:0} dBFS)");
+ }
+ finally { File.Delete(two); }
+ }
+
+ // ---- US3: switching mid-playback crossfades (FR-009, SC-004) -------------------------
+
+ private static IEnumerable<(bool, string)> SwitchWithoutClick()
+ {
+ var two = WriteStereoWav(Sine(440, 1.5, Amp), Sine(1000, 1.5, Amp));
+ try
+ {
+ foreach (bool flipBack in new[] { false, true })
+ {
+ using var eng = new NotaEngine();
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, two, 0);
+ eng.SetTrackPan(t, -1); // where the two laws differ most
+
+ // Render in 256-frame blocks while rolling; switch Balance → Stereo between two
+ // blocks at 0.5 s (and back one block later, mid-fade, on the second pass).
+ const int block = 256, total = Rate / block * block;
+ var buf = new float[total * 2];
+ var chunk = new float[block * 2];
+ int switchAt = Rate / 2 / block * block, backAt = switchAt + block; // back one block (5.3 ms) later
+ eng.Seek(0);
+ eng.Play();
+ for (int f = 0; f < total; f += block)
+ {
+ if (f == switchAt) eng.SetPanLaw(PanLaw.Stereo);
+ if (flipBack && f == backAt) eng.SetPanLaw(PanLaw.Balance);
+ eng.RenderOffline(chunk, block, Rate);
+ Array.Copy(chunk, 0, buf, f * 2, block * 2);
+ }
+ eng.StopTransport();
+
+ // Largest sample-to-sample step per channel: steady before, steady after, and
+ // across the switch (its 30 ms after). The switch must not outdo the steady
+ // signals by more than 1.5×.
+ double Step(int ch, int from, int to)
+ {
+ double m = 0;
+ for (int i = from + 1; i < to; i++) m = Math.Max(m, Math.Abs(buf[2 * i + ch] - buf[2 * (i - 1) + ch]));
+ return m;
+ }
+ int win = 30 * Rate / 1000;
+ bool ok = true; string detail = "";
+ for (int ch = 0; ch < 2; ch++)
+ {
+ double before = Step(ch, W0, switchAt), after = Step(ch, total - Rate / 5, total);
+ double across = Step(ch, switchAt - 1, switchAt + win);
+ ok &= across <= 1.5 * Math.Max(before, after) + 1e-6;
+ detail += $"{(ch == 0 ? "L" : " R")} {across:0.0000} vs {Math.Max(before, after):0.0000}";
+ }
+ yield return (ok, $"pan law: switching {(flipBack ? "and switching back mid-fade " : "")}while playing does not click ({detail})");
+ }
+ }
+ finally { File.Delete(two); }
+ }
+
+ // ---- US2: format v21 keeps the law; older projects open as Balance ------------------
+
+ private static IEnumerable<(bool, string)> Persistence()
+ {
+ var srcL = Sine(440, 1.5, Amp); var srcR = Sine(1000, 1.5, Amp);
+ var two = WriteStereoWav(srcL, srcR);
+ var store = new ProjectStore();
+ string Dir() => Path.Combine(Path.GetTempPath(), "nota-panlaw-" + Guid.NewGuid().ToString("N"));
+ var dirs = new List<string>();
+ try
+ {
+ // Round trip of both laws and of the older-project mark.
+ foreach (var (law, legacy) in new[] { (PanLaw.Stereo, false), (PanLaw.Balance, true) })
+ {
+ using var eng = new NotaEngine();
+ eng.AddAudioTrack();
+ eng.SetPanLaw(law);
+ string dir = Dir(); dirs.Add(dir);
+ store.Save(eng, new TransportState(120, 1, false, false, PanLawLegacy: legacy), dir);
+ using var eng2 = new NotaEngine();
+ var res = store.Load(eng2, dir);
+ yield return (eng2.PanLaw == law && res.Transport.PanLawLegacy == legacy,
+ $"pan law: save/load keeps {law}{(legacy ? " and the older-project mark" : "")} (FR-008)");
+ }
+
+ // A v20 project (no `mixer`) with a stereo track panned −0.5: opens as Balance + older
+ // project, and sounds by the Balance law — cos θ on L, sin θ on R, nothing crossed.
+ {
+ using var eng = new NotaEngine();
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, two, 0);
+ eng.SetTrackPan(t, -0.5f);
+ string dir = Dir(); dirs.Add(dir);
+ store.Save(eng, new TransportState(120, 1, false, false), dir);
+ string manifest = Path.Combine(dir, "project.json");
+ var root = (JsonObject)JsonNode.Parse(File.ReadAllText(manifest))!;
+ root.Remove("mixer");
+ root["formatVersion"] = 20;
+ File.WriteAllText(manifest, root.ToJsonString());
+
+ using var eng2 = new NotaEngine();
+ var res = store.Load(eng2, dir);
+ yield return (eng2.PanLaw == PanLaw.Balance && res.Transport.PanLawLegacy,
+ "pan law: a v20 project opens with Balance and the older-project mark (FR-006)");
+ var rendered = Render(eng2, 1.3);
+ int tid = -1;
+ for (int i = 0; i < eng2.TrackCount; i++) if (eng2.TryGetTrackInfo(i, out var ti) && ti.Id > 0) { tid = ti.Id; break; }
+ double nullDb = NullDb(rendered, W0, W1, 0, srcL, srcR, -0.5f, TrackVolume(eng2, tid), PanLaw.Balance);
+ yield return (nullDb < -120, $"pan law: …and renders sample-for-sample by the Balance law (residual {nullDb:0} dBFS, SC-002)");
+ var k = Tones(rendered);
+ double theta = (-0.5 + 1) * Math.PI / 4;
+ double ratio = Db(k[0]) - Db(k[3]), want = Db(Math.Cos(theta)) - Db(Math.Sin(theta));
+ double crossDb = Db(Math.Max(k[1], k[2])) - Db(k[3]);
+ yield return (Math.Abs(ratio - want) < 0.01 && crossDb < -90,
+ $"pan law: …and sounds by the Balance law (L/R {ratio:0.000} dB, want {want:0.000}; cross {crossDb:0} dB, SC-002)");
+ }
+
+ // The migration step itself: writes the Balance + legacy mixer, keeps an existing one.
+ var bare = ProjectMigrations.Migrate(new JsonObject { ["formatVersion"] = 20 });
+ var kept = ProjectMigrations.Migrate(new JsonObject { ["formatVersion"] = 20, ["mixer"] = new JsonObject { ["panLaw"] = "stereo" } });
+ yield return ((string?)bare["mixer"]?["panLaw"] == "balance" && (bool?)bare["mixer"]?["panLawLegacy"] == true
+ && (string?)kept["mixer"]?["panLaw"] == "stereo",
+ "pan law: migration v20 → v21 marks older projects Balance + legacy, keeps an existing mixer");
+ }
+ finally
+ {
+ File.Delete(two);
+ foreach (var d in dirs) try { if (Directory.Exists(d)) Directory.Delete(d, recursive: true); } catch (IOException) { }
+ }
+ }
+
+ // Measurement window: 1 s from 0.2 s (whole cycles of 440 Hz and 1 kHz; past any fade).
+ private const int W0 = Rate / 5, W1 = W0 + Rate;
+ private const float Amp = 0.25f; // −12 dBFS per tone
+
+ // Level of each tone on each output channel: [440 on L, 440 on R, 1k on L, 1k on R].
+ private static double[] Tones(float[] buf) => new[]
+ {
+ Goertzel(buf, 0, 440, W0, W1), Goertzel(buf, 1, 440, W0, W1),
+ Goertzel(buf, 0, 1000, W0, W1), Goertzel(buf, 1, 1000, W0, W1),
+ };
+
+ // ---- US1: Stereo moves the whole image (FR-002 … FR-005) ---------------------------
+
+ private static IEnumerable<(bool, string)> StereoImage()
+ {
+ var two = WriteStereoWav(Sine(440, 1.5, Amp), Sine(1000, 1.5, Amp)); // L = 440, R = 1 kHz
+ var mono = WriteStereoWav(Sine(440, 1.5, Amp), Sine(440, 1.5, Amp));
+ try
+ {
+ using var eng = new NotaEngine();
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, two, 0);
+
+ eng.SetPanLaw(PanLaw.Balance);
+ eng.SetTrackPan(t, 0);
+ var cBal = Render(eng, 1.3);
+ eng.SetPanLaw(PanLaw.Stereo);
+ var cSt = Render(eng, 1.3);
+ yield return (cBal.AsSpan().SequenceEqual(cSt), "pan law: at centre Stereo renders exactly as Balance (FR-003)");
+ var c = Tones(cSt); // centre: 440 on L and 1 kHz on R, each at cos(π/4)·source
+
+ foreach (var side in new[] { -1f, 1f })
+ {
+ string at = side < 0 ? "L100" : "R100";
+ eng.SetTrackPan(t, side);
+ var e = Tones(Render(eng, 1.3));
+ // The near side carries both tones at half the source amplitude = −3.01 dB under
+ // their centre level; the far side is silent.
+ double near440 = side < 0 ? e[0] : e[1], near1k = side < 0 ? e[2] : e[3];
+ double far440 = side < 0 ? e[1] : e[0], far1k = side < 0 ? e[3] : e[2];
+ double d440 = Db(near440) - Db(c[0]), d1k = Db(near1k) - Db(c[3]);
+ yield return (Math.Abs(d440 + 3.01) < 0.5 && Math.Abs(d1k + 3.01) < 0.5,
+ $"pan law: Stereo at {at} keeps both channels on the {(side < 0 ? "left" : "right")} (440 Hz {d440:+0.00;-0.00} dB, 1 kHz {d1k:+0.00;-0.00} dB re centre)");
+ double farDb = Db(Math.Max(far440, far1k)) - Db(c[0]);
+ yield return (farDb < -90, $"pan law: Stereo at {at} leaves the far side silent ({farDb:0} dB)");
+
+ double pC = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
+ double pE = e[0] * e[0] + e[1] * e[1] + e[2] * e[2] + e[3] * e[3];
+ double loss = 10 * Math.Log10(pE / pC);
+ yield return (loss > -3.5, $"pan law: unrelated L/R at {at} stays within 3.5 dB of centre ({loss:0.00} dB, FR-005)");
+ }
+
+ // Balance still drops the far channel (the legacy law is untouched).
+ eng.SetPanLaw(PanLaw.Balance);
+ eng.SetTrackPan(t, -1);
+ var b = Tones(Render(eng, 1.3));
+ yield return (Db(b[2]) - Db(c[3]) < -90, "pan law: Balance at L100 still drops the right channel");
+
+ // Mono material: Stereo == Balance at every position (FR-004).
+ eng.RemoveTrack(t);
+ int m = eng.AddAudioTrack();
+ eng.AddAudioClip(m, mono, 0);
+ double worst = 0;
+ foreach (var p in new[] { -1f, -0.6f, -0.25f, 0.3f, 0.8f, 1f })
+ {
+ eng.SetTrackPan(m, p);
+ eng.SetPanLaw(PanLaw.Balance);
+ var mb = Render(eng, 1.3);
+ eng.SetPanLaw(PanLaw.Stereo);
+ var ms = Render(eng, 1.3);
+ for (int ch = 0; ch < 2; ch++)
+ {
+ double lb = Goertzel(mb, ch, 440, W0, W1), ls = Goertzel(ms, ch, 440, W0, W1);
+ if (lb < 1e-6 && ls < 1e-6) continue; // both silent (full pan, far side)
+ worst = Math.Max(worst, Math.Abs(Db(ls) - Db(lb)));
+ }
+ }
+ yield return (worst < 0.1, $"pan law: mono sounds the same under Stereo and Balance at every pan (worst {worst:0.000} dB, FR-004)");
+ }
+ finally { File.Delete(two); File.Delete(mono); }
+ }
+
+ // ---- US1: returns follow the law, groups don't, new projects use Stereo -------------
+
+ private static IEnumerable<(bool, string)> ReturnsGroupsTemplate()
+ {
+ var two = WriteStereoWav(Sine(440, 1.5, Amp), Sine(1000, 1.5, Amp));
+ try
+ {
+ // A return panned hard left: Stereo keeps the right channel of what it receives
+ // (the 1 kHz tone reaches the left), Balance drops it. The source track is centred,
+ // so its own direct signal puts no 1 kHz on the left.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, two, 0);
+ int ret = eng.AddReturnTrack();
+ eng.AddBuiltinDevice(ret, Utility);
+ eng.SetTrackSend(t, 0, 1f);
+ eng.SetTrackPan(ret, -1);
+ eng.SetPanLaw(PanLaw.Stereo);
+ var st = Tones(Render(eng, 1.3));
+ eng.SetPanLaw(PanLaw.Balance);
+ var bal = Tones(Render(eng, 1.3));
+ double stDb = Db(st[2]) - Db(st[3]), balDb = Db(bal[2]) - Db(bal[3]);
+ yield return (stDb > -12 && balDb < -90,
+ $"pan law: a return panned L100 keeps both channels under Stereo (1 kHz on L {stDb:0.0} dB re R; Balance {balDb:0} dB)");
+ }
+
+ // A group panned −0.5 over a centred child: identical under both laws (FR-010).
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, two, 0);
+ int grp = eng.AddGroupTrack();
+ eng.SetTrackGroup(t, grp);
+ eng.SetTrackPan(grp, -0.5f);
+ eng.SetPanLaw(PanLaw.Balance);
+ var bal = Render(eng, 1.3);
+ eng.SetPanLaw(PanLaw.Stereo);
+ var st = Render(eng, 1.3);
+ yield return (bal.AsSpan().SequenceEqual(st), "pan law: group pan ignores the project law (FR-010)");
+ }
+
+ // New projects start with Stereo, and that is the baseline, not an undo step (FR-007).
+ using (var eng = new NotaEngine())
+ {
+ ProjectTemplate.ApplyDefault(eng);
+ yield return (eng.PanLaw == PanLaw.Stereo && !eng.CanUndo, "pan law: a new project starts with Stereo, not undoable (FR-007)");
+ }
+ }
+ finally { File.Delete(two); }
+ }
+
+ // ---- the law as engine state (contracts/c-abi-pan-law.md) -------------------------
+
+ private static IEnumerable<(bool, string)> Abi()
+ {
+ using var eng = new NotaEngine();
+ yield return (eng.PanLaw == PanLaw.Balance, "pan law: a fresh engine uses Balance");
+
+ int t = eng.AddAudioTrack(); // an edit to undo past
+ eng.SetPanLaw(PanLaw.Stereo);
+ yield return (eng.PanLaw == PanLaw.Stereo, "pan law: set Stereo");
+ eng.Undo();
+ bool undone = eng.PanLaw == PanLaw.Balance && eng.TrackCount == 1;
+ eng.Redo();
+ yield return (undone && eng.PanLaw == PanLaw.Stereo, "pan law: the switch is one undo step (undo → Balance, redo → Stereo)");
+
+ eng.SetPanLaw(PanLaw.Stereo); // unchanged: no new step
+ eng.Undo();
+ yield return (eng.PanLaw == PanLaw.Balance && eng.TrackCount == 1, "pan law: setting the same law adds no undo step");
+ eng.Redo();
+
+ // Without a checkpoint the Stereo state is not on the undo stack: undo lands on the
+ // Balance state from before the earlier switch, not on Stereo.
+ eng.SetPanLaw(PanLaw.Balance, checkpoint: false);
+ eng.Undo();
+ yield return (eng.PanLaw == PanLaw.Balance && eng.TrackCount == 1, "pan law: checkpoint = false adds no undo step");
+
+ bool threw = false;
+ try { eng.SetPanLaw((PanLaw)7); } catch (NotaEngineException) { threw = true; }
+ yield return (threw && eng.PanLaw == PanLaw.Balance, "pan law: an unknown law is refused");
+
+ eng.SetPanLaw(PanLaw.Stereo);
+ eng.Reset();
+ yield return (eng.PanLaw == PanLaw.Balance, "pan law: reset returns to Balance");
+ GC.KeepAlive(t);
+ }
+
+ // Graph-level fields must be carried through every fresh-graph build (inheritGraphLevel).
+ private static IEnumerable<(bool, string)> SurvivesEdits()
+ {
+ using var eng = new NotaEngine();
+ int inst = eng.AddInstrumentTrack();
+ eng.SetPanLaw(PanLaw.Stereo);
+ bool Kept() => eng.PanLaw == PanLaw.Stereo;
+
+ int audio = eng.AddAudioTrack();
+ yield return (Kept(), "pan law survives: add audio track");
+ int ret = eng.AddReturnTrack();
+ yield return (Kept(), "pan law survives: add return");
+ eng.MoveTrack(audio, 0);
+ yield return (Kept(), "pan law survives: move track");
+ int group = eng.AddGroupTrack();
+ eng.SetTrackGroup(audio, group);
+ yield return (Kept(), "pan law survives: group a track");
+ eng.AddScene();
+ yield return (Kept(), "pan law survives: add scene");
+ eng.RemoveScene(eng.SceneCount - 1);
+ yield return (Kept(), "pan law survives: remove scene");
+ int lane = eng.AddAutomationLane(inst, AutomationTarget.Volume, -1, -1);
+ eng.SetAutomationPoints(inst, lane, new[] { new AutomationPoint(0, 0.5f), new AutomationPoint(4, 1f) });
+ yield return (Kept(), "pan law survives: automation edit");
+ int mod = eng.ModulatorAdd(inst, 0);
+ if (mod >= 0) eng.CvLinkAdd(inst, mod, -1, 0);
+ yield return (Kept(), "pan law survives: modulator + CV link");
+ int clip = eng.AddMidiClip(inst, 0, 4);
+ eng.SetClipNotes(inst, clip, new[] { new NotaNote(60, 0, 1, 0.8f) });
+ yield return (Kept(), "pan law survives: MIDI clip edit");
+ eng.DuplicateTrack(inst);
+ yield return (Kept(), "pan law survives: duplicate track");
+ eng.AddBuiltinDevice(ret, Utility);
+ yield return (Kept(), "pan law survives: add device");
+ eng.RemoveTrack(audio);
+ yield return (Kept(), "pan law survives: remove track");
+ eng.Undo(); eng.Undo();
+ yield return (Kept(), "pan law survives: undo of later edits");
+ eng.Redo(); eng.Redo();
+ yield return (Kept(), "pan law survives: redo");
+ }
+
+ // ---- helpers -------------------------------------------------------------------------
+
+ private static float[] Sine(double hz, double seconds, float amp)
+ {
+ var x = new float[(int)(seconds * Rate)];
+ for (int i = 0; i < x.Length; i++) x[i] = amp * (float)Math.Sin(2 * Math.PI * hz * i / Rate);
+ return x;
+ }
+
+ private static string WriteStereoWav(float[] l, float[] r)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"nota-panlaw-{Guid.NewGuid():N}.wav");
+ var inter = new float[l.Length * 2];
+ for (int i = 0; i < l.Length; i++) { inter[2 * i] = l[i]; inter[2 * i + 1] = r[i]; }
+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(inter, l.Length);
+ return path;
+ }
+
+ private static float[] Render(NotaEngine eng, double seconds)
+ {
+ int frames = (int)(seconds * Rate);
+ var buf = new float[frames * 2];
+ eng.Seek(0);
+ eng.Play();
+ eng.RenderOffline(buf, frames, Rate);
+ eng.StopTransport();
+ return buf;
+ }
+
+ // Amplitude of a sine at `hz` on one channel of an interleaved buffer, over [from, to) frames.
+ private static double Goertzel(float[] inter, int channel, double hz, int from, int to)
+ {
+ double w = 2 * Math.PI * hz / Rate, c = 2 * Math.Cos(w), s1 = 0, s2 = 0;
+ for (int i = from; i < to; i++) { double s0 = inter[2 * i + channel] + c * s1 - s2; s2 = s1; s1 = s0; }
+ double power = s1 * s1 + s2 * s2 - c * s1 * s2;
+ return 2 * Math.Sqrt(Math.Max(0, power)) / (to - from);
+ }
+
+ private static double Db(double amp) => 20 * Math.Log10(Math.Max(amp, 1e-12));
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index e1b54059..ee5fbcd1 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -255,6 +255,30 @@ if (args.Length >= 1 && args[0] == "--returns")
Console.WriteLine(failures == 0 ? "RETURNS PASSED" : $"RETURNS FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Stereo Map measurements alone: `--stereomap`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--stereomap")
+{
+ Console.WriteLine("-- stereo map --");
+ foreach (var (ok, label) in StereoMeasureTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "STEREOMAP PASSED" : $"STEREOMAP FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+// Volume / pan undo alone: `--mixundo`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--mixundo")
+{
+ Console.WriteLine("-- mix undo --");
+ foreach (var (ok, label) in MixUndoTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "MIXUNDO PASSED" : $"MIXUNDO FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+// The project pan law alone: `--panlaw`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--panlaw")
+{
+ Console.WriteLine("-- pan law --");
+ foreach (var (ok, label) in PanLawTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "PANLAW PASSED" : $"PANLAW FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// What Nota Mosaic makes of a real library: `--mosaic-dump <file.sfz | folder>`.
if (args.Length >= 2 && args[0] == "--mosaic-dump")
{
@@ -14587,6 +14611,21 @@ foreach (var (ok, label) in ProjectTemplateTests.Run()) Check(ok, label);
Console.WriteLine("-- return delete --");
foreach (var (ok, label) in ReturnDeleteTests.Run()) Check(ok, label);
+Console.WriteLine("-- pan law --");
+foreach (var (ok, label) in PanLawTests.Run()) Check(ok, label);
+
+// The Linux JUCE message pump (.specify/bugs/linux-plugin-black-window): exported on every
+// platform and a safe no-op before any hosted plugin exists (the app ticks it on Linux).
+Console.WriteLine("-- plugin host pump --");
+Check(NotaEngine.PumpPluginHost() == 0 && NotaEngine.PumpPluginHost() == 0,
+ "plugin host pump: exported, non-blocking no-op with no plugin loaded");
+
+Console.WriteLine("-- mix undo --");
+foreach (var (ok, label) in MixUndoTests.Run()) Check(ok, label);
+
+Console.WriteLine("-- stereo map --");
+foreach (var (ok, label) in StereoMeasureTests.Run()) Check(ok, label);
+
Console.WriteLine("-- filter knob glide --");
foreach (var (ok, label) in FilterGlideTests.Run()) Check(ok, label);
diff --git a/tests/Nota.SmokeTest/RemoteTests.cs b/tests/Nota.SmokeTest/RemoteTests.cs
index ec79a282..97a60f76 100644
--- a/tests/Nota.SmokeTest/RemoteTests.cs
+++ b/tests/Nota.SmokeTest/RemoteTests.cs
@@ -409,10 +409,16 @@ internal static class RemoteTests
Send(new { t = "off", p = 65 });
Loudest(e, 30);
+ float remoteVol0 = e.TryGetTrackInfo(0, out var rv0) ? rv0.Volume : -1;
Send(new { t = "vol", id = inst, v = 0.5, ph = 2 });
Send(new { t = "mute", id = inst, on = true });
WaitFor(() => e.TryGetTrackInfo(0, out var t) && Math.Abs(t.Volume - 0.5f) < 1e-3 && t.Muted == 1 && host.Refreshes > 0);
yield return (e.TryGetTrackInfo(0, out var t1) && Math.Abs(t1.Volume - 0.5f) < 1e-3 && t1.Muted == 1, "fader and mute from the phone reach the track");
+ // A phone touch is one undo step (specs/009-mix-param-undo).
+ e.Undo();
+ e.TryGetTrackInfo(0, out var tu);
+ yield return (tu.Volume == remoteVol0, $"undo takes back the phone's fader move ({tu.Volume}, want {remoteVol0})");
+ e.Redo();
yield return (host.Refreshes > 0, "Nota redraws after a phone edit");
Send(new { t = "play" });
WaitFor(() => host.Plays == 1);
diff --git a/tests/Nota.SmokeTest/StereoMeasureTests.cs b/tests/Nota.SmokeTest/StereoMeasureTests.cs
new file mode 100644
index 00000000..ed83e563
--- /dev/null
+++ b/tests/Nota.SmokeTest/StereoMeasureTests.cs
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Stereo measurements for the Stereo Map (specs/008-stereo-map): a mono source panned to p
+// reads balance p and width 0, unrelated left/right material reads width 1 and correlation 0,
+// an anti-phase pair correlation −1, silence is below −60 dBFS, the master row matches its
+// only track, and a muted track fades out. Rendered from deterministic WAV clips. Also
+// runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --stereomap`.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class StereoMeasureTests
+{
+ private const int Rate = 48000;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in Measures()) yield return r;
+ }
+
+ private static float[] Sine(double hz, double seconds, float amp)
+ {
+ var x = new float[(int)(seconds * Rate)];
+ for (int i = 0; i < x.Length; i++) x[i] = amp * (float)Math.Sin(2 * Math.PI * hz * i / Rate);
+ return x;
+ }
+
+ private static string Wav(float[] l, float[] r)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"nota-stereo-{Guid.NewGuid():N}.wav");
+ var inter = new float[l.Length * 2];
+ for (int i = 0; i < l.Length; i++) { inter[2 * i] = l[i]; inter[2 * i + 1] = r[i]; }
+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(inter, l.Length);
+ return path;
+ }
+
+ // Play `seconds` from the start in 512-frame blocks (the averages need real blocks).
+ private static void Play(NotaEngine eng, double seconds)
+ {
+ var buf = new float[512 * 2];
+ eng.Seek(0); eng.Play();
+ for (int f = 0; f < seconds * Rate; f += 512) eng.RenderOffline(buf, 512, Rate);
+ eng.StopTransport();
+ }
+
+ private static StereoMeasure Row(NotaEngine eng, int id)
+ {
+ var rows = new StereoMeasure[64];
+ int n = eng.GetStereoMeasures(rows);
+ for (int i = 0; i < Math.Min(n, rows.Length); i++) if (rows[i].TrackId == id) return rows[i];
+ return new StereoMeasure { TrackId = -1, LevelDb = float.NaN };
+ }
+
+ private static bool Near(float a, float b, float tol) => Math.Abs(a - b) <= tol;
+
+ private static IEnumerable<(bool, string)> Measures()
+ {
+ var mono = Wav(Sine(440, 3, 0.25f), Sine(440, 3, 0.25f));
+ var pair = Wav(Sine(440, 3, 0.25f), Sine(1000, 3, 0.25f));
+ var anti = Wav(Sine(440, 3, 0.25f), Sine(440, 3, -0.25f));
+ try
+ {
+ // Mono panned L50 under the Stereo law: balance on the pan scale, no width.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ eng.SetPanLaw(PanLaw.Stereo);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, mono, 0);
+ eng.SetTrackPan(t, -0.5f);
+ Play(eng, 2.0);
+ var m = Row(eng, t);
+ yield return (Near(m.Balance, -0.5f, 0.05f) && m.Width < 0.05f && m.Correlation > 0.95f,
+ $"stereo map: mono at L50 reads balance {m.Balance:0.000}, width {m.Width:0.000}, correlation {m.Correlation:0.000}");
+ }
+
+ // Unrelated left/right material at C, alone in the project: wide, uncorrelated; the
+ // master row reads the same.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ eng.SetPanLaw(PanLaw.Stereo);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, pair, 0);
+ Play(eng, 2.0);
+ var m = Row(eng, t);
+ yield return (Near(m.Balance, 0f, 0.05f) && m.Width > 0.95f && Math.Abs(m.Correlation) < 0.05f,
+ $"stereo map: unrelated L/R at C reads balance {m.Balance:0.000}, width {m.Width:0.000}, correlation {m.Correlation:0.000}");
+ var ms = Row(eng, eng.MasterTrackId);
+ yield return (Near(ms.Balance, m.Balance, 0.05f) && Near(ms.Width, m.Width, 0.05f) && Near(ms.Correlation, m.Correlation, 0.05f),
+ $"stereo map: the master row matches its only track (width {ms.Width:0.000}, correlation {ms.Correlation:0.000})");
+
+ // Reaction (SC-005, τ = 0.3 s): muting drops the level by ≥ 20 dB within 1.5 s (the map
+ // hides a muted track's cloud at once from the mute flag); unmuting reaches within
+ // 3 dB of the steady level after 0.5 s.
+ float steady = m.LevelDb;
+ eng.SetTrackMute(t, true);
+ Play(eng, 1.5);
+ float muted = Row(eng, t).LevelDb;
+ eng.SetTrackMute(t, false);
+ Play(eng, 0.5);
+ float back = Row(eng, t).LevelDb;
+ yield return (steady - muted >= 20f && Math.Abs(back - steady) <= 3f,
+ $"stereo map: the level reacts in time (steady {steady:0.0}, muted 1.5 s {muted:0.0}, unmuted 0.5 s {back:0.0} dBFS)");
+ }
+
+ // Anti-phase pair: correlation −1, width 1.
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddAudioTrack();
+ eng.AddAudioClip(t, anti, 0);
+ Play(eng, 2.0);
+ var m = Row(eng, t);
+ yield return (m.Correlation < -0.95f && m.Width == 1f,
+ $"stereo map: an anti-phase pair reads correlation {m.Correlation:0.000}, width {m.Width:0.000}");
+ }
+
+ // Silence: an empty track and an idle master read below −60 dBFS; groups have no row.
+ using (var eng = new NotaEngine())
+ {
+ int t = eng.AddAudioTrack();
+ int g = eng.AddGroupTrack();
+ Play(eng, 0.5);
+ var m = Row(eng, t);
+ var gr = Row(eng, g);
+ yield return (m.Silent && Row(eng, eng.MasterTrackId).Silent && gr.TrackId == -1,
+ $"stereo map: silence reads {m.LevelDb:0} dBFS; groups have no row");
+ }
+ }
+ finally { File.Delete(mono); File.Delete(pair); File.Delete(anti); }
+ }
+}