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.

Add lens

Egor Khindikaynen5e1388291f03
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b5d6d916..a74b6ee9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,33 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
+### Added
+- **Nota Lens — analyzer and oscilloscope.** A new built-in audio effect (kind 22) that shows
+ you what a track is actually doing. Drop it anywhere in a chain; it passes the audio through
+ untouched and adds no latency. One card, three views behind tabs:
+ - **Spectrum** — FFT of 512 / 2048 / 4096 / 16384 points with a Hann, Blackman-Harris or
+ flat-top window, frame averaging, fractional-octave smoothing, adjustable fall time, a
+ pink-noise tilt so a balanced mix reads flat, and a peak-hold trace with its own hold
+ time. Move the pointer over the curve to read a frequency, its note and cents, and its
+ level. A 0.25 sine reads its own −12.0 dBFS.
+ - **Scope** — a triggered oscilloscope that behaves like a bench instrument: the trace is
+ pinned to the trigger point and stands still, older passes fade out behind it. Auto /
+ Normal / Single triggering on a rising or falling edge, with a level you drag on the
+ trace and a holdoff. Time/div from 20 µs to 20 ms, volt/div from 0.02 to 2. A/B cursors
+ you drag for Δt, 1/Δt, ΔV and the matching note, and **Export WAV** to write the captured
+ window to disk.
+ - **Waterfall** — a spectrogram over the last 4, 12 or 60 seconds, with gain, floor,
+ contrast and FFT overlap.
+ Plus a permanent SCALE rail (dB top and range, or volt/div and time/div), a live status
+ line (peak, crest, momentary LUFS, L/R correlation), Freeze, an optional note grid, a
+ linear or logarithmic frequency axis, and an L+R / L / R source that can read Mid/Side
+ instead. All 37 controls are device parameters, so automation, MIDI learn, A/B compare and
+ project save work as they do everywhere else. **32 factory presets** across the three views.
+- **MCP: `read_analyzer`.** Ask for what a Nota Lens is measuring and get it back parsed —
+ the summary line, the scope measurements, the A/B cursor readings, 31 third-octave band
+ levels and the strongest spectral peaks with note names. `get_device_text` on a Lens
+ returns the same reports as text.
+
## [0.40.0] — 2026-09-18
### Highlights
diff --git a/FEATURES.md b/FEATURES.md
index 94230dfb..a163e167 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -384,6 +384,17 @@ and user presets, automation, persistence and cloning.
band gain and solo. Amount scales every ratio; Peak/RMS detection, lookahead (PDC), a
band-split external sidechain with Listen, auto makeup, Mix, output gain and a −0.3 dBFS soft
clip. Transfer curve with drag handles, detector-envelope trace, per-band GR meters.
+- **Nota Lens** (22) — analyzer: spectrum, triggered oscilloscope and waterfall in one card,
+ passing the audio through untouched. *Spectrum*: FFT 512–16384, Hann / Blackman-Harris /
+ flat-top window, frame averaging, fractional-octave smoothing, fall time, pink tilt, peak
+ hold, and a pointer cursor reading frequency, note, cents and level. *Scope*: the trace is
+ pinned to the trigger point and stands still while older passes fade; Auto / Normal / Single
+ on a rising or falling edge, a level dragged on the trace, holdoff, 20 µs–20 ms per division,
+ A/B cursors for Δt / 1/Δt / ΔV with the matching note, and Export WAV of the captured window.
+ *Waterfall*: a 4 / 12 / 60-second spectrogram with gain, floor, contrast and FFT overlap.
+ A permanent SCALE rail, Freeze, a note grid, a linear or log frequency axis, an L+R / L / R
+ source that can read Mid/Side, and a status line with peak, crest, momentary LUFS and L/R
+ correlation. Readable from MCP with `read_analyzer`.
- **Nota Chorus** — modulation (chorus) effect.
- **Forge**, **Valve** and **Vintage** each carry an **OVERSAMPLE** selector
(Off/2×/4×/8×) to suppress aliasing under heavy drive.
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index de117580..5791f0de 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -387,9 +387,10 @@ public sealed partial class ArrangementView
if (!sepAdded) { flyout.Items.Add(new Separator()); sepAdded = true; }
var devMenu = new MenuItem { Header = dn };
// Nota Chamber (45 params) groups by its section prefix ("IR", "Algo", "EQ" …),
- // Nota Prism (52) by band ("Low", "Mid", "High", "Crossover"): a word shared
+ // Nota Prism (52) by band ("Low", "Mid", "High", "Crossover") and Nota Lens (37) by
+ // view ("Spectrum", "Scope", "Waterfall", "Cursor"): a word shared
// by two or more params becomes a submenu.
- bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 20 or 21;
+ bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 20 or 21 or 22;
var names = new string[builtinPc];
for (int p = 0; p < builtinPc; p++) names[p] = e.DeviceParamName(t.Id, d, p);
static string Head(string n) { int sp = n.IndexOf(' '); return sp > 0 ? n[..sp] : ""; }
diff --git a/src/managed/Nota.App/Controls/LensViews.cs b/src/managed/Nota.App/Controls/LensViews.cs
new file mode 100644
index 00000000..2013bc6a
--- /dev/null
+++ b/src/managed/Nota.App/Controls/LensViews.cs
@@ -0,0 +1,630 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Lens (device kind 22) visualisers — the three graphs the analyzer card
+// swaps between, plus the vertical scale slider of its SCALE rail. All three read
+// one LensData snapshot that the card refills from the engine on the 60 Hz tick
+// (curve / peak-hold / scope trace / waterfall row / measurements), so the graphs
+// never touch the engine themselves.
+//
+// They are controls, not decoration: the spectrum carries a frequency cursor with
+// its note, the scope's trigger level and A/B cursors are dragged straight on the
+// trace, and the waterfall follows the same log-frequency axis so a peak lines up
+// between the two views.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Avalonia.Media.Imaging;
+using Avalonia.Platform;
+
+namespace Nota.App;
+
+/// <summary>One analysis frame, refilled by the card from the engine each tick and
+/// shared by the three Lens graphs.</summary>
+internal sealed class LensData
+{
+ public const int Curve = 512, TraceN = 512, WfBins = 256, WfRows = 256;
+
+ public readonly float[] Spec = new float[Curve];
+ public readonly float[] Peak = new float[Curve];
+ public readonly float[] Trace = new float[TraceN];
+ 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;
+
+ /// <summary>Past scope traces for the afterglow, newest first, with their age in seconds.</summary>
+ public readonly List<(float[] Pts, double Age)> Ghosts = new();
+
+ public double SampleRate = 48000;
+ public double TopDb = -6, RangeDb = 90; // dB axis
+ public double VoltDiv = 0.5, TimeDivSec = 0.002;
+ public bool LogFreq = true, NoteGrid, PeakOn = true, Held;
+ public double TrigLevel, CursorA = 0.25, CursorB = 0.375;
+ public bool CursorsOn, CursorSnap, TrigRising = true, TrigOk;
+ public double Bright = 0.66;
+ public double WfSpanSec = 12;
+
+ public double FreqLo => 20;
+ public double FreqHi => Math.Min(20000, SampleRate * 0.45);
+
+ /// <summary>The curve index (0..Curve−1) a frequency sits at — the curve is log-spaced.</summary>
+ public double IndexOf(double hz)
+ => Math.Clamp(Math.Log(hz / FreqLo) / Math.Log(FreqHi / FreqLo), 0, 1) * (Curve - 1);
+
+ public double FreqOf(double index)
+ => FreqLo * Math.Pow(FreqHi / FreqLo, Math.Clamp(index / (Curve - 1), 0, 1));
+
+ /// <summary>Where a frequency sits on the always-logarithmic analysis curve, 0..1 — the
+ /// waterfall's bins are spaced that way whatever axis the view draws.</summary>
+ public double LogFrac(double hz)
+ => Math.Clamp(Math.Log(hz / FreqLo) / Math.Log(FreqHi / FreqLo), 0, 1);
+
+ /// <summary>Fraction across the graph a frequency sits at (log or linear axis).</summary>
+ public double FracOf(double hz) => LogFreq
+ ? Math.Clamp(Math.Log(hz / FreqLo) / Math.Log(FreqHi / FreqLo), 0, 1)
+ : Math.Clamp((hz - FreqLo) / (FreqHi - FreqLo), 0, 1);
+
+ public double HzAt(double frac) => LogFreq
+ ? FreqLo * Math.Pow(FreqHi / FreqLo, Math.Clamp(frac, 0, 1))
+ : FreqLo + (FreqHi - FreqLo) * Math.Clamp(frac, 0, 1);
+
+ public double DbAt(double hz)
+ {
+ double x = IndexOf(hz);
+ int i = Math.Min((int)x, Curve - 2);
+ double f = x - i;
+ return Spec[i] * (1 - f) + Spec[i + 1] * f;
+ }
+
+ public void PushWaterfallRow(float[] row)
+ {
+ Array.Copy(row, 0, Wf, (WfHead % WfRows) * WfBins, Math.Min(row.Length, WfBins));
+ WfHead++;
+ if (WfFilled < WfRows) WfFilled++;
+ }
+
+ public void ClearWaterfall() { Array.Clear(Wf); WfHead = 0; WfFilled = 0; }
+
+ public void PushGhost(double maxAgeSec, int maxTraces)
+ {
+ var copy = new float[TraceN];
+ Array.Copy(Trace, copy, TraceN);
+ Ghosts.Insert(0, (copy, 0));
+ while (Ghosts.Count > Math.Max(1, maxTraces)) Ghosts.RemoveAt(Ghosts.Count - 1);
+ for (int i = Ghosts.Count - 1; i >= 0; i--)
+ if (Ghosts[i].Age > maxAgeSec) Ghosts.RemoveAt(i);
+ }
+
+ public void AgeGhosts(double dt)
+ {
+ for (int i = 0; i < Ghosts.Count; i++) Ghosts[i] = (Ghosts[i].Pts, Ghosts[i].Age + dt);
+ }
+}
+
+internal static class LensInk
+{
+ public static IBrush Ground => NotaPalette.BgSunken;
+ public static IPen Frame => NotaGraph.FramePen;
+ public static IBrush Trace => NotaPalette.Accent;
+ public static IBrush TraceLit => NotaPalette.AccentBright;
+ public static IBrush Fill => NotaPalette.Wash(NotaPalette.Accent, 0x22);
+ public static IBrush Hold => NotaPalette.Teal;
+ public static IBrush Axis => NotaPalette.TextAxis;
+ public static IBrush Label => NotaPalette.TextTertiary;
+ public static IPen GridFaint => new Pen(NotaPalette.GridBeat, 1);
+ public static IPen GridStrong => new Pen(NotaPalette.WellGrid, 1);
+ public static IPen Zero => new Pen(NotaPalette.GridBar, 1);
+
+ /// <summary>The graph's own title: a caps eyebrow, then its value in mono so a unit
+ /// keeps its case ("SCOPE · 2.00 ms/div", never "2.00 MS/DIV").</summary>
+ public static void Title(DrawingContext ctx, string caps, string value, double x = 6, double y = 4)
+ {
+ var head = new FormattedText(caps.ToUpperInvariant(), CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
+ NotaFonts.SansBold, NotaGraph.TitleSize, Label);
+ ctx.DrawText(head, new Point(x, y));
+ if (value.Length > 0) Text(ctx, value, x + head.Width + 5, y, Axis, 8);
+ }
+
+ public static readonly string[] NoteNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+
+ /// <summary>"A#3 +4 ¢" for a frequency, or "—" below hearing.</summary>
+ public static string Note(double hz)
+ {
+ if (hz <= 16) return "—";
+ double midi = 69 + 12 * Math.Log2(hz / 440.0);
+ int n = (int)Math.Round(midi);
+ int cents = (int)Math.Round((midi - n) * 100);
+ return NotaNum.F($"{NoteNames[((n % 12) + 12) % 12]}{n / 12 - 1} {cents:+0;−0;0} ¢");
+ }
+
+ public static void Text(DrawingContext ctx, string s, double x, double y, IBrush ink, double size = 7, bool mono = true)
+ => ctx.DrawText(new FormattedText(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
+ mono ? NotaFonts.Mono : NotaFonts.SansBold, size, ink), new Point(x, y));
+
+ public static double TextW(string s, double size = 7, bool mono = true)
+ => new FormattedText(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
+ mono ? NotaFonts.Mono : NotaFonts.SansBold, size, NotaPalette.TextPrimary).Width;
+}
+
+// ===========================================================================
+// Spectrum
+// ===========================================================================
+internal sealed class LensSpectrumView : Control
+{
+ private static readonly double[] GridHz = { 30, 50, 100, 200, 300, 500, 1000, 2000, 3000, 5000, 10000, 20000 };
+ private static readonly double[] LabelHz = { 100, 1000, 10000 };
+
+ private readonly LensData _d;
+ private double _cursorFrac = -1;
+
+ /// <summary>The cursor's frequency (Hz), or 0 when the pointer is away.</summary>
+ public double CursorHz => _cursorFrac < 0 ? 0 : _d.HzAt(_cursorFrac);
+ public double CursorDb => _cursorFrac < 0 ? 0 : _d.DbAt(CursorHz);
+ public event Action? CursorMoved;
+
+ public LensSpectrumView(LensData d) { _d = d; ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Cross); }
+
+ public void Tick() => InvalidateVisual();
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ _cursorFrac = Math.Clamp(e.GetPosition(this).X / Math.Max(1, Bounds.Width), 0, 1);
+ CursorMoved?.Invoke();
+ InvalidateVisual();
+ }
+ protected override void OnPointerExited(PointerEventArgs e) { _cursorFrac = -1; CursorMoved?.Invoke(); InvalidateVisual(); }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 2 || h <= 2) return;
+ NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+
+ double top = _d.TopDb, range = Math.Max(6, _d.RangeDb);
+ // The frequency labels get their own lane under the plot, so the noise floor never
+ // sits on top of "1k" (the mockup's axis row).
+ const double AxisH = 11;
+ double plotH = Math.Max(8, h - AxisH);
+ double Y(double db) => Math.Clamp((top - db) / range, 0, 1) * plotH;
+
+ // dB grid: a line every 30 dB, labelled inside on the left.
+ for (double db = Math.Ceiling(top / 30) * 30; db > top - range; db -= 30)
+ {
+ double y = Y(db);
+ if (y < 2 || y > plotH - 2) continue;
+ ctx.DrawLine(LensInk.GridFaint, new Point(0, y), new Point(w, y));
+ LensInk.Text(ctx, NotaNum.F($"{db:0}"), 4, y - 8, LensInk.Axis);
+ }
+ // Frequency grid.
+ foreach (double hz in GridHz)
+ {
+ if (hz >= _d.FreqHi) continue;
+ double x = _d.FracOf(hz) * w;
+ ctx.DrawLine(Array.IndexOf(LabelHz, hz) >= 0 ? LensInk.GridStrong : LensInk.GridFaint, new Point(x, 0), new Point(x, plotH));
+ }
+ if (_d.NoteGrid)
+ {
+ for (int oct = 1; oct <= 9; oct++)
+ {
+ double hz = 440.0 * Math.Pow(2, (12 * oct - 57) / 12.0); // C of each octave
+ if (hz < _d.FreqLo || hz >= _d.FreqHi) continue;
+ double x = _d.FracOf(hz) * w;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x22), 1), new Point(x, 0), new Point(x, plotH));
+ }
+ }
+
+ // The curve: a filled body under an amber trace.
+ var fill = new StreamGeometry();
+ var line = new StreamGeometry();
+ using (var fc = fill.Open())
+ using (var lc = line.Open())
+ {
+ fc.BeginFigure(new Point(0, plotH), true);
+ bool started = false;
+ for (int px = 0; px <= (int)w; px++)
+ {
+ double frac = px / Math.Max(1.0, w);
+ double hz = _d.HzAt(frac);
+ double y = Y(_d.DbAt(hz));
+ fc.LineTo(new Point(px, y));
+ if (!started) { lc.BeginFigure(new Point(px, y), false); started = true; }
+ else lc.LineTo(new Point(px, y));
+ }
+ fc.LineTo(new Point(w, plotH));
+ fc.EndFigure(true);
+ if (started) lc.EndFigure(false);
+ }
+ ctx.DrawGeometry(LensInk.Fill, null, fill);
+
+ // Peak hold behind the live trace, in the second chroma.
+ if (_d.PeakOn)
+ {
+ var hold = new StreamGeometry();
+ using (var hc = hold.Open())
+ {
+ bool started = false;
+ for (int px = 0; px <= (int)w; px++)
+ {
+ double x = _d.LogFreq ? px / Math.Max(1.0, w) * (LensData.Curve - 1) : _d.IndexOf(_d.HzAt(px / Math.Max(1.0, w)));
+ int i = Math.Clamp((int)x, 0, LensData.Curve - 2);
+ double f = x - i;
+ double y = Y(_d.Peak[i] * (1 - f) + _d.Peak[i + 1] * f);
+ if (!started) { hc.BeginFigure(new Point(px, y), false); started = true; } else hc.LineTo(new Point(px, y));
+ }
+ if (started) hc.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xB4), 1), hold);
+ }
+ ctx.DrawGeometry(null, new Pen(LensInk.Trace, NotaGraph.PrimaryWidth * (0.6 + 0.6 * _d.Bright)), line);
+
+ // Cursor with its note readout.
+ if (_cursorFrac >= 0)
+ {
+ double x = _cursorFrac * w, hz = CursorHz, db = CursorDb;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x99), 1), new Point(x, 0), new Point(x, plotH));
+ double y = Y(db);
+ ctx.DrawEllipse(LensInk.TraceLit, null, new Point(x, y), 2.5, 2.5);
+ string s = NotaNum.F($"{LensInk.Note(hz)} · {Fmt(hz)} · {db:0.0} dB");
+ double tw = LensInk.TextW(s, 8);
+ LensInk.Text(ctx, s, Math.Clamp(x + 5, 3, w - tw - 3), 3, LensInk.TraceLit, 8);
+ }
+ else
+ {
+ LensInk.Title(ctx, "SPECTRUM", NotaNum.F($"{_d.TopDb:0} … {_d.TopDb - range:0} dB"));
+ }
+
+ // The axis lane: the decade labels sit under the plot, each on its grid line.
+ ctx.DrawLine(LensInk.GridFaint, new Point(0, plotH), new Point(w, plotH));
+ foreach (double hz in LabelHz)
+ {
+ if (hz >= _d.FreqHi) continue;
+ double x = _d.FracOf(hz) * w;
+ string s = hz >= 1000 ? NotaNum.F($"{hz / 1000:0} kHz") : NotaNum.F($"{hz:0} Hz");
+ LensInk.Text(ctx, s, Math.Min(x + 3, w - LensInk.TextW(s) - 3), plotH + 1, LensInk.Axis);
+ }
+ LensInk.Text(ctx, NotaNum.F($"{top - range:0} dB"), w - LensInk.TextW(NotaNum.F($"{top - range:0} dB")) - 4, plotH - 9, LensInk.Axis);
+ }
+
+ private static string Fmt(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.00} kHz") : NotaNum.F($"{hz:0} Hz");
+}
+
+// ===========================================================================
+// Scope
+// ===========================================================================
+internal sealed class LensScopeView : Control
+{
+ private const int Cols = 8, Rows = 4;
+
+ private readonly LensData _d;
+ private int _drag; // 0 none · 1 trigger level · 2 cursor A · 3 cursor B
+
+ public event Action<double>? TrigLevelChanged; // −1..1
+ public event Action<int, double>? CursorChanged; // (0=A / 1=B, 0..1)
+
+ public LensScopeView(LensData d) { _d = d; ClipToBounds = true; }
+
+ 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));
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ var p = e.GetPosition(this);
+ double w = Bounds.Width, h = Bounds.Height;
+ _drag = 0;
+ if (_d.CursorsOn)
+ {
+ if (Math.Abs(p.X - _d.CursorA * w) < 6) _drag = 2;
+ else if (Math.Abs(p.X - _d.CursorB * w) < 6) _drag = 3;
+ }
+ if (_drag == 0 && Math.Abs(p.Y - YOf(_d.TrigLevel, h)) < 8) _drag = 1;
+ if (_drag == 0) return;
+ e.Pointer.Capture(this); e.Handled = true;
+ Apply(p);
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { if (_drag != 0) Apply(e.GetPosition(this)); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e) { _drag = 0; e.Pointer.Capture(null); }
+
+ private void Apply(Point p)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (_drag == 1) TrigLevelChanged?.Invoke(Math.Clamp(VOf(p.Y, h), -1, 1));
+ else
+ {
+ double frac = Math.Clamp(p.X / Math.Max(1, w), 0, 1);
+ if (_d.CursorSnap) frac = SnapToPeak(frac);
+ CursorChanged?.Invoke(_drag - 2, frac);
+ }
+ InvalidateVisual();
+ }
+
+ /// <summary>Snap a cursor to the strongest turning point of the trace within ~2.5 % of
+ /// the window — "Snap to peaks", so a Δt lands on the waveform and not between samples.</summary>
+ private double SnapToPeak(double frac)
+ {
+ var t = _d.Trace;
+ int n = t.Length, c = Math.Clamp((int)Math.Round(frac * (n - 1)), 1, n - 2);
+ int win = Math.Max(2, n / 40);
+ int best = c; double bestV = -1;
+ for (int i = Math.Max(1, c - win); i <= Math.Min(n - 2, c + win); i++)
+ {
+ double v = Math.Abs(t[i]);
+ if (v < Math.Abs(t[i - 1]) || v < Math.Abs(t[i + 1])) continue; // a turning point only
+ if (v > bestV) { bestV = v; best = i; }
+ }
+ return best / (double)(n - 1);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 2 || h <= 2) return;
+ NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+
+ 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));
+ }
+
+ // 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.Accent, (byte)(k * 90)), 1.2), Path(pts, w, h));
+ }
+ ctx.DrawGeometry(null, new Pen(LensInk.Trace, 1.1 + 1.0 * _d.Bright), Path(_d.Trace, w, h));
+
+ // Trigger level (draggable) + the trigger point, pinned at 25 % like a bench scope.
+ double ty = YOf(_d.TrigLevel, h);
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xC0), 1, new DashStyle(new double[] { 3, 4 }, 0)), new Point(0, ty), new Point(w, ty));
+ ctx.DrawRectangle(LensInk.Hold, null, new Rect(0, ty - 3.5, 5, 7));
+ double tx = w * 0.25;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Accent, 0x80), 1), new Point(tx, 0), new Point(tx, h));
+ ctx.DrawRectangle(LensInk.Trace, null, new Rect(tx - 3.5, 0, 7, 5));
+
+ if (_d.CursorsOn)
+ {
+ foreach (var (frac, name) in new[] { (_d.CursorA, "A"), (_d.CursorB, "B") })
+ {
+ double x = frac * w;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0xAA), 1), new Point(x, 0), new Point(x, h));
+ LensInk.Text(ctx, name, x + 2, h / 2 - 12, LensInk.TraceLit, 8, false);
+ }
+ double dt = Math.Abs(_d.CursorB - _d.CursorA) * _d.TimeDivSec * Cols;
+ string s = NotaNum.F($"Δt {dt * 1000:0.000} ms · {(dt > 1e-9 ? 1 / dt : 0):0.0} Hz");
+ LensInk.Text(ctx, s, w - LensInk.TextW(s, 8) - 4, h - 11, LensInk.TraceLit, 8);
+ }
+
+ LensInk.Title(ctx, "SCOPE", NotaNum.F($"{Ms(_d.TimeDivSec)}/div · {_d.VoltDiv:0.00}/div"));
+ string trig = _d.Held ? "HELD" : NotaNum.F($"trig {(_d.TrigRising ? "↑" : "↓")} {_d.TrigLevel:0.00}{(_d.TrigOk ? "" : " ·free")}");
+ LensInk.Text(ctx, trig, w - LensInk.TextW(trig) - 4, 3, _d.TrigOk || _d.Held ? LensInk.TraceLit : LensInk.Axis);
+ 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);
+ }
+
+ private double _ghostLife = 0.42;
+ public double GhostLife { set => _ghostLife = value; }
+
+ private Geometry Path(float[] pts, double w, double h)
+ {
+ 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.EndFigure(false);
+ return g;
+ }
+
+ private static string Ms(double sec) => sec >= 0.001 ? NotaNum.F($"{sec * 1000:0.00} ms") : NotaNum.F($"{sec * 1e6:0} µs");
+}
+
+// ===========================================================================
+// Waterfall
+// ===========================================================================
+internal sealed class LensWaterfallView : Control
+{
+ private static readonly double[] LabelHz = { 100, 1000, 10000 };
+
+ private readonly LensData _d;
+ private readonly WriteableBitmap _bmp;
+ private readonly int[] _px = new int[LensData.WfRows * LensData.WfBins];
+ private readonly int[] _bin = new int[LensData.WfBins];
+ private readonly int[] _ramp = new int[256];
+ private int _rampSeed = -1;
+ private double _cursorFrac = -1, _cursorTime;
+
+ public double CursorHz => _cursorFrac < 0 ? 0 : _d.HzAt(1 - _cursorFrac);
+ public double CursorAgeSec => _cursorTime;
+ public event Action? CursorMoved;
+
+ public LensWaterfallView(LensData d)
+ {
+ _d = d;
+ ClipToBounds = true;
+ Cursor = new Cursor(StandardCursorType.Cross);
+ _bmp = new WriteableBitmap(new PixelSize(LensData.WfRows, LensData.WfBins), new Vector(96, 96),
+ PixelFormat.Bgra8888, AlphaFormat.Premul);
+ }
+
+ public void Tick() => InvalidateVisual();
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ var p = e.GetPosition(this);
+ _cursorFrac = Math.Clamp(p.Y / Math.Max(1, Bounds.Height - 11), 0, 1);
+ _cursorTime = (1 - Math.Clamp(p.X / Math.Max(1, Bounds.Width), 0, 1)) * _d.WfSpanSec;
+ CursorMoved?.Invoke();
+ InvalidateVisual();
+ }
+ protected override void OnPointerExited(PointerEventArgs e) { _cursorFrac = -1; CursorMoved?.Invoke(); InvalidateVisual(); }
+
+ // Well → brass ramp: the same warmth as every other graph, never a rainbow.
+ private void BuildRamp()
+ {
+ int seed = NotaPalette.Accent.Color.GetHashCode() ^ NotaPalette.BgSunken.Color.GetHashCode();
+ if (seed == _rampSeed) return;
+ _rampSeed = seed;
+ Color a = NotaPalette.BgSunken.Color, b = NotaPalette.AccentDeep.Color,
+ c = NotaPalette.Accent.Color, e = NotaPalette.AccentPale.Color;
+ for (int i = 0; i < 256; i++)
+ {
+ double t = i / 255.0;
+ Color lo, hi; double k;
+ if (t < 0.45) { lo = a; hi = b; k = t / 0.45; }
+ else if (t < 0.8) { lo = b; hi = c; k = (t - 0.45) / 0.35; }
+ else { lo = c; hi = e; k = (t - 0.8) / 0.2; }
+ byte R = (byte)(lo.R + (hi.R - lo.R) * k), G = (byte)(lo.G + (hi.G - lo.G) * k), B = (byte)(lo.B + (hi.B - lo.B) * k);
+ _ramp[i] = unchecked((int)0xFF000000) | (R << 16) | (G << 8) | B;
+ }
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 2 || h <= 2) return;
+ NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+ BuildRamp();
+
+ // Time runs left (oldest) → right (now); frequency runs bottom → top. The rows a
+ // frame carries are log-spaced, so a linear axis re-maps them rather than stretching.
+ int rows = LensData.WfRows, bins = LensData.WfBins;
+ for (int y = 0; y < bins; y++)
+ {
+ double hz = _d.HzAt(1 - y / (double)(bins - 1));
+ _bin[y] = Math.Clamp((int)Math.Round(_d.LogFrac(hz) * (bins - 1)), 0, bins - 1);
+ }
+ for (int x = 0; x < rows; x++)
+ {
+ int age = rows - 1 - x; // 0 = newest column
+ int slot = ((_d.WfHead - 1 - age) % rows + rows) % rows;
+ bool have = age < _d.WfFilled;
+ for (int y = 0; y < bins; y++)
+ {
+ float v = have ? _d.Wf[slot * bins + _bin[y]] : 0f;
+ _px[y * rows + x] = _ramp[Math.Clamp((int)(v * 255), 0, 255)];
+ }
+ }
+ using (var fb = _bmp.Lock())
+ {
+ for (int y = 0; y < bins; y++)
+ Marshal.Copy(_px, y * rows, IntPtr.Add(fb.Address, y * fb.RowBytes), rows);
+ }
+ // The spectrogram, then its own time lane under it — a bright low band would
+ // otherwise swallow the "−12 s" caption.
+ const double AxisH = 11;
+ double plotH = Math.Max(8, h - AxisH);
+ ctx.DrawImage(_bmp, new Rect(0, 0, rows, bins), new Rect(1, 1, w - 2, plotH - 1));
+
+ foreach (double hz in LabelHz)
+ {
+ if (hz >= _d.FreqHi) continue;
+ double y = (1 - _d.FracOf(hz)) * plotH;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.GridBeat, 0x88), 1), new Point(0, y), new Point(w, y));
+ LensInk.Text(ctx, hz >= 1000 ? NotaNum.F($"{hz / 1000:0} kHz") : NotaNum.F($"{hz:0} Hz"), 4, y - 9, LensInk.Axis);
+ }
+ if (_d.NoteGrid)
+ {
+ for (int oct = 1; oct <= 9; oct++)
+ {
+ double hz = 440.0 * Math.Pow(2, (12 * oct - 57) / 12.0); // C of each octave
+ if (hz < _d.FreqLo || hz >= _d.FreqHi) continue;
+ double y = (1 - _d.FracOf(hz)) * plotH;
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x33), 1), new Point(0, y), new Point(w, y));
+ }
+ }
+ if (_cursorFrac >= 0)
+ {
+ double y = Math.Min(_cursorFrac * plotH, plotH);
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x99), 1), new Point(0, y), new Point(w, y));
+ }
+ ctx.DrawLine(LensInk.GridFaint, new Point(0, plotH), new Point(w, plotH));
+ LensInk.Title(ctx, "WATERFALL", NotaNum.F($"{_d.WfSpanSec:0} s"));
+ string span = NotaNum.F($"−{_d.WfSpanSec:0} s");
+ LensInk.Text(ctx, span, 4, plotH + 1, LensInk.Axis);
+ LensInk.Text(ctx, "now", w - LensInk.TextW("now") - 4, plotH + 1, LensInk.Axis);
+ }
+}
+
+// ===========================================================================
+// SCALE rail slider
+// ===========================================================================
+/// <summary>The thin vertical slider of the Lens SCALE rail: a sunken groove with a
+/// filled column and a bright cap. Drag or wheel; double-click resets.</summary>
+internal sealed class LensVSlider : Control
+{
+ private readonly SolidColorBrush _ink;
+ private double _value;
+ private bool _drag;
+ private double _lastY;
+
+ public double Default { get; set; } = -1;
+ public bool Dragging => _drag;
+ public event Action<double>? ValueChanged;
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+
+ public double Value { get => _value; set { _value = Math.Clamp(value, 0, 1); InvalidateVisual(); } }
+
+ public LensVSlider(double value, SolidColorBrush ink)
+ {
+ _value = Math.Clamp(value, 0, 1);
+ _ink = ink;
+ Width = 16;
+ Cursor = new Cursor(StandardCursorType.SizeNorthSouth);
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2 && Default >= 0) { Value = Default; ValueChanged?.Invoke(_value); e.Handled = true; return; }
+ _drag = true; _lastY = e.GetPosition(this).Y;
+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ if (!_drag) return;
+ double y = e.GetPosition(this).Y;
+ Value = _value + (_lastY - y) / Math.Max(24, Bounds.Height);
+ _lastY = y;
+ ValueChanged?.Invoke(_value);
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_drag) { _drag = false; GestureEnd?.Invoke(); e.Pointer.Capture(null); }
+ }
+ protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
+ {
+ Value = _value + e.Delta.Y * 0.02;
+ ValueChanged?.Invoke(_value);
+ e.Handled = true;
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new Rect(0, 0, w, h);
+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), new RoundedRect(r.Deflate(0.5), w / 2));
+ double fillH = _value * (h - 4);
+ ctx.DrawRectangle(NotaPalette.Wash(_ink, 0x4C), null,
+ new RoundedRect(new Rect(1.5, h - 2 - fillH, w - 3, fillH), (w - 3) / 2));
+ double capY = Math.Clamp(h - 2 - fillH, 2, h - 4);
+ ctx.DrawRectangle(_ink, null, new RoundedRect(new Rect(1, capY - 1, w - 2, 2.5), 1.5));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs
new file mode 100644
index 00000000..19b80b78
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Bodies/LensDeviceBody.cs
@@ -0,0 +1,655 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — built-in Nota Lens body (device kind 22, analyzer), a build of the
+// "Nota Lens" mockup (700 × 260) on the Prism/Chamber frame: a permanent SCALE rail on the
+// left, one large graph in the middle behind Spectrum / Scope / Waterfall tabs, an
+// Analyze / Display panel on the right and a status strip. The scope behaves like a bench
+// instrument — the trace is pinned to the trigger point and stands still while older passes
+// fade out. Every control is a device param, so automation / MIDI learn / presets / A-B /
+// persistence come for free. FullBleed — the shared shell draws the header.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Avalonia.Platform.Storage;
+using Nota.Application;
+using static Nota.App.DeviceCardKit;
+
+namespace Nota.App;
+
+internal sealed class LensDeviceBody : IDeviceBody
+{
+ // ── Parameter indices (must match Lens.h) ────────────────────────────────
+ private const int ViewP = 0, FreezeP = 1, SourceP = 2, MidSideP = 3,
+ FftSizeP = 4, WindowP = 5, AverageP = 6, SmoothP = 7, DecayP = 8, TiltP = 9, FloorP = 10,
+ PeakHoldP = 11, PeakTimeP = 12, ScaleTopP = 13, ScaleRangeP = 14,
+ TimeDivP = 15, VoltDivP = 16, TrigModeP = 17, TrigEdgeP = 18, TrigLevelP = 19, HoldoffP = 20,
+ 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;
+
+ // ── 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;
+
+ private const int L_Spectrum = 0, L_Peak = 1, L_Trace = 2, L_Raw = 3, L_Waterfall = 4;
+ private const int A_Rearm = 0, A_ResetPeak = 1, A_ResetTrigger = 2;
+
+ private static readonly int[] FftSizes = { 512, 2048, 4096, 16384 };
+ private static readonly double[] WfSpans = { 4, 12, 60 };
+ private static readonly double[] Overlaps = { 0, 50, 75, 87.5 };
+
+ private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
+ private static readonly IBrush PanelBg = NotaPalette.SurfaceCard;
+ private static readonly IBrush Border2 = NotaPalette.BorderDefault;
+ private static readonly IBrush Inset = NotaPalette.BgSunken;
+ private static readonly IBrush Amber = NotaPalette.Accent;
+ private static readonly IBrush AmberLit = NotaPalette.AccentBright;
+ private static readonly IBrush TealC = NotaPalette.Teal;
+ private static readonly IBrush TxtC = NotaPalette.TextPrimary;
+ private static readonly IBrush Txt2 = NotaPalette.TextSecondary;
+ private static readonly IBrush MutedC = NotaPalette.TextTertiary;
+
+ /// <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();
+
+ public double Width => 700;
+ public bool FullBleed => true;
+ public string? Subtitle => "ANALYZER";
+
+ public Control Build(DeviceCardContext ctx, int index)
+ {
+ var engine = ctx.Engine;
+ int track = ctx.TrackId, di = index;
+
+ float P(int p) => engine.DeviceGetParam(track, di, p);
+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void Raw(int p, float v) => engine.DeviceSetParam(track, di, p, Math.Clamp(v, 0f, 1f));
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ bool On(int p) => P(p) >= 0.5f;
+ int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1);
+ float Def(int p) => engine.DeviceParamDefault(track, di, p);
+
+ var readouts = new List<Action>();
+ var data = new LensData();
+ var scope = new float[kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+
+ // ---- unit maps (mirror Lens.h) ------------------------------------------------
+ static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ static string Inv(FormattableString f) => NotaNum.F(f);
+ double TimeDiv() => Exp(P(TimeDivP), 0.00002, 0.02);
+ double VoltDiv() => Exp(P(VoltDivP), 0.02, 2.0);
+ double TopDb() => 24 - P(ScaleTopP) * 60;
+ double RangeDb() => 30 + P(ScaleRangeP) * 90;
+ int Avg() => (int)Math.Round(1 + P(AverageP) * 15);
+ double DecayS() => Exp(P(DecayP), 0.05, 8);
+ double PeakS() => Exp(P(PeakTimeP), 0.5, 30);
+ 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 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");
+ static string Hz(double hz) => hz >= 1000 ? Inv($"{hz / 1000:0.00} kHz") : Inv($"{hz:0} Hz");
+ static string Db(double db) => Inv($"{db:0.0} dB");
+ static string Pc(double v) => Inv($"{v * 100:0} %");
+
+ // ---- small builders (same kit as Prism / Chamber) -----------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static Control Docked(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
+ static Control Col(Control c, int col) { Grid.SetColumn(c, col); return c; }
+ Control Learn(Control c, int p) { MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p)); return c; }
+
+ Control K(int p, string name, Func<double, string> fmt, double size = 34, double cellW = 52, IBrush? arc = null)
+ {
+ var val = Mono(fmt(P(p)), 7, TxtC);
+ var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = Def(p), Width = size, Height = size };
+ knob.ValueChanged += v => { Raw(p, (float)v); val.Text = fmt(v); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ readouts.Add(() => { if (knob.Dragging || !knob.IsEffectivelyVisible) return; float c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; val.Text = fmt(c); });
+ return KnobCell(name, knob, val, cellW);
+ }
+
+ Control Toggle(int p, string label)
+ {
+ var wrap = Switch(label, () => On(p), () => SetP(p, On(p) ? 0f : 1f), out var sync);
+ readouts.Add(sync);
+ return Learn(wrap, p);
+ }
+
+ Control Seg(int p, string[] names, Action? changed = null)
+ {
+ int n = names.Length;
+ var seg = DeviceCardKit.Segments(names, () => Sel(p, n), iv => { SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); changed?.Invoke(); }, out var sync);
+ readouts.Add(sync);
+ return Learn(seg, p);
+ }
+
+ Control Row(string label, int p, Func<double, string> fmt, double labW = 48, double valW = 34)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => Math.Clamp(P(p), 0, 1), v => Raw(p, (float)v), () => fmt(Math.Clamp(P(p), 0, 1)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => SetP(p, Def(p)), valueWidth: valW);
+ readouts.Add(() => { if (bar.IsEffectivelyVisible) sync(); });
+ Learn(bar, p);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(Inv($"{labW},*")), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label)); g.Children.Add(Col(bar, 1));
+ return g;
+ }
+
+ // A sunken readout box: a caps eyebrow over one or two mono lines.
+ (Border Box, TextBlock A, TextBlock B) ReadBox(string title, string hintA = "—", string hintB = "")
+ {
+ var a = Mono(hintA, 9, AmberLit);
+ var b = Mono(hintB, 8, Txt2);
+ var box = new Border
+ {
+ Background = Inset, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Control, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 1, Children = { Caps(title), a, b } },
+ };
+ return (box, a, b);
+ }
+
+ Control Button(string text, string tip, Action click)
+ {
+ var b = new Border
+ {
+ Background = NotaPalette.SurfaceRaised, BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, Padding = new Thickness(8, 3), Cursor = new Cursor(StandardCursorType.Hand),
+ HorizontalAlignment = HorizontalAlignment.Stretch,
+ Child = new TextBlock { Text = text, FontSize = 9, Foreground = TxtC, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ ToolTip.SetTip(b, tip);
+ b.PointerPressed += (_, e) => { if (e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) { e.Handled = true; click(); } };
+ return b;
+ }
+
+ // ---- the three graphs ---------------------------------------------------------
+ var spectrum = new LensSpectrumView(data);
+ var scopeView = new LensScopeView(data);
+ var waterfall = new LensWaterfallView(data);
+
+ scopeView.TrigLevelChanged += v => { SetP(TrigLevelP, (float)(v * 0.5 + 0.5)); foreach (var a in readouts) a(); };
+ scopeView.CursorChanged += (which, v) => { SetP(which == 0 ? CursorAP : CursorBP, (float)v); foreach (var a in readouts) a(); };
+
+ // ---- centre tabs --------------------------------------------------------------
+ var curve = new float[LensData.Curve];
+ var wfRow = new float[LensData.WfBins];
+ var wfPend = new float[LensData.WfBins]; // the row being accumulated (see Overlap)
+
+ Control GraphHost(Control topRow, Control graph, Control knobRow) => new DockPanel
+ {
+ LastChildFill = true,
+ Margin = new Thickness(6, 5),
+ Children = { Docked(topRow, Dock.Top), Docked(knobRow, Dock.Bottom), graph },
+ };
+
+ Control KnobRow(params Control[] cells)
+ {
+ var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Height = 52, Margin = new Thickness(0, 4, 0, 0), VerticalAlignment = VerticalAlignment.Center };
+ foreach (var c in cells) sp.Children.Add(c);
+ return sp;
+ }
+
+ // A two-line mono summary that sits to the right of a knob row.
+ (Control Ctl, TextBlock A, TextBlock B) SideNote()
+ {
+ var a = Mono("", 7, MutedC);
+ var b = Mono("", 7, MutedC);
+ return (new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0), Children = { a, b } }, a, b);
+ }
+
+ var specNote = SideNote();
+ var scopeNote = SideNote();
+ var wfNote = SideNote();
+ var specInfo = Mono("", 7, MutedC);
+ var scopeInfo = Mono("", 7, MutedC);
+ var wfInfo = Mono("", 7, MutedC);
+
+ Control TopRow(string label, Control chips, TextBlock info)
+ {
+ var d = new DockPanel { Height = 18, LastChildFill = false, Margin = new Thickness(0, 0, 0, 4) };
+ d.Children.Add(Docked(Caps(label), Dock.Left));
+ var holder = new Border { Margin = new Thickness(6, 0, 0, 0), Child = chips };
+ d.Children.Add(Docked(holder, Dock.Left));
+ info.TextAlignment = TextAlignment.Right;
+ d.Children.Add(Docked(info, Dock.Right));
+ return d;
+ }
+
+ Control SpectrumTab() => GraphHost(
+ TopRow("FFT", Seg(FftSizeP, new[] { "512", "2048", "4096", "16384" }), specInfo),
+ spectrum,
+ KnobRow(K(SmoothP, "Smooth", v => Pc(v), 34, 48, TealC),
+ K(DecayP, "Decay", v => Sec(Exp(v, 0.05, 8)), 34, 48),
+ K(TiltP, "Tilt", v => Inv($"{v * 9:0.0} dB"), 34, 48, TealC),
+ K(FloorP, "Floor", v => Inv($"{-120 + v * 80:0} dB"), 34, 48),
+ specNote.Ctl));
+
+ Control ScopeTab()
+ {
+ var trig = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center,
+ Children = { Seg(TrigModeP, new[] { "Auto", "Normal", "Single" }), Seg(TrigEdgeP, new[] { "↑", "↓" }) },
+ };
+ return GraphHost(
+ TopRow("TRIG", trig, scopeInfo),
+ 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));
+ }
+
+ Control WaterfallTab() => GraphHost(
+ TopRow("SPEED", Seg(WfSpeedP, new[] { "4 s", "12 s", "60 s" }, () => data.ClearWaterfall()), wfInfo),
+ waterfall,
+ KnobRow(K(WfGainP, "Gain", v => Inv($"{-24 + v * 48:+0;−0;0} dB"), 34, 48),
+ K(WfFloorP, "Floor", v => Inv($"{-120 + v * 80:0} dB"), 34, 48),
+ K(WfContrastP, "Contrast", v => Pc(v), 34, 48, TealC),
+ K(WfOverlapP, "Overlap", v => Inv($"{Overlaps[Math.Clamp((int)Math.Round(v * 3), 0, 3)]:0.#} %"), 34, 48, TealC),
+ wfNote.Ctl));
+
+ // ---- right panel --------------------------------------------------------------
+ var cursorBox = ReadBox("CURSOR", "—", "move over the graph");
+ var captureBox = ReadBox("CAPTURE");
+ var measureBox = ReadBox("A → B");
+ var wfCursorBox = ReadBox("CURSOR", "—", "move over the graph");
+
+ spectrum.CursorMoved += () =>
+ {
+ double hz = spectrum.CursorHz;
+ if (hz <= 0) { cursorBox.A.Text = "—"; cursorBox.B.Text = "move over the graph"; return; }
+ cursorBox.A.Text = Inv($"{Hz(hz)} · {LensInk.Note(hz)}");
+ cursorBox.B.Text = Inv($"{spectrum.CursorDb:0.0} dB · bin {(Sc(M_BinHz) > 0 ? hz / Sc(M_BinHz) : 0):0}");
+ };
+ waterfall.CursorMoved += () =>
+ {
+ double hz = waterfall.CursorHz;
+ if (hz <= 0) { wfCursorBox.A.Text = "—"; wfCursorBox.B.Text = "move over the graph"; return; }
+ wfCursorBox.A.Text = Inv($"{Hz(hz)} · {LensInk.Note(hz)}");
+ wfCursorBox.B.Text = Inv($"−{waterfall.CursorAgeSec:0.0} s");
+ };
+
+ Control Stack(params Control[] cs)
+ {
+ var sp = new StackPanel { Spacing = 5, Margin = new Thickness(7, 6) };
+ foreach (var c in cs) sp.Children.Add(c);
+ return sp;
+ }
+
+ Control SpectrumAnalyze() => Stack(
+ new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), Children = { Caps("WINDOW"), Col(Seg(WindowP, new[] { "Hann", "B-H", "Flat" }), 1) } },
+ Row("AVG", AverageP, v => Inv($"{1 + v * 15:0}")),
+ Row("PEAK", PeakTimeP, v => Sec(Exp(v, 0.5, 30))),
+ Row("RATE", RateP, v => Inv($"{10 + v * 50:0} fps")),
+ cursorBox.Box,
+ Toggle(PeakHoldP, "Peak hold"),
+ Toggle(MidSideP, "Mid / Side"));
+
+ Control ScopeAnalyze() => Stack(
+ 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"));
+
+ Control CursorAnalyze() => Stack(
+ measureBox.Box,
+ Row("A POS", CursorAP, v => Ms(v * TimeDiv() * 8)),
+ Row("B POS", CursorBP, v => Ms(v * TimeDiv() * 8)),
+ new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 5,
+ Children =
+ {
+ new Border { Width = 82, Child = Button("Re-arm", "Arm the next Single capture", () => { engine.DeviceAction(track, di, A_Rearm, 0, 0f); foreach (var a in readouts) a(); }) },
+ new Border { Width = 82, Child = Button("Export WAV", "Write the captured scope window to a WAV file", ExportWav) },
+ },
+ },
+ Toggle(CursorSnapP, "Snap to peaks"),
+ Toggle(CursorsP, "Cursors"));
+
+ Control WaterfallAnalyze() => Stack(
+ new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), Children = { Caps("WINDOW"), Col(Seg(WindowP, new[] { "Hann", "B-H", "Flat" }), 1) } },
+ Row("FFT", FftSizeP, v => Inv($"{FftSizes[Math.Clamp((int)Math.Round(v * 3), 0, 3)]}")),
+ Row("OVERLAP", WfOverlapP, v => Inv($"{Overlaps[Math.Clamp((int)Math.Round(v * 3), 0, 3)]:0.#} %")),
+ Row("AVG", AverageP, v => Inv($"{1 + v * 15:0}")),
+ wfCursorBox.Box,
+ Toggle(LogFreqP, "Log frequency"),
+ Toggle(NoteGridP, "Note grid"));
+
+ Control DisplayTab() => Stack(
+ new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), Children = { Caps("SOURCE"), Col(Seg(SourceP, new[] { "L+R", "L", "R" }), 1) } },
+ Row("TOP", ScaleTopP, v => Inv($"{24 - v * 60:0} dB")),
+ Row("RANGE", ScaleRangeP, v => Inv($"{30 + v * 90:0} dB")),
+ Row("RATE", RateP, v => Inv($"{10 + v * 50:0} fps")),
+ Toggle(MidSideP, "Mid / Side"),
+ Toggle(LogFreqP, "Log frequency"),
+ Toggle(NoteGridP, "Note grid"),
+ Toggle(PeakHoldP, "Peak hold"));
+
+ // ---- SCALE rail ---------------------------------------------------------------
+ var railTopVal = Mono("", 7, AmberLit);
+ var railRngVal = Mono("", 7, TxtC);
+
+ // The slider stretches to the rail's height, its caption keeps its own line, and both
+ // retarget when the centre tab changes (dB scale for Spectrum / Waterfall, V and T for Scope).
+ Control RailSlider(Func<int> param, SolidColorBrush ink, Func<string> caption)
+ {
+ var s = new LensVSlider(P(param()), ink) { Default = Def(param()), VerticalAlignment = VerticalAlignment.Stretch };
+ var lbl = Caps(caption(), MutedC);
+ lbl.HorizontalAlignment = HorizontalAlignment.Center;
+ s.GestureBegin += () => Begin(param());
+ s.GestureEnd += () => End(param());
+ s.ValueChanged += v => Raw(param(), (float)v);
+ readouts.Add(() =>
+ {
+ lbl.Text = caption();
+ s.Default = Def(param());
+ if (!s.Dragging) { float c = P(param()); if (Math.Abs(c - s.Value) > 1e-4) s.Value = c; }
+ });
+ var g = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 3, Width = 16 };
+ g.Children.Add(s);
+ Grid.SetRow(lbl, 1); g.Children.Add(lbl);
+ return g;
+ }
+
+ int centreTab = Sel(ViewP, 3);
+ var railA = RailSlider(() => centreTab == 1 ? VoltDivP : ScaleTopP, NotaPalette.Accent, () => centreTab == 1 ? "V/D" : "TOP");
+ var railB = RailSlider(() => centreTab == 1 ? TimeDivP : ScaleRangeP, NotaPalette.Teal, () => centreTab == 1 ? "T/D" : "RNG");
+ var rail = new Border
+ {
+ Width = 56, Background = PanelBg, BorderBrush = Border2, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5),
+ Child = new DockPanel
+ {
+ LastChildFill = true,
+ Children =
+ {
+ Docked(new TextBlock { Text = "SCALE", FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.9, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 0, 0, 4) }, Dock.Top),
+ Docked(new StackPanel { Spacing = 1, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 0), Children = { railTopVal, railRngVal } }, Dock.Bottom),
+ new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 9, HorizontalAlignment = HorizontalAlignment.Center,
+ Children = { railA, railB },
+ },
+ },
+ },
+ };
+ DockPanel.SetDock(rail, Dock.Left);
+
+ // ---- assembly -----------------------------------------------------------------
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[3];
+ var rightBodies = new Control?[4]; // 0 spectrum · 1 scope · 2 waterfall · 3 display
+
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => ScopeTab(), 2 => WaterfallTab(), _ => SpectrumTab() };
+ bool cursorPanel = false;
+ Control RightBody(int t)
+ {
+ if (t == 3) return rightBodies[3] ??= DisplayTab();
+ if (t == 1)
+ {
+ bool want = On(CursorsP);
+ if (rightBodies[1] is null || want != cursorPanel) { cursorPanel = want; rightBodies[1] = want ? CursorAnalyze() : ScopeAnalyze(); }
+ return rightBodies[1]!;
+ }
+ return rightBodies[t] ??= t == 2 ? WaterfallAnalyze() : SpectrumAnalyze();
+ }
+
+ int rightTab = RightTab.TryGetValue((track, di), out var rt) ? rt : 0; // 0 = Analyze, 1 = Display
+
+ var freezeToggle = Switch("Freeze", () => On(FreezeP), () => SetP(FreezeP, On(FreezeP) ? 0f : 1f), out var freezeSync);
+ readouts.Add(freezeSync);
+ Learn(freezeToggle, FreezeP);
+ ToolTip.SetTip(freezeToggle, "Freeze — stop capturing and hold what is on screen");
+
+ var headNote = Mono("", 7, MutedC);
+ var extras = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { freezeToggle, headNote } };
+
+ Control TabFrame(string[] tabs, int initial, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = Math.Clamp(initial, 0, tabs.Length - 1);
+ var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? PanelBg : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Amber : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AmberLit : MutedC;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ int iv = i;
+ var b = new Border
+ {
+ Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent,
+ Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ e.Handled = true; sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv);
+ };
+ btns[i] = b; bar.Children.Add(b);
+ }
+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };
+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Dock.Right); barDock.Children.Add(ex); }
+ if (!centered) DockPanel.SetDock(bar, Dock.Left);
+ barDock.Children.Add(bar);
+ 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);
+ return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
+ }
+
+ 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);
+
+ var rightFrame = TabFrame(new[] { "Analyze", "Display" }, rightTab, rightHost, t =>
+ {
+ rightTab = t; RightTab[(track, di)] = t;
+ return RightBody(t == 1 ? 3 : centreTab);
+ }, true, null, null);
+
+ var right = new Border
+ {
+ Width = 186, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame,
+ };
+ DockPanel.SetDock(right, Dock.Right);
+
+ var centreBox = new Border
+ {
+ Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, Margin = new Thickness(5, 0), ClipToBounds = true, Child = centre,
+ };
+
+ // ---- status strip ---------------------------------------------------------------
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = Txt2, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, Txt2);
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft); statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border
+ {
+ Height = 18, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(0, 1, 0, 0),
+ Padding = new Thickness(8, 0), Child = statusGrid,
+ };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { rail, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { status, bodyRow } };
+
+ // ---- WAV export of the captured scope window --------------------------------------
+ async void ExportWav()
+ {
+ var top = TopLevel.GetTopLevel(scopeView);
+ if (top is null) return;
+ var raw = new float[65536];
+ int n = engine.DeviceLayerWave(track, di, L_Raw, raw, raw.Length);
+ if (n <= 0) return;
+ var file = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
+ {
+ Title = "Export the Lens capture to WAV",
+ DefaultExtension = "wav",
+ SuggestedFileName = "Nota Lens capture.wav",
+ FileTypeChoices = new[] { new FilePickerFileType("WAV audio") { Patterns = new[] { "*.wav" } } },
+ });
+ string? path = file?.TryGetLocalPath();
+ if (path is null) return;
+ int sr = (int)Math.Round(Sc(M_SampleRate) > 0 ? Sc(M_SampleRate) : 48000);
+ using var w = new Nota.Infrastructure.WavWriter(path, sr, 1, WavBitDepth.Float32);
+ w.WriteFrames(raw, n);
+ }
+
+ // ---- the 60 Hz tick ----------------------------------------------------------------
+ var clock = Stopwatch.StartNew();
+ double lastT = 0, wfAcc = 0, ghostAcc = 0;
+
+ void Refresh()
+ {
+ double now = clock.Elapsed.TotalSeconds;
+ double dt = Math.Min(0.25, now - lastT);
+ lastT = now;
+
+ scN = engine.DeviceScope(track, di, scope, kScope);
+ data.SampleRate = Sc(M_SampleRate) > 0 ? Sc(M_SampleRate) : 48000;
+ data.TopDb = TopDb(); data.RangeDb = RangeDb();
+ data.VoltDiv = VoltDiv(); data.TimeDivSec = TimeDiv();
+ data.LogFreq = On(LogFreqP); data.NoteGrid = On(NoteGridP);
+ data.PeakOn = On(PeakHoldP); data.Bright = P(BrightP);
+ data.TrigLevel = (P(TrigLevelP) - 0.5) * 2; data.TrigRising = !On(TrigEdgeP);
+ data.TrigOk = Sc(M_TrigOk) > 0.5; data.Held = Sc(M_Held) > 0.5;
+ data.CursorsOn = On(CursorsP); data.CursorA = P(CursorAP); data.CursorB = P(CursorBP);
+ data.CursorSnap = On(CursorSnapP);
+ data.WfSpanSec = WfSpan();
+
+ if (centreTab == 0)
+ {
+ engine.DeviceLayerWave(track, di, L_Spectrum, data.Spec, LensData.Curve);
+ engine.DeviceLayerWave(track, di, L_Peak, data.Peak, LensData.Curve);
+ spectrum.Tick();
+ }
+ else if (centreTab == 1)
+ {
+ engine.DeviceLayerWave(track, di, L_Trace, data.Trace, LensData.TraceN);
+ data.AgeGhosts(dt);
+ if (On(PersistP))
+ {
+ ghostAcc += dt;
+ double every = PersistS() / Math.Max(1, TraceCount());
+ if (ghostAcc >= every) { ghostAcc = 0; data.PushGhost(PersistS(), TraceCount()); }
+ }
+ else data.Ghosts.Clear();
+ scopeView.GhostLife = PersistS();
+ scopeView.Tick();
+ }
+ else
+ {
+ engine.DeviceLayerWave(track, di, L_Spectrum, data.Spec, LensData.Curve);
+ engine.DeviceLayerWave(track, di, L_Waterfall, wfRow, LensData.WfBins);
+ // Overlap = how much of the time between rows the row actually covers: at 0 %
+ // a row is the single frame that ends it, at 87.5 % it peak-holds nearly the
+ // whole interval, so a transient survives a 60-second window.
+ wfAcc += dt;
+ double rowEvery = WfSpan() / LensData.WfRows;
+ double cover = Overlaps[Sel(WfOverlapP, 4)] / 100.0;
+ if (wfAcc >= rowEvery * (1 - cover))
+ for (int i = 0; i < LensData.WfBins; i++) wfPend[i] = Math.Max(wfPend[i], wfRow[i]);
+ if (wfAcc >= rowEvery)
+ {
+ wfAcc = 0;
+ data.PushWaterfallRow(wfPend);
+ Array.Clear(wfPend);
+ }
+ waterfall.Tick();
+ }
+
+ foreach (var a in readouts) a();
+
+ // Rail readouts + captions follow the active view.
+ railTopVal.Text = centreTab == 1 ? Inv($"{VoltDiv():0.00} /d") : Inv($"{TopDb():0} dB");
+ railRngVal.Text = centreTab == 1 ? Ms(TimeDiv()) : Inv($"{RangeDb():0} dB");
+
+ int fftN = (int)Sc(M_FftN);
+ string winName = new[] { "Hann", "B-H", "Flat" }[Sel(WindowP, 3)];
+ headNote.Text = centreTab == 1
+ ? (data.Held ? "HELD" : 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");
+ 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))}");
+ specNote.B.Text = Inv($"crest {Sc(M_CrestDb):0.0} dB · LUFS {Sc(M_Lufs):0.0}");
+ scopeNote.A.Text = Sc(M_PeriodMs) > 0 ? Inv($"period {Sc(M_PeriodMs):0.000} ms · {Sc(M_FreqHz):0.0} Hz") : "period —";
+ scopeNote.B.Text = Inv($"Vpp {Sc(M_Vpp):0.000} · RMS {Sc(M_Vrms):0.000}");
+ wfNote.A.Text = Inv($"row {WfSpan() / LensData.WfRows * 1000:0} ms · {LensData.WfBins} bins");
+ wfNote.B.Text = Inv($"peak {Hz(Sc(M_PeakHz))} · {Sc(M_PeakDb):0.0} dB");
+
+ captureBox.A.Text = data.Held ? "held" : data.TrigOk ? "stable" : "free-run";
+ captureBox.B.Text = Inv($"holdoff {P(HoldoffP) * 200:0} ms · edge {(On(TrigEdgeP) ? "↓" : "↑")}");
+
+ double dtSec = Math.Abs(P(CursorBP) - P(CursorAP)) * TimeDiv() * 8;
+ measureBox.A.Text = Inv($"Δt {dtSec * 1000:0.000} ms → {(dtSec > 1e-9 ? 1 / dtSec : 0):0.0} Hz");
+ measureBox.B.Text = Inv($"ΔV {Sc(M_CursorBv) - Sc(M_CursorAv):0.000} · {LensInk.Note(dtSec > 1e-9 ? 1 / dtSec : 0)}");
+
+ statusLeft.Text = centreTab switch
+ {
+ 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" : "")}"),
+ };
+ statusLeft.Foreground = On(FreezeP) ? AmberLit : Txt2;
+ statusRight.Text = Inv($"{data.SampleRate / 1000:0.#} kHz · latency 0 smp · {(On(FreezeP) ? "frozen" : Inv($"{10 + P(RateP) * 50:0} fps"))} · corr {Sc(M_Corr):+0.00;−0.00;0.00}");
+
+ // The right Analyze panel follows the centre tab (and the Cursors switch).
+ if (rightTab == 0)
+ {
+ var want = RightBody(centreTab);
+ if (!ReferenceEquals(rightHost.Content, want)) rightHost.Content = want;
+ }
+ }
+
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
index 5c3048ec..34682cc5 100644
--- a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
+++ b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
@@ -40,6 +40,7 @@ internal sealed class DeviceCardFactory
[19] = new ShutterDeviceBody(),
[20] = new ChamberDeviceBody(),
[21] = new PrismDeviceBody(),
+ [22] = new LensDeviceBody(),
};
/// <summary>Resolve the body for a device: -1 = hosted plugin, a mapped built-in kind,
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 039ab5f4..834a6ea1 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -984,6 +984,88 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
("Mid Above Thresh", 0.5f), ("Mid Above Ratio", 0.9f), ("Mid Attack", 0.4248f), ("Mid Release", 0.4334f), ("Mid Gain", 0.625f),
("High Above Thresh", 0.5f), ("High Above Ratio", 0.9f), ("High Attack", 0.4248f), ("High Release", 0.4334f), ("High Gain", 0.625f));
+ // ---- Nota Lens (kind 22) — analyzer, all params normalized 0..1 (unnamed params reset to
+ // their defaults: a 4096-point Hann spectrum, −6 dB top over 90 dB). Discrete choices:
+ // View Spectrum 0 / Scope .5 / Waterfall 1 · Spectrum FFT 512 0 / 2048 .333 / 4096 .667 /
+ // 16384 1 · Window Hann 0 / Blackman-Harris .5 / Flat-top 1 · Scope Trigger Auto 0 /
+ // Normal .5 / Single 1 · Edge rising 0 / falling 1 · Waterfall Speed 4 s 0 / 12 s .5 /
+ // 60 s 1 · Waterfall Overlap 0 % 0 / 50 % .333 / 75 % .667 / 87.5 % 1.
+ // Continuous: Average = (n−1)/15 · Tilt = dB per octave / 9 · Floor / Waterfall Floor =
+ // (dB + 120)/80 · Scale Top = (24 − dB)/60 · Scale Range = (dB − 30)/90 · Waterfall Gain =
+ // (dB + 24)/48 · Rate = (fps − 10)/50 · Level = level/2 + .5 · Holdoff = ms/200 ·
+ // exponential: Decay 0.05…8 s, Peak Time 0.5…30 s, Persist Time 0.05…2 s,
+ // Time/Div 20 µs…20 ms, Volt/Div 0.02…2.
+ // Spectrum
+ Fx("lens", 22, "Mix Overview", ("View", 0f), ("Spectrum FFT", 0.667f), ("Spectrum Average", 0.2f), ("Spectrum Smooth", 0.35f),
+ ("Spectrum Decay", 0.5463f), ("Spectrum Tilt", 0.5f), ("Scale Top", 0.5f), ("Scale Range", 0.667f),
+ ("Spectrum Peak Hold", 1f), ("Spectrum Peak Time", 0.5079f));
+ Fx("lens", 22, "Fine Resolution", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Window", 0.5f), ("Spectrum Average", 0.4667f),
+ ("Spectrum Smooth", 0.2f), ("Spectrum Decay", 0.6702f), ("Scale Top", 0.5f), ("Scale Range", 0.667f), ("Display Rate", 0.4f));
+ Fx("lens", 22, "Fast Response", ("View", 0f), ("Spectrum FFT", 0f), ("Spectrum Average", 0f), ("Spectrum Smooth", 0.15f),
+ ("Spectrum Decay", 0.1366f), ("Spectrum Peak Hold", 0f), ("Display Rate", 1f), ("Scale Range", 0.4667f));
+ Fx("lens", 22, "Low End Focus", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Average", 0.4667f), ("Spectrum Smooth", 0.5f),
+ ("Spectrum Tilt", 0f), ("Scale Top", 0.6f), ("Scale Range", 0.333f), ("Display Note Grid", 1f));
+ Fx("lens", 22, "Tonal Balance", ("View", 0f), ("Spectrum FFT", 0.667f), ("Spectrum Average", 0.4667f), ("Spectrum Smooth", 0.8f),
+ ("Spectrum Tilt", 0.5f), ("Spectrum Decay", 0.8068f), ("Scale Top", 0.4f), ("Scale Range", 0.4667f));
+ Fx("lens", 22, "Peak Finder", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Window", 1f), ("Spectrum Average", 0f),
+ ("Spectrum Smooth", 0f), ("Spectrum Peak Hold", 1f), ("Spectrum Peak Time", 1f), ("Scale Range", 0.778f));
+ Fx("lens", 22, "Flat-Top Calibration", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Window", 1f), ("Spectrum Average", 1f),
+ ("Spectrum Smooth", 0f), ("Spectrum Tilt", 0f), ("Scale Top", 0.4f), ("Scale Range", 0.667f), ("Display Rate", 0.2f));
+ Fx("lens", 22, "Mid / Side Check", ("View", 0f), ("Mid/Side", 1f), ("Source", 0.5f), ("Spectrum FFT", 0.667f),
+ ("Spectrum Tilt", 0.5f), ("Spectrum Smooth", 0.45f), ("Scale Range", 0.667f));
+ Fx("lens", 22, "Noise Floor", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Average", 1f), ("Spectrum Decay", 0.8068f),
+ ("Spectrum Floor", 0f), ("Scale Top", 0.8f), ("Scale Range", 1f), ("Spectrum Peak Hold", 1f), ("Spectrum Peak Time", 1f));
+ Fx("lens", 22, "Tuning Check", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Window", 1f), ("Spectrum Smooth", 0f),
+ ("Spectrum Average", 0.4667f), ("Display Note Grid", 1f), ("Scale Top", 0.6f), ("Scale Range", 0.333f));
+ Fx("lens", 22, "Loudness Watch", ("View", 0f), ("Spectrum FFT", 0.667f), ("Spectrum Tilt", 0.5f), ("Spectrum Average", 1f),
+ ("Spectrum Decay", 0.8068f), ("Scale Top", 0.4f), ("Scale Range", 0.333f), ("Spectrum Peak Hold", 1f));
+ Fx("lens", 22, "Linear Sweep", ("View", 0f), ("Display Log Freq", 0f), ("Spectrum FFT", 1f), ("Spectrum Smooth", 0.2f),
+ ("Spectrum Average", 0.2f), ("Scale Range", 0.667f));
+ // Scope
+ Fx("lens", 22, "Scope · Waveform", ("View", 0.5f), ("Scope Time/Div", 0.667f), ("Scope Volt/Div", 0.699f), ("Scope Trigger", 0f),
+ ("Scope Level", 0.59f), ("Scope Persist", 1f), ("Scope Persist Time", 0.5769f), ("Scope Traces", 0.286f), ("Scope Bright", 0.66f));
+ Fx("lens", 22, "Scope · Transient", ("View", 0.5f), ("Scope Time/Div", 0.466f), ("Scope Volt/Div", 0.8495f), ("Scope Trigger", 0.5f),
+ ("Scope Level", 0.65f), ("Scope Holdoff", 0f), ("Scope Persist", 0f), ("Scope Bright", 1f));
+ Fx("lens", 22, "Scope · Single Shot", ("View", 0.5f), ("Scope Time/Div", 0.799f), ("Scope Volt/Div", 0.8495f), ("Scope Trigger", 1f),
+ ("Scope Level", 0.75f), ("Scope Persist", 0f), ("Cursor On", 1f), ("Cursor A", 0.25f), ("Cursor B", 0.5f));
+ Fx("lens", 22, "Scope · Sub Bass", ("View", 0.5f), ("Scope Time/Div", 0.9f), ("Scope Volt/Div", 0.8495f), ("Scope Trigger", 0f),
+ ("Scope Level", 0.52f), ("Scope Holdoff", 0.1f), ("Scope Persist", 1f), ("Scope Persist Time", 0.7517f), ("Scope Traces", 0.571f));
+ Fx("lens", 22, "Scope · Clip Watch", ("View", 0.5f), ("Scope Time/Div", 1f), ("Scope Volt/Div", 0.8495f), ("Scope Trigger", 0.5f),
+ ("Scope Level", 0.975f), ("Scope Persist", 1f), ("Scope Persist Time", 0.922f), ("Scope Traces", 1f), ("Scope Bright", 1f));
+ Fx("lens", 22, "Scope · Side Signal", ("View", 0.5f), ("Mid/Side", 1f), ("Source", 1f), ("Scope Time/Div", 0.667f),
+ ("Scope Volt/Div", 0.5f), ("Scope Trigger", 0f), ("Scope Persist", 1f), ("Scope Traces", 0.429f));
+ Fx("lens", 22, "Scope · Afterglow", ("View", 0.5f), ("Scope Time/Div", 0.667f), ("Scope Volt/Div", 0.699f), ("Scope Persist", 1f),
+ ("Scope Persist Time", 0.922f), ("Scope Traces", 1f), ("Scope Bright", 1f), ("Scope Trigger", 0f));
+ Fx("lens", 22, "Scope · Cursor Measure",("View", 0.5f), ("Scope Time/Div", 0.667f), ("Scope Volt/Div", 0.699f), ("Scope Trigger", 0.5f),
+ ("Cursor On", 1f), ("Cursor A", 0.25f), ("Cursor B", 0.5f), ("Cursor Snap", 1f), ("Scope Persist", 0f));
+ Fx("lens", 22, "Scope · High Frequency",("View", 0.5f), ("Scope Time/Div", 0.233f), ("Scope Volt/Div", 0.5f), ("Scope Trigger", 0.5f),
+ ("Scope Level", 0.55f), ("Scope Holdoff", 0.01f), ("Scope Persist", 1f), ("Scope Persist Time", 0.1879f));
+ Fx("lens", 22, "Scope · Left Channel", ("View", 0.5f), ("Source", 0.5f), ("Scope Time/Div", 0.667f), ("Scope Volt/Div", 0.699f),
+ ("Scope Trigger", 0f), ("Scope Persist", 1f), ("Scope Traces", 0.286f));
+ Fx("lens", 22, "Scope · Right Channel",("View", 0.5f), ("Source", 1f), ("Scope Time/Div", 0.667f), ("Scope Volt/Div", 0.699f),
+ ("Scope Trigger", 0f), ("Scope Persist", 1f), ("Scope Traces", 0.286f));
+ Fx("lens", 22, "Scope · Falling Edge", ("View", 0.5f), ("Scope Time/Div", 0.566f), ("Scope Volt/Div", 0.699f), ("Scope Trigger", 0.5f),
+ ("Scope Edge", 1f), ("Scope Level", 0.4f), ("Scope Persist", 1f), ("Scope Traces", 0.286f));
+ // Waterfall
+ Fx("lens", 22, "Waterfall · Arrangement",("View", 1f), ("Waterfall Speed", 1f), ("Waterfall Gain", 0.5f), ("Waterfall Floor", 0.375f),
+ ("Waterfall Contrast", 0.7f), ("Waterfall Overlap", 0.667f), ("Spectrum FFT", 0.333f), ("Scale Top", 0.6f));
+ Fx("lens", 22, "Waterfall · Detail", ("View", 1f), ("Waterfall Speed", 0f), ("Spectrum FFT", 1f), ("Waterfall Overlap", 1f),
+ ("Waterfall Contrast", 0.85f), ("Waterfall Gain", 0.625f), ("Waterfall Floor", 0.45f));
+ Fx("lens", 22, "Waterfall · Resonance Hunt",("View", 1f), ("Waterfall Speed", 0.5f), ("Spectrum Window", 0.5f), ("Waterfall Overlap", 0.667f),
+ ("Waterfall Gain", 0.75f), ("Waterfall Floor", 0.525f), ("Waterfall Contrast", 0.9f), ("Display Note Grid", 1f), ("Spectrum FFT", 1f));
+ Fx("lens", 22, "Waterfall · Reverb Tail",("View", 1f), ("Waterfall Speed", 0.5f), ("Waterfall Gain", 0.625f), ("Waterfall Floor", 0.25f),
+ ("Waterfall Contrast", 0.5f), ("Waterfall Overlap", 0.667f), ("Spectrum FFT", 0.667f));
+ Fx("lens", 22, "Waterfall · Noise Print",("View", 1f), ("Waterfall Speed", 1f), ("Waterfall Gain", 0.875f), ("Waterfall Floor", 0f),
+ ("Waterfall Contrast", 1f), ("Spectrum Average", 0.4667f), ("Spectrum FFT", 1f));
+ Fx("lens", 22, "Waterfall · Drum Pattern",("View", 1f), ("Waterfall Speed", 0f), ("Waterfall Gain", 0.625f), ("Waterfall Contrast", 0.9f),
+ ("Waterfall Overlap", 1f), ("Spectrum FFT", 0.333f), ("Spectrum Average", 0f));
+ Fx("lens", 22, "Waterfall · Vocal Formants",("View", 1f), ("Waterfall Speed", 0.5f), ("Spectrum FFT", 0.667f), ("Waterfall Overlap", 0.667f),
+ ("Waterfall Gain", 0.6667f), ("Waterfall Floor", 0.4f), ("Waterfall Contrast", 0.75f), ("Spectrum Smooth", 0.3f));
+ // Bus / master
+ Fx("lens", 22, "Master Bus", ("View", 0f), ("Spectrum FFT", 1f), ("Spectrum Window", 0.5f), ("Spectrum Tilt", 0.5f),
+ ("Spectrum Average", 0.4667f), ("Spectrum Smooth", 0.45f), ("Scale Top", 0.4f), ("Scale Range", 0.667f),
+ ("Spectrum Peak Hold", 1f), ("Spectrum Peak Time", 0.6772f));
+
// ---- Compressor (kind 1) — Thresh -60..0, Ratio 1..20, Attack .1..100 ms, Release 5..1000 ms, Makeup 0..24 dB
// Character: Clean 0 / Glue 1 / Punch 2 / Opto 3 / FET 4.
Fx("comp", 1, "Drum Glue", ("Character", 1f), ("Thresh", -18f), ("Ratio", 3f), ("Attack", 30f), ("Release", 200f), ("Knee", 8f), ("AutoGain", 1f), ("Mix", 100f));
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index dfb31163..433d75b7 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -20,6 +20,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
(6, "Nota Valve"), (7, "Auto Filter"), (8, "Nota Vintage"), (9, "Nota Orbit"), (10, "Auto Shift"),
(11, "Beat Repeat"), (12, "Crush"), (13, "Dynamic EQ-8"), (14, "Ceiling"), (15, "Strata"),
(16, "EQ-3"), (17, "Forge"), (18, "Nota Level"), (19, "Nota Shutter"), (20, "Nota Chamber"), (21, "Nota Prism"),
+ (22, "Nota Lens"),
};
public sealed record DeviceKind(int Kind, string Name);
@@ -66,6 +67,49 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
- [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR).")]
+ [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed.")]
public Task<string> GetDeviceText(int trackId, int deviceIndex, int id) => Read(() => E.DeviceText(trackId, deviceIndex, id));
+
+ public sealed record AnalyzerBand(double Hz, double Db);
+ public sealed record AnalyzerPeak(double Hz, double Db, string Note);
+ public sealed record AnalyzerReading(string Summary, string Scope, string Cursors, AnalyzerBand[] Bands, AnalyzerPeak[] Peaks);
+
+ [McpServerTool(Name = "read_analyzer"), Description(
+ "Read what a Nota Lens (built-in effect kind 22) is measuring on a track right now: a summary line "
+ + "(loudest spectral peak, RMS, crest factor, momentary LUFS, L/R correlation), the scope measurements "
+ + "(trigger state, window, period and frequency, Vpp, Vrms), the A/B cursor measurements, the 31 "
+ + "third-octave band levels in dB, and the strongest spectral peaks with their note names. The reading "
+ + "reflects the Lens's own parameters — FFT size, window, averaging, tilt, source (L+R / L / R, or "
+ + "Mid/Side) and Freeze — so set those with set_device_param first. Add a Lens with add_device (kind 22) "
+ + "on the track you want to measure; the analyzer passes audio through untouched.")]
+ public Task<AnalyzerReading> ReadAnalyzer(int trackId, int deviceIndex) => Read(() =>
+ {
+ var bands = new List<AnalyzerBand>();
+ foreach (var line in E.DeviceText(trackId, deviceIndex, 1).Split('\n', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var f = line.Split('\t');
+ if (f.Length >= 2 && Num(f[0]) is { } hz && Num(f[1]) is { } db) bands.Add(new AnalyzerBand(hz, db));
+ }
+ var peaks = new List<AnalyzerPeak>();
+ foreach (var line in E.DeviceText(trackId, deviceIndex, 3).Split('\n', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var f = line.Split('\t');
+ if (f.Length >= 3 && Num(f[0]) is { } hz && Num(f[1]) is { } db) peaks.Add(new AnalyzerPeak(hz, db, f[2].Trim()));
+ }
+ return new AnalyzerReading(
+ E.DeviceText(trackId, deviceIndex, 0),
+ E.DeviceText(trackId, deviceIndex, 2),
+ E.DeviceText(trackId, deviceIndex, 4),
+ bands.ToArray(), peaks.ToArray());
+ });
+
+ // "20 Hz" / "−18.4 dB" → the number, or null when the field is not one.
+ private static double? Num(string s)
+ {
+ var t = s.Trim().Replace('−', '-');
+ int end = 0;
+ while (end < t.Length && (char.IsDigit(t[end]) || t[end] is '-' or '+' or '.')) end++;
+ return double.TryParse(t[..end], System.Globalization.NumberStyles.Float,
+ System.Globalization.CultureInfo.InvariantCulture, out var v) ? v : null;
+ }
}
diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
index b6fffe2d..11d9a88f 100644
--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
@@ -242,6 +242,7 @@ public sealed partial class BrowserViewModel : ObservableObject
new() { Name = "Nota EQ-8", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 0, Sub = "8-band EQ" },
new() { Name = "Nota Compressor", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 1, Sub = "built-in" },
new() { Name = "Nota Prism", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 21, Sub = "multiband dynamics" },
+ new() { Name = "Nota Lens", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 22, Sub = "analyzer / scope" },
new() { Name = "Nota Reverb", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 2, Sub = "built-in" },
new() { Name = "Nota Chamber", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 20, Sub = "hybrid reverb" },
new() { Name = "Nota Delay", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 3, Sub = "built-in" },
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index 6f5c5af6..2b41958e 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -21,6 +21,7 @@
#include "AutoGain.h"
#include "Shutter.h"
#include "Chamber.h"
+#include "Lens.h"
#include "Prism.h"
#include "Ceiling.h"
#include "Strata.h"
@@ -444,6 +445,7 @@ int32_t Engine::addTrackBuiltinDevice(int32_t trackId, int32_t kind) {
else if (kind == 19) dev = std::make_shared<Shutter>();
else if (kind == 20) dev = std::make_shared<Chamber>();
else if (kind == 21) dev = std::make_shared<Prism>();
+ else if (kind == 22) dev = std::make_shared<Lens>();
else return -1;
dev->setSampleRate(transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0, kMaxBlock);
if (kind == 5) if (auto* rk = dynamic_cast<RackDevice*>(dev.get())) rk->addChain(-1); // one pass-through chain
@@ -508,6 +510,7 @@ std::shared_ptr<Device> Engine::cloneDevice(const Device& src) const {
case 19: d = std::make_shared<Shutter>(); break;
case 20: d = std::make_shared<Chamber>(); break;
case 21: d = std::make_shared<Prism>(); break;
+ case 22: d = std::make_shared<Lens>(); break;
default: d = src.clone(); break; // hosted plugin
}
if (!d) return nullptr;
@@ -584,6 +587,7 @@ static std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {
case 19: return std::make_shared<Shutter>();
case 20: return std::make_shared<Chamber>();
case 21: return std::make_shared<Prism>();
+ case 22: return std::make_shared<Lens>();
default: return nullptr; // Rack / plugin: no simple per-param default
}
}
diff --git a/src/native/nota.engine/src/Lens.h b/src/native/nota.engine/src/Lens.h
new file mode 100644
index 00000000..0d61c812
--- /dev/null
+++ b/src/native/nota.engine/src/Lens.h
@@ -0,0 +1,751 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Lens (device kind 22, mockup "Nota Lens") — an analyzer: FFT spectrum,
+// triggered oscilloscope and waterfall in one card. The audio passes through
+// untouched; process() only captures L/R into rings and runs the K-weighted
+// loudness follower. Everything expensive (FFT, the log-frequency curve, trigger
+// search, measurements) happens lazily on the message thread inside
+// ensureAnalyzed(), rate-limited by the Display Rate parameter — so the audio
+// thread stays a memcpy and the UI (or MCP) pulls whatever it needs:
+//
+// scopeRead → packed measurements (peak, RMS, crest, correlation, LUFS,
+// trigger state, period, Vpp, cursors …)
+// layerWave → L_Spectrum / L_Peak curves, the scope trace, the raw triggered
+// window (for WAV export) and the newest waterfall row
+// deviceText → the same analysis as text, for MCP
+// deviceAction→ re-arm Single, reset peak hold, reset the trigger
+//
+// A core Device (JUCE-free); params normalized 0..1, denormalized where used.
+// Persistence / automation / clone flow generically through the base Device.
+
+#pragma once
+
+#include "Device.h"
+
+#include "signalsmith-linear/fft.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cmath>
+#include <complex>
+#include <cstdint>
+#include <cstdio>
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace nota {
+
+class Lens : public Device {
+public:
+ enum {
+ View = 0, // 0 Spectrum · .5 Scope · 1 Waterfall
+ Freeze, // >= .5 holds the capture (rings stop advancing)
+ Source, // 0 L+R · .5 first channel · 1 second channel
+ MidSide, // >= .5 the channel pair is Mid/Side instead of L/R
+
+ FftSize, // 0 512 · .333 2048 · .667 4096 · 1 16384
+ Window, // 0 Hann · .5 Blackman-Harris · 1 Flat-top
+ Average, // 1..16 frames
+ Smooth, // 0..1 neighbour-bin smoothing
+ Decay, // trace fall, exp 0.05..8 s
+ Tilt, // 0..9 dB/oct pink-slope compensation
+ Floor, // −120..−40 dB
+ PeakHold, // >= .5 draw the peak-hold trace
+ PeakTime, // hold before the peak falls, exp 0.5..30 s
+
+ ScaleTop, // top of the dB axis, +24..−36 dB
+ ScaleRange, // visible span, 30..120 dB
+
+ TimeDiv, // exp 0.02..20 ms per division (8 divisions across)
+ VoltDiv, // exp 0.02..2 per division (4 divisions high)
+ TrigMode, // 0 Auto · .5 Normal · 1 Single
+ TrigEdge, // 0 rising · 1 falling
+ TrigLevel, // −1..1
+ Holdoff, // 0..200 ms
+ Persist, // >= .5 afterglow
+ PersistTime, // exp 50..2000 ms
+ Traces, // 1..8 ghost traces
+ Bright, // 0..1 trace brightness
+
+ Cursors, // >= .5 show the A/B cursors
+ CursorA, // 0..1 across the window
+ CursorB,
+ CursorSnap, // >= .5 snap a cursor to the nearest peak
+
+ WfSpeed, // 0 4 s · .5 12 s · 1 60 s of history
+ WfGain, // −24..+24 dB
+ WfFloor, // −120..−40 dB
+ WfContrast, // 0..1
+ WfOverlap, // 0 0 % · .333 50 % · .667 75 % · 1 87.5 %
+
+ LogFreq, // >= .5 logarithmic frequency axis
+ NoteGrid, // >= .5 draw the note grid
+ Rate, // display refresh, 10..60 fps
+ kNumParams
+ };
+
+ // scopeRead payload — packed measurements, not a signal (mirrors Shutter).
+ enum {
+ M_PeakHz = 0, // loudest spectral peak
+ M_PeakDb,
+ M_RmsDb, // analysis-signal RMS over the FFT window
+ M_LevelDb, // analysis-signal peak over the same window
+ M_CrestDb,
+ M_Corr, // L/R correlation, −1..1
+ M_Lufs, // momentary (400 ms) K-weighted loudness
+ M_TrigOk, // 1 = the trace is locked to a trigger
+ M_PeriodMs, // measured period of the scope trace (0 = none)
+ M_FreqHz, // 1 / period
+ M_Vpp,
+ M_Vrms,
+ M_WindowMs, // scope window (8 divisions)
+ M_BinHz, // FFT resolution
+ M_FftN,
+ M_FftMs, // FFT window in ms
+ M_CursorAv, // trace value under cursor A / B
+ M_CursorBv,
+ M_SampleRate,
+ M_Held, // 1 = frozen or a finished Single capture
+ kScope
+ };
+
+ // layerWave layers.
+ enum { L_Spectrum = 0, L_Peak, L_Trace, L_Raw, L_Waterfall };
+
+ // deviceAction ids.
+ enum { A_Rearm = 0, A_ResetPeak, A_ResetTrigger };
+
+ static constexpr int kCurve = 512; // points in a spectrum curve
+ static constexpr int kTrace = 512; // points in a scope trace
+ static constexpr int kWfBins = 256; // bins in a waterfall row
+
+ Lens() {
+ p_[View].store(0.0f);
+ p_[Freeze].store(0.0f);
+ p_[Source].store(0.0f);
+ p_[MidSide].store(0.0f);
+ p_[FftSize].store(0.667f); // 4096
+ p_[Window].store(0.0f); // Hann
+ p_[Average].store(0.2f); // ~4 frames
+ p_[Smooth].store(0.35f);
+ p_[Decay].store(0.45f); // ~0.8 s
+ p_[Tilt].store(0.0f);
+ p_[Floor].store(0.3f); // −96 dB
+ p_[PeakHold].store(1.0f);
+ p_[PeakTime].store(0.45f); // ~4 s
+ p_[ScaleTop].store(0.5f); // −6 dB
+ p_[ScaleRange].store(0.667f); // 90 dB
+ p_[TimeDiv].store(0.667f); // ~2 ms/div
+ p_[VoltDiv].store(0.7f); // ~0.5/div
+ p_[TrigMode].store(0.0f); // Auto
+ p_[TrigEdge].store(0.0f); // rising
+ p_[TrigLevel].store(0.59f); // +0.18
+ p_[Holdoff].store(0.06f); // 12 ms
+ p_[Persist].store(1.0f);
+ p_[PersistTime].store(0.58f); // ~420 ms
+ p_[Traces].store(0.286f); // 3
+ p_[Bright].store(0.66f);
+ p_[Cursors].store(0.0f);
+ p_[CursorA].store(0.25f);
+ p_[CursorB].store(0.375f);
+ p_[CursorSnap].store(0.0f);
+ p_[WfSpeed].store(0.5f); // 12 s
+ p_[WfGain].store(0.625f); // +6 dB
+ p_[WfFloor].store(0.375f); // −90 dB
+ p_[WfContrast].store(0.7f);
+ p_[WfOverlap].store(0.667f); // 75 %
+ p_[LogFreq].store(1.0f);
+ p_[NoteGrid].store(0.0f);
+ p_[Rate].store(0.4f); // 30 fps
+ setSampleRate(44100.0, 0);
+ }
+
+ void setSampleRate(double sr, int32_t /*maxBlock*/) override {
+ std::lock_guard<std::mutex> lock(mx_);
+ sr_ = sr > 0 ? sr : 44100.0;
+ ringL_.assign(kRing, 0.0f);
+ ringR_.assign(kRing, 0.0f);
+ ringW_.store(0, std::memory_order_relaxed);
+ curve_.assign(kCurve, -200.0f);
+ peak_.assign(kCurve, -200.0f);
+ peakAge_.assign(kCurve, 0.0f);
+ avg_.assign(kMaxFft / 2, -200.0f);
+ binDb_.assign(kMaxFft / 2, -200.0f);
+ trace_.assign(kTrace, 0.0f);
+ rawWin_.assign(kMaxWin, 0.0f);
+ rawLen_ = 0;
+ wfRow_.assign(kWfBins, 0.0f);
+ fftN_ = 0;
+ lastAnalyzeS_ = -1.0;
+ trigPos_ = 0; trigOk_ = false; armed_ = true; singleDone_ = false;
+ kInit();
+ lufsBlock_ = std::max(64, (int)std::lround(sr_ * 0.008)); // 8 ms sub-blocks
+ lufsRing_.assign(kLufsBlocks, 0.0);
+ lufsIdx_ = 0; lufsAcc_ = 0.0; lufsN_ = 0;
+ }
+
+ // Analyzer: the signal passes through untouched.
+ void process(float* buf, int32_t frames) override {
+ const bool frozen = get(Freeze) >= 0.5f;
+ 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) {
+ ringL_[w & (kRing - 1)] = l;
+ ringR_[w & (kRing - 1)] = r;
+ ++w;
+ }
+ corrLR += (double)l * r; corrLL += (double)l * l; corrRR += (double)r * r;
+ // K-weighted loudness (BS.1770): shelf then high-pass, per channel.
+ const float kl = kFilter(l, ks_[0]), kr = kFilter(r, ks_[1]);
+ lufsAcc_ += (double)kl * kl + (double)kr * kr;
+ if (++lufsN_ >= lufsBlock_) {
+ lufsRing_[lufsIdx_] = lufsAcc_ / (lufsN_ * 2);
+ lufsIdx_ = (lufsIdx_ + 1) % kLufsBlocks;
+ lufsAcc_ = 0.0; 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);
+ }
+ }
+ if (!frozen) ringW_.store(w, std::memory_order_relaxed);
+ 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);
+ }
+
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples < kScope) return 0;
+ std::lock_guard<std::mutex> lock(mx_);
+ ensureAnalyzed();
+ out[M_PeakHz] = mPeakHz_;
+ out[M_PeakDb] = mPeakDb_;
+ out[M_RmsDb] = mRmsDb_;
+ out[M_LevelDb] = mLevelDb_;
+ out[M_CrestDb] = mLevelDb_ - mRmsDb_;
+ out[M_Corr] = corr_.load(std::memory_order_relaxed);
+ out[M_Lufs] = lufs_.load(std::memory_order_relaxed);
+ out[M_TrigOk] = trigOk_ ? 1.0f : 0.0f;
+ out[M_PeriodMs] = mPeriodMs_;
+ out[M_FreqHz] = mPeriodMs_ > 1e-6f ? 1000.0f / mPeriodMs_ : 0.0f;
+ out[M_Vpp] = mVpp_;
+ out[M_Vrms] = mVrms_;
+ out[M_WindowMs] = (float)(windowSamples() * 1000.0 / sr_);
+ out[M_BinHz] = fftN_ > 0 ? (float)(sr_ / fftN_) : 0.0f;
+ out[M_FftN] = (float)fftN_;
+ out[M_FftMs] = fftN_ > 0 ? (float)(fftN_ * 1000.0 / sr_) : 0.0f;
+ out[M_CursorAv] = traceAt(get(CursorA));
+ 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;
+ return kScope;
+ }
+
+ int32_t layerWave(int32_t layer, float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ std::lock_guard<std::mutex> lock(mx_);
+ ensureAnalyzed();
+ switch (layer) {
+ case L_Spectrum: return copyOut(curve_.data(), kCurve, out, maxSamples);
+ case L_Peak: return copyOut(peak_.data(), kCurve, out, maxSamples);
+ 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);
+ default: return 0;
+ }
+ }
+
+ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {
+ std::lock_guard<std::mutex> lock(mx_);
+ switch (id) {
+ case A_Rearm: armed_ = true; singleDone_ = false; break;
+ case A_ResetPeak:
+ for (int i = 0; i < kCurve; ++i) { peak_[i] = -200.0f; peakAge_[i] = 0.0f; }
+ break;
+ case A_ResetTrigger: trigPos_ = 0; trigOk_ = false; break;
+ default: break;
+ }
+ }
+
+ // Text reports, for MCP (get_device_text) and the smoke test.
+ std::string deviceText(int32_t id) const override {
+ std::lock_guard<std::mutex> lock(mx_);
+ ensureAnalyzed();
+ char b[256];
+ switch (id) {
+ case 0: { // one-line summary
+ std::snprintf(b, sizeof b,
+ "%s · %s · peak %.1f Hz %.1f dB · rms %.1f dB · crest %.1f dB · LUFS %.1f · corr %+.2f",
+ viewName(), sourceName(), mPeakHz_, mPeakDb_, mRmsDb_,
+ mLevelDb_ - mRmsDb_, lufs_.load(std::memory_order_relaxed),
+ corr_.load(std::memory_order_relaxed));
+ return b;
+ }
+ case 1: { // third-octave band table
+ std::string s;
+ for (int i = 0; i < kBands; i++) {
+ std::snprintf(b, sizeof b, "%.0f Hz\t%.1f dB\n", kBandHz[i], bandDb(kBandHz[i]));
+ s += b;
+ }
+ return s;
+ }
+ case 2: { // scope measurements
+ const double winMs = windowSamples() * 1000.0 / sr_;
+ 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;
+ }
+ case 3: { // strongest spectral peaks, with note names
+ std::string s;
+ for (auto& pk : topPeaks(8)) {
+ std::snprintf(b, sizeof b, "%.1f Hz\t%.1f dB\t%s\n", pk.hz, pk.db, noteName(pk.hz).c_str());
+ s += b;
+ }
+ return s.empty() ? "(no peaks above the floor)" : s;
+ }
+ case 4: { // cursor measurements
+ const double winSec = windowSamples() / sr_;
+ const double a = get(CursorA) * winSec, bb = get(CursorB) * winSec;
+ const double dt = std::fabs(bb - a);
+ std::snprintf(b, sizeof b, "A %.3f ms · B %.3f ms · dt %.3f ms (%.1f Hz) · dV %.3f",
+ a * 1000, bb * 1000, dt * 1000, dt > 1e-9 ? 1.0 / dt : 0.0,
+ traceAt(get(CursorB)) - traceAt(get(CursorA)));
+ return b;
+ }
+ default: return {};
+ }
+ }
+
+ const char* displayName() const override { return "Nota Lens"; }
+ int32_t builtinKind() const override { return 22; }
+
+ int32_t paramCount() const override { return kNumParams; }
+ const char* paramName(int32_t i) const override {
+ static const char* nm[] = {
+ "View", "Freeze", "Source", "Mid/Side",
+ "Spectrum FFT", "Spectrum Window", "Spectrum Average", "Spectrum Smooth",
+ "Spectrum Decay", "Spectrum Tilt", "Spectrum Floor", "Spectrum Peak Hold", "Spectrum Peak Time",
+ "Scale Top", "Scale Range",
+ "Scope Time/Div", "Scope Volt/Div", "Scope Trigger", "Scope Edge", "Scope Level",
+ "Scope Holdoff", "Scope Persist", "Scope Persist Time", "Scope Traces", "Scope Bright",
+ "Cursor On", "Cursor A", "Cursor B", "Cursor Snap",
+ "Waterfall Speed", "Waterfall Gain", "Waterfall Floor", "Waterfall Contrast", "Waterfall Overlap",
+ "Display Log Freq", "Display Note Grid", "Display Rate",
+ };
+ return (i >= 0 && i < kNumParams) ? nm[i] : "";
+ }
+ float paramMin(int32_t /*i*/) const override { return 0.0f; }
+ float paramMax(int32_t /*i*/) const override { return 1.0f; }
+ float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
+ void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
+
+ // ---- 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); }
+ 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)]; }
+
+private:
+ static constexpr double kPi = 3.14159265358979323846;
+ static constexpr int kRing = 32768; // power of two, per channel
+ static constexpr int kMaxFft = 16384;
+ static constexpr int kMaxWin = 16384; // longest scope window we keep raw
+ static constexpr int kLufsBlocks = 50; // 50 × 8 ms = 400 ms momentary window
+ static constexpr int kBands = 31; // ISO third-octave centres, 20 Hz … 20 kHz
+
+ static constexpr double kBandHz[kBands] = {
+ 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630,
+ 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000, 20000 };
+
+ struct Peak { double hz; double db; };
+
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
+ 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); }
+
+ static int32_t copyOut(const float* src, int n, float* out, int32_t maxSamples) {
+ const int32_t k = std::min<int32_t>(n, maxSamples);
+ if (k > 0) std::copy(src, src + k, out);
+ return k;
+ }
+
+ // ---- K-weighting (BS.1770) ------------------------------------------
+ struct Biquad { double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0; };
+ struct KState { double z1[2] = { 0, 0 }, z2[2] = { 0, 0 }; };
+
+ void kInit() {
+ { // stage 1: high shelf, +4 dB at 1681.97 Hz
+ const double f0 = 1681.974450955533, Q = 0.7071752369554196, G = 3.999843853973347;
+ const double K = std::tan(kPi * f0 / sr_), Vh = std::pow(10.0, G / 20.0);
+ const double Vb = std::pow(Vh, 0.4996667741545416);
+ const double a0 = 1 + K / Q + K * K;
+ kb_[0] = { (Vh + Vb * K / Q + K * K) / a0, 2 * (K * K - Vh) / a0, (Vh - Vb * K / Q + K * K) / a0,
+ 2 * (K * K - 1) / a0, (1 - K / Q + K * K) / a0 };
+ }
+ { // stage 2: high pass at 38.14 Hz
+ const double f0 = 38.13547087602444, Q = 0.5003270373238773;
+ const double K = std::tan(kPi * f0 / sr_);
+ const double a0 = 1 + K / Q + K * K;
+ kb_[1] = { 1.0 / a0, -2.0 / a0, 1.0 / a0, 2 * (K * K - 1) / a0, (1 - K / Q + K * K) / a0 };
+ }
+ ks_[0] = ks_[1] = {};
+ }
+ float kFilter(float x, KState& st) const {
+ double y = x;
+ for (int s = 0; s < 2; ++s) {
+ const Biquad& c = kb_[s];
+ const double o = c.b0 * y + st.z1[s];
+ st.z1[s] = c.b1 * y - c.a1 * o + st.z2[s];
+ st.z2[s] = c.b2 * y - c.a2 * o;
+ y = o;
+ }
+ return (float)y;
+ }
+
+ // ---- analysis signal --------------------------------------------------
+ // The channel pair is L/R or Mid/Side; Source picks the sum or one of them.
+ // The selection is hoisted out of the sample loops (pick), so a 16 k FFT
+ // window costs two array reads per sample, not four atomic loads.
+ float pick(uint32_t idx, bool ms, int src) const {
+ const size_t i = idx & (kRing - 1);
+ const float l = ringL_[i], r = ringR_[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);
+ }
+ bool msOn() const { return get(MidSide) >= 0.5f; }
+ int srcIdx() const { return step(get(Source), 3); }
+
+ int windowSamples() const {
+ return std::clamp((int)std::lround(timeDivSec(get(TimeDiv)) * 8.0 * sr_), 16, kMaxWin);
+ }
+
+ float traceAt(float pos) const {
+ const double x = std::clamp((double)pos, 0.0, 1.0) * (kTrace - 1);
+ const int i = std::min((int)x, kTrace - 2);
+ const double f = x - i;
+ return (float)(trace_[i] * (1 - f) + trace_[i + 1] * f);
+ }
+
+ // ---- the analysis pass ------------------------------------------------
+ // Called under mx_ from every read entry point; recomputes at most once per
+ // 1/Rate seconds and only when the audio thread has produced a new block.
+ void ensureAnalyzed() const {
+ const double now = nowSeconds();
+ const double period = 1.0 / std::clamp(10.0 + get(Rate) * 50.0, 10.0, 60.0);
+ const uint32_t seq = frameSeq_.load(std::memory_order_relaxed);
+ if (lastAnalyzeS_ >= 0 && now - lastAnalyzeS_ < period && seq == lastSeq_) return;
+ const double dt = lastAnalyzeS_ < 0 ? period : std::min(now - lastAnalyzeS_, 0.5);
+ lastAnalyzeS_ = now; lastSeq_ = seq;
+
+ analyzeSpectrum(dt);
+ analyzeScope();
+ }
+
+ void analyzeSpectrum(double dt) const {
+ const int n = fftSizeOf(get(FftSize));
+ if (n != fftN_) {
+ fft_.resize((size_t)n);
+ freq_.assign((size_t)n / 2, {});
+ time_.assign((size_t)n, 0.0f);
+ win_.assign((size_t)n, 0.0f);
+ std::fill(avg_.begin(), avg_.end(), -200.0f); // bins mean new frequencies now
+ fftN_ = n; winKind_ = -1;
+ }
+ const int wk = step(get(Window), 3);
+ if (wk != winKind_) { buildWindow(wk, n); winKind_ = wk; }
+
+ const uint32_t head = ringW_.load(std::memory_order_relaxed);
+ const uint32_t start = head - (uint32_t)n;
+ const bool ms = msOn(); const int src = srcIdx();
+ double sumSq = 0; float peakLin = 0;
+ for (int i = 0; i < n; ++i) {
+ const float s = pick(start + (uint32_t)i, ms, src);
+ sumSq += (double)s * s;
+ peakLin = std::max(peakLin, std::fabs(s));
+ time_[i] = s * win_[i];
+ }
+ mRmsDb_ = (float)db(std::sqrt(sumSq / n));
+ mLevelDb_ = (float)db(peakLin);
+
+ fft_.fft(time_.data(), freq_.data());
+ const int bins = n / 2;
+ const double ref = winSum_ * 0.5; // full-scale sine → 0 dBFS
+ const double alpha = 1.0 / std::max(1.0, std::round(1.0 + get(Average) * 15.0));
+ for (int k = 1; k < bins; ++k) {
+ const double mag = std::abs(freq_[(size_t)k]);
+ const double d = db(mag / std::max(1e-12, ref));
+ float& a = avg_[(size_t)k];
+ if (a < -190.0f) a = (float)d; else a = (float)(a + alpha * (d - a));
+ binDb_[(size_t)k] = a;
+ }
+ binDb_[0] = binDb_[1];
+
+ // Neighbour smoothing: a widening box over the log axis reads as the
+ // classic "1/6 octave" smoothing without a second FFT.
+ // Averaged in the POWER domain, not in dB: a dB-domain box drags a narrow peak
+ // several dB down and the readout stops matching the signal.
+ const int sm = (int)std::lround(get(Smooth) * 6.0);
+ if (sm > 0) {
+ smTmp_.resize((size_t)bins);
+ for (int k = 0; k < bins; ++k) smTmp_[(size_t)k] = (float)std::pow(10.0, binDb_[(size_t)k] * 0.1);
+ for (int k = 0; k < bins; ++k) {
+ const int w = 1 + (int)(sm * (0.2 + 2.0 * k / (double)bins));
+ const int j0 = std::max(0, k - w), j1 = std::min(bins - 1, k + w);
+ double run = 0;
+ for (int j = j0; j <= j1; ++j) run += smTmp_[(size_t)j];
+ binDb_[(size_t)k] = (float)(10.0 * std::log10(std::max(1e-20, run / (j1 - j0 + 1))));
+ }
+ }
+
+ // Map the bins onto the log-frequency curve, applying tilt and floor,
+ // then apply the fall ballistic and the peak hold.
+ const double fLo = 20.0, fHi = std::min(20000.0, sr_ * 0.45);
+ const double tilt = get(Tilt) * 9.0;
+ const double floorDb = -120.0 + get(Floor) * 80.0;
+ const double fallDb = dt / std::max(0.01, expMap(get(Decay), 0.05, 8.0)) * 90.0;
+ const double holdS = expMap(get(PeakTime), 0.5, 30.0);
+ const bool peakOn = get(PeakHold) >= 0.5f;
+ double best = -400, bestHz = 0;
+ for (int i = 0; i < kCurve; ++i) {
+ const double f = fLo * std::pow(fHi / fLo, i / (double)(kCurve - 1));
+ const double f0 = i == 0 ? f : std::sqrt(f * fLo * std::pow(fHi / fLo, (i - 1) / (double)(kCurve - 1)));
+ const double f1 = i == kCurve - 1 ? f : std::sqrt(f * fLo * std::pow(fHi / fLo, (i + 1) / (double)(kCurve - 1)));
+ const double binHz = sr_ / n;
+ const int k0 = std::clamp((int)std::floor(f0 / binHz), 1, bins - 1);
+ const int k1 = std::clamp((int)std::ceil(f1 / binHz), 1, bins - 1);
+ double v;
+ if (k1 <= k0) {
+ const double x = std::clamp(f / binHz, 1.0, bins - 1.0);
+ const int ka = (int)x; const double fr = x - ka;
+ v = binDb_[(size_t)ka] * (1 - fr) + binDb_[(size_t)std::min(ka + 1, bins - 1)] * fr;
+ } else {
+ v = -400;
+ for (int k = k0; k <= k1; ++k) v = std::max(v, (double)binDb_[(size_t)k]);
+ }
+ v += tilt * std::log2(f / 1000.0);
+ v = std::max(v, floorDb);
+ if (v > best) { best = v; bestHz = f; }
+
+ float& c = curve_[(size_t)i];
+ c = v >= c ? (float)v : (float)std::max(v, c - fallDb);
+ if (peakOn) {
+ if (c >= peak_[(size_t)i]) { peak_[(size_t)i] = c; peakAge_[(size_t)i] = 0.0f; }
+ else {
+ peakAge_[(size_t)i] += (float)dt;
+ if (peakAge_[(size_t)i] > holdS)
+ peak_[(size_t)i] = (float)std::max((double)c, peak_[(size_t)i] - fallDb * 0.5);
+ }
+ } else { peak_[(size_t)i] = c; peakAge_[(size_t)i] = 0.0f; }
+ }
+ mPeakHz_ = (float)bestHz;
+ mPeakDb_ = (float)best;
+
+ // Waterfall row: the same curve, resampled and normalized to 0..1.
+ const double wfGain = -24.0 + get(WfGain) * 48.0;
+ const double wfFloor = -120.0 + get(WfFloor) * 80.0;
+ const double wfTop = std::max(wfFloor + 6.0, -6.0 + wfGain);
+ const double contrast = 0.5 + get(WfContrast) * 1.5;
+ for (int i = 0; i < kWfBins; ++i) {
+ const double x = i * (kCurve - 1) / (double)(kWfBins - 1);
+ const int a = (int)x; const double fr = x - a;
+ const double v = curve_[(size_t)a] * (1 - fr) + curve_[(size_t)std::min(a + 1, kCurve - 1)] * fr + wfGain;
+ wfRow_[(size_t)i] = (float)std::clamp(std::pow(std::clamp((v - wfFloor) / (wfTop - wfFloor), 0.0, 1.0), 1.0 / contrast), 0.0, 1.0);
+ }
+ }
+
+ void buildWindow(int kind, int n) const {
+ double sum = 0;
+ for (int i = 0; i < n; ++i) {
+ const double x = 2 * kPi * i / (n - 1);
+ double w;
+ switch (kind) {
+ case 1: // Blackman-Harris
+ w = 0.35875 - 0.48829 * std::cos(x) + 0.14128 * std::cos(2 * x) - 0.01168 * std::cos(3 * x);
+ break;
+ case 2: // Flat top
+ w = 0.21557895 - 0.41663158 * std::cos(x) + 0.277263158 * std::cos(2 * x)
+ - 0.083578947 * std::cos(3 * x) + 0.006947368 * std::cos(4 * x);
+ break;
+ default: // Hann
+ w = 0.5 - 0.5 * std::cos(x);
+ break;
+ }
+ win_[(size_t)i] = (float)w;
+ sum += w;
+ }
+ winSum_ = sum;
+ }
+
+ // 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 {
+ const int win = windowSamples();
+ const int pre = win / 4;
+ const uint32_t head = ringW_.load(std::memory_order_relaxed);
+ const bool frozen = get(Freeze) >= 0.5f;
+ const int mode = trigModeIdx(); // 0 Auto · 1 Normal · 2 Single
+ if (frozen || (mode == 2 && singleDone_)) return; // hold the captured trace
+
+ const float level = (get(TrigLevel) - 0.5f) * 2.0f;
+ const bool rising = get(TrigEdge) < 0.5f;
+ const int holdoff = (int)std::lround(get(Holdoff) * 0.2 * sr_);
+ const bool ms = msOn(); const int src = srcIdx();
+
+ // The newest sample index whose window is fully inside the ring.
+ const uint32_t newest = head - (uint32_t)(win - pre) - 1;
+ const uint32_t oldest = head - (uint32_t)(kRing - 8);
+ const uint32_t limit = newest - (uint32_t)std::min(kRing - win - 8, 4 * win + 2048);
+
+ bool found = false; uint32_t at = 0;
+ for (uint32_t t = newest; (int32_t)(t - limit) > 0 && (int32_t)(t - oldest) > 0; --t) {
+ if (holdoff > 0 && trigOk_ && (int32_t)(t - trigPos_) < holdoff && (int32_t)(t - trigPos_) > -holdoff) continue;
+ const float a = pick(t - 1, ms, src), b = pick(t, ms, src);
+ if (rising ? (a < level && b >= level) : (a > level && b <= level)) { found = true; at = t; break; }
+ }
+
+ if (!found) {
+ if (mode == 0) { at = newest; trigOk_ = false; } // Auto: free-run
+ else return; // Normal / Single: keep the last trace
+ } else {
+ trigOk_ = true; trigPos_ = at;
+ if (mode == 2) { if (!armed_) return; armed_ = false; singleDone_ = true; }
+ }
+
+ // Raw window (for export) + the decimated trace, peak-preserving so a
+ // transient survives a 400 ms window squeezed into 512 points.
+ const uint32_t s0 = at - (uint32_t)pre;
+ rawLen_ = std::min(win, kMaxWin);
+ for (int i = 0; i < rawLen_; ++i) rawWin_[(size_t)i] = pick(s0 + (uint32_t)i, ms, src);
+
+ double sumSq = 0; float lo = 1e9f, hi = -1e9f;
+ for (int i = 0; i < kTrace; ++i) {
+ const int a = (int)((int64_t)i * win / kTrace);
+ const int b = std::max(a + 1, (int)((int64_t)(i + 1) * win / kTrace));
+ float best = 0;
+ for (int j = a; j < b && j < win; ++j) {
+ const float v = rawWin_[(size_t)std::min(j, rawLen_ - 1)];
+ if (std::fabs(v) > std::fabs(best)) best = v;
+ }
+ trace_[(size_t)i] = best;
+ }
+ for (int i = 0; i < rawLen_; ++i) {
+ const float v = rawWin_[(size_t)i];
+ sumSq += (double)v * v; lo = std::min(lo, v); hi = std::max(hi, v);
+ }
+ mVpp_ = rawLen_ > 0 ? hi - lo : 0.0f;
+ mVrms_ = rawLen_ > 0 ? (float)std::sqrt(sumSq / rawLen_) : 0.0f;
+ mPeriodMs_ = (float)(measurePeriod() * 1000.0);
+ }
+
+ // Period by autocorrelation over the captured window (0 when nothing locks).
+ double measurePeriod() const {
+ const int n = rawLen_;
+ if (n < 32) return 0.0;
+ const int maxLag = std::min(n / 2, (int)(sr_ / 20.0));
+ const int minLag = std::max(2, (int)(sr_ / 20000.0));
+ double e0 = 0; for (int i = 0; i < n; ++i) e0 += (double)rawWin_[(size_t)i] * rawWin_[(size_t)i];
+ if (e0 < 1e-9) return 0.0;
+ double bestV = 0; int bestLag = 0; bool rose = false;
+ for (int lag = minLag; lag < maxLag; ++lag) {
+ double s = 0;
+ for (int i = 0; i + lag < n; ++i) s += (double)rawWin_[(size_t)i] * rawWin_[(size_t)(i + lag)];
+ const double norm = s / e0;
+ if (!rose) { if (norm < 0.2) rose = true; continue; } // skip the lag-0 lobe
+ if (norm > bestV) { bestV = norm; bestLag = lag; }
+ }
+ return bestV > 0.35 && bestLag > 0 ? bestLag / sr_ : 0.0;
+ }
+
+ double bandDb(double hz) const {
+ const double fLo = 20.0, fHi = std::min(20000.0, sr_ * 0.45);
+ if (hz <= fLo) return curve_[0];
+ if (hz >= fHi) return curve_[kCurve - 1];
+ const double x = std::log(hz / fLo) / std::log(fHi / fLo) * (kCurve - 1);
+ const int i = std::min((int)x, kCurve - 2);
+ const double f = x - i;
+ return curve_[(size_t)i] * (1 - f) + curve_[(size_t)(i + 1)] * f;
+ }
+
+ std::vector<Peak> topPeaks(int want) const {
+ const double fLo = 20.0, fHi = std::min(20000.0, sr_ * 0.45);
+ const double floorDb = -120.0 + get(Floor) * 80.0 + 3.0;
+ std::vector<Peak> out;
+ for (int i = 2; i < kCurve - 2; ++i) {
+ const float v = curve_[(size_t)i];
+ if (v <= floorDb) continue;
+ if (v < curve_[(size_t)(i - 1)] || v < curve_[(size_t)(i + 1)]) continue;
+ if (v < curve_[(size_t)(i - 2)] || v < curve_[(size_t)(i + 2)]) continue;
+ out.push_back({ fLo * std::pow(fHi / fLo, i / (double)(kCurve - 1)), v });
+ }
+ std::sort(out.begin(), out.end(), [](const Peak& a, const Peak& b) { return a.db > b.db; });
+ if ((int)out.size() > want) out.resize((size_t)want);
+ return out;
+ }
+
+ static std::string noteName(double hz) {
+ if (hz <= 0) return "—";
+ const double midi = 69.0 + 12.0 * std::log2(hz / 440.0);
+ const int n = (int)std::lround(midi);
+ const int cents = (int)std::lround((midi - n) * 100.0);
+ static const char* nm[12] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+ char b[32];
+ std::snprintf(b, sizeof b, "%s%d %+d ct", nm[((n % 12) + 12) % 12], n / 12 - 1, cents);
+ return b;
+ }
+
+ const char* viewName() const { static const char* v[3] = { "Spectrum", "Scope", "Waterfall" }; return v[step(get(View), 3)]; }
+ const char* sourceName() const {
+ const bool ms = get(MidSide) >= 0.5f;
+ static const char* lr[3] = { "L+R", "L", "R" };
+ static const char* msn[3] = { "Mid", "Mid", "Side" };
+ return (ms ? msn : lr)[step(get(Source), 3)];
+ }
+
+ static double db(double lin) { return 20.0 * std::log10(std::max(1e-10, lin)); }
+ static double nowSeconds() {
+ // A monotonic clock without <chrono> in the hot path's type soup.
+ using clock = std::chrono::steady_clock;
+ return std::chrono::duration<double>(clock::now().time_since_epoch()).count();
+ }
+
+ double sr_ = 44100.0;
+ std::atomic<float> p_[kNumParams] = {};
+
+ // Capture rings (audio thread writes, message thread reads).
+ std::vector<float> ringL_, ringR_;
+ std::atomic<uint32_t> ringW_{ 0 };
+ std::atomic<uint32_t> frameSeq_{ 0 };
+ std::atomic<float> corr_{ 0.0f }, lufs_{ -120.0f };
+
+ // Loudness follower (audio thread only).
+ Biquad kb_[2];
+ KState ks_[2];
+ std::vector<double> lufsRing_;
+ int lufsBlock_ = 353, lufsIdx_ = 0, lufsN_ = 0;
+ double lufsAcc_ = 0.0;
+
+ // Analysis state — message thread only, under mx_.
+ mutable std::mutex mx_;
+ 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 double winSum_ = 1.0, lastAnalyzeS_ = -1.0;
+ mutable uint32_t lastSeq_ = 0xFFFFFFFFu;
+ mutable int fftN_ = 0, winKind_ = -1, rawLen_ = 0;
+ mutable uint32_t trigPos_ = 0;
+ mutable bool trigOk_ = false, armed_ = true, singleDone_ = false;
+ mutable float mPeakHz_ = 0, mPeakDb_ = -120, mRmsDb_ = -120, mLevelDb_ = -120;
+ mutable float mPeriodMs_ = 0, mVpp_ = 0, mVrms_ = 0;
+};
+
+} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index c6a38e4d..401ad38a 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -3919,6 +3919,222 @@ Console.WriteLine("-- Nota Prism --");
}
}
+// ============================ Nota Lens ====================================
+Console.WriteLine("-- Nota Lens --");
+{
+ // Lens = analyzer (kind 22). Own engine, fed a deterministic 1 kHz sine so the
+ // spectrum peak, the scope period and the third-octave table are all predictable.
+ // The analysis runs lazily on the message thread and is rate-limited by Display Rate,
+ // so each read is preceded by a render + a short wait.
+ const int ViewP = 0, FreezeP = 1, SourceP = 2, MidSideP = 3, FftSizeP = 4, WindowP = 5,
+ 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;
+ 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;
+
+ string lensWav = Path.Combine(Path.GetTempPath(), "nota_lens_" + Guid.NewGuid().ToString("N") + ".wav");
+ Nota.SmokeTest.WavWriter.WriteTones(lensWav, 4.0, new double[] { 1000 }, 0.25, 44100);
+ using var le = new NotaEngine();
+ le.SetBpm(120); le.SetTimeSignature(4, 4);
+ int lt = le.AddAudioTrack();
+ le.AddAudioClip(lt, lensWav, startBeat: 0.0);
+ int ld = le.AddBuiltinDevice(lt, 22);
+ try
+ {
+ Check(ld >= 0, "add built-in 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})");
+ 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);
+ Check(Math.Abs(le.DeviceGetParam(lt, ld, TiltP) - 0.42f) < 1e-4, "Lens param set/get round-trips");
+ le.DeviceSetParam(lt, ld, TiltP, le.DeviceParamDefault(lt, ld, TiltP));
+ le.DeviceSetParam(lt, ld, RateP, 1f); // 60 fps: the shortest analysis interval
+
+ const int LN = 8192;
+ var lb = new float[LN * 2];
+ var lsc = new float[32];
+ float Render(int blocks = 4)
+ {
+ le.Seek(0); le.Play();
+ float r = 0;
+ for (int k = 0; k < blocks; k++)
+ {
+ le.RenderOffline(lb, LN);
+ foreach (var s in lb) if (!float.IsFinite(s)) { Check(false, "Lens render stays finite"); break; }
+ r = Rms(lb, LN);
+ }
+ le.StopTransport();
+ System.Threading.Thread.Sleep(40); // let the rate limiter open
+ return r;
+ }
+ double Sc(int i) => lsc[i];
+ void Read() { int n = le.DeviceScope(lt, ld, lsc, kLensScope); Check(n == kLensScope, $"Lens scope returns {kLensScope} values (got {n})"); }
+
+ // An analyzer passes audio through untouched.
+ le.SetDeviceBypassed(lt, ld, true);
+ float rByp = Render();
+ le.SetDeviceBypassed(lt, ld, false);
+ float rThru = Render();
+ Check(rByp > 1e-2f && Math.Abs(20 * Math.Log10(rThru / Math.Max(1e-9f, rByp))) < 0.01,
+ $"Lens passes the signal through unchanged ({20 * Math.Log10(rThru / Math.Max(1e-9f, rByp)):+0.000;-0.000} dB vs bypass)");
+ Check(le.TrackLatencySamples(lt) == 0, $"Lens adds no latency to the track (got {le.TrackLatencySamples(lt)} smp)");
+ Read();
+
+ // Spectrum: the 1 kHz tone is the loudest peak, at roughly −12 dBFS.
+ Check(Math.Abs(Sc(M_PeakHz) - 1000) < 80, $"spectrum finds the 1 kHz tone ({Sc(M_PeakHz):F0} Hz)");
+ Check(Sc(M_RmsDb) is > -25 and < -9, $"RMS follows the tone ({Sc(M_RmsDb):F1} dB)");
+ // Calibration: unsmoothed, a 0.25 sine must read its own −12.0 dBFS (a Hann window
+ // costs up to 1.4 dB of scalloping when the tone falls between bins). Smoothing then
+ // averages power over a band, so it legitimately reads a narrow tone lower.
+ float smoothWas = le.DeviceGetParam(lt, ld, SmoothP);
+ le.DeviceSetParam(lt, ld, SmoothP, 0f);
+ Render(); Read();
+ Check(Sc(M_PeakDb) is > -14 and < -11, $"an unsmoothed 0.25 sine reads −12 dBFS ({Sc(M_PeakDb):F1} dB)");
+ le.DeviceSetParam(lt, ld, SmoothP, smoothWas);
+ Render(); Read();
+ Check(Sc(M_PeakDb) < -13, $"smoothing averages the tone's power over its band ({Sc(M_PeakDb):F1} dB)");
+ Check(Math.Abs(Sc(M_SampleRate) - 44100) < 1, $"Lens reports the sample rate ({Sc(M_SampleRate):F0} Hz)");
+
+ var curveBuf = new float[1024];
+ Check(le.DeviceLayerWave(lt, ld, L_Spectrum, curveBuf, curveBuf.Length) == 512, "Lens publishes a 512-point spectrum curve");
+ Check(le.DeviceLayerWave(lt, ld, L_Peak, curveBuf, curveBuf.Length) == 512, "Lens publishes a 512-point peak-hold curve");
+ Check(le.DeviceLayerWave(lt, ld, L_Waterfall, curveBuf, curveBuf.Length) == 256, "Lens publishes a 256-bin waterfall row");
+ int traceN = le.DeviceLayerWave(lt, ld, L_Trace, curveBuf, curveBuf.Length);
+ Check(traceN == 512, $"Lens publishes a 512-point scope trace (got {traceN})");
+ Check(le.DeviceLayerWave(lt, ld, L_Raw, curveBuf, curveBuf.Length) > 0, "Lens publishes the raw triggered window");
+
+ // The curve peaks where the tone is, not at the edges.
+ le.DeviceLayerWave(lt, ld, L_Spectrum, curveBuf, curveBuf.Length);
+ int best = 0;
+ for (int i = 1; i < 512; i++) if (curveBuf[i] > curveBuf[best]) best = i;
+ double bestHz = 20 * Math.Pow(Math.Min(20000, 44100 * 0.45) / 20.0, best / 511.0);
+ Check(Math.Abs(bestHz - 1000) < 80, $"the published curve peaks at the tone ({bestHz:F0} Hz)");
+
+ // FFT size + resolution follow the parameter.
+ le.DeviceSetParam(lt, ld, FftSizeP, 1f); // 16384
+ Render(); Read();
+ Check((int)Sc(M_FftN) == 16384, $"FFT size follows the param ({Sc(M_FftN):F0})");
+ Check(Math.Abs(Sc(M_BinHz) - 44100.0 / 16384) < 0.01, $"bin width follows the FFT size ({Sc(M_BinHz):F3} Hz)");
+ Check(Math.Abs(Sc(M_PeakHz) - 1000) < 40, $"the finer FFT still finds the tone ({Sc(M_PeakHz):F0} Hz)");
+ le.DeviceSetParam(lt, ld, FftSizeP, le.DeviceParamDefault(lt, ld, FftSizeP));
+
+ // Scope: a 1 kHz sine measures a 1 ms period and a full-scale-ish Vpp.
+ le.DeviceSetParam(lt, ld, ViewP, 0.5f);
+ Render(); Read();
+ Check(Math.Abs(Sc(M_PeriodMs) - 1.0) < 0.06, $"scope measures the 1 ms period ({Sc(M_PeriodMs):F3} ms)");
+ Check(Math.Abs(Sc(M_FreqHz) - 1000) < 60, $"scope reports the tone's frequency ({Sc(M_FreqHz):F1} Hz)");
+ Check(Sc(M_Vpp) is > 0.2f and < 1.2f, $"scope measures Vpp ({Sc(M_Vpp):F3})");
+ Check(Sc(M_Vrms) > 0.05f, $"scope measures Vrms ({Sc(M_Vrms):F3})");
+
+ // Single-shot: the capture holds until it is re-armed.
+ le.DeviceSetParam(lt, ld, TrigModeP, 1f);
+ Render(); Read();
+ Check(Sc(M_Held) > 0.5f, "a finished Single capture holds the trace");
+ le.DeviceAction(lt, ld, A_Rearm, 0, 0f);
+ Render(); Read();
+ Check(Sc(M_Held) > 0.5f, "re-arm captures again and holds");
+ le.DeviceSetParam(lt, ld, TrigModeP, 0f);
+ Render(); Read();
+ Check(Sc(M_Held) < 0.5f, "Auto free-runs again");
+
+ // Freeze holds the display.
+ le.DeviceSetParam(lt, ld, FreezeP, 1f);
+ Render(); Read();
+ Check(Sc(M_Held) > 0.5f, "Freeze holds the capture");
+ le.DeviceSetParam(lt, ld, FreezeP, 0f);
+
+ // Source / Mid-Side: a mono clip has no Side content.
+ le.DeviceSetParam(lt, ld, MidSideP, 1f);
+ le.DeviceSetParam(lt, ld, SourceP, 0.5f); // Mid
+ Render(); Read();
+ double midDb = Sc(M_RmsDb);
+ le.DeviceSetParam(lt, ld, SourceP, 1f); // Side
+ Render(); Read();
+ double sideDb = Sc(M_RmsDb);
+ Check(midDb - sideDb > 40, $"a mono source has no Side content (Mid {midDb:F1} dB, Side {sideDb:F1} dB)");
+ le.DeviceSetParam(lt, ld, MidSideP, 0f);
+ le.DeviceSetParam(lt, ld, SourceP, 0f);
+ le.DeviceSetParam(lt, ld, ViewP, 0f);
+ le.DeviceAction(lt, ld, A_ResetPeak, 0, 0f);
+ Render(); Read();
+
+ // Text reports (the MCP surface).
+ var bandLines = le.DeviceText(lt, ld, 1).Split('\n', StringSplitOptions.RemoveEmptyEntries);
+ Check(bandLines.Length == 31, $"Lens reports 31 third-octave bands (got {bandLines.Length})");
+ Check(le.DeviceText(lt, ld, 0).Contains("peak"), "Lens summary names the peak");
+ Check(le.DeviceText(lt, ld, 2).Contains("window"), "Lens reports the scope window");
+ Check(le.DeviceText(lt, ld, 3).Length > 0, "Lens reports its spectral peaks");
+ le.DeviceSetParam(lt, ld, CursorAP, 0.25f);
+ le.DeviceSetParam(lt, ld, CursorBP, 0.5f);
+ Check(le.DeviceText(lt, ld, 4).Contains("dt"), "Lens reports the A/B cursor measurements");
+
+ // Clone: duplicating the track copies the params.
+ le.DeviceSetParam(lt, ld, SmoothP, 0.77f);
+ le.DeviceSetParam(lt, ld, WindowP, 1f);
+ int ldup = le.DuplicateTrack(lt);
+ Check(ldup > 0 && le.TrackDeviceBuiltinKind(ldup, 0) == 22
+ && Math.Abs(le.DeviceGetParam(ldup, 0, SmoothP) - 0.77f) < 1e-4
+ && Math.Abs(le.DeviceGetParam(ldup, 0, WindowP) - 1f) < 1e-4, "duplicate track clones the Lens params");
+ le.RemoveTrack(ldup);
+ for (int i = 0; i < lpc; i++) le.DeviceSetParam(lt, ld, i, le.DeviceParamDefault(lt, ld, i));
+
+ // Automation drives the trigger level.
+ int llane = le.AddAutomationLane(lt, AutomationTarget.DeviceParam, ld, TrigLevelP);
+ Check(llane >= 0, "add Lens Trigger Level automation lane");
+ le.SetAutomationPoints(lt, llane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
+ le.Seek(1.99); le.Play(); le.RenderOffline(lb, 4096); le.StopTransport();
+ Check(le.DeviceGetParam(lt, ld, TrigLevelP) > 0.7f, $"automation drives Lens Trigger Level ({le.DeviceGetParam(lt, ld, TrigLevelP):F2})");
+ le.RemoveAutomationLane(lt, llane);
+
+ // Factory presets: every named param exists and each applies + still passes audio.
+ {
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 22).ToList();
+ Check(mine.Count >= 25, $"Nota Lens ships at least 25 factory presets ({mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !lnames.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Lens preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ float rRef = Render(1); // same block count as the per-preset renders below
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(le, p.Id, lt, ld).Length != 0) { pf++; continue; }
+ float r = Render(1);
+ if (!float.IsFinite(r) || Math.Abs(20 * Math.Log10(r / Math.Max(1e-9f, rRef))) > 0.01) pf++;
+ }
+ Check(pf == 0, $"every Lens preset applies and still passes audio through ({pf} failed)");
+ cat.ApplyInPlace(le, "lens/Scope · Single Shot", lt, ld);
+ Check(le.DeviceGetParam(lt, ld, ViewP) > 0.4f && le.DeviceGetParam(lt, ld, TrigModeP) > 0.9f, "Scope · Single Shot selects the scope and arms Single");
+ cat.ApplyInPlace(le, "lens/Mix Overview", lt, ld);
+ Check(le.DeviceGetParam(lt, ld, ViewP) < 1e-3 && le.DeviceGetParam(lt, ld, TrigModeP) < 1e-3, "unnamed params reset to defaults between presets");
+ for (int i = 0; i < lpc; i++) le.DeviceSetParam(lt, ld, i, le.DeviceParamDefault(lt, ld, i));
+ le.DeviceSetParam(lt, ld, RateP, 1f);
+ }
+
+ // MCP: the kind is listed and read_analyzer returns a parsed reading.
+ {
+ var dt = new Nota.Mcp.Tools.DeviceTools(le, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ Check(dt.ListDeviceKinds().Any(k => k.Kind == 22 && k.Name == "Nota Lens"), "MCP lists Nota Lens (kind 22)");
+ Render();
+ var reading = dt.ReadAnalyzer(lt, ld).Result;
+ Check(reading.Bands.Length == 31, $"MCP read_analyzer returns 31 bands (got {reading.Bands.Length})");
+ Check(reading.Summary.Length > 0 && reading.Scope.Length > 0 && reading.Cursors.Length > 0, "MCP read_analyzer returns the summary, scope and cursor lines");
+ var loudest = reading.Bands.OrderByDescending(b => b.Db).First();
+ Check(Math.Abs(loudest.Hz - 1000) < 300, $"the loudest third-octave band is the 1 kHz one (got {loudest.Hz:F0} Hz)");
+ Check(reading.Peaks.Length > 0 && Math.Abs(reading.Peaks[0].Hz - 1000) < 80 && reading.Peaks[0].Note.Length > 0,
+ $"MCP read_analyzer names the strongest peak ({(reading.Peaks.Length > 0 ? $"{reading.Peaks[0].Hz:F0} Hz {reading.Peaks[0].Note}" : "none")})");
+ }
+ }
+ finally
+ {
+ try { File.Delete(lensWav); } catch { }
+ }
+}
+
// ============================ Nota Level ===================================
Console.WriteLine("-- Nota Level (AutoGain) --");
{