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.

Redesign of Reverb and Compressor

Egor Khindikaynen3233c198fe5d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92394e92..41117a5c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,34 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
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.
+- **MCP: sidechain routing and `read_dynamics`.** `set_device_sidechain` / `get_device_sidechain`
+ route a key into a Compressor (or any device that takes one) — source track, pre/post tap,
+ detector gain — so an assistant can set up ducking on its own. `read_dynamics` returns
+ what a Nota Compressor is doing: gain reduction, input / output peak and RMS, the key
+ level, the effective attack and release, look-ahead latency and how often it kicked in.
+
+### Changed
+- **Nota Compressor shows its dynamics, not just its settings.** The card moves onto the
+ Lens / Delay / Reverb frame — a LEVEL column (threshold against the live key level ·
+ make-up), a centre panel with **Curve**, **Motion** and **Sidechain** tabs, a
+ **Dynamics / Output** panel and a status strip:
+ - **Curve** — the transfer curve you drag (sideways for the threshold, up and down for the
+ ratio) beside four seconds of gain-reduction history with its peak, plus the average /
+ peak reduction and the crest factor in and out.
+ - **Motion** — the reduction envelope against the input over a window short enough to
+ read attack and release as shapes, with the effective timings after the character
+ voicing and the measured transient and recovery of the last hit.
+ - **Sidechain** — pick the key source and its pre/post tap, see the key's spectrum under
+ its filters and drag the HP / LP handles (up and down sets Q); **Listen** hears the key.
+ - **New in the engine:** an **Auto** detector (RMS body, still catches spikes), 2-pole key
+ filters with **Q**, **SC Gain**, **Hold**, an **External key** switch and **Stereo
+ link** (off = each channel compresses on its own). **Look-ahead now reports its
+ latency**, so delay compensation keeps the other tracks in time.
+ - **31 factory presets**, up from six — drums, bus, vocals (with a de-esser), bass and
+ instruments, and sidechain ducking. The five new parameters are appended, so older
+ projects open unchanged and every one of them automates (grouped under *SC* in the
+ lane menu), MIDI-learns, saves in a preset and is reachable over MCP; `get_device_text`
+ returns the compressor's status line.
## [0.40.0] — 2026-09-18
@@ -288,6 +316,26 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
restart — and the choice is remembered.
### Changed
+- **Nota Reverb moves onto the Chamber frame and grows the parts it was missing.** A TAIL
+ column (decay · HF damp), a centre panel with **Space** and **Tone · Mod** tabs over a
+ live decay-tail window, a **Levels / Output** panel and a status strip. The window
+ replays the sound: the impulse flashes at the pre-delay, the early reflections light in
+ turn and the RT60 curve draws itself while the reverb is sounding. Drag the teal marker
+ for the pre-delay or the tail for the decay.
+ - **Decay is now a true RT60**: the number on the knob is the time the tail takes to fall
+ 60 dB, whatever the size or algorithm. Older projects keep their settings, but long
+ decays ring a little differently than before.
+ - **Early reflections**, spaced by the algorithm (a hall's walls far apart, a plate's a
+ tight cluster) and the size, and an **input diffuser** for a denser onset.
+ **Latency comp.** shortens the pre-delay by the diffuser's group delay, so the tail
+ starts on the set pre-delay.
+ - **Mod on tail** chooses where the modulation goes (the tail itself, or only the early
+ part so the tail stays still), and **Vintage** gives it an early-digital colour.
+ - **An output stage:** separate **dry level**, **bass mono** on the tail and **Wet only**
+ for a return track. **Kill tail** empties the reverb at once, even when frozen.
+ - **30 factory presets**, up from four. The seven new parameters are appended, so every
+ one of them automates, MIDI-learns, saves in a preset and is reachable over MCP;
+ `get_device_text` returns the reverb's status line, and `device_action` kills the tail.
- **Nota Delay is a full delay, not a time-and-feedback box.** The card moves onto the same
frame as Nota Chamber — a LOOP column (feedback · spread), a centre panel with **Time**
and **Loop · Wow** tabs over a live repeat window, a **Levels / Output** panel and a
diff --git a/FEATURES.md b/FEATURES.md
index ea9d4771..3432a5ec 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -322,10 +322,21 @@ and user presets, automation, persistence and cloning.
### Audio effects
- **Nota EQ-8** (kind 0) — 8-band parametric.
- **Nota Compressor** (1) — 5 character models (Clean/Glue/Punch/Opto/FET), soft knee,
- look-ahead, Peak/RMS, auto-release, auto-gain, Range, sidechain HP/LP + Listen, MIX;
- transfer plot and gain-reduction history.
-- **Nota Reverb** (2) — Hall/Room/Plate/Chamber, RT60, HF damp, pre-delay, size,
- diffusion, low/high cut, width, tail modulation, Freeze; an interactive tail graph.
+ look-ahead (reported as latency for PDC), Peak/RMS/Auto detection, hold, auto-release,
+ auto-gain, Range, MIX; a sidechain key (internal or another track, pre/post tap, External
+ key switch) through 2-pole HP/LP filters with Q and SC Gain, Listen, Stereo link on/off.
+ Tabs: Curve (draggable transfer curve + gain-reduction history, crest in → out) / Motion
+ (reduction envelope against the input, measured transient and recovery) / Sidechain (key
+ spectrum under draggable filters), and Dynamics / Output, with a LEVEL column and a status
+ strip. 31 factory presets. MCP: `read_dynamics`, `set_device_sidechain` /
+ `get_device_sidechain`.
+- **Nota Reverb** (2) — Hall/Room/Plate/Chamber, a decay calibrated as a true RT60, HF damp,
+ pre-delay, size, diffusion (input diffuser + tail allpasses), early reflections spaced by
+ the algorithm and size, low/high cut, width, modulation on the tail or on the early part
+ only, Vintage (band-limited, 12-bit colour); Freeze (tail held, input muted) and Kill
+ tail; output stage with dry level, bass mono, wet only and latency compensation for the
+ diffuser. Tabs: Space / Tone · Mod and Levels / Output, over a live decay-tail window
+ (drag the pre-delay marker or the tail). 30 factory presets.
- **Nota Delay** (3) — independent L/R times (ms or tempo-synced 1/16…1/2 with triplets
and dotted values), Link, feedback, spread, ping-pong; a tone stage in the loop (low cut,
high cut, allpass diffusion, tape saturation) with tape WOW modulation; Freeze (loop held,
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index 5791f0de..0a1daffa 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -388,9 +388,9 @@ public sealed partial class ArrangementView
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") 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 or 22;
+ // view ("Spectrum", "Scope", "Waterfall", "Cursor") and the Compressor its key
+ // ("SC HP", "SC Gain" …): a word shared by two or more params becomes a submenu.
+ bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 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/CompGrHistory.cs b/src/managed/Nota.App/Controls/CompGrHistory.cs
deleted file mode 100644
index 7f90dd55..00000000
--- a/src/managed/Nota.App/Controls/CompGrHistory.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Compressor gain-reduction history (mockup 2n): a scrolling meter that hangs from the
-// top — depth = gain reduction — drawn in record red (red is reserved for reduction,
-// brass stays signal). Push() the current reduction each UI tick; the control tracks a
-// decaying peak. The current/peak numbers are shown by the card beside it.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class CompGrHistory : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush Grid = NotaGraph.Grid;
- // Gain reduction is the device doing its job, not an alert: it is the primary data, so brass.
- private static readonly IBrush Red = NotaPalette.Accent;
- private static readonly IBrush Axis = NotaPalette.TextAxis;
- private static readonly Typeface Face = NotaFonts.Mono;
- private const int N = 220;
- private const double MaxDb = 24.0;
-
- private readonly double[] _h = new double[N];
- private int _w;
- public double Current { get; private set; }
- public double Peak { get; private set; }
-
- public void Push(double grDb)
- {
- _h[_w % N] = grDb; _w++;
- Current = grDb;
- Peak = Math.Max(grDb, Peak); // the peak holds; it does not fall on its own
- InvalidateVisual();
- }
-
- protected override void OnPointerPressed(Avalonia.Input.PointerPressedEventArgs e)
- {
- // Click clears the held peak back to the current reduction.
- if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
- Peak = Current; InvalidateVisual(); e.Handled = true;
- }
-
- private const double HeadH = 14.0; // reserved top band for the labels — the plot starts below it
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height; if (w <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- // The plot lives below a reserved header band so the labels stay readable when it fills.
- double top0 = HeadH, plotH = h - HeadH - 1;
- // Horizontal dB gridlines at −6/−12/−18.
- for (int d = 6; d < 24; d += 6) { double gy = top0 + d / MaxDb * plotH; ctx.DrawLine(new Pen(Grid, 1), new Point(2, gy), new Point(w - 2, gy)); }
-
- int count = Math.Min(N, _w);
- if (count > 1)
- {
- var top = new System.Collections.Generic.List<Point>();
- for (int i = 0; i < count; i++)
- {
- int idx = (_w - count + i) % N; if (idx < 0) idx += N;
- double x = 2 + (double)i / (count - 1) * (w - 4);
- double depth = Math.Clamp(_h[idx] / MaxDb, 0, 1) * plotH;
- top.Add(new Point(x, top0 + depth));
- }
- var geo = new StreamGeometry();
- using (var gc = geo.Open()) { gc.BeginFigure(new Point(top[0].X, top0), true); foreach (var p in top) gc.LineTo(p); gc.LineTo(new Point(top[^1].X, top0)); gc.EndFigure(true); }
- var pen = new Pen(Red, NotaGraph.PrimaryWidth, lineJoin: PenLineJoin.Round);
- for (int i = 1; i < top.Count; i++) ctx.DrawLine(pen, top[i - 1], top[i]);
- }
- // Peak-hold line.
- if (Peak > 0.05) { double py = top0 + Math.Clamp(Peak / MaxDb, 0, 1) * plotH; ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x99), 1) { DashStyle = DashStyle.Dash }, new Point(2, py), new Point(w - 2, py)); }
- // Labels drawn in the reserved header band: title top-left, current · peak top-right (in red).
- ctx.DrawText(new FormattedText("GAIN REDUCTION", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, Axis), new Point(5, 2));
- string cur = Current <= 0.05 ? "0.0" : $"−{Current:0.0}", pk = Peak <= 0.05 ? "0.0" : $"−{Peak:0.0}";
- var ft = new FormattedText($"{cur}\u2009dB · peak {pk}", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, NotaPalette.AccentBright);
- ctx.DrawText(ft, new Point(w - ft.Width - 5, 2));
- }
-}
diff --git a/src/managed/Nota.App/Controls/CompTransfer.cs b/src/managed/Nota.App/Controls/CompTransfer.cs
deleted file mode 100644
index 8d2ff956..00000000
--- a/src/managed/Nota.App/Controls/CompTransfer.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Compressor transfer plot (mockup 2n): input→output dB curve with a dashed unity
-// diagonal, a threshold line, the soft knee drawn as a curve and the operating point
-// as a lit handle. Drag the handle: left/right sets Threshold, up/down sets Ratio.
-// Reads/writes the device's Threshold (0) / Ratio (1) params (raw dB / ratio) with
-// automation gestures; the Knee (5) shapes the curve.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Input;
-using Avalonia.Media;
-using Nota.Application;
-
-namespace Nota.App;
-
-internal sealed class CompTransfer : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush Accent = NotaPalette.AccentBright;
- private static readonly IBrush Grid = NotaGraph.Grid;
- private static readonly IBrush Axis = NotaPalette.TextAxis;
- private static readonly IBrush Fill = NotaPalette.Wash(NotaPalette.Accent, 0x16);
- private static readonly Typeface Face = NotaFonts.Mono;
- private const int Threshold = 0, Ratio = 1, Knee = 5;
- private const double Lo = -60, Hi = 0;
-
- private readonly IAudioEngine _e; private readonly int _t, _di;
- private bool _drag; private double _startY, _startRatio;
-
- public CompTransfer(IAudioEngine e, int t, int di) { _e = e; _t = t; _di = di; MinHeight = 90; }
- public void Tick() => InvalidateVisual();
- private float P(int p) => _e.DeviceGetParam(_t, _di, p);
- private (double x0, double x1, double top, double bot) Geo() => (18, Bounds.Width - 6, 6, Bounds.Height - 16);
- private double X(double db, double x0, double x1) => x0 + (db - Lo) / (Hi - Lo) * (x1 - x0);
- private double Y(double db, double top, double bot) => bot - (db - Lo) / (Hi - Lo) * (bot - top);
-
- private double OutDb(double inDb, double thr, double ratio, double knee)
- {
- double over = inDb - thr, slope = 1.0 - 1.0 / ratio, gr;
- if (knee > 0.01 && 2 * over > -knee && 2 * over < knee) { double t = over + knee / 2; gr = slope * t * t / (2 * knee); }
- else gr = over > 0 ? slope * over : 0;
- return inDb - gr;
- }
-
- protected override void OnPointerPressed(PointerPressedEventArgs e)
- { _drag = true; _startY = e.GetPosition(this).Y; _startRatio = P(Ratio); Gest(true); e.Pointer.Capture(this); Apply(e.GetPosition(this)); e.Handled = true; }
- protected override void OnPointerMoved(PointerEventArgs e) { if (_drag) Apply(e.GetPosition(this)); }
- protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_drag) { _drag = false; Gest(false); e.Pointer.Capture(null); } }
- private void Gest(bool begin)
- {
- void G(int p) { if (begin) _e.BeginAutomationWrite(_t, AutomationTarget.DeviceParam, _di, p, ""); else _e.EndAutomationWrite(_t, AutomationTarget.DeviceParam, _di, p, ""); }
- G(Threshold); G(Ratio);
- }
- private void Apply(Point p)
- {
- var (x0, x1, top, bot) = Geo();
- double thr = Math.Clamp(Lo + (p.X - x0) / Math.Max(1, x1 - x0) * (Hi - Lo), Lo, Hi);
- double ratio = Math.Clamp(_startRatio + (p.Y - _startY) / 8.0, 1, 20);
- _e.DeviceSetParam(_t, _di, Threshold, (float)thr);
- _e.DeviceSetParam(_t, _di, Ratio, (float)ratio);
- InvalidateVisual();
- }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height; if (w <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- var (x0, x1, top, bot) = Geo();
- for (int i = 1; i <= 3; i++) { double gx = x0 + (x1 - x0) * i / 4.0, gy = top + (bot - top) * i / 4.0; ctx.DrawLine(new Pen(Grid, 1), new Point(gx, top), new Point(gx, bot)); ctx.DrawLine(new Pen(Grid, 1), new Point(x0, gy), new Point(x1, gy)); }
- // Unity diagonal (dashed).
- ctx.DrawLine(new Pen(Axis, 1) { DashStyle = DashStyle.Dash }, new Point(X(Lo, x0, x1), Y(Lo, top, bot)), new Point(X(Hi, x0, x1), Y(Hi, top, bot)));
-
- double thr = P(Threshold), ratio = Math.Max(1, P(Ratio)), knee = P(Knee);
- // Threshold line.
- double tx = X(thr, x0, x1);
- ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x50), 1), new Point(tx, top), new Point(tx, bot));
-
- // Transfer curve + fill.
- var geo = new StreamGeometry();
- var pts = new System.Collections.Generic.List<Point>();
- for (double db = Lo; db <= Hi + 0.01; db += 1.5) pts.Add(new Point(X(db, x0, x1), Y(OutDb(db, thr, ratio, knee), top, bot)));
- using (var gc = geo.Open()) { gc.BeginFigure(new Point(pts[0].X, bot), true); foreach (var pt in pts) gc.LineTo(pt); gc.LineTo(new Point(pts[^1].X, bot)); gc.EndFigure(true); }
- var pen = new Pen(Accent, 1.8, lineJoin: PenLineJoin.Round);
- for (int i = 1; i < pts.Count; i++) ctx.DrawLine(pen, pts[i - 1], pts[i]);
-
- // Operating handle at the threshold knee point.
- NotaGraph.Node(ctx, new Point(tx, Y(OutDb(thr, thr, ratio, knee), top, bot)), active: true);
-
- void Txt(string t, double x, double y, IBrush b) => ctx.DrawText(new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));
- Txt("TRANSFER", x0 + 1, top - 1, Axis);
- Txt($"{ratio:0}:1 · knee {knee:0}", x1 - 68, top - 1, Accent);
- Txt("−60", 1, bot - 5, Axis);
- Txt("0\u2009dB in", x1 - 34, bot + 3, Axis);
- }
-}
diff --git a/src/managed/Nota.App/Controls/CompViews.cs b/src/managed/Nota.App/Controls/CompViews.cs
new file mode 100644
index 00000000..8f8195d0
--- /dev/null
+++ b/src/managed/Nota.App/Controls/CompViews.cs
@@ -0,0 +1,577 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The custom-drawn views of the Nota Compressor card: the LEVEL column's faders (with the
+// live level the fader is set against), the transfer curve (drag the threshold node), the
+// gain-reduction history, the Motion envelope (reduction against the input, at a time scale
+// where attack and release can be read) and the sidechain key spectrum with its filters
+// (drag the HP / LP handles; up/down sets Q). They draw what the card hands them and own
+// no engine state — every edit goes out through events.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class CompDraw
+{
+ public static FormattedText Text(string t, IBrush ink, double size = 7)
+ => new(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);
+
+ public static void Polyline(DrawingContext ctx, IPen pen, IReadOnlyList<Point> pts)
+ {
+ if (pts.Count < 2) return;
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ g.BeginFigure(pts[0], false);
+ for (int i = 1; i < pts.Count; i++) g.LineTo(pts[i]);
+ }
+ ctx.DrawGeometry(null, pen, geo);
+ }
+
+ /// <summary>The soft-knee static curve, in dB: the reduction at input level <paramref name="inDb"/>.</summary>
+ public static double Reduction(double inDb, double thr, double ratio, double knee, double range)
+ {
+ double over = inDb - thr, slope = 1.0 - 1.0 / Math.Max(1, ratio), gr;
+ if (knee > 0.01 && 2 * over > -knee && 2 * over < knee) { double t = over + knee / 2; gr = slope * t * t / (2 * knee); }
+ else gr = over > 0 ? slope * over : 0;
+ return Math.Min(gr, range);
+ }
+
+ public static string Db(double db) => db <= -99 ? "−∞" : NotaNum.F($"{db:0.0}");
+}
+
+// A vertical fader in the LEVEL column: a groove, a wash fill in its chroma up to the value
+// and a bright handle, plus a hairline tick at the live level it works against (the input
+// for the threshold). Drag moves the value relative to where it was — a click never jumps it;
+// Shift / Ctrl / ⌘ drag fine; double-click restores the default.
+internal sealed class CompFader : Control
+{
+ private double _v, _live = double.NaN, _startV, _startY;
+ private bool _drag;
+
+ public IBrush Ink { get; set; } = NotaPalette.Accent;
+ public IBrush Handle { get; set; } = NotaPalette.AccentBright;
+ public double Default { get; set; } = double.NaN;
+ public bool Dragging => _drag;
+
+ public event Action<double>? Changed;
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+
+ public CompFader() { Width = 16; Cursor = new Cursor(StandardCursorType.SizeNorthSouth); }
+
+ public void Set(double v, double live = double.NaN)
+ {
+ double n = Math.Clamp(v, 0, 1);
+ bool dirty = !_drag && Math.Abs(n - _v) > 1e-4;
+ if (!_drag) _v = n;
+ if (!(double.IsNaN(live) && double.IsNaN(_live)) && Math.Abs(live - _live) > 1e-3) { _live = live; dirty = true; }
+ if (dirty) InvalidateVisual();
+ }
+
+ public void Recolor(IBrush ink, IBrush handle) { Ink = ink; Handle = handle; InvalidateVisual(); }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2 && !double.IsNaN(Default))
+ {
+ GestureBegin?.Invoke(); _v = Default; Changed?.Invoke(_v); GestureEnd?.Invoke();
+ InvalidateVisual(); e.Handled = true; return;
+ }
+ _drag = true; _startV = _v; _startY = e.GetPosition(this).Y;
+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (!_drag) return;
+ double h = Math.Max(20, Bounds.Height);
+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;
+ double v = Math.Clamp(_startV + (_startY - e.GetPosition(this).Y) / h * (fine ? 0.2 : 1.0), 0, 1);
+ if (Math.Abs(v - _v) < 1e-6) return;
+ _v = v; Changed?.Invoke(_v); InvalidateVisual();
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_drag) return;
+ _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 2 || h < 4) return;
+ var rect = new Rect(0.5, 0.5, w - 1, h - 1);
+ double r = Math.Min(8, w / 2);
+ ctx.DrawRectangle(NotaPalette.BgSunken, null, rect, r, r);
+ double y = (1 - _v) * h;
+ using (ctx.PushClip(new RoundedRect(rect, r)))
+ {
+ ctx.FillRectangle(NotaPalette.Wash((SolidColorBrush)Ink, 0x48), new Rect(0, y, w, h - y));
+ if (!double.IsNaN(_live) && _live > 0.001)
+ {
+ double ly = (1 - Math.Clamp(_live, 0, 1)) * h;
+ ctx.DrawLine(new Pen(NotaPalette.TextSecondary, 1), new Point(3, ly), new Point(w - 3, ly));
+ }
+ }
+ ctx.DrawRectangle(null, new Pen(NotaPalette.BorderDefault, 1), rect, r, r);
+ double hy = Math.Clamp(y, 1.5, h - 2.5);
+ ctx.DrawRectangle(Handle, null, new Rect(1.5, hy - 1, w - 3, 2), 1, 1);
+ }
+}
+
+// The transfer curve: input dB (x, −60…0) against output dB (y), unity dashed, the knee drawn
+// as a curve, the threshold node brass. Drag anywhere: left / right moves the threshold,
+// up / down the ratio; double-click restores both. The live input level rides the curve as a small dot.
+internal sealed class CompTransferView : Control
+{
+ private const double Lo = -60, Hi = 0;
+ private double _thr = -18, _ratio = 3, _knee = 6, _range = 48, _live = double.NaN;
+ private bool _drag;
+ private double _startX, _startY, _startRatio, _startThr;
+
+ public event Action<double, double>? Changed; // threshold dB, ratio
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+ public event Action? Reset;
+ public bool Dragging => _drag;
+
+ public CompTransferView() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); }
+
+ public void Set(double thr, double ratio, double knee, double range, double liveInDb)
+ {
+ _thr = thr; _ratio = Math.Max(1, ratio); _knee = knee; _range = range; _live = liveInDb;
+ InvalidateVisual();
+ }
+
+ protected override Size MeasureOverride(Size available)
+ {
+ double s = double.IsInfinity(available.Height) ? 100 : available.Height;
+ return new Size(s, s);
+ }
+
+ private (double x0, double x1, double top, double bot) Geo() => (4, Bounds.Width - 4, 14, Bounds.Height - 12);
+ private static double Map(double db, double a, double b) => a + (db - Lo) / (Hi - Lo) * (b - a);
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { Reset?.Invoke(); e.Handled = true; return; }
+ _drag = true; _startX = e.GetPosition(this).X; _startY = e.GetPosition(this).Y; _startRatio = _ratio; _startThr = _thr;
+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_drag) Apply(e.GetPosition(this)); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_drag) return;
+ _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke();
+ }
+ private void Apply(Point p)
+ {
+ var (x0, x1, _, _) = Geo();
+ // Relative to where the drag began, so a click never jumps the curve.
+ double thr = Math.Clamp(_startThr + (p.X - _startX) / Math.Max(1, x1 - x0) * (Hi - Lo), Lo, Hi);
+ // Ratio on a log feel: 40 px up doubles it, down halves it.
+ double ratio = Math.Clamp(_startRatio * Math.Pow(2, (_startY - p.Y) / 40.0), 1, 20);
+ _thr = thr; _ratio = ratio;
+ Changed?.Invoke(thr, ratio);
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 20) return;
+ var rect = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, rect);
+ var (x0, x1, top, bot) = Geo();
+ double X(double db) => Map(db, x0, x1);
+ double Y(double db) => Map(db, bot, top);
+ for (int i = 1; i <= 3; i++)
+ {
+ double gx = x0 + (x1 - x0) * i / 4.0, gy = top + (bot - top) * i / 4.0;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(gx, top), new Point(gx, bot));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, gy), new Point(x1, gy));
+ }
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1) { DashStyle = new DashStyle(new double[] { 2, 3 }, 0) }, new Point(X(Lo), Y(Lo)), new Point(X(Hi), Y(Hi)));
+ double tx = X(_thr);
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(tx, top), new Point(tx, bot));
+
+ var pts = new List<Point>();
+ for (double db = Lo; db <= Hi + 0.01; db += 0.75)
+ pts.Add(new Point(X(db), Y(db - CompDraw.Reduction(db, _thr, _ratio, _knee, _range))));
+ CompDraw.Polyline(ctx, NotaGraph.PrimaryPen, pts);
+
+ // The live operating point: where the signal sits on the curve right now.
+ if (!double.IsNaN(_live) && _live > Lo)
+ {
+ double li = Math.Min(Hi, _live);
+ ctx.DrawEllipse(NotaPalette.TextPrimary, null, new Point(X(li), Y(li - CompDraw.Reduction(li, _thr, _ratio, _knee, _range))), 2, 2);
+ }
+ NotaGraph.Node(ctx, new Point(tx, Y(_thr - CompDraw.Reduction(_thr, _thr, _ratio, _knee, _range))), active: true);
+
+ NotaGraph.Title(ctx, rect, "Transfer");
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.TopRight, NotaNum.F($"{_ratio:0.#}:1"), NotaPalette.AccentBright);
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.BottomLeft, "−60");
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.BottomRight, "0 in");
+ }
+}
+
+// The reduction history: four seconds of gain reduction hanging from the top edge (depth =
+// reduction), a teal dashed line at the held peak. Push() once per UI tick; a click clears
+// the held peak.
+internal sealed class CompGrHistoryView : Control
+{
+ private const int N = 240; // 4 s at the 60 Hz UI tick
+ private readonly double[] _h = new double[N];
+ private int _w, _count;
+ public double Current { get; private set; }
+ public double Peak { get; private set; }
+ public double Average { get; private set; }
+
+ public CompGrHistoryView() => ClipToBounds = true;
+
+ public void Push(double grDb)
+ {
+ _h[_w] = Math.Max(0, grDb); _w = (_w + 1) % N; _count = Math.Min(N, _count + 1);
+ Current = Math.Max(0, grDb);
+ double pk = 0, sum = 0; int active = 0;
+ for (int i = 0; i < _count; i++) { double v = _h[i]; pk = Math.Max(pk, v); if (v > 0.05) { sum += v; active++; } }
+ Peak = pk;
+ Average = active > 0 ? sum / active : 0;
+ InvalidateVisual();
+ }
+
+ public void Clear() { Array.Clear(_h); _count = 0; Current = Peak = Average = 0; InvalidateVisual(); }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ Clear(); e.Handled = true;
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 20) return;
+ var rect = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, rect);
+ double top = 14, bot = h - 12, x0 = 3, x1 = w - 3;
+ double scale = Peak > 18 ? 36 : Peak > 9 ? 18 : 12; // dB at the bottom edge
+ for (int i = 1; i <= 3; i++) { double gy = top + (bot - top) * i / 4.0; ctx.DrawLine(NotaGraph.GridPen, new Point(x0, gy), new Point(x1, gy)); }
+ ctx.DrawLine(new Pen(NotaPalette.GraphBorder, 1), new Point(x0, top), new Point(x1, top));
+
+ if (_count > 1)
+ {
+ var pts = new List<Point>(_count);
+ for (int i = 0; i < _count; i++)
+ {
+ int idx = (_w - _count + i + N) % N;
+ double x = x1 - (_count - 1 - i) * (x1 - x0) / (N - 1);
+ pts.Add(new Point(x, top + Math.Clamp(_h[idx] / scale, 0, 1) * (bot - top)));
+ }
+ CompDraw.Polyline(ctx, NotaGraph.PrimaryPen, pts);
+ }
+ if (Peak > 0.05)
+ {
+ double py = top + Math.Clamp(Peak / scale, 0, 1) * (bot - top);
+ ctx.DrawLine(new Pen(NotaPalette.Teal, 1) { DashStyle = new DashStyle(new double[] { 2, 4 }, 0) }, new Point(x0, py), new Point(x1, py));
+ var ft = CompDraw.Text(NotaNum.F($"peak −{Peak:0.0}"), NotaPalette.TealBright);
+ ctx.DrawText(ft, new Point(x1 - ft.Width - 2, Math.Clamp(py - ft.Height - 1, top, bot - ft.Height)));
+ }
+ NotaGraph.Title(ctx, rect, "Gain reduction");
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.TopRight, Current > 0.05 ? NotaNum.F($"−{Current:0.0} dB") : "0.0 dB", NotaPalette.AccentBright);
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.BottomLeft, "−4 s");
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.BottomRight, "now");
+ }
+}
+
+// Motion: the reduction envelope (brass, hanging from 0 dB at the top) over the input level
+// (teal, −60…0 dB bottom→top) with the threshold dashed on the input scale — a window short
+// enough that attack and release read as shapes. Fed from the device's 1 ms envelope ring.
+internal sealed class CompMotionView : Control
+{
+ private float[] _in = Array.Empty<float>(), _gr = Array.Empty<float>();
+ private int _points;
+ private double _thr = -18, _windowMs = 600;
+ private double _grScale = 12;
+
+ public CompMotionView() => ClipToBounds = true;
+
+ /// <summary>Feed the rings (oldest→newest, one point per ms) and the window to show.</summary>
+ public void Set(float[] input, float[] gr, int count, double threshold, double windowMs)
+ {
+ _in = input; _gr = gr; _points = count; _thr = threshold; _windowMs = windowMs;
+ double pk = 0;
+ int n = Math.Min(count, (int)windowMs);
+ for (int i = count - n; i < count; i++) if (i >= 0) pk = Math.Max(pk, gr[i]);
+ _grScale = pk > 24 ? 48 : pk > 12 ? 24 : pk > 6 ? 12 : 6;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 20) return;
+ var rect = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, rect);
+ double top = 14, bot = h - 12, x0 = 3, x1 = w - 3;
+ for (int i = 1; i < 6; i++) { double gx = x0 + (x1 - x0) * i / 6.0; ctx.DrawLine(NotaGraph.GridPen, new Point(gx, top), new Point(gx, bot)); }
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, (top + bot) / 2), new Point(x1, (top + bot) / 2));
+
+ double YIn(double db) => bot - Math.Clamp((db + 60) / 60, 0, 1) * (bot - top);
+ double YGr(double db) => top + Math.Clamp(db / _grScale, 0, 1) * (bot - top);
+
+ int n = Math.Min(_points, (int)Math.Round(_windowMs));
+ if (n > 1 && _in.Length >= _points && _gr.Length >= _points)
+ {
+ int start = _points - n;
+ // Decimate to about one point per pixel, keeping each column's extreme.
+ int cols = Math.Max(2, (int)(x1 - x0));
+ var inPts = new List<Point>(cols); var grPts = new List<Point>(cols);
+ for (int c = 0; c < cols; c++)
+ {
+ int a = start + (int)((long)c * n / cols), b = start + (int)((long)(c + 1) * n / cols);
+ if (b <= a) b = a + 1;
+ double mi = -120, mg = 0;
+ for (int k = a; k < b && k < _points; k++) { mi = Math.Max(mi, _in[k]); mg = Math.Max(mg, _gr[k]); }
+ double x = x0 + (double)c / (cols - 1) * (x1 - x0);
+ inPts.Add(new Point(x, YIn(mi))); grPts.Add(new Point(x, YGr(mg)));
+ }
+ CompDraw.Polyline(ctx, NotaGraph.SecondaryPen(NotaPalette.Teal, 1.1), inPts);
+ CompDraw.Polyline(ctx, NotaGraph.PrimaryPen, grPts);
+ }
+ double ty = YIn(_thr);
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1) { DashStyle = new DashStyle(new double[] { 2, 4 }, 0) }, new Point(x0, ty), new Point(x1, ty));
+
+ NotaGraph.Title(ctx, rect, "Reduction envelope");
+ NotaGraph.Legend(ctx, x1 - 2, 3, ("reduction", NotaPalette.AccentBright, NotaGraph.Mark.Line), ("input", NotaPalette.TealBright, NotaGraph.Mark.Line));
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.BottomLeft, "0");
+ NotaGraph.Axis(ctx, rect, NotaGraph.Corner.BottomRight, _windowMs >= 1000 ? NotaNum.F($"{_windowMs / 1000:0.#} s") : NotaNum.F($"{_windowMs:0} ms"));
+ var sc = CompDraw.Text(NotaNum.F($"−{_grScale:0} dB"), NotaPalette.TextAxis);
+ ctx.DrawText(sc, new Point(x1 - sc.Width - 2, bot - sc.Height - 11));
+ }
+}
+
+// The sidechain key: the spectrum of the unfiltered key (brass) with the detector filters
+// laid over it (teal dashed — the 2-pole HP × LP response with its Q). Drag a handle
+// sideways to move its corner, up / down to change Q; double-click opens that filter.
+// Framed brass while Listen is on (the key is what you hear).
+internal sealed class CompKeyView : Control
+{
+ private const int FftN = 2048, Bins = FftN / 2;
+ private const double FMin = 20, FMax = 20000;
+ private readonly double[] _re = new double[FftN], _im = new double[FftN], _hann = new double[FftN], _db = new double[Bins];
+ private double _sr = 48000, _hp = 20, _lp = 20000, _q = 0.707;
+ private bool _listen, _has;
+ private int _drag, _hover; // 0 none, 1 HP, 2 LP
+ private double _startY, _startQ;
+ private bool _qGesture;
+
+ public double PeakHz { get; private set; }
+ public event Action<int, double>? FreqChanged; // handle (0 HP / 1 LP), Hz
+ public event Action<double>? QChanged;
+ public event Action<int>? GestureBegin; // 0 HP, 1 LP, 2 Q
+ public event Action<int>? GestureEnd;
+ public event Action<int>? Reset;
+ public bool Dragging => _drag != 0;
+
+ public CompKeyView()
+ {
+ ClipToBounds = true;
+ Cursor = new Cursor(StandardCursorType.SizeAll);
+ for (int i = 0; i < FftN; i++) _hann[i] = 0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (FftN - 1));
+ Array.Fill(_db, -120);
+ }
+
+ public void SetFilter(double hpHz, double lpHz, double q, bool listen)
+ {
+ _hp = hpHz; _lp = lpHz; _q = q; _listen = listen;
+ InvalidateVisual();
+ }
+
+ private int _silentTicks;
+
+ /// <summary>Analyse the key samples (oldest→newest, at least 2048). A silent frame keeps the
+ /// last frame that had signal for about a second, so a drum key does not blink out between hits.</summary>
+ public void SetKey(float[] src, int offset, int count, double sampleRate)
+ {
+ if (count < FftN) { _has = false; InvalidateVisual(); return; }
+ _sr = sampleRate > 0 ? sampleRate : 48000;
+ int s0 = offset + count - FftN;
+ double energy = 0;
+ for (int i = 0; i < FftN; i++) { double v = src[s0 + i]; energy += v * v; _re[i] = v * _hann[i]; _im[i] = 0; }
+ if (energy <= 1e-10)
+ {
+ if (++_silentTicks > 60 && _has) { _has = false; PeakHz = 0; InvalidateVisual(); }
+ return;
+ }
+ _silentTicks = 0;
+ _has = true;
+ Fft(_re, _im);
+ double refMag = FftN / 4.0, best = -200; int bestK = 0;
+ for (int k = 1; k < Bins; k++)
+ {
+ double mag = Math.Sqrt(_re[k] * _re[k] + _im[k] * _im[k]);
+ double db = 20 * Math.Log10(mag / refMag + 1e-9);
+ _db[k] = db;
+ double hz = k * _sr / FftN;
+ if (hz >= FMin && db > best) { best = db; bestK = k; }
+ }
+ PeakHz = bestK * _sr / FftN;
+ InvalidateVisual();
+ }
+
+ private static double XOf(double hz, double w) => Math.Log(Math.Clamp(hz, FMin, FMax) / FMin) / Math.Log(FMax / FMin) * w;
+ private static double HzOf(double x, double w) => FMin * Math.Pow(FMax / FMin, Math.Clamp(x / Math.Max(1, w), 0, 1));
+ private int Nearest(double x) => Math.Abs(x - XOf(_hp, Bounds.Width)) <= Math.Abs(x - XOf(_lp, Bounds.Width)) ? 1 : 2;
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ int hnd = Nearest(e.GetPosition(this).X);
+ if (e.ClickCount == 2) { Reset?.Invoke(hnd - 1); e.Handled = true; return; }
+ _drag = hnd; _startY = e.GetPosition(this).Y; _startQ = _q;
+ GestureBegin?.Invoke(hnd - 1); _qGesture = false;
+ e.Pointer.Capture(this); Apply(e.GetPosition(this)); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (_drag != 0) { Apply(e.GetPosition(this)); return; }
+ int hnd = Nearest(e.GetPosition(this).X);
+ if (hnd != _hover) { _hover = hnd; InvalidateVisual(); }
+ }
+ protected override void OnPointerExited(PointerEventArgs e) { base.OnPointerExited(e); if (_hover != 0) { _hover = 0; InvalidateVisual(); } }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (_drag == 0) return;
+ GestureEnd?.Invoke(_drag - 1);
+ if (_qGesture) { GestureEnd?.Invoke(2); _qGesture = false; }
+ _drag = 0; e.Pointer.Capture(null);
+ }
+ private void Apply(Point p)
+ {
+ double hz = HzOf(p.X, Bounds.Width);
+ if (_drag == 1) { _hp = Math.Clamp(hz, 20, 2000); FreqChanged?.Invoke(0, _hp); }
+ else { _lp = Math.Clamp(hz, 200, 20000); FreqChanged?.Invoke(1, _lp); }
+ double q = Math.Clamp(_startQ * Math.Pow(2, (_startY - p.Y) / 50.0), 0.5, 4);
+ if (Math.Abs(q - _q) > 1e-4 && Math.Abs(p.Y - _startY) > 3)
+ {
+ if (!_qGesture) { GestureBegin?.Invoke(2); _qGesture = true; }
+ _q = q; QChanged?.Invoke(q);
+ }
+ InvalidateVisual();
+ }
+
+ // |H| of a 2-pole high-pass / low-pass at f, corner fc, quality q.
+ private static double Mag2(double f, double fc, double q, bool high)
+ {
+ double r = f / fc, re = 1 - r * r, im = r / q;
+ double den = Math.Sqrt(re * re + im * im);
+ return (high ? r * r : 1) / Math.Max(den, 1e-9);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 20) return;
+ var rect = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, rect);
+ if (_listen) ctx.DrawRectangle(null, new Pen(NotaPalette.BorderBrass, 1), new RoundedRect(rect.Deflate(0.5), NotaGraph.Radius));
+ double top = 14, bot = h - 12;
+ const double floor = -84, ceil = 0;
+ double Y(double db) => top + Math.Clamp((ceil - db) / (ceil - floor), 0, 1) * (bot - top);
+ foreach (double f in new[] { 100.0, 1000, 10000 }) { double gx = XOf(f, w); ctx.DrawLine(NotaGraph.GridPen, new Point(gx, top), new Point(gx, bot)); }
+ for (int i = 1; i <= 3; i++) { double gy = top + (bot - top) * i / 4.0; ctx.DrawLine(NotaGraph.GridPen, new Point(2, gy), new Point(w - 2, gy)); }
+
+ if (_has)
+ {
+ var pts = new List<Point>();
+ int cols = Math.Max(8, (int)(w / 2));
+ for (int c = 0; c <= cols; c++)
+ {
+ double f0 = HzOf((c - 0.5) * w / cols, w), f1 = HzOf((c + 0.5) * w / cols, w);
+ int k0 = Math.Max(1, (int)(f0 * FftN / _sr)), k1 = Math.Min(Bins - 1, Math.Max(k0, (int)(f1 * FftN / _sr)));
+ double db = -120; for (int k = k0; k <= k1; k++) db = Math.Max(db, _db[k]);
+ pts.Add(new Point(c * w / cols, Y(db)));
+ }
+ CompDraw.Polyline(ctx, NotaGraph.PrimaryPen, pts);
+ }
+
+ // The key filter response, pinned at 0 dB = the top grid line.
+ bool hpOn = _hp > 20.5, lpOn = _lp < 19999;
+ var fp = new List<Point>();
+ for (int i = 0; i <= 96; i++)
+ {
+ double x = w * i / 96.0, f = HzOf(x, w);
+ double m = (hpOn ? Mag2(f, _hp, _q, true) : 1) * (lpOn ? Mag2(f, _lp, _q, false) : 1);
+ fp.Add(new Point(x, Y(20 * Math.Log10(Math.Max(m, 1e-6)) - 6)));
+ }
+ CompDraw.Polyline(ctx, new Pen(NotaPalette.Teal, 1.2) { DashStyle = new DashStyle(new double[] { 4, 3 }, 0) }, fp);
+
+ foreach (var (hz, idx, on) in new[] { (_hp, 1, hpOn), (_lp, 2, lpOn) })
+ {
+ double x = Math.Clamp(XOf(hz, w), 3, w - 3);
+ bool hot = _drag == idx || (_drag == 0 && _hover == idx);
+ ctx.DrawLine(new Pen(hot ? NotaPalette.AccentBright : NotaPalette.BorderStrong, 1), new Point(x, top), new Point(x, bot));
+ NotaGraph.Node(ctx, new Point(x, Y(-6)), active: hot || on);
+ string lbl = !on ? "off" : hz >= 1000 ? NotaNum.F($"{hz / 1000:0.#}k") : NotaNum.F($"{hz:0}");
+ var ft = CompDraw.Text(lbl, on ? NotaPalette.AccentBright : NotaPalette.TextAxis);
+ double lx = Math.Clamp(x - ft.Width / 2, 3, w - 3 - ft.Width);
+ ctx.DrawText(ft, new Point(lx, h - ft.Height - 2));
+ }
+
+ NotaGraph.Title(ctx, rect, "Sidechain key");
+ NotaGraph.Legend(ctx, w - 6, 3, ("key", NotaPalette.AccentBright, NotaGraph.Mark.Line), ("key filter", NotaPalette.TealBright, NotaGraph.Mark.Dashed));
+ if (!_has)
+ {
+ var ft = CompDraw.Text("no key signal", NotaPalette.TextTertiary, 8);
+ ctx.DrawText(ft, new Point((w - ft.Width) / 2, (top + bot - ft.Height) / 2));
+ }
+ }
+
+ // In-place iterative radix-2 Cooley–Tukey FFT.
+ private static void Fft(double[] re, double[] im)
+ {
+ int n = re.Length;
+ for (int i = 1, j = 0; i < n; i++)
+ {
+ int bit = n >> 1;
+ for (; (j & bit) != 0; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) { (re[i], re[j]) = (re[j], re[i]); (im[i], im[j]) = (im[j], im[i]); }
+ }
+ for (int len = 2; len <= n; len <<= 1)
+ {
+ double ang = -2 * Math.PI / len, wr = Math.Cos(ang), wi = Math.Sin(ang);
+ for (int i = 0; i < n; i += len)
+ {
+ double cr = 1, ci = 0;
+ for (int k = 0; k < len / 2; k++)
+ {
+ int a = i + k, b = i + k + len / 2;
+ double tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;
+ re[b] = re[a] - tr; im[b] = im[a] - ti;
+ re[a] += tr; im[a] += ti;
+ double nr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = nr;
+ }
+ }
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/ReverbTail.cs b/src/managed/Nota.App/Controls/ReverbTail.cs
deleted file mode 100644
index 073dc7e6..00000000
--- a/src/managed/Nota.App/Controls/ReverbTail.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Interactive reverb decay tail (mockup 2h): a real decaying impulse response with the
-// teal pre-delay gap marked and RT60 printed. Drag the tail (right area) to set decay,
-// drag near the gap edge to set pre-delay. Reads/writes the device's Decay + Pre-Delay
-// params with automation gestures.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Input;
-using Avalonia.Media;
-using Nota.Application;
-
-namespace Nota.App;
-
-internal sealed class ReverbTail : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush Accent = NotaPalette.AccentBright;
- private static readonly IBrush Teal = NotaPalette.Teal;
- private static readonly IBrush GridB = NotaGraph.Grid;
- private static readonly IBrush Fill = NotaPalette.Wash(NotaPalette.Accent, 0x20);
- private static readonly IBrush TealFill = NotaPalette.Wash(NotaPalette.Teal, 0x1E);
- private static readonly IBrush Axis = NotaPalette.TextAxis;
- private static readonly Typeface Face = NotaFonts.Mono;
-
- private readonly IAudioEngine _e;
- private readonly int _t, _di, _decayP, _preP;
- private readonly Func<double, double> _rt60;
- private const double AxisSec = 4.0, MaxPreMs = 200.0, GapFrac = 0.18;
- private int _drag = -1; // 0 = decay, 1 = pre-delay
-
- public ReverbTail(IAudioEngine e, int t, int di, int decayP, int preP, Func<double, double> rt60)
- { _e = e; _t = t; _di = di; _decayP = decayP; _preP = preP; _rt60 = rt60; MinHeight = 96; }
- public void Tick() => InvalidateVisual();
-
- private float P(int p) => _e.DeviceGetParam(_t, _di, p);
- private (double x0, double x1, double top, double bot) Geo() => (8, Bounds.Width - 8, 14, Bounds.Height - 14);
- private double GapX() { var (x0, x1, _, _) = Geo(); return x0 + P(_preP) * GapFrac * (x1 - x0); }
-
- protected override void OnPointerPressed(PointerPressedEventArgs e)
- {
- var p = e.GetPosition(this);
- _drag = Math.Abs(p.X - GapX()) < 10 ? 1 : 0;
- Gest(true); e.Pointer.Capture(this); Apply(p); e.Handled = true;
- }
- protected override void OnPointerMoved(PointerEventArgs e) { if (_drag >= 0) Apply(e.GetPosition(this)); }
- protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_drag >= 0) { Gest(false); _drag = -1; e.Pointer.Capture(null); } }
-
- private void Gest(bool begin)
- {
- int p = _drag == 1 ? _preP : _decayP;
- if (begin) _e.BeginAutomationWrite(_t, AutomationTarget.DeviceParam, _di, p, "");
- else _e.EndAutomationWrite(_t, AutomationTarget.DeviceParam, _di, p, "");
- }
- private void Apply(Point pt)
- {
- var (x0, x1, _, _) = Geo();
- if (_drag == 1) _e.DeviceSetParam(_t, _di, _preP, (float)Math.Clamp((pt.X - x0) / (GapFrac * (x1 - x0)), 0, 1));
- else _e.DeviceSetParam(_t, _di, _decayP, (float)Math.Clamp((pt.X - x0) / (x1 - x0), 0, 1));
- InvalidateVisual();
- }
-
- private void Txt(DrawingContext c, string t, double x, double y, IBrush b) => c.DrawText(new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height; if (w <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- var (x0, x1, top, bot) = Geo();
- for (int i = 1; i <= 3; i++) { double gy = top + (bot - top) * i / 4.0; ctx.DrawLine(new Pen(GridB, 1), new Point(x0, gy), new Point(x1, gy)); }
-
- double gapX = GapX();
- // Pre-delay gap (teal).
- ctx.FillRectangle(TealFill, new Rect(x0, top, gapX - x0, bot - top));
- ctx.DrawLine(new Pen(Teal, 1.4), new Point(gapX, top), new Point(gapX, bot));
-
- // Decay envelope: exp(-6.9 t / RT60) over a 4 s axis, drawn as hair lines + fill.
- double rt60 = Math.Max(0.05, _rt60(P(_decayP)));
- var geo = new StreamGeometry();
- using (var g = geo.Open())
- {
- g.BeginFigure(new Point(gapX, bot), true);
- for (double x = gapX; x <= x1; x += 2)
- {
- double t = (x - gapX) / (x1 - gapX) * AxisSec;
- double env = Math.Exp(-6.9 * t / rt60);
- g.LineTo(new Point(x, bot - env * (bot - top)));
- }
- g.LineTo(new Point(x1, bot)); g.EndFigure(true);
- }
- var pen = new Pen(Accent, 1.6, lineJoin: PenLineJoin.Round);
- Point? prev = null;
- for (double x = gapX; x <= x1; x += 3)
- {
- double t = (x - gapX) / (x1 - gapX) * AxisSec;
- double env = Math.Exp(-6.9 * t / rt60);
- var cur = new Point(x, bot - env * (bot - top));
- if (prev is { } pp) ctx.DrawLine(pen, pp, cur);
- prev = cur;
- if (((int)x & 3) == 0) ctx.DrawLine(new Pen(Fill, 1), new Point(x, bot), new Point(x, bot - env * (bot - top)));
- }
-
- Txt(ctx, $"DECAY TAIL", x0 + 2, top - 1, Axis);
- Txt(ctx, $"RT60 {rt60:0.00}\u2009s", x1 - 66, top - 1, Accent);
- Txt(ctx, $"pre {P(_preP) * MaxPreMs:0}\u2009ms", gapX + 3, bot - 10, Teal);
- Txt(ctx, "4\u2009s", x1 - 16, bot + 2, Axis);
- }
-}
diff --git a/src/managed/Nota.App/Controls/ReverbViews.cs b/src/managed/Nota.App/Controls/ReverbViews.cs
new file mode 100644
index 00000000..0642b8cb
--- /dev/null
+++ b/src/managed/Nota.App/Controls/ReverbViews.cs
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The custom-drawn view of the Nota Reverb card: the decay-tail window. The impulse flashes
+// at the pre-delay (teal), the early reflections light one after another, then the RT60
+// curve draws itself and fades — a loop while the reverb is sounding, a still picture when
+// it is not. Frozen, the tail is a held line under a brass frame. It is also a control:
+// drag the pre-delay marker to set the pre-delay, drag anywhere else to lengthen or shorten
+// the decay; double-click either to reset. It draws what the card hands it and owns no
+// engine state.
+
+using System;
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class ReverbTailView : Control
+{
+ public const double AxisSec = 4.0;
+ // The pre-delay marker sits between 3 % and 33 % of the width (0 … 200 ms); the early
+ // reflections are drawn magnified — 100 ms spans 35 % — or they would pile onto the marker.
+ private const double PreLo = 0.03, PreSpan = 0.30, ErSpanPer100Ms = 0.35;
+
+ private double _rt60 = 2, _preNorm = 0.1, _preMs = 20;
+ private double[] _erMs = Array.Empty<double>();
+ private float[] _erGain = Array.Empty<float>();
+ private bool _freeze;
+ private double _phase = -1; // 0..1 while sounding, −1 = still
+ private int _drag; // 0 none, 1 decay, 2 pre-delay
+ private double _dragX, _dragY, _dragV;
+
+ public event Action<int, double>? Changed; // target (0 decay / 1 pre-delay), new normalised value
+ public event Action<int>? GestureBegin;
+ public event Action<int>? GestureEnd;
+ public event Action<int>? Reset;
+ public Func<double>? DecayValue { get; set; } // the Decay param now, for the relative drag
+
+ public bool Dragging => _drag != 0;
+
+ public ReverbTailView()
+ {
+ ClipToBounds = true;
+ MinHeight = 40;
+ Cursor = new Cursor(StandardCursorType.SizeWestEast);
+ }
+
+ /// <summary>Feed the window: RT60 in seconds (≤ 0 = frozen), the pre-delay (normalised,
+ /// and in ms for the label), and the early reflections (ms after the pre-delay, level 0..1;
+ /// empty = off).</summary>
+ public void Set(double rt60, bool freeze, double preNorm, double preMs, double[] erMs, float[] erGain)
+ {
+ _rt60 = rt60; _freeze = freeze; _preNorm = Math.Clamp(preNorm, 0, 1); _preMs = preMs;
+ _erMs = erMs; _erGain = erGain;
+ InvalidateVisual();
+ }
+
+ /// <summary>Where the loop is (0..1), or −1 for the still picture.</summary>
+ public void SetPhase(double phase)
+ {
+ if (phase < 0 && _phase < 0) return;
+ _phase = phase;
+ InvalidateVisual();
+ }
+
+ private (double x0, double x1, double top, double bot) Geo() => (8, Bounds.Width - 8, 15, Bounds.Height - 12);
+ private double PreX() { var (x0, x1, _, _) = Geo(); return x0 + (PreLo + PreSpan * _preNorm) * (x1 - x0); }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ var p = e.GetPosition(this);
+ int target = Math.Abs(p.X - PreX()) <= 8 ? 2 : 1;
+ if (e.ClickCount == 2) { Reset?.Invoke(target - 1); e.Handled = true; return; }
+ _drag = target; _dragX = p.X; _dragY = p.Y; _dragV = DecayValue?.Invoke() ?? 0.5;
+ GestureBegin?.Invoke(target - 1);
+ e.Pointer.Capture(this);
+ Apply(p);
+ e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_drag != 0) Apply(e.GetPosition(this)); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (_drag == 0) return;
+ GestureEnd?.Invoke(_drag - 1); _drag = 0; e.Pointer.Capture(null);
+ }
+
+ private void Apply(Point p)
+ {
+ var (x0, x1, top, bot) = Geo();
+ if (x1 <= x0) return;
+ if (_drag == 2)
+ Changed?.Invoke(1, Math.Clamp(((p.X - x0) / (x1 - x0) - PreLo) / PreSpan, 0, 1));
+ else
+ // Right or up = a longer tail; one window width spans the whole range.
+ Changed?.Invoke(0, Math.Clamp(_dragV + (p.X - _dragX) / (x1 - x0) - (p.Y - _dragY) / Math.Max(20, bot - top) * 0.5, 0, 1));
+ }
+
+ private static FormattedText Text(string t, IBrush ink, double size = 7.5)
+ => new(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 16 || h < 16) return;
+ var rect = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, rect);
+ if (_freeze)
+ {
+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Accent, 0x0D), rect);
+ ctx.DrawRectangle(null, new Pen(NotaPalette.BorderBrass, 1), new RoundedRect(rect.Deflate(0.5), NotaGraph.Radius));
+ }
+ var (x0, x1, top, bot) = Geo();
+ if (x1 <= x0 || bot <= top) return;
+ double span = bot - top;
+
+ // Quarter-second grid across the window, a mid line and the floor.
+ for (int i = 1; i < 4; i++)
+ {
+ double x = x0 + (x1 - x0) * i / 4.0;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x, 4), new Point(x, h - 4));
+ }
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, top + span * 0.5), new Point(x1, top + span * 0.5));
+ ctx.DrawLine(new Pen(NotaPalette.GridBeat, 1.2), new Point(x0, bot), new Point(x1, bot));
+
+ double preX = PreX();
+ bool live = _phase >= 0;
+ double ph = live ? _phase : 1;
+
+ // ---- the tail: exp(−6.9 t / RT60) on a linear amplitude scale over 4 s --------
+ double Env(double t) => _freeze ? 0.92 : Math.Exp(-6.9 * t / Math.Max(0.05, _rt60));
+ double YAt(double x) => bot - span * Env((x - preX) / Math.Max(1, x1 - preX) * AxisSec);
+ var full = new StreamGeometry();
+ var fill = new StreamGeometry();
+ using (var g = full.Open())
+ using (var f = fill.Open())
+ {
+ g.BeginFigure(new Point(x0, bot), false);
+ g.LineTo(new Point(preX, bot));
+ f.BeginFigure(new Point(preX, bot), true);
+ for (double x = preX; x <= x1 + 0.1; x += 2)
+ {
+ var pt = new Point(Math.Min(x, x1), YAt(Math.Min(x, x1)));
+ g.LineTo(pt); f.LineTo(pt);
+ }
+ f.LineTo(new Point(x1, bot));
+ f.EndFigure(true);
+ }
+ ctx.DrawGeometry(NotaPalette.Wash(NotaPalette.Accent, 0x12), null, fill);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.Accent, 0x55), 1.4, lineJoin: PenLineJoin.Round), full);
+
+ // The bright stroke draws itself over the first half of the loop, then fades a little.
+ double reach = _freeze || !live ? 1 : Math.Clamp(ph / 0.52, 0, 1);
+ double tailOp = !live ? 1 : _freeze ? 0.75 + 0.25 * Math.Sin(ph * Math.PI) : ph < 0.06 ? 0.2 + ph / 0.06 * 0.8 : ph < 0.86 ? 1 : 1 - (ph - 0.86) / 0.14 * 0.8;
+ if (reach > 0)
+ {
+ double xEnd = preX + (x1 - preX) * reach;
+ var bright = new StreamGeometry();
+ using (var g = bright.Open())
+ {
+ g.BeginFigure(new Point(x0, bot), false);
+ g.LineTo(new Point(preX, bot));
+ for (double x = preX; x <= xEnd + 0.1; x += 2) g.LineTo(new Point(Math.Min(x, xEnd), YAt(Math.Min(x, xEnd))));
+ }
+ using (ctx.PushOpacity(tailOp))
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, 1.8, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), bright);
+ }
+
+ // Where the tail has fallen 60 dB — the decay the knob names.
+ if (!_freeze)
+ {
+ double rx = preX + _rt60 / AxisSec * (x1 - preX);
+ if (rx <= x1) ctx.DrawEllipse(NotaPalette.AccentBright, null, new Point(rx, bot), 2.2, 2.2);
+ }
+
+ // ---- the impulse at the pre-delay and the early reflections ----------------
+ double burstOp = !live ? 0.9 : ph < 0.1 ? 1 : ph < 0.4 ? 1 - (ph - 0.1) / 0.3 * 0.6 : 0.4 - (ph - 0.4) / 0.6 * 0.18;
+ using (ctx.PushOpacity(burstOp))
+ ctx.DrawLine(new Pen(NotaPalette.Teal, 1.2), new Point(preX, top - 2), new Point(preX, bot));
+
+ int n = Math.Min(_erMs.Length, _erGain.Length);
+ for (int k = 0; k < n; k++)
+ {
+ double x = preX + _erMs[k] / 100.0 * ErSpanPer100Ms * (x1 - x0);
+ if (x > x1) break;
+ double fire = 0.08 + 0.1 * k / Math.Max(1, n - 1); // each lights a beat after the last
+ double since = ph - fire;
+ double op, sc;
+ if (_freeze) { op = 0.6 + 0.4 * Math.Max(0, Math.Cos(since * Math.PI * 2)); sc = 0.9; }
+ else if (!live) { op = 0.75; sc = 1; }
+ else if (since < 0) { op = 0.15; sc = 0.5; }
+ else if (since < 0.36) { op = 1 - since / 0.36 * 0.7; sc = 1 - since / 0.36 * 0.2; }
+ else { op = 0.3 - Math.Min(1, (since - 0.36) / 0.6) * 0.15; sc = 0.8 - Math.Min(1, (since - 0.36) / 0.6) * 0.3; }
+ double len = Math.Max(3, span * 0.52 * _erGain[k] * sc);
+ using (ctx.PushOpacity(op))
+ ctx.DrawLine(new Pen(NotaPalette.Teal, 1.2), new Point(x, bot), new Point(x, bot - len));
+ }
+
+ // ---- labels ------------------------------------------------------------------
+ var title = _freeze ? Text("TAIL HELD · no decay", NotaPalette.AccentBright) : Text("DECAY TAIL", NotaGraph.TitleInk);
+ ctx.DrawText(title, new Point(x0 - 3, 3));
+ var rt = Text(_freeze ? "RT60 ∞" : NotaNum.F($"RT60 {_rt60:0.00} s"), NotaPalette.AccentBright);
+ ctx.DrawText(rt, new Point(x1 + 3 - rt.Width, 3));
+ var pre = Text(NotaNum.F($"pre {_preMs:0} ms"), NotaPalette.TealBright);
+ ctx.DrawText(pre, new Point(Math.Min(preX + 3, x1 - pre.Width - 24), h - pre.Height - 2));
+ var ax = Text("4 s", NotaGraph.AxisInk);
+ ctx.DrawText(ax, new Point(x1 + 3 - ax.Width, h - ax.Height - 2));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs
index 08a9bcf2..f4bc5b3c 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs
@@ -1,15 +1,23 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Compressor (kind 1) body, mockup 2n on the shared shell
-// (700×260, full-bleed): a LIVE strip (character models + Thresh/Ratio/Mix) over a body
-// of the transfer plot + gain-reduction history (graphs 264) | a TIMING panel (Peak/RMS
-// · auto-release · Attack/Release/Knee/Lookahead · side-chain row) | an OUTPUT rail
-// (auto-gain · Makeup · Range). Params are the device's raw-unit params.
+// Detail · Devices — built-in Compressor body (device kind 1), a build of the "Nota
+// Compressor" mockup (700 × 260) on the Lens / Delay / Reverb frame: an always-visible LEVEL
+// column (threshold against the live key level · make-up, or the key gain on the Sidechain
+// tab), a centre tabbed panel — Curve (transfer curve + reduction history), Motion (the
+// reduction envelope against the input, so attack and release are seen, not guessed) and
+// Sidechain (key source, the key's spectrum under its filters, Listen) — a right tabbed panel
+// (Dynamics / Output) and a status strip. The graphs are controls: drag the transfer curve
+// for threshold / ratio, the key filter handles for HP / LP / Q. Every control is a device
+// param (raw units), so automation / MIDI learn / presets / A-B / persistence come for free;
+// the key source and its pre/post tap are the device's sidechain routing, not params.
+// FullBleed — the shared shell draws the header (name · preset · badge · GR meter · bypass).
using System;
+using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -20,147 +28,621 @@ namespace Nota.App;
internal sealed class CompressorDeviceBody : IDeviceBody
{
+ // ── Parameter indices (must match Compressor.h) ─────────────────────────────
private const int Threshold = 0, Ratio = 1, Attack = 2, Release = 3, Makeup = 4, Knee = 5, Mix = 6,
- Lookahead = 7, Detection = 8, AutoRelease = 9, AutoGain = 10, Range = 11, Character = 12, ScHP = 13, ScLP = 14, ScListen = 15;
+ Lookahead = 7, Detection = 8, AutoRelease = 9, AutoGain = 10, Range = 11, Character = 12,
+ ScHP = 13, ScLP = 14, ScListen = 15, ScGain = 16, Hold = 17, ScQ = 18, External = 19, StereoLink = 20;
+ // Scope telemetry layout (Compressor::S_*), then the envelope rings and the key samples.
+ private const int S_InPk = 0, S_OutPk = 1, S_InRms = 2, S_OutRms = 3, S_Gr = 4, S_KeyPk = 5, S_AtkMs = 6,
+ S_RelMs = 7, S_SampleRate = 8, S_Bpm = 9, S_Latency = 10, S_Cpu = 11, S_ExtKey = 12, kScope = 14;
+ private const int EnvN = 2048, KeyN = 2048, ScopeLen = kScope + 2 * EnvN + KeyN;
+
private static readonly string[] Chars = { "Clean", "Glue", "Punch", "Opto", "FET" };
+ private static readonly string[] Detects = { "Peak", "RMS", "Auto" };
+ private static readonly double[] Windows = { 300, 600, 1000, 1500, 2000 };
public double Width => 700;
-
- public string? Subtitle => "DYNAMICS"; // the processing type, shown as the header badge
public bool FullBleed => true;
+ public string? Subtitle => "DYNAMICS";
public Control Build(DeviceCardContext ctx, int index)
{
- var engine = ctx.Engine; int track = ctx.TrackId, di = index;
+ var engine = ctx.Engine;
+ int track = ctx.TrackId, di = index;
float P(int p) => engine.DeviceGetParam(track, di, p);
float Mn(int p) => engine.DeviceParamMin(track, di, p);
float Mx(int p) => engine.DeviceParamMax(track, di, p);
- void SetR(int p, float v) => engine.DeviceSetParam(track, di, p, v);
+ float Def(int p) => engine.DeviceParamDefault(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, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, Mn(p), Mx(p)));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, double v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) => SetP(p, Def(p));
+ bool On(int p) => P(p) >= 0.5f;
int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p)), 0, n - 1);
- var readouts = new System.Collections.Generic.List<Action>();
- Control Lbl(string t, double fs, IBrush c) => new TextBlock { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c, VerticalAlignment = VerticalAlignment.Center };
- Control Row(double sp, params Control[] cs) { var r = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) r.Children.Add(c); return r; }
+ var readouts = new List<Action>();
+ var scope = new float[ScopeLen];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+ var envIn = new float[EnvN];
+ var envGr = new float[EnvN];
+
+ // ---- value maps (raw ↔ 0..1 for knobs and sliders) ------------------------------
+ (Func<double, double> N, Func<double, double> V) Lin(int p)
+ { double a = Mn(p), b = Mx(p); return (v => (v - a) / (b - a), n => a + Math.Clamp(n, 0, 1) * (b - a)); }
+ (Func<double, double> N, Func<double, double> V) Log(int p)
+ { double a = Mn(p), b = Mx(p); return (v => Math.Log(Math.Clamp(v, a, b) / a) / Math.Log(b / a), n => a * Math.Pow(b / a, Math.Clamp(n, 0, 1))); }
+ (Func<double, double> N, Func<double, double> V) Sq(int p)
+ { double b = Mx(p); return (v => Math.Sqrt(Math.Clamp(v, 0, b) / b), n => b * Math.Clamp(n, 0, 1) * Math.Clamp(n, 0, 1)); }
+ // Range reads as the limit it puts on the reduction: empty = off (48 dB), full = 1 dB.
+ (Func<double, double> N, Func<double, double> V) RangeMap() =>
+ (v => v >= 47.5 ? 0 : Math.Clamp((48 - v) / 47, 0, 1), n => n <= 0.005 ? 48 : 48 - 47 * Math.Clamp(n, 0, 1));
+
+ // ---- formatters -------------------------------------------------------------------
+ static string Ms(double ms) => ms >= 100 ? NotaNum.F($"{ms:0} ms") : NotaNum.F($"{ms:0.0} ms");
+ static string MsShort(double ms) => ms >= 100 ? NotaNum.F($"{ms:0}") : NotaNum.F($"{ms:0.0}");
+ static string Hz(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0} k") : NotaNum.F($"{hz:0} Hz");
+ static string Db(double db) => NotaNum.F($"{db:0.0} dB");
+ static string SDb(double db) => NotaNum.F($"{db:+0.0;−0.0;0.0} dB");
+ static string RatioF(double r) => r >= 9.95 ? NotaNum.F($"{r:0}:1") : NotaNum.F($"{r:0.#}:1");
+ static string PctF(double v) => NotaNum.F($"{v:0} %");
+ static string RangeF(double v) => v >= 47.5 ? "off" : NotaNum.F($"{v:0} dB");
+ static string Gr(double g) => g > 0.05 ? NotaNum.F($"−{g:0.0}") : "0.0";
+ static double LinDb(double lin) => lin > 1e-6 ? 20 * Math.Log10(lin) : -120;
+ static string Lvl(double db) => db <= -99 ? "−∞" : NotaNum.F($"{db:0.0}");
+ string HpF(double v) => v <= 20.5 ? "off" : Hz(v);
+ string LpF(double v) => v >= 19999 ? "off" : Hz(v);
+
+ // ---- small builders ---------------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, 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 T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+ static Border Rule() => new() { Height = 1, Background = NotaPalette.GraphBorder, Margin = new Thickness(0, 1) };
- var transfer = new CompTransfer(engine, track, di) { VerticalAlignment = VerticalAlignment.Stretch };
- var grHist = new CompGrHistory { VerticalAlignment = VerticalAlignment.Stretch };
+ // Gauge knob over a raw param through a value map (gesture + MIDI learn + live follow).
+ Control K(int p, string name, Func<double, string> fmt, (Func<double, double> N, Func<double, double> V) map,
+ IBrush? arc = null, bool emphasised = false, double cellW = 50)
+ {
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(map.N(P(p)), 1.0) { Accent = true, ArcColor = arc, Default = map.N(Def(p)), Width = 34, Height = 34 };
+ knob.ValueChanged += v => { Raw(p, map.V(v)); val.Text = fmt(P(p)); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ readouts.Add(() => { if (knob.Dragging) return; double c = map.N(P(p)); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; val.Text = fmt(P(p)); });
+ return KnobCell(name, knob, val, cellW, emphasised);
+ }
- // Gauge knob over a raw min..max param.
- Control Cell(string name, int p, Func<double, string> fmt, IBrush? arc = null, double size = 34)
+ // On/off switch bound to a param (≥ 0.5 = on).
+ Control Toggle(int p, string label, string tip)
{
- double mn = Mn(p), mx = Mx(p), span = Math.Max(1e-6, mx - mn);
- var val = new TextBlock { Text = fmt(P(p)), FontSize = 8, Foreground = TextPrimary };
- val.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var knob = new Knob((P(p) - mn) / span, 1.0) { Accent = true, ArcColor = arc, Default = (engine.DeviceParamDefault(track, di, p) - mn) / span, Width = size, Height = size };
- knob.ValueChanged += v => { float raw = (float)(mn + v * span); SetR(p, raw); val.Text = fmt(raw); transfer.Tick(); };
- knob.GestureBegin += () => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- knob.GestureEnd += () => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, p), name);
- readouts.Add(() => { if (!knob.Dragging) { double c = (P(p) - mn) / span; if (Math.Abs(c - knob.Value) > 1e-3) { knob.Value = c; val.Text = fmt(P(p)); } } });
- return KnobCell(name, knob, val, size + 16);
+ var wrap = Switch(label, () => On(p), () => SetP(p, On(p) ? 0 : 1), out var sync);
+ readouts.Add(sync);
+ ToolTip.SetTip(wrap, tip);
+ MidiLearn.Bind(wrap, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return wrap;
}
- Control Chips(int p, string[] names, IBrush? tint = null)
+
+ // Segmented chips over a discrete raw param (0 … n−1).
+ Control Seg(int p, string[] names, bool fill = false, double padX = 6)
{
int n = names.Length;
- var host = DeviceCardKit.Segments(names, () => Sel(p, n), iv => { SetR(p, iv); transfer.Tick(); }, out var sync);
+ var seg = Segments(names, () => Sel(p, n), iv => SetP(p, iv), out var sync, fill: fill, padX: padX);
readouts.Add(sync);
- MidiLearn.Bind(host, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
- return host;
+ MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return seg;
}
- Control Toggle(int p, string label)
+
+ // A latching chip over a toggle param (Listen · Auto gain).
+ Border Latch(int p, string text, string tip)
{
- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.SemiBold } };
- void Hi() { bool on = P(p) > 0.5f; b.Background = on ? NotaPalette.AccentSubtle : Sunken; b.BorderBrush = on ? NotaPalette.BorderBrass : BorderDef; ((TextBlock)b.Child!).Foreground = on ? NotaPalette.AccentHover : TextTertiary; }
- b.PointerPressed += (_, _) => { SetR(p, P(p) > 0.5f ? 0f : 1f); Hi(); };
+ var tb = new TextBlock { Text = text, FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ void Hi()
+ {
+ bool on = On(p);
+ b.Background = on ? NotaPalette.AccentSubtle : Raised;
+ b.BorderBrush = on ? NotaPalette.BorderBrass : Brushes.Transparent;
+ tb.Foreground = on ? NotaPalette.AccentHover : TextPrimary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; SetP(p, On(p) ? 0 : 1); Hi(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
readouts.Add(Hi); Hi();
- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), label);
return b;
}
- // Horizontal slider (label · track · value) over a raw param; optional log scale.
- Control HSlider(int p, string name, Func<double, string> fmt, bool log, IBrush accent, double tw, double lw = 0)
- {
- double mn = Mn(p), mx = Mx(p);
- double lmn = log ? Math.Log(mn) : mn, lspan = (log ? Math.Log(mx) : mx) - lmn;
- double NormOf(double v) { double x = log ? Math.Log(Math.Clamp(v, mn, mx)) : Math.Clamp(v, mn, mx); return (x - lmn) / Math.Max(1e-9, lspan); }
- double ValOf(double n) { double x = lmn + Math.Clamp(n, 0, 1) * lspan; return log ? Math.Exp(x) : x; }
- var row = DeviceCardKit.SliderRow(name, () => NormOf(P(p)), n => { SetR(p, (float)ValOf(n)); transfer.Tick(); }, () => fmt(P(p)), out var sync,
- begin: () => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, ""),
- end: () => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, ""),
- labelWidth: lw, trackWidth: tw, valueWidth: 44);
+
+ // A caps label + slider row over a raw param.
+ Control SliderRow(string label, int p, Func<double, string> fmt, (Func<double, double> N, Func<double, double> V) map, bool teal = false, double valW = 34)
+ {
+ var row = DeviceCardKit.SliderRow("", () => map.N(P(p)), n => Raw(p, map.V(n)), () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: valW, modulation: teal);
readouts.Add(sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), name);
- return row;
- }
-
- string Db1(double v) => $"{v:+0.0;−0.0;0.0}";
- string DbT(double v) => $"{v:0.0}\u2009dB";
- string RatioF(double v) => $"{v:0}:1";
- string Pct(double v) => $"{v:0}\u2009%";
- string Ms(double v) => v < 10 ? $"{v:0.0}\u2009ms" : $"{v:0}\u2009ms";
- string Hz(double v) => v >= 1000 ? $"{v / 1000:0.0}k" : $"{v:0}";
-
- // ---- top strip: character models + threshold/ratio/mix sliders ----
- var live = new Border { Height = 34, Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(9, 0), Children = {
- Chips(Character, Chars),
- HSlider(Threshold, "THRESH", DbT, false, Brass, 60), HSlider(Ratio, "RATIO", RatioF, true, Brass, 52), HSlider(Mix, "MIX", Pct, false, Brass, 52) } } };
-
- // ---- graphs column (transfer plot · GR history; both label themselves on-graph) ----
- var graphsCol = new Grid { Width = 264, RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 5, VerticalAlignment = VerticalAlignment.Stretch };
- graphsCol.Children.Add(transfer);
- grHist.Height = 64; Grid.SetRow(grHist, 1); graphsCol.Children.Add(grHist);
-
- // ---- TIMING panel ----
- Control Panel(string title, Control body) => new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 6), Child = new StackPanel { Spacing = 5, Children = { Lbl(title, 8, TextTertiary), body } } };
- var autoRel = Toggle(AutoRelease, "Auto-release"); DockPanel.SetDock(autoRel, Dock.Right);
- var detRow = new DockPanel { LastChildFill = false, Children = { Chips(Detection, new[] { "Peak", "RMS" }), autoRel } };
- var timing = Panel("TIMING", new StackPanel { Spacing = 6, Children = {
- detRow,
- Row(2, Cell("Attack", Attack, Ms), Cell("Release", Release, Ms), Cell("Knee", Knee, DbT), Cell("Lookahead", Lookahead, Ms)) } });
-
- // Sidechain row (teal — a detector path).
- Control Sidechain()
- {
- var ids = new System.Collections.Generic.List<int> { -1 };
- var combo = new ComboBox { FontSize = 9, Height = 22, MinWidth = 96 };
- combo.Items.Add("Internal");
- for (int i = 0; i < engine.TrackCount; i++) { if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue; ids.Add(ti.Id); combo.Items.Add($"{i + 1} · {(ti.IsReturn ? "Return" : ti.IsInstrument ? "Instr" : "Audio")}"); }
- combo.SelectedIndex = Math.Max(0, ids.IndexOf(engine.DeviceSidechainSource(track, di)));
- combo.SelectionChanged += (_, _) => { int s = combo.SelectedIndex; if (s >= 0 && s < ids.Count) { engine.SetDeviceSidechainSource(track, di, ids[s]); ctx.NotifyChanged(); } };
- var preBox = DeviceCardKit.Segments(new[] { "Pre", "Post" }, () => engine.DeviceSidechainTapPre(track, di) ? 0 : 1,
- i => engine.SetDeviceSidechainTapPre(track, di, i == 0), out _);
- var listen = Toggle(ScListen, "Listen"); DockPanel.SetDock(listen, Dock.Right);
- var topRow = new DockPanel { LastChildFill = false, Children = { new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { combo, preBox } }, listen } };
- // HP and LP side by side (2 columns) so the sliders line up on the grid.
- var filters = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 10 };
- var hp = HSlider(ScHP, "HP", Hz, true, Teal, 68, lw: 16);
- var lp = HSlider(ScLP, "LP", Hz, true, Teal, 68, lw: 16);
- Grid.SetColumn(lp, 1); filters.Children.Add(hp); filters.Children.Add(lp);
- return new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 6),
- Child = new StackPanel { Spacing = 5, Children = { Lbl("SIDECHAIN", 8, TextTertiary), topRow, filters } } };
- }
- var timingCol = new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { timing, Sidechain() } };
-
- // ---- output rail ----
- var outRail = new Border { Width = 104, Background = NotaPalette.SurfaceInset, BorderBrush = BorderDef, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(7, 8),
- Child = new StackPanel { Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = {
- Lbl("OUTPUT", 8, TextPrimary), Toggle(AutoGain, "Auto gain"),
- Cell("Makeup", Makeup, Db1, null, 40), Cell("Range", Range, v => v >= 47.5 ? "off" : $"−{v:0}", null, 36) } } };
- DockPanel.SetDock(outRail, Dock.Right);
-
- var content = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 10, Margin = new Thickness(9, 8) };
- content.Children.Add(graphsCol); Grid.SetColumn(timingCol, 1); content.Children.Add(timingCol);
- var body = new DockPanel { LastChildFill = true, Children = { outRail, content } };
-
- ctx.AddDeviceRefresher(() =>
- {
- grHist.Push(engine.DeviceGainReduction(track, di));
- transfer.Tick();
- foreach (var a in readouts) a();
+ MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("40,*"), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label));
+ g.Children.Add(Col(row, 1));
+ return g;
+ }
+
+ // ---- live measurements ------------------------------------------------------------
+ // Peaks held over ~300 ms of UI ticks, for the crest factors.
+ var inPkHist = new double[18]; var outPkHist = new double[18]; int pkW = 0;
+ double inPkHeld = 0, outPkHeld = 0;
+ double KeyDb() => LinDb(Sc(S_KeyPk));
+ double Bpm() => Sc(S_Bpm) > 1 ? Sc(S_Bpm) : 120;
+ double WindowMs()
+ {
+ double want = 4 * (P(Attack) + P(Release) + P(Hold));
+ foreach (double w in Windows) if (w >= want) return w;
+ return Windows[^1];
+ }
+ // Hits: rises of the reduction through 1 dB (re-armed below 0.5 dB) over the last n ms.
+ int Hits(int n)
+ {
+ int hits = 0; bool armed = true;
+ for (int i = Math.Max(0, EnvN - n); i < EnvN; i++)
+ {
+ if (armed && envGr[i] > 1) { hits++; armed = false; }
+ else if (!armed && envGr[i] < 0.5) armed = true;
+ }
+ return hits;
+ }
+ // The last hit in the window (the reduction rising through 1 dB from below 0.5 dB):
+ // onset → its first peak (transient) and that peak → 37 % of it (recovery), in ms;
+ // NaN when there is nothing to measure.
+ (double Transient, double Recovery) Timings(int n)
+ {
+ int start = Math.Max(1, EnvN - n), onset = -1;
+ bool armed = false;
+ for (int i = start; i < EnvN; i++)
+ {
+ if (envGr[i] < 0.5) armed = true;
+ else if (armed && envGr[i] > 1) { onset = i; armed = false; }
+ }
+ if (onset < 0) return (double.NaN, double.NaN);
+ while (onset > start && envGr[onset - 1] >= 0.5) onset--; // back to where it left 0.5 dB
+ int peak = onset;
+ while (peak + 1 < EnvN && envGr[peak + 1] >= envGr[peak]) peak++;
+ if (peak + 1 >= EnvN) return (Math.Max(peak - onset, 0.5), double.NaN); // still attacking
+ double pv = envGr[peak];
+ int k = peak;
+ while (k + 1 < EnvN && envGr[k] > 0.37 * pv && !(envGr[k + 1] > envGr[k] + 0.5)) k++;
+ double recovery = envGr[k] <= 0.37 * pv ? k - peak : double.NaN;
+ return (Math.Max(peak - onset, 0.5), recovery);
+ }
+
+ // ======================================================================
+ // LEFT — LEVEL column (threshold · make-up / key gain)
+ // ======================================================================
+ int centreTab = 0;
+ var thrFader = new CompFader { Ink = NotaPalette.Accent, Handle = NotaPalette.AccentBright, VerticalAlignment = VerticalAlignment.Stretch };
+ var thrMap = Lin(Threshold);
+ thrFader.Default = thrMap.N(Def(Threshold));
+ thrFader.Changed += v => Raw(Threshold, thrMap.V(v));
+ thrFader.GestureBegin += () => Begin(Threshold);
+ thrFader.GestureEnd += () => End(Threshold);
+ MidiLearn.Bind(thrFader, MidiTarget.DeviceParam(track, di, Threshold), "Thresh");
+ ToolTip.SetTip(thrFader, "Threshold — the tick is the key's level right now. Double-click resets.");
+
+ // The second fader is make-up on Curve / Motion and the key's gain on Sidechain.
+ int F2() => centreTab == 2 ? ScGain : Makeup;
+ var f2 = new CompFader { Ink = NotaPalette.Teal, Handle = NotaPalette.TealBright, VerticalAlignment = VerticalAlignment.Stretch };
+ f2.Changed += v => Raw(F2(), Lin(F2()).V(v));
+ f2.GestureBegin += () => Begin(F2());
+ f2.GestureEnd += () => End(F2());
+ MidiLearn.Bind(f2, MidiTarget.DeviceParam(track, di, Makeup), "Makeup");
+
+ var thrLbl = Caps("THR"); thrLbl.HorizontalAlignment = HorizontalAlignment.Center;
+ var f2Lbl = Caps("MKP"); f2Lbl.HorizontalAlignment = HorizontalAlignment.Center;
+ var thrVal = Mono("", 7, AccentBright); thrVal.HorizontalAlignment = HorizontalAlignment.Center;
+ var f2Val = Mono("", 7, TextPrimary); f2Val.HorizontalAlignment = HorizontalAlignment.Center;
+ readouts.Add(() =>
+ {
+ double keyDb = KeyDb();
+ thrFader.Set(thrMap.N(P(Threshold)), keyDb > -60 ? (keyDb + 60) / 60 : double.NaN);
+ int p2 = F2();
+ f2.Default = Lin(p2).N(Def(p2));
+ f2.Set(Lin(p2).N(P(p2)));
+ thrVal.Text = Db(P(Threshold));
+ f2Val.Text = SDb(P(p2));
+ f2Lbl.Text = p2 == ScGain ? "SC IN" : "MKP";
+ ToolTip.SetTip(f2, p2 == ScGain ? "Key gain — drives the detector harder or softer. Double-click resets." : "Make-up gain. Double-click resets.");
});
- foreach (var a in readouts) a();
+ var faders = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 9, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 3) };
+ faders.Children.Add(new DockPanel { Children = { Docked(thrLbl, Dock.Bottom), thrFader } });
+ faders.Children.Add(Col(new DockPanel { Children = { Docked(f2Lbl, Dock.Bottom), f2 } }, 1));
+ var levelTitle = Caps("LEVEL"); levelTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var levelCol = new Border
+ {
+ Width = 56, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(levelTitle, Dock.Top), Docked(f2Val, Dock.Bottom), Docked(thrVal, Dock.Bottom), faders } },
+ };
+ DockPanel.SetDock(levelCol, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — shared pieces
+ // ======================================================================
+ Control CharRow(Func<string> right, Func<IBrush> rightInk)
+ {
+ var info = Mono("", 7, TextTertiary); info.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => { info.Text = right(); info.Foreground = rightInk(); });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 6, Height = 18 };
+ g.Children.Add(Caps("CHAR"));
+ var seg = Seg(Character, Chars);
+ ToolTip.SetTip(seg, "Character — the voicing: Clean as set, Glue slower and softer, Punch faster, Opto slow and program-soft, FET very fast");
+ g.Children.Add(Col(seg, 1));
+ g.Children.Add(Col(info, 2));
+ return g;
+ }
+ // The four timing knobs + two lines of measurements on the right.
+ Control TimingRow(bool motion, Func<string> stat1, Func<string> stat2)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("56,56,56,56,*"), ColumnSpacing = 2, Height = 52 };
+ g.Children.Add(K(Attack, "ATTACK", Ms, Log(Attack), emphasised: motion, cellW: 56));
+ g.Children.Add(Col(K(Release, "RELEASE", Ms, Log(Release), emphasised: motion, cellW: 56), 1));
+ g.Children.Add(Col(K(Knee, "KNEE", Db, Lin(Knee), cellW: 56), 2));
+ g.Children.Add(Col(K(Lookahead, "LOOKAHEAD", v => v < 0.05 ? "off" : Ms(v), Lin(Lookahead), cellW: 56), 3));
+ var s1 = Mono("", 7, TextTertiary); s1.HorizontalAlignment = HorizontalAlignment.Right;
+ var s2 = Mono("", 7, TextTertiary); s2.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => { s1.Text = stat1(); s2.Text = stat2(); });
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { s1, s2 } }, 4));
+ return g;
+ }
+
+ // ======================================================================
+ // CENTRE — Curve
+ // ======================================================================
+ var grHist = new CompGrHistoryView();
+ ToolTip.SetTip(grHist, "Gain reduction over the last four seconds; the dashed line is the peak. Click to clear it.");
+ Control CurveTab()
+ {
+ var transfer = new CompTransferView();
+ ToolTip.SetTip(transfer, "Drag sideways for the threshold, up / down for the ratio. Double-click resets both. The dot is the key level right now.");
+ transfer.GestureBegin += () => { Begin(Threshold); Begin(Ratio); };
+ transfer.GestureEnd += () => { End(Threshold); End(Ratio); };
+ transfer.Changed += (thr, ratio) => { Raw(Threshold, thr); Raw(Ratio, ratio); };
+ transfer.Reset += () => { Reset(Threshold); Reset(Ratio); };
+ MidiLearn.Bind(transfer, MidiTarget.DeviceParam(track, di, Threshold), "Thresh");
+ readouts.Add(() => { if (!transfer.Dragging) transfer.Set(P(Threshold), P(Ratio), P(Knee), P(Range), KeyDb()); });
- DockPanel.SetDock(live, Dock.Top);
- return new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };
+ var graphs = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6, Margin = new Thickness(0, 5, 0, 5) };
+ graphs.Children.Add(transfer);
+ graphs.Children.Add(Col(grHist, 1));
+
+ string Crest(double pk, double rms) => rms > 1e-5 && pk > 1e-5 ? NotaNum.F($"{LinDb(pk) - LinDb(rms):0.0}") : "–";
+ return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 5, 8, 4), Children = {
+ Docked(CharRow(() => NotaNum.F($"in {Lvl(LinDb(Sc(S_InRms)))} · out {Lvl(LinDb(Sc(S_OutRms)))} dB"), () => TextTertiary), Dock.Top),
+ Docked(TimingRow(false,
+ () => NotaNum.F($"GR avg {Gr(grHist.Average)} · peak {Gr(grHist.Peak)} dB"),
+ () => NotaNum.F($"crest {Crest(inPkHeld, Sc(S_InRms))} → {Crest(outPkHeld, Sc(S_OutRms))} dB")), Dock.Bottom),
+ graphs } };
+ }
+
+ // ======================================================================
+ // CENTRE — Motion
+ // ======================================================================
+ Control MotionTab()
+ {
+ var motion = new CompMotionView();
+ ToolTip.SetTip(motion, "The reduction (brass, hanging from 0 dB) against the input level (teal) — attack is the fall, release the climb back. The dashed line is the threshold.");
+ readouts.Add(() => motion.Set(envIn, envGr, scN >= kScope + 2 * EnvN ? EnvN : 0, P(Threshold), WindowMs()));
+ string Measured()
+ {
+ var (tr, rec) = Timings((int)WindowMs());
+ if (double.IsNaN(tr)) return "no reduction to measure";
+ return NotaNum.F($"transient {Ms(tr)} · recovery {(double.IsNaN(rec) ? "–" : Ms(rec))}");
+ }
+ return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 5, 8, 4), Children = {
+ Docked(CharRow(() => NotaNum.F($"attack {Ms(Sc(S_AtkMs))} · release {Ms(Sc(S_RelMs))}"), () => AccentBright), Dock.Top),
+ Docked(TimingRow(true,
+ () => NotaNum.F($"GR peak {Gr(grHist.Peak)} dB · {Hits((int)WindowMs())} hits / window"),
+ Measured), Dock.Bottom),
+ new Border { Margin = new Thickness(0, 5, 0, 5), Child = motion } } };
+ }
+
+ // ======================================================================
+ // CENTRE — Sidechain
+ // ======================================================================
+ var srcIds = new List<int> { -1 };
+ var srcNames = new List<string> { "Internal" };
+ for (int i = 0; i < engine.TrackCount; i++)
+ {
+ if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;
+ srcIds.Add(ti.Id);
+ srcNames.Add(NotaNum.F($"{i + 1} · {(ti.IsReturn ? "Return" : ti.IsInstrument ? "Instr" : "Audio")}"));
+ }
+ string SourceName() { int k = srcIds.IndexOf(engine.DeviceSidechainSource(track, di)); return k > 0 ? srcNames[k] : "Internal"; }
+ bool ExtActive() => Sc(S_ExtKey) > 0.5;
+
+ Control SidechainTab()
+ {
+ var combo = new ComboBox { FontSize = 8, Height = 18, MinHeight = 18, MinWidth = 92, Padding = new Thickness(6, 0), VerticalAlignment = VerticalAlignment.Center };
+ foreach (var n in srcNames) combo.Items.Add(n);
+ combo.SelectedIndex = Math.Max(0, srcIds.IndexOf(engine.DeviceSidechainSource(track, di)));
+ bool syncing = false;
+ // The source can change elsewhere (MCP, undo): follow it while the list is closed.
+ readouts.Add(() =>
+ {
+ if (combo.IsDropDownOpen) return;
+ int want = Math.Max(0, srcIds.IndexOf(engine.DeviceSidechainSource(track, di)));
+ if (combo.SelectedIndex != want) { syncing = true; combo.SelectedIndex = want; syncing = false; }
+ });
+ combo.SelectionChanged += (_, _) =>
+ {
+ int s = combo.SelectedIndex;
+ if (syncing || s < 0 || s >= srcIds.Count) return;
+ engine.SetDeviceSidechainSource(track, di, srcIds[s]);
+ // Picking a source means using it.
+ if (srcIds[s] >= 0 && !On(External)) SetP(External, 1);
+ ctx.NotifyChanged();
+ };
+ ToolTip.SetTip(combo, "Key source — Internal keys off this track; pick another track to duck or pump against it");
+ var tap = Segments(new[] { "Pre", "Post" }, () => engine.DeviceSidechainTapPre(track, di) ? 0 : 1,
+ i => { engine.SetDeviceSidechainTapPre(track, di, i == 0); ctx.NotifyChanged(); }, out var tapSync);
+ readouts.Add(tapSync);
+ ToolTip.SetTip(tap, "Where the source track is tapped: before its effects and fader, or after");
+ var info = Mono("", 7, TextTertiary); info.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => info.Text = NotaNum.F($"HP {HpF(P(ScHP))} · LP {LpF(P(ScLP))} · Q {P(ScQ):0.0}"));
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*"), ColumnSpacing = 6, Height = 18 };
+ head.Children.Add(Caps("KEY"));
+ head.Children.Add(Col(combo, 1));
+ head.Children.Add(Col(tap, 2));
+ head.Children.Add(Col(info, 3));
+
+ var key = new CompKeyView();
+ ToolTip.SetTip(key, "The key's spectrum under its filters — drag a handle sideways to move HP / LP, up / down for Q. Double-click a handle to open it.");
+ int KParam(int h) => h == 0 ? ScHP : h == 1 ? ScLP : ScQ;
+ key.GestureBegin += h => Begin(KParam(h));
+ key.GestureEnd += h => End(KParam(h));
+ key.FreqChanged += (h, hz) => Raw(h == 0 ? ScHP : ScLP, hz);
+ key.QChanged += q => Raw(ScQ, q);
+ key.Reset += h => Reset(h == 0 ? ScHP : ScLP);
+ MidiLearn.Bind(key, MidiTarget.DeviceParam(track, di, ScHP), "SC HP");
+ readouts.Add(() =>
+ {
+ if (!key.Dragging) key.SetFilter(P(ScHP), P(ScLP), P(ScQ), On(ScListen));
+ if (scN >= ScopeLen) key.SetKey(scope, kScope + 2 * EnvN, KeyN, Sc(S_SampleRate));
+ });
+
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("46,46,46,46,46,*"), ColumnSpacing = 3, Height = 52 };
+ g.Children.Add(K(ScHP, "HP", HpF, Log(ScHP), emphasised: true, cellW: 46));
+ g.Children.Add(Col(K(ScLP, "LP", LpF, Log(ScLP), emphasised: true, cellW: 46), 1));
+ g.Children.Add(Col(K(ScQ, "Q", v => NotaNum.F($"{v:0.00}"), Log(ScQ), cellW: 46), 2));
+ g.Children.Add(Col(K(ScGain, "SC GAIN", SDb, Lin(ScGain), Teal, cellW: 46), 3));
+ g.Children.Add(Col(K(Hold, "HOLD", v => v < 0.5 ? "off" : Ms(v), Sq(Hold), Teal, cellW: 46), 4));
+ var s1 = Mono("", 7, TextTertiary); s1.HorizontalAlignment = HorizontalAlignment.Right;
+ var s2 = Mono("", 7, TextTertiary); s2.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() =>
+ {
+ double kdb = KeyDb();
+ s1.Text = kdb <= -99 ? "key silent" : key.PeakHz > 0 ? NotaNum.F($"key {Lvl(kdb)} dB · peak {Hz(key.PeakHz)}") : NotaNum.F($"key {Lvl(kdb)} dB");
+ double barMs = 4 * 60000.0 / Bpm();
+ s2.Text = NotaNum.F($"{Hits(EnvN) * barMs / EnvN:0.#} triggers / bar");
+ });
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { s1, s2 } }, 5));
+
+ return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 5, 8, 4), Children = {
+ Docked(head, Dock.Top), Docked(g, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 5), Child = key } } };
+ }
+
+ // ======================================================================
+ // RIGHT — Dynamics / Output
+ // ======================================================================
+ Border GrBox(bool levels)
+ {
+ var title = Caps(levels ? "OUTPUT" : "REDUCTION");
+ var stack = new StackPanel { Spacing = 2, Children = { title } };
+ var box = new Border { Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(NotaRadius.ControlValue), Padding = new Thickness(6, 4), Child = stack };
+ if (levels)
+ {
+ Control Line(string name, Func<string> v, Func<IBrush> ink)
+ {
+ var val = Mono("", 8, TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => { val.Text = v(); val.Foreground = ink(); });
+ var gg = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ gg.Children.Add(new TextBlock { Text = name, FontSize = 8, Foreground = TextSecondary });
+ gg.Children.Add(Col(val, 1));
+ return gg;
+ }
+ stack.Children.Add(Line("in", () => NotaNum.F($"{Lvl(LinDb(Sc(S_InRms)))} dB"), () => TextPrimary));
+ stack.Children.Add(Line("out", () => NotaNum.F($"{Lvl(LinDb(Sc(S_OutRms)))} dB"), () => Sc(S_OutPk) > 0.5 ? NotaPalette.Warning : TextPrimary));
+ stack.Children.Add(Line("GR", () => NotaNum.F($"{Gr(Sc(S_Gr))} dB"), () => AccentBright));
+ }
+ else
+ {
+ var now = Mono("", 9, AccentBright);
+ var set = Mono("", 8, TextSecondary);
+ stack.Children.Add(now); stack.Children.Add(set);
+ readouts.Add(() =>
+ {
+ now.Text = NotaNum.F($"{Gr(Sc(S_Gr))} dB · peak {Gr(grHist.Peak)}");
+ set.Text = NotaNum.F($"thresh {P(Threshold):0.0} · {RatioF(P(Ratio))} · knee {P(Knee):0.#}");
+ bool hot = grHist.Peak >= 10;
+ box.BorderBrush = hot ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
+ title.Foreground = hot ? AccentBright : TextTertiary;
+ });
+ }
+ return box;
+ }
+
+ Control DynamicsTab()
+ {
+ var det = new Grid { ColumnDefinitions = new ColumnDefinitions("40,*"), VerticalAlignment = VerticalAlignment.Center };
+ det.Children.Add(Caps("DETECT"));
+ var detSeg = Seg(Detection, Detects);
+ ToolTip.SetTip(detSeg, "Detector — Peak reacts to every transient, RMS to the body, Auto follows the body and still catches the spikes");
+ det.Children.Add(Col(detSeg, 1));
+ var rows = new Control[]
+ {
+ det,
+ SliderRow("RATIO", Ratio, RatioF, Log(Ratio)),
+ SliderRow("MIX", Mix, PctF, Lin(Mix)),
+ Rule(),
+ SliderRow("RANGE", Range, RangeF, RangeMap(), teal: true),
+ GrBox(false),
+ new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {
+ Toggle(AutoRelease, "Auto-release", "Auto-release — a slower second release once the reduction runs deep, so sustained material does not pump"),
+ Toggle(AutoGain, "Auto gain", "Auto gain — make-up that follows the threshold and ratio") } },
+ };
+ var grid = new Grid { RowDefinitions = new RowDefinitions("*,*,*,Auto,*,Auto,*"), RowSpacing = 2 };
+ for (int r = 0; r < rows.Length; r++) grid.Children.Add(GRow(rows[r], r));
+ return new Border { Padding = new Thickness(8, 5), Child = grid };
+ }
+
+ Control OutputTab()
+ {
+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ var listen = Latch(ScListen, "Listen", "Listen — hear the filtered key instead of the output, to set HP / LP by ear");
+ var autoGain = Latch(AutoGain, "Auto gain", "Auto gain — make-up that follows the threshold and ratio");
+ listen.HorizontalAlignment = HorizontalAlignment.Stretch; autoGain.HorizontalAlignment = HorizontalAlignment.Stretch;
+ btns.Children.Add(listen); btns.Children.Add(Col(autoGain, 1));
+ var rows = new Control[]
+ {
+ GrBox(true),
+ SliderRow("MAKEUP", Makeup, v => NotaNum.F($"{v:+0.0;−0.0;0.0}"), Lin(Makeup)),
+ SliderRow("MIX", Mix, PctF, Lin(Mix)),
+ SliderRow("RANGE", Range, RangeF, RangeMap(), teal: true),
+ new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 4, 0, 0), Child = btns },
+ new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {
+ Toggle(External, "External key", "External key — key off the source picked on the Sidechain tab; off, the track keys itself"),
+ Toggle(StereoLink, "Stereo link", "Stereo link — one reduction for both channels; off, left and right compress on their own") } },
+ };
+ var grid = new Grid { RowDefinitions = new RowDefinitions("Auto,*,*,*,Auto,*"), RowSpacing = 3 };
+ for (int r = 0; r < rows.Length; r++) grid.Children.Add(GRow(rows[r], r));
+ return new Border { Padding = new Thickness(8, 5), Child = grid };
+ }
+
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[3];
+ var rightBodies = new Control?[2];
+ var extras = Mono("", 7, TextTertiary);
+ readouts.Add(() =>
+ {
+ switch (centreTab)
+ {
+ case 1:
+ extras.Text = NotaNum.F($"window {Ms(WindowMs())} · {RatioF(P(Ratio))} · knee {P(Knee):0.0}");
+ extras.Foreground = TextTertiary; break;
+ case 2:
+ extras.Text = On(ScListen) ? "key audible · output muted" : ExtActive() ? NotaNum.F($"external key · {SourceName()}") : "internal key";
+ extras.Foreground = On(ScListen) ? AccentBright : TextTertiary; break;
+ default:
+ extras.Text = NotaNum.F($"{RatioF(P(Ratio))} · knee {P(Knee):0.0} dB · {Detects[Sel(Detection, 3)].ToLowerInvariant()}");
+ extras.Foreground = TextTertiary; break;
+ }
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => MotionTab(), 2 => SidechainTab(), _ => CurveTab() };
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? OutputTab() : DynamicsTab();
+
+ var centre = TabFrame(new[] { "Curve", "Motion", "Sidechain" }, centreHost, CentreBody, false, t => { centreTab = t; Refresh(); }, extras);
+ var rightFrame = TabFrame(new[] { "Dynamics", "Output" }, rightHost, RightBody, true, _ => Refresh(), null);
+ var right = new Border { Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Card2, BorderBrush = BorderDef, 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 = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ if (On(ScListen))
+ return NotaNum.F($"Listen: only the key is heard · {SourceName()} {(engine.DeviceSidechainTapPre(track, di) ? "pre" : "post")} · HP {HpF(P(ScHP))} · LP {LpF(P(ScLP))}");
+ string range = P(Range) >= 47.5 ? "" : NotaNum.F($" · range {RangeF(P(Range))}");
+ string ext = ExtActive() ? NotaNum.F($" · key {SourceName()}") : "";
+ return NotaNum.F($"{Chars[Sel(Character, 5)]} · thresh {Db(P(Threshold))} · {RatioF(P(Ratio))} · knee {P(Knee):0.0} · {MsShort(P(Attack))} / {MsShort(P(Release))} ms · mix {PctF(P(Mix))}{range}{ext}");
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ statusLeft.Foreground = On(ScListen) ? AccentBright : TextSecondary;
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · latency {Sc(S_Latency):0} smp · CPU {Sc(S_Cpu) * 100:0.0} %") : "";
+ });
+ 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 = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { levelCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, ScopeLen);
+ if (scN >= kScope + 2 * EnvN)
+ {
+ Array.Copy(scope, kScope, envIn, 0, EnvN);
+ Array.Copy(scope, kScope + EnvN, envGr, 0, EnvN);
+ }
+ inPkHist[pkW] = Sc(S_InPk); outPkHist[pkW] = Sc(S_OutPk); pkW = (pkW + 1) % inPkHist.Length;
+ inPkHeld = 0; outPkHeld = 0;
+ for (int i = 0; i < inPkHist.Length; i++) { inPkHeld = Math.Max(inPkHeld, inPkHist[i]); outPkHeld = Math.Max(outPkHeld, outPkHist[i]); }
+ foreach (var a in readouts) a();
+ }
+ void Tick() { grHist.Push(Sc(S_Gr)); }
+ ctx.AddDeviceRefresher(() => { Refresh(); Tick(); });
+ Refresh();
+ return root;
+
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = 0;
+ var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? Card2 : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AccentBright : TextTertiary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.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 = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ 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 = BorderDef, 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 } };
+ }
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/ReverbDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/ReverbDeviceBody.cs
index cd2d9e88..fbe696d9 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/ReverbDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/ReverbDeviceBody.cs
@@ -1,15 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Reverb body (kind 2), mockup 2h on the shared shell
-// (700×260): a LIVE strip (Decay · HF Damp · Freeze · Algorithm · Mix) over a body of
-// the decay-tail GRAPH (flex) | two honest bands SPACE (pre-delay/size/diffusion) and
-// TONE (low cut/high cut/width) + MOD | an OUTPUT rail (dry/wet · out). All controls are
-// generic device params on the shared gauge Knob.
+// Detail · Devices — built-in Reverb body (device kind 2), a build of the "Nota Reverb"
+// mockup (700 × 260) on the Chamber / Delay frame: an always-visible TAIL column (Decay ·
+// HF Damp), a centre tabbed panel (Space / Tone · Mod) over the live decay-tail window, a
+// right tabbed panel (Levels / Output) and a status strip. The tail window is a control,
+// not decoration (drag the pre-delay marker, drag the tail for the decay). Every control is
+// a device param, so automation / MIDI learn / presets / A-B / persistence come for free;
+// Kill tail is the one action that is not (it empties the reverb's buffers).
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
+using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -20,315 +25,469 @@ namespace Nota.App;
internal sealed class ReverbDeviceBody : IDeviceBody
{
- // ── Parameter indices (must match engine layout) ─────────────────────────
- private const int Decay = 0;
- private const int HFDamp = 1;
- private const int PreDelay = 2;
- private const int Size = 3;
- private const int Diffusion = 4;
- private const int LowCut = 5;
- private const int HighCut = 6;
- private const int StereoWidth = 7;
- private const int ModRate = 8;
- private const int ModDepth = 9;
- private const int Algorithm = 10;
- private const int Freeze = 11;
- private const int DryWet = 12;
- private const int Output = 13;
-
- // ── Display ranges ───────────────────────────────────────────────────────
- private const double DecayMinSec = 0.2, DecayMaxSec = 12.0;
- private const double FreqMinHz = 20, FreqMaxHz = 20000;
- private const double RateMinHz = 0.05, RateMaxHz = 5.0;
- private const double PreDelayMaxMs = 200;
-
- // ── Device-local palette ─────────────────────────────────────────────────
- private static readonly IBrush LiveStripBg = NotaPalette.SurfaceCard;
- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
- private static readonly IBrush SliderHandleBg = NotaPalette.TextSecondary;
+ // ── Parameter indices (must match Reverb.h) ──────────────────────────────
+ private const int Decay = 0, HFDamp = 1, PreDelay = 2, Size = 3, Diffusion = 4, LowCut = 5, HighCut = 6,
+ WidthP = 7, ModRate = 8, ModDepth = 9, Algorithm = 10, Freeze = 11, DryWet = 12, Output = 13,
+ DryLevel = 14, EarlyRefl = 15, ModOnTail = 16, Vintage = 17, BassMono = 18, WetOnly = 19, LatencyComp = 20;
+ // Scope telemetry layout (Reverb::S_*).
+ private const int S_WetPk = 0, S_OutL = 1, S_OutR = 2, S_Cpu = 3, S_SampleRate = 4, S_Latency = 5,
+ S_DiffuseSmp = 8, kScope = 11; // 6 RT60 · 7 effective pre-delay ms · 9 frozen · 10 early on
+ private const int A_KillTail = 0;
+
+ private static readonly string[] Algos = { "Hall", "Room", "Plate", "Chamber" };
+ // The early-reflection pattern — mirrors Reverb.h (kErMs · kErGain · kErScale).
+ private static readonly double[] ErMs = { 7.3, 11.9, 16.1, 23.4, 29.7, 37.9, 47.3, 61.1 };
+ private static readonly float[] ErGain = { 1.0f, 0.78f, 0.86f, 0.62f, 0.66f, 0.5f, 0.42f, 0.34f };
+ private static readonly double[] ErScale = { 1.0, 0.45, 0.28, 0.7 };
+ private const double LoopSec = 3.4; // one flash-and-fade of the tail window
public double Width => 700;
-
- public string? Subtitle => "REVERB"; // the processing type, shown as the header badge
public bool FullBleed => true;
+ public string? Subtitle => "REVERB";
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 SetP(int p, float v) => engine.DeviceSetParam(track, di, p, v);
- void BeginWrite(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- void EndWrite(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, 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));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); 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);
+
+ var readouts = new List<Action>();
+ var scope = new float[kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+
+ // ---- formatters -------------------------------------------------------------
static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
-
- // ── Tail visualization ───────────────────────────────────────────────
- var tail = new ReverbTail(engine, track, di, Decay, PreDelay, v => Exp(v, DecayMinSec, DecayMaxSec))
+ static string Pct(double v) => NotaNum.F($"{v * 100:0} %");
+ static string Hz(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0} kHz") : NotaNum.F($"{hz:0} Hz");
+ static string ShortDb(double db) => db <= -99 ? "−∞" : NotaNum.F($"{db:0.0;−0.0;0.0}");
+ static string Db(double db) => db <= -99 ? "−∞" : NotaNum.F($"{db:+0.0;−0.0;0.0} dB");
+ static double OutDb(double v) => v <= 0.0005 ? -100 : 20 * Math.Log10(v * 2);
+ static double DryDb(double v) { double g = 2 * v * v; return g <= 1e-5 ? -100 : 20 * Math.Log10(g); }
+ static double Rt60(double v) => Exp(v, 0.2, 12);
+ static string Secs(double s) => s >= 10 ? NotaNum.F($"{s:0.0} s") : NotaNum.F($"{s:0.00} s");
+ static double LowHz(double v) => Exp(v, 20, 1000);
+ static double HighHz(double v) => Exp(v, 1000, 20000);
+ static string RateF(double v) { double hz = Exp(v, 0.05, 5); return hz >= 1 ? NotaNum.F($"{hz:0.0} Hz") : NotaNum.F($"{hz:0.00} Hz"); }
+ static string PreF(double v) => NotaNum.F($"{v * 200:0} ms");
+ string DecayF(double v) => On(Freeze) ? "HOLD" : Secs(Rt60(v));
+ string Algo() => Algos[Sel(Algorithm, 4)];
+
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, 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 StackPanel Row(double sp, params Control[] cs)
+ { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+ static Border Divider(Control child, double top = 5) => new()
+ { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, top, 0, 0), Child = child };
+
+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
+ Control K(int p, string name, Func<double, string> fmt, double size = 34, double cellW = 50, IBrush? arc = null)
{
- VerticalAlignment = VerticalAlignment.Stretch,
- };
- ctx.AddDeviceRefresher(tail.Tick);
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = engine.DeviceParamDefault(track, di, p), Width = size, Height = size };
+ knob.ValueChanged += v => { Raw(p, (float)v); val.Text = fmt(v); SyncTail(); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ readouts.Add(() => { if (knob.Dragging) 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);
+ }
- // ── Value formatters ─────────────────────────────────────────────────
- string Sec(double v) => $"{Exp(v, DecayMinSec, DecayMaxSec):0.00}\u2009s";
- string Pct(double v) => $"{v * 100:0}\u2009%";
- string Hz(double v)
+ // On/off switch bound to a param (> 0.5 = on).
+ Control Toggle(int p, string label)
{
- double f = Exp(v, FreqMinHz, FreqMaxHz);
- return f >= 1000 ? $"{f / 1000:0.0}k" : $"{f:0}";
+ var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); SyncTail(); }, out var sync);
+ readouts.Add(sync);
+ MidiLearn.Bind(wrap, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return wrap;
}
- string PreMs(double v) => $"{v * PreDelayMaxMs:0}\u2009ms";
- string RateF(double v) => $"{Exp(v, RateMinHz, RateMaxHz):0.00}\u2009Hz";
- string DbF(double v) => v <= 0.001 ? "−∞" : $"{20 * Math.Log10(v * 2):+0.0;−0.0;0.0}";
-
- // ── Widget factories ─────────────────────────────────────────────────
- Control Cell(string name, int p, Func<double, string> fmt, IBrush? arc = null, double size = 34)
+ // Segmented chips over a discrete param (n options spread over 0..1).
+ Control Seg(int p, string[] names)
{
- var val = new TextBlock { Text = fmt(P(p)), FontSize = 8, Foreground = TextPrimary };
- val.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
-
- var knob = new Knob(P(p), 1.0)
- {
- Accent = true,
- ArcColor = arc,
- Default = engine.DeviceParamDefault(track, di, p),
- Width = size,
- Height = size,
- };
- knob.ValueChanged += v =>
- {
- SetP(p, (float)v);
- val.Text = fmt(v);
- tail.Tick();
- };
- knob.GestureBegin += () => BeginWrite(p);
- knob.GestureEnd += () => EndWrite(p);
-
- MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, p), name);
+ int n = names.Length;
+ var seg = DeviceCardKit.Segments(names, () => Sel(p, n), iv => { SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); SyncTail(); }, out var sync, padX: 8);
+ readouts.Add(sync);
+ MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return seg;
+ }
- ctx.AddDeviceRefresher(() =>
- {
- if (knob.Dragging) return;
- float c = P(p);
- if (Math.Abs(c - knob.Value) > 1e-3)
- {
- knob.Value = c;
- val.Text = fmt(c);
- }
- });
+ // A small text button (an action, or a latch drawn as a button).
+ Border Btn(string text, Action click, string? tip = null)
+ {
+ var tb = new TextBlock { Text = text, FontSize = 8, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Badge, Background = Raised, BorderThickness = new Thickness(1), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); e.Handled = true; };
+ if (tip != null) ToolTip.SetTip(b, tip);
+ return b;
+ }
- return KnobCell(name, knob, val, size + 16);
+ // Horizontal bar slider over a param, with a caps label.
+ Control SliderRow(string label, int p, Func<double, string> fmt, Func<bool>? dim = null, Func<bool>? hot = null)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => P(p), v => { Raw(p, (float)v); SyncTail(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), dim: dim, valueWidth: 34);
+ readouts.Add(sync);
+ MidiLearn.Bind(bar, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("44,*"), VerticalAlignment = VerticalAlignment.Center };
+ var lb = Caps(label);
+ if (hot is not null) readouts.Add(() => lb.Foreground = hot() ? AccentBright : TextTertiary);
+ g.Children.Add(lb);
+ g.Children.Add(Col(bar, 1));
+ return g;
}
- Control Row(params Control[] cs)
+ // ======================================================================
+ // The decay-tail window — shared by both centre tabs
+ // ======================================================================
+ // One view per centre tab — a control has one parent, and both tabs show the window.
+ var tails = new List<ReverbTailView>();
+ var start = DateTime.UtcNow;
+ ReverbTailView NewTail()
+ {
+ var t = new ReverbTailView { DecayValue = () => P(Decay) };
+ t.Changed += (target, v) => { Raw(target == 0 ? Decay : PreDelay, (float)v); SyncTail(); };
+ t.GestureBegin += target => Begin(target == 0 ? Decay : PreDelay);
+ t.GestureEnd += target => End(target == 0 ? Decay : PreDelay);
+ t.Reset += target => { Reset(target == 0 ? Decay : PreDelay); SyncTail(); };
+ ToolTip.SetTip(t, "The decay tail — the impulse at the pre-delay (teal), the early reflections (drawn magnified), then the RT60 curve over 4 s. Drag the teal marker for the pre-delay, drag the tail for the decay; double-click to reset.");
+ MidiLearn.Bind(t, MidiTarget.DeviceParam(track, di, Decay), "Decay");
+ tails.Add(t);
+ return t;
+ }
+ double[] erBuf = new double[ErMs.Length];
+ void SyncTail()
+ {
+ if (tails.Count == 0) return;
+ bool freeze = On(Freeze);
+ // Frozen, the reflections stay drawn (held, as the mockup shows) even though the
+ // muted input feeds them nothing new.
+ bool early = On(EarlyRefl);
+ double scale = ErScale[Sel(Algorithm, 4)] * (0.5 + P(Size) * 0.8);
+ for (int k = 0; k < ErMs.Length; k++) erBuf[k] = ErMs[k] * scale;
+ double[] er = early ? erBuf : Array.Empty<double>();
+ foreach (var t in tails) t.Set(freeze ? -1 : Rt60(P(Decay)), freeze, P(PreDelay), P(PreDelay) * 200, er, ErGain);
+ }
+ readouts.Add(() =>
{
- var sp = new StackPanel
+ SyncTail();
+ // The window loops only while the reverb is actually making sound (or is held).
+ bool sounding = Sc(S_WetPk) > 2e-4 || On(Freeze);
+ double ph = sounding ? (DateTime.UtcNow - start).TotalSeconds % LoopSec / LoopSec : -1;
+ foreach (var t in tails) t.SetPhase(ph);
+ });
+
+ // ======================================================================
+ // LEFT — TAIL column (Decay · HF Damp)
+ // ======================================================================
+ Control TailFader(int p, string label, IBrush ink, IBrush handle, string tip)
+ {
+ var f = new DelayFader { Ink = ink, Handle = handle, Width = 16, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Center, Default = engine.DeviceParamDefault(track, di, p) };
+ f.Changed += v => { Raw(p, (float)v); SyncTail(); };
+ f.GestureBegin += () => Begin(p);
+ f.GestureEnd += () => End(p);
+ MidiLearn.Bind(f, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ ToolTip.SetTip(f, tip);
+ var lb = Caps(label); lb.HorizontalAlignment = HorizontalAlignment.Center; lb.Margin = new Thickness(0, 3, 0, 0);
+ readouts.Add(() =>
{
- Orientation = Orientation.Horizontal,
- Spacing = 2,
- HorizontalAlignment = HorizontalAlignment.Center,
- };
- foreach (var c in cs) sp.Children.Add(c);
- return sp;
+ bool hold = On(Freeze) && p == Decay;
+ f.Set(hold ? 1 : P(p));
+ lb.Foreground = hold ? AccentBright : TextTertiary;
+ });
+ return new DockPanel { Width = 29, Children = { Docked(lb, Dock.Bottom), f } };
}
-
- TextBlock BandHeader(string title) => new()
+ var tailTitle = Caps("TAIL"); tailTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var faders = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 1, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 3) };
+ faders.Children.Add(TailFader(Decay, "DECAY", NotaPalette.Accent, NotaPalette.AccentBright,
+ "Decay — RT60, the time the tail takes to fall 60 dB (0.2 … 12 s); Freeze holds it forever. Double-click resets."));
+ faders.Children.Add(Col(TailFader(HFDamp, "DAMP", NotaPalette.Teal, NotaPalette.TealBright,
+ "HF Damp — how much faster the highs die than the lows. Double-click resets."), 1));
+ var decVal = Mono("", 7, AccentBright); decVal.HorizontalAlignment = HorizontalAlignment.Center;
+ var dmpVal = Mono("", 7, TextPrimary); dmpVal.HorizontalAlignment = HorizontalAlignment.Center;
+ readouts.Add(() =>
{
- Text = title,
- FontSize = 8,
- FontWeight = FontWeight.Bold,
- Foreground = TextTertiary,
- Margin = new Thickness(0, 0, 0, 3),
- };
-
- Control Band(string title, params Control[] knobs) => new Border
+ decVal.Text = DecayF(P(Decay));
+ dmpVal.Text = Pct(P(HFDamp));
+ tailTitle.Foreground = On(Freeze) ? AccentBright : TextTertiary;
+ });
+ var tailCol = new Border
{
- Background = Card2,
- BorderBrush = BorderDef,
- BorderThickness = new Thickness(1),
- CornerRadius = NotaRadius.Panel,
- Padding = new Thickness(7, 5),
- Child = new StackPanel { Children = { BandHeader(title), Row(knobs) } },
+ Width = 64, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(tailTitle, Dock.Top), Docked(dmpVal, Dock.Bottom), Docked(decVal, Dock.Bottom), faders } },
};
+ readouts.Add(() => tailCol.BorderBrush = On(Freeze) ? NotaPalette.BorderBrass : BorderDef);
+ DockPanel.SetDock(tailCol, Dock.Left);
- // Vertical band (knobs stacked) — used for MOD so it sits as a slim island
- // to the right of the graph instead of a third row that overruns the card.
- Control VBand(string title, params Control[] knobs)
+ // ======================================================================
+ // CENTRE — the mode row, shared by both tabs
+ // ======================================================================
+ Control ModeRow()
{
- var col = new StackPanel
- {
- Spacing = 6,
- HorizontalAlignment = HorizontalAlignment.Center,
- VerticalAlignment = VerticalAlignment.Center,
- };
-
- foreach (var k in knobs) col.Children.Add(k);
-
- var header = BandHeader(title);
- var child = col;
- var grid = new Grid()
- {
- RowDefinitions = new RowDefinitions("Auto, *"),
- RowSpacing = 6,
- Children = { header, child }
- };
-
- Grid.SetRow(header, 0);
- Grid.SetRow(child, 1);
+ var hint = Mono("", 7, TextTertiary); hint.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => hint.Text = Sel(Algorithm, 4) == 2
+ ? NotaNum.F($"maximum density · size {Pct(P(Size))}")
+ : NotaNum.F($"size {Pct(P(Size))} · diffuse {Pct(P(Diffusion))}"));
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 6, Height = 18 };
+ head.Children.Add(Caps("MODE"));
+ var seg = Seg(Algorithm, Algos);
+ ToolTip.SetTip(seg, "Algorithm — Hall (large, spaced reflections) · Room (small, close walls) · Plate (dense, no room at all) · Chamber (between)");
+ head.Children.Add(Col(seg, 1));
+ head.Children.Add(Col(hint, 2));
+ return head;
+ }
- return new Border
- {
- Background = Card2,
- BorderBrush = BorderDef,
- BorderThickness = new Thickness(1),
- CornerRadius = NotaRadius.Panel,
- Padding = new Thickness(7, 5),
- VerticalAlignment = VerticalAlignment.Stretch,
- Child = grid,
- };
+ Control CentreTab(Control knobs)
+ {
+ var bottom = new Border { Height = 54, Margin = new Thickness(0, 4, 0, 0), Child = knobs };
+ return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 5, 8, 3), Children = {
+ Docked(ModeRow(), Dock.Top),
+ Docked(bottom, Dock.Bottom),
+ new Border { Margin = new Thickness(0, 5, 0, 0), Child = NewTail() } } };
}
- // Compact horizontal slider for the LIVE strip.
- Control Slider(int p, string name, Func<double, string> fmt, double w)
+ Control SpaceTab()
{
- var row = DeviceCardKit.SliderRow(name, () => P(p), n => { SetP(p, (float)n); tail.Tick(); }, () => fmt(P(p)), out var sync,
- begin: () => BeginWrite(p), end: () => EndWrite(p), trackWidth: w, valueWidth: 46);
- ctx.AddDeviceRefresher(sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), name);
- return row;
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto,*,Auto") };
+ g.Children.Add(K(PreDelay, "PRE", PreF));
+ g.Children.Add(Col(K(Size, "SIZE", Pct), 1));
+ g.Children.Add(Col(K(Diffusion, "DIFFUSE", Pct), 2));
+ g.Children.Add(Col(K(Decay, "DECAY", DecayF), 3));
+ var er = Toggle(EarlyRefl, "Early reflections");
+ ToolTip.SetTip(er, "Early reflections — the first discrete echoes off the walls, spaced by the algorithm and the size");
+ var fr = Toggle(Freeze, "Freeze");
+ ToolTip.SetTip(fr, "Freeze — hold the tail forever; the input is muted and nothing decays");
+ g.Children.Add(Col(new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { er, fr } }, 5));
+ return CentreTab(g);
}
- // Discrete selector rendered as a chip row (Algorithm).
- Control Chips(int p, string[] names)
+ Control ToneTab()
{
- int n = names.Length;
- var host = DeviceCardKit.Segments(names, () => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1), iv => { BeginWrite(p); SetP(p, iv / (float)(n - 1)); EndWrite(p); }, out var sync);
- ctx.AddDeviceRefresher(sync);
- MidiLearn.Bind(host, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
- return host;
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto,Auto,*,Auto") };
+ g.Children.Add(K(LowCut, "LOW CUT", v => Hz(LowHz(v)), arc: Teal));
+ g.Children.Add(Col(K(HighCut, "HIGH CUT", v => Hz(HighHz(v)), arc: Teal), 1));
+ g.Children.Add(Col(K(WidthP, "WIDTH", Pct), 2));
+ g.Children.Add(Col(K(ModRate, "MOD RATE", RateF, arc: NotaPalette.Rose), 3));
+ g.Children.Add(Col(K(ModDepth, "MOD DEPTH", Pct, arc: NotaPalette.Rose), 4));
+ var mt = Toggle(ModOnTail, "Mod on tail");
+ ToolTip.SetTip(mt, "Mod on tail — the modulation wobbles the tail itself (a chorused, evolving decay); off, it moves only the early part and the tail stays still");
+ var vi = Toggle(Vintage, "Vintage");
+ ToolTip.SetTip(vi, "Vintage — an early-digital colour: a band-limited input, 12-bit wet and a deeper wobble");
+ g.Children.Add(Col(new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { mt, vi } }, 6));
+ return CentreTab(g);
}
- Control Toggle(int p, string label)
+ // ======================================================================
+ // RIGHT — Levels / Output
+ // ======================================================================
+ Control LevelsTab()
{
- var b = new Border
+ var wetBar = new PentadLevelBar { Height = 4, VerticalAlignment = VerticalAlignment.Center };
+ var wetDb = Mono("", 8, TextPrimary); wetDb.Width = 30; wetDb.TextAlignment = TextAlignment.Right;
+ readouts.Add(() =>
{
- CornerRadius = NotaRadius.Control,
- BorderThickness = new Thickness(1),
- Padding = new Thickness(8, 2),
- Cursor = new Cursor(StandardCursorType.Hand),
- VerticalAlignment = VerticalAlignment.Center,
- Child = new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.SemiBold },
- };
+ double pk = Sc(S_WetPk);
+ wetBar.SetLinear(pk);
+ double db = pk > 1e-5 ? 20 * Math.Log10(pk) : -100;
+ wetDb.Text = ShortDb(db);
+ wetDb.Foreground = db > -6 ? NotaPalette.Warning : TextPrimary;
+ });
+ var wet = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ wet.Children.Add(Caps("WET")); wet.Children.Add(Col(wetBar, 1)); wet.Children.Add(Col(wetDb, 2));
- void SyncVisual()
+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ var freezeBtn = Btn("Freeze", () => { SetP(Freeze, On(Freeze) ? 0f : 1f); SyncTail(); }, "Freeze — hold the tail forever; the input is muted and nothing decays");
+ var freezeTxt = (TextBlock)freezeBtn.Child!;
+ readouts.Add(() =>
{
- bool on = P(p) > 0.5f;
- b.Background = on ? AccentSubtleB : Sunken;
- b.BorderBrush = on ? Brass : BorderDef;
- ((TextBlock)b.Child!).Foreground = on ? AccentBright : TextTertiary;
- }
+ bool on = On(Freeze);
+ freezeBtn.Background = on ? NotaPalette.AccentSubtle : Raised;
+ freezeBtn.BorderBrush = on ? NotaPalette.BorderBrass : Brushes.Transparent;
+ freezeTxt.Foreground = on ? NotaPalette.AccentHover : TextPrimary;
+ freezeTxt.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ });
+ MidiLearn.Bind(freezeBtn, MidiTarget.DeviceParam(track, di, Freeze), "Freeze");
+ btns.Children.Add(freezeBtn);
+ btns.Children.Add(Col(Btn("Kill tail", () => engine.DeviceAction(track, di, A_KillTail, 0, 0), "Kill tail — empty the reverb at once; whatever is still ringing (or frozen) stops"), 1));
- b.PointerPressed += (_, _) =>
+ var rows = new Control[]
{
- BeginWrite(p);
- SetP(p, P(p) > 0.5f ? 0f : 1f);
- EndWrite(p);
- SyncVisual();
+ SliderRow("MIX", DryWet, Pct, () => On(WetOnly), () => On(WetOnly)),
+ SliderRow("DRY", DryLevel, v => ShortDb(DryDb(v)), () => On(WetOnly)),
+ SliderRow("OUT", Output, v => ShortDb(OutDb(v))),
+ new Border { Height = 1, Background = NotaPalette.GraphBorder, Margin = new Thickness(0, 2) },
+ SliderRow("DECAY", Decay, DecayF, null, () => On(Freeze)),
+ SliderRow("HF DAMP", HFDamp, Pct),
+ new Border { Height = 1, Background = NotaPalette.GraphBorder, Margin = new Thickness(0, 2) },
+ btns, wet,
};
-
- ctx.AddDeviceRefresher(SyncVisual);
- SyncVisual();
- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), label);
- return b;
+ var grid = new Grid { RowDefinitions = new RowDefinitions("*,*,*,Auto,*,*,Auto,*,*") };
+ for (int r = 0; r < rows.Length; r++) grid.Children.Add(GRow(rows[r], r));
+ return new Border { Padding = new Thickness(8, 4), Child = grid };
}
- // ── Layout ───────────────────────────────────────────────────────────
+ Control OutputTab()
+ {
+ var meterL = new PentadLevelBar { Vertical = true, Width = 11, Height = 56 };
+ var meterR = new PentadLevelBar { Vertical = true, Width = 11, Height = 56 };
+ readouts.Add(() => { meterL.SetLinear(Sc(S_OutL)); meterR.SetLinear(Sc(S_OutR)); });
+ static Control Centre(Control c) { c.HorizontalAlignment = HorizontalAlignment.Center; return c; }
+ var scale = new Grid { RowDefinitions = new RowDefinitions("*,*,*"), Height = 56, Children = { Mono("0", 7, TextDisabled), GRow(Mono("−12", 7, TextDisabled), 1), GRow(Mono("−48", 7, TextDisabled), 2) } };
+ var meters = Row(4,
+ new StackPanel { Spacing = 2, Children = { meterL, Centre(Caps("L")) } },
+ new StackPanel { Spacing = 2, Children = { meterR, Centre(Caps("R")) } },
+ scale);
+ meters.VerticalAlignment = VerticalAlignment.Top;
+ var top = Row(8, K(Output, "OUT", v => Db(OutDb(v)), 40, 54), meters);
+
+ var mid = new StackPanel { Spacing = 6, Children = {
+ SliderRow("MIX", DryWet, Pct, () => On(WetOnly)),
+ SliderRow("WIDTH", WidthP, Pct),
+ SliderRow("MONO f", BassMono, v => v <= 0.001 ? "off" : NotaNum.F($"{Exp(v, 30, 500):0}")) } };
+ ToolTip.SetTip(mid.Children[2], "Bass mono — below this frequency the tail is mono, so a wide reverb does not smear the low end (off at the far left)");
+
+ var wetOnly = Toggle(WetOnly, "Wet only (send)");
+ ToolTip.SetTip(wetOnly, "Wet only — the tail with no dry, for a return / send track");
+ var comp = Toggle(LatencyComp, "Latency comp.");
+ ToolTip.SetTip(comp, "The input diffuser delays the tail by a fixed group delay; on, the pre-delay is shortened by exactly that so the tail starts on the set pre-delay (it cannot go below zero).");
+ var bottom = new StackPanel { Spacing = 5, Children = { wetOnly, comp } };
+
+ var body = new DockPanel { LastChildFill = false, Children = {
+ Docked(top, Dock.Top), Docked(Divider(mid), Dock.Top), Docked(Divider(bottom), Dock.Bottom) } };
+ ((Control)body.Children[1]).Margin = new Thickness(0, 5, 0, 0);
+ return new Border { Padding = new Thickness(8, 5), Child = body };
+ }
- // Top LIVE strip: performance-critical params, always visible.
- var live = new Border
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[2];
+ var rightBodies = new Control?[2];
+ int centreTab = 0;
+ var extras = Mono("", 7, TextTertiary);
+ readouts.Add(() =>
{
- Height = 34,
- Background = LiveStripBg,
- BorderBrush = BorderDef,
- BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new StackPanel
+ if (On(Freeze))
{
- Orientation = Orientation.Horizontal,
- Spacing = 12,
- VerticalAlignment = VerticalAlignment.Center,
- Margin = new Thickness(9, 0),
- Children =
- {
- Slider(Decay, "DECAY", Sec, 80),
- Slider(HFDamp, "HF DAMP", Pct, 56),
- Toggle(Freeze, "Freeze"),
- Chips(Algorithm, new[] { "Hall", "Room", "Plate", "Chamber" }),
- Slider(DryWet, "MIX", Pct, 56),
- },
- },
- };
+ extras.Text = "input muted · tail held";
+ extras.Foreground = AccentBright;
+ return;
+ }
+ extras.Foreground = TextTertiary;
+ extras.Text = centreTab == 0
+ ? NotaNum.F($"RT60 {Secs(Rt60(P(Decay)))} · {P(PreDelay) * 200:0} ms pre")
+ : NotaNum.F($"low cut {Hz(LowHz(P(LowCut)))} · high cut {Hz(HighHz(P(HighCut)))}");
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t == 1 ? ToneTab() : SpaceTab();
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? OutputTab() : LevelsTab();
+
+ var centre = TabFrame(new[] { "Space", "Tone · Mod" }, centreHost, CentreBody, false, t => { centreTab = t; foreach (var a in readouts) a(); }, extras);
+ var rightFrame = TabFrame(new[] { "Levels", "Output" }, rightHost, RightBody, true, _ => { foreach (var a in readouts) a(); }, null);
+ var right = new Border { Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Card2, BorderBrush = BorderDef, 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 = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ if (On(Freeze))
+ return NotaNum.F($"Freeze: tail held, input muted · damp {Pct(P(HFDamp))}");
+ string rt = NotaNum.F($"{Algo()} · RT60 {Secs(Rt60(P(Decay)))}");
+ string vin = On(Vintage) ? " · vintage" : "";
+ return centreTab == 0
+ ? NotaNum.F($"{rt} · pre {P(PreDelay) * 200:0} ms · diffuse {Pct(P(Diffusion))}{(On(EarlyRefl) ? "" : " · no early reflections")}")
+ : NotaNum.F($"{rt} · mod {RateF(P(ModRate))} / {Pct(P(ModDepth))}{(On(ModOnTail) ? "" : " (early part)")} · width {Pct(P(WidthP))}{vin}");
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ statusLeft.Foreground = On(Freeze) ? AccentBright : TextSecondary;
+ double sr = Sc(S_SampleRate), diff = Sc(S_DiffuseSmp);
+ // How much of the diffuser delay the pre-delay could actually absorb.
+ double preSmp = P(PreDelay) * 0.2 * sr;
+ string comp = diff < 1 ? "" : On(LatencyComp)
+ ? NotaNum.F($" · diffuser −{Math.Min(diff, preSmp):0} smp compensated")
+ : NotaNum.F($" · diffuser +{diff:0} smp");
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · latency {Sc(S_Latency):0} smp{comp} · CPU {Sc(S_Cpu) * 100:0.0} %") : "";
+ });
+ 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 = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { tailCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, kScope);
+ foreach (var a in readouts) a();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
- // Middle: tail graph | slim MOD island | SPACE+TONE column.
- var spaceBand = Band("SPACE", Cell("Pre", PreDelay, PreMs), Cell("Size", Size, Pct), Cell("Diffuse", Diffusion, Pct));
- var toneBand = Band("TONE", Cell("Low Cut", LowCut, Hz), Cell("High Cut", HighCut, Hz),
- Cell("Width", StereoWidth, Pct));
- var bands = new Grid()
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
{
- RowSpacing = 6,
- RowDefinitions = new RowDefinitions("*,*"),
- VerticalAlignment = VerticalAlignment.Stretch,
- Children =
+ int sel = 0;
+ var btns = new Border[tabs.Length];
+ void Hi()
{
- spaceBand,
- toneBand,
- },
- };
-
- Grid.SetRow(spaceBand, 0);
- Grid.SetRow(toneBand, 1);
-
- var mod = VBand("MOD", Cell("Rate", ModRate, RateF, Teal), Cell("Depth", ModDepth, Pct, Teal));
-
- // Right rail: output stage.
- var rail = new Border
- {
- Width = 96,
- Background = RailBg,
- BorderBrush = BorderDef,
- BorderThickness = new Thickness(1, 0, 0, 0),
- Padding = new Thickness(6, 8),
- Child = new StackPanel
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? Card2 : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AccentBright : TextTertiary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
{
- Spacing = 10,
- HorizontalAlignment = HorizontalAlignment.Center,
- VerticalAlignment = VerticalAlignment.Center,
- Children =
+ int iv = i;
+ var b = new Border
{
- Cell("Dry/Wet", DryWet, Pct, Teal, 40),
- Cell("Out", Output, DbF, null, 38),
- },
- },
- };
- DockPanel.SetDock(rail, Dock.Right);
-
- var content = new Grid
- {
- ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"),
- ColumnSpacing = 8,
- Margin = new Thickness(9, 8),
- };
- content.Children.Add(tail);
- Grid.SetColumn(mod, 1);
- content.Children.Add(mod);
- Grid.SetColumn(bands, 2);
- content.Children.Add(bands);
-
- var contentDock = new DockPanel { LastChildFill = true, Children = { rail, content } };
-
- DockPanel.SetDock(live, Dock.Top);
- return new DockPanel { LastChildFill = true, Children = { live, contentDock } };
+ 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 = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, _) => { 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 = BorderDef, 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 } };
+ }
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 68e59e87..920e49e4 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1066,20 +1066,90 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
("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));
- Fx("comp", 1, "Drum Punch", ("Character", 2f), ("Thresh", -24f), ("Ratio", 4f), ("Attack", 8f), ("Release", 90f), ("Knee", 2f), ("Makeup", 5f));
- Fx("comp", 1, "Vocal Opto", ("Character", 3f), ("Thresh", -20f), ("Ratio", 3f), ("Attack", 12f), ("Release", 180f), ("Knee", 8f), ("AutoRelease", 1f), ("Makeup", 4f));
- Fx("comp", 1, "Bus Parallel",("Character", 0f), ("Thresh", -30f), ("Ratio", 6f), ("Attack", 5f), ("Release", 120f), ("Mix", 45f), ("Makeup", 3f));
- Fx("comp", 1, "FET Slam", ("Character", 4f), ("Thresh", -16f), ("Ratio", 8f), ("Attack", 1f), ("Release", 80f), ("Knee", 1f), ("Lookahead", 2f), ("Makeup", 4f));
- Fx("comp", 1, "Brick Limit", ("Character", 4f), ("Thresh", -8f), ("Ratio", 20f), ("Attack", 0.5f), ("Release", 50f), ("Lookahead", 4f), ("Range", 12f), ("Makeup", 2f));
+ // ---- Compressor (kind 1) — 31 presets, raw units: Thresh −60..0 dB, Ratio 1..20, Attack .1..100 ms,
+ // Release 5..1000 ms, Makeup 0..24 dB, Knee 0..24 dB, Mix 0..100 %, Lookahead 0..10 ms,
+ // Range 0..48 dB (48 = off), SC HP 20..2000 Hz (20 = off), SC LP 200..20000 Hz (20000 = off),
+ // SC Gain ±24 dB, Hold 0..500 ms, SC Q .5..4. Character: Clean 0 / Glue 1 / Punch 2 / Opto 3 /
+ // FET 4 · Detection: Peak 0 / RMS 1 / Auto 2. External Key and Stereo Link default on. The
+ // sidechain presets need a key source picked on the card's Sidechain tab (or set_device_sidechain).
+ // Drums
+ Fx("comp", 1, "Drum Glue", ("Character", 1f), ("Thresh", -18f), ("Ratio", 3f), ("Attack", 30f), ("Release", 200f), ("Knee", 8f), ("AutoGain", 1f), ("Mix", 100f));
+ Fx("comp", 1, "Drum Punch", ("Character", 2f), ("Thresh", -24f), ("Ratio", 4f), ("Attack", 8f), ("Release", 90f), ("Knee", 2f), ("Makeup", 5f));
+ Fx("comp", 1, "Snare Punch", ("Character", 2f), ("Thresh", -28.5f), ("Ratio", 8f), ("Attack", 1.4f), ("Release", 60f), ("Knee", 2f), ("Range", 12f), ("Mix", 64f), ("AutoGain", 1f));
+ Fx("comp", 1, "Kick Tighten", ("Character", 2f), ("Thresh", -20f), ("Ratio", 4f), ("Attack", 15f), ("Release", 60f), ("Knee", 3f), ("Makeup", 3f));
+ Fx("comp", 1, "Room Smash", ("Character", 4f), ("Thresh", -35f), ("Ratio", 20f), ("Attack", 0.5f), ("Release", 120f), ("Knee", 0f), ("Makeup", 10f), ("Mix", 35f));
+ Fx("comp", 1, "Overheads Tame", ("Character", 3f), ("Thresh", -22f), ("Ratio", 2.5f), ("Attack", 20f), ("Release", 250f), ("Knee", 10f), ("Detection", 1f), ("SC HP", 200f), ("Makeup", 2f));
+ Fx("comp", 1, "Hat Smooth", ("Character", 0f), ("Thresh", -26f), ("Ratio", 3f), ("Attack", 3f), ("Release", 80f), ("Knee", 4f), ("SC HP", 1500f), ("Makeup", 2f));
+ // Bus / master
+ Fx("comp", 1, "Bus Glue", ("Character", 1f), ("Thresh", -18f), ("Ratio", 3f), ("Attack", 30f), ("Release", 200f), ("Knee", 8f), ("Lookahead", 2.9f), ("AutoRelease", 1f), ("Makeup", 3f));
+ Fx("comp", 1, "Bus Parallel", ("Character", 0f), ("Thresh", -30f), ("Ratio", 6f), ("Attack", 5f), ("Release", 120f), ("Mix", 45f), ("Makeup", 3f));
+ Fx("comp", 1, "Mix Bus Gentle", ("Character", 1f), ("Thresh", -14f), ("Ratio", 1.5f), ("Attack", 30f), ("Release", 300f), ("Knee", 10f), ("Detection", 2f), ("AutoRelease", 1f), ("SC HP", 90f), ("Makeup", 1.5f));
+ Fx("comp", 1, "Master Leveler", ("Character", 3f), ("Thresh", -16f), ("Ratio", 2f), ("Attack", 40f), ("Release", 400f), ("Knee", 12f), ("Detection", 1f), ("AutoRelease", 1f), ("Range", 6f), ("Makeup", 2f));
+ Fx("comp", 1, "Brick Limit", ("Character", 4f), ("Thresh", -8f), ("Ratio", 20f), ("Attack", 0.5f), ("Release", 50f), ("Lookahead", 4f), ("Range", 12f), ("Makeup", 2f));
+ Fx("comp", 1, "Peak Catcher", ("Character", 0f), ("Thresh", -6f), ("Ratio", 20f), ("Attack", 0.1f), ("Release", 40f), ("Knee", 0f), ("Lookahead", 5f), ("Range", 6f));
+ // Vocals
+ Fx("comp", 1, "Vocal Opto", ("Character", 3f), ("Thresh", -20f), ("Ratio", 3f), ("Attack", 12f), ("Release", 180f), ("Knee", 8f), ("AutoRelease", 1f), ("Makeup", 4f));
+ Fx("comp", 1, "Vocal Leveler", ("Character", 3f), ("Thresh", -24f), ("Ratio", 3f), ("Attack", 15f), ("Release", 220f), ("Knee", 10f), ("Detection", 1f), ("AutoRelease", 1f), ("AutoGain", 1f));
+ Fx("comp", 1, "Vocal Presence", ("Character", 4f), ("Thresh", -20f), ("Ratio", 4f), ("Attack", 2f), ("Release", 60f), ("Knee", 3f), ("Makeup", 4f), ("Mix", 70f));
+ Fx("comp", 1, "Rap Vocal", ("Character", 4f), ("Thresh", -22f), ("Ratio", 6f), ("Attack", 1f), ("Release", 70f), ("Knee", 2f), ("Makeup", 5f));
+ Fx("comp", 1, "De-Esser", ("Character", 0f), ("Thresh", -30f), ("Ratio", 6f), ("Attack", 0.5f), ("Release", 40f), ("Knee", 2f), ("Lookahead", 1f), ("Range", 8f), ("SC HP", 2000f), ("SC LP", 12000f), ("SC Q", 1.2f));
+ // Bass and instruments
+ Fx("comp", 1, "Bass Even", ("Character", 3f), ("Thresh", -22f), ("Ratio", 4f), ("Attack", 20f), ("Release", 150f), ("Knee", 6f), ("Detection", 1f), ("Makeup", 4f));
+ Fx("comp", 1, "Bass Pluck", ("Character", 2f), ("Thresh", -26f), ("Ratio", 5f), ("Attack", 8f), ("Release", 80f), ("Knee", 2f), ("Makeup", 5f));
+ Fx("comp", 1, "Acoustic Guitar", ("Character", 1f), ("Thresh", -20f), ("Ratio", 2.5f), ("Attack", 18f), ("Release", 180f), ("Knee", 8f), ("Detection", 1f), ("SC HP", 100f), ("Makeup", 3f));
+ Fx("comp", 1, "Guitar Sustain", ("Character", 4f), ("Thresh", -30f), ("Ratio", 8f), ("Attack", 5f), ("Release", 400f), ("Knee", 4f), ("Makeup", 8f));
+ Fx("comp", 1, "Piano Smooth", ("Character", 3f), ("Thresh", -18f), ("Ratio", 2f), ("Attack", 25f), ("Release", 300f), ("Knee", 10f), ("Detection", 2f), ("AutoRelease", 1f), ("Makeup", 2f));
+ Fx("comp", 1, "Pad Breathe", ("Character", 0f), ("Thresh", -30f), ("Ratio", 3f), ("Attack", 50f), ("Release", 600f), ("Knee", 12f), ("Detection", 1f), ("Mix", 60f));
+ Fx("comp", 1, "Wide Dual Mono", ("Character", 0f), ("Thresh", -20f), ("Ratio", 3f), ("Attack", 10f), ("Release", 150f), ("Knee", 6f), ("Stereo Link", 0f), ("Makeup", 2f));
+ Fx("comp", 1, "Lo-fi Squash", ("Character", 4f), ("Thresh", -40f), ("Ratio", 20f), ("Attack", 0.1f), ("Release", 30f), ("Knee", 0f), ("Makeup", 18f), ("Mix", 50f));
+ // Sidechain — pick the key source on the Sidechain tab
+ Fx("comp", 1, "Kick Duck", ("Character", 0f), ("Thresh", -21.6f), ("Ratio", 6f), ("Attack", 0.5f), ("Release", 120f), ("Knee", 2f), ("SC HP", 120f), ("SC LP", 8000f), ("SC Gain", 2f), ("Hold", 18f), ("Range", 9f), ("Makeup", 2.4f));
+ Fx("comp", 1, "EDM Pump", ("Character", 0f), ("Thresh", -30f), ("Ratio", 20f), ("Attack", 0.1f), ("Release", 180f), ("Knee", 0f), ("SC LP", 200f), ("Hold", 30f));
+ Fx("comp", 1, "Gentle Duck", ("Character", 1f), ("Thresh", -24f), ("Ratio", 3f), ("Attack", 10f), ("Release", 250f), ("Knee", 8f), ("SC LP", 400f), ("Hold", 10f));
+ Fx("comp", 1, "Voice-over Duck", ("Character", 3f), ("Thresh", -30f), ("Ratio", 4f), ("Attack", 20f), ("Release", 500f), ("Knee", 10f), ("Detection", 1f), ("Range", 10f), ("SC HP", 150f), ("SC LP", 5000f));
+ Fx("comp", 1, "Bass Under Kick", ("Character", 2f), ("Thresh", -24f), ("Ratio", 4f), ("Attack", 1f), ("Release", 90f), ("Knee", 3f), ("SC LP", 150f), ("Hold", 20f), ("Range", 8f));
- // ---- Reverb (kind 2) — all params normalized 0..1. Algorithm: Hall 0 / Room .33 / Plate .66 / Chamber 1.
- Fx("reverb", 2, "Small Room", ("Algorithm", 0.33f), ("Decay", 0.32f), ("HF Damp", 0.55f), ("Size", 0.35f), ("Diffusion", 0.6f), ("Dry/Wet", 0.2f));
- Fx("reverb", 2, "Long Hall", ("Algorithm", 0.0f), ("Decay", 0.72f), ("HF Damp", 0.4f), ("Pre-Delay", 0.12f), ("Size", 0.85f), ("Width", 0.8f), ("Dry/Wet", 0.32f));
- Fx("reverb", 2, "Bright Plate",("Algorithm", 0.66f), ("Decay", 0.5f), ("HF Damp", 0.15f), ("High Cut", 1.0f), ("Diffusion", 0.8f), ("Dry/Wet", 0.3f));
- Fx("reverb", 2, "Shimmer Freeze",("Algorithm", 0.0f), ("Freeze", 1.0f), ("Mod Rate", 0.4f), ("Mod Depth", 0.6f), ("Width", 1.0f), ("Dry/Wet", 0.5f));
+ // ---- Reverb (kind 2) — 30 presets, all params normalized 0..1. Algorithm: Hall 0 / Room .333 /
+ // Plate .667 / Chamber 1. Decay = ln(RT60 / 0.2) / ln(60) (1.9 s ≈ .55) · Pre-Delay = ms / 200 ·
+ // Low Cut = log(Hz / 20) / log(50) · High Cut = log(Hz / 1000) / log(20) (1 = 20 kHz) ·
+ // Mod Rate = log(Hz / .05) / log(100) · Bass Mono = log(Hz / 30) / log(16.7) (0 = off) ·
+ // Dry Level and Output are 0 dB at .707 and .5. Early Refl / Mod on Tail / Latency Comp default on.
+ // Rooms
+ Fx("reverb", 2, "Small Room", ("Algorithm", 0.333f), ("Decay", 0.32f), ("HF Damp", 0.55f), ("Size", 0.35f), ("Diffusion", 0.6f), ("Dry/Wet", 0.2f));
+ Fx("reverb", 2, "Tight Room", ("Algorithm", 0.333f), ("Decay", 0.17f), ("HF Damp", 0.6f), ("Pre-Delay", 0.02f), ("Size", 0.2f), ("Diffusion", 0.7f), ("Width", 0.5f), ("Dry/Wet", 0.18f));
+ Fx("reverb", 2, "Drum Room", ("Algorithm", 0.333f), ("Decay", 0.34f), ("HF Damp", 0.35f), ("Pre-Delay", 0.03f), ("Size", 0.5f), ("Diffusion", 0.75f), ("Low Cut", 0.35f), ("Width", 0.75f), ("Dry/Wet", 0.25f));
+ Fx("reverb", 2, "Vocal Booth", ("Algorithm", 0.333f), ("Decay", 0.12f), ("HF Damp", 0.7f), ("Size", 0.1f), ("Diffusion", 0.5f), ("High Cut", 0.7f), ("Width", 0.35f), ("Dry/Wet", 0.15f));
+ Fx("reverb", 2, "Live Room", ("Algorithm", 0.333f), ("Decay", 0.44f), ("HF Damp", 0.45f), ("Pre-Delay", 0.05f), ("Size", 0.65f), ("Diffusion", 0.65f), ("Low Cut", 0.3f), ("Width", 0.7f), ("Dry/Wet", 0.24f));
+ // Halls
+ Fx("reverb", 2, "Wide Hall", ("Algorithm", 0f), ("Decay", 0.55f), ("HF Damp", 0.5f), ("Pre-Delay", 0.1f), ("Size", 0.6f), ("Diffusion", 0.6f), ("Width", 0.8f), ("Dry/Wet", 0.3f));
+ Fx("reverb", 2, "Long Hall", ("Algorithm", 0f), ("Decay", 0.72f), ("HF Damp", 0.4f), ("Pre-Delay", 0.12f), ("Size", 0.85f), ("Width", 0.8f), ("Dry/Wet", 0.32f));
+ Fx("reverb", 2, "Concert Hall", ("Algorithm", 0f), ("Decay", 0.64f), ("HF Damp", 0.55f), ("Pre-Delay", 0.14f), ("Size", 0.9f), ("Diffusion", 0.7f), ("Low Cut", 0.3f), ("High Cut", 0.77f), ("Width", 0.75f), ("Dry/Wet", 0.28f));
+ Fx("reverb", 2, "Cathedral", ("Algorithm", 0f), ("Decay", 0.9f), ("HF Damp", 0.6f), ("Pre-Delay", 0.2f), ("Size", 1f), ("Diffusion", 0.8f), ("Low Cut", 0.35f), ("High Cut", 0.65f), ("Width", 0.9f), ("Mod Depth", 0.3f), ("Dry/Wet", 0.35f));
+ Fx("reverb", 2, "Dark Hall", ("Algorithm", 0f), ("Decay", 0.66f), ("HF Damp", 0.85f), ("Pre-Delay", 0.08f), ("Size", 0.75f), ("High Cut", 0.45f), ("Width", 0.7f), ("Dry/Wet", 0.3f));
+ // Plates
+ Fx("reverb", 2, "Bright Plate", ("Algorithm", 0.667f), ("Decay", 0.5f), ("HF Damp", 0.15f), ("High Cut", 1.0f), ("Diffusion", 0.8f), ("Dry/Wet", 0.3f));
+ Fx("reverb", 2, "Vocal Plate", ("Algorithm", 0.667f), ("Decay", 0.44f), ("HF Damp", 0.35f), ("Pre-Delay", 0.1f), ("Diffusion", 0.8f), ("Low Cut", 0.46f), ("High Cut", 0.83f), ("Mod Rate", 0.3f), ("Mod Depth", 0.25f), ("Early Refl", 0f), ("Dry/Wet", 0.26f));
+ Fx("reverb", 2, "Snare Plate", ("Algorithm", 0.667f), ("Decay", 0.36f), ("HF Damp", 0.2f), ("Pre-Delay", 0.04f), ("Size", 0.45f), ("Diffusion", 0.9f), ("Low Cut", 0.59f), ("Early Refl", 0f), ("Width", 0.7f), ("Dry/Wet", 0.3f));
+ Fx("reverb", 2, "Gold Plate", ("Algorithm", 0.667f), ("Decay", 0.58f), ("HF Damp", 0.3f), ("Pre-Delay", 0.06f), ("Diffusion", 0.85f), ("Low Cut", 0.4f), ("High Cut", 0.9f), ("Mod Rate", 0.39f), ("Mod Depth", 0.35f), ("Early Refl", 0f), ("Width", 0.75f), ("Dry/Wet", 0.3f));
+ Fx("reverb", 2, "Vintage Plate", ("Algorithm", 0.667f), ("Decay", 0.5f), ("HF Damp", 0.4f), ("Pre-Delay", 0.05f), ("Diffusion", 0.8f), ("Low Cut", 0.4f), ("High Cut", 0.6f), ("Vintage", 1f), ("Early Refl", 0f), ("Dry/Wet", 0.3f));
+ // Chambers
+ Fx("reverb", 2, "Echo Chamber", ("Algorithm", 1f), ("Decay", 0.5f), ("HF Damp", 0.45f), ("Pre-Delay", 0.08f), ("Size", 0.6f), ("Diffusion", 0.65f), ("Low Cut", 0.35f), ("Dry/Wet", 0.28f));
+ Fx("reverb", 2, "Studio Chamber", ("Algorithm", 1f), ("Decay", 0.42f), ("HF Damp", 0.55f), ("Pre-Delay", 0.06f), ("Size", 0.5f), ("Diffusion", 0.7f), ("Low Cut", 0.4f), ("High Cut", 0.75f), ("Width", 0.65f), ("Dry/Wet", 0.24f));
+ Fx("reverb", 2, "Stone Chamber", ("Algorithm", 1f), ("Decay", 0.62f), ("HF Damp", 0.3f), ("Pre-Delay", 0.13f), ("Size", 0.84f), ("Diffusion", 0.72f), ("Width", 0.7f), ("Dry/Wet", 0.3f));
+ // Creative and frozen
+ Fx("reverb", 2, "Shimmer Freeze", ("Algorithm", 0.0f), ("Freeze", 1.0f), ("Mod Rate", 0.4f), ("Mod Depth", 0.6f), ("Width", 1.0f), ("Dry/Wet", 0.5f));
+ Fx("reverb", 2, "Stone Hold", ("Algorithm", 1f), ("Freeze", 1f), ("HF Damp", 0.34f), ("Pre-Delay", 0.13f), ("Size", 0.84f), ("Diffusion", 0.72f), ("Dry Level", 0f), ("Dry/Wet", 1f), ("Output", 0.38f));
+ Fx("reverb", 2, "Infinite Pad", ("Algorithm", 0f), ("Decay", 1f), ("HF Damp", 0.55f), ("Pre-Delay", 0.1f), ("Size", 1f), ("Diffusion", 0.9f), ("Low Cut", 0.46f), ("High Cut", 0.6f), ("Mod Rate", 0.3f), ("Mod Depth", 0.45f), ("Width", 1f), ("Dry/Wet", 0.55f));
+ Fx("reverb", 2, "Ambient Wash", ("Algorithm", 0f), ("Decay", 0.83f), ("HF Damp", 0.5f), ("Pre-Delay", 0.25f), ("Size", 0.95f), ("Diffusion", 0.85f), ("Low Cut", 0.46f), ("Mod Rate", 0.3f), ("Mod Depth", 0.4f), ("Width", 0.9f), ("Dry/Wet", 0.45f));
+ Fx("reverb", 2, "Lo-Fi Cloud", ("Algorithm", 1f), ("Decay", 0.7f), ("HF Damp", 0.6f), ("Pre-Delay", 0.1f), ("Size", 0.8f), ("Low Cut", 0.5f), ("High Cut", 0.37f), ("Vintage", 1f), ("Mod Rate", 0.45f), ("Mod Depth", 0.6f), ("Dry/Wet", 0.4f));
+ Fx("reverb", 2, "Seasick", ("Algorithm", 0f), ("Decay", 0.66f), ("Size", 0.7f), ("Mod Rate", 0.6f), ("Mod Depth", 1f), ("Vintage", 1f), ("Width", 0.9f), ("Dry/Wet", 0.38f));
+ Fx("reverb", 2, "Still Water", ("Algorithm", 0f), ("Decay", 0.7f), ("HF Damp", 0.45f), ("Pre-Delay", 0.15f), ("Size", 0.85f), ("Mod on Tail", 0f), ("Mod Depth", 0.5f), ("Width", 0.8f), ("Dry/Wet", 0.35f));
+ Fx("reverb", 2, "Short Burst", ("Algorithm", 0f), ("Decay", 0.2f), ("HF Damp", 0.2f), ("Size", 1f), ("Diffusion", 1f), ("Early Refl", 0f), ("Width", 1f), ("Dry/Wet", 0.35f));
+ Fx("reverb", 2, "Slap Space", ("Algorithm", 0.333f), ("Decay", 0.25f), ("Pre-Delay", 0.4f), ("Size", 0.4f), ("Diffusion", 0.4f), ("Early Refl", 1f), ("Dry/Wet", 0.25f));
+ // Sends (wet only, for a return track)
+ Fx("reverb", 2, "Send · Hall", ("Wet Only", 1f), ("Algorithm", 0f), ("Decay", 0.58f), ("HF Damp", 0.5f), ("Pre-Delay", 0.12f), ("Size", 0.75f), ("Low Cut", 0.46f), ("High Cut", 0.77f), ("Bass Mono", 0.49f), ("Width", 0.8f), ("Dry/Wet", 1f));
+ Fx("reverb", 2, "Send · Plate", ("Wet Only", 1f), ("Algorithm", 0.667f), ("Decay", 0.47f), ("HF Damp", 0.3f), ("Pre-Delay", 0.08f), ("Diffusion", 0.85f), ("Low Cut", 0.52f), ("Bass Mono", 0.57f), ("Early Refl", 0f), ("Dry/Wet", 1f));
+ Fx("reverb", 2, "Send · Room", ("Wet Only", 1f), ("Algorithm", 0.333f), ("Decay", 0.3f), ("HF Damp", 0.5f), ("Pre-Delay", 0.03f), ("Size", 0.45f), ("Low Cut", 0.46f), ("Bass Mono", 0.49f), ("Dry/Wet", 1f));
// ---- Delay (kind 3) — 29 presets, all params normalized 0..1. Div: 1/16 0 · 1/8T .143 ·
// 1/8 .286 · 1/8. .429 · 1/4T .571 · 1/4 .714 · 1/4. .857 · 1/2 1. Time L/R = ms / 2000.
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 35f5c092..74273fa5 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -67,13 +67,59 @@ 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). 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. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen).")]
+ [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. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers.")]
public Task<string> GetDeviceText(int trackId, int deviceIndex, int id) => Read(() => E.DeviceText(trackId, deviceIndex, id));
- [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Devices without a command ignore the call.")]
+ [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Devices without a command ignore the call.")]
public Task DeviceAction(int trackId, int deviceIndex, [Description("Command id — see the device's list in this description")] int id,
int intArg = 0, float floatArg = 0) => Mutate(() => E.DeviceAction(trackId, deviceIndex, id, intArg, floatArg));
+ public sealed record Sidechain(bool Accepts, int SourceTrackId, bool TapPre, float GainDb, float Mix);
+
+ [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1).")]
+ public Task<Sidechain> GetDeviceSidechain(int trackId, int deviceIndex) => Read(() => new Sidechain(
+ E.DeviceAcceptsSidechain(trackId, deviceIndex), E.DeviceSidechainSource(trackId, deviceIndex),
+ E.DeviceSidechainTapPre(trackId, deviceIndex), E.DeviceSidechainGain(trackId, deviceIndex), E.DeviceSidechainMix(trackId, deviceIndex)));
+
+ [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain.")]
+ public Task SetDeviceSidechain(int trackId, int deviceIndex, [Description("Key source track id, or -1 for none")] int sourceTrackId,
+ bool? tapPre = null, float? gainDb = null) => Mutate(() =>
+ {
+ E.SetDeviceSidechainSource(trackId, deviceIndex, sourceTrackId);
+ if (tapPre is { } pre) E.SetDeviceSidechainTapPre(trackId, deviceIndex, pre);
+ if (gainDb is { } g) E.SetDeviceSidechainGain(trackId, deviceIndex, Math.Clamp(g, -24f, 24f));
+ });
+
+ public sealed record DynamicsReading(string Summary, double GainReductionDb, double InputPeakDb, double InputRmsDb,
+ double OutputPeakDb, double OutputRmsDb, double KeyPeakDb, bool ExternalKey, double AttackMs, double ReleaseMs,
+ int LatencySamples, double SampleRate, int HitsLast2s, double DeepestReductionLast2sDb);
+
+ [McpServerTool(Name = "read_dynamics"), Description(
+ "Read what a Nota Compressor (built-in effect kind 1) is doing right now: the gain reduction (dB, positive = "
+ + "reduced), input / output peak and 300 ms RMS levels (dBFS), the detector key's peak level (after the key "
+ + "filters and SC Gain — compare it with the threshold), whether an external sidechain key is driving it, the "
+ + "effective attack / release in ms (after the Character voicing and auto-release), the look-ahead latency, "
+ + "how many times the reduction kicked in (rose through 1 dB) and the deepest reduction over the last 2 s, and "
+ + "the one-line summary. Levels are only live while audio plays through the track.")]
+ public Task<DynamicsReading> ReadDynamics(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int kScope = 14, envN = 2048;
+ var sc = new float[kScope + 2 * envN];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ static double Db(float lin) => lin > 1e-6f ? Math.Round(20 * Math.Log10(lin), 1) : -120;
+ int hits = 0; bool armed = true; double deepest = 0;
+ if (n >= sc.Length)
+ for (int i = kScope + envN; i < kScope + 2 * envN; i++)
+ {
+ deepest = Math.Max(deepest, sc[i]);
+ if (armed && sc[i] > 1) { hits++; armed = false; }
+ else if (!armed && sc[i] < 0.5f) armed = true;
+ }
+ float V(int i) => n > i ? sc[i] : 0f;
+ return new DynamicsReading(E.DeviceText(trackId, deviceIndex, 0), Math.Round(V(4), 2), Db(V(0)), Db(V(2)), Db(V(1)), Db(V(3)),
+ Db(V(5)), V(12) > 0.5f, Math.Round(V(6), 2), Math.Round(V(7), 1), (int)V(10), V(8), hits, Math.Round(deepest, 1));
+ });
+
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);
diff --git a/src/native/nota.engine/src/Compressor.h b/src/native/nota.engine/src/Compressor.h
index 32b2df31..506dda8f 100644
--- a/src/native/nota.engine/src/Compressor.h
+++ b/src/native/nota.engine/src/Compressor.h
@@ -1,13 +1,22 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in compressor (mockup 2n) — feed-forward, stereo-linked, with a smoothed
-// level follower (attack/release, optional program-dependent auto-release), a
-// soft-knee gain computer, peak/RMS detection, look-ahead, a gain-reduction range
-// limit, auto make-up gain, dry/wet mix, five voicing "character" models and a
-// filtered side-chain detector (HP/LP) with a Listen monitor. A core Device
-// (JUCE-free); params are atomic / lock-free. Existing params keep their names so
-// old projects load; new ones are appended.
+// Built-in compressor ("Nota Compressor" — almanac update: curve · motion · sidechain) —
+// feed-forward with a smoothed level follower (attack / hold / release, optional
+// program-dependent auto-release), a soft-knee gain computer, Peak / RMS / Auto detection,
+// look-ahead (reported as latency, so PDC keeps the track aligned), a gain-reduction range
+// limit, auto make-up gain, dry/wet mix and five voicing "character" models. The detector
+// keys off the track itself or an external sidechain source (External Key), through a
+// 2-pole high-pass + low-pass with a shared Q and a detector gain; Listen monitors that
+// key. Stereo Link on detects the L/R mean and applies one gain to both channels; off, each
+// channel compresses on its own.
+//
+// Params are raw units (the card and presets read them as such); persist / clone /
+// automation are generic through the base Device. Param order is the persisted layout —
+// APPEND ONLY. Old projects keep their names and values; the appended ones default to the
+// old behaviour (external key on, stereo linked, no hold, Butterworth key filters).
+// Telemetry for the card goes through scopeRead (see the S_* layout). A core Device
+// (JUCE-free); params are atomic / lock-free and process() never allocates.
#pragma once
@@ -15,8 +24,11 @@
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
#include <vector>
namespace nota {
@@ -25,80 +37,134 @@ class Compressor : public Device {
public:
enum { Threshold = 0, Ratio, Attack, Release, Makeup,
Knee, Mix, Lookahead, Detection, AutoRelease, AutoGain, Range, Character,
- ScHP, ScLP, ScListen, kNumParams };
+ ScHP, ScLP, ScListen,
+ // ---- appended for the almanac update — keep the order, append only ----
+ ScGain, Hold, ScQ, External, StereoLink, kNumParams };
+
+ // Scope telemetry layout (read by the card and the MCP read_dynamics tool). After the
+ // kScope values come kEnvN input-level points, kEnvN gain-reduction points (dB, one per
+ // kEnvMs, oldest→newest) and kKeyN samples of the unfiltered key (oldest→newest).
+ enum { S_InPk = 0, S_OutPk, S_InRms, S_OutRms, S_Gr, S_KeyPk, S_AtkMs, S_RelMs,
+ S_SampleRate, S_Bpm, S_Latency, S_Cpu, S_ExtKey, S_EnvMs, kScope };
+ static constexpr int kEnvN = 2048; // 2 s of envelope at 1 ms per point
+ static constexpr int kKeyN = 2048; // key signal for the card's spectrum
+ static constexpr float kEnvMs = 1.0f;
+
+ static constexpr int kNumChars = 5; // Clean / Glue / Punch / Opto / FET
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
sr_ = sr > 0 ? sr : 44100.0;
laSize_ = static_cast<int>(sr_ * 0.011) + 2; // up to ~10 ms look-ahead
laBuf_.assign(static_cast<size_t>(laSize_) * 2, 0.0f); laW_ = 0;
+ envDecim_ = std::max(1, static_cast<int>(sr_ * kEnvMs * 0.001));
+ envCnt_ = 0; envIn_ = 0.0f; envGr_ = 0.0f;
+ for (auto& c : ch_) c = Chan{};
+ inMs_ = outMs_ = 0.0;
+ srA_.store(static_cast<float>(sr_), std::memory_order_relaxed);
+ }
+ void setTransport(double, double samplesPerBeat, bool) override {
+ if (samplesPerBeat > 0.0) spb_ = samplesPerBeat;
}
void process(float* buf, int32_t frames) override {
+ if (frames <= 0) return;
+ const auto t0 = std::chrono::steady_clock::now();
const double sr = sr_;
- const int ch = std::clamp((int)std::lround(p_[Character].load(std::memory_order_relaxed)), 0, 4);
- static const float chAtk[5] = {1.0f, 1.4f, 0.5f, 1.7f, 0.3f}; // Clean/Glue/Punch/Opto/FET
- static const float chRel[5] = {1.0f, 1.7f, 0.8f, 2.2f, 0.6f};
- static const float chKnee[5] = {0.0f, 6.0f, 1.0f, 8.0f, 2.0f};
-
- const float threshDb = p_[Threshold].load(std::memory_order_relaxed);
- const float ratio = std::max(1.0f, p_[Ratio].load(std::memory_order_relaxed));
- const float atkMs = std::max(0.05f, p_[Attack].load(std::memory_order_relaxed)) * chAtk[ch];
- const float relMs = std::max(1.0f, p_[Release].load(std::memory_order_relaxed)) * chRel[ch];
- const float makeupDb = p_[Makeup].load(std::memory_order_relaxed);
- const float kneeDb = std::max(0.0f, p_[Knee].load(std::memory_order_relaxed) + chKnee[ch]);
- const float mix = std::clamp(p_[Mix].load(std::memory_order_relaxed) * 0.01f, 0.0f, 1.0f);
- const float rangeDb = p_[Range].load(std::memory_order_relaxed); // max reduction, dB
- const bool rms = p_[Detection].load(std::memory_order_relaxed) > 0.5f;
- const bool autoRel = p_[AutoRelease].load(std::memory_order_relaxed) > 0.5f;
- const bool autoGain = p_[AutoGain].load(std::memory_order_relaxed) > 0.5f;
- const bool listen = p_[ScListen].load(std::memory_order_relaxed) > 0.5f;
+ const int chr = charIndex();
+ static const float chAtk[kNumChars] = {1.0f, 1.4f, 0.5f, 1.7f, 0.3f}; // Clean/Glue/Punch/Opto/FET
+ static const float chRel[kNumChars] = {1.0f, 1.7f, 0.8f, 2.2f, 0.6f};
+ static const float chKnee[kNumChars] = {0.0f, 6.0f, 1.0f, 8.0f, 2.0f};
+
+ const float threshDb = get(Threshold);
+ const float ratio = std::max(1.0f, get(Ratio));
+ const float atkMs = std::max(0.05f, get(Attack)) * chAtk[chr];
+ const float relMs = std::max(1.0f, get(Release)) * chRel[chr];
+ const float makeupDb = get(Makeup);
+ const float kneeDb = std::max(0.0f, get(Knee) + chKnee[chr]);
+ const float mix = std::clamp(get(Mix) * 0.01f, 0.0f, 1.0f);
+ const float rangeDb = get(Range); // max reduction, dB
+ const int detMode = detectionMode();
+ const bool autoRel = on(AutoRelease);
+ const bool autoGain = on(AutoGain);
+ const bool listen = on(ScListen);
+ const bool linked = on(StereoLink);
+ const bool useExt = on(External);
const double atkC = std::exp(-1.0 / (atkMs * 0.001 * sr));
const double relC = std::exp(-1.0 / (relMs * 0.001 * sr));
const double relCs = std::exp(-1.0 / (relMs * 4.0 * 0.001 * sr)); // slow stage (auto-release)
const double rmsC = std::exp(-1.0 / (0.010 * sr)); // 10 ms RMS window
+ const double lvlC = std::exp(-1.0 / (0.300 * sr)); // 300 ms in/out RMS meters
const float slope = 1.0f - 1.0f / ratio;
+ const int holdN = static_cast<int>(std::clamp(get(Hold), 0.0f, 500.0f) * 0.001f * sr);
- // Side-chain detector filters (HP + LP one-pole) on the detector path.
- const double hp = std::clamp((double)p_[ScHP].load(std::memory_order_relaxed), 20.0, 2000.0);
- const double lp = std::clamp((double)p_[ScLP].load(std::memory_order_relaxed), 200.0, 20000.0);
- const float hpCoef = (float)std::exp(-2.0 * kPi * hp / sr);
- const float lpCoef = (float)(1.0 - std::exp(-2.0 * kPi * lp / sr));
+ // Key filters: 2-pole TPT state-variable HP and LP sharing one Q. A cut at its range
+ // end is skipped entirely, so the default key is the plain detector signal.
+ const float hpHz = std::clamp(get(ScHP), 20.0f, 2000.0f);
+ const float lpHz = std::clamp(get(ScLP), 200.0f, 20000.0f);
+ const float q = std::clamp(get(ScQ), 0.5f, 4.0f);
+ const bool hpOn = hpHz > 20.5f, lpOn = lpHz < 19999.0f;
+ const Svf hpF = Svf::make(hpHz, q, sr), lpF = Svf::make(lpHz, q, sr);
// Auto make-up estimate: roughly half the reduction at 0 dBFS peaks.
const float autoMk = autoGain ? std::max(0.0f, -threshDb * slope * 0.5f) : 0.0f;
- const float* sc = (scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;
- const float scGainLin = std::pow(10.0f, sidechainGainDb() / 20.0f);
- const int la = std::clamp((int)(p_[Lookahead].load(std::memory_order_relaxed) * 0.001 * sr), 0, laSize_ - 1);
+ const float* sc = (useExt && scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;
+ // The detector gain: the SC Gain param always, plus the base sidechain gain when an
+ // external source keys it (the older, generic sidechain control).
+ const float keyGain = dbToLin(get(ScGain) + (sc ? sidechainGainDb() : 0.0f));
+ const int la = lookaheadSamples();
- float maxGr = 0.0f;
+ float maxGr = 0.0f, inPk = 0.0f, outPk = 0.0f, keyPk = 0.0f;
+ const int nDet = linked ? 1 : 2;
for (int32_t i = 0; i < frames; ++i) {
const float l = buf[i * 2], r = buf[i * 2 + 1];
- float d = sc ? (sc[i * 2] + sc[i * 2 + 1]) * 0.5f * scGainLin : (l + r) * 0.5f;
- // Detector HP then LP.
- hpS_ = hpCoef * (hpS_ + d - hpPrev_); hpPrev_ = d; d = hpS_;
- lpS_ += lpCoef * (d - lpS_); d = lpS_;
-
- float det;
- if (rms) { rmsE_ = (float)(rmsC * rmsE_ + (1.0 - rmsC) * d * d); det = std::sqrt(rmsE_); }
- else det = std::fabs(d);
-
- if (det > env_) env_ = (float)(atkC * env_ + (1.0 - atkC) * det);
- else { double rc = (autoRel && grPrev_ > 3.0f) ? relCs : relC; env_ = (float)(rc * env_ + (1.0 - rc) * det); }
-
- const float envDb = 20.0f * std::log10(env_ + 1e-9f);
- const float over = envDb - threshDb;
- float grDb;
- if (kneeDb > 0.01f && 2.0f * over > -kneeDb && 2.0f * over < kneeDb)
- grDb = slope * (over + kneeDb * 0.5f) * (over + kneeDb * 0.5f) / (2.0f * kneeDb); // soft knee
- else grDb = over > 0.0f ? slope * over : 0.0f;
- grDb = std::min(grDb, rangeDb);
- grPrev_ = grDb;
- if (grDb > maxGr) maxGr = grDb;
-
- const float wetGain = std::pow(10.0f, (makeupDb + autoMk - grDb) / 20.0f);
- const float gain = (1.0f - mix) + mix * wetGain;
+ const float kl = (sc ? sc[i * 2] : l) * keyGain, kr = (sc ? sc[i * 2 + 1] : r) * keyGain;
+ const float keyRaw[2] = { linked ? (kl + kr) * 0.5f : kl, kr };
+
+ float gr[2] = {0.0f, 0.0f}, key[2] = {0.0f, 0.0f};
+ for (int c = 0; c < nDet; ++c) {
+ Chan& s = ch_[c];
+ float d = keyRaw[c];
+ if (hpOn) d = s.hp.tick(hpF, d, true);
+ if (lpOn) d = s.lp.tick(lpF, d, false);
+ key[c] = d;
+
+ float det;
+ const float pk = std::fabs(d);
+ if (detMode == 0) det = pk;
+ else {
+ s.rmsE = static_cast<float>(rmsC * s.rmsE + (1.0 - rmsC) * d * d);
+ const float rmsLvl = std::sqrt(s.rmsE);
+ // Auto: RMS scaled to a sine's peak for the body, with the raw peak still able
+ // to catch a transient that stands well above it.
+ det = detMode == 1 ? rmsLvl : std::max(rmsLvl * 1.41421356f, pk * 0.5f);
+ }
+
+ if (det > s.env) { s.env = static_cast<float>(atkC * s.env + (1.0 - atkC) * det); s.hold = holdN; }
+ else if (s.hold > 0) --s.hold;
+ else {
+ const double rc = (autoRel && s.grPrev > 3.0f) ? relCs : relC;
+ s.env = static_cast<float>(rc * s.env + (1.0 - rc) * det);
+ }
+
+ const float envDb = 20.0f * std::log10(s.env + 1e-9f);
+ const float over = envDb - threshDb;
+ float g;
+ if (kneeDb > 0.01f && 2.0f * over > -kneeDb && 2.0f * over < kneeDb)
+ g = slope * (over + kneeDb * 0.5f) * (over + kneeDb * 0.5f) / (2.0f * kneeDb); // soft knee
+ else g = over > 0.0f ? slope * over : 0.0f;
+ g = std::min(g, rangeDb);
+ s.grPrev = g;
+ gr[c] = g;
+ }
+ if (linked) { gr[1] = gr[0]; key[1] = key[0]; }
+ const float grMax = std::max(gr[0], gr[1]);
+ maxGr = std::max(maxGr, grMax);
+ keyPk = std::max(keyPk, std::max(std::fabs(key[0]), std::fabs(key[1])));
+
+ const float gainL = (1.0f - mix) + mix * dbToLin(makeupDb + autoMk - gr[0]);
+ const float gainR = (1.0f - mix) + mix * dbToLin(makeupDb + autoMk - gr[1]);
// Look-ahead: apply the current gain to the delayed audio.
laBuf_[laW_ * 2] = l; laBuf_[laW_ * 2 + 1] = r;
@@ -106,15 +172,110 @@ public:
const float dl = laBuf_[rp * 2], dr = laBuf_[rp * 2 + 1];
if (++laW_ >= laSize_) laW_ = 0;
- if (listen) { buf[i * 2] = d; buf[i * 2 + 1] = d; }
- else { buf[i * 2] = dl * gain; buf[i * 2 + 1] = dr * gain; }
+ float oL, oR;
+ if (listen) { oL = key[0]; oR = key[1]; }
+ else { oL = dl * gainL; oR = dr * gainR; }
+ buf[i * 2] = oL; buf[i * 2 + 1] = oR;
+
+ // ---- meters: peak + 300 ms RMS on the input (as it enters) and the output ----
+ const float inA = std::max(std::fabs(l), std::fabs(r)), outA = std::max(std::fabs(oL), std::fabs(oR));
+ inPk = std::max(inPk, inA); outPk = std::max(outPk, outA);
+ inMs_ = lvlC * inMs_ + (1.0 - lvlC) * 0.5 * (l * l + r * r);
+ outMs_ = lvlC * outMs_ + (1.0 - lvlC) * 0.5 * (oL * oL + oR * oR);
+
+ // ---- envelope ring (1 ms buckets: the loudest input and the deepest reduction) ----
+ envIn_ = std::max(envIn_, inA);
+ envGr_ = std::max(envGr_, grMax);
+ if (++envCnt_ >= envDecim_) {
+ const int w = envW_.load(std::memory_order_relaxed);
+ envRing_[w] = 20.0f * std::log10(envIn_ + 1e-9f);
+ grRing_[w] = envGr_;
+ envW_.store((w + 1) % kEnvN, std::memory_order_relaxed);
+ envCnt_ = 0; envIn_ = 0.0f; envGr_ = 0.0f;
+ }
+ // ---- key ring (unfiltered, so the card can draw what the filters take away) ----
+ const int kw = keyW_.load(std::memory_order_relaxed);
+ keyRing_[kw] = (keyRaw[0] + (linked ? keyRaw[0] : keyRaw[1])) * 0.5f;
+ keyW_.store((kw + 1) % kKeyN, std::memory_order_relaxed);
}
gr_.store(maxGr, std::memory_order_relaxed);
scBuf_ = nullptr;
+
+ // ---- telemetry ---------------------------------------------------------------
+ inPkA_.store(decayPeak(inPkA_.load(std::memory_order_relaxed), inPk), std::memory_order_relaxed);
+ outPkA_.store(decayPeak(outPkA_.load(std::memory_order_relaxed), outPk), std::memory_order_relaxed);
+ keyPkA_.store(decayPeak(keyPkA_.load(std::memory_order_relaxed), keyPk), std::memory_order_relaxed);
+ inRmsA_.store(static_cast<float>(std::sqrt(inMs_)), std::memory_order_relaxed);
+ outRmsA_.store(static_cast<float>(std::sqrt(outMs_)), std::memory_order_relaxed);
+ extA_.store(sc ? 1.0f : 0.0f, std::memory_order_relaxed);
+ atkA_.store(atkMs, std::memory_order_relaxed);
+ relA_.store(autoRel && maxGr > 3.0f ? relMs * 4.0f : relMs, std::memory_order_relaxed);
+ bpmA_.store(spb_ > 0.0 ? static_cast<float>(60.0 * sr_ / spb_) : 0.0f, std::memory_order_relaxed);
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store(static_cast<float>(cpuS_), std::memory_order_relaxed);
}
+ // Look-ahead delays the audio by this much; the engine's PDC lines the other tracks up.
+ int32_t latencySamples() const override { return lookaheadSamples(); }
+
float gainReductionDb() const override { return gr_.load(std::memory_order_relaxed); }
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples < kScope) return 0;
+ out[S_InPk] = inPkA_.load(std::memory_order_relaxed);
+ out[S_OutPk] = outPkA_.load(std::memory_order_relaxed);
+ out[S_InRms] = inRmsA_.load(std::memory_order_relaxed);
+ out[S_OutRms] = outRmsA_.load(std::memory_order_relaxed);
+ out[S_Gr] = gr_.load(std::memory_order_relaxed);
+ out[S_KeyPk] = keyPkA_.load(std::memory_order_relaxed);
+ out[S_AtkMs] = atkA_.load(std::memory_order_relaxed);
+ out[S_RelMs] = relA_.load(std::memory_order_relaxed);
+ out[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ out[S_Bpm] = bpmA_.load(std::memory_order_relaxed);
+ out[S_Latency] = static_cast<float>(latencySamples());
+ out[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ out[S_ExtKey] = extA_.load(std::memory_order_relaxed);
+ out[S_EnvMs] = kEnvMs;
+ int32_t n = kScope;
+ if (maxSamples >= kScope + 2 * kEnvN) {
+ const int w = envW_.load(std::memory_order_relaxed);
+ for (int k = 0; k < kEnvN; ++k) {
+ const int idx = (w + k) % kEnvN;
+ out[kScope + k] = envRing_[idx];
+ out[kScope + kEnvN + k] = grRing_[idx];
+ }
+ n += 2 * kEnvN;
+ if (maxSamples >= kScope + 2 * kEnvN + kKeyN) {
+ const int kw = keyW_.load(std::memory_order_relaxed);
+ for (int k = 0; k < kKeyN; ++k) out[n + k] = keyRing_[(kw + k) % kKeyN];
+ n += kKeyN;
+ }
+ }
+ return n;
+ }
+
+ // id 0 — a one-line summary of what the compressor is doing now (the card's status strip,
+ // and get_device_text over MCP).
+ std::string deviceText(int32_t id) const override {
+ if (id != 0) return {};
+ static const char* chn[kNumChars] = { "Clean", "Glue", "Punch", "Opto", "FET" };
+ static const char* det[3] = { "peak", "RMS", "auto" };
+ char b[320];
+ const float rng = getParam(Range);
+ char rngS[32];
+ if (rng >= 47.5f) std::snprintf(rngS, sizeof rngS, "off"); else std::snprintf(rngS, sizeof rngS, "%.0f dB", rng);
+ std::snprintf(b, sizeof b,
+ "%s - threshold %.1f dB - %.1f:1 - knee %.1f dB - attack %.1f ms / release %.0f ms%s - %s - range %s - mix %.0f %% - GR %.1f dB%s%s%s",
+ chn[charIndex()], getParam(Threshold), getParam(Ratio), getParam(Knee), getParam(Attack), getParam(Release),
+ getParam(AutoRelease) >= 0.5f ? " (auto)" : "", det[detectionMode()], rngS, getParam(Mix),
+ gr_.load(std::memory_order_relaxed),
+ extA_.load(std::memory_order_relaxed) > 0.5f ? " - external key" : "",
+ getParam(StereoLink) >= 0.5f ? "" : " - unlinked",
+ getParam(ScListen) >= 0.5f ? " - LISTEN (key only)" : "");
+ return std::string(b);
+ }
+
int32_t sidechainSourceTrackId() const override { return scTrackId_.load(std::memory_order_relaxed); }
void setSidechainSourceTrackId(int32_t id) override { scTrackId_.store(id, std::memory_order_relaxed); }
void setSidechain(const float* interleaved, int32_t frames) override { scBuf_ = interleaved; scFrames_ = frames; }
@@ -125,36 +286,85 @@ public:
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
static const char* nm[] = { "Thresh", "Ratio", "Attack", "Release", "Makeup", "Knee", "Mix",
- "Lookahead", "Detection", "AutoRelease", "AutoGain", "Range", "Character", "SC HP", "SC LP", "SC Listen" };
+ "Lookahead", "Detection", "AutoRelease", "AutoGain", "Range", "Character", "SC HP", "SC LP", "SC Listen",
+ "SC Gain", "Hold", "SC Q", "External Key", "Stereo Link" };
return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
float paramMin(int32_t i) const override {
switch (i) { case Threshold: return -60.0f; case Ratio: return 1.0f; case Attack: return 0.1f; case Release: return 5.0f;
- case ScHP: return 20.0f; case ScLP: return 200.0f; default: return 0.0f; }
+ case ScHP: return 20.0f; case ScLP: return 200.0f; case ScGain: return -24.0f; case ScQ: return 0.5f; default: return 0.0f; }
}
float paramMax(int32_t i) const override {
switch (i) { case Threshold: return 0.0f; case Ratio: return 20.0f; case Attack: return 100.0f; case Release: return 1000.0f;
case Makeup: return 24.0f; case Knee: return 24.0f; case Mix: return 100.0f; case Lookahead: return 10.0f;
- case Range: return 48.0f; case Character: return 4.0f; case ScHP: return 2000.0f; case ScLP: return 20000.0f; default: return 1.0f; }
+ case Detection: return 2.0f; case Range: return 48.0f; case Character: return 4.0f; case ScHP: return 2000.0f;
+ case ScLP: return 20000.0f; case ScGain: return 24.0f; case Hold: return 500.0f; case ScQ: return 4.0f; default: 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(v, std::memory_order_relaxed); }
Compressor() {
- p_[Threshold].store(-18.0f); p_[Ratio].store(3.0f); p_[Attack].store(10.0f); p_[Release].store(120.0f); p_[Makeup].store(0.0f);
- p_[Knee].store(6.0f); p_[Mix].store(100.0f); p_[Lookahead].store(0.0f); p_[Detection].store(0.0f);
- p_[AutoRelease].store(0.0f); p_[AutoGain].store(0.0f); p_[Range].store(48.0f); p_[Character].store(0.0f);
- p_[ScHP].store(20.0f); p_[ScLP].store(20000.0f); p_[ScListen].store(0.0f);
+ set(Threshold, -18.0f); set(Ratio, 3.0f); set(Attack, 10.0f); set(Release, 120.0f); set(Makeup, 0.0f);
+ set(Knee, 6.0f); set(Mix, 100.0f); set(Lookahead, 0.0f); set(Detection, 0.0f);
+ set(AutoRelease, 0.0f); set(AutoGain, 0.0f); set(Range, 48.0f); set(Character, 0.0f);
+ set(ScHP, 20.0f); set(ScLP, 20000.0f); set(ScListen, 0.0f);
+ set(ScGain, 0.0f); set(Hold, 0.0f); set(ScQ, 0.7071f); set(External, 1.0f); set(StereoLink, 1.0f);
+ std::fill(std::begin(envRing_), std::end(envRing_), -120.0f);
setSampleRate(44100.0, 0);
}
private:
static constexpr double kPi = 3.14159265358979323846;
- double sr_ = 44100.0;
- float env_ = 0.0f, rmsE_ = 0.0f, grPrev_ = 0.0f;
- float hpS_ = 0.0f, hpPrev_ = 0.0f, lpS_ = 0.0f;
+
+ // A TPT (Zavalishin) state-variable filter: one set of coefficients, HP or LP out.
+ struct Svf {
+ float g = 0, k = 1.414f, a1 = 0, a2 = 0, a3 = 0;
+ static Svf make(double hz, double q, double sr) {
+ Svf s;
+ s.g = static_cast<float>(std::tan(kPi * std::clamp(hz, 5.0, sr * 0.45) / sr));
+ s.k = static_cast<float>(1.0 / std::max(0.1, q));
+ s.a1 = 1.0f / (1.0f + s.g * (s.g + s.k)); s.a2 = s.g * s.a1; s.a3 = s.g * s.a2;
+ return s;
+ }
+ };
+ struct SvfState {
+ float ic1 = 0, ic2 = 0;
+ float tick(const Svf& f, float x, bool highPass) {
+ const float v3 = x - ic2;
+ const float v1 = f.a1 * ic1 + f.a2 * v3;
+ const float v2 = ic2 + f.a2 * ic1 + f.a3 * v3;
+ ic1 = 2.0f * v1 - ic1; ic2 = 2.0f * v2 - ic2;
+ return highPass ? x - f.k * v1 - v2 : v2;
+ }
+ };
+ struct Chan {
+ SvfState hp, lp;
+ float env = 0.0f, rmsE = 0.0f, grPrev = 0.0f;
+ int hold = 0;
+ };
+
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ bool on(int i) const { return get(i) >= 0.5f; }
+ void set(int i, float v) { p_[i].store(v, std::memory_order_relaxed); }
+ int charIndex() const { return std::clamp(static_cast<int>(std::lround(getParam(Character))), 0, kNumChars - 1); }
+ int detectionMode() const { return std::clamp(static_cast<int>(std::lround(getParam(Detection))), 0, 2); }
+ int lookaheadSamples() const {
+ return std::clamp(static_cast<int>(getParam(Lookahead) * 0.001 * sr_), 0, std::max(0, laSize_ - 1));
+ }
+ static float dbToLin(float db) { return std::exp(db * 0.11512925f); }
+ static float decayPeak(float held, float now) { return now > held ? now : held * 0.86f; }
+
+ double sr_ = 44100.0, spb_ = 0.0;
+ Chan ch_[2];
std::vector<float> laBuf_; int laSize_ = 0, laW_ = 0;
+ double inMs_ = 0.0, outMs_ = 0.0, cpuS_ = 0.0;
+ int envDecim_ = 44, envCnt_ = 0;
+ float envIn_ = 0.0f, envGr_ = 0.0f;
+ float envRing_[kEnvN] = {}, grRing_[kEnvN] = {}, keyRing_[kKeyN] = {};
+ std::atomic<int> envW_{0}, keyW_{0};
std::atomic<float> gr_{0.0f};
+ std::atomic<float> inPkA_{0}, outPkA_{0}, keyPkA_{0}, inRmsA_{0}, outRmsA_{0}, extA_{0},
+ atkA_{0}, relA_{0}, srA_{44100.0f}, bpmA_{0}, cpuA_{0};
std::atomic<int32_t> scTrackId_{-1};
const float* scBuf_ = nullptr; int32_t scFrames_ = 0;
std::atomic<float> p_[kNumParams] = {};
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index 2b41958e..e057c151 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -775,7 +775,12 @@ void Engine::deviceSetParam(int32_t trackId, int32_t deviceIndex, int32_t paramI
// A modulated param's UI edit sets the stored base (the atomic is driven by the
// modulation each block); set the atomic too for immediate feedback.
routeCvBaseEdit(0, trackId, deviceIndex, paramIndex, value);
- if (auto* d = deviceAt(trackId, deviceIndex)) d->setParam(paramIndex, value);
+ if (auto* d = deviceAt(trackId, deviceIndex)) {
+ // A param can change the device's latency (the Compressor's look-ahead): keep PDC in step.
+ const int32_t latBefore = d->latencySamples();
+ d->setParam(paramIndex, value);
+ if (d->latencySamples() != latBefore) recomputePdc();
+ }
}
float Engine::deviceGainReduction(int32_t trackId, int32_t deviceIndex) const {
auto* d = deviceAt(trackId, deviceIndex);
diff --git a/src/native/nota.engine/src/Reverb.h b/src/native/nota.engine/src/Reverb.h
index 9928c093..19a284f3 100644
--- a/src/native/nota.engine/src/Reverb.h
+++ b/src/native/nota.engine/src/Reverb.h
@@ -1,16 +1,25 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in reverb (mockup 2h) — an extended Freeverb (Schroeder-Moorer): 8 damped comb
-// filters + 4 allpasses per channel on a variable-size, modulated fractional delay line.
-// Two honest bands: SPACE (pre-delay · size · diffusion) and TONE (low cut · high cut ·
-// width), plus decay (RT60), HF damping, a chorus-like tail modulation, four algorithms
-// (Hall/Room/Plate/Chamber), Freeze (infinite tail) and dry/wet + output trim.
+// Built-in reverb ("Nota Reverb" — almanac update) on the Chamber frame — an extended
+// Freeverb (Schroeder-Moorer): 8 damped comb filters + 4 allpasses per channel on a
+// variable-size, modulated fractional delay line, fed through a pre-delay line and a short
+// input diffuser. SPACE (pre-delay · size · diffusion · early reflections) and TONE (low
+// cut · high cut · width), a decay calibrated as a true RT60, HF damping, a chorus-like
+// modulation on the tail (or on the early part only), four algorithms (Hall / Room /
+// Plate / Chamber), Vintage (a band-limited, 12-bit early-digital colour), Freeze
+// (infinite tail, input muted), Kill tail, and an output stage (dry level · dry/wet ·
+// width · bass mono · wet only · output trim).
+//
+// The input diffuser delays the tail by a fixed group delay; Latency Comp shortens the
+// pre-delay by that much so the tail starts where the pre-delay says (as far as the
+// pre-delay allows — it cannot go below zero).
//
// All params are normalized 0..1 (denormalized in process()); persist/clone/automation
-// are generic through the base Device. Buffers are allocated at max size on the message
-// thread in setSampleRate, so process() never allocates. Freeverb is public-domain
-// (Jezar at Dreampoint); the extensions & tuning are Nota's own.
+// are generic through the base Device. Param order is the persisted layout — APPEND ONLY.
+// Buffers are allocated at max size on the message thread in setSampleRate, so process()
+// never allocates. Freeverb is public-domain (Jezar at Dreampoint); the extensions &
+// tuning are Nota's own.
#pragma once
@@ -18,18 +27,32 @@
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
#include <vector>
namespace nota {
class Reverb : public Device {
public:
+ static constexpr int kEr = 8; // early-reflection taps
+
enum {
Decay = 0, HFDamp, PreDelay, Size, Diffusion, LowCut, HighCut, Width,
- ModRate, ModDepth, Algorithm, Freeze, DryWet, Output, kNumParams
+ ModRate, ModDepth, Algorithm, Freeze, DryWet, Output,
+ // ---- appended for the almanac update — keep the order, append only ----
+ DryLevel, EarlyRefl, ModOnTail, Vintage, BassMono, WetOnly, LatencyComp, kNumParams
};
+ // Scope telemetry layout (read by the card).
+ enum {
+ S_WetPk = 0, S_OutL, S_OutR, S_Cpu, S_SampleRate, S_Latency, S_Rt60, S_PreMs,
+ S_DiffuseSmp, S_Frozen, S_EarlyOn, kScope
+ };
+ // deviceAction ids.
+ enum { A_KillTail = 0 };
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
sr_ = sr > 0 ? sr : 44100.0;
@@ -43,41 +66,55 @@ public:
allpL_[a].init(static_cast<int>(kAllpassTuning[a] * scale) + 2);
allpR_[a].init(static_cast<int>((kAllpassTuning[a] + kStereoSpread) * scale) + 2);
}
- preL_.assign(static_cast<int>(sr_ * 0.2) + 2, 0.0f);
+ // Pre-delay (200 ms) + the furthest early reflection (~110 ms) + modulation headroom.
+ preL_.assign(static_cast<int>(sr_ * 0.34) + 4, 0.0f);
preR_.assign(preL_.size(), 0.0f);
preW_ = 0;
+ for (int k = 0; k < kInAp; ++k) inAp_[k].resize(static_cast<int>(sr_ * kInApSec[k]));
+ hpL_ = hpR_ = hpPrevL_ = hpPrevR_ = lpL_ = lpR_ = vlp_ = monoS_ = 0.0f;
+ srA_.store(static_cast<float>(sr_), std::memory_order_relaxed);
}
void process(float* buf, int32_t frames) override {
- const float decay = clamp01(p_[Decay]);
- const float damp = clamp01(p_[HFDamp]);
- const float preMs = clamp01(p_[PreDelay]) * 200.0f;
- const float size = 0.55f + clamp01(p_[Size]) * (kMaxSize - 0.55f);
- const float diff = 0.4f + clamp01(p_[Diffusion]) * 0.35f; // allpass gain
- const float width = clamp01(p_[Width]);
- const float modHz = expMap(clamp01(p_[ModRate]), 0.05, 5.0);
- const float modD = clamp01(p_[ModDepth]) * 12.0f * (float)srScale_; // samples
- const int algo = (int)std::lround(clamp01(p_[Algorithm]) * 3.0f);
- const bool freeze = p_[Freeze].load(std::memory_order_relaxed) > 0.5f;
- const float wet = clamp01(p_[DryWet]);
- const float dry = 1.0f - wet;
- const float outG = clamp01(p_[Output]) * 2.0f;
-
- const float feedback = freeze ? 1.0f : (0.72f + decay * 0.265f);
+ if (frames <= 0 || preL_.size() < 4) return;
+ const auto t0 = std::chrono::steady_clock::now();
+ if (kill_.exchange(false, std::memory_order_relaxed)) wipe();
+
+ const bool freeze = on(Freeze);
+ const bool early = on(EarlyRefl) && !freeze;
+ const bool modTail = on(ModOnTail);
+ const bool vintage = on(Vintage);
+ const bool wetOnly = on(WetOnly);
+
+ const double rt60 = expMap(clamp01(Decay), 0.2, 12.0);
+ const float damp = clamp01(HFDamp);
+ const float preMs = clamp01(PreDelay) * 200.0f;
+ const float sizeV = clamp01(Size);
+ const float size = 0.55f + sizeV * (kMaxSize - 0.55f);
+ const float diffV = clamp01(Diffusion);
+ const float diff = 0.4f + diffV * 0.35f; // output allpass gain
+ const float width = clamp01(Width);
+ const float modHz = static_cast<float>(expMap(clamp01(ModRate), 0.05, 5.0));
+ const float modD = clamp01(ModDepth) * (vintage ? 18.0f : 12.0f) * static_cast<float>(srScale_); // samples
+ const int algo = static_cast<int>(std::lround(clamp01(Algorithm) * 3.0f));
+ const float mix = wetOnly ? 1.0f : clamp01(DryWet);
+ const float dryG = wetOnly ? 0.0f : (1.0f - mix) * dryGain(clamp01(DryLevel));
+ const float outG = clamp01(Output) * 2.0f;
+
const float damp1 = freeze ? 0.0f : damp * 0.4f, damp2 = 1.0f - damp1;
const float inGain = freeze ? 0.0f : 0.015f;
const float algoScale = kAlgoScale[algo];
+ // Input diffusion: denser for the plate, the algorithm with no room to speak of.
+ const float inApG = std::min(0.75f, 0.25f + diffV * 0.45f + (algo == 2 ? 0.1f : 0.0f));
// Tone: one-pole HP (low cut) + LP (high cut) coefficients on the wet path.
- const double lc = expMap(clamp01(p_[LowCut]), 20.0, 1000.0);
- const double hc = expMap(clamp01(p_[HighCut]), 1000.0, 20000.0);
- const float hpCoef = (float)std::exp(-2.0 * kPi * lc / sr_);
- const float lpCoef = (float)(1.0 - std::exp(-2.0 * kPi * hc / sr_));
-
- for (int c = 0; c < kCombs; ++c) { combL_[c].set(feedback, damp1, damp2); combR_[c].set(feedback, damp1, damp2); }
- for (int a = 0; a < kAllpasses; ++a) { allpL_[a].g = diff; allpR_[a].g = diff; }
- const int preSamp = std::clamp((int)(preMs * 0.001 * sr_), 0, (int)preL_.size() - 1);
- const double modInc = modHz / sr_;
+ const double lc = expMap(clamp01(LowCut), 20.0, 1000.0);
+ const double hc = expMap(clamp01(HighCut), 1000.0, 20000.0);
+ const float hpCoef = static_cast<float>(std::exp(-2.0 * kPi * lc / sr_));
+ const float lpCoef = static_cast<float>(1.0 - std::exp(-2.0 * kPi * hc / sr_));
+ const float vintC = onePole(7000.0);
+ const float monoC = onePole(expMap(clamp01(BassMono), 30.0, 500.0));
+ const bool monoOn = clamp01(BassMono) > 0.001f;
// Comb delay length = kCombTuning[c] * srScale * (size * algoScale). Size and
// Algorithm change per block; jumping the read pointer inside a high-feedback loop
@@ -87,66 +124,171 @@ public:
const float spanTarget = size * algoScale;
if (span_ < 0.0f) span_ = spanTarget;
+ // Decay is an honest RT60: each comb loses 60 dB in rt60 seconds, whatever its length.
+ for (int c = 0; c < kCombs; ++c) {
+ const double loopSec = kCombTuning[c] * srScale_ * spanTarget / sr_;
+ const float fb = freeze ? 1.0f : static_cast<float>(std::min(0.995, std::pow(10.0, -3.0 * loopSec / rt60)));
+ combL_[c].set(fb, damp1, damp2); combR_[c].set(fb, damp1, damp2);
+ }
+ for (int a = 0; a < kAllpasses; ++a) { allpL_[a].g = diff; allpR_[a].g = diff; }
+
+ // Pre-delay, less the input diffuser's group delay when compensated.
+ int diffSmp = 0; for (const auto& a : inAp_) diffSmp += a.n;
+ const int preLen = static_cast<int>(preL_.size());
+ const double preSmp = preMs * 0.001 * sr_;
+ const double effPre = std::max(0.0, preSmp - (on(LatencyComp) ? diffSmp : 0));
+
+ // Early reflections: taps on the pre-delay line after the pre-delay, spaced by the
+ // algorithm and the size; even taps lean left, odd ones right.
+ const double erScale = kErScale[algo] * (0.5 + sizeV * 0.8);
+ for (int k = 0; k < kEr; ++k)
+ erSmp_[k] = std::min(kErMs[k] * erScale * 0.001 * sr_, 0.11 * sr_);
+
+ const double modInc = modHz / sr_;
+ float wetPk = 0.0f, outPkL = 0.0f, outPkR = 0.0f;
+
for (int32_t i = 0; i < frames; ++i) {
const float l = san(buf[i * 2]), r = san(buf[i * 2 + 1]);
span_ += (spanTarget - span_) * kSpanGlide;
- // Pre-delay (feed the reverb a delayed copy of the input). Write first so a
- // zero pre-delay reads back the current sample (passthrough), not a full buffer.
+ // Write first so a zero pre-delay reads back the current sample (passthrough).
preL_[preW_] = l; preR_[preW_] = r;
- int pr = preW_ - preSamp; if (pr < 0) pr += (int)preL_.size();
- const float pl = preL_[pr], prr = preR_[pr];
- if (++preW_ >= (int)preL_.size()) preW_ = 0;
- const float input = (pl + prr) * inGain;
- const float lfo = std::sin(kTwoPi * modPhase_); modPhase_ += modInc; if (modPhase_ >= 1.0) modPhase_ -= 1.0;
- const float mod = lfo * modD;
+ const float lfo = std::sin(static_cast<float>(kTwoPi * modPhase_));
+ modPhase_ += modInc; if (modPhase_ >= 1.0) modPhase_ -= 1.0;
+ // Mod on tail: the comb lines wobble. Off: the early part (pre-delay read) wobbles
+ // instead and the tail stays still — never reading ahead of the write head.
+ const float combMod = modTail ? lfo * modD : 0.0f;
+ const double preMod = modTail ? 0.0 : (lfo * 0.5f + 0.5f) * modD;
+
+ const float pl = readPre(preL_, effPre + preMod), prr = readPre(preR_, effPre + preMod);
+
+ float input = (pl + prr) * inGain;
+ if (vintage) { vlp_ = san(vlp_ + vintC * (input - vlp_)); input = vlp_; }
+ for (auto& a : inAp_) input = a.tick(input, inApG);
float outL = 0.0f, outR = 0.0f;
for (int c = 0; c < kCombs; ++c) {
- float dl = kCombTuning[c] * (float)srScale_ * span_;
- outL += combL_[c].process(input, dl + mod);
- outR += combR_[c].process(input, dl - mod);
+ const float dl = kCombTuning[c] * static_cast<float>(srScale_) * span_;
+ outL += combL_[c].process(input, dl + combMod);
+ outR += combR_[c].process(input, dl - combMod);
}
for (int a = 0; a < kAllpasses; ++a) { outL = allpL_[a].process(outL); outR = allpR_[a].process(outR); }
+ if (early) {
+ float eL = 0.0f, eR = 0.0f;
+ for (int k = 0; k < kEr; ++k) {
+ const double d = effPre + preMod + erSmp_[k];
+ const float s = (readPre(preL_, d) + readPre(preR_, d)) * 0.5f * kErGain[k] * kErLevel;
+ if (k & 1) { eR += s; eL += s * 0.35f; } else { eL += s; eR += s * 0.35f; }
+ }
+ outL += eL; outR += eR;
+ }
+ if (++preW_ >= preLen) preW_ = 0;
+
// Tone filters on the wet signal.
hpL_ = san(hpCoef * (hpL_ + outL - hpPrevL_)); hpPrevL_ = san(outL); outL = hpL_;
hpR_ = san(hpCoef * (hpR_ + outR - hpPrevR_)); hpPrevR_ = san(outR); outR = hpR_;
lpL_ = san(lpL_ + lpCoef * (outL - lpL_)); outL = lpL_;
lpR_ = san(lpR_ + lpCoef * (outR - lpR_)); outR = lpR_;
- // Stereo width (mid/side).
- const float mid = (outL + outR) * 0.5f, side = (outL - outR) * 0.5f * (0.2f + width * 1.8f);
+ // Stereo width (mid/side), then bass mono: high-pass the side.
+ const float mid = (outL + outR) * 0.5f;
+ float side = (outL - outR) * 0.5f * (0.2f + width * 1.8f);
+ if (monoOn) { monoS_ = san(monoS_ + monoC * (side - monoS_)); side -= monoS_; }
outL = mid + side; outR = mid - side;
// Final guard: a runaway (but finite) loop build-up here would blast the
// speakers. A hard clamp bounds it but the clip itself sounds metallic, so
// soft-saturate the wet contribution instead: transparent at normal levels,
// a smooth tanh knee only when the tail overshoots (dry path stays clean).
- float wl = softClip(san(outL * wet)), wr = softClip(san(outR * wet));
- buf[i * 2] = (wl + l * dry) * outG;
- buf[i * 2 + 1] = (wr + r * dry) * outG;
+ float wl = softClip(san(outL * mix)), wr = softClip(san(outR * mix));
+ if (vintage) { wl = std::round(wl * 2048.0f) / 2048.0f; wr = std::round(wr * 2048.0f) / 2048.0f; }
+ const float oL = (wl + l * dryG) * outG, oR = (wr + r * dryG) * outG;
+ buf[i * 2] = oL; buf[i * 2 + 1] = oR;
+
+ wetPk = std::max(wetPk, std::max(std::fabs(wl), std::fabs(wr)));
+ outPkL = std::max(outPkL, std::fabs(oL)); outPkR = std::max(outPkR, std::fabs(oR));
}
+
+ // ---- telemetry -----------------------------------------------------------
+ mWet_.store(decayPeak(mWet_.load(std::memory_order_relaxed), wetPk), std::memory_order_relaxed);
+ mOutL_.store(decayPeak(mOutL_.load(std::memory_order_relaxed), outPkL), std::memory_order_relaxed);
+ mOutR_.store(decayPeak(mOutR_.load(std::memory_order_relaxed), outPkR), std::memory_order_relaxed);
+ rt60A_.store(freeze ? -1.0f : static_cast<float>(rt60), std::memory_order_relaxed);
+ preA_.store(static_cast<float>(effPre * 1000.0 / sr_), std::memory_order_relaxed);
+ diffA_.store(static_cast<float>(diffSmp), std::memory_order_relaxed);
+ erOnA_.store(early ? 1.0f : 0.0f, std::memory_order_relaxed);
+ srA_.store(static_cast<float>(sr_), std::memory_order_relaxed);
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store(static_cast<float>(cpuS_), std::memory_order_relaxed);
}
+ // ---- identity / params -------------------------------------------------------
const char* displayName() const override { return "Nota Reverb"; }
int32_t builtinKind() const override { return 2; }
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
static const char* nm[] = { "Decay", "HF Damp", "Pre-Delay", "Size", "Diffusion", "Low Cut",
- "High Cut", "Width", "Mod Rate", "Mod Depth", "Algorithm", "Freeze", "Dry/Wet", "Output" };
+ "High Cut", "Width", "Mod Rate", "Mod Depth", "Algorithm", "Freeze", "Dry/Wet", "Output",
+ "Dry Level", "Early Refl", "Mod on Tail", "Vintage", "Bass Mono", "Wet Only", "Latency Comp" };
return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
float paramMin(int32_t) const override { return 0.0f; }
float paramMax(int32_t) 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(v, std::memory_order_relaxed); }
+ 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); }
+
+ // Nothing is added to the dry path — the wet is the effect itself.
+ int32_t latencySamples() const override { return 0; }
+
+ void deviceAction(int32_t id, int32_t, float) override {
+ if (id == A_KillTail) kill_.store(true, std::memory_order_relaxed);
+ }
+
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples < kScope) return 0;
+ out[S_WetPk] = mWet_.load(std::memory_order_relaxed);
+ out[S_OutL] = mOutL_.load(std::memory_order_relaxed);
+ out[S_OutR] = mOutR_.load(std::memory_order_relaxed);
+ out[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ out[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ out[S_Latency] = static_cast<float>(latencySamples());
+ out[S_Rt60] = rt60A_.load(std::memory_order_relaxed);
+ out[S_PreMs] = preA_.load(std::memory_order_relaxed);
+ out[S_DiffuseSmp] = diffA_.load(std::memory_order_relaxed);
+ out[S_Frozen] = getParam(Freeze) >= 0.5f ? 1.0f : 0.0f;
+ out[S_EarlyOn] = erOnA_.load(std::memory_order_relaxed);
+ return kScope;
+ }
+
+ // id 0 — a one-line summary of what the reverb is doing now (the card's status strip,
+ // and get_device_text over MCP).
+ std::string deviceText(int32_t id) const override {
+ if (id != 0) return {};
+ static const char* algo[4] = { "Hall", "Room", "Plate", "Chamber" };
+ const int a = static_cast<int>(std::lround(std::clamp(getParam(Algorithm), 0.0f, 1.0f) * 3.0f));
+ char b[256];
+ if (getParam(Freeze) >= 0.5f) {
+ std::snprintf(b, sizeof b, "Freeze: %s tail held, input muted - damp %.0f %% - mix %.0f %%",
+ algo[a], getParam(HFDamp) * 100.0f, getParam(DryWet) * 100.0f);
+ } else {
+ std::snprintf(b, sizeof b, "%s - RT60 %.2f s - pre %.0f ms - diffuse %.0f %% - mix %.0f %%%s%s",
+ algo[a], expMap(getParam(Decay), 0.2, 12.0), getParam(PreDelay) * 200.0f,
+ getParam(Diffusion) * 100.0f, getParam(WetOnly) >= 0.5f ? 100.0f : getParam(DryWet) * 100.0f,
+ getParam(EarlyRefl) >= 0.5f ? " - early reflections" : "",
+ getParam(Vintage) >= 0.5f ? " - vintage" : "");
+ }
+ return std::string(b);
+ }
Reverb() {
set(Decay, 0.55f); set(HFDamp, 0.5f); set(PreDelay, 0.1f); set(Size, 0.6f); set(Diffusion, 0.6f);
set(LowCut, 0.0f); set(HighCut, 0.85f); set(Width, 0.6f); set(ModRate, 0.3f); set(ModDepth, 0.25f);
set(Algorithm, 0.0f); set(Freeze, 0.0f); set(DryWet, 0.3f); set(Output, 0.5f);
+ set(DryLevel, 0.70711f); set(EarlyRefl, 1.0f); set(ModOnTail, 1.0f); set(Vintage, 0.0f);
+ set(BassMono, 0.0f); set(WetOnly, 0.0f); set(LatencyComp, 1.0f);
setSampleRate(44100.0, 0);
}
@@ -157,7 +299,9 @@ private:
static constexpr float kSpanGlide = 0.002f; // per-sample delay-length smoothing (~11 ms @ 44.1k)
- static float clamp01(const std::atomic<float>& a) { return std::clamp(a.load(std::memory_order_relaxed), 0.0f, 1.0f); }
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ bool on(int i) const { return get(i) >= 0.5f; }
+ float clamp01(int i) const { return std::clamp(get(i), 0.0f, 1.0f); }
static float san(float x) { return std::isfinite(x) ? x : 0.0f; }
// Transparent below |x| = 1.2, then a smooth tanh knee bounded to ±2.2 — slope-continuous
// at the threshold so a runaway tail rounds off gracefully instead of clipping metallically.
@@ -168,12 +312,36 @@ private:
}
void set(int i, float v) { p_[i].store(v, std::memory_order_relaxed); }
static double expMap(double v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp(v, 0.0, 1.0)); }
+ // Dry trim: 0 dB at 1/√2, up to +6 dB at the top, silent at 0.
+ static float dryGain(float v) { return 2.0f * v * v; }
+ static float decayPeak(float held, float now) { return now > held ? now : held * 0.82f; }
+ float onePole(double hz) const { return static_cast<float>(1.0 - std::exp(-kTwoPi * std::clamp(hz, 5.0, sr_ * 0.45) / sr_)); }
+
+ // Fractional read `delay` samples behind the pre-delay write head (0 = the sample just written).
+ float readPre(const std::vector<float>& b, double delay) const {
+ const int n = static_cast<int>(b.size());
+ double rp = preW_ - std::clamp(delay, 0.0, static_cast<double>(n) - 2.0);
+ if (rp < 0) rp += n;
+ const int i0 = static_cast<int>(rp); const float frac = static_cast<float>(rp - i0);
+ int i1 = i0 + 1; if (i1 >= n) i1 -= n;
+ return b[i0] + (b[i1] - b[i0]) * frac;
+ }
+
+ void wipe() {
+ for (int c = 0; c < kCombs; ++c) { combL_[c].wipe(); combR_[c].wipe(); }
+ for (int a = 0; a < kAllpasses; ++a) { allpL_[a].wipe(); allpR_[a].wipe(); }
+ for (auto& a : inAp_) a.wipe();
+ std::fill(preL_.begin(), preL_.end(), 0.0f);
+ std::fill(preR_.begin(), preR_.end(), 0.0f);
+ hpL_ = hpR_ = hpPrevL_ = hpPrevR_ = lpL_ = lpR_ = vlp_ = monoS_ = 0.0f;
+ }
// Damped comb on a fractional delay line (variable length + modulation).
struct Comb {
std::vector<float> buf; int size = 1, w = 0;
float store = 0.0f, fb = 0.7f, damp1 = 0.5f, damp2 = 0.5f;
void init(int n) { size = std::max(4, n); buf.assign(size, 0.0f); w = 0; store = 0.0f; }
+ void wipe() { std::fill(buf.begin(), buf.end(), 0.0f); store = 0.0f; }
void set(float f, float d1, float d2) { fb = f; damp1 = d1; damp2 = d2; }
float process(float in, float delay) {
// Reject non-finite input so a NaN upstream can't seed the loop.
@@ -195,6 +363,7 @@ private:
struct Allpass {
std::vector<float> buf; int size = 1, idx = 0; float g = 0.5f;
void init(int n) { size = std::max(2, n); buf.assign(size, 0.0f); idx = 0; }
+ void wipe() { std::fill(buf.begin(), buf.end(), 0.0f); }
float process(float in) {
if (!std::isfinite(in)) in = 0.0f;
const float bufout = std::isfinite(buf[idx]) ? buf[idx] : 0.0f;
@@ -206,19 +375,44 @@ private:
return std::isfinite(out) ? out : 0.0f;
}
};
+ // A Schroeder allpass for the input diffuser (lossless; its length is its group delay).
+ struct DiffAp {
+ std::vector<float> z; int n = 1, w = 0;
+ void resize(int len) { n = std::max(1, len); z.assign(n, 0.0f); w = 0; }
+ void wipe() { std::fill(z.begin(), z.end(), 0.0f); }
+ float tick(float x, float g) {
+ const float d = z[w];
+ float v = x + g * d;
+ if (!std::isfinite(v)) v = 0.0f;
+ z[w] = v; if (++w >= n) w = 0;
+ return d - g * v;
+ }
+ };
- static constexpr int kCombs = 8, kAllpasses = 4, kStereoSpread = 23;
+ static constexpr int kCombs = 8, kAllpasses = 4, kStereoSpread = 23, kInAp = 4;
static constexpr int kCombTuning[kCombs] = {1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617};
static constexpr int kAllpassTuning[kAllpasses] = {556, 441, 341, 225};
+ static constexpr double kInApSec[kInAp] = {0.00083, 0.00121, 0.00211, 0.00297}; // ≈ 7.1 ms in all
// Hall (big), Room (small), Plate (bright/dense), Chamber (mid).
static constexpr float kAlgoScale[4] = {1.0f, 0.62f, 0.82f, 0.9f};
+ // Early-reflection pattern (ms at scale 1) and how the algorithm stretches it: a hall's
+ // walls are far apart, a plate's "reflections" are a tight cluster.
+ static constexpr double kErMs[kEr] = {7.3, 11.9, 16.1, 23.4, 29.7, 37.9, 47.3, 61.1};
+ static constexpr float kErGain[kEr] = {1.0f, 0.78f, 0.86f, 0.62f, 0.66f, 0.5f, 0.42f, 0.34f};
+ static constexpr double kErScale[4] = {1.0, 0.45, 0.28, 0.7};
+ static constexpr float kErLevel = 0.32f;
double sr_ = 44100.0, srScale_ = 1.0, modPhase_ = 0.0;
float span_ = -1.0f; // smoothed size*algoScale; <0 = prime to target on first block
Comb combL_[kCombs], combR_[kCombs];
Allpass allpL_[kAllpasses], allpR_[kAllpasses];
+ DiffAp inAp_[kInAp];
std::vector<float> preL_, preR_; int preW_ = 0;
- float hpL_ = 0, hpR_ = 0, hpPrevL_ = 0, hpPrevR_ = 0, lpL_ = 0, lpR_ = 0;
+ double erSmp_[kEr] = {};
+ float hpL_ = 0, hpR_ = 0, hpPrevL_ = 0, hpPrevR_ = 0, lpL_ = 0, lpR_ = 0, vlp_ = 0, monoS_ = 0;
+ double cpuS_ = 0.0;
+ std::atomic<bool> kill_{false};
+ std::atomic<float> mWet_{0}, mOutL_{0}, mOutR_{0}, cpuA_{0}, srA_{44100.0f}, rt60A_{0}, preA_{0}, diffA_{0}, erOnA_{0};
std::atomic<float> p_[kNumParams] = {};
};
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 009a1ed7..0250705e 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -3067,7 +3067,7 @@ Check(Rms(buf, frames) > 1e-4f, $"audio flows through EQ + Compressor chain (rms
// -- M6-3: Reverb / Delay / Utility built-ins --
int revDev = engine.AddBuiltinDevice(fxT, 2);
-Check(revDev >= 0 && engine.DeviceName(fxT, revDev) == "Nota Reverb" && engine.DeviceParamCount(fxT, revDev) == 14, "add built-in Reverb (14 params)");
+Check(revDev >= 0 && engine.DeviceName(fxT, revDev) == "Nota Reverb" && engine.DeviceParamCount(fxT, revDev) == 21, "add built-in Reverb (21 params)");
int delDev = engine.AddBuiltinDevice(fxT, 3);
Check(delDev >= 0 && engine.DeviceName(fxT, delDev) == "Nota Delay" && engine.DeviceParamCount(fxT, delDev) == 24, "add built-in Delay (24 params)");
int utilDev = engine.AddBuiltinDevice(fxT, 4);
@@ -3231,6 +3231,301 @@ Console.WriteLine("-- Nota Delay --");
Check(de.DeviceGetParam(dt, dd, Feedback) > 0.7f, $"automation drives Delay Feedback ({de.DeviceGetParam(dt, dd, Feedback):F2})");
}
+// ============================ Nota Compressor ===============================
+Console.WriteLine("-- Nota Compressor --");
+{
+ using var ce = new NotaEngine();
+ ce.SetBpm(120); ce.SetTimeSignature(4, 4);
+ int ct = ce.AddInstrumentTrack();
+ ce.AddMidiClip(ct, 0.0, 8.0);
+ ce.SetClipNotes(ct, 0, new[] { new NotaNote(48, 0.0, 8.0, 1.0f) });
+ int cd = ce.AddBuiltinDevice(ct, 1);
+ const int Thresh = 0, Ratio = 1, Attack = 2, Release = 3, Lookahead = 7, Detection = 8, Character = 12,
+ ScHP = 13, ScListen = 15, ScGain = 16, Hold = 17, ScQ = 18, External = 19, StereoLink = 20;
+ Check(cd >= 0 && ce.TrackDeviceBuiltinKind(ct, cd) == 1 && ce.DeviceName(ct, cd) == "Nota Compressor"
+ && ce.DeviceParamCount(ct, cd) == 21, $"add built-in Nota Compressor (kind 1, 21 params — got {ce.DeviceParamCount(ct, cd)})");
+ Check(ce.DeviceParamName(ct, cd, ScGain) == "SC Gain" && ce.DeviceParamName(ct, cd, Hold) == "Hold"
+ && ce.DeviceParamName(ct, cd, ScQ) == "SC Q" && ce.DeviceParamName(ct, cd, External) == "External Key"
+ && ce.DeviceParamName(ct, cd, StereoLink) == "Stereo Link", "Compressor names its appended params");
+ Check(ce.DeviceParamName(ct, cd, Thresh) == "Thresh" && ce.DeviceParamName(ct, cd, ScListen) == "SC Listen",
+ "Compressor keeps its original param names (old projects load)");
+ Check(ce.DeviceGetParam(ct, cd, External) >= 0.5f && ce.DeviceGetParam(ct, cd, StereoLink) >= 0.5f
+ && Math.Abs(ce.DeviceGetParam(ct, cd, ScQ) - 0.7071f) < 1e-3 && ce.DeviceParamMax(ct, cd, Detection) == 2f,
+ "Compressor appended params default to the old behaviour (external key on, linked, Butterworth) + Detection has Auto");
+ ce.DeviceSetParam(ct, cd, Hold, 42f);
+ Check(Math.Abs(ce.DeviceGetParam(ct, cd, Hold) - 42f) < 1e-4, "Compressor param set/get round-trips");
+ ce.DeviceSetParam(ct, cd, Hold, 0f);
+
+ float[] Render(int frames = 24000)
+ {
+ var b = new float[frames * 2];
+ ce.Seek(0); ce.Play(); ce.RenderOffline(b, frames); ce.StopTransport();
+ return b;
+ }
+ static bool Finite(float[] b) { foreach (var v in b) if (!float.IsFinite(v) || Math.Abs(v) > 8f) return false; return true; }
+
+ ce.DeviceSetParam(ct, cd, Thresh, 0f);
+ float open = Rms(Render(), 24000);
+ ce.DeviceSetParam(ct, cd, Thresh, -40f);
+ ce.DeviceSetParam(ct, cd, Ratio, 10f);
+ ce.DeviceSetParam(ct, cd, Attack, 1f);
+ ce.DeviceSetParam(ct, cd, Release, 50f);
+ var squashed = Render();
+ float sq = Rms(squashed, 24000);
+ float grNow = ce.DeviceGainReduction(ct, cd);
+ Check(Finite(squashed) && open > 1e-3f && sq < open * 0.5f && grNow > 3f,
+ $"Compressor pulls a loud note down (rms {sq:F4} vs {open:F4}, GR {grNow:F1} dB)");
+
+ // Every detector and voicing renders finite and still compresses.
+ for (int d = 0; d < 3; d++)
+ {
+ ce.DeviceSetParam(ct, cd, Detection, d);
+ var b = Render();
+ Check(Finite(b) && Rms(b, 24000) < open * 0.7f, $"Compressor detection {new[] { "Peak", "RMS", "Auto" }[d]} renders + compresses (rms {Rms(b, 24000):F4})");
+ }
+ ce.DeviceSetParam(ct, cd, Detection, 0f);
+ for (int c = 0; c < 5; c++)
+ {
+ ce.DeviceSetParam(ct, cd, Character, c);
+ var b = Render();
+ Check(Finite(b) && Rms(b, 24000) > 1e-4f, $"Compressor character {c} renders finite + audible");
+ }
+ ce.DeviceSetParam(ct, cd, Character, 0f);
+ ce.DeviceSetParam(ct, cd, StereoLink, 0f);
+ var unlinked = Render();
+ Check(Finite(unlinked) && Rms(unlinked, 24000) < open * 0.7f, "Compressor unlinked (dual mono) renders + compresses");
+ ce.DeviceSetParam(ct, cd, StereoLink, 1f);
+ ce.DeviceSetParam(ct, cd, Hold, 200f);
+ var held = Render();
+ Check(Finite(held) && Rms(held, 24000) > 1e-4f, "Compressor with Hold renders finite + audible");
+ ce.DeviceSetParam(ct, cd, Hold, 0f);
+
+ // Telemetry: levels, the envelope rings, the key samples.
+ var sc = new float[14 + 2 * 2048 + 2048];
+ int scn = ce.DeviceScope(ct, cd, sc, sc.Length);
+ double ringGr = 0; for (int i = 14 + 2048; i < 14 + 4096; i++) ringGr = Math.Max(ringGr, sc[i]);
+ double keyE = 0; for (int i = 14 + 4096; i < sc.Length; i++) keyE += sc[i] * sc[i];
+ Check(scn == sc.Length && sc[8] > 1000 && sc[0] > 0.01f && sc[2] > 0.001f && ringGr > 3 && keyE > 0,
+ $"Compressor scope reports levels, sample rate, the reduction envelope and the key (n {scn}, sr {sc[8]:0}, ring GR {ringGr:F1})");
+ Check(ce.DeviceScope(ct, cd, sc, 14) == 14, "Compressor scope returns just the telemetry when asked for 14 values");
+
+ // Look-ahead is reported as latency (PDC) and follows the param.
+ ce.DeviceSetParam(ct, cd, Lookahead, 5f);
+ int lat = ce.TrackLatencySamples(ct);
+ Check(Math.Abs(lat - 0.005 * sc[8]) <= 1.5, $"Compressor look-ahead reports its latency ({lat} smp at {sc[8]:0} Hz)");
+ ce.DeviceSetParam(ct, cd, Lookahead, 0f);
+ Check(ce.TrackLatencySamples(ct) == 0, "Compressor latency returns to 0 without look-ahead");
+
+ // Listen: the output is the key; a steep high-pass on a low note leaves little of it.
+ ce.DeviceSetParam(ct, cd, ScListen, 1f);
+ float keyOpen = Rms(Render(), 24000);
+ ce.DeviceSetParam(ct, cd, ScHP, 2000f);
+ ce.DeviceSetParam(ct, cd, ScQ, 0.7071f);
+ float keyCut = Rms(Render(), 24000);
+ Check(keyOpen > 1e-3f && keyCut < keyOpen * 0.5f, $"Listen monitors the key, and SC HP filters it ({keyCut:F4} vs {keyOpen:F4})");
+ ce.DeviceSetParam(ct, cd, ScListen, 0f);
+ ce.DeviceSetParam(ct, cd, ScHP, 20f);
+
+ // SC Gain drives the detector: less key, less reduction.
+ ce.DeviceSetParam(ct, cd, Thresh, -30f);
+ Render();
+ float grBase = ce.DeviceGainReduction(ct, cd);
+ ce.DeviceSetParam(ct, cd, ScGain, -18f);
+ Render();
+ float grLow = ce.DeviceGainReduction(ct, cd);
+ Check(grLow < grBase - 3, $"SC Gain lowers the reduction ({grLow:F1} vs {grBase:F1} dB)");
+ ce.DeviceSetParam(ct, cd, ScGain, 0f);
+
+ // External key: a loud source keys a silent target; External Key off falls back to self.
+ int src = ce.AddInstrumentTrack();
+ ce.AddMidiClip(src, 0.0, 8.0);
+ ce.SetClipNotes(src, 0, new[] { new NotaNote(36, 0.0, 8.0, 1.0f) });
+ int tgt = ce.AddAudioTrack(); // no audio of its own: only the key can drive it
+ int td = ce.AddBuiltinDevice(tgt, 1);
+ ce.DeviceSetParam(tgt, td, Thresh, -40f);
+ ce.DeviceSetParam(tgt, td, Ratio, 10f);
+ ce.DeviceSetParam(tgt, td, Attack, 1f);
+ ce.SetDeviceSidechainSource(tgt, td, src);
+ Render(32000);
+ float grExt = ce.DeviceGainReduction(tgt, td);
+ var xsc = new float[14 + 2 * 2048 + 2048];
+ ce.DeviceScope(tgt, td, xsc, xsc.Length);
+ double xkey = 0; for (int i = 14 + 4096; i < xsc.Length; i++) xkey += xsc[i] * xsc[i];
+ Check(xsc[12] > 0.5f && xkey > 1e-6, $"Compressor scope carries the external key for the card's spectrum (energy {xkey:E2})");
+ ce.DeviceSetParam(tgt, td, External, 0f);
+ Render(32000);
+ float grOwn = ce.DeviceGainReduction(tgt, td);
+ Check(grExt > 3 && grOwn < 0.5f, $"External Key switches the detector to the sidechain source ({grExt:F1} vs {grOwn:F1} dB)");
+ ce.DeviceSetParam(tgt, td, External, 1f);
+
+ // MCP: sidechain routing + the dynamics reading + the status line.
+ var dtools = new Nota.Mcp.Tools.DeviceTools(ce, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ dtools.SetDeviceSidechain(tgt, td, -1, tapPre: true).Wait();
+ var scr = dtools.GetDeviceSidechain(tgt, td).Result;
+ Check(scr.Accepts && scr.SourceTrackId == -1 && scr.TapPre, "MCP set/get_device_sidechain round-trips (source cleared, tap pre)");
+ dtools.SetDeviceSidechain(tgt, td, src, tapPre: false).Wait();
+ Check(dtools.GetDeviceSidechain(tgt, td).Result.SourceTrackId == src, "MCP set_device_sidechain routes the key source");
+ Render(32000);
+ var dyn = dtools.ReadDynamics(tgt, td).Result;
+ Check(dyn.GainReductionDb > 1 && dyn.ExternalKey && dyn.SampleRate > 1000 && dyn.Summary.Contains("threshold") && dyn.HitsLast2s >= 1,
+ $"MCP read_dynamics reports the reduction, external key and summary (GR {dyn.GainReductionDb:F1}, hits {dyn.HitsLast2s})");
+ string ctext = ce.DeviceText(tgt, td, 0);
+ Check(ctext.Contains("external key"), $"Compressor status text says the external key drives it (got '{ctext}')");
+
+ // Clone: duplicating the track keeps the appended params.
+ ce.DeviceSetParam(ct, cd, Hold, 33f);
+ int t2 = ce.DuplicateTrack(ct);
+ int cd2 = ce.TrackDeviceCount(t2) - 1;
+ Check(t2 > 0 && Math.Abs(ce.DeviceGetParam(t2, cd2, Hold) - 33f) < 1e-3, "duplicate track clones the Compressor's params");
+
+ // Automation: a device-param lane drives the threshold (lane values are the raw dB).
+ int lane = ce.AddAutomationLane(ct, AutomationTarget.DeviceParam, cd, Thresh);
+ Check(lane >= 0, "add Compressor Thresh automation lane");
+ ce.SetAutomationPoints(ct, lane, new[] { new AutomationPoint(0.0, -40f), new AutomationPoint(2.0, -6f) }); // raw dB
+ var ab = new float[4096 * 2];
+ ce.Seek(1.99); ce.Play(); ce.RenderOffline(ab, 4096); ce.StopTransport();
+ float thrAuto = ce.DeviceGetParam(ct, cd, Thresh);
+ Check(thrAuto > -12f, $"automation drives the Compressor threshold ({thrAuto:F1} dB)");
+}
+
+// ============================ Nota Reverb ===================================
+Console.WriteLine("-- Nota Reverb --");
+{
+ using var re = new NotaEngine();
+ re.SetBpm(120); re.SetTimeSignature(4, 4);
+ int rt = re.AddInstrumentTrack();
+ re.AddMidiClip(rt, 0.0, 4.0);
+ re.SetClipNotes(rt, 0, new[] { new NotaNote(60, 0.0, 0.25, 1.0f) });
+ int rd = re.AddBuiltinDevice(rt, 2);
+ const int Decay = 0, HFDamp = 1, PreDelay = 2, Size = 3, Algorithm = 10, Freeze = 11, DryWet = 12, Output = 13,
+ DryLevel = 14, EarlyRefl = 15, ModOnTail = 16, Vintage = 17, BassMono = 18, WetOnly = 19, LatencyComp = 20;
+ Check(rd >= 0 && re.TrackDeviceBuiltinKind(rt, rd) == 2 && re.DeviceParamCount(rt, rd) == 21, "add built-in Nota Reverb (kind 2, 21 params)");
+ Check(re.DeviceParamName(rt, rd, Decay) == "Decay" && re.DeviceParamName(rt, rd, Output) == "Output"
+ && re.DeviceParamName(rt, rd, DryLevel) == "Dry Level" && re.DeviceParamName(rt, rd, EarlyRefl) == "Early Refl"
+ && re.DeviceParamName(rt, rd, ModOnTail) == "Mod on Tail" && re.DeviceParamName(rt, rd, Vintage) == "Vintage"
+ && re.DeviceParamName(rt, rd, BassMono) == "Bass Mono" && re.DeviceParamName(rt, rd, WetOnly) == "Wet Only"
+ && re.DeviceParamName(rt, rd, LatencyComp) == "Latency Comp",
+ "Reverb keeps its 14 params in place and names the appended ones");
+ Check(re.DeviceParamDefault(rt, rd, EarlyRefl) > 0.5f && re.DeviceParamDefault(rt, rd, ModOnTail) > 0.5f
+ && re.DeviceParamDefault(rt, rd, Vintage) < 0.5f && re.DeviceParamDefault(rt, rd, WetOnly) < 0.5f,
+ "Reverb switch defaults (early reflections + mod on tail on, vintage + wet only off)");
+ re.DeviceSetParam(rt, rd, Size, 0.42f);
+ Check(Math.Abs(re.DeviceGetParam(rt, rd, Size) - 0.42f) < 1e-4, "Reverb param set/get round-trips");
+ re.DeviceSetParam(rt, rd, Size, 0.6f);
+
+ float[] Render(int frames = 60000)
+ {
+ var b = new float[frames * 2];
+ re.Seek(0); re.Play(); re.RenderOffline(b, frames); re.StopTransport();
+ return b;
+ }
+ static bool Finite(float[] b) { foreach (var s in b) if (!float.IsFinite(s) || Math.Abs(s) > 8f) return false; return true; }
+ static double Energy(float[] b, int from, int to)
+ {
+ double sum = 0; int n = 0;
+ for (int i = from * 2; i < Math.Min(b.Length, to * 2); i++) { sum += b[i] * b[i]; n++; }
+ return n > 0 ? Math.Sqrt(sum / n) : 0;
+ }
+
+ // Wet only: the tail is all that is left, and it rings on after the 125 ms note.
+ re.DeviceSetParam(rt, rd, WetOnly, 1f);
+ var wet = Render();
+ Check(Finite(wet) && Energy(wet, 20000, 40000) > 1e-4, $"Reverb tail rings on after the note (rms {Energy(wet, 20000, 40000):F4})");
+
+ // Decay is a real RT60: a long decay leaves far more in the late tail than a short one.
+ re.DeviceSetParam(rt, rd, Decay, 0.3f); // ≈ 0.7 s
+ var shortT = Render();
+ re.DeviceSetParam(rt, rd, Decay, 0.8f); // ≈ 5.2 s
+ var longT = Render();
+ Check(Energy(longT, 44000, 60000) > Energy(shortT, 44000, 60000) * 4,
+ $"Decay lengthens the tail ({Energy(longT, 44000, 60000):F5} vs {Energy(shortT, 44000, 60000):F5})");
+ re.DeviceSetParam(rt, rd, Decay, 0.55f);
+
+ // Early reflections change the first 100 ms; every algorithm and switch renders finite + audible.
+ re.DeviceSetParam(rt, rd, EarlyRefl, 0f);
+ var noEr = Render(12000);
+ re.DeviceSetParam(rt, rd, EarlyRefl, 1f);
+ var er = Render(12000);
+ double erDiff = 0; for (int i = 0; i < er.Length; i++) { double d = er[i] - noEr[i]; erDiff += d * d; }
+ Check(Math.Sqrt(erDiff / er.Length) > 1e-4, "Early reflections add to the early response");
+ for (int a = 0; a < 4; a++)
+ {
+ re.DeviceSetParam(rt, rd, Algorithm, a / 3f);
+ var b = Render(30000);
+ Check(Finite(b) && Energy(b, 10000, 30000) > 1e-5, $"Reverb algorithm {a} renders finite + audible");
+ }
+ re.DeviceSetParam(rt, rd, Algorithm, 0f);
+ foreach (var (p, v, what) in new[] { (ModOnTail, 0f, "mod on early part"), (Vintage, 1f, "vintage"),
+ (BassMono, 0.6f, "bass mono"), (HFDamp, 1f, "full damping"), (PreDelay, 1f, "200 ms pre-delay") })
+ {
+ float was = re.DeviceGetParam(rt, rd, p);
+ re.DeviceSetParam(rt, rd, p, v);
+ var b = Render(30000);
+ Check(Finite(b) && Energy(b, 10000, 30000) > 1e-5, $"Reverb {what} renders finite + audible (rms {Energy(b, 10000, 30000):F4})");
+ re.DeviceSetParam(rt, rd, p, was);
+ }
+
+ // Freeze holds the tail instead of letting it decay, and Kill tail empties it.
+ re.DeviceSetParam(rt, rd, Decay, 0.3f);
+ var nf = new float[8000 * 2];
+ re.Seek(0); re.Play(); re.RenderOffline(nf, 8000); // the note goes into the tank first…
+ re.DeviceSetParam(rt, rd, Freeze, 1f); // …then the tail is held
+ var held = new float[60000 * 2];
+ re.RenderOffline(held, 60000); re.StopTransport();
+ double early = Energy(held, 0, 10000), late = Energy(held, 50000, 60000);
+ Check(Finite(held) && early > 1e-5 && late > early * 0.5, $"Freeze holds the tail (late {late:F5} vs early {early:F5})");
+ re.DeviceAction(rt, rd, 0, 0, 0); // Kill tail
+ var killed = new float[8000 * 2];
+ re.RenderOffline(killed, 8000);
+ Check(Rms(killed, 8000) < 1e-5, $"Kill tail empties the reverb (rms {Rms(killed, 8000):F6})");
+ re.DeviceSetParam(rt, rd, Freeze, 0f);
+ re.DeviceSetParam(rt, rd, Decay, 0.55f);
+ re.DeviceSetParam(rt, rd, WetOnly, 0f);
+
+ // Dry Level trims the dry path.
+ re.DeviceSetParam(rt, rd, DryWet, 0f);
+ re.DeviceSetParam(rt, rd, DryLevel, 0.70711f);
+ float unity = Rms(Render(8000), 8000);
+ re.DeviceSetParam(rt, rd, DryLevel, 0f);
+ float silent = Rms(Render(8000), 8000);
+ Check(unity > 1e-3 && silent < unity * 0.05f, $"Reverb Dry Level trims the dry path ({silent:F4} vs {unity:F4})");
+ re.DeviceSetParam(rt, rd, DryLevel, 0.70711f);
+
+ // Latency Comp pulls the tail forward by the diffuser's group delay — a different signal.
+ re.DeviceSetParam(rt, rd, DryWet, 1f);
+ re.DeviceSetParam(rt, rd, PreDelay, 0.25f); // 50 ms, room to absorb the ~7 ms diffuser
+ re.DeviceSetParam(rt, rd, LatencyComp, 1f);
+ var comped = Render(20000);
+ re.DeviceSetParam(rt, rd, LatencyComp, 0f);
+ var raw = Render(20000);
+ double lcDiff = 0; for (int i = 0; i < raw.Length; i++) { double d = comped[i] - raw[i]; lcDiff += d * d; }
+ Check(Finite(comped) && Math.Sqrt(lcDiff / raw.Length) > 1e-5, "Reverb Latency Comp moves the tail");
+ re.DeviceSetParam(rt, rd, LatencyComp, 1f);
+
+ // Telemetry + the MCP status line.
+ var sc = new float[11];
+ int scn = re.DeviceScope(rt, rd, sc, sc.Length);
+ Check(scn == 11 && sc[4] > 1000 && sc[8] > 100 && Math.Abs(sc[6] - 1.9) < 0.1,
+ $"Reverb scope reports sample rate, diffuser delay and RT60 ({sc[4]:0} Hz, {sc[8]:0} smp, {sc[6]:0.00} s)");
+ string text = re.DeviceText(rt, rd, 0);
+ Check(text.Contains("Hall") && text.Contains("RT60"), $"Reverb status text names the algorithm and RT60 (got '{text}')");
+
+ // Clone: duplicating the track keeps the appended params.
+ re.DeviceSetParam(rt, rd, Vintage, 1f);
+ int t2 = re.DuplicateTrack(rt);
+ int rd2 = re.TrackDeviceCount(t2) - 1;
+ Check(t2 > 0 && re.DeviceGetParam(t2, rd2, Vintage) > 0.5f, "duplicate track clones the Reverb's params");
+ re.DeviceSetParam(rt, rd, Vintage, 0f);
+
+ // Automation: a device-param lane drives Decay.
+ int lane = re.AddAutomationLane(rt, AutomationTarget.DeviceParam, rd, Decay);
+ Check(lane >= 0, "add Reverb Decay automation lane");
+ re.SetAutomationPoints(rt, lane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
+ var ab = new float[4096 * 2];
+ re.Seek(1.99); re.Play(); re.RenderOffline(ab, 4096); re.StopTransport();
+ Check(re.DeviceGetParam(rt, rd, Decay) > 0.8f, $"automation drives Reverb Decay ({re.DeviceGetParam(rt, rd, Decay):F2})");
+}
+
// ============================ Nota Crush ====================================
Console.WriteLine("-- Nota Crush --");
{
@@ -5720,6 +6015,7 @@ Console.WriteLine("-- Built-in instrument presets + factory catalog --");
factory.Apply(engine, glue.Id, compTrack);
int lastDev = engine.TrackDeviceCount(compTrack) - 1;
Check(lastDev >= 0 && engine.TrackDeviceBuiltinKind(compTrack, lastDev) == 1, "factory effect preset added a Compressor device");
+ Check(all.Count(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 1) >= 25, $"at least 25 Compressor factory presets ({all.Count(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 1)})");
}
// ===================== M7-7: crash recovery ================================