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) Tempo-synced scope and key overlay in Nota Lens (#371)

Chris Laupamafedebc9767b2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 73b922b2..2dc0a49f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Tempo-synced scope in Nota Lens** (#119): the Scope view gains **Sync**, which lines the
+ trace up with the song: pick a **Span** from a quarter beat to four bars and the scope shows
+ that stretch of the beat grid, with beat and bar lines, a sweep line at the playhead and the
+ previous pass fading out to its right. It draws from a min/max history, so a one-sample
+ transient keeps its full height at any span, and a seek or loop wrap restarts the pass
+ cleanly. Lens also takes a sidechain **Key** (any other track): its waveform is drawn in teal
+ over the main one or **Stacked** under it, with its own display gain, in both the synced and
+ the triggered scope. A new button opens Lens in its own resizable window. The audio still
+ passes through untouched. Five params are appended (Sync, Span, Key, Key Gain, Layout);
+ older projects open with Sync off.
- **Band labels and notes in EQ-8** (#135): name a band in the band panel's new **Label** field
and the name shows next to its node in the graph (and on its chip); click the label, or
**Note**, for a multiline note on what the band is for. Labels that would overlap move apart,
diff --git a/specs/050-lens-tempo-scope/plan.md b/specs/050-lens-tempo-scope/plan.md
new file mode 100644
index 00000000..c3af7eb8
--- /dev/null
+++ b/specs/050-lens-tempo-scope/plan.md
@@ -0,0 +1,87 @@
+# Implementation Plan: Tempo-synced scope in Nota Lens
+
+**Branch**: `feat/lens-tempo-scope` | **Spec**: [spec.md](spec.md) | **Issue**: nota-daw/nota#119
+
+## Summary
+
+Lens learns the transport (it already gets `setTransport` / `setTransportInfo` like every
+insert), accepts a sidechain key, and keeps a min/max history of the analysis channel for the
+main signal and the key, each bin stamped with its beat. The message-thread analysis turns that
+history into a synced frame (this pass and the previous one on the beat grid) or, with Sync
+off, adds a key trace on the existing trigger. The card draws both. A pop-out window hosts the
+same body at any size.
+
+## Engine (`devices/effects/Lens.h/.cpp`)
+
+- **Params** (appended, normalized 0..1 like the rest):
+ - 37 Sync (≥ .5 on, default 0)
+ - 38 Span: 7 steps, 1/4 beat … 4 bars, default 1 bar (step 4)
+ - 39 Key (≥ .5 show, default 1)
+ - 40 Key Gain: −24..+24 dB, default 0 (.5)
+ - 41 Layout: 0 Overlay, 1 Stacked
+- **Transport**:
+ - `setTransport(beatStart, spb, playing)` keeps the block's start beat, samples per beat and
+ playing flag.
+ - `setTransportInfo(ti)` keeps the beats per bar (`tsNum × 4 / tsDenom`).
+ - Both are audio thread only, read in `process()`.
+- **Key**:
+ - `acceptsSidechain()` is true.
+ - `setSidechain(ptr, frames)` keeps the pointer for the next `process()`.
+ - The key track id is stored like the Compressor's.
+ - `process()` writes the key's L/R into two more raw rings (`ringKL_`, `ringKR_`, same size and
+ head as the main rings), so the triggered key trace lines up sample for sample. No key:
+ zeros, and `keyLive_` false.
+ - The engine's sidechain taps hand over the source's previous block, so with a key routed the
+ capture (rings + history) runs one block behind: `process()` holds the block and captures it
+ with the next call's key. Without a key nothing is held.
+- **History**:
+ - `binLen_ = max(16, round(sr / 1500))` samples per bin.
+ - `kBins = 65536` bins (≈ 43 s at any rate).
+ - Per bin: main min/max and key min/max of the analysis channel (Source / Mid-Side), its
+ start beat (double), and a flags byte (playing, key present).
+ - Fixed arrays allocated in `setSampleRate`. The audio thread writes and publishes the head
+ with release; readers take acquire and read under `mx_`. Freeze stops writing, as for the
+ rings.
+- **Synced frame** (`analyzeSync()`, under `mx_` in `ensureAnalyzed`):
+ - **Inputs**: the newest bin's beat B, span S (beats, the bar from beats per bar), window start
+ W0 = floor(B / S) × S, kSync = 1024 columns.
+ - **Walk**: back from the newest bin while bins are playing and each is one bin's worth of
+ beats before the next (a seek either way, a loop wrap or a stop ends the walk, so the pass
+ restarts).
+ - **Placement**: a bin with beat ≥ W0 goes into this pass's column. One with W0 − S ≤ beat < W0
+ goes into the previous pass's column, but only right of the playhead, and marked "previous".
+ - **Free mode**: the newest bin not playing means a rolling window of S beats at the current
+ tempo by bin count, newest at the right.
+ - **Output**: header [mode, playhead fraction, bpm, beats per bar, span beats, W0, key present,
+ 0] + per column (main min, main max, key min, key max, age 0 = this pass / 1 = previous /
+ NaN = empty) → `layerWave(L_Sync)`.
+- **Key trace (Sync off)**: `analyzeScope` builds `keyTrace_` from the key rings over the same
+ window as the main trace → `layerWave(L_KeyTrace)`.
+- **Telemetry**: `M_KeyLive` (1 = a key arrived in the last blocks) appended to `scopeRead`,
+ `kScope` 21. The MCP text (id 2) adds sync, span and key.
+- **Audio**: untouched; the new work is a min/max per sample and two more ring stores.
+
+## UI
+
+- **`LensScopeView`**:
+ - **Sync mode**: draws the synced frame. Beat lines (bar lines stronger) and the sweep line.
+ Previous-pass columns at 45 % alpha. The main as a min/max band in the graph's ink, the key
+ as teal (× key gain). Overlay or Stacked.
+ - **Sync off**: draws the key trace over the main trace (teal) when Key is on and a key is
+ live.
+- **`LensDeviceBody`**:
+ - Scope Analyze tab: **Sync** switch, **Span** segments, a **KEY** row (key source picker like
+ Prism's, Key switch, Key gain, Layout).
+ - An expand button in the centre tab bar opens `LensWindow`.
+- **`LensWindow`**: a resizable window that builds the same body with its own refresher list on a
+ 60 Hz timer, in a viewbox-free layout where the graph takes the extra space. Closed when the
+ device goes (the device chain closes open Lens windows on rebuild if the device is gone).
+
+## Testing (`--lens-sync`)
+
+- Click every beat at 120 BPM, Sync 1 bar: peaks within 1 % of the beat lines.
+- A single-sample spike keeps full height at 4 bars.
+- Stop → free mode. Seek → the pass restarts (no columns from before the seek).
+- Key routed from a click track: key columns follow it; key gain doesn't change the main.
+- Sync off + key: the key trace lines up with the main for the same signal.
+- Output bit-identical with and without Sync/key; older projects get the defaults.
diff --git a/specs/050-lens-tempo-scope/spec.md b/specs/050-lens-tempo-scope/spec.md
new file mode 100644
index 00000000..894de71f
--- /dev/null
+++ b/specs/050-lens-tempo-scope/spec.md
@@ -0,0 +1,176 @@
+# Feature Specification: Tempo-synced scope in Nota Lens
+
+**Feature Branch**: `feat/lens-tempo-scope`
+
+**Created**: 2026-10-28
+
+**Status**: Draft
+
+**Input**: User description: "Native tempo-synced oscilloscope and audio visualizer
+(nota-daw/nota#119): beat, bar and waveform views synchronized to the project tempo, main and
+sidechain overlays, mono / stereo / left / right viewing, visual-only scaling, inspection and
+freeze, bounded buffering with no added audio latency." Scope agreed with Chris (Oct 28): the
+analysis core, built into Nota Lens (as ambertape suggested on the issue): a beat/bar-synced
+scope window, a sidechain overlay, and a larger pop-out view. Themes, glow, logo overlays and a
+presentation mode stay open on the issue.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - See a bar of audio lined up with the beat (Priority: P1)
+
+A producer has a kick and a bass that feel loose. On the bass track's Lens they open the Scope
+view, turn **Sync** on and pick **1 bar**. The scope now shows exactly one bar of the bass's
+waveform from the bar line to the next, with the beats marked, redrawn as the playhead sweeps
+across it, so each note's attack lines up visibly with a beat line, or doesn't.
+
+**Why this priority**: Tempo-synced display is the core of the request; the rest builds on it.
+
+**Independent Test**: Play a project at 120 BPM with a click on every beat through Lens, Sync on
+at 1 bar: four spikes sit on the four beat lines and stay put from bar to bar.
+
+**Acceptance Scenarios**:
+
+1. **Given** the Scope view, **Then** it has a **Sync** switch and, while Sync is on, a span
+ picker: 1/4 beat, 1/2 beat, 1 beat, 2 beats, 1 bar, 2 bars, 4 bars (a bar is the project's
+ beats per bar). Off, the scope works exactly as today (time/div, trigger, cursors).
+2. **Given** Sync on and the transport playing, **Then** the scope's left edge is a multiple of
+ the span on the song's beat grid (a span of 1 bar starts on a bar line), the right edge is one
+ span later, and a sweep line at the playhead's position in the span divides this pass (left of
+ it) from the previous one (right of it), which fades.
+3. **Given** Sync on, **Then** the scope draws beat lines (bar lines stronger) and labels the span
+ ("1 bar · 120 BPM").
+4. **Given** a span longer than the raw audio Lens keeps, **Then** the trace is drawn from a
+ min/max history, so a one-sample transient still shows at its full height at any span.
+5. **Given** Sync on and the transport stopped on a track that still sounds (an instrument, or a
+ monitored input), **Then** the scope rolls freely: the newest audio at the right, the span
+ long at the current tempo, and a "free" mark in the header. A stopped audio track runs no
+ devices, so its scope holds the last pass.
+6. **Given** a tempo change, a seek, a loop wrap or a time-signature change, **Then** the next
+ frame follows the new grid: the pass restarts cleanly at the new position instead of drawing
+ audio from the old position under the new beat lines.
+7. **Given** Freeze, **Then** the synced trace holds as it is (both passes), as today's trace does.
+
+---
+
+### User Story 2 - Compare the main signal with its sidechain (Priority: P1)
+
+The producer routes the kick track to the bass track's Lens as its key (the same sidechain
+picker the Compressor uses). The kick's waveform appears over the bass's in a second colour, on
+the same synced bar, so they can see whether the bass ducks where the kick hits.
+
+**Why this priority**: Main and sidechain comparison is the second half of the core request.
+
+**Independent Test**: Route a click track as Lens's key, Sync at 1 bar, and see the key trace in
+teal over the main trace with its spikes on the beats; change the key's display gain and see only
+the key trace grow.
+
+**Acceptance Scenarios**:
+
+1. **Given** Lens on a track, **Then** it accepts a sidechain source like the Compressor does
+ (the device header's key picker); the routed track's post-FX audio is the key.
+2. **Given** a key routed, **Then** the scope draws the key trace in its own colour (teal) with
+ the main trace (the graph's neutral ink, as today), labelled "main" and the key track's name.
+3. **Given** a key routed, **Then** **Key** gain (−24 to +24 dB, display only, default 0) scales
+ only the key trace, and **Layout** picks **Overlay** (both on one axis) or **Stacked** (main on
+ top, key below, each with half the height).
+4. **Given** a key routed, **Then** a **Key** switch hides or shows the key trace; with no key
+ routed the key controls are disabled and say "no key".
+5. **Given** a key and Sync off, **Then** the key trace follows the main trace's trigger and time
+ base, so the two line up sample for sample.
+6. **Given** Source and Mid/Side, **Then** they choose the channel for both traces (L+R, L, R,
+ Mid, Side), as they do for the main trace today.
+
+---
+
+### User Story 3 - A bigger view (Priority: P2)
+
+The 700 × 260 card is too small to read one bar of a dense mix. The user clicks Lens's expand
+button and gets the same graph in its own resizable window, with the same controls, which they
+can put on a second display.
+
+**Why this priority**: The issue and ambertape's comment both ask for more room, but the synced
+scope and overlay are useful in the card already.
+
+**Independent Test**: Open the pop-out, resize it to full screen, and see the same live view
+(spectrum, scope or waterfall) and controls at the new size; delete the device and the window
+closes.
+
+**Acceptance Scenarios**:
+
+1. **Given** a Lens card, **When** the user clicks its expand button, **Then** a separate
+ resizable window opens titled after the track and device, showing the current view with the
+ view tabs and the scope controls, live.
+2. **Given** the pop-out, **When** the device or the track is removed, or the project is closed,
+ **Then** the window closes. Closing it changes nothing on the device.
+3. **Given** a change in the pop-out (a view, Sync, span, key gain), **Then** the card follows,
+ since both edit the same device params.
+
+### Edge Cases
+
+- **No tempo**: the engine always has a tempo; "free" (story 1, scenario 5) covers the stopped
+ transport.
+- **Span longer than history**: the min/max history covers at least 4 bars at 40 BPM at 192 kHz;
+ anything older than the history is drawn empty.
+- **Cost when unused**: the history is recorded only while Sync is on (and the key ring only
+ while a key is routed), so a plain Lens costs what it did before; turning Sync on starts the
+ history there, and the previous pass appears after one pass.
+- **Key timing**: the engine hands every sidechain consumer its source's previous block. With a
+ key routed, Lens captures one block behind (the held block with the key that belongs to it),
+ so the two traces line up sample for sample; the display lags by one block (about 10 ms).
+- **Key track removed**: the key trace disappears and the controls say "no key".
+- **Mono source**: L and R are the same; the trace is drawn once.
+- **Older projects**: a Lens saved before this change opens with Sync off, 1 bar, key shown at
+ 0 dB, Overlay, and no key routed; nothing else changes.
+- **Audio**: Lens still passes the audio through untouched (bit-identical, zero latency).
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Lens MUST record a min/max history of the analysis channel for the main signal and
+ for the key, with each history bin stamped with the transport's beat position and whether the
+ transport was playing, written only by the audio thread with no allocation, and read lock-free
+ (or under the existing analysis lock) by the UI.
+- **FR-002**: Lens MUST accept a sidechain source and record its audio into the key history.
+- **FR-003**: Lens MUST gain these params, appended: Sync (0/1, default 0), Span (7 steps, default
+ 1 bar), Key (show, default 1), Key Gain (−24..+24 dB, default 0), Layout (Overlay / Stacked).
+- **FR-004**: The scope MUST draw the synced window as specified in story 1 (grid-aligned span,
+ sweep, previous pass fading, beat and bar lines), from the min/max history.
+- **FR-005**: The scope MUST draw the key trace as specified in story 2, in both the synced and
+ the triggered modes.
+- **FR-006**: The Lens card MUST have an expand button that opens the pop-out of story 3.
+- **FR-007**: Lens's MCP text (get_device_text / read_analyzer) MUST report Sync, the span, the
+ key source and whether a key is arriving.
+- **FR-008**: The audio MUST pass through bit-identical and with zero latency.
+- **FR-009**: The user guide (EN and RU) MUST describe the synced scope, the key overlay and the
+ pop-out.
+
+### Key Entities
+
+- **History bin**: min and max of the analysis signal over a short run of samples (main and key),
+ with the beat position at its start and a playing flag.
+- **Synced window**: the span on the beat grid containing the playhead, plus the previous pass.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: With a click on every beat at 120 BPM and Sync at 1 bar, each click's peak is drawn
+ within 1 % of the span from its beat line.
+- **SC-002**: A single-sample spike shows at its full height at every span.
+- **SC-003**: Lens adds no audio-thread allocation and its per-block work stays within the perf
+ gate (no override).
+- **SC-004**: Rendering through Lens with and without the new features gives bit-identical
+ output.
+
+## Assumptions
+
+- The issue's presentation features (themes, glow, logo overlay, presentation mode, theme files)
+ are out of scope here and stay open on #119.
+- "Combined" waveform colouring and pre-FX taps are left out: Lens sits where it is in the chain
+ (pre/post is where you put it), and the key is the source track's post-FX audio, as for the
+ Compressor.
+- The pop-out is a plain resizable window; docking and a full-screen presentation mode are not
+ part of this.
+- GPU-specific rendering is not needed: the min/max history keeps the drawing to a few thousand
+ points per frame, like today's scope.
diff --git a/specs/050-lens-tempo-scope/tasks.md b/specs/050-lens-tempo-scope/tasks.md
new file mode 100644
index 00000000..20a2f35c
--- /dev/null
+++ b/specs/050-lens-tempo-scope/tasks.md
@@ -0,0 +1,13 @@
+# Tasks: Tempo-synced scope in Nota Lens
+
+- [x] T1 Engine: five appended params (Sync, Span, Key, Key Gain, Layout), `M_KeyLive`
+- [x] T2 Engine: transport + sidechain overrides; key rings; one-block-behind capture with a key
+- [x] T3 Engine: beat-stamped min/max history; `analyzeSync()` (synced, free, seek / wrap restart)
+- [x] T4 Engine: `L_KeyTrace` on the main trace's trigger; `L_Sync` frame; MCP text (id 2)
+- [x] T5 UI: `LensScopeView` synced frame (beat / bar grid, sweep, previous pass), key overlay,
+ Overlay / Stacked, legend
+- [x] T6 UI: Lens card Sync switch, Span segments, Key Gain knob, KEY row (source + show), Layout
+- [x] T7 UI: `LensWindow` pop-out (expand button, closes with the device / on project load)
+- [x] T8 Smoke test `--lens-sync`; Lens param / scope counts in the main run
+- [x] T9 CHANGELOG, user guide EN + RU (nota-docs)
+- [x] T10 Screenshots, macOS check
diff --git a/src/managed/Nota.App/Controls/LensViews.cs b/src/managed/Nota.App/Controls/LensViews.cs
index 1f31cbe4..79a7c064 100644
--- a/src/managed/Nota.App/Controls/LensViews.cs
+++ b/src/managed/Nota.App/Controls/LensViews.cs
@@ -30,10 +30,16 @@ namespace Nota.App;
internal sealed class LensData
{
public const int Curve = 512, TraceN = 512, WfBins = 256, WfRows = 256;
+ // The synced frame (Lens::L_Sync, specs/050): a header, then SyncCols × (main min, main
+ // max, key min, key max, age).
+ public const int SyncHead = 8, SyncCols = 1024, SyncCol = 5;
+ public const int S_Mode = 0, S_Playhead = 1, S_Bpm = 2, S_BeatsPerBar = 3, S_SpanBeats = 4, S_Start = 5, S_KeyLive = 6;
public readonly float[] Spec = new float[Curve];
public readonly float[] Peak = new float[Curve];
public readonly float[] Trace = new float[TraceN];
+ public readonly float[] KeyTrace = new float[TraceN];
+ public readonly float[] Sync = new float[SyncHead + SyncCols * SyncCol];
public readonly float[] Wf = new float[WfBins * WfRows]; // ring of rows, oldest → newest
public int WfHead; // rows written (mod WfRows = next slot)
public int WfFilled;
@@ -50,6 +56,11 @@ internal sealed class LensData
public double Bright = 0.66;
public double WfSpanSec = 12;
+ // Tempo sync + the sidechain key (specs/050).
+ public bool SyncOn, KeyOn, Stacked;
+ public double KeyGain = 1; // linear, display only
+ public string KeyName = "key";
+
public double FreqLo => 20;
public double FreqHi => Math.Min(20000, SampleRate * 0.45);
@@ -311,12 +322,19 @@ internal sealed class LensScopeView : Control
public void Tick() => InvalidateVisual();
- private double YOf(double v, double h) => h / 2 - Math.Clamp(v / Math.Max(1e-6, _d.VoltDiv * (Rows / 2.0)), -1.2, 1.2) * (h / 2);
- private double VOf(double y, double h) => (h / 2 - y) / (h / 2) * (_d.VoltDiv * (Rows / 2.0));
+ // A lane is the band of the graph one trace uses: the whole height, or with the key
+ // Stacked, the top half (main) or the bottom half (key).
+ private bool StackedNow => _d.KeyOn && _d.Stacked;
+ private (double Mid, double Half) MainLane(double h) => StackedNow ? (h / 4, h / 4) : (h / 2, h / 2);
+ private (double Mid, double Half) KeyLane(double h) => StackedNow ? (h * 3 / 4, h / 4) : (h / 2, h / 2);
+ private double YIn(double v, (double Mid, double Half) lane, double gain = 1)
+ => lane.Mid - Math.Clamp(v * gain / Math.Max(1e-6, _d.VoltDiv * (Rows / 2.0)), -1.2, 1.2) * lane.Half;
+ private double YOf(double v, double h) => YIn(v, MainLane(h));
+ private double VOf(double y, double h) { var l = MainLane(h); return (l.Mid - y) / l.Half * (_d.VoltDiv * (Rows / 2.0)); }
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
- if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed || _d.SyncOn) return; // synced: no trigger or cursors
var p = e.GetPosition(this);
double w = Bounds.Width, h = Bounds.Height;
_drag = 0;
@@ -371,26 +389,25 @@ internal sealed class LensScopeView : Control
double w = Bounds.Width, h = Bounds.Height;
if (w <= 2 || h <= 2) return;
NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+ if (_d.SyncOn) { RenderSync(ctx, w, h); return; }
for (int c = 1; c < Cols; c++)
{
double x = w * c / Cols;
ctx.DrawLine(c == Cols / 2 ? LensInk.GridStrong : LensInk.GridFaint, new Point(x, 0), new Point(x, h));
}
- for (int r = 1; r < Rows; r++)
- {
- double y = h * r / Rows;
- ctx.DrawLine(r == Rows / 2 ? LensInk.Zero : LensInk.GridFaint, new Point(0, y), new Point(w, y));
- }
+ LaneGrid(ctx, w, h);
// Afterglow: older passes fade out behind the live trace.
foreach (var (pts, age) in _d.Ghosts)
{
double k = Math.Clamp(1 - age / Math.Max(0.05, _ghostLife), 0, 1);
if (k <= 0.02) continue;
- ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.VizInk, (byte)(k * 90)), 1.2), Path(pts, w, h));
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.VizInk, (byte)(k * 90)), 1.2), Path(pts, w, MainLane(h)));
}
- ctx.DrawGeometry(null, new Pen(LensInk.Trace, 1.1 + 1.0 * _d.Bright), Path(_d.Trace, w, h));
+ ctx.DrawGeometry(null, new Pen(LensInk.Trace, 1.1 + 1.0 * _d.Bright), Path(_d.Trace, w, MainLane(h)));
+ // The sidechain key on the same trigger and time base, in the second chroma.
+ if (_d.KeyOn) ctx.DrawGeometry(null, new Pen(KeyInk, 1.0 + 0.8 * _d.Bright), Path(_d.KeyTrace, w, KeyLane(h), _d.KeyGain));
// Trigger level (draggable) + the trigger point, pinned at 25 % like a bench scope.
double ty = YOf(_d.TrigLevel, h);
@@ -419,17 +436,170 @@ internal sealed class LensScopeView : Control
LensInk.Text(ctx, "0", 4, h - 10, LensInk.Axis);
string right = Ms(_d.TimeDivSec * Cols);
LensInk.Text(ctx, right, w - LensInk.TextW(right) - 4, h - 10, LensInk.Axis);
+ Legend(ctx, h, "0");
+ }
+
+ private static SolidColorBrush KeyInk => NotaPalette.Teal;
+
+ // Horizontal divisions; Stacked, each half gets its own zero line under a divider.
+ private void LaneGrid(DrawingContext ctx, double w, double h)
+ {
+ if (!StackedNow)
+ {
+ for (int r = 1; r < Rows; r++)
+ {
+ double y = h * r / Rows;
+ ctx.DrawLine(r == Rows / 2 ? LensInk.Zero : LensInk.GridFaint, new Point(0, y), new Point(w, y));
+ }
+ return;
+ }
+ ctx.DrawLine(LensInk.GridStrong, new Point(0, h / 2), new Point(w, h / 2));
+ foreach (double y in new[] { h / 4, h * 3 / 4 }) ctx.DrawLine(LensInk.Zero, new Point(0, y), new Point(w, y));
+ }
+
+ // "main" and the key track's name, in their trace colours, when the key is drawn: after the
+ // bottom-left axis label, side by side (Overlay) or each at the foot of its lane (Stacked).
+ private void Legend(DrawingContext ctx, double h, string axisLabel)
+ {
+ if (!_d.KeyOn) return;
+ double x = 4 + LensInk.TextW(axisLabel) + 8;
+ string k = _d.KeyName + (Math.Abs(_d.KeyGain - 1) > 0.01 ? NotaNum.F($" {20 * Math.Log10(_d.KeyGain):+0.#;−0.#} dB") : "");
+ if (StackedNow)
+ {
+ LensInk.Text(ctx, "main", 4, h / 2 - 11, LensInk.Trace, 7, false);
+ LensInk.Text(ctx, k, x, h - 10, KeyInk, 7, false);
+ return;
+ }
+ LensInk.Text(ctx, "main", x, h - 10, LensInk.Trace, 7, false);
+ LensInk.Text(ctx, k, x + LensInk.TextW("main", 7, false) + 8, h - 10, KeyInk, 7, false);
+ }
+
+ // ---- tempo sync (specs/050) -----------------------------------------------------
+
+ /// <summary>"1 bar", "2 beats", "1/4 beat" for a span in beats.</summary>
+ public static string SpanName(double beats, double beatsPerBar)
+ {
+ double bars = beats / Math.Max(1, beatsPerBar);
+ if (beats > beatsPerBar - 1e-6 && Math.Abs(bars - Math.Round(bars)) < 1e-6)
+ return NotaNum.F($"{bars:0} bar{(Math.Round(bars) == 1 ? "" : "s")}");
+ if (beats < 1 - 1e-6) return NotaNum.F($"1/{Math.Round(1 / beats):0} beat");
+ return NotaNum.F($"{beats:0.##} beat{(Math.Abs(beats - 1) < 1e-6 ? "" : "s")}");
+ }
+
+ /// <summary>"5.3" — bar.beat (1-based) of a song beat.</summary>
+ public static string BarBeat(double beat, double beatsPerBar)
+ {
+ double bpb = Math.Max(1, beatsPerBar);
+ int bar = (int)Math.Floor(beat / bpb + 1e-9);
+ double inBar = beat - bar * bpb;
+ return Math.Abs(inBar - Math.Round(inBar)) < 1e-6
+ ? NotaNum.F($"{bar + 1}.{Math.Round(inBar) + 1:0}")
+ : NotaNum.F($"{bar + 1}.{inBar + 1:0.##}");
+ }
+
+ private static bool OnGrid(double beat, double step) => Math.Abs(beat / step - Math.Round(beat / step)) < 1e-6;
+
+ // The synced frame: the span on the song's grid, beat and bar lines, this pass up to the
+ // sweep line and the previous pass (faded) after it; the key in its own colour.
+ private void RenderSync(DrawingContext ctx, double w, double h)
+ {
+ var s = _d.Sync;
+ bool synced = s[LensData.S_Mode] > 0.5f;
+ double play = Math.Clamp(s[LensData.S_Playhead], 0, 1), bpm = s[LensData.S_Bpm];
+ double bpb = Math.Max(1, s[LensData.S_BeatsPerBar]), span = Math.Max(1e-3, s[LensData.S_SpanBeats]), start = s[LensData.S_Start];
+
+ // Beat lines (bar lines stronger); spans under a beat get quarters of the span.
+ double step = span <= 1 + 1e-6 ? span / 4 : 1;
+ int lines = (int)Math.Round(span / step);
+ var sub = new Pen(NotaPalette.Wash(NotaPalette.GridBeat, 0x88), 1);
+ var bar = new Pen(NotaPalette.GridBar, 1);
+ for (int k = 1; k < lines; k++)
+ {
+ double beat = start + k * step, x = w * k / lines;
+ IPen pen = !synced ? LensInk.GridFaint : OnGrid(beat, bpb) ? bar : OnGrid(beat, 1) ? LensInk.GridStrong : sub;
+ ctx.DrawLine(pen, new Point(x, 0), new Point(x, h));
+ }
+ LaneGrid(ctx, w, h);
+
+ Bands(ctx, w, 0, MainLane(h), 1, NotaPalette.VizInk);
+ if (_d.KeyOn) Bands(ctx, w, 2, KeyLane(h), _d.KeyGain, KeyInk);
+
+ if (synced)
+ {
+ double x = play * w;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0xC0), 1.2), new Point(x, 0), new Point(x, h));
+ ctx.DrawRectangle(LensInk.TraceLit, null, new Rect(x - 3.5, 0, 7, 5));
+ }
+
+ LensInk.Title(ctx, "SCOPE", NotaNum.F($"{SpanName(span, bpb)} · {bpm:0.#} BPM"));
+ string mode = synced ? "sync" : "free";
+ LensInk.Text(ctx, mode, w - LensInk.TextW(mode) - 4, 3, synced ? LensInk.TraceLit : LensInk.Axis);
+ string left = synced ? BarBeat(start, bpb) : NotaNum.F($"−{SpanName(span, bpb)}");
+ string right = synced ? BarBeat(start + span, bpb) : "now";
+ LensInk.Text(ctx, left, 4, h - 10, LensInk.Axis);
+ LensInk.Text(ctx, right, w - LensInk.TextW(right) - 4, h - 10, LensInk.Axis);
+ Legend(ctx, h, left);
+ }
+
+ // One trace of the synced frame as filled min/max bands, one pixel column at a time,
+ // this pass at full strength and the previous one at 45 %.
+ private void Bands(DrawingContext ctx, double w, int off, (double Mid, double Half) lane, double gain, SolidColorBrush ink)
+ {
+ var s = _d.Sync;
+ int cols = LensData.SyncCols, px = Math.Max(1, (int)Math.Ceiling(w));
+ foreach (int age in new[] { 1, 0 })
+ {
+ var g = new StreamGeometry();
+ bool any = false;
+ using (var gc = g.Open())
+ {
+ var top = new List<Point>();
+ var bot = new List<Point>();
+ void Flush()
+ {
+ if (top.Count == 0) return;
+ if (top.Count == 1) { top.Add(top[0] + new Point(1, 0)); bot.Add(bot[0] + new Point(1, 0)); }
+ gc.BeginFigure(top[0], true);
+ for (int i = 1; i < top.Count; i++) gc.LineTo(top[i]);
+ for (int i = bot.Count - 1; i >= 0; i--) gc.LineTo(bot[i]);
+ gc.EndFigure(true);
+ any = true;
+ top.Clear(); bot.Clear();
+ }
+ for (int x = 0; x < px; x++)
+ {
+ int c0 = (int)((long)x * cols / px), c1 = Math.Max(c0 + 1, (int)((long)(x + 1) * cols / px));
+ float lo = float.MaxValue, hi = float.MinValue;
+ bool have = false;
+ for (int c = c0; c < c1 && c < cols; c++)
+ {
+ int b = LensData.SyncHead + c * LensData.SyncCol;
+ float a = s[b + 4];
+ if (float.IsNaN(a) || (int)a != age) continue;
+ lo = Math.Min(lo, s[b + off]); hi = Math.Max(hi, s[b + off + 1]);
+ have = true;
+ }
+ if (!have) { Flush(); continue; }
+ double yHi = YIn(hi, lane, gain), yLo = YIn(lo, lane, gain);
+ if (yLo - yHi < 1) { double m = (yLo + yHi) / 2; yHi = m - 0.5; yLo = m + 0.5; } // a flat run stays visible
+ double xx = x * w / px;
+ top.Add(new Point(xx, yHi)); bot.Add(new Point(xx, yLo));
+ }
+ Flush();
+ }
+ if (any) ctx.DrawGeometry(age == 0 ? ink : NotaPalette.Wash(ink, 0x73), null, g);
+ }
}
private double _ghostLife = 0.42;
public double GhostLife { set => _ghostLife = value; }
- private Geometry Path(float[] pts, double w, double h)
+ private Geometry Path(float[] pts, double w, (double Mid, double Half) lane, double gain = 1)
{
var g = new StreamGeometry();
using var c = g.Open();
- c.BeginFigure(new Point(0, YOf(pts[0], h)), false);
- for (int i = 1; i < pts.Length; i++) c.LineTo(new Point(i * w / (pts.Length - 1), YOf(pts[i], h)));
+ c.BeginFigure(new Point(0, YIn(pts[0], lane, gain)), false);
+ for (int i = 1; i < pts.Length; i++) c.LineTo(new Point(i * w / (pts.Length - 1), YIn(pts[i], lane, gain)));
c.EndFigure(false);
return g;
}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs
index 7f0656d0..ba3ad87f 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs
@@ -34,15 +34,17 @@ internal sealed class LensDeviceBody : IDeviceBody
PersistP = 21, PersistTimeP = 22, TracesP = 23, BrightP = 24,
CursorsP = 25, CursorAP = 26, CursorBP = 27, CursorSnapP = 28,
WfSpeedP = 29, WfGainP = 30, WfFloorP = 31, WfContrastP = 32, WfOverlapP = 33,
- LogFreqP = 34, NoteGridP = 35, RateP = 36;
+ LogFreqP = 34, NoteGridP = 35, RateP = 36,
+ SyncP = 37, SpanP = 38, KeyShowP = 39, KeyGainP = 40, LayoutP = 41; // specs/050
// ── Scope telemetry (Lens::M_*) ──────────────────────────────────────────
private const int M_PeakHz = 0, M_PeakDb = 1, M_RmsDb = 2, M_LevelDb = 3, M_CrestDb = 4, M_Corr = 5,
M_Lufs = 6, M_TrigOk = 7, M_PeriodMs = 8, M_FreqHz = 9, M_Vpp = 10, M_Vrms = 11, M_WindowMs = 12,
M_BinHz = 13, M_FftN = 14, M_FftMs = 15, M_CursorAv = 16, M_CursorBv = 17, M_SampleRate = 18,
- M_Held = 19, kScope = 20;
+ M_Held = 19, M_KeyLive = 20, M_Instance = 21, kScope = 22;
- private const int L_Spectrum = 0, L_Peak = 1, L_Trace = 2, L_Raw = 3, L_Waterfall = 4;
+ private const int L_Spectrum = 0, L_Peak = 1, L_Trace = 2, L_Raw = 3, L_Waterfall = 4, L_KeyTrace = 5, L_Sync = 6;
+ private static readonly string[] SpanNames = { "¼ b", "½ b", "1 b", "2 b", "1 bar", "2 bar", "4 bar" };
private const int A_Rearm = 0, A_ResetPeak = 1, A_ResetTrigger = 2;
private static readonly int[] FftSizes = { 512, 2048, 4096, 16384 };
@@ -63,6 +65,12 @@ internal sealed class LensDeviceBody : IDeviceBody
/// <summary>The right panel's tab survives a card rebuild (keyed by track + device slot).</summary>
private static readonly Dictionary<(int, int), int> RightTab = new();
+ private readonly bool _popout;
+
+ /// <summary><paramref name="popout"/>: built for <see cref="LensWindow"/>, which gives the
+ /// graph the room and has no expand button of its own.</summary>
+ public LensDeviceBody(bool popout = false) => _popout = popout;
+
public double Width => 700;
public bool FullBleed => true;
public string? Subtitle => "Analyzer";
@@ -100,6 +108,10 @@ internal sealed class LensDeviceBody : IDeviceBody
double PersistS() => Exp(P(PersistTimeP), 0.05, 2.0);
int TraceCount() => (int)Math.Round(1 + P(TracesP) * 7);
double WfSpan() => WfSpans[Sel(WfSpeedP, 3)];
+ static double KeyDb(double v) => -24 + 48 * Math.Clamp(v, 0, 1);
+ bool scOk = engine.DeviceAcceptsSidechain(track, di);
+ int KeySrc() => scOk ? engine.DeviceSidechainSource(track, di) : -1;
+ string SrcName(int id) { string n = TrackNames.Of(engine, id); return n == "—" ? "None" : n; }
static string Ms(double sec) => sec >= 1 ? Inv($"{sec:0.00} s") : sec >= 0.001 ? Inv($"{sec * 1000:0.00} ms") : Inv($"{sec * 1e6:0} µs");
static string Sec(double s) => s >= 1 ? Inv($"{s:0.0} s") : Inv($"{s * 1000:0} ms");
@@ -247,19 +259,46 @@ internal sealed class LensDeviceBody : IDeviceBody
Control ScopeTab()
{
+ // Sync swaps the trigger chips for the span on the song's grid (specs/050).
var trig = new StackPanel
{
Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center,
Children = { Seg(TrigModeP, new[] { "Auto", "Normal", "Single" }), Seg(TrigEdgeP, new[] { "↑", "↓" }) },
};
+ var span = Seg(SpanP, SpanNames);
+ ToolTip.SetTip(span, "Span — how much of the song the scope shows, from a quarter beat to four bars");
+ var sync = Toggle(SyncP, "Sync");
+ ToolTip.SetTip(sync, "Sync — line the scope up with the song's beats and bars");
+ var caps = Caps("TRIG");
+ readouts.Add(() =>
+ {
+ bool on = On(SyncP);
+ trig.IsVisible = !on; span.IsVisible = on;
+ caps.Text = NotaText.Label(on ? "SPAN" : "TRIG");
+ });
+ var top = new DockPanel { Height = 18, LastChildFill = false, Margin = new Thickness(0, 0, 0, 4) };
+ top.Children.Add(Docked(new Border { Margin = new Thickness(0, 0, 8, 0), Child = sync }, Dock.Left));
+ top.Children.Add(Docked(caps, Dock.Left));
+ top.Children.Add(Docked(new Border { Margin = new Thickness(6, 0, 0, 0), Child = new Panel { Children = { trig, span } } }, Dock.Left));
+ scopeInfo.TextAlignment = TextAlignment.Right;
+ top.Children.Add(Docked(scopeInfo, Dock.Right));
+
+ // Time base and trigger knobs rest while Sync draws the beat grid.
+ var timeK = K(TimeDivP, "Time/Div", v => Ms(Exp(v, 0.00002, 0.02)), 34, 48);
+ var trigK = K(TrigLevelP, "Trig Lvl", v => Inv($"{(v - 0.5) * 2:+0.00;−0.00;0.00}"), 34, 48, TealC);
+ var holdK = K(HoldoffP, "Holdoff", v => Inv($"{v * 200:0} ms"), 34, 48, TealC);
+ var keyK = K(KeyGainP, "Key Gain", v => Inv($"{KeyDb(v):+0.#;−0.#;0} dB"), 34, 48, TealC);
+ ToolTip.SetTip(keyK, "Key gain — scales only the key's trace, for the eye (the sound is untouched)");
+ readouts.Add(() =>
+ {
+ bool on = On(SyncP);
+ foreach (var c in new[] { timeK, trigK, holdK }) { c.IsEnabled = !on; c.Opacity = on ? 0.4 : 1; }
+ keyK.IsEnabled = KeySrc() >= 0; keyK.Opacity = keyK.IsEnabled ? 1 : 0.4;
+ });
return GraphHost(
- TopRow("TRIG", trig, scopeInfo),
+ top,
scopeView,
- KnobRow(K(TimeDivP, "Time/Div", v => Ms(Exp(v, 0.00002, 0.02)), 34, 48),
- K(VoltDivP, "Volt/Div", v => Inv($"{Exp(v, 0.02, 2.0):0.00}"), 34, 48),
- K(TrigLevelP, "Trig Lvl", v => Inv($"{(v - 0.5) * 2:+0.00;−0.00;0.00}"), 34, 48, TealC),
- K(HoldoffP, "Holdoff", v => Inv($"{v * 200:0} ms"), 34, 48, TealC),
- scopeNote.Ctl));
+ KnobRow(timeK, K(VoltDivP, "Volt/Div", v => Inv($"{Exp(v, 0.02, 2.0):0.00}"), 34, 48), trigK, holdK, keyK, scopeNote.Ctl));
}
Control WaterfallTab() => GraphHost(
@@ -308,14 +347,67 @@ internal sealed class LensDeviceBody : IDeviceBody
Toggle(PeakHoldP, "Peak hold"),
Toggle(MidSideP, "Mid / Side"));
+ // The sidechain key (specs/050): None, or any other track's post-FX audio.
+ Control KeyRow()
+ {
+ var name = new TextBlock { FontSize = 8, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ readouts.Add(() =>
+ {
+ int src = KeySrc();
+ name.Text = !scOk ? "n/a in a rack" : src < 0 ? "no key" : SrcName(src);
+ name.Foreground = src >= 0 ? TxtC : Txt2;
+ });
+ var box = new Border
+ {
+ Height = 16, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 0),
+ Cursor = new Cursor(StandardCursorType.Hand), IsEnabled = scOk,
+ Child = new DockPanel { Children = { Docked(new Glyph(GlyphKind.ChevronDown, 8) { Foreground = MutedC, Margin = new Thickness(5, 0, 0, 0) }, Dock.Right), name } },
+ };
+ ToolTip.SetTip(box, "Key — draw another track's audio over this one, in teal");
+ box.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed || !scOk) return;
+ var fly = new MenuFlyout();
+ int cur = KeySrc();
+ void Item(string n, int id)
+ {
+ var mi = new MenuItem { Header = n, ToggleType = MenuItemToggleType.Radio, IsChecked = id == cur };
+ mi.Click += (_, _) => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); foreach (var a in readouts) a(); };
+ fly.Items.Add(mi);
+ }
+ Item("None", -1);
+ fly.Items.Add(new Separator());
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) Item(SrcName(ti.Id), ti.Id);
+ fly.ShowAt(box);
+ e.Handled = true;
+ };
+ var show = Switch("", () => On(KeyShowP), () => SetP(KeyShowP, On(KeyShowP) ? 0f : 1f), out var showSync);
+ readouts.Add(showSync);
+ Learn(show, KeyShowP);
+ ToolTip.SetTip(show, "Show the key's trace");
+ show.Margin = new Thickness(5, 0, 0, 0);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("48,*,Auto"), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps("KEY")); g.Children.Add(Col(box, 1)); g.Children.Add(Col(show, 2));
+ return g;
+ }
+
+ Control TwoToggles(Control a, Control b)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*") };
+ g.Children.Add(a); g.Children.Add(Col(b, 1));
+ return g;
+ }
+
Control ScopeAnalyze() => Stack(
+ new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), Children = { Caps("SOURCE"), Col(Seg(SourceP, new[] { "L+R", "L", "R" }), 1) } },
+ KeyRow(),
+ new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), Children = { Caps("LAYOUT"), Col(Seg(LayoutP, new[] { "Overlay", "Stacked" }), 1) } },
Row("PERSIST", PersistTimeP, v => Sec(Exp(v, 0.05, 2.0))),
Row("TRACES", TracesP, v => Inv($"{1 + v * 7:0}")),
Row("BRIGHT", BrightP, v => Pc(v)),
- new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), Children = { Caps("SOURCE"), Col(Seg(SourceP, new[] { "L+R", "L", "R" }), 1) } },
captureBox.Box,
- Toggle(PersistP, "Afterglow"),
- Toggle(CursorsP, "Cursors"));
+ TwoToggles(Toggle(PersistP, "Afterglow"), Toggle(CursorsP, "Cursors")));
Control CursorAnalyze() => Stack(
measureBox.Box,
@@ -430,8 +522,23 @@ internal sealed class LensDeviceBody : IDeviceBody
var headNote = Mono("", 7, MutedC);
var extras = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { freezeToggle, headNote } };
+ // Expand: the same body in its own resizable window (specs/050). Top-level chain only —
+ // a rack chain's Lens has no window to follow.
+ if (!_popout && engine is not System.Reflection.DispatchProxy)
+ {
+ var pop = new Border
+ {
+ Background = Brushes.Transparent, Padding = new Thickness(3), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
+ Child = new Glyph(GlyphKind.PopOut, 10) { Foreground = MutedC },
+ };
+ ToolTip.SetTip(pop, "Open Lens in its own window");
+ pop.PointerReleased += (_, e) => { LensWindow.Open(ctx, di, pop); e.Handled = true; };
+ pop.PointerPressed += (_, e) => e.Handled = true;
+ extras.Children.Add(pop);
+ }
- Control TabFrame(string[] tabs, int initial, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ Control TabFrame(string[] tabs, int initial, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl,
+ Action<Action<int>>? exposeSelect = null)
{
int sel = Math.Clamp(initial, 0, tabs.Length - 1);
var btns = new Border[tabs.Length];
@@ -471,16 +578,19 @@ internal sealed class LensDeviceBody : IDeviceBody
var barBorder = new Border { BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };
DockPanel.SetDock(barBorder, Dock.Top);
Hi(); host.Content = body(sel);
+ // Select from outside (the param moved under us): no `changed`, the caller follows.
+ exposeSelect?.Invoke(i => { if (i == sel) return; sel = i; Hi(); host.Content = body(i); });
return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
}
+ Action<int>? selectCentre = null;
var centre = TabFrame(new[] { "Spectrum", "Scope", "Waterfall" }, centreTab, centreHost, CentreBody, false, t =>
{
centreTab = t;
SetP(ViewP, t / 2f);
rightHost.Content = RightBody(rightTab == 1 ? 3 : t); // Display is shared; Analyze follows the view
foreach (var a in readouts) a();
- }, extras);
+ }, extras, s => selectCentre = s);
var rightFrame = TabFrame(new[] { "Analyze", "Display" }, rightTab, rightHost, t =>
{
@@ -552,6 +662,15 @@ internal sealed class LensDeviceBody : IDeviceBody
data.CursorSnap = On(CursorSnapP);
data.WfSpanSec = WfSpan();
+ // The view moved elsewhere (the pop-out window or the card, undo, MCP): follow it.
+ if (Sel(ViewP, 3) is var view && view != centreTab)
+ {
+ centreTab = view;
+ selectCentre?.Invoke(view);
+ rightHost.Content = RightBody(rightTab == 1 ? 3 : view);
+ foreach (var a in readouts) a();
+ }
+
if (centreTab == 0)
{
engine.DeviceLayerWave(track, di, L_Spectrum, data.Spec, LensData.Curve);
@@ -560,6 +679,13 @@ internal sealed class LensDeviceBody : IDeviceBody
}
else if (centreTab == 1)
{
+ data.SyncOn = On(SyncP);
+ data.KeyOn = On(KeyShowP) && KeySrc() >= 0 && Sc(M_KeyLive) > 0.5;
+ data.KeyGain = Math.Pow(10, KeyDb(P(KeyGainP)) / 20);
+ data.Stacked = On(LayoutP);
+ data.KeyName = KeySrc() >= 0 ? SrcName(KeySrc()) : "key";
+ if (data.SyncOn) engine.DeviceLayerWave(track, di, L_Sync, data.Sync, data.Sync.Length);
+ else if (data.KeyOn) engine.DeviceLayerWave(track, di, L_KeyTrace, data.KeyTrace, LensData.TraceN);
engine.DeviceLayerWave(track, di, L_Trace, data.Trace, LensData.TraceN);
data.AgeGhosts(dt);
if (On(PersistP))
@@ -601,12 +727,15 @@ internal sealed class LensDeviceBody : IDeviceBody
int fftN = (int)Sc(M_FftN);
string winName = new[] { "Hann", "B-H", "Flat" }[Sel(WindowP, 3)];
+ bool synced = data.SyncOn && data.Sync[LensData.S_Mode] > 0.5f;
headNote.Text = centreTab == 1
- ? (data.Held ? "Held" : data.TrigOk ? "Trig’d" : "Free")
+ ? (data.Held ? "Held" : data.SyncOn ? (synced ? "Sync" : "Free") : data.TrigOk ? "Trig’d" : "Free")
: centreTab == 2 ? Inv($"{LensData.WfBins} bins") : Inv($"FFT {fftN}");
specInfo.Text = Inv($"window {Sc(M_FftMs):0} ms · slope {P(TiltP) * 9:0.0} dB/oct");
- scopeInfo.Text = Inv($"level {(P(TrigLevelP) - 0.5) * 2:0.00} · holdoff {P(HoldoffP) * 200:0} ms");
+ scopeInfo.Text = data.SyncOn
+ ? Inv($"{LensScopeView.SpanName(data.Sync[LensData.S_SpanBeats], data.Sync[LensData.S_BeatsPerBar])} · {data.Sync[LensData.S_Bpm]:0.#} BPM{(synced ? "" : " · stopped")}")
+ : Inv($"level {(P(TrigLevelP) - 0.5) * 2:0.00} · holdoff {P(HoldoffP) * 200:0} ms");
wfInfo.Text = Inv($"floor {-120 + P(WfFloorP) * 80:0} dB · {(On(LogFreqP) ? "log" : "linear")} freq");
specNote.A.Text = Inv($"peak {Sc(M_PeakDb):0.0} dB @ {Hz(Sc(M_PeakHz))}");
@@ -625,6 +754,7 @@ internal sealed class LensDeviceBody : IDeviceBody
statusLeft.Text = centreTab switch
{
+ 1 when data.SyncOn => Inv($"Scope · sync {LensScopeView.SpanName(data.Sync[LensData.S_SpanBeats], data.Sync[LensData.S_BeatsPerBar])} · {VoltDiv():0.00}/div{(data.KeyOn ? " · key " + data.KeyName : "")}"),
1 => Inv($"Scope · {Ms(TimeDiv())}/div · {VoltDiv():0.00}/div · trig {(On(TrigEdgeP) ? "↓" : "↑")} {(P(TrigLevelP) - 0.5) * 2:0.00} {new[] { "auto", "normal", "single" }[Sel(TrigModeP, 3)]}{(On(PersistP) ? Inv($" · persist {Sec(PersistS())}") : "")}"),
2 => Inv($"Waterfall · {LensData.WfBins} bins · {winName} · overlap {Overlaps[Sel(WfOverlapP, 4)]:0.#} % · window {WfSpan():0} s · floor {-120 + P(WfFloorP) * 80:0} dB"),
_ => Inv($"Spectrum · FFT {fftN} · {winName} · avg {Avg()} · slope {P(TiltP) * 9:0.0} dB/oct{(On(MidSideP) ? " · Mid/Side" : "")}"),
diff --git a/src/managed/Nota.App/LensWindow.cs b/src/managed/Nota.App/LensWindow.cs
new file mode 100644
index 00000000..caa83baa
--- /dev/null
+++ b/src/managed/Nota.App/LensWindow.cs
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Lens popped out into its own resizable window (specs/050): the same body as the card,
+// built again over the same device, with the graph taking the extra room. Both edit the same
+// device params, so the card and the window follow each other. It closes itself when its Lens
+// (or its track) is gone, and when a project is opened or a new one started.
+
+using System;
+using System.Collections.Generic;
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Avalonia.Threading;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal sealed class LensWindow : NotaWindow
+{
+ private const int LensKind = 22, M_Instance = 21, kScope = 22;
+ private static readonly Dictionary<(int Track, int Device), LensWindow> Open_ = new();
+
+ private readonly IAudioEngine _engine;
+ private readonly int _trackId, _device;
+ private readonly List<Action> _ticks = new();
+ private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromMilliseconds(16) };
+ private readonly float[] _scope = new float[kScope];
+ private readonly float _instance; // the Lens's serial: another Lens shifted to this index isn't it
+
+ private LensWindow(DeviceCardContext card, int device)
+ {
+ _engine = card.Engine; _trackId = card.TrackId; _device = device;
+ _instance = Instance();
+ Title = $"Nota Lens · {TrackNames.Of(_engine, _trackId)}";
+ Width = 1100; Height = 520; MinWidth = 640; MinHeight = 260;
+ CanResize = true;
+ ShowInTaskbar = false;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner;
+ // A context of its own: the window ticks its body; a sidechain change still reaches the
+ // track headers through the card's context.
+ var ctx = new DeviceCardContext(_engine, _trackId, _ticks.Add, card.NotifyChanged, (_, _, _, _) => { }, _ => { }, _ => { },
+ () => 0, _ => { }, _ => { }, () => { }, () => { }, _ => { }, () => { }, card.Factory);
+ SetBody(new LensDeviceBody(popout: true).Build(ctx, device));
+ _timer.Tick += (_, _) => Tick();
+ Opened += (_, _) => _timer.Start();
+ Closed += (_, _) => { _timer.Stop(); Open_.Remove((_trackId, _device)); };
+ }
+
+ /// <summary>Open (or bring forward) the window of the Lens at <paramref name="device"/> on
+ /// the card's track.</summary>
+ public static void Open(DeviceCardContext card, int device, Control anchor)
+ {
+ if (Open_.TryGetValue((card.TrackId, device), out var w)) { w.Activate(); return; }
+ w = new LensWindow(card, device);
+ Open_[(card.TrackId, device)] = w;
+ // After the click has finished, owned by the window that holds the card.
+ var owner = TopLevel.GetTopLevel(anchor) as Window;
+ Dispatcher.UIThread.Post(() => { w.ShowOver(owner); w.Activate(); }, DispatcherPriority.Background);
+ }
+
+ /// <summary>A new or reopened project reuses track ids: close every Lens window.</summary>
+ public static void CloseAll()
+ {
+ foreach (var w in new List<LensWindow>(Open_.Values)) w.Close();
+ Open_.Clear();
+ }
+
+ private float Instance() =>
+ _engine.TrackDeviceBuiltinKind(_trackId, _device) == LensKind && _engine.DeviceScope(_trackId, _device, _scope, kScope) >= kScope
+ ? _scope[M_Instance] : -1f;
+
+ private void Tick()
+ {
+ if (_instance < 0 || Instance() != _instance) { Close(); return; } // deleted, moved, or another Lens took its place
+ for (int i = 0; i < _ticks.Count; i++) _ticks[i]();
+ }
+
+ private void ShowOver(Window? owner)
+ {
+ owner ??= (Avalonia.Application.Current?.ApplicationLifetime as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime)?.MainWindow;
+ if (owner is null) { Show(); return; }
+ if (owner is MainWindow mw)
+ {
+ AddHandler(KeyDownEvent, (_, e) => mw.HandleTransportKeyTunnel(e), RoutingStrategies.Tunnel);
+ KeyDown += (_, e) => { if (!e.Handled) mw.HandleFloatingKeyDown(e); };
+ KeyUp += (_, e) => { if (!e.Handled) mw.HandleKeyUp(e); };
+ }
+ Show(owner);
+ }
+}
diff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.cs
index 08be1e66..773954ba 100644
--- a/src/managed/Nota.App/MainWindow.Files.cs
+++ b/src/managed/Nota.App/MainWindow.Files.cs
@@ -452,6 +452,7 @@ public partial class MainWindow
CloseDetail(); // collapse the docked row too, not just hide the panel
_deviceChain?.ForgetCardState(); // per-track preset labels belong to the old project
_modular?.ForgetScopes(); // so do frozen Scope traces and Scope windows
+ LensWindow.CloseAll(); // and Lens windows
TrackArming.ForgetSelection(); // the arm-on-select memory too
Timeline.Refresh();
_session?.Refresh();
diff --git a/src/native/nota.engine/src/devices/effects/Lens.cpp b/src/native/nota.engine/src/devices/effects/Lens.cpp
index 56cf72f1..bef34545 100644
--- a/src/native/nota.engine/src/devices/effects/Lens.cpp
+++ b/src/native/nota.engine/src/devices/effects/Lens.cpp
@@ -49,15 +49,30 @@ Lens::Lens() {
p_[LogFreq].store(1.0f);
p_[NoteGrid].store(0.0f);
p_[Rate].store(0.4f); // 30 fps
+ p_[Sync].store(0.0f);
+ p_[Span].store(4.0f / 6.0f); // 1 bar
+ p_[KeyShow].store(1.0f);
+ p_[KeyGain].store(0.5f); // 0 dB
+ p_[Layout].store(0.0f); // Overlay
setSampleRate(44100.0, 0);
}
-void Lens::setSampleRate(double sr, int32_t /*maxBlock*/) {
+void Lens::setSampleRate(double sr, int32_t maxBlock) {
std::lock_guard<std::mutex> lock(mx_);
sr_ = sr > 0 ? sr : 44100.0;
ringL_.assign(kRing, 0.0f);
ringR_.assign(kRing, 0.0f);
+ ringKL_.assign(kRing, 0.0f);
+ ringKR_.assign(kRing, 0.0f);
ringW_.store(0, std::memory_order_relaxed);
+ bins_.assign(kBins, Bin{});
+ binW_.store(0, std::memory_order_relaxed);
+ binLen_ = std::max(16, (int)std::lround(sr_ / 1500.0));
+ binN_ = 0;
+ pend_.assign((size_t)std::max(maxBlock, 8192) * 2, 0.0f);
+ pendN_ = 0;
+ keyTrace_.assign(kTrace, 0.0f);
+ sync_.assign(kSyncHead + kSync * kSyncCol, 0.0f);
curve_.assign(kCurve, -200.0f);
peak_.assign(kCurve, -200.0f);
peakAge_.assign(kCurve, 0.0f);
@@ -82,13 +97,89 @@ void Lens::setSampleRate(double sr, int32_t /*maxBlock*/) {
}
// Analyzer: the signal passes through untouched.
+void Lens::capture(const float* main, const float* key, int32_t keyFrames, int32_t frames, double beat0, double spb,
+ bool playing, bool hist) {
+ const bool ms = msOn();
+ const int src = srcIdx();
+ auto sel = [ms, src](float l, float r) {
+ if (ms) return src == 2 ? 0.5f * (l - r) : 0.5f * (l + r);
+ return src == 1 ? l : src == 2 ? r : 0.5f * (l + r);
+ };
+ const uint8_t flags = (uint8_t)((playing && spb > 0.0 ? kBinPlaying : 0) | (key ? kBinKey : 0) | chanBits(ms, src));
+ uint32_t w = ringW_.load(std::memory_order_relaxed);
+ for (int32_t i = 0; i < frames; ++i) {
+ const float l = main[i * 2], r = main[i * 2 + 1];
+ const bool haveKey = key && i < keyFrames;
+ const float kl = haveKey ? key[i * 2] : 0.0f, kr = haveKey ? key[i * 2 + 1] : 0.0f;
+ ringL_[w & (kRing - 1)] = l;
+ ringR_[w & (kRing - 1)] = r;
+ ringKL_[w & (kRing - 1)] = kl;
+ ringKR_[w & (kRing - 1)] = kr;
+ ++w;
+ // The beat-stamped min/max history.
+ if (!hist) continue;
+ if (binN_ == 0) {
+ acc_.beat = spb > 0.0 ? beat0 + (playing ? i / spb : 0.0) : beat0;
+ acc_.spb = spb;
+ acc_.sample = w - 1;
+ acc_.flags = flags;
+ acc_.mLo = acc_.kLo = 1e9f;
+ acc_.mHi = acc_.kHi = -1e9f;
+ }
+ const float a = sel(l, r), k = sel(kl, kr);
+ acc_.mLo = std::min(acc_.mLo, a);
+ acc_.mHi = std::max(acc_.mHi, a);
+ acc_.kLo = std::min(acc_.kLo, k);
+ acc_.kHi = std::max(acc_.kHi, k);
+ if (++binN_ >= binLen_) {
+ const uint32_t bw = binW_.load(std::memory_order_relaxed);
+ bins_[bw & (kBins - 1)] = acc_;
+ binW_.store(bw + 1, std::memory_order_release);
+ binN_ = 0;
+ }
+ }
+ ringW_.store(w, std::memory_order_release);
+}
+
void Lens::process(float* buf, int32_t frames) {
const bool frozen = get(Freeze) >= 0.5f;
+ // The key (specs/050): the engine hands it over before each process(), one block late.
+ const float* key = scBuf_ && scFrames_ > 0 ? scBuf_ : nullptr;
+ const int32_t keyN = scFrames_;
+ scBuf_ = nullptr;
+ const bool keyed = scTrackId_.load(std::memory_order_relaxed) >= 0;
+ const bool sync = get(Sync) >= 0.5f;
+ // A key routed from now: no earlier key in its ring. Sync turned on: a fresh bin.
+ if (keyed && !keyedPrev_) {
+ std::fill(ringKL_.begin(), ringKL_.end(), 0.0f);
+ std::fill(ringKR_.begin(), ringKR_.end(), 0.0f);
+ }
+ if (sync && !syncPrev_) binN_ = 0;
+ keyedPrev_ = keyed;
+ syncPrev_ = sync;
+ // The plain scope (no key, no Sync) only fills the main ring, in the loop below.
+ const bool lean = !frozen && !keyed && !sync;
+ const bool delay = keyed && (size_t)frames * 2 <= pend_.size();
+ if (frozen || lean)
+ pendN_ = 0;
+ else if (delay) {
+ // The bus holds the source's previous block: as long as the held one, whatever this one is.
+ if (pendN_ > 0) capture(pend_.data(), key, key ? pendN_ : 0, pendN_, pendBeat_, pendSpb_, pendPlaying_, sync);
+ std::copy(buf, buf + (size_t)frames * 2, pend_.begin());
+ pendN_ = frames;
+ pendBeat_ = beat0_;
+ pendSpb_ = spb_;
+ pendPlaying_ = playing_;
+ } else {
+ pendN_ = 0;
+ capture(buf, key, keyN, frames, beat0_, spb_, playing_, sync);
+ }
+
double corrLR = 0, corrLL = 0, corrRR = 0;
uint32_t w = ringW_.load(std::memory_order_relaxed);
for (int32_t i = 0; i < frames; ++i) {
const float l = buf[i * 2], r = buf[i * 2 + 1];
- if (!frozen) {
+ if (lean) {
ringL_[w & (kRing - 1)] = l;
ringR_[w & (kRing - 1)] = r;
++w;
@@ -106,17 +197,18 @@ void Lens::process(float* buf, int32_t frames) {
lufsN_ = 0;
double sum = 0;
for (double e : lufsRing_) sum += e;
- const double ms = sum / kLufsBlocks;
- lufs_.store(ms > 1e-12 ? (float)(-0.691 + 10.0 * std::log10(ms)) : -120.0f, std::memory_order_relaxed);
+ const double msq = sum / kLufsBlocks;
+ lufs_.store(msq > 1e-12 ? (float)(-0.691 + 10.0 * std::log10(msq)) : -120.0f, std::memory_order_relaxed);
}
}
- if (!frozen) ringW_.store(w, std::memory_order_relaxed);
+ if (lean) ringW_.store(w, std::memory_order_release);
if (corrLL > 1e-12 && corrRR > 1e-12) {
const float c = (float)(corrLR / std::sqrt(corrLL * corrRR));
const float prev = corr_.load(std::memory_order_relaxed);
corr_.store(prev + 0.2f * (c - prev), std::memory_order_relaxed);
}
- frameSeq_.fetch_add(1, std::memory_order_relaxed);
+ const uint32_t seq = frameSeq_.fetch_add(1, std::memory_order_relaxed) + 1;
+ if (key) keySeen_.store(seq, std::memory_order_relaxed);
}
int32_t Lens::scopeRead(float* out, int32_t maxSamples) const {
@@ -143,6 +235,8 @@ int32_t Lens::scopeRead(float* out, int32_t maxSamples) const {
out[M_CursorBv] = traceAt(get(CursorB));
out[M_SampleRate] = (float)sr_;
out[M_Held] = (get(Freeze) >= 0.5f || (trigModeIdx() == 2 && singleDone_)) ? 1.0f : 0.0f;
+ out[M_KeyLive] = keyLive() ? 1.0f : 0.0f;
+ out[M_Instance] = (float)instance_;
return kScope;
}
@@ -156,6 +250,8 @@ int32_t Lens::layerWave(int32_t layer, float* out, int32_t maxSamples) const {
case L_Trace: return copyOut(trace_.data(), kTrace, out, maxSamples);
case L_Raw: return copyOut(rawWin_.data(), rawLen_, out, maxSamples);
case L_Waterfall: return copyOut(wfRow_.data(), kWfBins, out, maxSamples);
+ case L_KeyTrace: return copyOut(keyTrace_.data(), kTrace, out, maxSamples);
+ case L_Sync: return copyOut(sync_.data(), kSyncHead + kSync * kSyncCol, out, maxSamples);
default: return 0;
}
}
@@ -207,7 +303,14 @@ std::string Lens::deviceText(int32_t id) const {
std::snprintf(b, sizeof b, "trigger %s · window %.2f ms · period %.3f ms (%.1f Hz) · Vpp %.3f · Vrms %.3f",
trigOk_ ? "locked" : "free-run", winMs, mPeriodMs_, mPeriodMs_ > 1e-6f ? 1000.0f / mPeriodMs_ : 0.0f, mVpp_,
mVrms_);
- return b;
+ std::string s = b;
+ // Tempo sync and the key (specs/050).
+ static const char* spans[7] = {"1/4 beat", "1/2 beat", "1 beat", "2 beats", "1 bar", "2 bars", "4 bars"};
+ std::snprintf(b, sizeof b, " · sync %s (%s, %s) · key %s%s, %+.1f dB, %s", get(Sync) >= 0.5f ? "on" : "off",
+ spans[step(get(Span), 7)], sync_[S_Mode] > 0.5f ? "on the beat grid" : "free",
+ scTrackId_.load(std::memory_order_relaxed) >= 0 ? (keyLive() ? "arriving" : "routed, silent") : "none",
+ get(KeyShow) >= 0.5f ? "" : " (hidden)", keyGainDb(get(KeyGain)), get(Layout) >= 0.5f ? "stacked" : "overlay");
+ return s + b;
}
case 3: { // strongest spectral peaks, with note names
std::string s;
@@ -268,6 +371,11 @@ const char* Lens::paramName(int32_t i) const {
"Display Log Freq",
"Display Note Grid",
"Display Rate",
+ "Scope Sync",
+ "Scope Span",
+ "Scope Key",
+ "Scope Key Gain",
+ "Scope Layout",
};
return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
@@ -334,6 +442,7 @@ void Lens::ensureAnalyzed() const {
analyzeSpectrum(dt);
analyzeScope();
+ analyzeSync();
}
void Lens::analyzeSpectrum(double dt) const {
@@ -558,6 +667,13 @@ void Lens::analyzeScope() const {
if (std::fabs(v) > std::fabs(best)) best = v;
}
trace_[(size_t)i] = best;
+ // The key over the same window, so the two line up sample for sample (specs/050).
+ float kb = 0;
+ for (int j = a; j < b && j < win; ++j) {
+ const float v = pickKey(s0 + (uint32_t)j, ms, src);
+ if (std::fabs(v) > std::fabs(kb)) kb = v;
+ }
+ keyTrace_[(size_t)i] = kb;
}
for (int i = 0; i < rawLen_; ++i) {
const float v = rawWin_[(size_t)i];
@@ -635,4 +751,160 @@ std::string Lens::noteName(double hz) {
return b;
}
+// The synced frame (specs/050). With the transport playing, the window is the span on the
+// beat grid that holds the playhead: columns left of the playhead are this pass, the rest the
+// previous pass. The history is walked back only while it is one continuous run (playing, beats
+// falling): a seek, a loop wrap or a stop ends it, so the pass restarts cleanly. Stopped, the
+// window rolls: the last span of audio at the current tempo, newest at the right. Short spans
+// read the raw rings, longer ones the min/max bins, so a transient keeps its height.
+void Lens::analyzeSync() const {
+ if (get(Freeze) >= 0.5f || get(Sync) < 0.5f) return; // hold the frame; Sync off nobody reads it
+ float* h = sync_.data();
+ float* col = h + kSyncHead;
+ const float nan = std::nanf("");
+ for (int i = 0; i < kSync * kSyncCol; ++i) col[i] = nan;
+ const uint32_t head = binW_.load(std::memory_order_acquire);
+ const double bpb = bpb_.load(std::memory_order_relaxed);
+ const double S = spanBeats(get(Span), bpb);
+ const bool keyOn = keyLive();
+ h[S_BeatsPerBar] = (float)bpb;
+ h[S_SpanBeats] = (float)S;
+ h[S_KeyLive] = keyOn ? 1.0f : 0.0f;
+ h[S_Mode] = 0.0f;
+ h[S_Playhead] = 1.0f;
+ h[S_Start] = 0.0f;
+ h[S_Bpm] = 120.0f;
+ if (head == 0) return;
+ const uint32_t mask = kBins - 1;
+ const Bin& nb = bins_[(head - 1) & mask];
+ const double spb = nb.spb > 0.0 ? nb.spb : sr_ * 0.5; // 120 BPM when the engine gave none
+ h[S_Bpm] = (float)(60.0 * sr_ / spb);
+ const bool ms = msOn();
+ const int src = srcIdx();
+ const uint8_t chan = chanBits(ms, src);
+ auto sameChan = [chan](const Bin& b) { return (b.flags & kBinChan) == chan; };
+ const uint32_t ringHead = ringW_.load(std::memory_order_acquire);
+ const uint32_t newestEnd = nb.sample + (uint32_t)binLen_; // one past the newest bin's last sample
+
+ auto put = [&](int c, float mLo, float mHi, float kLo, float kHi, float age) {
+ float* v = col + (size_t)c * kSyncCol;
+ if (std::isnan(v[4])) {
+ v[0] = mLo;
+ v[1] = mHi;
+ v[2] = kLo;
+ v[3] = kHi;
+ v[4] = age;
+ return;
+ }
+ v[0] = std::min(v[0], mLo);
+ v[1] = std::max(v[1], mHi);
+ v[2] = std::min(v[2], kLo);
+ v[3] = std::max(v[3], kHi);
+ };
+ // Samples [a, b) of the raw rings into column c (b > a), if they are still in the ring.
+ auto putRaw = [&](int c, uint32_t a, uint32_t b, float age) {
+ if ((int32_t)(ringHead - b) < 0 || ringHead - a > (uint32_t)(kRing - 16)) return false;
+ float mLo = 1e9f, mHi = -1e9f, kLo = 1e9f, kHi = -1e9f;
+ for (uint32_t t = a; t != b; ++t) {
+ const float m = pick(t, ms, src), k = pickKey(t, ms, src);
+ mLo = std::min(mLo, m);
+ mHi = std::max(mHi, m);
+ kLo = std::min(kLo, k);
+ kHi = std::max(kHi, k);
+ }
+ put(c, mLo, mHi, kLo, kHi, age);
+ return true;
+ };
+ const uint32_t depth = std::min<uint32_t>(head, kBins - 1);
+
+ if (!(nb.flags & kBinPlaying)) {
+ // Free: the last S beats at this tempo, rolling.
+ const double span = S * spb;
+ if (span + 64 < kRing) {
+ const uint32_t n = std::max<uint32_t>(1, (uint32_t)std::lround(span));
+ for (int c = 0; c < kSync; ++c) {
+ const uint32_t a = newestEnd - n + (uint32_t)((uint64_t)n * c / kSync);
+ const uint32_t b = std::max(a + 1, newestEnd - n + (uint32_t)((uint64_t)n * (c + 1) / kSync));
+ putRaw(c, a, b, 0.0f);
+ }
+ } else {
+ // Scaled by the span asked for: history it doesn't have yet stays empty on the left.
+ const uint32_t want = std::max<uint32_t>(1, (uint32_t)(span / binLen_));
+ const uint32_t nBins = std::min<uint32_t>(depth, want);
+ for (uint32_t k = 0; k < nBins; ++k) {
+ const Bin& b = bins_[(head - 1 - k) & mask];
+ if (!sameChan(b)) break;
+ const double x0 = 1.0 - (double)(k + 1) / want, x1 = 1.0 - (double)k / want;
+ const int c0 = std::clamp((int)(x0 * kSync), 0, kSync - 1), c1 = std::clamp((int)std::ceil(x1 * kSync) - 1, c0, kSync - 1);
+ for (int c = c0; c <= c1; ++c) put(c, b.mLo, b.mHi, b.kLo, b.kHi, 0.0f);
+ }
+ }
+ return;
+ }
+
+ // Synced: B is where the newest audio ends, W0 the window's start on the grid.
+ const double B = nb.beat + binLen_ / spb;
+ const double W0 = std::floor(B / S + 1e-9) * S;
+ const double play = std::clamp((B - W0) / S, 0.0, 1.0);
+ h[S_Mode] = 1.0f;
+ h[S_Playhead] = (float)play;
+ h[S_Start] = (float)W0;
+
+ // Bin k (newest first) still follows bin k-1 on the song's timeline: playing, and one bin's
+ // worth of beats earlier. A loop wrap or a seek either way ends the run.
+ auto follows = [&](const Bin& b, double later) {
+ if (!(b.flags & kBinPlaying)) return false;
+ const double step = binLen_ / (b.spb > 0.0 ? b.spb : spb), d = later - b.beat;
+ return d > 0.0 && d < step * 1.5 + 1e-9;
+ };
+
+ // The continuous run back from now: where it starts (in beats).
+ double validFrom = nb.beat, prev = nb.beat;
+ for (uint32_t k = 1; k < depth; ++k) {
+ const Bin& b = bins_[(head - 1 - k) & mask];
+ if (!follows(b, prev)) break;
+ prev = b.beat;
+ validFrom = b.beat;
+ if (b.beat < W0 - S) break;
+ }
+
+ if (2.0 * S * spb + 64 < kRing) {
+ // Short span: each column's beats → samples on the newest bin's tempo.
+ for (int pass = 0; pass < 2; ++pass) {
+ const double base = W0 - pass * S;
+ for (int c = 0; c < kSync; ++c) {
+ const double x0 = (double)c / kSync, x1 = (double)(c + 1) / kSync;
+ if (pass == 0 && x0 >= play) break; // not played yet in this pass
+ if (pass == 1 && x1 <= play) continue; // overwritten by this pass
+ const double b0 = base + x0 * S, b1 = base + std::min(x1, pass == 0 ? play : 1.0) * S;
+ if (b0 < validFrom) continue;
+ // Half-open [s0, s1): a click on a column edge lands in one column only.
+ const int64_t s0 = (int64_t)std::floor((b0 - nb.beat) * spb + 1e-6), s1 = (int64_t)std::floor((b1 - nb.beat) * spb + 1e-6);
+ const uint32_t a = nb.sample + (uint32_t)s0, e = nb.sample + (uint32_t)std::max<int64_t>(s0 + 1, s1);
+ putRaw(c, a, e, (float)pass);
+ }
+ }
+ return;
+ }
+
+ // Long span: place each bin of the run by its own beat.
+ for (uint32_t k = 0; k < depth; ++k) {
+ const Bin& b = bins_[(head - 1 - k) & mask];
+ if (!sameChan(b) || (k > 0 && !follows(b, prev))) break; // the raw path above reads any channel
+ prev = b.beat;
+ const double e = b.beat + binLen_ / (b.spb > 0.0 ? b.spb : spb);
+ if (b.beat < W0 - S) break;
+ // Columns [x0, x1) of a pass; a bin that straddles the window's start feeds both.
+ auto place = [&](double x0, double x1, int pass) {
+ if (x1 <= 0.0 || x0 >= 1.0) return;
+ int c0 = std::clamp((int)(x0 * kSync), 0, kSync - 1);
+ const int c1 = std::clamp((int)std::ceil(x1 * kSync) - 1, c0, kSync - 1);
+ if (pass == 1) c0 = std::max(c0, (int)std::ceil(play * kSync)); // right of the sweep only
+ for (int c = c0; c <= c1; ++c) put(c, b.mLo, b.mHi, b.kLo, b.kHi, (float)pass);
+ };
+ if (e > W0) place((b.beat - W0) / S, (e - W0) / S, 0);
+ if (b.beat < W0) place((b.beat - (W0 - S)) / S, (e - (W0 - S)) / S, 1);
+ }
+}
+
} // namespace nota
diff --git a/src/native/nota.engine/src/devices/effects/Lens.h b/src/native/nota.engine/src/devices/effects/Lens.h
index e0134e43..79e10e57 100644
--- a/src/native/nota.engine/src/devices/effects/Lens.h
+++ b/src/native/nota.engine/src/devices/effects/Lens.h
@@ -91,6 +91,13 @@ class Lens : public Device {
LogFreq, // >= .5 logarithmic frequency axis
NoteGrid, // >= .5 draw the note grid
Rate, // display refresh, 10..60 fps
+
+ // Tempo-synced scope and the key overlay (specs/050), appended.
+ Sync, // >= .5 the scope spans beats on the song's grid
+ Span, // 7 steps: 1/4 beat, 1/2 beat, 1 beat, 2 beats, 1 bar, 2 bars, 4 bars
+ KeyShow, // >= .5 draw the sidechain key's trace
+ KeyGain, // −24..+24 dB, display only
+ Layout, // < .5 Overlay · >= .5 Stacked
kNumParams
};
@@ -115,12 +122,20 @@ class Lens : public Device {
M_CursorAv, // trace value under cursor A / B
M_CursorBv,
M_SampleRate,
- M_Held, // 1 = frozen or a finished Single capture
+ M_Held, // 1 = frozen or a finished Single capture
+ M_KeyLive, // 1 = a sidechain key is arriving (specs/050)
+ M_Instance, // this Lens's serial, so a window can tell it from another Lens at its index
kScope
};
// layerWave layers.
- enum { L_Spectrum = 0, L_Peak, L_Trace, L_Raw, L_Waterfall };
+ // L_KeyTrace: the key over the main trace's window (Sync off). L_Sync: the synced frame —
+ // kSyncHead header values (S_*), then kSync columns of (main min, main max, key min,
+ // key max, age: 0 this pass · 1 the previous pass · NaN empty).
+ enum { L_Spectrum = 0, L_Peak, L_Trace, L_Raw, L_Waterfall, L_KeyTrace, L_Sync };
+ enum { S_Mode = 0, S_Playhead, S_Bpm, S_BeatsPerBar, S_SpanBeats, S_Start, S_KeyLive, kSyncHead = 8 };
+ static constexpr int kSync = 1024; // columns in a synced frame
+ static constexpr int kSyncCol = 5; // values per column
// deviceAction ids.
enum { A_Rearm = 0, A_ResetPeak, A_ResetTrigger };
@@ -155,6 +170,30 @@ class Lens : public Device {
// ---- unit helpers, shared with the card so both read the same numbers ----
static double timeDivSec(float v) { return expMap(v, 0.00002, 0.02); }
static double voltDiv(float v) { return expMap(v, 0.02, 2.0); }
+ // Span in beats for a Span param value; a "bar" is beatsPerBar beats.
+ static double spanBeats(float v, double beatsPerBar) {
+ static const double b[7] = {0.25, 0.5, 1, 2, -1, -2, -4}; // negative = bars
+ const double x = b[step(v, 7)];
+ return x > 0 ? x : -x * std::max(1.0, beatsPerBar);
+ }
+ static double keyGainDb(float v) { return -24.0 + 48.0 * std::clamp((double)v, 0.0, 1.0); }
+
+ // Tempo sync + the sidechain key (specs/050). Audio thread.
+ void setTransport(double beatStart, double samplesPerBeat, bool playing) override {
+ beat0_ = beatStart;
+ spb_ = samplesPerBeat;
+ playing_ = playing;
+ }
+ void setTransportInfo(const TransportInfo& ti) override {
+ bpb_.store(ti.tsDenom > 0 ? ti.tsNum * 4.0 / ti.tsDenom : 4.0, std::memory_order_relaxed);
+ }
+ int32_t sidechainSourceTrackId() const override { return scTrackId_.load(std::memory_order_relaxed); }
+ void setSidechainSourceTrackId(int32_t id) override { scTrackId_.store(id, std::memory_order_relaxed); }
+ void setSidechain(const float* interleaved, int32_t frames) override {
+ scBuf_ = interleaved;
+ scFrames_ = frames;
+ }
+ bool acceptsSidechain() const override { return true; }
static int fftSizeOf(float v) {
static const int n[4] = {512, 2048, 4096, 16384};
return n[std::clamp((int)std::lround(v * 3.0f), 0, 3)];
@@ -180,6 +219,7 @@ class Lens : public Device {
static double expMap(float v, double lo, double hi) {
return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0));
}
+ public:
static int step(float v, int n) { return std::clamp((int)std::lround(v * (n - 1)), 0, n - 1); }
int trigModeIdx() const { return step(get(TrigMode), 3); }
@@ -211,6 +251,11 @@ class Lens : public Device {
return src == 1 ? l : src == 2 ? r : 0.5f * (l + r);
}
bool msOn() const { return get(MidSide) >= 0.5f; }
+ // A key arrived within the last ~16 blocks.
+ bool keyLive() const {
+ const uint32_t seen = keySeen_.load(std::memory_order_relaxed);
+ return seen != 0 && frameSeq_.load(std::memory_order_relaxed) - seen < 16;
+ }
int srcIdx() const { return step(get(Source), 3); }
int windowSamples() const;
@@ -226,6 +271,18 @@ class Lens : public Device {
// Trigger search + trace capture. The trace is pinned to the trigger point
// (25 % pre-trigger, like the mockup's marker) so it stands still.
void analyzeScope() const;
+ // The synced frame from the beat-stamped history (specs/050).
+ void analyzeSync() const;
+ // Rings + history for one block of audio (main and, when routed, the key); the
+ // beat-stamped history only with `hist` (Sync on). Audio thread.
+ void capture(const float* main, const float* key, int32_t keyFrames, int32_t frames, double beat0, double spb,
+ bool playing, bool hist);
+ float pickKey(uint32_t idx, bool ms, int src) const {
+ const size_t i = idx & (kRing - 1);
+ const float l = ringKL_[i], r = ringKR_[i];
+ if (ms) return src == 2 ? 0.5f * (l - r) : 0.5f * (l + r);
+ return src == 1 ? l : src == 2 ? r : 0.5f * (l + r);
+ }
// Period by autocorrelation over the captured window (0 when nothing locks).
double measurePeriod() const;
@@ -260,6 +317,43 @@ class Lens : public Device {
std::atomic<uint32_t> frameSeq_{0};
std::atomic<float> corr_{0.0f}, lufs_{-120.0f};
+ // Tempo sync + the key (specs/050). The transport and key pointer are audio-thread only.
+ double beat0_ = 0.0, spb_ = 0.0;
+ bool playing_ = false;
+ std::atomic<double> bpb_{4.0};
+ std::atomic<int32_t> scTrackId_{-1};
+ static inline std::atomic<uint32_t> nextInstance_{1};
+ const uint32_t instance_ = nextInstance_.fetch_add(1, std::memory_order_relaxed) & 0xFFFFFF; // exact in a float
+ const float* scBuf_ = nullptr;
+ int32_t scFrames_ = 0;
+ // The engine hands a sidechain key one block late, so with a key routed the capture runs a
+ // block behind: the held block and its transport, captured with the next block's key.
+ std::vector<float> pend_;
+ int32_t pendN_ = 0;
+ double pendBeat_ = 0.0, pendSpb_ = 0.0;
+ bool pendPlaying_ = false;
+ bool keyedPrev_ = false, syncPrev_ = false; // audio thread
+ std::atomic<uint32_t> keySeen_{0}; // frameSeq_ of the last block a key arrived in
+ std::vector<float> ringKL_, ringKR_; // the key, beside ringL_/ringR_ (same head)
+
+ // Beat-stamped min/max history: one bin per binLen_ samples of the analysis channel. The
+ // audio thread fills bin binW_ (accumulators below) and publishes it by bumping binW_.
+ static constexpr int kBins = 65536; // power of two
+ struct Bin {
+ float mLo, mHi, kLo, kHi;
+ double beat; // the transport beat at the bin's first sample
+ double spb; // samples per beat then
+ uint32_t sample; // ringW_ at the bin's first sample
+ uint8_t flags; // 1 playing · 2 key present · bits 2..4 the channel (Source, M/S)
+ };
+ static constexpr uint8_t kBinPlaying = 1, kBinKey = 2, kBinChan = 0x1C;
+ // A bin is drawn only under the channel it was measured on (Source, M/S).
+ static uint8_t chanBits(bool ms, int src) { return (uint8_t)(((ms ? 4 : 0) | (src & 3)) << 2); }
+ std::vector<Bin> bins_;
+ std::atomic<uint32_t> binW_{0};
+ int binLen_ = 32, binN_ = 0; // audio thread
+ Bin acc_{}; // audio thread: the bin being filled
+
// Loudness follower (audio thread only).
Biquad kb_[2];
KState ks_[2];
@@ -272,7 +366,7 @@ class Lens : public Device {
mutable signalsmith::linear::RealFFT<float> fft_;
mutable std::vector<std::complex<float>> freq_;
mutable std::vector<float> time_, win_, avg_, binDb_, smTmp_;
- mutable std::vector<float> curve_, peak_, peakAge_, trace_, rawWin_, wfRow_;
+ mutable std::vector<float> curve_, peak_, peakAge_, trace_, rawWin_, wfRow_, keyTrace_, sync_;
mutable double winSum_ = 1.0, lastAnalyzeS_ = -1.0;
mutable uint32_t lastSeq_ = 0xFFFFFFFFu;
mutable int fftN_ = 0, winKind_ = -1, rawLen_ = 0;
diff --git a/tests/Nota.SmokeTest/LensSyncTests.cs b/tests/Nota.SmokeTest/LensSyncTests.cs
new file mode 100644
index 00000000..25cbd4d7
--- /dev/null
+++ b/tests/Nota.SmokeTest/LensSyncTests.cs
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Lens tempo sync and key overlay (specs/050, #119): with Sync on, the scope's synced
+// frame spans the song's beat grid (clicks land on their beat lines, this pass left of the
+// playhead and the previous one right of it), a one-sample spike keeps its height at any span,
+// a stopped transport rolls freely and a seek restarts the pass; a routed sidechain key gets
+// its own trace (synced and triggered); and the audio is untouched. Also runnable alone:
+// `--lens-sync`.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class LensSyncTests
+{
+ private const int LensKind = 22, Rate = 44100, Spb = Rate / 2; // 120 BPM
+ private const int RateP = 36, SyncP = 37, SpanP = 38, KeyShowP = 39, KeyGainP = 40, LayoutP = 41, TrigLevelP = 19;
+ private const int M_KeyLive = 20, M_Instance = 21, kScope = 22, L_Trace = 2, L_KeyTrace = 5, L_Sync = 6;
+ private const int Head = 8, Cols = 1024, Col = 5;
+ private const int S_Mode = 0, S_Playhead = 1, S_Bpm = 2, S_BeatsPerBar = 3, S_SpanBeats = 4, S_Start = 5, S_KeyLive = 6;
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ var tmp = new List<string>();
+ try
+ {
+ string beats = Clicks(tmp, 0.0), offBeats = Clicks(tmp, 0.5);
+ foreach (var r in Params()) yield return r;
+ foreach (var r in Grid(beats)) yield return r;
+ foreach (var r in FreeAndSeek(beats)) yield return r;
+ foreach (var r in Key(beats, offBeats)) yield return r;
+ foreach (var r in Sound(beats, offBeats)) yield return r;
+ foreach (var r in ChannelAndInstance(beats)) yield return r;
+ }
+ finally { foreach (var f in tmp) try { File.Delete(f); } catch (IOException) { } }
+ }
+
+ // 24 beats of one-sample 0.8 clicks, one per beat, `offset` beats late.
+ private static string Clicks(List<string> tmp, double offset)
+ {
+ string path = Path.Combine(Path.GetTempPath(), "nota_lens_sync_" + Guid.NewGuid().ToString("N") + ".wav");
+ tmp.Add(path);
+ var buf = new float[24 * Spb];
+ for (int b = 0; b < 24; b++) { int i = (int)Math.Round((b + offset) * Spb); if (i < buf.Length) buf[i] = 0.8f; }
+ using var w = new Nota.Infrastructure.WavWriter(path, Rate, 1, WavBitDepth.Float32);
+ w.WriteFrames(buf, buf.Length);
+ return path;
+ }
+
+ // A Lens on a track playing `clip`; with `key`, a key track playing it comes first, so the
+ // engine renders it before the Lens track and hands Lens the same block.
+ private static (NotaEngine E, int T, int D) NewLens(string clip) => NewLens(clip, null, out _);
+ private static (NotaEngine E, int T, int D) NewLens(string clip, string? key, out int keyTrack)
+ {
+ var e = new NotaEngine();
+ e.SetBpm(120); e.SetTimeSignature(4, 4);
+ keyTrack = -1;
+ if (key != null) { keyTrack = e.AddAudioTrack(); e.AddAudioClip(keyTrack, key, startBeat: 0.0); }
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, clip, startBeat: 0.0);
+ int d = e.AddBuiltinDevice(t, LensKind);
+ e.DeviceSetParam(t, d, RateP, 1f); // 60 fps: the shortest analysis interval
+ return (e, t, d);
+ }
+
+ private static float SpanV(int step) => step / 6f; // 0 = 1/4 beat … 4 = 1 bar … 6 = 4 bars
+
+ // Play from `from` to `to` (beats), in 512-frame blocks.
+ private static void Play(NotaEngine e, double from, double to, bool seek = true)
+ {
+ if (seek) { e.Seek(from); e.Play(); }
+ var buf = new float[512 * 2];
+ long n = (long)Math.Round((to - from) * Spb);
+ while (n > 0) { int k = (int)Math.Min(512, n); e.RenderOffline(buf, k); n -= k; }
+ }
+
+ private static float[] Frame(IAudioEngine e, int t, int d)
+ {
+ System.Threading.Thread.Sleep(40); // let the rate limiter open
+ var f = new float[Head + Cols * Col];
+ e.DeviceLayerWave(t, d, L_Sync, f, f.Length);
+ return f;
+ }
+
+ // Centres of the runs of columns of one age whose max (main: 1, key: 3) passes 0.4.
+ private static List<double> Peaks(float[] f, int age, int max = 1)
+ {
+ var res = new List<double>();
+ int start = -1;
+ for (int c = 0; c <= Cols; c++)
+ {
+ bool hit = c < Cols && (int)f[Head + c * Col + 4] == age && !float.IsNaN(f[Head + c * Col + 4]) && f[Head + c * Col + max] > 0.4f;
+ if (hit && start < 0) start = c;
+ if (!hit && start >= 0) { res.Add((start + c - 1) / 2.0); start = -1; }
+ }
+ return res;
+ }
+
+ private static bool Near(List<double> got, double[] want, double tol)
+ => got.Count == want.Length && got.Zip(want).All(p => Math.Abs(p.First - p.Second) <= tol);
+
+ private static string Show(List<double> v) => string.Join(", ", v.Select(x => x.ToString("0")));
+
+ // The long-span history is drawn only under the channel it was measured on: a mono click
+ // seen as Mid, then switched to Side (silent), leaves nothing of it. Each Lens reports its
+ // own serial, so a window can tell two Lenses apart.
+ private static IEnumerable<(bool, string)> ChannelAndInstance(string beats)
+ {
+ const int SourceP = 2, MidSideP = 3;
+ var (e, t, d) = NewLens(beats);
+ using var _ = e;
+ e.DeviceSetParam(t, d, SyncP, 1f);
+ e.DeviceSetParam(t, d, SpanP, SpanV(6)); // 4 bars: the history path
+ e.DeviceSetParam(t, d, MidSideP, 1f);
+ e.DeviceSetParam(t, d, SourceP, 0f); // Mid
+ Play(e, 0.0, 10.0);
+ int mid = Peaks(Frame(e, t, d), 0).Count;
+ e.DeviceSetParam(t, d, SourceP, 1f); // Side: a mono click has none
+ Play(e, 10.0, 10.05, seek: false);
+ int side = Peaks(Frame(e, t, d), 0).Count;
+ yield return (mid >= 8 && side == 0, $"long-span history follows the channel: {mid} clicks as Mid, {side} after switching to Side");
+
+ int d2 = e.AddBuiltinDevice(t, LensKind);
+ var a = new float[kScope]; var b = new float[kScope];
+ e.DeviceScope(t, d, a, kScope); e.DeviceScope(t, d2, b, kScope);
+ yield return (a[M_Instance] > 0 && b[M_Instance] > 0 && a[M_Instance] != b[M_Instance],
+ $"each Lens reports its own serial ({a[M_Instance]:0} vs {b[M_Instance]:0})");
+ }
+
+ private static IEnumerable<(bool, string)> Params()
+ {
+ var (e, t, d) = NewLens(Clicks(new List<string>(), 0));
+ using var _ = e;
+ string[] names = { "Scope Sync", "Scope Span", "Scope Key", "Scope Key Gain", "Scope Layout" };
+ float[] defs = { 0f, 4f / 6f, 1f, 0.5f, 0f };
+ bool ok = e.DeviceParamCount(t, d) == 42;
+ for (int i = 0; i < 5; i++)
+ ok &= e.DeviceParamName(t, d, SyncP + i) == names[i] && Math.Abs(e.DeviceGetParam(t, d, SyncP + i) - defs[i]) < 1e-5;
+ yield return (ok && e.DeviceAcceptsSidechain(t, d),
+ "Lens appends Sync (off), Span (1 bar), Key (shown), Key Gain (0 dB) and Layout (Overlay), and takes a sidechain key");
+ }
+
+ private static IEnumerable<(bool, string)> Grid(string beats)
+ {
+ var (e, t, d) = NewLens(beats);
+ using var _ = e;
+ e.DeviceSetParam(t, d, SyncP, 1f);
+ e.DeviceSetParam(t, d, SpanP, SpanV(4));
+ Play(e, 0, 10); // two and a half bars
+ var f = Frame(e, t, d);
+ yield return (f[S_Mode] == 1f && Math.Abs(f[S_Bpm] - 120) < 0.1 && f[S_BeatsPerBar] == 4 && f[S_SpanBeats] == 4 && f[S_Start] == 8
+ && Math.Abs(f[S_Playhead] - 0.5) < 0.01,
+ $"Sync at 1 bar, beat 10: the window is bar 3 (beat {f[S_Start]}), playhead {f[S_Playhead]:0.000}, {f[S_Bpm]:0.#} BPM");
+ var now = Peaks(f, 0);
+ // The previous pass ends where this one starts: the click on that bar line can show at
+ // both edges (one history bin holds it), so the right edge is left out.
+ var before = Peaks(f, 1).Where(c => c < Cols - 2).ToList();
+ yield return (Near(now, new[] { 0.0, 256 }, Cols * 0.01) && Near(before, new[] { 512.0, 768 }, Cols * 0.01),
+ $"each click sits on its beat line (within 1 %): this pass at {Show(now)}, the previous one at {Show(before)}");
+
+ // Four bars: drawn from the min/max history, the one-sample clicks keep their height.
+ e.DeviceSetParam(t, d, SpanP, SpanV(6));
+ Play(e, 0, 18);
+ f = Frame(e, t, d);
+ float top = 0;
+ for (int c = 0; c < Cols; c++) if (!float.IsNaN(f[Head + c * Col + 4])) top = Math.Max(top, f[Head + c * Col + 1]);
+ var all = Peaks(f, 0).Concat(Peaks(f, 1)).ToList();
+ yield return (f[S_SpanBeats] == 16 && f[S_Start] == 16 && top > 0.79f && all.Count >= 15,
+ $"at 4 bars a one-sample click still reaches {top:0.00} of 0.80, and every beat shows ({all.Count} marks)");
+
+ // Half a beat: the short-span path reads the raw ring.
+ e.DeviceSetParam(t, d, SpanP, SpanV(1));
+ Play(e, 0, 10.25);
+ f = Frame(e, t, d);
+ now = Peaks(f, 0);
+ yield return (f[S_SpanBeats] == 0.5f && f[S_Start] == 10 && Near(now, new[] { 0.0 }, Cols * 0.01),
+ $"at 1/2 beat the click at beat 10 sits on the window's left edge ({Show(now)})");
+
+ }
+
+ private static IEnumerable<(bool, string)> FreeAndSeek(string beats)
+ {
+ // Stopped, only a track that still sounds runs its devices (an instrument, or a
+ // monitored input); there the scope rolls freely.
+ using (var ie = new NotaEngine())
+ {
+ ie.SetBpm(120); ie.SetTimeSignature(4, 4);
+ int it = ie.AddInstrumentTrack();
+ int idv = ie.AddBuiltinDevice(it, LensKind);
+ ie.DeviceSetParam(it, idv, RateP, 1f);
+ ie.DeviceSetParam(it, idv, SyncP, 1f);
+ Play(ie, 0, 2);
+ ie.StopTransport();
+ Play(ie, 0, 0.5, seek: false);
+ var fr = Frame(ie, it, idv);
+ int filled = 0;
+ for (int c = 0; c < Cols; c++) if (!float.IsNaN(fr[Head + c * Col + 4])) filled++;
+ yield return (fr[S_Mode] == 0f && filled > Cols / 2,
+ $"stopped, an instrument track's scope rolls freely over the last bar ({filled} of {Cols} columns)");
+ }
+
+ var (e, t, d) = NewLens(beats);
+ using var _ = e;
+ e.DeviceSetParam(t, d, SyncP, 1f);
+ e.DeviceSetParam(t, d, SpanP, SpanV(4));
+
+ // A seek while playing restarts the pass: nothing from before it under the new beat lines.
+ Play(e, 0, 10);
+ e.Seek(20.5);
+ Play(e, 20.5, 21, seek: false);
+ var f = Frame(e, t, d);
+ int old = 0, early = 0, now = 0;
+ for (int c = 0; c < Cols; c++)
+ {
+ float a = f[Head + c * Col + 4];
+ if (float.IsNaN(a)) continue;
+ if ((int)a == 1) old++;
+ else if (c < 120) early++;
+ else now++;
+ }
+ yield return (f[S_Mode] == 1f && f[S_Start] == 20 && old == 0 && early == 0 && now > 100,
+ $"after a seek to beat 20.5 the pass restarts there ({now} new columns, {early + old} from before the seek)");
+ }
+
+ private static IEnumerable<(bool, string)> Key(string beats, string offBeats)
+ {
+ var (e, t, d) = NewLens(beats, offBeats, out int k);
+ using var _ = e;
+ e.SetDeviceSidechainSource(t, d, k);
+ e.DeviceSetParam(t, d, SyncP, 1f);
+ Play(e, 0, 10);
+ var f = Frame(e, t, d);
+ var sc = new float[kScope];
+ int n = e.DeviceScope(t, d, sc, kScope);
+ var keyNow = Peaks(f, 0, 3);
+ var keyBefore = Peaks(f, 1, 3).Where(c => c < Cols - 2).ToList();
+ var main = Peaks(f, 0);
+ yield return (n == kScope && sc[M_KeyLive] == 1f && f[S_KeyLive] == 1f && e.DeviceSidechainSource(t, d) == k,
+ "a routed key is reported as arriving");
+ yield return (Near(keyNow, new[] { 128.0, 384 }, Cols * 0.01) && Near(keyBefore, new[] { 640.0, 896 }, Cols * 0.01)
+ && Near(main, new[] { 0.0, 256 }, Cols * 0.01),
+ $"the key's off-beat clicks get their own trace ({Show(keyNow)} / {Show(keyBefore)}) beside the main ({Show(main)})");
+
+ e.DeviceSetParam(t, d, KeyGainP, 1f);
+ e.DeviceSetParam(t, d, LayoutP, 1f);
+ var g = Frame(e, t, d);
+ bool same = true;
+ for (int i = Head; i < f.Length; i++) same &= f[i].Equals(g[i]);
+ string txt = e.DeviceText(t, d, 2);
+ yield return (same && txt.Contains("sync on") && txt.Contains("arriving") && txt.Contains("+24.0 dB") && txt.Contains("stacked"),
+ $"Key Gain and Layout are display only, and the device text reports them: \"{txt[txt.IndexOf("sync", StringComparison.Ordinal)..]}\"");
+
+ // Sync off: the key trace follows the main trace's trigger, sample for sample.
+ string tone = Path.Combine(Path.GetTempPath(), "nota_lens_sync_tone_" + Guid.NewGuid().ToString("N") + ".wav");
+ Nota.SmokeTest.WavWriter.WriteTones(tone, 4.0, new double[] { 220 }, 0.5, Rate);
+ var (e2, t2, d2) = NewLens(tone, tone, out int k2);
+ using var __ = e2;
+ e2.SetDeviceSidechainSource(t2, d2, k2);
+ e2.DeviceSetParam(t2, d2, TrigLevelP, 0.6f);
+ Play(e2, 0, 160 * 512.0 / Spb); // whole blocks, as a live callback gives
+ System.Threading.Thread.Sleep(40);
+ float[] mt = new float[512], kt = new float[512];
+ int a = e2.DeviceLayerWave(t2, d2, L_Trace, mt, 512), b = e2.DeviceLayerWave(t2, d2, L_KeyTrace, kt, 512);
+ // The key is the other track's post-FX audio, so its level can differ (pan law): compare
+ // the shapes, the key scaled to the main's peak.
+ double diff = 0, peak = 0, kpeak = 0;
+ for (int i = 0; i < 512; i++) { peak = Math.Max(peak, Math.Abs(mt[i])); kpeak = Math.Max(kpeak, Math.Abs(kt[i])); }
+ for (int i = 0; i < 512; i++) diff = Math.Max(diff, Math.Abs(mt[i] - kt[i] * (kpeak > 0 ? peak / kpeak : 0)));
+ File.Delete(tone);
+ yield return (a == 512 && b == 512 && peak > 0.1 && diff < 1e-3 * peak,
+ $"Sync off, the key trace of the same audio lines up with the main trace (max diff {diff:0.0e+0}, peak {peak:0.00}, {a}/{b})");
+ }
+
+ private static IEnumerable<(bool, string)> Sound(string beats, string offBeats)
+ {
+ float[] Render(bool features, bool bypass)
+ {
+ var (e, t, d) = NewLens(beats);
+ using var _ = e;
+ int k = e.AddAudioTrack();
+ e.AddAudioClip(k, offBeats, startBeat: 0.0);
+ if (features) { e.SetDeviceSidechainSource(t, d, k); e.DeviceSetParam(t, d, SyncP, 1f); e.DeviceSetParam(t, d, LayoutP, 1f); }
+ if (bypass) e.SetDeviceBypassed(t, d, true);
+ e.Seek(0); e.Play();
+ var all = new float[8 * 4096 * 2];
+ var buf = new float[4096 * 2];
+ for (int i = 0; i < 8; i++) { e.RenderOffline(buf, 4096); Array.Copy(buf, 0, all, i * buf.Length, buf.Length); }
+ return all;
+ }
+ float[] plain = Render(false, true), on = Render(true, false);
+ bool same = plain.Length == on.Length && plain.Zip(on).All(p => p.First.Equals(p.Second));
+ yield return (same, "with Sync and a key, the audio through Lens is bit-identical to Lens bypassed");
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index a43fbc6c..8c7075fb 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -477,6 +477,14 @@ if (args.Length >= 1 && args[0] == "--eq-analyzer")
Console.WriteLine(failures == 0 ? "EQ ANALYZER PASSED" : $"EQ ANALYZER FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Nota Lens tempo sync + key overlay alone (specs/050): `--lens-sync`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--lens-sync")
+{
+ Console.WriteLine("-- lens sync --");
+ foreach (var (ok, label) in LensSyncTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "LENS SYNC PASSED" : $"LENS SYNC FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// EQ-8 band labels and notes alone (specs/049): `--eq-labels`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--eq-labels")
{
@@ -6430,7 +6438,7 @@ Console.WriteLine("-- Nota Lens --");
AverageP = 6, SmoothP = 7, TiltP = 9, PeakHoldP = 11, TimeDivP = 15, TrigModeP = 17,
TrigLevelP = 19, CursorAP = 26, CursorBP = 27, RateP = 36;
const int M_PeakHz = 0, M_PeakDb = 1, M_RmsDb = 2, M_PeriodMs = 8, M_FreqHz = 9, M_Vpp = 10,
- M_Vrms = 11, M_BinHz = 13, M_FftN = 14, M_SampleRate = 18, M_Held = 19, kLensScope = 20;
+ M_Vrms = 11, M_BinHz = 13, M_FftN = 14, M_SampleRate = 18, M_Held = 19, kLensScope = 22;
const int L_Spectrum = 0, L_Peak = 1, L_Trace = 2, L_Raw = 3, L_Waterfall = 4;
const int A_Rearm = 0, A_ResetPeak = 1;
@@ -6447,7 +6455,7 @@ Console.WriteLine("-- Nota Lens --");
Check(le.DeviceName(lt, ld) == "Nota Lens", $"name is Nota Lens (got '{le.DeviceName(lt, ld)}')");
Check(le.TrackDeviceBuiltinKind(lt, ld) == 22, $"builtin kind is 22 (got {le.TrackDeviceBuiltinKind(lt, ld)})");
int lpc = le.DeviceParamCount(lt, ld);
- Check(lpc == 37, $"Nota Lens exposes 37 params (got {lpc})");
+ Check(lpc == 42, $"Nota Lens exposes 42 params (got {lpc})");
var lnames = Enumerable.Range(0, lpc).Select(i => le.DeviceParamName(lt, ld, i)).ToList();
Check(lnames.Distinct().Count() == lpc && lnames.All(n => n.Length > 0), "Lens param names are unique and non-empty");
le.DeviceSetParam(lt, ld, TiltP, 0.42f);
@@ -15233,6 +15241,8 @@ Console.WriteLine("-- eq labels --");
foreach (var (ok, label) in EqLabelTests.Run()) Check(ok, label);
Console.WriteLine("-- scope view --");
foreach (var (ok, label) in ScopeViewTests.Run()) Check(ok, label);
+Console.WriteLine("-- lens sync --");
+foreach (var (ok, label) in LensSyncTests.Run()) Check(ok, label);
Console.WriteLine("-- plug-in preview --");
foreach (var (ok, label) in PluginPreviewTests.Run()) Check(ok, label);