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 Crush and Dynamic EQ-8

Egor Khindikaynence7d14c3dcda
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e15e44f..2f65eb94 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,75 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Dynamic EQ-8 is redrawn around its graph, and each band gets its own key.** The card
+ follows the new mockup on the 700 × 260 frame: the response graph takes almost the whole
+ width, a row of eight band chips sits over it, the selected band is edited in a panel on the
+ right, and a status strip closes the card:
+ - **Graph** — the live response in brass, the static one as a teal dashed line while they
+ differ, the output spectrum under them (from the engine's FFT) and the selected band's own
+ curve. Every band is a numbered node, off bands included; a dynamic band grows a whisker
+ to where its range can take it, with a dot riding it at the gain it has now. A tooltip by
+ the selected node reads the band and, for a dynamic band, its gain now with a 2-second
+ history. Drag a node for frequency and gain, the wheel over it for Q, double-click it to
+ switch the band on or off, double-click empty space for a new bell there; right-click
+ keeps the type / mode / on / solo menu.
+ - **Band chips** — number, type and frequency of all eight bands, with a bar showing how
+ much of its range each dynamic band uses right now. Click to select, double-click to
+ switch a band on or off.
+ - **Band panel** — On, the type (HP · LS · Bell · Notch · HS · LP), FREQ / GAIN / Q knobs (Q
+ reads RESO on the cuts), the dynamics mode (Static · Duck · Lift), THRESH with the band's
+ level marked on it, RANGE, ATTACK, RELEASE, the key and Solo. Range is set by magnitude;
+ Duck starts as a cut and Lift as a boost, and the arrow by the value flips it (upward /
+ downward expansion).
+ - New **Dynamic** master switch: off parks every band on its static gain, to hear what the
+ dynamics do. New per-band **Key**: Self, or Ext — the key track (click Ext to pick it). The
+ old all-bands Sidechain switch still works and hands over to the per-band keys when a
+ band is set back to Self.
+ - The **Output** gain now has a control: drag the OUT readout in the status strip.
+ - **33 factory presets**, up from six — vocal (de-essers, tame, presence, proximity, air,
+ podcast), mix and master (bus air, glue, mud, harshness, loudness contour), drums, bass,
+ keyed ducking (kick ducks bass, vocal pocket, voice-over space), instruments, expansion
+ and a static cleanup. The new parameters are appended and default to the old sound, so
+ older projects and presets open unchanged; the automation menu lists the parameters
+ under Band 1 … Band 8. `get_device_text` returns the status line, the live reading and a
+ guide to the parameters, the new `read_dynamic_eq` returns every band with its level and
+ gain now plus the spectrum, and `set_dynamic_eq_band` edits a band in one call.
+- **Nota Crush shows its steps, its spectrum and its transfer curve, and gains Auto gain and a
+ DC filter.** The card moves onto the 700 × 260 frame of Ceiling and Beat Repeat — a CRUSH
+ column (input and output), a centre panel with **Quantiser**, **Spectrum** and **Transfer**
+ tabs, a **Grit** / **Output** panel and a status strip. The slider row over the graph
+ becomes Bits / Rate / Drive / Wet knobs under it, Mode a switch over it, Anti-alias moves
+ next to it:
+ - **Quantiser** — 10 ms of a sine held and quantised to the real hold length, the steps
+ over the level grid (enlarged above 4 bits, and it says so). Drag up / down for Bits,
+ left / right for Rate. Shows the rate against the project's, one sample of how many is
+ kept, and the quantisation noise.
+ - **Spectrum** — the output in 40 bands from an FFT in the engine: brass where it is the
+ signal, teal where the crush added something — bright above the reduced Nyquist (the
+ images); a dashed outline where the post filter took signal away. Drag the Nyquist line
+ for Rate and the filter line for the post filter. Shows the images above the Nyquist and
+ THD+N.
+ - **Transfer** — the input → output curve through Drive, the mode and the real level count,
+ with a dot where the signal peaks, next to the form it makes of a sine. Drag for Drive.
+ Shows how many times Fold folds the signal.
+ - **Grit** holds Dither, Jitter, Noise, the post filter and the gain, with a Result box —
+ bits and rate, and whether the filter cuts the images. **Output** measures in, out and
+ the crest factor, and holds the new switches.
+ - New **Auto gain**: rides the output back to the input's loudness (300 ms RMS, ±24 dB), so
+ Bits and Drive stop jumping in level. New **DC filter**: a 10 Hz high-pass on the crushed
+ signal.
+ - Rate is now a fractional sample and hold, so it sweeps smoothly and automation doesn't
+ zipper. Anti-alias is a 4th-order
+ Butterworth low-pass instead of a one-pole, so far less folds back into the audible range.
+ - **33 factory presets**, up from six — classic lo-fi (tape, sampler, SP-1200, telephone,
+ AM, walkie-talkie), retro machines (8-bit, 4-bit, NES, 16-bit console, Game Boy, Speak &
+ Spell), subtle texture for buses and hats, destruction (1-bit, aliasing, broken clock,
+ bitrot) and folds. The two new parameters are appended and default off, so older projects
+ and presets open unchanged. Every parameter automates, MIDI-learns, saves in a preset and
+ is reachable over MCP. `get_device_text` returns the status line, the live reading and a
+ guide to the parameter values, `device_action` 0 resets the meters, and the new
+ `read_crush` returns the settings, the meters, THD+N, the images, the folds, the
+ auto-gain correction and the spectrum.
- **Nota Ceiling shows its level, its reduction and its loudness, and gains True Peak, Delta, a
key high-pass and a loudness target.** The card moves onto the 700 × 260 frame of Beat Repeat
and Shutter — a LIMIT column (input with the ceiling, reduction, output), a centre panel with
@@ -345,6 +414,15 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
returns the compressor's status line.
### Fixed
+- **Nota Dynamic EQ-8's key track did nothing.** The device never stored the sidechain source
+ it was given, so a chosen key track was forgotten at once and every band kept listening to
+ its own track. The key is now kept, saved with the project and heard by the bands set to
+ Ext.
+- **Nota Crush's Fold went silent under Drive, and Rate moved in steps.** Fold clamped its
+ input at four times the fold point, so with a few dB of Drive whole stretches of the wave
+ collapsed to zero; it now folds on for as far as the signal goes, and more Drive means more
+ folds. The sample and hold rounded the hold to whole samples, so the upper half of Rate
+ jumped between a few rates (22 → 14.7 → 11 kHz); it now holds fractional lengths.
- **Nota Ceiling's integrated loudness and true peak.** The integrated LUFS gated 100 ms
slices instead of the 400 ms blocks BS.1770 asks for, so quiet passages were weighed wrong;
it now gates overlapping 400 ms blocks. The true-peak meter interpolated with a spline that
diff --git a/FEATURES.md b/FEATURES.md
index 994e812e..d37d0150 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -397,18 +397,26 @@ and user presets, automation, persistence and cloning.
box and meters; 31 factory presets; MCP `read_beat_repeat`.
- **Nota Orbit** (10, formerly Auto Pan) — auto-pan and tremolo, L/R phase (0° = tremolo …
180° = pan), 5 LFO shapes, Shape, Mix.
-- **Nota Crush** (12) — bit crusher: Bit Depth, Sample Rate, Drive, Wet, Anti-Alias;
- Digital/Analog/Fold modes; GRIT (Dither/Jitter/Noise); an OUTPUT filter; quantizer and
- aliasing-spectrum visualisers.
+- **Nota Crush** (12) — bit crusher: Bits (1–24), Rate (fractional sample and hold), Drive,
+ Wet; Digital / Analog / Fold modes; Anti-alias (4th order); GRIT (Dither / Jitter / Noise);
+ a post filter, output gain, Auto gain and a DC filter. Quantiser / Spectrum (engine FFT:
+ signal, added content, images above the Nyquist) / Transfer graphs (drag Bits and Rate, the
+ Nyquist and the filter, Drive), a CRUSH in/out column, Grit / Output panels; 33 factory
+ presets; MCP `read_crush`.
- **Nota Ceiling** (14) — look-ahead brick-wall limiter: Gain, Ceiling, Release (with a
program-dependent auto stage), Clean / Punch / Glue characters, look-ahead, stereo link,
True Peak (4× inter-sample detection), Delta (hear what it removes), a key high-pass and an
external key; a BS.1770 / R128 loudness meter (LUFS M / S / I, LRA, PLR, true peak) against
a Target. Level / Reduction / Loudness graphs (drag the ceiling and the target), a LIMIT
column, Meters / Detector panels; 32 factory presets; MCP `read_ceiling`.
-- **Nota Dynamic EQ-8** (13) — 8-band parametric with dynamics: each band Static/Duck/Lift,
- threshold, range, attack/release, sidechain, Solo band; a dual curve (static plus
- momentary) and a band table with GR.
+- **Nota Dynamic EQ-8** (13) — 8-band parametric with dynamics: each band Static / Duck
+ (above the threshold) / Lift (below it), threshold, signed range (cut or boost — upward and
+ downward expansion too), attack / release and its own key (Self or a key track); a Dynamic
+ master switch, Solo, output. A full-width response graph (live curve, static curve while
+ they differ, the output spectrum, draggable numbered nodes with a whisker to each dynamic
+ band's range and its gain now, a tooltip with a 2 s gain history), a strip of band chips
+ with their activity, a panel for the selected band with the band's level on the threshold;
+ 33 factory presets; MCP `read_dynamic_eq`, `set_dynamic_eq_band`.
- **Nota Strata** (15) — multi-layer overdub looper: layers with waveform, level and mute;
Record/Overdub/Play/Stop, Undo/Clear, Feedback, input gain, speed/reverse, quantize,
count-in, set-tempo, Export; audio layers persist into the project.
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index 265d7e2e..c867782f 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -394,9 +394,11 @@ public sealed partial class ArrangementView
// Nota Utility its mono, phase and true-peak params ("Mono Freq", "Invert L", "TP Ceiling" …),
// Nota Shutter its detector ("Det HP", "Det LP", "Det Filter"), Nota Auto Shift its
// scale notes, detector and MIDI target ("Note C#", "Det Low", "MIDI Glide" …) and Nota
- // Beat Repeat its repeat filter ("Filter Freq", "Filter Type", "Filter Narrow" …):
+ // Beat Repeat its repeat filter ("Filter Freq", "Filter Type", "Filter Narrow" …) and
+ // Nota Dynamic EQ-8 its eight bands ("3 Freq", "3 Thr" … under "Band 3"):
// a word shared by two or more params becomes a submenu.
- bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 4 or 6 or 7 or 8 or 10 or 11 or 19 or 20 or 21 or 22;
+ int bkind = e.TrackDeviceBuiltinKind(t.Id, d);
+ bool grouped = bkind is 1 or 4 or 6 or 7 or 8 or 10 or 11 or 13 or 19 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] : ""; }
@@ -409,7 +411,11 @@ public sealed partial class ArrangementView
var leaf = Leaf(sub ? names[p][(head.Length + 1)..] : names[p], $"D:{dd}:{pp}",
() => SetAutoTarget(t, AutomationTarget.DeviceParam, dd, pp), automated);
if (!sub) { devMenu.Items.Add(leaf); continue; }
- if (!groups.TryGetValue(head, out var g)) { g = new MenuItem { Header = head }; groups[head] = g; devMenu.Items.Add(g); }
+ if (!groups.TryGetValue(head, out var g))
+ {
+ g = new MenuItem { Header = bkind == 13 && int.TryParse(head, out _) ? "Band " + head : head };
+ groups[head] = g; devMenu.Items.Add(g);
+ }
g.Items.Add(leaf);
}
flyout.Items.Add(devMenu);
diff --git a/src/managed/Nota.App/Controls/CrushViews.cs b/src/managed/Nota.App/Controls/CrushViews.cs
new file mode 100644
index 00000000..7c9e82bf
--- /dev/null
+++ b/src/managed/Nota.App/Controls/CrushViews.cs
@@ -0,0 +1,392 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Crush (device kind 12) card windows:
+// · CrQuantView — the Quantiser tab: 10 ms of a 100 Hz sine through the crusher — the source
+// dashed, the held and quantised steps in brass over the level grid. The hold is drawn to
+// scale; above 4 bits the level step is enlarged (so it stays visible) and says so. Drag up /
+// down for Bits, left / right for Rate; double-click resets both.
+// · CrSpectrumView — the Spectrum tab, from the engine's FFT (Crush.h scopeRead): the crushed
+// output in 40 log bands, brass up to the (level-matched) input, teal where the crush added
+// content — bright above the reduced Nyquist (the images), dim below (harmonics, noise). A
+// ghost outline shows input the post filter took away. Drag the Nyquist line (Rate) or the
+// filter line (Post Filter).
+// · CrTransferView — the Transfer tab's curve: input → output through Drive, the mode's shape
+// and the quantiser, at the real level count. Drag up / down for Drive.
+// · CrWaveView — the Transfer tab's form: two cycles of a sine at the driven level and what
+// comes out.
+// The shape functions mirror Crush.h so the pictures are the DSP.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class CrushMath
+{
+ public static readonly string[] Modes = { "Digital", "Analog", "Fold" };
+
+ public static double Shape(int mode, double x) => mode switch
+ {
+ 1 => Math.Tanh(x * 1.5) / 0.905,
+ 2 => Fold(x * 2.5, 0.7),
+ _ => x,
+ };
+
+ public static double Fold(double x, double threshold)
+ {
+ double period = 4 * threshold;
+ double u = (x + threshold) % period;
+ if (u < 0) u += period;
+ return 1 - Math.Abs(u - 2 * threshold) / threshold;
+ }
+
+ /// <summary>Quantise like the DSP: round(x · (L − 1)) / (L − 1).</summary>
+ public static double Quant(double x, double levels)
+ {
+ double s = Math.Max(1, levels - 1);
+ return Math.Round(x * s) / s;
+ }
+
+ /// <summary>The level count the Quantiser draws: exact up to 4 bits (16 levels), then
+ /// enlarged — 16 … 40 levels over 4 … 24 bits — so a step stays visible.</summary>
+ public static double ShownLevels(double bits) => bits <= 4 ? Math.Pow(2, bits) : 16 + (bits - 4) * 1.2;
+
+ public static string Hz(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0}\u2009k") : NotaNum.F($"{hz:0}\u2009Hz");
+}
+
+internal sealed class CrQuantView : Control
+{
+ private double _bits = 13.7, _hold = 24, _sr = 48000, _drive = 1;
+ private int _mode;
+ private bool _drag;
+ private Point _start;
+ private double _b0, _r0;
+
+ /// <summary>Bits and Rate (both 0..1) at the start of a drag.</summary>
+ public Func<(double Bits, double Rate)>? Value { get; set; }
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+ public event Action<double, double>? Changed;
+ public event Action? ResetRequested;
+ public bool Dragging => _drag;
+
+ public CrQuantView() { ClipToBounds = true; MinHeight = 36; Cursor = new Cursor(StandardCursorType.SizeAll); }
+
+ public void Set(double bits, double hold, double sr, int mode, double drive)
+ {
+ if (Math.Abs(bits - _bits) < 1e-4 && Math.Abs(hold - _hold) < 1e-4 && Math.Abs(sr - _sr) < 1 && mode == _mode && Math.Abs(drive - _drive) < 1e-4) return;
+ _bits = bits; _hold = Math.Max(1, hold); _sr = sr > 0 ? sr : 48000; _mode = mode; _drive = drive;
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { ResetRequested?.Invoke(); e.Handled = true; return; }
+ var v = Value?.Invoke() ?? (0.5, 0.5);
+ _b0 = v.Bits; _r0 = v.Rate; _start = e.GetPosition(this); _drag = true;
+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (!_drag) return;
+ var p = e.GetPosition(this);
+ double b = Math.Clamp(_b0 + (_start.Y - p.Y) / Math.Max(60, Bounds.Height * 1.6), 0, 1);
+ double r = Math.Clamp(_r0 + (p.X - _start.X) / Math.Max(120, Bounds.Width * 1.2), 0, 1);
+ Changed?.Invoke(b, r);
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_drag) return;
+ _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke(); InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 6, x1 = w - 6, top = 16, bot = h - 12, mid = (top + bot) / 2, amp = (bot - top) / 2 * 0.86;
+ double Y(double v) => mid - Math.Clamp(v, -1.12, 1.12) * amp;
+
+ double levels = CrushMath.ShownLevels(_bits);
+ bool enlarged = _bits > 4.0001;
+ // Level grid: every level when there are few, else every n-th.
+ int every = Math.Max(1, (int)Math.Ceiling((levels - 1) / 10.0));
+ double s = Math.Max(1, levels - 1);
+ for (int k = -(int)s; k <= (int)s; k += every)
+ {
+ double y = Y(k / s);
+ if (y < top - 1 || y > bot + 1 || k == 0) continue;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, y), new Point(x1, y));
+ }
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(x0, mid), new Point(x1, mid));
+
+ // 10 ms: one cycle of a 100 Hz sine at 0.8 × Drive.
+ double win = _sr / 100.0;
+ double pxPerSmp = (x1 - x0) / win;
+ double Src(double smp) => Math.Sin(2 * Math.PI * smp / win - 0.1) * 0.8 * _drive;
+
+ var src = new StreamGeometry();
+ using (var g = src.Open())
+ {
+ for (double x = x0; x <= x1 + 0.1; x += 2)
+ {
+ var pt = new Point(x, Y(Src((x - x0) / pxPerSmp)));
+ if (x == x0) g.BeginFigure(pt, false); else g.LineTo(pt);
+ }
+ g.EndFigure(false);
+ }
+
+ var step = new StreamGeometry();
+ var area = new StreamGeometry();
+ using (var g = step.Open())
+ using (var a = area.Open())
+ {
+ bool first = true;
+ for (double smp = 0; smp < win; smp += _hold)
+ {
+ double y = Y(CrushMath.Quant(CrushMath.Shape(_mode, Src(smp)), levels));
+ double xa = x0 + smp * pxPerSmp, xb = Math.Min(x1, x0 + (smp + _hold) * pxPerSmp);
+ if (first) { g.BeginFigure(new Point(xa, y), false); first = false; } else g.LineTo(new Point(xa, y));
+ g.LineTo(new Point(xb, y));
+ a.BeginFigure(new Point(xa, mid), true);
+ a.LineTo(new Point(xa, y)); a.LineTo(new Point(xb, y)); a.LineTo(new Point(xb, mid));
+ a.EndFigure(true);
+ }
+ if (!first) g.EndFigure(false);
+ }
+ ctx.DrawGeometry(NotaPalette.Wash(NotaPalette.Accent, 0x29), null, area);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.TextTertiary, 1, new DashStyle(new double[] { 3, 3 }, 0)), src);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, _drag ? 2.2 : NotaGraph.PrimaryWidth, lineJoin: PenLineJoin.Round), step);
+
+ NotaGraph.Title(ctx, frame, "Quantiser");
+ double rate = _sr / _hold;
+ NotaGraph.Legend(ctx, w - 6, 3, ("source", NotaPalette.TextSecondary, NotaGraph.Mark.Dashed),
+ (NotaNum.F($"{_bits:0.0} bit @ {CrushMath.Hz(rate)}"), NotaPalette.AccentBright, NotaGraph.Mark.Line));
+ if (enlarged) NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "level step shown enlarged");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "10\u2009ms");
+ }
+}
+
+internal sealed class CrSpectrumView : ShDragView
+{
+ public const int HNyquist = 0, HFilter = 1;
+ private readonly float[] _in = new float[40], _out = new float[40];
+ private int _n;
+ private double _nyq = 1000, _filt = 10000;
+ private bool _valid;
+ private const double FLo = 20, FHi = 20000, DbLo = -84, DbHi = 0;
+ public Func<double, double> NyquistToNorm { get; set; } = hz => 0.5;
+ public Func<double, double> FilterToNorm { get; set; } = hz => 0.5;
+
+ public void Set(float[] src, int inAt, int outAt, int n, double nyqHz, double filterHz, bool valid)
+ {
+ n = Math.Min(n, _in.Length);
+ if (n > 0 && Math.Max(inAt, outAt) + n <= src.Length)
+ {
+ Array.Copy(src, inAt, _in, 0, n);
+ Array.Copy(src, outAt, _out, 0, n);
+ }
+ _n = n; _nyq = nyqHz; _filt = filterHz; _valid = valid && n > 0;
+ InvalidateVisual();
+ }
+
+ private (double x0, double x1, double top, double bot) Plot() => (6, Bounds.Width - 6, 16, Bounds.Height - 12);
+ private double X(double hz) { var (x0, x1, _, _) = Plot(); return x0 + Math.Log(Math.Clamp(hz, FLo, FHi) / FLo) / Math.Log(FHi / FLo) * (x1 - x0); }
+ private double F(double x) { var (x0, x1, _, _) = Plot(); return FLo * Math.Pow(FHi / FLo, Math.Clamp((x - x0) / Math.Max(1, x1 - x0), 0, 1)); }
+
+ protected override int Hit(Point p)
+ {
+ if (Math.Abs(p.X - X(_nyq)) <= 5) return HNyquist;
+ if (Math.Abs(p.X - X(_filt)) <= 5) return HFilter;
+ return -1;
+ }
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ => handle == HNyquist ? NyquistToNorm(F(p.X)) : FilterToNorm(F(p.X));
+ protected override StandardCursorType CursorFor(int handle) => StandardCursorType.SizeWestEast;
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ var (x0, x1, top, bot) = Plot();
+ double Y(double db) => bot - Math.Clamp((db - DbLo) / (DbHi - DbLo), 0, 1) * (bot - top);
+ for (int q = 1; q < 3; q++) ctx.DrawLine(NotaGraph.GridPen, new Point(x0, top + (bot - top) * q / 3), new Point(x1, top + (bot - top) * q / 3));
+ foreach (double f in new[] { 100.0, 1000.0, 10000.0 }) ctx.DrawLine(NotaGraph.GridPen, new Point(X(f), top), new Point(X(f), bot));
+
+ double nx = X(_nyq);
+ if (_valid)
+ {
+ double bw = (x1 - x0) / _n, gap = bw > 4 ? 1.5 : 0.5;
+ var ghost = new Pen(NotaPalette.TextDisabled, 1, new DashStyle(new double[] { 2, 2 }, 0));
+ var addLo = NotaPalette.Wash(NotaPalette.Teal, 0x66);
+ var addHi = NotaPalette.Wash(NotaPalette.TealBright, 0xC0);
+ for (int b = 0; b < _n; b++)
+ {
+ double x = x0 + b * bw, cw = Math.Max(0.6, bw - gap);
+ double fc = FLo * Math.Pow(FHi / FLo, (b + 0.5) / _n);
+ double yi = Y(_in[b]), yo = Y(_out[b]);
+ double ys = Math.Max(yi, yo); // the signal part: up to the lower of in and out
+ if (ys < bot - 0.5) ctx.DrawRectangle(NotaPalette.Accent, null, new Rect(x, ys, cw, bot - ys), 1, 1);
+ if (_out[b] > _in[b] + 1 && yo < ys - 0.5)
+ ctx.DrawRectangle(fc > _nyq ? addHi : addLo, null, new Rect(x, yo, cw, ys - yo), 1, 1);
+ if (_in[b] > _out[b] + 3 && yi < bot - 1)
+ ctx.DrawRectangle(null, ghost, new Rect(x + 0.5, yi, cw - 1, yo - yi));
+ }
+ }
+ else
+ {
+ var ft = NotaGraph.AxisText("no signal", NotaPalette.TextTertiary, 8);
+ ctx.DrawText(ft, new Point((w - ft.Width) / 2, (top + bot - ft.Height) / 2));
+ }
+
+ // The post filter and the Nyquist of the reduced rate — both draggable.
+ double fx = X(_filt);
+ ctx.DrawLine(new Pen(Active == HFilter ? NotaPalette.AccentBright : NotaPalette.AccentDim, Active == HFilter ? 1.6 : 1, new DashStyle(new double[] { 2, 3 }, 0)),
+ new Point(fx, top), new Point(fx, bot));
+ ctx.DrawLine(new Pen(Active == HNyquist ? NotaPalette.TealBright : NotaPalette.Teal, Active == HNyquist ? 1.6 : 1, new DashStyle(new double[] { 3, 2 }, 0)),
+ new Point(nx, top), new Point(nx, bot));
+ Label(ctx, "Nyquist " + CrushMath.Hz(_nyq), nx, top + 2, NotaPalette.TealBright);
+ Label(ctx, "filter " + CrushMath.Hz(_filt), fx, top + 12, NotaPalette.AccentBright);
+
+ NotaGraph.Title(ctx, frame, "Spectrum");
+ NotaGraph.Legend(ctx, w - 6, 3, ("signal", NotaPalette.AccentBright, NotaGraph.Mark.Area),
+ ("added", NotaPalette.Teal, NotaGraph.Mark.Area), ("images", NotaPalette.TealBright, NotaGraph.Mark.Area));
+ Text(ctx, "100", X(100) + 2, h - 11);
+ Text(ctx, "1\u2009k", X(1000) + 2, h - 11);
+ Text(ctx, "10\u2009k", X(10000) + 2, h - 11);
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "20");
+ }
+
+ // A marker label on the side of the line that has room.
+ private void Label(DrawingContext ctx, string s, double x, double y, IBrush ink)
+ {
+ var ft = NotaGraph.AxisText(s, ink);
+ var (x0, x1, _, _) = Plot();
+ double lx = x + 3 + ft.Width > x1 ? x - 3 - ft.Width : x + 3;
+ ctx.DrawText(ft, new Point(Math.Max(x0, lx), y));
+ }
+}
+
+internal sealed class CrTransferView : ShDragView
+{
+ public const int HDrive = 0;
+ private int _mode;
+ private double _drive = 1, _levels = 16, _peak;
+
+ public void Set(int mode, double drive, double levels, double drivenPeak)
+ {
+ if (mode == _mode && Math.Abs(drive - _drive) < 1e-4 && Math.Abs(levels - _levels) < 1e-3 && Math.Abs(drivenPeak - _peak) < 1e-3) return;
+ _mode = mode; _drive = drive; _levels = levels; _peak = drivenPeak;
+ InvalidateVisual();
+ }
+
+ protected override int Hit(Point p) => HDrive;
+ protected override double DragTo(int handle, Point start, Point p, double v0) => v0 + (start.Y - p.Y) / Math.Max(80, Bounds.Height * 1.4);
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double pad = 8, top = 16, x0 = pad, x1 = w - pad, bot = h - pad;
+ double side = Math.Min(x1 - x0, bot - top);
+ double cx = (x0 + x1) / 2, cy = (top + bot) / 2, r = side / 2;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(cx, cy - r), new Point(cx, cy + r));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(cx - r, cy), new Point(cx + r, cy));
+ ctx.DrawLine(new Pen(NotaPalette.TextTertiary, 1, new DashStyle(new double[] { 2, 3 }, 0)), new Point(cx - r, cy + r), new Point(cx + r, cy - r));
+
+ var g = new StreamGeometry();
+ using (var gc = g.Open())
+ {
+ const int N = 240;
+ for (int i = 0; i <= N; i++)
+ {
+ double x = -1 + 2.0 * i / N;
+ double y = CrushMath.Quant(CrushMath.Shape(_mode, x * _drive), _levels);
+ var pt = new Point(cx + x * r, cy - Math.Clamp(y, -1.1, 1.1) * r / 1.1);
+ if (i == 0) gc.BeginFigure(pt, false); else gc.LineTo(pt);
+ }
+ gc.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, Dragging ? 2.2 : NotaGraph.PrimaryWidth, lineJoin: PenLineJoin.Round), g);
+ // Where the signal peaks on the curve (the driven peak back in input units).
+ if (_peak > 1e-4 && _drive > 1e-6)
+ {
+ double xin = Math.Clamp(_peak / _drive, 0, 1);
+ double y = CrushMath.Quant(CrushMath.Shape(_mode, xin * _drive), _levels);
+ NotaGraph.Node(ctx, new Point(cx + xin * r, cy - Math.Clamp(y, -1.1, 1.1) * r / 1.1), true);
+ }
+ NotaGraph.Title(ctx, frame, "Curve");
+ }
+}
+
+internal sealed class CrWaveView : Control
+{
+ private int _mode;
+ private double _drive = 1, _levels = 16, _hold = 1, _sr = 48000, _driveDb;
+
+ public CrWaveView() { ClipToBounds = true; MinHeight = 36; }
+
+ public void Set(int mode, double drive, double driveDb, double levels, double hold, double sr)
+ {
+ if (mode == _mode && Math.Abs(drive - _drive) < 1e-4 && Math.Abs(levels - _levels) < 1e-3 && Math.Abs(hold - _hold) < 1e-4 && Math.Abs(sr - _sr) < 1) return;
+ _mode = mode; _drive = drive; _driveDb = driveDb; _levels = levels; _hold = Math.Max(1, hold); _sr = sr > 0 ? sr : 48000;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 6, x1 = w - 6, top = 16, bot = h - 12, mid = (top + bot) / 2, amp = (bot - top) / 2 * 0.8;
+ double Y(double v) => mid - Math.Clamp(v, -1.22, 1.22) * amp;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, mid), new Point(x1, mid));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, Y(1)), new Point(x1, Y(1)));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, Y(-1)), new Point(x1, Y(-1)));
+
+ // 10 ms: two cycles of a 200 Hz sine at full scale × Drive, held and crushed.
+ double win = _sr / 100.0, pxPerSmp = (x1 - x0) / win;
+ double Src(double smp) => Math.Sin(4 * Math.PI * smp / win) * _drive;
+ var src = new StreamGeometry();
+ var outG = new StreamGeometry();
+ using (var s = src.Open())
+ using (var o = outG.Open())
+ {
+ double held = 0, next = 0;
+ for (double x = x0; x <= x1 + 0.1; x += 1)
+ {
+ double smp = (x - x0) / pxPerSmp;
+ if (smp >= next) { held = Src(Math.Floor(smp / _hold) * _hold); next = (Math.Floor(smp / _hold) + 1) * _hold; }
+ var ps = new Point(x, Y(Src(smp)));
+ var po = new Point(x, Y(CrushMath.Quant(CrushMath.Shape(_mode, held), _levels)));
+ if (x == x0) { s.BeginFigure(ps, false); o.BeginFigure(po, false); }
+ else { s.LineTo(ps); o.LineTo(po); }
+ }
+ s.EndFigure(false); o.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xB3), 1, new DashStyle(new double[] { 3, 3 }, 0)), src);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, 1.6, lineJoin: PenLineJoin.Round), outG);
+
+ NotaGraph.Title(ctx, frame, "Form");
+ NotaGraph.Legend(ctx, w - 6, 3, (NotaNum.F($"in {_driveDb:+0;−0;0}\u2009dB"), NotaPalette.TealBright, NotaGraph.Mark.Dashed),
+ ("out", NotaPalette.AccentBright, NotaGraph.Mark.Line));
+ string lv = _levels >= 1e6 ? NotaNum.F($"{_levels / 1e6:0.0}\u2009M levels") : _levels >= 1e4 ? NotaNum.F($"{_levels / 1e3:0}\u2009k levels") : NotaNum.F($"{_levels:0} levels");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, lv);
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "10\u2009ms");
+ }
+}
diff --git a/src/managed/Nota.App/Controls/DynamicEqCurve.cs b/src/managed/Nota.App/Controls/DynamicEqCurve.cs
index a6fd443b..ebca1fd0 100644
--- a/src/managed/Nota.App/Controls/DynamicEqCurve.cs
+++ b/src/managed/Nota.App/Controls/DynamicEqCurve.cs
@@ -1,16 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Dynamic EQ-8 response graph. Like the static EQ-8 curve, but a dynamic EQ has two
-// answers at once — where a band sits and where it is right now — so it draws two
-// curves: the static response in brass and the live, momentary response (static gain
-// plus each band's current dynamic gain) as a teal dashed line. The gap between them
-// is the compression happening. Dynamic bands announce themselves: a teal handle plus
-// a dashed vertical "reach" line showing how far the band can travel. Drag a dot =
-// freq (+gain for shelves/bells); wheel = Q; double-click empty = add a bell;
-// right-click a dot = type / dynamic mode / remove. Momentary gains come from the
-// device's scope telemetry (8 floats, dB per band); a per-band GR history is kept for
-// the sparkline in the strip.
+// Nota Dynamic EQ-8 (device kind 13) response graph, a build of the "Nota Dynamic EQ" mockup.
+// A dynamic EQ has two answers at once — where a band sits and where it is right now — so the
+// window draws the live response (static gain + each band's momentary dynamic gain) as the
+// brass primary curve and the static response as a teal dashed line, shown only while the two
+// differ. Under them: the output spectrum (the engine's FFT, a dim line) and the selected
+// band's own curve (a faint brass line). Every band is a numbered node — selected brass, the
+// rest Ink 3, an off band Ink 6. A dynamic band grows a whisker from its node to where Range
+// can take it (teal for a cut, rose for a boost), with a dot riding it at the gain it has now.
+// A tooltip beside the selected node reads the band, and for a dynamic band its gain now with
+// a 2-second history of it.
+//
+// Drag a node — frequency and gain; the wheel over a node — Q; double-click a node turns the
+// band on / off, double-click empty space switches on a free band there as a bell;
+// right-click a node — type, mode, on and solo. The magnitude maths mirrors DynamicEq.h.
using System;
using System.Globalization;
@@ -22,96 +26,52 @@ using Nota.Application;
namespace Nota.App;
-public sealed class DynamicEqCurve : Control
+/// <summary>The Dynamic EQ-8 parameter layout (mirrors DynamicEq.h) and the maths the card and
+/// the graph share.</summary>
+internal static class DynEq
{
- private const int Bands = 8, PerBand = 10;
- private const int On = 0, TypeF = 1, FreqF = 2, GainF = 3, QF = 4, ModeF = 5, ThrF = 6, RangeF = 7, AtkF = 8, RelF = 9;
- private const int LowCut = 0, LowShelf = 1, Bell = 2, Notch = 3, HighShelf = 4, HighCut = 5;
- private static readonly string[] TypeNames = { "Low cut", "Low shelf", "Bell", "Notch", "High shelf", "High cut" };
- private static readonly string[] ModeNames = { "Static", "Dynamic ↓ (above)", "Dynamic ↑ (below)" };
-
- private const double Fmin = 20, Fmax = 20000, GMax = 18;
- public const int HistLen = 120; // 2 s at 60 Hz
-
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IPen GridPen = NotaGraph.GridPen;
- private static readonly IPen GridPenFaint = new Pen(NotaPalette.Wash(NotaPalette.WellGrid, 0x60), 1);
- private static readonly IPen ZeroPen = new Pen(NotaPalette.BorderStrong, 1);
- private static readonly IPen CurvePen = new Pen(NotaPalette.Accent, NotaGraph.PrimaryWidth);
- private static readonly IBrush CurveFill = NotaPalette.Wash(NotaPalette.Accent, 0x1E);
- private static readonly IPen DynPen = new Pen(NotaPalette.Teal, 1.5) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
- private static readonly IPen ReachPen = new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x88), 1) { DashStyle = new DashStyle(new double[] { 2, 3 }, 0) };
- private static readonly IBrush DotBrass = NotaPalette.AccentBright;
- private static readonly IBrush DotTeal = NotaPalette.Teal;
- private static readonly IBrush DotOff = NotaPalette.TextAxis;
- private static readonly IBrush DotRing = NotaPalette.BgSunken;
- private static readonly IBrush SelRing = NotaPalette.AccentBright;
- private static readonly IBrush LabelDim = NotaPalette.TextTertiary;
- private static readonly IBrush LabelBright = NotaPalette.TextSecondary;
- private static readonly IBrush OnAccentText = NotaPalette.TextOnAccent;
- private static readonly Typeface Mono = NotaFonts.Mono;
- private static readonly Typeface DotFont = NotaFonts.SansBold;
-
- private readonly IAudioEngine _engine;
- private readonly int _track, _device;
- private int _drag = -1, _selected = 4;
- private bool _gestFreq, _gestGain;
-
- private readonly float[] _gr = new float[Bands];
- private readonly float[] _histBuf = new float[Bands * HistLen];
- private int _histHead;
-
- public event Action? SelectionChanged;
- public int SelectedBand => _selected;
- public float Gr(int b) => (b >= 0 && b < Bands) ? _gr[b] : 0f;
-
- // Copy a band's GR history oldest→newest into dst (length HistLen).
- public void FillHistory(int band, float[] dst)
- {
- if (band < 0 || band >= Bands) { Array.Clear(dst); return; }
- for (int i = 0; i < HistLen; i++)
- dst[i] = _histBuf[band * HistLen + (_histHead + i) % HistLen];
- }
-
- public DynamicEqCurve(IAudioEngine engine, int track, int device)
- {
- _engine = engine; _track = track; _device = device;
- MinHeight = 150;
- }
-
- // ---- param helpers ----
- private float P(int band, int field) => _engine.DeviceGetParam(_track, _device, band * PerBand + field);
- private void SetP(int band, int field, double v) => _engine.DeviceSetParam(_track, _device, band * PerBand + field, (float)v);
- private bool BandOn(int b) => P(b, On) > 0.5f;
- private int BandType(int b) => Math.Clamp((int)Math.Round(P(b, TypeF)), 0, 5);
- private int BandMode(int b) => Math.Clamp((int)Math.Round(P(b, ModeF)), 0, 2);
- private static bool HasGain(int type) => type is LowShelf or Bell or HighShelf;
- private bool IsDyn(int b) => BandOn(b) && HasGain(BandType(b)) && BandMode(b) != 0;
-
- public void Select(int b)
- {
- if (b == _selected) return;
- _selected = b; SelectionChanged?.Invoke(); InvalidateVisual();
- }
-
- // ---- coordinate mapping ----
- private double FreqToX(double f, double w) => w * Math.Log(f / Fmin) / Math.Log(Fmax / Fmin);
- private double XToFreq(double x, double w) => Fmin * Math.Pow(Fmax / Fmin, Math.Clamp(x / w, 0, 1));
- private double GainToY(double g, double h) => h * (0.5 - g / (2 * GMax));
- private double YToGain(double y, double h) => Math.Clamp(GMax * (1 - 2 * y / h), -GMax, GMax);
-
- // ---- magnitude response (mirrors DynamicEq.h RBJ biquads) ----
- private (double b0, double b1, double b2, double a1, double a2) Coeffs(int type, double sr, double f0, double gDb, double q)
+ public const int Bands = 8, PerBand = 10;
+ public const int On = 0, TypeF = 1, FreqF = 2, GainF = 3, QF = 4, ModeF = 5, ThrF = 6, RangeF = 7, AtkF = 8, RelF = 9;
+ public const int OutputP = 80, SidechainP = 81, SoloP = 82, DynamicsP = 83, KeyBase = 84, ParamCount = 92;
+ public const int LowCut = 0, LowShelf = 1, Bell = 2, Notch = 3, HighShelf = 4, HighCut = 5;
+ public const int Static = 0, Duck = 1, Lift = 2;
+ // Telemetry (DynamicEq::S_* / kTele / kSpec).
+ public const int S_Gain = 0, S_Level = 8, S_SampleRate = 16, S_Cpu = 17, S_Analysed = 18, S_InPeak = 19, S_OutPeak = 20,
+ S_KeyLive = 21, S_Latency = 23, kTele = 32, kSpec = 96, kScope = kTele + kSpec;
+ public const double Fmin = 20, Fmax = 20000;
+
+ public static readonly string[] TypeNames = { "Low cut", "Low shelf", "Bell", "Notch", "High shelf", "High cut" };
+ public static readonly string[] TypeShort = { "HP", "LS", "Bell", "Nt", "HS", "LP" };
+ public static readonly string[] TypeSeg = { "HP", "LS", "Bell", "Ntch", "HS", "LP" };
+ // Segment order HP · LS · Bell · Ntch · HS · LP is the type order itself.
+ public static readonly string[] ModeNames = { "Static", "Duck", "Lift" };
+
+ public static bool HasGain(int type) => type is LowShelf or Bell or HighShelf;
+ public static int P(int band, int field) => band * PerBand + field;
+
+ public static double FreqToN(double f) => Math.Log(Math.Clamp(f, Fmin, Fmax) / Fmin) / Math.Log(Fmax / Fmin);
+ public static double NToFreq(double n) => Fmin * Math.Pow(Fmax / Fmin, Math.Clamp(n, 0, 1));
+ /// <summary>Gain → 0..1 from the top: ±18 dB span 5 % … 95 % of the height (the mockup's yF).</summary>
+ public static double GainToN(double db) => 0.5 - Math.Clamp(db, -20, 20) / 18.0 * 0.45;
+ public static double NToGain(double n) => Math.Clamp((0.5 - n) / 0.45 * 18.0, -18, 18);
+
+ public static string Hz(double f) => f < 1000 ? NotaNum.F($"{f:0} Hz") : NotaNum.F($"{f / 1000:0.0} kHz");
+ public static string HzShort(double f) => f < 1000 ? NotaNum.F($"{f:0}") : f < 10000 ? NotaNum.F($"{f / 1000:0.0}k") : NotaNum.F($"{f / 1000:0}k");
+ public static string Db(double g) => NotaNum.F($"{g:+0.0;−0.0;0.0}");
+ public static string Ms(double v) => v < 10 ? NotaNum.F($"{v:0.0} ms") : NotaNum.F($"{v:0} ms");
+
+ public record struct Bq(double B0, double B1, double B2, double A1, double A2);
+
+ public static Bq Coeffs(int type, double sr, double f0, double gDb, double q)
{
double w0 = 2 * Math.PI * Math.Clamp(f0, 20, sr * 0.49) / sr, cw = Math.Cos(w0), sw = Math.Sin(w0);
double a = sw / (2 * Math.Max(q, 0.1));
- (double, double, double, double, double) N(double b0, double b1, double b2, double a0, double a1, double a2)
- => (b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0);
+ static Bq N(double b0, double b1, double b2, double a0, double a1, double a2) => new(b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0);
switch (type)
{
- case LowCut: return N((1 + cw) / 2, -(1 + cw), (1 + cw) / 2, 1 + a, -2 * cw, 1 - a);
+ case LowCut: return N((1 + cw) / 2, -(1 + cw), (1 + cw) / 2, 1 + a, -2 * cw, 1 - a);
case HighCut: return N((1 - cw) / 2, 1 - cw, (1 - cw) / 2, 1 + a, -2 * cw, 1 - a);
- case Notch: return N(1, -2 * cw, 1, 1 + a, -2 * cw, 1 - a);
+ case Notch: return N(1, -2 * cw, 1, 1 + a, -2 * cw, 1 - a);
case LowShelf:
{
double A = Math.Pow(10, gDb / 40), al = sw / 2 * Math.Sqrt(2), t = 2 * Math.Sqrt(A) * al;
@@ -132,260 +92,429 @@ public sealed class DynamicEqCurve : Control
}
}
- // Combined response in dB at frequency f. momentary=true adds each band's live GR.
- private double MagnitudeDb(double f, double sr, bool momentary)
+ public static double MagDb(in Bq k, double w)
+ {
+ double cw = Math.Cos(w), sw = Math.Sin(w), c2 = Math.Cos(2 * w), s2 = Math.Sin(2 * w);
+ double nr = k.B0 + k.B1 * cw + k.B2 * c2, ni = -(k.B1 * sw + k.B2 * s2);
+ double dr = 1 + k.A1 * cw + k.A2 * c2, di = -(k.A1 * sw + k.A2 * s2);
+ return 10 * Math.Log10(Math.Max(1e-12, (nr * nr + ni * ni) / Math.Max(1e-12, dr * dr + di * di)));
+ }
+}
+
+public sealed class DynamicEqCurve : Control
+{
+ public const int HistLen = 120; // 2 s at 60 Hz
+ private const int Pts = 150;
+ private const double NodeD = 11, HitR = 9;
+
+ private static readonly IPen GridFaint = new Pen(NotaPalette.GridSubBeat, 1);
+ private static readonly IPen GridMid = new Pen(NotaPalette.GridBeat, 1);
+ private static readonly IPen ZeroPen = new Pen(NotaPalette.TrackOff, 1);
+ private static readonly IPen SpecPen = new Pen(NotaPalette.BorderStrong, 1);
+ private static readonly IPen SelPen = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x5A), 1);
+ private static readonly IPen StaticPen = new Pen(NotaPalette.TealBright, 1.2) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
+ private static readonly IPen RingPen = new Pen(NotaPalette.BgSunken, 2);
+
+ private readonly IAudioEngine _engine;
+ private readonly int _track, _device;
+ private int _selected = 4, _drag = -1;
+ private bool _gestFreq, _gestGain;
+
+ private readonly float[] _gr = new float[DynEq.Bands];
+ private readonly float[] _lvl = new float[DynEq.Bands];
+ private readonly float[] _spec = new float[DynEq.kSpec];
+ private bool _specOk;
+ private readonly float[] _hist = new float[DynEq.Bands * HistLen];
+ private int _histHead;
+
+ public event Action? SelectionChanged;
+ /// <summary>Raised after a gesture on the graph wrote params (so the card repaints).</summary>
+ public event Action? Edited;
+
+ public DynamicEqCurve(IAudioEngine engine, int track, int device)
{
- double total = 0;
- double w = 2 * Math.PI * f / sr, cw = Math.Cos(w), sw = Math.Sin(w);
- double cos2 = Math.Cos(2 * w), sin2 = Math.Sin(2 * w);
- for (int b = 0; b < Bands; b++)
+ _engine = engine; _track = track; _device = device;
+ ClipToBounds = true;
+ MinHeight = 60;
+ for (int b = 0; b < DynEq.Bands; b++) _lvl[b] = -120;
+ }
+
+ public int SelectedBand
+ {
+ get => _selected;
+ set { int v = Math.Clamp(value, 0, DynEq.Bands - 1); if (v == _selected) return; _selected = v; SelectionChanged?.Invoke(); InvalidateVisual(); }
+ }
+ public float Gr(int b) => b is >= 0 and < DynEq.Bands ? _gr[b] : 0f;
+ public float Level(int b) => b is >= 0 and < DynEq.Bands ? _lvl[b] : -120f;
+
+ /// <summary>Feed the telemetry read by the card (DynamicEq scopeRead layout).</summary>
+ public void Update(float[] scope, int n)
+ {
+ for (int b = 0; b < DynEq.Bands; b++)
{
- if (!BandOn(b)) continue;
- double g = P(b, GainF) + (momentary && IsDyn(b) ? _gr[b] : 0);
- var (b0, b1, b2, a1, a2) = Coeffs(BandType(b), sr, P(b, FreqF), g, P(b, QF));
- double numR = b0 + b1 * cw + b2 * cos2, numI = -(b1 * sw + b2 * sin2);
- double denR = 1 + a1 * cw + a2 * cos2, denI = -(a1 * sw + a2 * sin2);
- double mag2 = (numR * numR + numI * numI) / Math.Max(1e-12, denR * denR + denI * denI);
- total += 10 * Math.Log10(Math.Max(1e-12, mag2));
+ _gr[b] = n > DynEq.S_Gain + b ? scope[DynEq.S_Gain + b] : 0f;
+ _lvl[b] = n > DynEq.S_Level + b ? scope[DynEq.S_Level + b] : -120f;
}
- return total;
+ _specOk = n >= DynEq.kScope && scope[DynEq.S_Analysed] > 0.5f;
+ if (_specOk) Array.Copy(scope, DynEq.kTele, _spec, 0, DynEq.kSpec);
+ _histHead = (_histHead + 1) % HistLen;
+ for (int b = 0; b < DynEq.Bands; b++) _hist[b * HistLen + _histHead] = IsDyn(b) ? _gr[b] : 0f;
+ InvalidateVisual();
}
- // ---- telemetry pull + history ----
- public void Tick()
+ // ---- params ----
+ private float P(int band, int field) => _engine.DeviceGetParam(_track, _device, DynEq.P(band, field));
+ private void SetP(int band, int field, double v) => _engine.DeviceSetParam(_track, _device, DynEq.P(band, field), (float)v);
+ private void Gesture(int p, Action a)
{
- int n = _engine.DeviceScope(_track, _device, _gr, Bands);
- for (int b = n; b < Bands; b++) _gr[b] = 0;
- _histHead = (_histHead + HistLen - 1) % HistLen; // advance ring (write oldest slot)
- for (int b = 0; b < Bands; b++) _histBuf[b * HistLen + _histHead] = _gr[b];
- InvalidateVisual();
+ _engine.BeginAutomationWrite(_track, AutomationTarget.DeviceParam, _device, p, "");
+ a();
+ _engine.EndAutomationWrite(_track, AutomationTarget.DeviceParam, _device, p, "");
}
+ private bool BandOn(int b) => P(b, DynEq.On) > 0.5f;
+ private int BandType(int b) => Math.Clamp((int)Math.Round(P(b, DynEq.TypeF)), 0, 5);
+ private int BandMode(int b) => Math.Clamp((int)Math.Round(P(b, DynEq.ModeF)), 0, 2);
+ private bool DynMaster => _engine.DeviceGetParam(_track, _device, DynEq.DynamicsP) >= 0.5f;
+ private int SoloBand => Math.Clamp((int)Math.Round(_engine.DeviceGetParam(_track, _device, DynEq.SoloP)), 0, DynEq.Bands) - 1;
+ private bool IsDyn(int b) => DynMaster && BandOn(b) && DynEq.HasGain(BandType(b)) && BandMode(b) != DynEq.Static;
private double Sr => _engine.SampleRate > 0 ? _engine.SampleRate : 48000;
- // ---- interaction ----
- private int HitDot(Point p, double w, double h)
+ // ---- geometry: the plot is the whole control ----
+ private double X(double f) => DynEq.FreqToN(f) * Bounds.Width;
+ private double Y(double db) => DynEq.GainToN(db) * Bounds.Height;
+ private Point NodeAt(int b) => new(X(P(b, DynEq.FreqF)), Y(DynEq.HasGain(BandType(b)) ? P(b, DynEq.GainF) : 0));
+
+ private int Hit(Point p)
{
- int best = -1; double bestD = 16 * 16;
- for (int b = 0; b < Bands; b++)
+ int best = -1; double bestD = HitR * HitR;
+ for (int k = 0; k < DynEq.Bands; k++)
{
- if (!BandOn(b)) continue;
- double dx = p.X - FreqToX(P(b, FreqF), w);
- double dy = p.Y - GainToY(HasGain(BandType(b)) ? P(b, GainF) : 0, h);
- double d = dx * dx + dy * dy;
+ int b = (_selected + k) % DynEq.Bands; // the selected node wins a tie
+ var n = NodeAt(b);
+ double d = (p.X - n.X) * (p.X - n.X) + (p.Y - n.Y) * (p.Y - n.Y);
if (d < bestD) { bestD = d; best = b; }
}
return best;
}
+ // ---- interaction ----
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ var p = e.GetPosition(this);
+ if (_drag < 0) { Cursor = Hit(p) >= 0 ? new Cursor(StandardCursorType.Hand) : Cursor.Default; return; }
+ SetP(_drag, DynEq.FreqF, DynEq.NToFreq(p.X / Math.Max(1, Bounds.Width)));
+ if (DynEq.HasGain(BandType(_drag))) SetP(_drag, DynEq.GainF, DynEq.NToGain(p.Y / Math.Max(1, Bounds.Height)));
+ Edited?.Invoke();
+ InvalidateVisual();
+ }
+
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
- double w = Bounds.Width, h = Bounds.Height;
- var pt = e.GetPosition(this);
+ base.OnPointerPressed(e);
+ var p = e.GetPosition(this);
var props = e.GetCurrentPoint(this).Properties;
-
+ int hit = Hit(p);
if (props.IsRightButtonPressed)
{
- int b = HitDot(pt, w, h);
- if (b >= 0) { Select(b); ShowBandMenu(b); e.Handled = true; }
+ if (hit >= 0) { SelectedBand = hit; ShowBandMenu(hit); e.Handled = true; }
return;
}
+ if (!props.IsLeftButtonPressed) return;
if (e.ClickCount == 2)
{
- if (HitDot(pt, w, h) < 0) { AddBandAt(XToFreq(pt.X, w)); e.Handled = true; }
+ if (hit >= 0) Gesture(DynEq.P(hit, DynEq.On), () => SetP(hit, DynEq.On, BandOn(hit) ? 0 : 1));
+ else AddBandAt(p);
+ Edited?.Invoke(); InvalidateVisual(); e.Handled = true;
return;
}
- int hit = HitDot(pt, w, h);
- Select(hit);
- if (hit >= 0)
+ if (hit < 0) return;
+ SelectedBand = hit;
+ _drag = hit;
+ e.Pointer.Capture(this);
+ _gestFreq = true;
+ _engine.BeginAutomationWrite(_track, AutomationTarget.DeviceParam, _device, DynEq.P(hit, DynEq.FreqF), "");
+ if (DynEq.HasGain(BandType(hit)))
{
- _drag = hit; e.Pointer.Capture(this);
- _gestFreq = true; _engine.BeginAutomationWrite(_track, AutomationTarget.DeviceParam, _device, hit * PerBand + FreqF, "");
- if (HasGain(BandType(hit))) { _gestGain = true; _engine.BeginAutomationWrite(_track, AutomationTarget.DeviceParam, _device, hit * PerBand + GainF, ""); }
- Apply(pt, w, h);
+ _gestGain = true;
+ _engine.BeginAutomationWrite(_track, AutomationTarget.DeviceParam, _device, DynEq.P(hit, DynEq.GainF), "");
}
e.Handled = true;
}
- protected override void OnPointerMoved(PointerEventArgs e)
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ EndDrag();
+ e.Pointer.Capture(null);
+ }
+
+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
{
- if (_drag < 0) return;
- Apply(e.GetPosition(this), Bounds.Width, Bounds.Height);
+ EndDrag(); // never leave an automation session dangling
+ base.OnPointerCaptureLost(e);
}
- protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ private void EndDrag()
{
if (_drag >= 0)
{
- if (_gestFreq) _engine.EndAutomationWrite(_track, AutomationTarget.DeviceParam, _device, _drag * PerBand + FreqF, "");
- if (_gestGain) _engine.EndAutomationWrite(_track, AutomationTarget.DeviceParam, _device, _drag * PerBand + GainF, "");
+ if (_gestFreq) _engine.EndAutomationWrite(_track, AutomationTarget.DeviceParam, _device, DynEq.P(_drag, DynEq.FreqF), "");
+ if (_gestGain) _engine.EndAutomationWrite(_track, AutomationTarget.DeviceParam, _device, DynEq.P(_drag, DynEq.GainF), "");
}
_drag = -1; _gestFreq = _gestGain = false;
- e.Pointer.Capture(null);
}
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
- int b = _selected >= 0 && BandOn(_selected) ? _selected : HitDot(e.GetPosition(this), Bounds.Width, Bounds.Height);
- if (b < 0) return;
- double q = Math.Clamp(P(b, QF) * (e.Delta.Y > 0 ? 1.15 : 1 / 1.15), 0.1, 18);
- int pi = b * PerBand + QF;
- _engine.BeginAutomationWrite(_track, AutomationTarget.DeviceParam, _device, pi, "");
- SetP(b, QF, q);
- _engine.EndAutomationWrite(_track, AutomationTarget.DeviceParam, _device, pi, "");
- e.Handled = true; InvalidateVisual();
- }
-
- private void Apply(Point p, double w, double h)
- {
- if (_drag < 0) return;
- SetP(_drag, FreqF, Math.Clamp(XToFreq(p.X, w), Fmin, Fmax));
- if (HasGain(BandType(_drag))) SetP(_drag, GainF, YToGain(p.Y, h));
- InvalidateVisual();
+ base.OnPointerWheelChanged(e);
+ int b = Hit(e.GetPosition(this));
+ if (b < 0) b = _selected;
+ SelectedBand = b;
+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;
+ double step = fine ? 1.03 : 1.15;
+ double q = Math.Clamp(P(b, DynEq.QF) * (e.Delta.Y > 0 ? step : 1 / step), 0.1, 18);
+ Gesture(DynEq.P(b, DynEq.QF), () => SetP(b, DynEq.QF, q));
+ Edited?.Invoke(); InvalidateVisual();
+ e.Handled = true;
}
- private void AddBandAt(double freq)
+ private void AddBandAt(Point p)
{
- for (int b = 0; b < Bands; b++)
+ for (int b = 0; b < DynEq.Bands; b++)
{
if (BandOn(b)) continue;
- SetP(b, On, 1); SetP(b, TypeF, Bell); SetP(b, FreqF, Math.Clamp(freq, Fmin, Fmax));
- SetP(b, GainF, 0); SetP(b, QF, 0.7);
- Select(b); return;
+ double f = DynEq.NToFreq(p.X / Math.Max(1, Bounds.Width)), g = DynEq.NToGain(p.Y / Math.Max(1, Bounds.Height));
+ Gesture(DynEq.P(b, DynEq.TypeF), () => SetP(b, DynEq.TypeF, DynEq.Bell));
+ Gesture(DynEq.P(b, DynEq.FreqF), () => SetP(b, DynEq.FreqF, f));
+ Gesture(DynEq.P(b, DynEq.GainF), () => SetP(b, DynEq.GainF, g));
+ Gesture(DynEq.P(b, DynEq.QF), () => SetP(b, DynEq.QF, 1.0));
+ Gesture(DynEq.P(b, DynEq.ModeF), () => SetP(b, DynEq.ModeF, DynEq.Static));
+ Gesture(DynEq.P(b, DynEq.On), () => SetP(b, DynEq.On, 1));
+ SelectedBand = b;
+ return;
}
}
private void ShowBandMenu(int b)
{
- var flyout = new MenuFlyout();
+ var fly = new MenuFlyout();
int curT = BandType(b);
- for (int t = 0; t < TypeNames.Length; t++)
+ for (int t = 0; t < DynEq.TypeNames.Length; t++)
{
int tt = t;
- var mi = new MenuItem { Header = TypeNames[t], ToggleType = MenuItemToggleType.Radio, IsChecked = t == curT };
- mi.Click += (_, _) => { SetP(b, TypeF, tt); InvalidateVisual(); SelectionChanged?.Invoke(); };
- flyout.Items.Add(mi);
+ var mi = new MenuItem { Header = DynEq.TypeNames[t], ToggleType = MenuItemToggleType.Radio, IsChecked = t == curT };
+ mi.Click += (_, _) => { Gesture(DynEq.P(b, DynEq.TypeF), () => SetP(b, DynEq.TypeF, tt)); Edited?.Invoke(); InvalidateVisual(); };
+ fly.Items.Add(mi);
}
- flyout.Items.Add(new Separator());
+ fly.Items.Add(new Separator());
int curM = BandMode(b);
- for (int m = 0; m < ModeNames.Length; m++)
+ string[] modeWords = { "Static", "Duck — acts above the threshold", "Lift — acts below the threshold" };
+ for (int m = 0; m < 3; m++)
{
int mm = m;
- var mi = new MenuItem { Header = ModeNames[m], ToggleType = MenuItemToggleType.Radio, IsChecked = m == curM, IsEnabled = HasGain(curT) || m == 0 };
- mi.Click += (_, _) =>
- {
- // Seed a working Range when engaging dynamics (default is 0 → no GR ever).
- if (mm != 0 && Math.Abs(P(b, RangeF)) < 0.01) SetP(b, RangeF, mm == 1 ? -6.0 : 6.0);
- SetP(b, ModeF, mm); InvalidateVisual(); SelectionChanged?.Invoke();
- };
- flyout.Items.Add(mi);
+ var mi = new MenuItem { Header = modeWords[m], ToggleType = MenuItemToggleType.Radio, IsChecked = m == curM, IsEnabled = DynEq.HasGain(curT) || m == 0 };
+ mi.Click += (_, _) => { SetMode(_engine, _track, _device, b, mm); Edited?.Invoke(); InvalidateVisual(); };
+ fly.Items.Add(mi);
}
- flyout.Items.Add(new Separator());
- var rm = new MenuItem { Header = "Remove band" };
- rm.Click += (_, _) => { SetP(b, On, 0); if (_selected == b) Select(-1); InvalidateVisual(); SelectionChanged?.Invoke(); };
- flyout.Items.Add(rm);
- flyout.ShowAt(this, showAtPointer: true);
+ fly.Items.Add(new Separator());
+ var on = new MenuItem { Header = "Band on", ToggleType = MenuItemToggleType.CheckBox, IsChecked = BandOn(b) };
+ on.Click += (_, _) => { Gesture(DynEq.P(b, DynEq.On), () => SetP(b, DynEq.On, BandOn(b) ? 0 : 1)); Edited?.Invoke(); InvalidateVisual(); };
+ fly.Items.Add(on);
+ var solo = new MenuItem { Header = "Solo", ToggleType = MenuItemToggleType.CheckBox, IsChecked = SoloBand == b };
+ solo.Click += (_, _) =>
+ {
+ float v = SoloBand == b ? 0 : b + 1;
+ Gesture(DynEq.SoloP, () => _engine.DeviceSetParam(_track, _device, DynEq.SoloP, v));
+ Edited?.Invoke(); InvalidateVisual();
+ };
+ fly.Items.Add(solo);
+ fly.ShowAt(this, showAtPointer: true);
}
- // ---- render ----
- private void Label(DrawingContext ctx, string s, double x, double y, IBrush brush, double size = 8)
- => ctx.DrawText(new FormattedText(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, size, brush), new Point(x, y));
- private void DotLabel(DrawingContext ctx, string s, double cx, double cy, IBrush brush, double size)
+ /// <summary>Switch a band's mode. Duck seeds a cut and Lift a boost (6 dB when Range is
+ /// empty); a range already flipped the other way (upward expansion, downward expansion) is
+ /// kept by magnitude only when the mode actually changes.</summary>
+ internal static void SetMode(IAudioEngine engine, int track, int device, int band, int mode)
{
- var ft = new FormattedText(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, DotFont, size, brush);
- ctx.DrawText(ft, new Point(cx - ft.Width / 2, cy - ft.Height / 2));
+ int pm = DynEq.P(band, DynEq.ModeF), pr = DynEq.P(band, DynEq.RangeF);
+ int cur = Math.Clamp((int)Math.Round(engine.DeviceGetParam(track, device, pm)), 0, 2);
+ if (mode != DynEq.Static && mode != cur)
+ {
+ float r = Math.Abs(engine.DeviceGetParam(track, device, pr));
+ if (r < 0.05f) r = 6f;
+ float nr = mode == DynEq.Duck ? -r : r;
+ engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, device, pr, "");
+ engine.DeviceSetParam(track, device, pr, nr);
+ engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, device, pr, "");
+ }
+ engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, device, pm, "");
+ engine.DeviceSetParam(track, device, pm, mode);
+ engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, device, pm, "");
}
+ // ---- render ----
+ private static FormattedText Text(string s, IBrush ink, double size, bool bold = false, bool mono = true)
+ => new(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
+ mono ? (bold ? NotaFonts.MonoBold : NotaFonts.Mono) : bold ? NotaFonts.SansBold : NotaFonts.Sans, size, ink);
+
public override void Render(DrawingContext ctx)
{
double w = Bounds.Width, h = Bounds.Height, sr = Sr;
if (w <= 0 || h <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
-
- // grid
- double[] majors = { 100, 1000, 10000 };
- double[] minors = { 30, 50, 70, 200, 300, 500, 700, 2000, 3000, 5000, 7000, 20000 };
- foreach (var f in minors) { double x = FreqToX(f, w); ctx.DrawLine(GridPenFaint, new Point(x, 0), new Point(x, h)); }
- foreach (var f in majors)
- {
- double x = FreqToX(f, w);
- ctx.DrawLine(GridPen, new Point(x, 0), new Point(x, h));
- }
- for (int db = -12; db <= 12; db += 6)
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ using var clip = ctx.PushClip(new RoundedRect(frame.Deflate(1), NotaGraph.Radius));
+
+ // grid: 100 Hz · 1 kHz (stronger) · 10 kHz; ±6 / ±12 dB, 0 dB stronger
+ foreach (var f in new[] { 100.0, 10000.0 }) ctx.DrawLine(GridFaint, new Point(X(f), 0), new Point(X(f), h));
+ ctx.DrawLine(GridMid, new Point(X(1000), 0), new Point(X(1000), h));
+ foreach (var db in new[] { -12.0, -6.0, 6.0, 12.0 }) ctx.DrawLine(GridFaint, new Point(0, Y(db)), new Point(w, Y(db)));
+ ctx.DrawLine(ZeroPen, new Point(0, Y(0)), new Point(w, Y(0)));
+
+ // band state + coefficients
+ int solo = SoloBand;
+ var on = new bool[DynEq.Bands];
+ var live = new DynEq.Bq[DynEq.Bands];
+ var stat = new DynEq.Bq[DynEq.Bands];
+ for (int b = 0; b < DynEq.Bands; b++)
{
- double y = GainToY(db, h);
- ctx.DrawLine(db == 0 ? ZeroPen : GridPen, new Point(0, y), new Point(w, y));
+ on[b] = solo >= 0 ? b == solo : BandOn(b);
+ if (!on[b]) continue;
+ int ty = BandType(b);
+ double f = P(b, DynEq.FreqF), g = P(b, DynEq.GainF), q = P(b, DynEq.QF);
+ stat[b] = DynEq.Coeffs(ty, sr, f, g, q);
+ live[b] = IsDyn(b) ? DynEq.Coeffs(ty, sr, f, g + _gr[b], q) : stat[b];
}
- // The range is labelled in the bottom corners and nowhere else — no full axes.
- NotaGraph.Axis(ctx, new Rect(0, 0, w, h), NotaGraph.Corner.BottomLeft, "20");
- NotaGraph.Axis(ctx, new Rect(0, 0, w, h), NotaGraph.Corner.BottomRight, "20k Hz");
+ int sel = _selected;
+ int selT = BandType(sel);
+ var selK = DynEq.Coeffs(selT, sr, P(sel, DynEq.FreqF), P(sel, DynEq.GainF) + (IsDyn(sel) ? _gr[sel] : 0), P(sel, DynEq.QF));
- // reach lines for dynamic bands (how far each can travel)
- for (int b = 0; b < Bands; b++)
+ // spectrum (output, 0 dBFS at the top … −80 at the bottom)
+ if (_specOk)
{
- if (!IsDyn(b)) continue;
- double x = FreqToX(P(b, FreqF), w);
- double y0 = GainToY(P(b, GainF), h);
- double y1 = GainToY(P(b, GainF) + P(b, RangeF), h);
- ctx.DrawLine(ReachPen, new Point(x, y0), new Point(x, y1));
+ var sg = new StreamGeometry();
+ using (var g = sg.Open())
+ for (int i = 0; i < DynEq.kSpec; i++)
+ {
+ double x = (i + 0.5) / DynEq.kSpec * w;
+ double y = Math.Clamp(-_spec[i] / 80.0, 0, 1) * h;
+ if (i == 0) g.BeginFigure(new Point(x, y), false); else g.LineTo(new Point(x, y));
+ }
+ ctx.DrawGeometry(null, SpecPen, sg);
}
- // static curve (brass)
- DrawCurve(ctx, w, h, sr, false, CurveFill, CurvePen);
- // momentary curve (teal dashed) — only meaningful when something is engaged
- DrawCurve(ctx, w, h, sr, true, null, DynPen);
-
- // band dots
- for (int b = 0; b < Bands; b++)
+ // curves
+ var gl = new StreamGeometry(); var gs = new StreamGeometry(); var gx = new StreamGeometry();
+ double diff = 0;
+ using (var cl = gl.Open())
+ using (var cs = gs.Open())
+ using (var cx = gx.Open())
+ for (int i = 0; i < Pts; i++)
+ {
+ double n = i / (double)(Pts - 1), x = n * w;
+ double wv = 2 * Math.PI * DynEq.NToFreq(n) / sr;
+ double l = 0, s = 0;
+ for (int b = 0; b < DynEq.Bands; b++)
+ {
+ if (!on[b]) continue;
+ l += DynEq.MagDb(live[b], wv);
+ s += DynEq.MagDb(stat[b], wv);
+ }
+ diff = Math.Max(diff, Math.Abs(l - s));
+ var pl = new Point(x, Math.Clamp(Y(l), -2, h + 2));
+ var ps = new Point(x, Math.Clamp(Y(s), -2, h + 2));
+ var px = new Point(x, Math.Clamp(Y(DynEq.MagDb(selK, wv)), -2, h + 2));
+ if (i == 0) { cl.BeginFigure(pl, false); cs.BeginFigure(ps, false); cx.BeginFigure(px, false); }
+ else { cl.LineTo(pl); cs.LineTo(ps); cx.LineTo(px); }
+ }
+ if (BandOn(sel)) ctx.DrawGeometry(null, SelPen, gx);
+ if (diff > 0.05) ctx.DrawGeometry(null, StaticPen, gs);
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, gl);
+
+ // axis labels
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "20");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "20k Hz");
+ var k1 = NotaGraph.AxisText("1k");
+ ctx.DrawText(k1, new Point(X(1000) + 3, h - 4 - k1.Height + 1));
+ var p12 = NotaGraph.AxisText("+12", null, 6); var m12 = NotaGraph.AxisText("−12", null, 6);
+ ctx.DrawText(p12, new Point(w - 5 - p12.Width, Y(12) - p12.Height - 1));
+ ctx.DrawText(m12, new Point(w - 5 - m12.Width, Y(-12) + 1));
+
+ // title + legend
+ var title = solo >= 0 ? NotaNum.F($"SOLO · B{solo + 1}") : "RESPONSE";
+ ctx.DrawText(Text(title, solo >= 0 ? NotaPalette.AccentBright : NotaGraph.TitleInk, 7, bold: true, mono: false), new Point(5, 3));
+ NotaGraph.Legend(ctx, w - 5, 2, ("static", NotaPalette.TealBright, NotaGraph.Mark.Dashed), ("live", NotaPalette.AccentBright, NotaGraph.Mark.Line));
+
+ // whiskers (dynamic bands): node → where Range can take it, a dot at the gain it has now
+ for (int b = 0; b < DynEq.Bands; b++)
{
- bool on = BandOn(b);
- int type = BandType(b);
- double x = FreqToX(P(b, FreqF), w);
- double y = GainToY(HasGain(type) ? P(b, GainF) : 0, h);
- // Almanac node: selected brass, the rest Ink 3; a dynamic band keeps its teal
- // (modulation) and an off band drops to Ink 6. The band number is in the readout.
- bool sel = b == _selected;
- IBrush? ink = !on ? NotaPalette.TextDisabled : sel ? null : IsDyn(b) ? NotaPalette.Teal : null;
- NotaGraph.Node(ctx, new Point(x, y), sel, ink);
+ if (!IsDyn(b) || !on[b]) continue;
+ double g = P(b, DynEq.GainF), r = P(b, DynEq.RangeF);
+ var ink = r >= 0 ? NotaPalette.Rose : NotaPalette.TealBright;
+ double x = Math.Round(X(P(b, DynEq.FreqF))) + 0.5, y0 = Y(g), y1 = Y(g + r);
+ ctx.DrawLine(new Pen(ink, 1) { DashStyle = new DashStyle(new double[] { 2, 2 }, 0) }, new Point(x, y0), new Point(x, y1));
+ ctx.DrawLine(new Pen(ink, 1), new Point(x - 3.5, y1), new Point(x + 3.5, y1));
+ ctx.DrawEllipse(ink, null, new Point(x, Y(g + _gr[b])), 2.5, 2.5);
}
- // readout
- string txt;
- if (_selected >= 0 && BandOn(_selected))
+ // nodes (selected last, on top)
+ for (int k = 1; k <= DynEq.Bands; k++)
{
- int b = _selected, type = BandType(b);
- string dynTxt = IsDyn(b) ? $" {(BandMode(b) == 1 ? "↓" : "↑")} {P(b, RangeF):+0.0;−0.0}\u2009dB · GR {_gr[b]:+0.0;−0.0;0.0}" : "";
- txt = string.Format(NotaNum.Culture, "B{0} {1} {2:0} Hz{3} Q {4:0.00}{5}",
- b + 1, TypeNames[type], P(b, FreqF),
- HasGain(type) ? $" {P(b, GainF):+0.0;−0.0}\u2009dB" : "", P(b, QF), dynTxt);
+ int b = (sel + k) % DynEq.Bands;
+ bool bOn = BandOn(b), isSel = b == sel, dimmed = solo >= 0 && !isSel;
+ var c = NodeAt(b);
+ IBrush fill = !bOn || dimmed ? NotaPalette.BorderStrong : isSel ? NotaPalette.AccentBright : NotaPalette.TextSecondary;
+ IBrush num = bOn && !dimmed ? NotaPalette.TextOnAccent : NotaPalette.TextTertiary;
+ double r = NodeD / 2;
+ ctx.DrawEllipse(fill, RingPen, c, r + 1, r + 1);
+ if (IsDyn(b) && on[b])
+ ctx.DrawEllipse(null, new Pen(P(b, DynEq.RangeF) >= 0 ? NotaPalette.Rose : NotaPalette.TealBright, 1), c, r + 2.5, r + 2.5);
+ var t = Text(NotaNum.F($"{b + 1}"), num, 7, bold: true);
+ ctx.DrawText(t, new Point(c.X - t.Width / 2, c.Y - t.Height / 2));
}
- else
- {
- int active = 0; for (int b = 0; b < Bands; b++) if (BandOn(b)) active++;
- txt = $"{active}/8 bands · double-click to add · right-click a dot for type/dynamics · wheel = Q";
- }
- Label(ctx, txt, 6, 4, LabelBright);
+
+ DrawTip(ctx, w, h);
}
- private void DrawCurve(DrawingContext ctx, double w, double h, double sr, bool momentary, IBrush? fill, IPen pen)
+ // The selected band's reading beside its node, clear of the node and inside the window.
+ private void DrawTip(DrawingContext ctx, double w, double h)
{
- const int n = 160;
- var curve = new StreamGeometry();
- var fillGeo = fill != null ? new StreamGeometry() : null;
- using (var gc = curve.Open())
- {
- var gf = fillGeo?.Open();
- gf?.BeginFigure(new Point(0, h / 2), true);
- for (int i = 0; i <= n; i++)
+ int b = _selected, ty = BandType(b);
+ bool bOn = BandOn(b), g = DynEq.HasGain(ty), dyn = IsDyn(b);
+ double r = P(b, DynEq.RangeF);
+ var a = Text(NotaNum.F($"B{b + 1} {DynEq.TypeNames[ty]}") + (bOn ? "" : " · off"), NotaPalette.AccentBright, 8, bold: true, mono: false);
+ var l2 = Text(DynEq.Hz(P(b, DynEq.FreqF)) + (g ? " · " + DynEq.Db(P(b, DynEq.GainF)) + " dB" : "") + NotaNum.F($" · Q {P(b, DynEq.QF):0.00}"),
+ NotaPalette.TextPrimary, 7);
+ IBrush dynInk = r >= 0 ? NotaPalette.RoseBright : NotaPalette.TealBright;
+ string c = dyn ? (r >= 0 ? "↑ " : "↓ ") + DynEq.Db(_gr[b]) + " dB of " + DynEq.Db(r)
+ : !g ? "no dynamics" : BandMode(b) != DynEq.Static && !DynMaster ? "dynamics off" : "static";
+ var l3 = Text(c, dyn ? dynInk : NotaPalette.TextTertiary, 7);
+ double histH = dyn ? 12 : 0;
+ double tw = Math.Max(a.Width, Math.Max(l2.Width, l3.Width)) + 12, th = a.Height + l2.Height + l3.Height + 6 + histH;
+ var n = NodeAt(b);
+ double x = n.X > w * 0.62 ? n.X - 12 - tw : n.X + 12;
+ double y = n.Y < h * 0.34 ? n.Y + 8 : n.Y - 8 - th;
+ x = Math.Clamp(x, 3, Math.Max(3, w - tw - 3)); y = Math.Clamp(y, 3, Math.Max(3, h - th - 3));
+ var box = new Rect(x, y, tw, th);
+ ctx.DrawRectangle(NotaPalette.SurfaceCard, new Pen(NotaPalette.BorderStrong, 1), new RoundedRect(box.Deflate(0.5), 3));
+ double ty0 = y + 3;
+ ctx.DrawText(a, new Point(x + 6, ty0)); ty0 += a.Height;
+ ctx.DrawText(l2, new Point(x + 6, ty0)); ty0 += l2.Height;
+ ctx.DrawText(l3, new Point(x + 6, ty0)); ty0 += l3.Height;
+ if (!dyn) return;
+ // 2-second history of the band's dynamic gain, 0 dB at the top for a cut, the bottom for a boost.
+ double hx0 = x + 6, hx1 = x + tw - 6, hy0 = ty0 + 1, hy1 = ty0 + histH - 2, span = Math.Max(1, Math.Abs(r));
+ ctx.DrawLine(new Pen(NotaPalette.GridBeat, 1), new Point(hx0, r >= 0 ? hy1 : hy0), new Point(hx1, r >= 0 ? hy1 : hy0));
+ var sg = new StreamGeometry();
+ using (var gg = sg.Open())
+ for (int i = 0; i < HistLen; i++)
{
- double x = w * i / n;
- double y = Math.Clamp(GainToY(MagnitudeDb(XToFreq(x, w), sr, momentary), h), -2, h + 2);
- var pt = new Point(x, y);
- if (i == 0) gc.BeginFigure(pt, false); else gc.LineTo(pt);
- gf?.LineTo(pt);
+ float v = _hist[b * HistLen + (_histHead + 1 + i) % HistLen];
+ double t = Math.Clamp(Math.Abs(v) / span, 0, 1);
+ var pt = new Point(hx0 + (hx1 - hx0) * i / (HistLen - 1), r >= 0 ? hy1 - t * (hy1 - hy0) : hy0 + t * (hy1 - hy0));
+ if (i == 0) gg.BeginFigure(pt, false); else gg.LineTo(pt);
}
- if (gf != null) { gf.LineTo(new Point(w, h / 2)); gf.EndFigure(true); gf.Dispose(); }
- }
- // No fill under the curve (almanac § Visualisations); the fill argument is ignored.
- ctx.DrawGeometry(null, pen, curve);
+ ctx.DrawGeometry(null, new Pen(dynInk, 1), sg);
}
}
diff --git a/src/managed/Nota.App/Controls/SliderTrack.cs b/src/managed/Nota.App/Controls/SliderTrack.cs
index 7920fa2c..00d5b738 100644
--- a/src/managed/Nota.App/Controls/SliderTrack.cs
+++ b/src/managed/Nota.App/Controls/SliderTrack.cs
@@ -46,6 +46,15 @@ internal sealed class SliderTrack : Control
/// <summary>A modulation depth: teal fill and handle instead of brass.</summary>
public bool Modulation { get; init; }
+ /// <summary>A role chroma for the fill (teal / rose), overriding brass or Modulation; its
+ /// light tone draws the handle. May change live.</summary>
+ public IBrush? Ink { get => _ink; set { if (ReferenceEquals(_ink, value)) return; _ink = value; InvalidateVisual(); } }
+ private IBrush? _ink;
+
+ /// <summary>A 1px teal mark at this 0..1 position (a live level against the value); NaN hides it.</summary>
+ public double Marker { get => _marker; set { if (value.Equals(_marker)) return; _marker = value; InvalidateVisual(); } }
+ private double _marker = double.NaN;
+
/// <summary>Double-click handler (restore the default). Null disables double-click.</summary>
public Action? Reset { get; init; }
@@ -128,12 +137,17 @@ internal sealed class SliderTrack : Control
double x = _norm * w;
double a = Bipolar ? Math.Min(w / 2, x) : 0, b = Bipolar ? Math.Max(w / 2, x) : x;
if (b - a > 0.5)
- ctx.DrawRectangle(_dim ? FillDim : Modulation ? ModFill : Fill, null, new RoundedRect(new Rect(a, ty, b - a, TrackH), NotaRadius.ClipValue));
+ ctx.DrawRectangle(_dim ? FillDim : _ink ?? (Modulation ? ModFill : Fill), null, new RoundedRect(new Rect(a, ty, b - a, TrackH), NotaRadius.ClipValue));
if (Bipolar)
ctx.FillRectangle(Centre, new Rect(Math.Round(w / 2) - 0.5, cy - 3, 1, 6));
+ if (!double.IsNaN(_marker) && !_dim)
+ ctx.FillRectangle(ModHandle, new Rect(Math.Round(Math.Clamp(_marker, 0, 1) * (w - 1)), 0, 1, h));
+
double hx = Math.Clamp(x, HandleW / 2, w - HandleW / 2) - HandleW / 2;
- ctx.DrawRectangle(_dim ? HandleDim : Modulation ? ModHandle : Handle, null,
+ IBrush inkHandle = ReferenceEquals(_ink, NotaPalette.Rose) ? NotaPalette.RoseBright
+ : ReferenceEquals(_ink, NotaPalette.Teal) ? ModHandle : _ink ?? (Modulation ? ModHandle : Handle);
+ ctx.DrawRectangle(_dim ? HandleDim : inkHandle, null,
new RoundedRect(new Rect(hx, cy - HandleH / 2, HandleW, HandleH), NotaRadius.ClipValue));
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CrushDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CrushDeviceBody.cs
index 7fd94d0e..4aa10f9b 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/CrushDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/CrushDeviceBody.cs
@@ -1,17 +1,23 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Crush (device kind 12) body, built to mockup 3l:
-// a 700×260 standard shell with a LIVE strip (Bits · Rate · WET sliders + Anti-Alias
-// toggle), a quantiser waveform display + spectrum, a MODE selector (Digital/Analog/
-// Fold), a GRIT panel (Dither/Jitter/Noise Floor, teal spine), and an OUTPUT panel
-// (Post Filter / Dry/Wet). All controls are the device's generic params → automation
-// + persist for free.
+// Detail · Devices — built-in Nota Crush body (bit crusher, device kind 12), a build of the
+// "Nota Crush" mockup (700 × 260) on the Ceiling / Beat Repeat frame: an always-visible CRUSH
+// column (input · output), a centre panel with Quantiser / Spectrum / Transfer tabs — the held
+// and quantised steps over a sine (drag: Bits up / down, Rate left / right), the output
+// spectrum from the engine's FFT with what the crush added and the images above the reduced
+// Nyquist (drag the Nyquist and the filter lines), the transfer curve with the form it makes
+// (drag: Drive) — with Mode and Anti-alias over the graph and Bits / Rate / Drive / Wet under
+// it, a right panel with Grit / Output tabs, and a status strip. The meters and the spectrum
+// come from the engine (Crush.h scopeRead). Every control is a device param (normalized 0..1),
+// so automation / MIDI learn / presets / A-B / persistence come for free.
+// 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;
@@ -22,360 +28,501 @@ namespace Nota.App;
internal sealed class CrushDeviceBody : IDeviceBody
{
- // Param indices — must match Crush.h.
- private const int Bits = 0, Rate = 1, Mode = 2, Dither = 3, Jitter = 4, NoiseFloor = 5,
- PostFilter = 6, DryWet = 7, AntiAlias = 8, Output = 9, Drive = 10;
+ // ── Parameter indices (must match Crush.h) ───────────────────────────────
+ private const int Bits = 0, Rate = 1, Mode = 2, Dither = 3, Jitter = 4, NoiseFloor = 5, PostFilter = 6, DryWet = 7,
+ AntiAlias = 8, Output = 9, Drive = 10, AutoGain = 11, DcFilter = 12, kParams = 13;
+ // Scope layout (Crush::S_* / kTele / kBands).
+ private const int S_InPeak = 0, S_OutPeak = 1, S_InRms = 2, S_OutRms = 3, S_Crest = 4, S_SampleRate = 5, S_RateHz = 6,
+ S_Hold = 7, S_Bits = 8, S_Levels = 9, S_QuantNoise = 10, S_ThdN = 11, S_Images = 12, S_AutoGain = 13, S_Cpu = 14,
+ S_Latency = 15, S_DrivenPeak = 16, S_Folds = 17, S_Nyquist = 20, S_FilterHz = 21, S_Analysed = 22, S_Signal = 23,
+ kTele = 32, kBands = 40, kScope = kTele + 2 * kBands;
- private static readonly string[] Modes = { "Digital", "Analog", "Fold" };
- private static readonly string[] ModeSubs = { "hard truncate", "soft clip", "wavefold" };
- // Defaults mirror Crush.h constructor (index order): Bits, Rate, Mode, Dither, Jitter,
- // NoiseFloor, PostFilter, DryWet, AntiAlias, Output, Drive.
- private static readonly float[] Defaults = { 0.55f, 0.35f, 0f, 0.15f, 0f, 0f, 0.85f, 1f, 0f, 0.5f, 0.333f };
-
- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;
- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
- private static readonly IBrush Border2 = NotaPalette.BorderDefault;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush FieldBorder = NotaPalette.GraphBorder;
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush TealC = NotaPalette.Teal;
- private static readonly IBrush TxtC = NotaPalette.TextPrimary;
- private static readonly IBrush MutedC = NotaPalette.TextTertiary;
- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);
- private static readonly IBrush TealSubtle = NotaPalette.Wash(NotaPalette.Teal, 0x24);
- private static readonly IBrush RowLit = NotaPalette.SurfaceRaised;
- internal static readonly IBrush GridLine = NotaPalette.SurfaceCard;
- internal static readonly IBrush GridCenter = NotaPalette.BorderDefault;
- internal static readonly IBrush SrcLine = NotaPalette.TextDisabled;
- internal static readonly IBrush NyqLine = NotaPalette.Wash(NotaPalette.AccentBright, 0x73);
+ private static readonly string[] ModeWords = { "hard truncate", "soft clip", "wavefold" };
public double Width => 700;
-
- public string? Subtitle => "BITCRUSHER"; // the processing type, shown as the header badge
public bool FullBleed => true;
+ public string? Subtitle => "BITCRUSHER";
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 Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ void Raw(int p, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1));
+ // 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); }
+ double Def(int p) => engine.DeviceParamDefault(track, di, p);
+ bool On(int p) => P(p) >= 0.5f;
+ int ModeI() => Math.Clamp((int)Math.Round(P(Mode) * 2), 0, 2);
var readouts = new List<Action>();
-
- // ---- formatters ----
- string BitsF(double v) => $"{1 + v * 23:0.0}\u2009bit";
- string RateF(double v) { double hz = Exp(v, 500, 44100 * 0.48); return hz >= 1000 ? $"{hz / 1000:0.0}\u2009k" : $"{(int)Math.Round(hz)}\u2009Hz"; }
- static string PctF(double v) => $"{v * 100:0}\u2009%";
- static string DriveF(double v) { double db = -12 + v * 36; return $"{(db >= 0 ? "+" : "")}{db:0.0}\u2009dB"; }
- static string GainF(double v) { double db = (v - 0.5) * 24; return $"{(db >= 0 ? "+" : "")}{db:0.0}\u2009dB"; }
-
- // ---- quantiser viz ----
- var quantViz = new CrushQuantiserViz { VerticalAlignment = VerticalAlignment.Stretch };
- void SyncQuant() => quantViz.Set(P(Bits), P(Rate), P(Mode), P(Dither), P(Jitter), P(NoiseFloor), P(Drive));
- ctx.AddDeviceRefresher(quantViz.Tick);
-
- // ---- spectrum viz ----
- var specViz = new CrushSpectrumViz { VerticalAlignment = VerticalAlignment.Stretch };
- void SyncSpec() => specViz.Set(P(Bits), P(Rate), P(AntiAlias));
- ctx.AddDeviceRefresher(specViz.Tick);
-
- static TextBlock Cap(string t, IBrush? c = null) => new() { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, VerticalAlignment = VerticalAlignment.Center };
-
- // ---- horizontal param slider (LIVE strip + rails) ----
- Control HSlider(int p, string label, Func<double, string> fmt, double lw, double vw, bool bipolar = false)
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
+ var scope = new float[kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+ double ScDb(int i) => scN > i ? scope[i] : -120;
+
+ // ---- mappings (Crush.h) and units -------------------------------------------------
+ double Sr() => Sc(S_SampleRate) > 0 ? Sc(S_SampleRate) : 44100;
+ double BitsOf(double v) => 1 + Math.Clamp(v, 0, 1) * 23;
+ double RateHz(double v) => 500 * Math.Pow(Sr() * 0.48 / 500, Math.Clamp(v, 0, 1));
+ double RateNorm(double hz) => Math.Log(Math.Clamp(hz, 500, Sr() * 0.48) / 500) / Math.Log(Sr() * 0.48 / 500);
+ static double FiltHz(double v) => 200 * Math.Pow(100, Math.Clamp(v, 0, 1));
+ static double FiltNorm(double hz) => Math.Log(Math.Clamp(hz, 200, 20000) / 200) / Math.Log(100);
+ static double DriveDb(double v) => -12 + v * 36;
+ static double GainDb(double v) => (v - 0.5) * 24;
+ double Hold() => Math.Max(1, Sr() / RateHz(P(Rate)));
+ double Levels() => Math.Pow(2, BitsOf(P(Bits)));
+
+ static string Sgn(double v) => NotaNum.F($"{v:+0.0;−0.0;0.0}");
+ static string Lvl(double db) => db <= -119 ? "—" : Sgn(db);
+ static string Hz(double hz) => CrushMath.Hz(hz);
+ static string KHz(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.#}\u2009k") : NotaNum.F($"{hz:0}");
+ static string Pct(double v) => NotaNum.F($"{v * 100:0}\u2009%");
+ static string LvF(double lv) => lv >= 1e6 ? NotaNum.F($"{lv / 1e6:0.0}\u2009M") : lv >= 1e4 ? NotaNum.F($"{lv / 1e3:0.0}\u2009k") : NotaNum.F($"{lv:0}");
+ string BitsF(double v) => NotaNum.F($"{BitsOf(v):0.0}");
+ string RateF(double v) => Hz(RateHz(v));
+ static string DriveF(double v) => Sgn(DriveDb(v)) + " dB";
+ static string GainF(double v) => Sgn(GainDb(v)) + " dB";
+ static string FiltF(double v) => Hz(FiltHz(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 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; }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+
+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
+ // `lit` lights the label and value (the knob the current tab is about).
+ Control K(int p, string name, Func<double, string> fmt, string tip, Func<bool>? lit = null, bool teal = false)
{
- var row = DeviceCardKit.SliderRow(lw > 0 ? label : "", () => P(p), n => { SetP(p, (float)n); SyncQuant(); SyncSpec(); }, () => fmt(P(p)), out var sync,
- begin: () => Begin(p), end: () => End(p), bipolar: bipolar, labelWidth: lw, valueWidth: vw);
- readouts.Add(sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);
- return row;
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(P(p), 1.0) { Accent = true, Default = Def(p), Width = 34, Height = 34 };
+ if (teal) knob.ArcColor = Teal;
+ knob.ValueChanged += v => { Raw(p, v); val.Text = fmt(P(p)); RefreshAll(); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ ToolTip.SetTip(knob, tip);
+ var cell = KnobCell(name, knob, val, 50);
+ TextBlock? label = null;
+ if (cell is Panel pl) foreach (var c in pl.Children) if (c is TextBlock tb && tb != val) { label = tb; break; }
+ readouts.Add(() =>
+ {
+ if (!knob.Dragging) { double c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; }
+ val.Text = fmt(P(p));
+ bool on = lit?.Invoke() ?? false;
+ val.Foreground = on ? AccentBright : TextPrimary;
+ if (label is not null) label.Foreground = on ? AccentBright : TextTertiary;
+ });
+ return cell;
}
- // ---- rail slider (teal for GRIT) ----
- Control RailSlider(int p, string label, Func<double, string> fmt, IBrush? color = null)
+ // On/off switch bound to a param (>= 0.5 = on), with an optional live word.
+ Control Toggle(int p, string label, string tip, Func<string>? live = null)
{
- var row = DeviceCardKit.SliderRow(label, () => P(p), n => { SetP(p, (float)n); SyncQuant(); SyncSpec(); }, () => fmt(P(p)), out var sync,
- begin: () => Begin(p), end: () => End(p), labelWidth: 38, valueWidth: 48);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);
+ var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); RefreshAll(); }, out var sync, liveLabel: live);
readouts.Add(sync);
- return row;
+ Learn(wrap, p);
+ ToolTip.SetTip(wrap, tip);
+ return wrap;
}
- // ---- mode selector chips ----
- Control ModeSelector()
+ // A latching chip bound to an on/off param.
+ Border ParamChip(int p, string text, string tip)
{
- var chips = new Border[Modes.Length]; var texts = new TextBlock[Modes.Length]; var subs = new TextBlock[Modes.Length];
- void Sync() { int cur = (int)Math.Round(P(Mode) * 2); for (int i = 0; i < Modes.Length; i++) { bool on = i == cur; chips[i].Background = on ? Amber : Inset; chips[i].BorderBrush = on ? Amber : Border2; texts[i].Foreground = on ? NotaPalette.TextOnAccent : MutedC; subs[i].Foreground = on ? NotaPalette.TextOnAccent : MutedC; } }
- var col = new StackPanel { Spacing = 2 };
- for (int i = 0; i < Modes.Length; i++)
+ var tb = new TextBlock { Text = text, FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ void Hi()
{
- int iv = i;
- var tb = new TextBlock { Text = Modes[i], FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = MutedC };
- var sub = new TextBlock { Text = ModeSubs[i], FontSize = 8, Foreground = MutedC };
- var c = new Border { Height = 15, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { tb, new TextBlock { Text = ModeSubs[i], FontSize = 8, Foreground = MutedC, [DockPanel.DockProperty] = Dock.Right } } } };
- c.PointerPressed += (_, e) => { e.Handled = true; SetP(Mode, iv / 2f); SyncQuant(); SyncSpec(); RefreshAll(); };
- chips[i] = c; texts[i] = tb; subs[i] = sub; col.Children.Add(c);
+ bool on = On(p);
+ b.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
+ b.BorderBrush = on ? Brass : NotaPalette.BorderStrong;
+ tb.Foreground = on ? AccentBright : TextSecondary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
}
- readouts.Add(Sync);
- MidiLearn.Bind(col, MidiTarget.DeviceParam(track, di, Mode), engine.DeviceParamName(track, di, Mode));
- return col;
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; SetP(p, On(p) ? 0f : 1f); RefreshAll(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ Learn(b, p);
+ readouts.Add(Hi); Hi();
+ return b;
}
- // ---- anti-alias toggle ----
- Control AaToggle()
+ // Slider row: caps label · track · mono value.
+ Control SliderRow(string label, int p, Func<double, string> fmt, string tip, bool modulation = false, bool bipolar = false)
{
- var sw = new ToggleSwitch(P(AntiAlias) >= 0.5f);
- sw.Changed += on => { SetP(AntiAlias, on ? 1f : 0f); SyncSpec(); };
- readouts.Add(() => { bool on = P(AntiAlias) >= 0.5f; if (sw.IsOn != on) sw.IsOn = on; });
- var host = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { sw, new TextBlock { Text = "ANTI-ALIAS", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TealC, VerticalAlignment = VerticalAlignment.Center } } };
- MidiLearn.Bind(host, MidiTarget.DeviceParam(track, di, AntiAlias), engine.DeviceParamName(track, di, AntiAlias));
- return host;
+ var bar = DeviceCardKit.SliderRow("", () => P(p), v => { Raw(p, v); RefreshAll(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: 38, modulation: modulation, bipolar: bipolar);
+ readouts.Add(sync);
+ Learn(bar, p);
+ ToolTip.SetTip(bar, tip);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("40,*"), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label));
+ g.Children.Add(Col(bar, 1));
+ return g;
}
- // ---- rail button (Init / Bypass) ----
- Control RailBtn(string label, Action onClick)
+ static Grid HeadRow(Control left, Control right)
{
- var b = new Border { Background = RowLit, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(0, 2), HorizontalAlignment = HorizontalAlignment.Stretch, Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = label, FontSize = 9, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center } };
- b.PointerPressed += (_, e) => { e.Handled = true; onClick(); };
- return b;
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 18, ColumnSpacing = 6 };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
+ }
+ Control ModeHead()
+ {
+ var seg = Segments(CrushMath.Modes, ModeI, i => { SetP(Mode, i / 2f); RefreshAll(); }, out var sync, padX: 6);
+ readouts.Add(sync);
+ Learn(seg, Mode);
+ ToolTip.SetTip(seg, "Mode — Digital: hard truncation to the levels; Analog: a soft tanh clip before them (+4\u2009dB, rounder); Fold: a wavefolder — more Drive folds the peaks back more times");
+ var words = new TextBlock { FontSize = 7, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ readouts.Add(() => words.Text = ModeWords[ModeI()]);
+ var aa = ParamChip(AntiAlias, "Anti-alias", "Anti-alias — a 4th-order low-pass at the reduced rate's Nyquist before the hold, so less folds back as images");
+ return HeadRow(Row(6, Caps("MODE"), seg, words), aa);
}
- // ================= LIVE strip =================
- var live = new Border { Height = 34, Background = HdrBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new DockPanel { LastChildFill = false, Margin = new Thickness(9, 0), Children = {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 150, Children = { Cap("BITS"), HSlider(Bits, "", BitsF, 0, 50) } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 156, Children = { Cap("RATE"), HSlider(Rate, "", RateF, 0, 54) } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 150, Children = { Cap("DRIVE"), HSlider(Drive, "", DriveF, 0, 52) } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 98, Children = { Cap("WET"), HSlider(DryWet, "", PctF, 0, 32) } } } },
- new StackPanel { [DockPanel.DockProperty] = Dock.Right, VerticalAlignment = VerticalAlignment.Center, Children = { AaToggle() } } } } };
-
- // ================= quantiser panel =================
- var Dim = NotaPalette.TextDisabled;
- static TextBlock Tiny(string t, IBrush c) => new() { Text = t, FontSize = 8, Foreground = c, VerticalAlignment = VerticalAlignment.Center };
- TextBlock TinyMono(string t, IBrush c) { var b = Tiny(t, c); b.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return b; }
-
- var quantSpec = TinyMono("", Amber); // "6.0-bit @ 11.0\u2009kHz"
- var quantHdr = new DockPanel { LastChildFill = false, Height = 11, Children = {
- WithDock(new TextBlock { Text = "QUANTISER", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center }, Dock.Left),
- WithDock(quantSpec, Dock.Right),
- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 6, 0), Children = {
- new Avalonia.Controls.Shapes.Line { StartPoint = new Point(0, 0), EndPoint = new Point(10, 0), Stroke = Dim, StrokeThickness = 1.2, StrokeDashArray = new Avalonia.Collections.AvaloniaList<double> { 2, 2 }, VerticalAlignment = VerticalAlignment.Center },
- new TextBlock { Text = "source", FontSize = 8, Foreground = Dim, VerticalAlignment = VerticalAlignment.Center } } }, Dock.Right) } };
- var quantLevels = TinyMono("", Dim); // "64 levels"
- var quantHold = TinyMono("", Dim); // "hold 3\u2009smp"
- var quantFooter = new DockPanel { LastChildFill = false, Height = 10, Children = {
- WithDock(quantLevels, Dock.Left), WithDock(quantHold, Dock.Right) } };
- readouts.Add(() => {
- double bits = 1 + P(Bits) * 23; double lv = Math.Pow(2, bits);
- string lvS = lv >= 1e6 ? $"{lv / 1e6:0.0} M" : lv >= 1e3 ? $"{lv / 1e3:0.0} k" : $"{(long)Math.Round(lv)}";
- double hz = Exp(P(Rate), 500, 44100 * 0.48); int hold = Math.Max(1, (int)Math.Round(44100.0 / hz));
- quantSpec.Text = $"▮ {bits:0.0}-bit @ {(hz >= 1000 ? $"{hz / 1000:0.0}\u2009k" : $"{(int)hz}\u2009Hz")}";
- quantLevels.Text = $"{lvS} levels"; quantHold.Text = $"hold {hold}\u2009smp";
+ // The knob row under every graph: Bits, Rate, Drive, Wet and two info lines.
+ int centreTab = 0;
+ Control KnobRow(Func<string> info1, Func<string> info2)
+ {
+ var i1 = Mono("", 7, TextTertiary); i1.HorizontalAlignment = HorizontalAlignment.Right;
+ var i2 = Mono("", 7, TextTertiary); i2.HorizontalAlignment = HorizontalAlignment.Right;
+ i1.TextTrimming = i2.TextTrimming = TextTrimming.CharacterEllipsis;
+ readouts.Add(() => { i1.Text = info1(); i2.Text = info2(); });
+ var knobs = Row(2,
+ K(Bits, "BITS", BitsF, "Bits — the bit depth, 1 … 24: fewer bits, fewer levels, more grit", lit: () => centreTab == 0),
+ K(Rate, "RATE", RateF, "Rate — the reduced sample rate, 500\u2009Hz … full: lower holds each value longer and adds images above its Nyquist", lit: () => centreTab == 1),
+ K(Drive, "DRIVE", DriveF, "Drive — −12 … +24\u2009dB into the crusher: pushes the signal up the levels, into the Analog clip or into more folds", lit: () => centreTab == 2),
+ K(DryWet, "WET", v => Pct(v), "Wet — the crushed signal against the dry one", teal: true));
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 52, ColumnSpacing = 8 };
+ g.Children.Add(knobs);
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { i1, i2 } }, 1));
+ return g;
+ }
+ static Control TabBody(Control head, Control window, Control knobs) => new DockPanel
+ {
+ LastChildFill = true, Margin = new Thickness(8, 5, 8, 0),
+ Children = { Docked(head, Dock.Top), Docked(knobs, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 0), Child = window } },
+ };
+
+ // ======================================================================
+ // LEFT — CRUSH column (input · output)
+ // ======================================================================
+ var colTitle = Caps("CRUSH"); colTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var inPill = new ShPill { Ink = Teal, VerticalAlignment = VerticalAlignment.Stretch, Width = 14 };
+ var outPill = new ShPill { Ink = Brass, VerticalAlignment = VerticalAlignment.Stretch, Width = 14 };
+ ToolTip.SetTip(inPill, "The input peak, −60 … 0\u2009dBFS");
+ ToolTip.SetTip(outPill, "The output peak, −60 … 0\u2009dBFS");
+ var colIn = Mono("", 7, TextPrimary); colIn.HorizontalAlignment = HorizontalAlignment.Center;
+ var colOut = Mono("", 7, AccentBright); colOut.HorizontalAlignment = HorizontalAlignment.Center;
+ static double NormLvl(double db) => Math.Clamp((db + 60) / 60, 0, 1);
+ bool Crushing() => Sc(S_Signal) > 0.5 && P(DryWet) > 0.01f;
+ readouts.Add(() =>
+ {
+ inPill.Set(NormLvl(ScDb(S_InPeak)), double.NaN);
+ outPill.Set(NormLvl(ScDb(S_OutPeak)), double.NaN);
+ colIn.Text = Lvl(ScDb(S_InPeak));
+ colOut.Text = Lvl(ScDb(S_OutPeak));
+ colTitle.Foreground = Crushing() ? AccentBright : TextTertiary; // lit while it crushes
});
- var quantPanel = new Border { Padding = new Thickness(8, 4), Child = new Border { Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 4), Child = new DockPanel { LastChildFill = true, Children = { WithDock(quantHdr, Dock.Top), WithDock(quantFooter, Dock.Bottom), quantViz } } } };
-
- // ================= spectrum panel =================
- var specHdr = new DockPanel { LastChildFill = false, Height = 10, Children = {
- WithDock(new TextBlock { Text = "SPECTRUM", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center }, Dock.Left),
- WithDock(Tiny("▮ aliased images", TealC), Dock.Right),
- WithDock(new TextBlock { Text = "▮ signal ", FontSize = 8, Foreground = Amber, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0,0,6,0) }, Dock.Right) } };
- var specPanel = new Border { Height = 66, Padding = new Thickness(8, 0, 8, 4), Child = new Border { Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 4), Child = new DockPanel { LastChildFill = true, Children = { WithDock(specHdr, Dock.Top), specViz } } } };
-
- // ================= left column (quantiser fills, spectrum fixed at bottom) =================
- var leftCol = new DockPanel { LastChildFill = true, Children = { WithDock(specPanel, Dock.Bottom), quantPanel } };
-
- // ================= right rail (mode + grit + output) =================
- var modeSection = new StackPanel { Spacing = 2, Children = {
- new TextBlock { Text = "MODE", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC },
- ModeSelector() } };
-
- var gritSection = new StackPanel { Spacing = 3, Children = {
- new TextBlock { Text = "GRIT", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TealC },
- RailSlider(Dither, "DITHER", PctF, TealC),
- RailSlider(Jitter, "JITTER", PctF, TealC),
- RailSlider(NoiseFloor, "NOISE", PctF, TealC) } };
-
- var outSection = new StackPanel { Spacing = 3, Children = {
- new TextBlock { Text = "OUTPUT", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC },
- RailSlider(PostFilter, "FILTER", RateF),
- RailSlider(Output, "GAIN", GainF) } };
-
- var rightRail = new Border { Width = 212, Background = RailBg, Padding = new Thickness(8, 7), Child =
- new DockPanel { LastChildFill = false, Children = {
- WithDock(new StackPanel { Spacing = 4, Children = { modeSection, new Border { Height = 1, Background = RowLit }, new Border { BorderBrush = TealC, BorderThickness = new Thickness(2, 0, 0, 0), Padding = new Thickness(6, 0, 0, 0), Child = new StackPanel { Spacing = 3, Children = { gritSection, new Border { Height = 1, Background = RowLit }, outSection } } } } }, Dock.Top),
- WithDock(new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4, Margin = new Thickness(0, 6, 0, 0), Children = {
- RailBtn("Init", () => { for (int p = 0; p < Defaults.Length; p++) { Begin(p); SetP(p, Defaults[p]); End(p); } SyncQuant(); SyncSpec(); RefreshAll(); }),
- WithCol(RailBtn("Bypass", () => { engine.SetDeviceBypassed(track, di, !engine.DeviceBypassed(track, di)); ctx.RequestRebuild(); }), 1) } }, Dock.Bottom) } } };
-
- // ================= assemble =================
- DockPanel.SetDock(rightRail, Dock.Right);
- var body = new DockPanel { LastChildFill = true, Children = { rightRail, leftCol } };
- DockPanel.SetDock(live, Dock.Top);
- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };
-
- void RefreshAll() { foreach (var a in readouts) a(); }
- SyncQuant(); SyncSpec();
- ctx.AddDeviceRefresher(() => { SyncQuant(); SyncSpec(); RefreshAll(); });
- RefreshAll();
- return root;
- }
-
- private static Control WithDock(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
- private static Control WithCol(Control c, int col) { Grid.SetColumn(c, col); return c; }
-}
-
-// ---- custom-drawn quantiser waveform display ----
-internal sealed class CrushQuantiserViz : Control
-{
- private float _bits = 0.55f, _rate = 0.35f, _mode = 0f, _dither = 0.15f, _jitter = 0f, _noiseFloor = 0f, _drive = 0.333f;
- private double _phase;
- private readonly Random _rng = new();
-
- public void Set(float bits, float rate, float mode, float dither, float jitter, float noiseFloor, float drive)
- {
- _bits = bits; _rate = rate; _mode = mode; _dither = dither; _jitter = jitter; _noiseFloor = noiseFloor; _drive = drive;
- }
-
- public void Tick() { _phase += 0.02; if (_phase > 1.0) _phase -= 1.0; InvalidateVisual(); }
-
- private static double FoldViz(double x, double threshold)
- {
- double limit = threshold * 4.0;
- x = Math.Clamp(x, -limit, limit);
- int iter = 0;
- while (Math.Abs(x) > threshold && iter < 8) { if (x > threshold) x = 2 * threshold - x; else if (x < -threshold) x = -2 * threshold - x; iter++; }
- return x / threshold;
- }
-
- public override void Render(DrawingContext dc)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
-
- // Level grid
- float bits = 1f + _bits * 23f;
- int levels = (int)Math.Pow(2, bits);
- int shown = Math.Min(levels, 32);
- var gridPen = new Pen(CrushDeviceBody.GridLine, 1);
- var centerPen = new Pen(CrushDeviceBody.GridCenter, 1);
- for (int i = 0; i <= shown; i++)
+ Control PillCol(ShPill pill, string lbl)
{
- double y = h * (1.0 - i / (double)shown);
- dc.DrawLine(i == shown / 2 ? centerPen : gridPen, new Point(0, y), new Point(w, y));
+ var l = Caps(lbl); l.HorizontalAlignment = HorizontalAlignment.Center;
+ return new DockPanel { Children = { Docked(l, Dock.Bottom), new Border { Margin = new Thickness(0, 0, 0, 3), HorizontalAlignment = HorizontalAlignment.Center, Child = pill } } };
+ }
+ var pills = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 8, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 4) };
+ pills.Children.Add(PillCol(inPill, "IN"));
+ pills.Children.Add(Col(PillCol(outPill, "OUT"), 1));
+ var leftCol = 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(colTitle, Dock.Top), Docked(colOut, Dock.Bottom), Docked(colIn, Dock.Bottom), pills } },
+ };
+ DockPanel.SetDock(leftCol, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — Quantiser / Spectrum / Transfer
+ // ======================================================================
+ CrQuantView? quant = null;
+ Control QuantTab()
+ {
+ quant = new CrQuantView { Value = () => (P(Bits), P(Rate)) };
+ quant.GestureBegin += () => { Begin(Bits); Begin(Rate); };
+ quant.GestureEnd += () => { End(Bits); End(Rate); };
+ quant.Changed += (b, r) => { Raw(Bits, b); Raw(Rate, r); RefreshAll(); };
+ quant.ResetRequested += () => { Reset(Bits); Reset(Rate); RefreshAll(); };
+ Learn(quant, Bits);
+ ToolTip.SetTip(quant, "10\u2009ms of a sine through the crusher: the source dashed, the held and quantised steps in brass. Drag up / down for Bits, left / right for Rate; double-click resets both.");
+ var knobs = KnobRow(
+ () => NotaNum.F($"{KHz(Sr())} → {KHz(RateHz(P(Rate)))} · 1 of {Hold():0.#}"),
+ () => NotaNum.F($"quant. noise {-(6.02 * BitsOf(P(Bits)) + 1.76):0}\u2009dB"));
+ return TabBody(ModeHead(), quant, knobs);
}
- // Source waveform (thin grey line) + crushed output (brass steps)
- var srcPen = new Pen(CrushDeviceBody.SrcLine, 1);
- var crushPen = new Pen(NotaPalette.Accent, 1.5);
- var crushFill = NotaPalette.Wash(NotaPalette.Accent, 0x4D);
- double scale = levels - 1.0;
- double invScale = 1.0 / scale;
- int holdMax = Math.Max(1, (int)(44100.0 / (500.0 * Math.Pow(44100.0 * 0.48 / 500.0, _rate))));
- int cnt = 0;
- double held = 0;
- var srcPts = new List<Point>();
- var crushPts = new List<Point>();
+ CrSpectrumView? spectrum = null;
+ Control SpectrumTab()
+ {
+ spectrum = new CrSpectrumView { NyquistToNorm = hz => RateNorm(hz * 2), FilterToNorm = FiltNorm };
+ int[] map = { Rate, PostFilter };
+ spectrum.Value = h => P(map[h]);
+ spectrum.Changed += (h, v) => { Raw(map[h], v); RefreshAll(); };
+ spectrum.GestureBegin += h => Begin(map[h]);
+ spectrum.GestureEnd += h => End(map[h]);
+ spectrum.ResetRequested += h => { Reset(map[h]); RefreshAll(); };
+ Learn(spectrum, Rate);
+ ToolTip.SetTip(spectrum, "The output spectrum: brass is the signal, teal what the crush added — bright above the reduced Nyquist (the images). Drag the Nyquist line for Rate, the filter line for the post filter; double-click resets.");
+ var knobs = KnobRow(
+ () => Sc(S_Analysed) < 0.5 ? "no signal" : ScDb(S_Images) <= -119 ? NotaNum.F($"no images above {KHz(Sc(S_Nyquist))}")
+ : NotaNum.F($"images above {KHz(Sc(S_Nyquist))} {ScDb(S_Images):0}\u2009dB"),
+ () => Sc(S_Analysed) < 0.5 ? "THD+N —" : NotaNum.F($"THD+N {Sc(S_ThdN) * 100:0.0}\u2009%"));
+ return TabBody(ModeHead(), spectrum, knobs);
+ }
- double driveGain = Math.Pow(10, (-12 + _drive * 36) / 20.0);
- for (int x = 0; x < (int)w; x++)
+ CrTransferView? curve = null;
+ CrWaveView? wave = null;
+ Control TransferTab()
{
- double ph = (_phase + x / w) % 1.0;
- double src = Math.Sin(ph * Math.PI * 2) * 0.8;
- srcPts.Add(new Point(x, h * (0.5 - src * 0.45)));
+ curve = new CrTransferView { Width = 120 };
+ curve.Value = _ => P(Drive);
+ curve.Changed += (_, v) => { Raw(Drive, v); RefreshAll(); };
+ curve.GestureBegin += _ => Begin(Drive);
+ curve.GestureEnd += _ => End(Drive);
+ curve.ResetRequested += _ => { Reset(Drive); RefreshAll(); };
+ Learn(curve, Drive);
+ ToolTip.SetTip(curve, "Input → output through Drive, the mode and the levels; the dot is where the signal peaks. Drag up / down for Drive; double-click resets.");
+ wave = new CrWaveView();
+ ToolTip.SetTip(wave, "Two cycles of a sine at the driven level (dashed) and what comes out");
+ var pair = new DockPanel { LastChildFill = true, Children = { Docked(curve, Dock.Left), new Border { Margin = new Thickness(5, 0, 0, 0), Child = wave } } };
+ string DriveX() => NotaNum.F($"×{Math.Pow(10, DriveDb(P(Drive)) / 20):0.0}");
+ var knobs = KnobRow(
+ () => ModeI() switch
+ {
+ 2 => Sc(S_Signal) > 0.5 ? NotaNum.F($"drive {DriveX()} → {Sc(S_Folds):0} folds") : NotaNum.F($"drive {DriveX()} · no signal"),
+ 1 => NotaNum.F($"drive {DriveX()} → soft clip"),
+ _ => NotaNum.F($"drive {DriveX()} · straight"),
+ },
+ () => ModeI() == 2 ? LvF(Levels()) + " levels after the fold" : LvF(Levels()) + " levels");
+ return TabBody(ModeHead(), pair, knobs);
+ }
- if (--cnt <= 0) { cnt = holdMax; held = src * driveGain; }
- double q = held;
- if (_dither > 0) { double d = (_rng.NextDouble() - _rng.NextDouble()) * _dither * 0.5 * invScale; q += d; }
- // mode shaping (mirror the DSP): 0 Digital, 1 Analog soft-clip, 2 Fold
- int mode = (int)Math.Round(_mode * 2);
- if (mode == 1) q = Math.Tanh(q * 1.5) / 0.905;
- else if (mode == 2) q = FoldViz(q * 2.5, 0.7);
- q = Math.Clamp(Math.Round(q * scale) * invScale, -1.05, 1.05);
- crushPts.Add(new Point(x, h * (0.5 - q * 0.45)));
+ // ======================================================================
+ // RIGHT — Grit / Output
+ // ======================================================================
+ static Control Spread(params Control[] rows)
+ {
+ var defs = new List<string>();
+ for (int i = 0; i < rows.Length; i++) { if (i > 0) defs.Add("*"); defs.Add("Auto"); }
+ var g = new Grid { RowDefinitions = new RowDefinitions(string.Join(",", defs)) };
+ for (int i = 0; i < rows.Length; i++) g.Children.Add(GRow(rows[i], i * 2));
+ return new Border { Padding = new Thickness(8, 6), Child = g };
}
+ static Control Rule(Control c) => new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = c };
+ Control FilterRow() => SliderRow("FILTER", PostFilter, FiltF, "Post filter — a low-pass after the crush, 200\u2009Hz … 20 kHz: under the Nyquist it smooths the steps", modulation: true);
+ Control GainRow() => SliderRow("GAIN", Output, GainF, "Output gain, ±12\u2009dB", bipolar: true);
- // Draw source as polyline
- if (srcPts.Count > 1)
+ Control GritTab()
{
- var srcGeo = new StreamGeometry();
- using (var ctx = srcGeo.Open()) { ctx.BeginFigure(srcPts[0], false); for (int i = 1; i < srcPts.Count; i++) ctx.LineTo(srcPts[i]); ctx.EndFigure(false); }
- dc.DrawGeometry(null, srcPen, srcGeo);
+ var t = Caps("RESULT");
+ var l1 = Mono("", 9, TextPrimary);
+ var l2 = Mono("", 8, TextSecondary);
+ l1.TextTrimming = l2.TextTrimming = TextTrimming.CharacterEllipsis;
+ var box = new Border
+ {
+ Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 2, Children = { t, l1, l2 } },
+ };
+ readouts.Add(() =>
+ {
+ bool hot = Crushing();
+ double nyq = RateHz(P(Rate)) / 2, filt = FiltHz(P(PostFilter));
+ string tail = (ModeI() switch { 1 => " · soft", 2 => " · fold", _ => "" }) + (On(AntiAlias) ? " · AA" : "");
+ double rate = RateHz(P(Rate));
+ l1.Text = NotaNum.F($"{BitsOf(P(Bits)):0.0} bit · ") + (rate >= 1000 ? NotaNum.F($"{rate / 1000:0.0}\u2009kHz") : NotaNum.F($"{rate:0}\u2009Hz")) + tail;
+ l2.Text = filt < nyq ? "the filter cuts the images"
+ : NotaNum.F($"Nyquist {Hz(nyq)} · filter above");
+ t.Foreground = hot ? AccentBright : TextTertiary;
+ l1.Foreground = hot ? AccentBright : TextPrimary;
+ box.BorderBrush = hot ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
+ });
+ ToolTip.SetTip(box, "What comes out: the bit depth and the rate, and whether the post filter cuts the images above the reduced Nyquist or lets them through");
+ return Spread(
+ SliderRow("DITHER", Dither, v => Pct(v), "Dither — up to ±½ LSB of triangular noise before the levels: softens the steps into hiss"),
+ SliderRow("JITTER", Jitter, v => Pct(v), "Jitter — the hold length wanders up to ±50 %: an unsteady, broken clock"),
+ SliderRow("NOISE", NoiseFloor, v => Pct(v), "Noise — a white noise floor under the crush, up to −50\u2009dBFS"),
+ Rule(FilterRow()), GainRow(), box);
}
- // Draw crushed as filled steps
- if (crushPts.Count > 1)
+ Control OutputTab()
{
- var crushGeo = new StreamGeometry();
- using (var ctx = crushGeo.Open())
+ Control MRow(string key, Func<string> val, Func<IBrush> ink)
{
- ctx.BeginFigure(new Point(crushPts[0].X, h * 0.5), true);
- for (int i = 0; i < crushPts.Count; i++) ctx.LineTo(crushPts[i]);
- ctx.LineTo(new Point(crushPts[^1].X, h * 0.5));
- ctx.EndFigure(true);
+ var k = new TextBlock { Text = key, FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
+ var v = Mono("", 8, TextPrimary); v.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => { v.Text = val(); v.Foreground = ink(); });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ g.Children.Add(k); g.Children.Add(Col(v, 1));
+ return g;
}
- dc.DrawGeometry(crushFill, crushPen, crushGeo);
+ var meters = new Border
+ {
+ Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel
+ {
+ Spacing = 2, Children =
+ {
+ Caps("MEASUREMENTS"),
+ MRow("in", () => Lvl(ScDb(S_InPeak)) + " dB", () => TextPrimary),
+ MRow("out", () => Lvl(ScDb(S_OutPeak)) + " dB", () => ScDb(S_OutPeak) > 0 ? NotaPalette.DangerBright : AccentBright),
+ MRow("crest", () => ScDb(S_OutRms) <= -119 ? "—" : NotaNum.F($"{Sc(S_Crest):0.0} dB"), () => TextPrimary),
+ },
+ },
+ };
+ ToolTip.SetTip(meters, "Peaks in and out, and the output's crest factor (peak over RMS) — the crush flattens it");
+ var toggles = new StackPanel
+ {
+ Spacing = 5, Children =
+ {
+ Toggle(AutoGain, "Auto gain", "Auto gain — rides the output back to the input's loudness (300\u2009ms RMS, ±24\u2009dB), so turning Bits or Drive doesn't jump in level",
+ () => On(AutoGain) ? "Auto gain " + Sgn(Sc(S_AutoGain)) + "\u2009dB" : "Auto gain"),
+ Toggle(DcFilter, "DC filter", "DC filter — a 10\u2009Hz high-pass on the crushed signal: takes out the offset a coarse, folded or noisy crush can leave"),
+ },
+ };
+ return Spread(meters, FilterRow(), GainRow(), Rule(toggles));
}
- }
-}
-
-// ---- custom-drawn spectrum display ----
-internal sealed class CrushSpectrumViz : Control
-{
- private float _bits = 0.55f, _rate = 0.35f, _antiAlias = 0f;
- private double _phase;
- private readonly Random _rng = new();
-
- public void Set(float bits, float rate, float antiAlias) { _bits = bits; _rate = rate; _antiAlias = antiAlias; }
-
- public void Tick() { _phase += 0.03; if (_phase > 1.0) _phase -= 1.0; InvalidateVisual(); }
-
- public override void Render(DrawingContext dc)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- double targetHz = 500.0 * Math.Pow(44100.0 * 0.48 / 500.0, _rate);
- double nyqNorm = targetHz / (44100.0 * 0.48);
- double nyqX = w * nyqNorm;
+ // ======================================================================
+ // 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(() =>
+ {
+ extras.Text = centreTab switch
+ {
+ 1 => "20\u2009Hz … 20\u2009kHz",
+ 2 => "in → out",
+ _ => NotaNum.F($"{LvF(Levels())} levels · hold {Hold():0.#} smp"),
+ };
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => SpectrumTab(), 2 => TransferTab(), _ => QuantTab() };
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? OutputTab() : GritTab();
+
+ var centre = TabFrame(new[] { "Quantiser", "Spectrum", "Transfer" }, centreHost, CentreBody, false, t => { centreTab = t; Refresh(); }, extras);
+ var rightFrame = TabFrame(new[] { "Grit", "Output" }, rightHost, RightBody, true, _ => RefreshAll(), 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()
+ {
+ var parts = new List<string>
+ {
+ CrushMath.Modes[ModeI()],
+ "bits " + BitsF(P(Bits)),
+ "rate " + KHz(RateHz(P(Rate))),
+ "drive " + DriveF(P(Drive)),
+ "wet " + Pct(P(DryWet)),
+ };
+ if (P(Dither) > 0.005f) parts.Add("dither " + Pct(P(Dither)));
+ if (P(Jitter) > 0.005f) parts.Add("jitter " + Pct(P(Jitter)));
+ if (P(NoiseFloor) > 0.005f) parts.Add("noise " + Pct(P(NoiseFloor)));
+ if (Math.Abs(GainDb(P(Output))) > 0.05) parts.Add("gain " + GainF(P(Output)));
+ if (On(AntiAlias)) parts.Add("AA on");
+ if (On(AutoGain)) parts.Add("auto gain");
+ if (On(DcFilter)) parts.Add("DC");
+ return string.Join(" · ", parts);
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#}\u2009kHz · latency {Sc(S_Latency):0} smp · CPU {Sc(S_Cpu) * 100:0.0}\u2009%") : "";
+ });
+ 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);
- // Nyquist line
- var nyqPen = new Pen(CrushDeviceBody.NyqLine, 1);
- dc.DrawLine(nyqPen, new Point(nyqX, 0), new Point(nyqX, h));
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { leftCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
- // Spectrum bars: signal (brass) + aliased images (teal)
- var sigBrush = NotaPalette.Accent;
- var aliBrush = NotaPalette.Teal;
- int bars = 26;
- double barW = w / bars;
- for (int i = 0; i < bars; i++)
+ void Refresh()
{
- double freqNorm = i / (double)(bars - 1);
- double barH;
- bool isAlias = freqNorm > nyqNorm * 0.95;
+ // Only the Spectrum tab pays for the FFT; the others read the telemetry.
+ scN = engine.DeviceScope(track, di, scope, centreTab == 1 ? kScope : kTele);
+ double drive = Math.Pow(10, DriveDb(P(Drive)) / 20);
+ if (centreTab == 0 && quant is not null)
+ quant.Set(BitsOf(P(Bits)), Hold(), Sr(), ModeI(), drive);
+ if (centreTab == 1 && spectrum is not null)
+ spectrum.Set(scope, kTele, kTele + kBands, scN >= kScope ? kBands : 0, RateHz(P(Rate)) / 2, FiltHz(P(PostFilter)), Sc(S_Analysed) > 0.5);
+ if (centreTab == 2 && curve is not null && wave is not null)
+ {
+ curve.Set(ModeI(), drive, Levels(), Sc(S_Signal) > 0.5 ? Sc(S_DrivenPeak) : 0);
+ wave.Set(ModeI(), drive, DriveDb(P(Drive)), Levels(), Hold(), Sr());
+ }
+ RefreshAll();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
- if (isAlias)
+ // 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()
{
- // Aliased images: mirror around nyquist
- double mirror = nyqNorm - (freqNorm - nyqNorm);
- mirror = Math.Max(0, mirror);
- barH = h * 0.15 * (1.0 - mirror) * (1.0 - _antiAlias * 0.8) * (0.5 + 0.5 * Math.Sin(_phase * 3 + i * 0.5));
+ 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;
+ }
}
- else
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
{
- barH = h * 0.6 * (1.0 - freqNorm) * (0.6 + 0.4 * Math.Sin(_phase * 2 + i * 0.3));
+ 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 += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };
+ btns[i] = b;
+ bar.Children.Add(b);
}
-
- barH = Math.Max(1, barH);
- var brush = isAlias ? aliBrush : sigBrush;
- double opacity = isAlias ? 0.7 * (1.0 - _antiAlias) : 0.85;
- dc.DrawRectangle(new SolidColorBrush(Color.FromArgb((byte)(opacity * 255), ((SolidColorBrush)brush).Color.R, ((SolidColorBrush)brush).Color.G, ((SolidColorBrush)brush).Color.B)), null, new Rect(i * barW + 1, h - barH, Math.Max(1, barW - 2), barH));
+ 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/DynamicEqDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs
index 7fba9ea2..f5aac997 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs
@@ -1,19 +1,22 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Dynamic EQ-8 (device kind 13) body. A two-curve
-// response graph (static brass + momentary teal) fills the left; a LIVE strip drives
-// the selected band — frequency & Q stay brass, threshold/range/attack/release are
-// teal because they modulate the band's gain — with Sidechain and Solo beside them.
-// A band table on the right lists all eight (DYN direction/range + a live GR bar) and
-// a 2-second GR history sparkline sits under it. Every control is a generic device
-// param → automation + persist for free.
+// Detail · Devices — built-in Nota Dynamic EQ-8 body (device kind 13), a build of the "Nota
+// Dynamic EQ" mockup (700 × 260): the response graph takes almost the whole width — nodes drag
+// right on the curve, a row of eight band chips above it shows each band's dynamic activity, a
+// panel on the right edits the selected band (type, FREQ / GAIN / Q, the dynamics mode with
+// THRESH — the band's level marked on it — RANGE, ATTACK, RELEASE, its key and Solo), and a
+// status strip carries the summary, the selected band's gain now, the Dynamic master switch
+// and the output. The live readings come from the engine (DynamicEq.h scopeRead). Every
+// control is a device param (raw units), so automation / MIDI learn / presets / A-B /
+// persistence come for free; the key track is the device's sidechain routing.
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
using System.Collections.Generic;
-using System.Globalization;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -24,272 +27,485 @@ namespace Nota.App;
internal sealed class DynamicEqDeviceBody : IDeviceBody
{
- private const int Bands = 8, PerBand = 10;
- private const int On = 0, TypeF = 1, FreqF = 2, GainF = 3, QF = 4, ModeF = 5, ThrF = 6, RangeF = 7, AtkF = 8, RelF = 9;
- private const int OutputP = 80, SidechainP = 81, SoloP = 82;
- private const int LowShelf = 1, Bell = 2, HighShelf = 4;
- private static readonly string[] TypeAbbr = { "HP", "LS", "Bell", "Notch", "HS", "LP" };
-
public double Width => 700;
-
- public string? Subtitle => "DYNAMIC EQ"; // the processing type, shown as the header badge
- public bool FullBleed => true; // manage our own padding so the tall band table fits the card
+ public bool FullBleed => true;
+ public string? Subtitle => "DYNAMIC EQ";
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);
-
- var curve = new DynamicEqCurve(engine, track, di) { HorizontalAlignment = HorizontalAlignment.Stretch };
- ctx.AddDeviceRefresher(curve.Tick);
-
- // ---------------- LIVE strip (selected band) ----------------
- int Cur() => curve.SelectedBand;
- bool HasGain(int b) => (int)Math.Round(P(b * PerBand + TypeF)) is LowShelf or Bell or HighShelf;
- bool IsDyn(int b) => P(b * PerBand + On) > 0.5f && HasGain(b) && (int)Math.Round(P(b * PerBand + ModeF)) != 0;
-
- // A gauge knob bound to <field> of whatever band is currently selected.
- Control DevKnob(string name, int field, Func<double, string> fmt, bool log, IBrush? arc)
+ int pc = Math.Min(engine.DeviceParamCount(track, di), DynEq.ParamCount);
+ var mn = new float[DynEq.ParamCount];
+ var mx = new float[DynEq.ParamCount];
+ for (int p = 0; p < DynEq.ParamCount; p++)
{
- double Min() => engine.DeviceParamMin(track, di, Cur() * PerBand + field);
- double Max() => engine.DeviceParamMax(track, di, Cur() * PerBand + field);
- double ToNorm(double raw) { double lo = Min(), hi = Max(); return log ? Math.Log(Math.Max(raw, lo) / lo) / Math.Log(hi / lo) : (raw - lo) / (hi - lo); }
- double ToRaw(double n) { double lo = Min(), hi = Max(); return log ? lo * Math.Pow(hi / lo, n) : lo + n * (hi - lo); }
+ mn[p] = p < pc ? engine.DeviceParamMin(track, di, p) : 0;
+ mx[p] = p < pc ? engine.DeviceParamMax(track, di, p) : 1;
+ if (mx[p] <= mn[p]) mx[p] = mn[p] + 1;
+ }
+ float P(int p) => p < pc ? engine.DeviceGetParam(track, di, p) : 0f;
+ float B(int b, int f) => P(DynEq.P(b, f));
+ 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) { if (p < pc) engine.DeviceSetParam(track, di, p, 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, float v) { Begin(p); Raw(p, v); End(p); }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
- int pi = Cur() * PerBand + field;
- var value = new TextBlock { Text = fmt(P(pi)), FontSize = 9, Foreground = TextPrimary };
- value.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var knob = new Knob(ToNorm(P(pi)), 1.0) { Accent = true, ArcColor = arc, Width = 30, Height = 30 };
- knob.ValueChanged += v => { int p = Cur() * PerBand + field; float raw = (float)ToRaw(v); SetP(p, raw); value.Text = fmt(raw); };
- knob.GestureBegin += () => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, Cur() * PerBand + field, "");
- knob.GestureEnd += () => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, Cur() * PerBand + field, "");
- MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, Cur() * PerBand + field), name);
- ctx.AddDeviceRefresher(() =>
- {
- if (knob.Dragging) return;
- int p = Cur() * PerBand + field; float raw = P(p);
- double nv = ToNorm(raw);
- if (Math.Abs(nv - knob.Value) > 1e-3) knob.Value = nv;
- value.Text = fmt(raw);
- });
- var cell = KnobCell(name, knob, value, 44);
- return cell;
+ var readouts = new List<Action>();
+ var bandReadouts = new List<Action>();
+ void RefreshAll()
+ {
+ for (int i = 0; i < readouts.Count; i++) readouts[i]();
+ for (int i = 0; i < bandReadouts.Count; i++) bandReadouts[i]();
}
+ var scope = new float[DynEq.kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
- static string HzF(double v) => v >= 1000 ? $"{v / 1000:0.0}k" : $"{v:0}\u2009Hz";
- static string QF2(double v) => v.ToString("0.00", NotaNum.Culture);
- static string DbF(double v) => $"{v:+0.0;−0.0;0}\u2009dB";
- static string MsF(double v) => v >= 100 ? $"{v:0}\u2009ms" : $"{v:0.0}\u2009ms";
+ var curve = new DynamicEqCurve(engine, track, di);
+ int Sel() => curve.SelectedBand;
+ bool BandOn(int b) => B(b, DynEq.On) > 0.5f;
+ int TypeOf(int b) => Math.Clamp((int)Math.Round(B(b, DynEq.TypeF)), 0, 5);
+ int ModeOf(int b) => Math.Clamp((int)Math.Round(B(b, DynEq.ModeF)), 0, 2);
+ bool DynMaster() => P(DynEq.DynamicsP) >= 0.5f;
+ int Solo() => Math.Clamp((int)Math.Round(P(DynEq.SoloP)), 0, DynEq.Bands) - 1;
+ bool Capable(int b) => DynEq.HasGain(TypeOf(b));
+ bool IsDyn(int b) => DynMaster() && BandOn(b) && Capable(b) && ModeOf(b) != DynEq.Static;
+ bool KeyExt(int b) => P(DynEq.SidechainP) >= 0.5f || P(DynEq.KeyBase + b) >= 0.5f;
+ IBrush DirInk(int b, bool bright = false) => B(b, DynEq.RangeF) >= 0 ? (bright ? NotaPalette.RoseBright : NotaPalette.Rose) : (bright ? NotaPalette.TealBright : Teal);
- var kFreq = DevKnob("FREQ", FreqF, HzF, true, Brass);
- var kQ = DevKnob("Q", QF, QF2, false, Brass);
- var kThr = DevKnob("THRESH", ThrF, v => $"{v:0.0}\u2009dB", false, Teal);
- var kRange = DevKnob("RANGE", RangeF, DbF, false, Teal);
- var kAtk = DevKnob("ATTACK", AtkF, MsF, true, Teal);
- var kRel = DevKnob("RELEASE", RelF, MsF, true, Teal);
+ // ---- 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; }
- // Mode chips: Static / ↓ Above / ↑ Below
- var modeChips = new Border[3];
- string[] modeLbl = { "STAT", "DUCK", "LIFT" };
- void SyncMode()
+ // Key source: the device's sidechain routing (a track), picked from a menu.
+ string SrcName(int id)
{
- int cur = (int)Math.Round(P(Cur() * PerBand + ModeF));
- bool canDyn = HasGain(Cur());
- for (int i = 0; i < 3; i++)
- {
- bool onc = i == cur;
- modeChips[i].Background = onc ? (i == 0 ? Brass : Teal) : Card2;
- ((TextBlock)modeChips[i].Child!).Foreground = onc ? OnAccent : TextSecondary;
- Inactive.Set(modeChips[i], !(canDyn || i == 0));
- }
- bool dyn = IsDyn(Cur());
- foreach (var k in new[] { kThr, kRange, kAtk, kRel }) Inactive.Set(k, !dyn, interactive: true);
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)
+ { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }
+ return "—";
}
- var modeRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };
- for (int i = 0; i < 3; i++)
+ int Src() => engine.DeviceSidechainSource(track, di);
+ void ShowKeyMenu(Control at)
{
- int vi = i;
+ var fly = new MenuFlyout();
+ var none = new MenuItem { Header = "No key track", ToggleType = MenuItemToggleType.Radio, IsChecked = Src() < 0 };
+ none.Click += (_, _) => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); RefreshAll(); };
+ fly.Items.Add(none);
+ fly.Items.Add(new Separator());
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track)
+ {
+ int id = ti.Id;
+ var mi = new MenuItem { Header = SrcName(id), ToggleType = MenuItemToggleType.Radio, IsChecked = Src() == id };
+ mi.Click += (_, _) => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); RefreshAll(); };
+ fly.Items.Add(mi);
+ }
+ fly.ShowAt(at);
+ }
+
+ // ======================================================================
+ // LEFT — band chips over the response graph
+ // ======================================================================
+ var chipRow = new UniformGrid { Rows = 1, Margin = new Thickness(3, 0), VerticalAlignment = VerticalAlignment.Center };
+ for (int b = 0; b < DynEq.Bands; b++)
+ {
+ int bb = b;
+ var num = new TextBlock { FontSize = 8, FontWeight = FontWeight.Bold, Text = (b + 1).ToString(), VerticalAlignment = VerticalAlignment.Center };
+ num.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ var type = new TextBlock { FontSize = 7, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(3, 0, 0, 0) };
+ var hz = Mono("", 7, TextPrimary); hz.HorizontalAlignment = HorizontalAlignment.Right;
+ var bar = new Border { Height = 2, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom };
+ var inner = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), Margin = new Thickness(4, 0) };
+ inner.Children.Add(num); inner.Children.Add(Col(type, 1)); inner.Children.Add(Col(hz, 2));
var chip = new Border
{
- Background = Card2, BorderBrush = BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control,
- Padding = new Thickness(7, 3), Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = modeLbl[i], FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextSecondary },
+ Height = 15, Margin = new Thickness(1, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), ClipToBounds = true,
+ Cursor = new Cursor(StandardCursorType.Hand), Child = new Grid { Children = { inner, bar } },
};
- chip.PointerPressed += (_, e) => { e.Handled = true; if (HasGain(Cur()) || vi == 0) {
- int bp = Cur() * PerBand;
- // Engaging a dynamic mode with a zero Range would move nothing (no GR ever) —
- // seed a musical default so the band actually reacts: DUCK −6 dB, LIFT +6 dB.
- if (vi != 0 && Math.Abs(P(bp + RangeF)) < 0.01f) SetP(bp + RangeF, vi == 1 ? -6f : 6f);
- SetP(bp + ModeF, vi); SyncMode(); curve.InvalidateVisual(); } };
- modeChips[i] = chip; modeRow.Children.Add(chip);
+ ToolTip.SetTip(chip, NotaNum.F($"Band {b + 1} — click to edit it; the bar shows how much of its range the dynamics use now"));
+ chip.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(chip).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) SetP(DynEq.P(bb, DynEq.On), BandOn(bb) ? 0 : 1);
+ curve.SelectedBand = bb; RefreshAll(); e.Handled = true;
+ };
+ readouts.Add(() =>
+ {
+ bool on = BandOn(bb), sel = bb == Sel(), dimmed = Solo() >= 0 && !sel;
+ num.Foreground = !on || dimmed ? TextDisabled : sel ? AccentBright : Brass;
+ type.Text = DynEq.TypeShort[TypeOf(bb)];
+ type.Foreground = on && !dimmed ? TextSecondary : TextDisabled;
+ hz.Text = DynEq.HzShort(B(bb, DynEq.FreqF));
+ hz.Foreground = on && !dimmed ? TextPrimary : TextDisabled;
+ chip.BorderBrush = sel ? Brass : Brushes.Transparent;
+ chip.Background = sel ? Raised : Sunken;
+ double r = Math.Abs(B(bb, DynEq.RangeF));
+ double frac = IsDyn(bb) && r > 0.05 ? Math.Clamp(Math.Abs(curve.Gr(bb)) / r, 0, 1) : 0;
+ bar.Width = frac * Math.Max(0, chip.Bounds.Width - 2);
+ bar.Background = DirInk(bb);
+ });
+ chipRow.Children.Add(chip);
}
- MidiLearn.Bind(modeRow, MidiTarget.DeviceParam(track, di, Cur() * PerBand + ModeF), engine.DeviceParamName(track, di, Cur() * PerBand + ModeF));
-
- // Sidechain + Solo toggles
- Border Toggle(string text, Func<bool> get, Action<bool> set)
+ var chipStrip = new Border { Height = 20, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = chipRow };
+ DockPanel.SetDock(chipStrip, Dock.Top);
+ ToolTip.SetTip(curve, "Drag a node — frequency and gain · wheel over a node — Q · double-click a node — band on / off · "
+ + "double-click empty space — a new bell there · right-click a node — type, mode, solo");
+ var graphPanel = new Border
{
- var b = new Border { BorderBrush = BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(8, 4), Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = text, FontSize = 9, FontWeight = FontWeight.SemiBold } };
- void Sync() { bool on = get(); b.Background = on ? Teal : Card2; ((TextBlock)b.Child!).Foreground = on ? OnAccent : TextSecondary; }
- b.PointerPressed += (_, e) => { e.Handled = true; set(!get()); Sync(); };
- ctx.AddDeviceRefresher(Sync); Sync();
- return b;
- }
- var scToggle = Toggle("SC", () => P(SidechainP) > 0.5f, on => SetP(SidechainP, on ? 1 : 0));
- MidiLearn.Bind(scToggle, MidiTarget.DeviceParam(track, di, SidechainP), engine.DeviceParamName(track, di, SidechainP));
- var soloToggle = Toggle("SOLO", () => (int)Math.Round(P(SoloP)) == Cur() + 1, on => SetP(SoloP, on ? Cur() + 1 : 0));
+ Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ ClipToBounds = true, Margin = new Thickness(0, 0, 5, 0),
+ Child = new DockPanel { LastChildFill = true, Children = { chipStrip, new Border { Padding = new Thickness(5), Child = curve } } },
+ };
+
+ // ======================================================================
+ // RIGHT — the selected band (rebuilt when the selection moves, so MIDI learn and
+ // automation bind to that band's own params)
+ // ======================================================================
+ var bandHost = new ContentControl();
- // Compact sidechain source picker (None + every other track).
- var scIds = new List<int> { -1 };
- var scCombo = new ComboBox { FontSize = 9, MinWidth = 92, MaxWidth = 92, VerticalAlignment = VerticalAlignment.Center };
- scCombo.Items.Add("Key: none");
- for (int i = 0; i < engine.TrackCount; i++)
+ Control BandPanel(int b)
{
- if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;
- scIds.Add(ti.Id); scCombo.Items.Add($"Key: {i + 1}");
- }
- scCombo.SelectedIndex = Math.Max(0, scIds.IndexOf(engine.DeviceSidechainSource(track, di)));
- scCombo.SelectionChanged += (_, _) => { int s = scCombo.SelectedIndex; if (s >= 0 && s < scIds.Count) { engine.SetDeviceSidechainSource(track, di, scIds[s]); ctx.NotifyChanged(); } };
+ bandReadouts.Clear();
+ int pOn = DynEq.P(b, DynEq.On), pType = DynEq.P(b, DynEq.TypeF), pF = DynEq.P(b, DynEq.FreqF), pG = DynEq.P(b, DynEq.GainF),
+ pQ = DynEq.P(b, DynEq.QF), pMode = DynEq.P(b, DynEq.ModeF), pThr = DynEq.P(b, DynEq.ThrF), pRange = DynEq.P(b, DynEq.RangeF),
+ pAtk = DynEq.P(b, DynEq.AtkF), pRel = DynEq.P(b, DynEq.RelF), pKey = DynEq.KeyBase + b;
- var bandTitle = new TextBlock { FontSize = 9, FontWeight = FontWeight.Bold, Foreground = AccentBright, VerticalAlignment = VerticalAlignment.Center, MinWidth = 96 };
- void SyncTitle() { int b = Cur(); int ty = (int)Math.Round(P(b * PerBand + TypeF)); bandTitle.Text = $"BAND {b + 1} · {TypeAbbr[Math.Clamp(ty, 0, 5)]}"; }
- ctx.AddDeviceRefresher(SyncTitle); ctx.AddDeviceRefresher(SyncMode);
- curve.SelectionChanged += () => { SyncTitle(); SyncMode(); };
+ // 0..1 mappings (frequency, Q, attack and release are log)
+ bool IsLog(int p) => p == pF || p == pQ || p == pAtk || p == pRel;
+ double ToN(int p, double v) => IsLog(p)
+ ? Math.Log(Math.Clamp(v, mn[p], mx[p]) / mn[p]) / Math.Log(mx[p] / mn[p])
+ : (Math.Clamp(v, mn[p], mx[p]) - mn[p]) / (mx[p] - mn[p]);
+ double FromN(int p, double n) { n = Math.Clamp(n, 0, 1); return IsLog(p) ? mn[p] * Math.Pow(mx[p] / mn[p], n) : mn[p] + n * (mx[p] - mn[p]); }
+ double DefOf(int p) => engine.DeviceParamDefault(track, di, p);
- Border VSep() => new() { Width = 1, Background = BorderDef, Margin = new Thickness(3, 4) };
- var liveStrip = new Border
- {
- Height = 60, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel,
- Padding = new Thickness(9, 3), Margin = new Thickness(0, 0, 0, 4),
- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children =
+ // ---- header: badge · name · ON ----
+ var badgeTxt = Mono((b + 1).ToString(), 8, OnAccent); badgeTxt.FontWeight = FontWeight.Bold; badgeTxt.HorizontalAlignment = HorizontalAlignment.Center;
+ var badge = new Border { Width = 13, Height = 13, CornerRadius = NotaRadius.Pill, VerticalAlignment = VerticalAlignment.Center, Child = badgeTxt };
+ var name = new TextBlock { FontSize = 9, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0) };
+ var onSw = Switch("On", () => BandOn(b), () => { SetP(pOn, BandOn(b) ? 0 : 1); RefreshAll(); }, out var onSync);
+ Learn(onSw, pOn);
+ ToolTip.SetTip(onSw, "Band on — off leaves the band out of the signal (double-click its node does the same)");
+ bandReadouts.Add(onSync);
+ bandReadouts.Add(() =>
{
- new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Width = 138, Children = { bandTitle, modeRow } },
- VSep(),
- kFreq, kQ,
- VSep(),
- kThr, kRange, kAtk, kRel,
- VSep(),
- new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { scToggle, soloToggle } }, scCombo } },
- } },
- };
+ bool on = BandOn(b);
+ badge.Background = on ? AccentBright : NotaPalette.TextAxis;
+ badgeTxt.Foreground = on ? OnAccent : TextTertiary;
+ name.Text = DynEq.TypeNames[TypeOf(b)].ToUpperInvariant();
+ name.Foreground = on ? AccentBright : TextTertiary;
+ });
+ var head = new DockPanel { Height = 20, Margin = new Thickness(8, 0), Children = { Docked(onSw, Dock.Right), badge, name } };
+ var headBorder = new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = head };
- // ---------------- band table ----------------
- var table = new Grid { RowDefinitions = new RowDefinitions("Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto"), ColumnDefinitions = new ColumnDefinitions("16,30,44,44,*") };
- var rowBorders = new Border[Bands];
- for (int b = 0; b < Bands; b++)
- {
- int bb = b;
- var num = new TextBlock { Text = (b + 1).ToString(), FontSize = 9, FontWeight = FontWeight.Bold, HorizontalAlignment = HorizontalAlignment.Center };
- var type = new TextBlock { FontSize = 9 };
- var hz = new TextBlock { FontSize = 9 }; hz.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var dyn = new TextBlock { FontSize = 9 }; dyn.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var grBar = new Border { Height = 6, CornerRadius = NotaRadius.Badge, Background = NotaPalette.BorderDefault, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };
- var grFill = new Border { Height = 6, CornerRadius = NotaRadius.Badge, Background = Teal, HorizontalAlignment = HorizontalAlignment.Left };
- var grWrap = new Grid { Margin = new Thickness(0, 0, 4, 0) }; grWrap.Children.Add(grBar); grWrap.Children.Add(grFill);
+ // ---- type ----
+ var typeSeg = Segments(DynEq.TypeSeg, () => TypeOf(b), i =>
+ {
+ SetP(pType, i);
+ if (!DynEq.HasGain(i) && ModeOf(b) != DynEq.Static) SetP(pMode, DynEq.Static);
+ RefreshAll();
+ }, out var typeSync, fill: true, padX: 0);
+ Learn(typeSeg, pType);
+ ToolTip.SetTip(typeSeg, "Type — high-pass, low shelf, bell, notch, high shelf, low-pass; only shelves and bells take gain and dynamics");
+ bandReadouts.Add(typeSync);
- void SyncRow()
+ // ---- knobs ----
+ Control K(int p, string label, Func<string> fmt, string tip, Func<string>? liveLabel = null, Func<bool>? inactive = null)
{
- bool on = P(bb * PerBand + On) > 0.5f;
- int ty = Math.Clamp((int)Math.Round(P(bb * PerBand + TypeF)), 0, 5);
- bool dynB = IsDyn(bb);
- var tc = on ? (bb == Cur() ? AccentBright : TextSecondary) : TextDisabled;
- num.Foreground = on ? (dynB ? Teal : Brass) : TextDisabled;
- type.Text = TypeAbbr[ty]; type.Foreground = tc;
- hz.Text = HzF(P(bb * PerBand + FreqF)); hz.Foreground = tc;
- if (dynB) { int m = (int)Math.Round(P(bb * PerBand + ModeF)); dyn.Text = $"{(m == 1 ? "↓" : "↑")}{P(bb * PerBand + RangeF):+0;−0;0}"; dyn.Foreground = Teal; }
- else if (HasGain(bb)) { dyn.Text = "—"; dyn.Foreground = TextTertiary; }
- else { dyn.Text = ""; }
- double gr = Math.Min(1, Math.Abs(curve.Gr(bb)) / 12);
- grFill.Width = Math.Max(0, gr * 60);
- grBar.Width = 60;
- rowBorders[bb].Background = bb == Cur() ? NotaPalette.Wash(NotaPalette.Accent, 0x20) : Brushes.Transparent;
+ var val = Mono(fmt(), 7, TextPrimary);
+ var knob = new Knob(ToN(p, P(p)), 1.0) { Accent = true, Default = ToN(p, DefOf(p)), Width = 34, Height = 34 };
+ knob.ValueChanged += v => { Raw(p, (float)FromN(p, v)); val.Text = fmt(); curve.InvalidateVisual(); RefreshAll(); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ ToolTip.SetTip(knob, tip);
+ var cell = KnobCell(label, knob, val, 54);
+ TextBlock? lbl = null;
+ if (cell is Panel pl) foreach (var c in pl.Children) if (c is TextBlock tb && tb != val) { lbl = tb; break; }
+ bool? wasInactive = null;
+ bandReadouts.Add(() =>
+ {
+ if (!knob.Dragging) { double c = ToN(p, P(p)); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; }
+ val.Text = fmt();
+ if (lbl is not null && liveLabel is not null) lbl.Text = liveLabel();
+ bool ina = inactive?.Invoke() ?? false;
+ if (wasInactive != ina) { Inactive.Set(cell, ina); wasInactive = ina; }
+ });
+ return cell;
}
- ctx.AddDeviceRefresher(SyncRow);
-
- Grid.SetColumn(num, 0); Grid.SetColumn(type, 1); Grid.SetColumn(hz, 2); Grid.SetColumn(dyn, 3); Grid.SetColumn(grWrap, 4);
- var rowGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("16,30,44,44,*"), Height = 11 };
- rowGrid.Children.Add(num); rowGrid.Children.Add(type); rowGrid.Children.Add(hz); rowGrid.Children.Add(dyn); rowGrid.Children.Add(grWrap);
- var rb = new Border { Child = rowGrid, CornerRadius = NotaRadius.Badge, Cursor = new Cursor(StandardCursorType.Hand), Padding = new Thickness(2, 0) };
- rb.PointerPressed += (_, e) => { e.Handled = true; curve.Select(bb); };
- rowBorders[b] = rb;
- Grid.SetRow(rb, b); table.Children.Add(rb);
- }
-
- // ---------------- GR history sparkline ----------------
- var hist = new GrHistoryView(curve) { Height = 22 };
- ctx.AddDeviceRefresher(hist.Tick);
-
- var rightCol = new StackPanel { Spacing = 3, Width = 236, Children =
- {
- new TextBlock { Text = "BANDS", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextTertiary },
- table,
- new TextBlock { Text = "GR HISTORY · 2\u2009s", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextTertiary, Margin = new Thickness(0, 1, 0, 0) },
- hist,
- } };
+ var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), Children =
+ {
+ K(pF, "FREQ", () => DynEq.HzShort(B(b, DynEq.FreqF)) + (B(b, DynEq.FreqF) < 1000 ? " Hz" : ""), "Frequency — or drag the node left / right"),
+ Col(K(pG, "GAIN", () => Capable(b) ? DynEq.Db(B(b, DynEq.GainF)) + " dB" : "—", "Gain — the static gain; or drag the node up / down",
+ inactive: () => !Capable(b)), 1),
+ Col(K(pQ, "Q", () => NotaNum.F($"{B(b, DynEq.QF):0.00}"), "Q — the width (the resonance on the cuts); or the wheel over the node",
+ liveLabel: () => TypeOf(b) is DynEq.LowCut or DynEq.HighCut ? "RESO" : "Q"), 2),
+ } };
- var graphPanel = new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(6), Child = curve, HorizontalAlignment = HorizontalAlignment.Stretch };
- var tablePanel = new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 6), Child = rightCol };
+ // ---- dynamics mode ----
+ var modeSeg = Segments(DynEq.ModeNames, () => ModeOf(b), i =>
+ {
+ if (i != DynEq.Static && !Capable(b)) return;
+ DynamicEqCurve.SetMode(engine, track, di, b, i);
+ RefreshAll(); curve.InvalidateVisual();
+ }, out var modeSync, padX: 6, dim: () => !Capable(b));
+ Learn(modeSeg, pMode);
+ ToolTip.SetTip(modeSeg, "Static — a plain EQ band · Duck — acts as the band's level rises above the threshold (a cut by default) · "
+ + "Lift — acts as it falls below it (a boost by default)");
+ bandReadouts.Add(modeSync);
+ var dynLabel = Caps("DYNAMICS");
+ bandReadouts.Add(() => dynLabel.Foreground = IsDyn(b) ? AccentBright : TextTertiary);
+ var modeRow = new Border
+ {
+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0),
+ Child = new DockPanel { Children = { Docked(modeSeg, Dock.Right), dynLabel } },
+ };
- var mainRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6, Height = 154 };
- Grid.SetColumn(graphPanel, 0); Grid.SetColumn(tablePanel, 1);
- mainRow.Children.Add(graphPanel); mainRow.Children.Add(tablePanel);
+ // ---- sliders ----
+ bool DynOp() => IsDyn(b);
+ Control SliderRow(string label, int p, Func<string> fmt, string tip, Func<double>? getN = null, Action<double>? setN = null,
+ Func<double>? marker = null, Func<IBrush?>? ink = null, Action? reset = null, Control? valueCtl = null)
+ {
+ getN ??= () => ToN(p, P(p));
+ setN ??= n => Raw(p, (float)FromN(p, n));
+ reset ??= () => SetP(p, (float)DefOf(p));
+ var trk = new SliderTrack { Reset = () => { reset(); RefreshAll(); } };
+ trk.Changed += v => { setN(v); RefreshAll(); curve.InvalidateVisual(); };
+ trk.GestureBegin += () => Begin(p);
+ trk.GestureEnd += () => End(p);
+ Learn(trk, p);
+ ToolTip.SetTip(trk, tip);
+ var val = Mono(fmt(), 8, TextPrimary); val.TextAlignment = TextAlignment.Right; val.HorizontalAlignment = HorizontalAlignment.Right;
+ var lbl = Caps(label);
+ bandReadouts.Add(() =>
+ {
+ bool op = DynOp();
+ if (!trk.Dragging) trk.Norm = getN();
+ trk.IsDim = !op;
+ trk.Ink = ink?.Invoke();
+ trk.Marker = marker is not null && op ? marker() : double.NaN;
+ val.Text = fmt();
+ val.Foreground = op ? TextPrimary : TextDisabled;
+ lbl.Foreground = op ? TextTertiary : TextDisabled;
+ });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("40,*,40"), ColumnSpacing = 6, Height = 11 };
+ g.Children.Add(lbl);
+ g.Children.Add(Col(trk, 1));
+ g.Children.Add(Col(valueCtl ?? val, 2));
+ if (valueCtl is Border { Child: Panel vp }) vp.Children.Add(val);
+ return g;
+ }
+ float Rng() => B(b, DynEq.RangeF);
+ // Range: the slider sets the magnitude, the arrow the direction (click it to flip).
+ var flip = new Border
+ {
+ Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), HorizontalAlignment = HorizontalAlignment.Right,
+ };
+ ToolTip.SetTip(flip, "Flip — cut ↔ boost (a Duck that boosts is upward expansion, a Lift that cuts is downward expansion)");
+ var flipPanel = new Panel();
+ flip.Child = flipPanel;
+ flip.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(flip).Properties.IsLeftButtonPressed) return;
+ float r = Rng(); if (Math.Abs(r) < 0.05f) r = ModeOf(b) == DynEq.Lift ? -6 : 6;
+ SetP(pRange, -r); RefreshAll(); curve.InvalidateVisual(); e.Handled = true;
+ };
+ var sliders = new StackPanel
+ {
+ Spacing = 5, Children =
+ {
+ SliderRow("THRESH", pThr, () => NotaNum.F($"{B(b, DynEq.ThrF):0} dB"),
+ "Threshold — where the band starts to act; the teal mark is the band's level now",
+ marker: () => ToN(pThr, Math.Max(mn[pThr], curve.Level(b)))),
+ SliderRow("RANGE", pRange, () => (Rng() >= 0 ? "↑ " : "↓ ") + NotaNum.F($"{Math.Abs(Rng()):0.0}"),
+ "Range — how far the gain can move at full engagement (6 dB past the threshold); click the arrow to flip cut / boost",
+ getN: () => Math.Abs(Rng()) / 18.0,
+ setN: n =>
+ {
+ float sgn = Rng() > 0 || (Math.Abs(Rng()) < 0.05f && ModeOf(b) == DynEq.Lift) ? 1 : -1;
+ Raw(pRange, sgn * (float)(Math.Clamp(n, 0, 1) * 18.0));
+ },
+ ink: () => DirInk(b),
+ reset: () => SetP(pRange, ModeOf(b) == DynEq.Lift ? 6 : -6),
+ valueCtl: flip),
+ SliderRow("ATTACK", pAtk, () => DynEq.Ms(B(b, DynEq.AtkF)), "Attack — how fast the band moves toward its range"),
+ SliderRow("RELEASE", pRel, () => DynEq.Ms(B(b, DynEq.RelF)), "Release — how fast it returns to its static gain"),
+ },
+ };
- return new Border { Padding = new Thickness(8, 6), Child = new StackPanel { Children = { liveStrip, mainRow } } };
- }
-}
+ // ---- key + solo ----
+ var keySeg = Segments(new[] { "Self", "Ext" }, () => KeyExt(b) ? 1 : 0, i =>
+ {
+ if (i == 0)
+ {
+ if (P(DynEq.SidechainP) >= 0.5f)
+ {
+ // Leave the legacy "every band keyed" switch: the other bands keep Ext.
+ for (int o = 0; o < DynEq.Bands; o++) if (o != b) SetP(DynEq.KeyBase + o, 1);
+ SetP(DynEq.SidechainP, 0);
+ }
+ SetP(pKey, 0);
+ }
+ else
+ {
+ bool was = KeyExt(b);
+ SetP(pKey, 1);
+ if (was || Src() < 0) ShowKeyMenu(bandHost);
+ }
+ RefreshAll();
+ }, out var keySync);
+ Learn(keySeg, pKey);
+ ToolTip.SetTip(keySeg, "Key — Self: the band listens to this track · Ext: to the key track (click Ext again to pick the track)");
+ bandReadouts.Add(keySync);
+ var soloTb = new TextBlock { Text = "Solo", FontSize = 8, VerticalAlignment = VerticalAlignment.Center };
+ var solo = new Border
+ {
+ Height = 15, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1),
+ Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = soloTb,
+ };
+ solo.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(solo).Properties.IsLeftButtonPressed) return;
+ SetP(DynEq.SoloP, Solo() == b ? 0 : b + 1); RefreshAll(); curve.InvalidateVisual(); e.Handled = true;
+ };
+ Learn(solo, DynEq.SoloP);
+ ToolTip.SetTip(solo, "Solo — hear this band alone");
+ bandReadouts.Add(() =>
+ {
+ bool on = Solo() == b;
+ solo.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
+ solo.BorderBrush = on ? Brass : NotaPalette.BorderStrong;
+ soloTb.Foreground = on ? AccentBright : TextSecondary;
+ soloTb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ });
+ var keyRow = new DockPanel
+ {
+ Children = { Docked(solo, Dock.Right), Docked(new Border { Width = 46, Child = Caps("KEY") }, Dock.Left), new Border { HorizontalAlignment = HorizontalAlignment.Left, Child = keySeg } },
+ };
-// 2-second per-band gain-reduction history, newest at the right. Duck (negative GR)
-// draws downward in teal; lift (positive) upward in brass — the same colour logic as
-// the graph, so the history reads at a glance whether the release is too fast.
-internal sealed class GrHistoryView : Control
-{
- private readonly DynamicEqCurve _curve;
- private readonly float[] _buf = new float[DynamicEqCurve.HistLen];
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IPen Mid = new Pen(NotaPalette.BorderStrong, 1);
- private static readonly IBrush DuckFill = NotaPalette.Wash(NotaPalette.Teal, 0x40);
- private static readonly IPen DuckPen = new Pen(NotaPalette.Teal, 1.2);
- private static readonly IPen LiftPen = new Pen(NotaPalette.Accent, 1.2);
+ var body = new Grid
+ {
+ RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto,*,Auto,*,Auto"), Margin = new Thickness(8, 6, 8, 6),
+ };
+ void Row(Control c, int r) { Grid.SetRow(c, r); body.Children.Add(c); }
+ Row(typeSeg, 0); Row(knobs, 2); Row(modeRow, 4); Row(sliders, 6); Row(keyRow, 8);
+ var panel = new DockPanel { LastChildFill = true, Children = { Docked(headBorder, Dock.Top), body } };
+ for (int i = 0; i < bandReadouts.Count; i++) bandReadouts[i]();
+ return panel;
+ }
- public GrHistoryView(DynamicEqCurve curve) { _curve = curve; MinHeight = 28; }
- public void Tick() => InvalidateVisual();
+ var right = new Border
+ {
+ Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ ClipToBounds = true, Child = bandHost,
+ };
+ DockPanel.SetDock(right, Dock.Right);
+ bandHost.Content = BandPanel(Sel());
+ curve.SelectionChanged += () => { bandHost.Content = BandPanel(Sel()); RefreshAll(); };
+ curve.Edited += RefreshAll;
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- ctx.FillRectangle(Bg, new Rect(0, 0, w, h), 4);
- double mid = h / 2;
- ctx.DrawLine(Mid, new Point(0, mid), new Point(w, mid));
- _curve.FillHistory(_curve.SelectedBand, _buf);
- const double range = 12; // ±12 dB full scale
- var geo = new StreamGeometry();
- using (var g = geo.Open())
+ // ======================================================================
+ // Status strip: summary · gain now · Dynamic · output · engine
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ string StatusText()
{
- g.BeginFigure(new Point(0, mid), true);
- for (int i = 0; i < _buf.Length; i++)
- {
- double x = w * i / (_buf.Length - 1);
- double y = mid - Math.Clamp(_buf[i] / range, -1, 1) * (mid - 2);
- g.LineTo(new Point(x, y));
- }
- g.LineTo(new Point(w, mid));
- g.EndFigure(true);
+ int s = Sel(), nOn = 0, nDyn = 0;
+ for (int b = 0; b < DynEq.Bands; b++) { if (BandOn(b)) nOn++; if (IsDyn(b)) nDyn++; }
+ var parts = new List<string> { NotaNum.F($"{nOn} bands · {nDyn} dynamic") };
+ string band = NotaNum.F($"B{s + 1} {DynEq.TypeNames[TypeOf(s)]} {DynEq.Hz(B(s, DynEq.FreqF))}");
+ if (Capable(s)) band += " " + DynEq.Db(B(s, DynEq.GainF)) + " dB";
+ band += NotaNum.F($" · Q {B(s, DynEq.QF):0.00}");
+ parts.Add(band);
+ bool anyExt = false;
+ for (int b = 0; b < DynEq.Bands; b++) if (IsDyn(b) && KeyExt(b)) anyExt = true;
+ if (anyExt) parts.Add("key " + (Src() >= 0 ? SrcName(Src()) : "none"));
+ return string.Join(" · ", parts);
}
- ctx.DrawGeometry(DuckFill, null, geo);
- // outline
- var line = new StreamGeometry();
- using (var g = line.Open())
+ var nowRead = Mono("", 8, TextTertiary);
+ ToolTip.SetTip(nowRead, "The selected band's dynamic gain right now");
+ readouts.Add(() =>
{
- for (int i = 0; i < _buf.Length; i++)
+ int s = Sel();
+ if (IsDyn(s))
{
- double x = w * i / (_buf.Length - 1);
- double y = mid - Math.Clamp(_buf[i] / range, -1, 1) * (mid - 2);
- if (i == 0) g.BeginFigure(new Point(x, y), false); else g.LineTo(new Point(x, y));
+ double g = curve.Gr(s);
+ nowRead.Text = NotaNum.F($"B{s + 1} ") + (B(s, DynEq.RangeF) >= 0 ? "↑ " : "↓ ") + NotaNum.F($"{Math.Abs(g):0.0} dB");
+ nowRead.Foreground = DirInk(s, bright: true);
}
+ else
+ {
+ nowRead.Text = Solo() >= 0 ? NotaNum.F($"SOLO B{Solo() + 1}") : NotaNum.F($"B{s + 1} static");
+ nowRead.Foreground = Solo() >= 0 ? AccentBright : TextTertiary;
+ }
+ });
+ var dynSw = Switch("Dynamic", DynMaster, () => { SetP(DynEq.DynamicsP, DynMaster() ? 0 : 1); RefreshAll(); curve.InvalidateVisual(); }, out var dynSync);
+ Learn(dynSw, DynEq.DynamicsP);
+ ToolTip.SetTip(dynSw, "Dynamic — off parks every band on its static gain: hear what the dynamics do");
+ readouts.Add(dynSync);
+
+ // OUT: a mono readout that drags vertically (±18 dB), double-click resets to 0.
+ var outTb = Mono("", 8, TextSecondary);
+ var outBox = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), VerticalAlignment = VerticalAlignment.Center, Child = outTb };
+ bool outDrag = false; double outY = 0;
+ outBox.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(outBox).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { SetP(DynEq.OutputP, 0); RefreshAll(); e.Handled = true; return; }
+ outDrag = true; outY = e.GetPosition(outBox).Y; e.Pointer.Capture(outBox); Begin(DynEq.OutputP); e.Handled = true;
+ };
+ outBox.PointerMoved += (_, e) =>
+ {
+ if (!outDrag) return;
+ double y = e.GetPosition(outBox).Y, dy = outY - y; outY = y;
+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;
+ Raw(DynEq.OutputP, P(DynEq.OutputP) + (float)(dy * 36.0 / (fine ? 1400.0 : 140.0)));
+ RefreshAll();
+ };
+ void OutEnd() { if (!outDrag) return; outDrag = false; End(DynEq.OutputP); }
+ outBox.PointerReleased += (_, e) => { OutEnd(); e.Pointer.Capture(null); };
+ outBox.PointerCaptureLost += (_, _) => OutEnd();
+ Learn(outBox, DynEq.OutputP);
+ ToolTip.SetTip(outBox, "Output — drag up / down (Shift for fine), double-click for 0 dB");
+ readouts.Add(() =>
+ {
+ float o = P(DynEq.OutputP);
+ outTb.Text = "OUT " + DynEq.Db(o) + " dB";
+ outTb.Foreground = Math.Abs(o) > 0.05f ? AccentBright : TextSecondary;
+ });
+ var engineRead = Mono("", 8, TextTertiary);
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ double sr = Sc(DynEq.S_SampleRate);
+ engineRead.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · CPU {Sc(DynEq.S_Cpu) * 100:0.0} %") : "";
+ });
+ var statusRight = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { nowRead, dynSw, outBox, engineRead } };
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };
+ 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 = { right, graphPanel } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, DynEq.kScope);
+ curve.Update(scope, scN);
+ RefreshAll();
}
- ctx.DrawGeometry(null, _curve.Gr(_curve.SelectedBand) > 0 ? LiftPen : DuckPen, line);
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 590e0117..9bae37f3 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1584,22 +1584,123 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("beatrepeat", 11, "Latch Freeze", ("Chance", 0f), ("Grid", 0.2f), ("Mode", 0.5f), ("Latch", 1f));
Fx("beatrepeat", 11, "Gate Only Bursts", ("Interval", 0.6f), ("Offset", 0.5f), ("Grid", 0.4f), ("Gate", 0.5f), ("Mode", 1f));
- // ---- Nota Crush (kind 12) — all params normalized 0..1. Mode 0 Digital/.5 Analog/1 Fold.
- Fx("crush", 12, "Broken Radio", ("Bits", 0.35f), ("Rate", 0.30f), ("Mode", 0f), ("Dither", 0.15f), ("Jitter", 0.10f), ("Noise Floor", 0.05f), ("Post Filter", 0.70f), ("Dry/Wet", 0.78f), ("Output", 0.5f));
- Fx("crush", 12, "8-Bit Arcade", ("Bits", 0.30f), ("Rate", 0.25f), ("Mode", 0f), ("Dither", 0.05f), ("Jitter", 0f), ("Noise Floor", 0f), ("Post Filter", 0.85f), ("Dry/Wet", 1f), ("Output", 0.5f));
- Fx("crush", 12, "Lo-Fi Warmth", ("Bits", 0.45f), ("Rate", 0.40f), ("Mode", 1f), ("Dither", 0.30f), ("Jitter", 0.15f), ("Noise Floor", 0.10f), ("Post Filter", 0.60f), ("Dry/Wet", 0.65f), ("Output", 0.5f));
- Fx("crush", 12, "Digital Grit", ("Bits", 0.20f), ("Rate", 0.15f), ("Mode", 0f), ("Dither", 0f), ("Jitter", 0.25f), ("Noise Floor", 0.15f), ("Post Filter", 0.50f), ("Dry/Wet", 0.85f), ("Output", 0.5f));
- Fx("crush", 12, "Folded Crunch", ("Bits", 0.40f), ("Rate", 0.50f), ("Mode", 1f), ("Dither", 0.10f), ("Jitter", 0.05f), ("Noise Floor", 0.05f), ("Post Filter", 0.75f), ("Dry/Wet", 0.70f), ("Output", 0.5f));
- Fx("crush", 12, "Telephone Line", ("Bits", 0.15f), ("Rate", 0.10f), ("Mode", 0f), ("Dither", 0f), ("Jitter", 0f), ("Noise Floor", 0.20f), ("Post Filter", 0.40f), ("Dry/Wet", 1f), ("Output", 0.5f));
+ // ---- Nota Crush (kind 12) — all params normalized 0..1 (unnamed ones reset to their defaults:
+ // 13.7 bit, ~1.9 kHz, Digital, dither 15 %, filter ~10 kHz, wet 100 %, drive 0 dB). Bits
+ // 1 + v·23 (0.13 = 4 bit, 0.30 = 8 bit, 0.48 = 12 bit); Rate exp 500 Hz … 0.48·sr (0.185 =
+ // 1 kHz, 0.37 = 2 k, 0.555 = 4 k, 0.74 = 8 k, 0.825 = 11 k); Mode 0 Digital / .5 Analog /
+ // 1 Fold; Post Filter exp 200 Hz … 20 k (0.5 = 2 k, 0.65 = 4 k, 0.8 = 8 k); Drive −12 … +24 dB
+ // (0.333 = 0 dB, 0.5 = +6, 0.667 = +12); Output ±12 dB (0.5 = 0). Anti-Alias, Auto Gain,
+ // DC Filter 1 = on.
+ Fx("crush", 12, "Init");
+ // Classic lo-fi
+ Fx("crush", 12, "Broken Radio", ("Bits", 0.35f), ("Rate", 0.30f), ("Mode", 0f), ("Dither", 0.15f), ("Jitter", 0.10f), ("Noise Floor", 0.05f), ("Post Filter", 0.70f), ("Dry/Wet", 0.78f), ("Output", 0.5f));
+ Fx("crush", 12, "Lo-Fi Warmth", ("Bits", 0.45f), ("Rate", 0.40f), ("Mode", 0.5f), ("Dither", 0.30f), ("Jitter", 0.15f), ("Noise Floor", 0.10f), ("Post Filter", 0.60f), ("Dry/Wet", 0.65f), ("Auto Gain", 1f));
+ Fx("crush", 12, "Lo-Fi Tape", ("Bits", 0.30f), ("Rate", 0.66f), ("Mode", 0.5f), ("Dither", 0.30f), ("Jitter", 0.22f), ("Noise Floor", 0.12f), ("Post Filter", 0.68f), ("Dry/Wet", 0.70f), ("Anti-Alias", 1f), ("Drive", 0.5f), ("Output", 0.375f));
+ Fx("crush", 12, "Dusty Sampler", ("Bits", 0.48f), ("Rate", 0.74f), ("Mode", 0.5f), ("Dither", 0.20f), ("Noise Floor", 0.08f), ("Post Filter", 0.78f), ("Dry/Wet", 1f), ("Anti-Alias", 1f), ("Drive", 0.42f));
+ Fx("crush", 12, "SP-1200 Grit", ("Bits", 0.48f), ("Rate", 0.87f), ("Mode", 0f), ("Dither", 0f), ("Post Filter", 0.92f), ("Dry/Wet", 1f), ("Drive", 0.40f));
+ Fx("crush", 12, "MPC Crunch", ("Bits", 0.65f), ("Rate", 0.92f), ("Mode", 0.5f), ("Dither", 0.10f), ("Post Filter", 0.95f), ("Dry/Wet", 1f), ("Anti-Alias", 1f), ("Drive", 0.45f));
+ Fx("crush", 12, "Telephone Line", ("Bits", 0.15f), ("Rate", 0.10f), ("Mode", 0f), ("Dither", 0f), ("Noise Floor", 0.20f), ("Post Filter", 0.40f), ("Dry/Wet", 1f), ("Output", 0.5f));
+ Fx("crush", 12, "AM Transmitter", ("Bits", 0.26f), ("Rate", 0.48f), ("Mode", 0.5f), ("Dither", 0.25f), ("Jitter", 0.30f), ("Noise Floor", 0.30f), ("Post Filter", 0.55f), ("Dry/Wet", 1f), ("Anti-Alias", 1f), ("DC Filter", 1f));
+ Fx("crush", 12, "Walkie-Talkie", ("Bits", 0.17f), ("Rate", 0.28f), ("Mode", 0.5f), ("Dither", 0.40f), ("Jitter", 0.15f), ("Noise Floor", 0.35f), ("Post Filter", 0.52f), ("Dry/Wet", 1f), ("Drive", 0.6f), ("Auto Gain", 1f));
+ // Retro machines
+ Fx("crush", 12, "8-Bit Arcade", ("Bits", 0.30f), ("Rate", 0.25f), ("Mode", 0f), ("Dither", 0.05f), ("Jitter", 0f), ("Noise Floor", 0f), ("Post Filter", 0.85f), ("Dry/Wet", 1f), ("Output", 0.5f));
+ Fx("crush", 12, "4-Bit Handheld", ("Bits", 0.13f), ("Rate", 0.56f), ("Mode", 0f), ("Dither", 0f), ("Post Filter", 0.80f), ("Dry/Wet", 1f), ("Drive", 0.40f), ("Auto Gain", 1f));
+ Fx("crush", 12, "NES Pulse", ("Bits", 0.13f), ("Rate", 0.78f), ("Mode", 0f), ("Dither", 0f), ("Post Filter", 0.95f), ("Dry/Wet", 1f), ("DC Filter", 1f));
+ Fx("crush", 12, "16-Bit Console", ("Bits", 0.65f), ("Rate", 0.70f), ("Mode", 0f), ("Dither", 0.05f), ("Post Filter", 0.76f), ("Dry/Wet", 1f), ("Anti-Alias", 1f));
+ Fx("crush", 12, "Game Boy Wave", ("Bits", 0.13f), ("Rate", 0.66f), ("Mode", 0f), ("Dither", 0f), ("Post Filter", 0.72f), ("Dry/Wet", 1f), ("DC Filter", 1f), ("Output", 0.42f));
+ Fx("crush", 12, "Speak & Spell", ("Bits", 0.22f), ("Rate", 0.52f), ("Mode", 0.5f), ("Dither", 0.10f), ("Jitter", 0.05f), ("Post Filter", 0.62f), ("Dry/Wet", 1f), ("Drive", 0.45f));
+ // Subtle texture
+ Fx("crush", 12, "Subtle Air", ("Bits", 0.60f), ("Rate", 0.95f), ("Mode", 0.5f), ("Dither", 0.20f), ("Post Filter", 1f), ("Dry/Wet", 0.35f));
+ Fx("crush", 12, "Parallel Grit", ("Bits", 0.26f), ("Rate", 0.60f), ("Mode", 0f), ("Dither", 0.10f), ("Post Filter", 0.75f), ("Dry/Wet", 0.30f), ("Drive", 0.5f), ("Auto Gain", 1f));
+ Fx("crush", 12, "Vinyl Dust", ("Bits", 0.55f), ("Rate", 0.85f), ("Mode", 0.5f), ("Dither", 0.45f), ("Jitter", 0.08f), ("Noise Floor", 0.18f), ("Post Filter", 0.74f), ("Dry/Wet", 0.55f));
+ Fx("crush", 12, "Warm 12-Bit", ("Bits", 0.48f), ("Rate", 0.82f), ("Mode", 0.5f), ("Dither", 0.25f), ("Post Filter", 0.80f), ("Dry/Wet", 1f), ("Anti-Alias", 1f), ("Auto Gain", 1f));
+ Fx("crush", 12, "Hi-Hat Sizzle", ("Bits", 0.35f), ("Rate", 0.68f), ("Mode", 0f), ("Dither", 0f), ("Post Filter", 1f), ("Dry/Wet", 0.45f));
+ Fx("crush", 12, "Drum Bus Dirt", ("Bits", 0.40f), ("Rate", 0.80f), ("Mode", 0.5f), ("Dither", 0.10f), ("Post Filter", 0.85f), ("Dry/Wet", 0.50f), ("Drive", 0.55f), ("Auto Gain", 1f), ("DC Filter", 1f));
+ // Destroy
+ Fx("crush", 12, "Digital Grit", ("Bits", 0.20f), ("Rate", 0.15f), ("Mode", 0f), ("Dither", 0f), ("Jitter", 0.25f), ("Noise Floor", 0.15f), ("Post Filter", 0.50f), ("Dry/Wet", 0.85f), ("Output", 0.5f));
+ Fx("crush", 12, "1-Bit Buzz", ("Bits", 0f), ("Rate", 0.55f), ("Mode", 0f), ("Dither", 0f), ("Post Filter", 0.62f), ("Dry/Wet", 1f), ("Auto Gain", 1f), ("DC Filter", 1f));
+ Fx("crush", 12, "Aliasing Storm", ("Bits", 0.35f), ("Rate", 0.12f), ("Mode", 0f), ("Dither", 0f), ("Jitter", 0.10f), ("Post Filter", 1f), ("Dry/Wet", 1f), ("Auto Gain", 1f));
+ Fx("crush", 12, "Broken Clock", ("Bits", 0.40f), ("Rate", 0.45f), ("Mode", 0f), ("Dither", 0.05f), ("Jitter", 1f), ("Post Filter", 0.80f), ("Dry/Wet", 1f));
+ Fx("crush", 12, "Bitrot", ("Bits", 0.09f), ("Rate", 0.35f), ("Mode", 0.5f), ("Dither", 0.60f), ("Jitter", 0.40f), ("Noise Floor", 0.45f), ("Post Filter", 0.58f), ("Dry/Wet", 1f), ("Drive", 0.6f), ("Auto Gain", 1f), ("DC Filter", 1f));
+ Fx("crush", 12, "Sub Destroyer", ("Bits", 0.10f), ("Rate", 0.20f), ("Mode", 0.5f), ("Dither", 0f), ("Post Filter", 0.35f), ("Dry/Wet", 0.60f), ("Drive", 0.75f), ("Auto Gain", 1f), ("DC Filter", 1f));
+ // Fold
+ Fx("crush", 12, "Folded Crunch", ("Bits", 0.40f), ("Rate", 0.50f), ("Mode", 1f), ("Dither", 0.10f), ("Jitter", 0.05f), ("Noise Floor", 0.05f), ("Post Filter", 0.75f), ("Dry/Wet", 0.70f), ("Output", 0.5f));
+ Fx("crush", 12, "Broken Toy", ("Bits", 0.13f), ("Rate", 0.82f), ("Mode", 1f), ("Dither", 0f), ("Post Filter", 0.80f), ("Dry/Wet", 1f), ("Drive", 0.667f), ("Output", 0.29f), ("Auto Gain", 1f));
+ Fx("crush", 12, "Gentle Fold", ("Bits", 0.70f), ("Rate", 1f), ("Mode", 1f), ("Dither", 0.05f), ("Post Filter", 0.85f), ("Dry/Wet", 0.50f), ("Drive", 0.25f), ("Auto Gain", 1f), ("DC Filter", 1f));
+ Fx("crush", 12, "West Coast Fold", ("Bits", 0.80f), ("Rate", 1f), ("Mode", 1f), ("Dither", 0f), ("Post Filter", 0.90f), ("Dry/Wet", 1f), ("Drive", 0.58f), ("Anti-Alias", 1f), ("Auto Gain", 1f), ("DC Filter", 1f));
+ Fx("crush", 12, "Metal Fold", ("Bits", 0.22f), ("Rate", 0.62f), ("Mode", 1f), ("Dither", 0.05f), ("Jitter", 0.10f), ("Post Filter", 0.70f), ("Dry/Wet", 1f), ("Drive", 0.83f), ("Auto Gain", 1f), ("DC Filter", 1f));
- // ---- Nota Dynamic EQ-8 (kind 13) — raw units, param names "<band> <field>".
- // "n Mode": 0 Static / 1 Above (duck) / 2 Below (lift). "n Rng" signed dB.
- Fx("dyneq", 13, "De-Ess", ("6 On", 1f), ("6 Type", 2f), ("6 Freq", 7000f), ("6 Q", 3.5f), ("6 Mode", 1f), ("6 Thr", -28f), ("6 Rng", -8f), ("6 Atk", 1f), ("6 Rel", 60f));
- Fx("dyneq", 13, "De-Harsh Vox", ("4 Freq", 3000f), ("4 Q", 2.4f), ("4 Mode", 1f), ("4 Thr", -24f), ("4 Rng", -6f), ("4 Atk", 5f), ("4 Rel", 120f));
- Fx("dyneq", 13, "Bass Control", ("2 Freq", 90f), ("2 Q", 1.0f), ("2 Mode", 1f), ("2 Thr", -20f), ("2 Rng", -6f), ("2 Atk", 8f), ("2 Rel", 140f));
- Fx("dyneq", 13, "Vocal Presence", ("4 Freq", 3500f), ("4 Q", 1.2f), ("4 Mode", 2f), ("4 Thr", -30f), ("4 Rng", 4f), ("4 Atk", 12f), ("4 Rel", 180f), ("7 Type", 4f), ("7 Freq", 11000f), ("7 Gain", 2f));
- Fx("dyneq", 13, "Warm Master", ("2 Type", 1f), ("2 Freq", 110f), ("2 Gain", 1.8f), ("7 Freq", 10000f), ("7 Mode", 1f), ("7 Thr", -18f), ("7 Rng", -3f), ("7 Atk", 20f), ("7 Rel", 250f));
- Fx("dyneq", 13, "Punch Tighten", ("3 Freq", 800f), ("3 Q", 1.2f), ("3 Mode", 1f), ("3 Thr", -22f), ("3 Rng", -5f), ("3 Atk", 3f), ("3 Rel", 90f));
+ // ---- Nota Dynamic EQ-8 (kind 13) — raw units, param names "<band> <field>" (unnamed
+ // params reset to the defaults: 1 low cut 30 Hz, 2 bell 120, 3 bell 800, 4 bell 3 k,
+ // 7 high shelf 10 k, 8 high cut 20 k on and flat; 5 / 6 off; dynamics −24 dB, −6 dB,
+ // 10 / 120 ms). "n Type" 0 HP / 1 LS / 2 Bell / 3 Notch / 4 HS / 5 LP. "n Mode" 0 Static /
+ // 1 Duck (acts above Thr) / 2 Lift (acts below Thr); "n Rng" signed dB (Duck normally
+ // cuts, Lift boosts — the other sign is upward / downward expansion). "n Key" 1 = the
+ // band listens to the key track (route one with the sidechain source).
+ Fx("dyneq", 13, "Init");
+ // Vocal
+ Fx("dyneq", 13, "De-Ess", ("6 On", 1f), ("6 Type", 2f), ("6 Freq", 7000f), ("6 Q", 3.5f), ("6 Mode", 1f), ("6 Thr", -28f), ("6 Rng", -8f), ("6 Atk", 1f), ("6 Rel", 60f));
+ Fx("dyneq", 13, "De-Ess Soft", ("6 On", 1f), ("6 Type", 4f), ("6 Freq", 6500f), ("6 Mode", 1f), ("6 Thr", -30f), ("6 Rng", -5f), ("6 Atk", 2f), ("6 Rel", 80f));
+ Fx("dyneq", 13, "De-Harsh Vox", ("4 Freq", 3000f), ("4 Q", 2.4f), ("4 Mode", 1f), ("4 Thr", -24f), ("4 Rng", -6f), ("4 Atk", 5f), ("4 Rel", 120f));
+ Fx("dyneq", 13, "Vocal Tame", ("1 Freq", 90f), ("2 Type", 1f), ("2 Freq", 180f), ("2 Gain", -1.5f), ("2 Q", 0.71f),
+ ("3 Freq", 380f), ("3 Gain", -1f), ("3 Q", 1.4f), ("3 Mode", 1f), ("3 Thr", -28f), ("3 Rng", -4f), ("3 Atk", 20f), ("3 Rel", 180f),
+ ("4 Freq", 2600f), ("4 Gain", 2f), ("4 Q", 0.9f),
+ ("5 On", 1f), ("5 Freq", 6800f), ("5 Q", 3f), ("5 Mode", 1f), ("5 Thr", -34f), ("5 Rng", -9f), ("5 Atk", 1f), ("5 Rel", 60f),
+ ("7 Freq", 12000f), ("7 Gain", 2.5f), ("8 On", 0f));
+ Fx("dyneq", 13, "Vocal Presence", ("4 Freq", 3500f), ("4 Q", 1.2f), ("4 Mode", 2f), ("4 Thr", -30f), ("4 Rng", 4f), ("4 Atk", 12f), ("4 Rel", 180f), ("7 Type", 4f), ("7 Freq", 11000f), ("7 Gain", 2f));
+ Fx("dyneq", 13, "Proximity Control", ("1 Freq", 70f), ("2 Type", 1f), ("2 Freq", 200f), ("2 Q", 0.71f), ("2 Mode", 1f), ("2 Thr", -22f), ("2 Rng", -5f), ("2 Atk", 10f), ("2 Rel", 150f));
+ Fx("dyneq", 13, "Air Lift Vocal", ("1 Freq", 80f), ("7 Freq", 11000f), ("7 Gain", 1f), ("7 Mode", 2f), ("7 Thr", -36f), ("7 Rng", 4f), ("7 Atk", 15f), ("7 Rel", 200f));
+ Fx("dyneq", 13, "Podcast Voice", ("1 Freq", 80f), ("2 Freq", 250f), ("2 Q", 1.2f), ("2 Mode", 1f), ("2 Thr", -26f), ("2 Rng", -4f), ("2 Atk", 15f), ("2 Rel", 160f),
+ ("4 Freq", 3500f), ("4 Gain", 1.5f), ("4 Q", 1f),
+ ("6 On", 1f), ("6 Freq", 7500f), ("6 Q", 3f), ("6 Mode", 1f), ("6 Thr", -30f), ("6 Rng", -6f), ("6 Atk", 1f), ("6 Rel", 50f));
+ // Mix and master
+ Fx("dyneq", 13, "Mix Bus Air", ("2 Type", 1f), ("2 Freq", 90f), ("2 Gain", 1f), ("2 Q", 0.71f), ("2 Mode", 1f), ("2 Thr", -20f), ("2 Rng", -3f), ("2 Atk", 5f), ("2 Rel", 90f), ("2 Key", 1f),
+ ("3 Freq", 778f), ("3 Gain", 1.5f), ("3 Q", 1f), ("3 Mode", 1f), ("3 Thr", -30f), ("3 Rng", -6f), ("3 Atk", 8f), ("3 Rel", 140f),
+ ("4 Q", 1f), ("7 Freq", 8300f), ("7 Gain", -2f), ("7 Mode", 2f), ("7 Thr", -24f), ("7 Rng", 6f), ("7 Atk", 10f), ("7 Rel", 120f));
+ Fx("dyneq", 13, "Warm Master", ("2 Type", 1f), ("2 Freq", 110f), ("2 Gain", 1.8f), ("7 Freq", 10000f), ("7 Mode", 1f), ("7 Thr", -18f), ("7 Rng", -3f), ("7 Atk", 20f), ("7 Rel", 250f));
+ Fx("dyneq", 13, "Master Glue EQ", ("2 Type", 1f), ("2 Freq", 60f), ("2 Mode", 1f), ("2 Thr", -18f), ("2 Rng", -2f), ("2 Atk", 30f), ("2 Rel", 300f),
+ ("3 Freq", 250f), ("3 Q", 0.8f), ("3 Mode", 1f), ("3 Thr", -24f), ("3 Rng", -2f), ("3 Atk", 20f), ("3 Rel", 250f),
+ ("4 Freq", 2500f), ("4 Q", 1f), ("4 Mode", 1f), ("4 Thr", -22f), ("4 Rng", -2f), ("4 Atk", 10f), ("4 Rel", 200f),
+ ("7 Freq", 12000f), ("7 Gain", 1f));
+ Fx("dyneq", 13, "Mud Control", ("3 Freq", 300f), ("3 Q", 1.2f), ("3 Mode", 1f), ("3 Thr", -26f), ("3 Rng", -5f), ("3 Atk", 15f), ("3 Rel", 160f));
+ Fx("dyneq", 13, "Harshness Guard", ("4 Freq", 3200f), ("4 Q", 2f), ("4 Mode", 1f), ("4 Thr", -24f), ("4 Rng", -4f), ("4 Atk", 3f), ("4 Rel", 100f),
+ ("6 On", 1f), ("6 Freq", 5500f), ("6 Q", 2.5f), ("6 Mode", 1f), ("6 Thr", -26f), ("6 Rng", -4f), ("6 Atk", 2f), ("6 Rel", 80f));
+ Fx("dyneq", 13, "Loudness Contour", ("2 Type", 1f), ("2 Freq", 100f), ("2 Mode", 2f), ("2 Thr", -30f), ("2 Rng", 4f), ("2 Atk", 30f), ("2 Rel", 400f),
+ ("7 Freq", 9000f), ("7 Mode", 2f), ("7 Thr", -34f), ("7 Rng", 3f), ("7 Atk", 30f), ("7 Rel", 400f));
+ // Drums
+ Fx("dyneq", 13, "Punch Tighten", ("3 Freq", 800f), ("3 Q", 1.2f), ("3 Mode", 1f), ("3 Thr", -22f), ("3 Rng", -5f), ("3 Atk", 3f), ("3 Rel", 90f));
+ Fx("dyneq", 13, "Kick Box Cut", ("2 Type", 1f), ("2 Freq", 60f), ("2 Gain", 2f), ("3 Freq", 350f), ("3 Q", 1.6f), ("3 Mode", 1f), ("3 Thr", -28f), ("3 Rng", -6f), ("3 Atk", 5f), ("3 Rel", 120f));
+ Fx("dyneq", 13, "Snare Ring Tamer", ("5 On", 1f), ("5 Freq", 230f), ("5 Q", 6f), ("5 Mode", 1f), ("5 Thr", -30f), ("5 Rng", -8f), ("5 Atk", 2f), ("5 Rel", 180f));
+ Fx("dyneq", 13, "Cymbal Smoother", ("6 On", 1f), ("6 Freq", 4500f), ("6 Q", 2f), ("6 Mode", 1f), ("6 Thr", -30f), ("6 Rng", -3f), ("6 Atk", 2f), ("6 Rel", 100f),
+ ("7 Freq", 8000f), ("7 Mode", 1f), ("7 Thr", -28f), ("7 Rng", -5f), ("7 Atk", 1f), ("7 Rel", 90f));
+ Fx("dyneq", 13, "Room Mic Duck", ("2 Type", 1f), ("2 Freq", 150f), ("2 Mode", 1f), ("2 Thr", -20f), ("2 Rng", -6f), ("2 Atk", 1f), ("2 Rel", 80f),
+ ("3 Freq", 600f), ("3 Q", 1f), ("3 Mode", 1f), ("3 Thr", -24f), ("3 Rng", -4f), ("3 Atk", 2f), ("3 Rel", 120f));
+ // Bass
+ Fx("dyneq", 13, "Bass Control", ("2 Freq", 90f), ("2 Q", 1.0f), ("2 Mode", 1f), ("2 Thr", -20f), ("2 Rng", -6f), ("2 Atk", 8f), ("2 Rel", 140f));
+ Fx("dyneq", 13, "Bass Clarity", ("1 Freq", 35f), ("3 Freq", 250f), ("3 Q", 1.4f), ("3 Mode", 1f), ("3 Thr", -24f), ("3 Rng", -5f), ("3 Atk", 10f), ("3 Rel", 120f),
+ ("4 Freq", 800f), ("4 Gain", 2f), ("4 Q", 1.2f));
+ Fx("dyneq", 13, "Sub Tamer", ("1 Freq", 25f), ("2 Type", 1f), ("2 Freq", 60f), ("2 Mode", 1f), ("2 Thr", -18f), ("2 Rng", -6f), ("2 Atk", 20f), ("2 Rel", 200f));
+ // Keyed from another track (route the key track with the sidechain source)
+ Fx("dyneq", 13, "Kick Ducks Bass", ("2 Freq", 70f), ("2 Q", 1.2f), ("2 Mode", 1f), ("2 Thr", -30f), ("2 Rng", -8f), ("2 Atk", 1f), ("2 Rel", 120f), ("2 Key", 1f));
+ Fx("dyneq", 13, "Vocal Pocket", ("3 Freq", 1000f), ("3 Q", 1f), ("3 Mode", 1f), ("3 Thr", -34f), ("3 Rng", -3f), ("3 Atk", 5f), ("3 Rel", 150f), ("3 Key", 1f),
+ ("4 Freq", 2500f), ("4 Q", 0.8f), ("4 Mode", 1f), ("4 Thr", -32f), ("4 Rng", -4f), ("4 Atk", 5f), ("4 Rel", 150f), ("4 Key", 1f));
+ Fx("dyneq", 13, "Voiceover Space", ("3 Freq", 1500f), ("3 Q", 0.7f), ("3 Mode", 1f), ("3 Thr", -35f), ("3 Rng", -5f), ("3 Atk", 10f), ("3 Rel", 250f), ("3 Key", 1f));
+ // Instruments
+ Fx("dyneq", 13, "Guitar Resonance", ("2 Freq", 180f), ("2 Q", 1f), ("2 Mode", 1f), ("2 Thr", -22f), ("2 Rng", -3f), ("2 Atk", 10f), ("2 Rel", 150f),
+ ("3 Freq", 1800f), ("3 Q", 4f), ("3 Mode", 1f), ("3 Thr", -26f), ("3 Rng", -6f), ("3 Atk", 2f), ("3 Rel", 100f));
+ Fx("dyneq", 13, "Piano Boom Control", ("2 Type", 1f), ("2 Freq", 150f), ("2 Mode", 1f), ("2 Thr", -24f), ("2 Rng", -4f), ("2 Atk", 20f), ("2 Rel", 250f),
+ ("7 Freq", 9000f), ("7 Gain", 1.5f));
+ Fx("dyneq", 13, "Acoustic Body Lift", ("2 Freq", 200f), ("2 Q", 1f), ("2 Mode", 2f), ("2 Thr", -36f), ("2 Rng", 3f), ("2 Atk", 20f), ("2 Rel", 300f),
+ ("7 Gain", 1.5f));
+ Fx("dyneq", 13, "Pad Smoother", ("4 Freq", 2000f), ("4 Q", 1f), ("4 Mode", 1f), ("4 Thr", -28f), ("4 Rng", -4f), ("4 Atk", 20f), ("4 Rel", 300f),
+ ("7 Freq", 7000f), ("7 Mode", 1f), ("7 Thr", -30f), ("7 Rng", -3f), ("7 Atk", 20f), ("7 Rel", 300f));
+ // Expansion (the flipped directions)
+ Fx("dyneq", 13, "Upward Air", ("7 Freq", 10000f), ("7 Mode", 1f), ("7 Thr", -30f), ("7 Rng", 4f), ("7 Atk", 5f), ("7 Rel", 150f));
+ Fx("dyneq", 13, "Hiss Dip", ("7 Freq", 6000f), ("7 Mode", 2f), ("7 Thr", -45f), ("7 Rng", -8f), ("7 Atk", 5f), ("7 Rel", 200f));
+ // Static
+ Fx("dyneq", 13, "Cleanup", ("1 Freq", 80f), ("1 Q", 0.9f), ("2 Freq", 250f), ("2 Gain", -3f), ("2 Q", 2f), ("3 Freq", 1200f), ("3 Gain", -1.5f), ("3 Q", 1f),
+ ("4 Freq", 4000f), ("4 Gain", 2.5f), ("4 Q", 1.2f), ("5 On", 1f), ("5 Type", 3f), ("5 Freq", 3150f), ("5 Q", 8f),
+ ("6 On", 1f), ("6 Type", 4f), ("6 Freq", 10000f), ("6 Gain", 3f), ("6 Q", 0.71f), ("7 On", 0f), ("8 On", 0f));
// ---- Nota Ceiling (kind 14) — look-ahead limiter, raw units (unnamed params reset to their
// defaults: Ceiling −1 dB, Gain 0, Release 120 ms, Look-ahead 3 ms, Link 100 %, SC HP
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 4571a685..8398008d 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -67,10 +67,10 @@ 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). 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. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers.")]
+ [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. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Dynamic EQ-8 (kind 13): id 0 = a one-line summary (bands on and dynamic, the Dynamic switch, each band on with its type, frequency, gain, Q and — for a dynamic band — mode, threshold, range, attack / release and key, solo, output, whether a key track is routed), 1 = the live reading (in / out peaks, whether a key arrives, each band's detector level and — for a dynamic band — its threshold and the gain it has now of its range, CPU), 2 = a guide to the parameter layout and units — or use read_dynamic_eq for the numbers and set_dynamic_eq_band to edit a band. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers. Nota Crush (kind 12): id 0 = a one-line summary (mode, bits, rate with the hold, drive, wet, dither / jitter / noise, post filter, output, anti-alias, auto gain, DC filter), 1 = the live reading (in / out peak and RMS, crest, peak holds, bits with the level count and quantisation noise, the reduced rate, hold and Nyquist, THD+N, images above the Nyquist, the driven peak and folds, auto gain, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_crush 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). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Nota Shutter (kind 19): id 0 resets the meters (peak reduction, the opening count, the history); id 1 sets the history window read_shutter and the card show (intArg 0 = 250 ms, 1 = 1 s, 2 = 4 s). Nota Auto Shift (kind 10): id 0 resets the analysis (the sung-note histogram and the pitch history); id 1 is Learn — intArg 1 starts listening (clears the histogram), 0 stops and sets Key + Scale (Major / Minor) to the best match and Key Source to Manual, 2 cancels. Nota Beat Repeat (kind 11): id 0 resets (stops the repeat, clears the timeline, the meters and the burst count); id 1 fires a repeat now, as if the interval hit (ignores Chance; while the transport plays — to hold one, set the Repeat param to 1). Nota Ceiling (kind 14): id 0 resets the peaks (the peak and true-peak holds, the max reduction, the clip count and the 4 s level window); id 1 resets the loudness (integrated, LRA, the 60 s window) and the peaks. 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). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Nota Shutter (kind 19): id 0 resets the meters (peak reduction, the opening count, the history); id 1 sets the history window read_shutter and the card show (intArg 0 = 250 ms, 1 = 1 s, 2 = 4 s). Nota Auto Shift (kind 10): id 0 resets the analysis (the sung-note histogram and the pitch history); id 1 is Learn — intArg 1 starts listening (clears the histogram), 0 stops and sets Key + Scale (Major / Minor) to the best match and Key Source to Manual, 2 cancels. Nota Beat Repeat (kind 11): id 0 resets (stops the repeat, clears the timeline, the meters and the burst count); id 1 fires a repeat now, as if the interval hit (ignores Chance; while the transport plays — to hold one, set the Repeat param to 1). Nota Ceiling (kind 14): id 0 resets the peaks (the peak and true-peak holds, the max reduction, the clip count and the 4 s level window); id 1 resets the loudness (integrated, LRA, the 60 s window) and the peaks. Nota Crush (kind 12): id 0 resets the meters (the peak holds and the spectrum average). 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));
@@ -488,6 +488,158 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
lufsI > -119 ? R1(lufsI - target) : 0, R1(V(11)), R1(V(12)), R1(V(30)), (int)V(22), V(20), cells.ToArray(), louds.ToArray());
});
+ public sealed record CrushBand(double Hz, double InputDb, double OutputDb);
+ public sealed record CrushReading(string Summary, string Live, string Mode, double Bits, double Levels, double QuantNoiseDb,
+ double RateHz, double HoldSamples, double NyquistHz, double DriveDb, double Wet, double PostFilterHz, bool AntiAlias,
+ bool AutoGain, bool DcFilter, double InputPeakDb, double OutputPeakDb, double InputRmsDb, double OutputRmsDb, double CrestDb,
+ double InputPeakHoldDb, double OutputPeakHoldDb, double ThdNPercent, double ImagesDb, double DrivenPeak, int Folds,
+ double AutoGainDb, bool Signal, bool SpectrumValid, double SampleRate, CrushBand[] Spectrum);
+
+ [McpServerTool(Name = "read_crush"), Description(
+ "Read what a Nota Crush (built-in effect kind 12 — bit crusher) is doing right now: the mode (Digital / Analog / Fold), "
+ + "the bit depth with its level count and the theoretical quantisation noise, the reduced sample rate with the samples "
+ + "each value is held and its Nyquist, drive, wet, the post filter, anti-alias / auto gain / DC filter; the meters — "
+ + "input and output peak and RMS (dBFS), the output crest factor, the peak holds since the reset; what the crush does "
+ + "to the sound, from an FFT of the driven input against the crushed output — THD+N (the content it added, % of the "
+ + "level-matched input), the images above the reduced Nyquist (dB against the whole output, −120 = none), the driven "
+ + "peak (linear) and how many times Fold folds it, the auto-gain correction; plus the spectrum in 20 log bands "
+ + "(input level-matched to the output, dB). Levels read −120 while silent; the meters move only while audio runs "
+ + "through the track. device_action 0 resets the meters; get_device_text id 2 explains each parameter value.")]
+ public Task<CrushReading> ReadCrush(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int tele = 32, bands = 40;
+ var sc = new float[tele + 2 * bands];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float Db(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ float Pm(int p) => E.DeviceGetParam(trackId, deviceIndex, p);
+ string[] modes = { "Digital", "Analog", "Fold" };
+ var spec = new List<CrushBand>();
+ if (n >= sc.Length)
+ for (int k = 0; k < 20; k++)
+ {
+ double pi = 0, po = 0;
+ for (int b = 2 * k; b < 2 * k + 2; b++) { pi += Math.Pow(10, sc[tele + b] / 10); po += Math.Pow(10, sc[tele + bands + b] / 10); }
+ double hz = 20 * Math.Pow(1000, (k + 0.5) / 20);
+ spec.Add(new CrushBand(Math.Round(hz), R1(Math.Max(-120, 10 * Math.Log10(Math.Max(1e-12, pi)))), R1(Math.Max(-120, 10 * Math.Log10(Math.Max(1e-12, po))))));
+ }
+ return new CrushReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ modes[Math.Clamp((int)Math.Round(Pm(2) * 2), 0, 2)], R1(V(8)), Math.Round(V(9)), R1(V(10)),
+ Math.Round(V(6)), V(7), Math.Round(V(20)), R1(-12 + Pm(10) * 36), Math.Round(Pm(7), 3), Math.Round(V(21)),
+ Pm(8) >= 0.5f, Pm(11) >= 0.5f, Pm(12) >= 0.5f, R1(Db(0)), R1(Db(1)), R1(Db(2)), R1(Db(3)), R1(V(4)), R1(Db(25)), R1(Db(24)),
+ R1(V(11) * 100), R1(Db(12)), Math.Round(V(16), 3), (int)V(17), R1(V(13)), V(23) > 0.5f, V(22) > 0.5f, V(5), spec.ToArray());
+ });
+
+ public sealed record DynEqBand(int Band, bool On, string Type, double FreqHz, double GainDb, double Q, string Mode, double ThresholdDb,
+ double RangeDb, double AttackMs, double ReleaseMs, string Key, bool Dynamic, double LevelDb, double GainNowDb, double ResponseDb);
+ public sealed record DynEqSpectrumBand(double Hz, double Db);
+ public sealed record DynEqReading(string Summary, string Live, bool Dynamics, int SoloBand, double OutputDb, int KeyTrackId, bool KeyLive,
+ double InputPeakDb, double OutputPeakDb, double SampleRate, DynEqBand[] Bands, bool SpectrumValid, DynEqSpectrumBand[] Spectrum);
+
+ private static readonly string[] DynEqTypes = { "Low cut", "Low shelf", "Bell", "Notch", "High shelf", "High cut" };
+ private static readonly string[] DynEqModes = { "Static", "Duck", "Lift" };
+
+ [McpServerTool(Name = "read_dynamic_eq"), Description(
+ "Read what a Nota Dynamic EQ-8 (built-in effect kind 13 — eight-band EQ where each band can react to level) is doing right "
+ + "now: the Dynamic master switch, the soloed band (0 = none), output, the key track routed (−1 none) and whether its signal "
+ + "arrives, in / out peaks; per band: on, type, frequency, static gain, Q, mode (Static / Duck — acts above the threshold / "
+ + "Lift — acts below it), threshold, signed range (negative cuts, positive boosts), attack / release, key (Self / Ext), "
+ + "whether it is dynamic now, its detector level (dBFS), the gain it adds now (dB) and the band's static response at its "
+ + "own frequency; plus the output spectrum in 24 log bands (dB). Levels read −120 while silent; they move only while audio "
+ + "runs through the track. get_device_text id 2 explains the parameter layout.")]
+ public Task<DynEqReading> ReadDynamicEq(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int tele = 32, spec = 96;
+ var sc = new float[tele + spec];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float Db(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ int pc = E.DeviceParamCount(trackId, deviceIndex);
+ float Pm(int p) => p < pc ? E.DeviceGetParam(trackId, deviceIndex, p) : 0f;
+ bool dyn = pc <= 83 || Pm(83) >= 0.5f;
+ var bands = new DynEqBand[8];
+ for (int b = 0; b < 8; b++)
+ {
+ int o = b * 10, ty = Math.Clamp((int)Math.Round(Pm(o + 1)), 0, 5), md = Math.Clamp((int)Math.Round(Pm(o + 5)), 0, 2);
+ bool on = Pm(o) > 0.5f, gain = ty is 1 or 2 or 4, ext = Pm(81) >= 0.5f || Pm(84 + b) >= 0.5f;
+ bool isDyn = dyn && on && gain && md != 0;
+ bands[b] = new DynEqBand(b + 1, on, DynEqTypes[ty], Math.Round(Pm(o + 2)), gain ? R1(Pm(o + 3)) : 0, Math.Round(Pm(o + 4), 2),
+ gain ? DynEqModes[md] : "Static", R1(Pm(o + 6)), R1(Pm(o + 7)), Math.Round(Pm(o + 8), 1), Math.Round(Pm(o + 9)), ext ? "Ext" : "Self",
+ isDyn, R1(Db(8 + b)), isDyn ? R1(V(b)) : 0, gain ? R1(Pm(o + 3) + (isDyn ? V(b) : 0)) : 0);
+ }
+ var sp = new List<DynEqSpectrumBand>();
+ bool valid = n >= sc.Length && V(18) > 0.5f;
+ if (valid)
+ for (int k = 0; k < 24; k++)
+ {
+ double pw = 0;
+ for (int b = 4 * k; b < 4 * k + 4; b++) pw += Math.Pow(10, sc[tele + b] / 10);
+ sp.Add(new DynEqSpectrumBand(Math.Round(20 * Math.Pow(1000, (k + 0.5) / 24)), R1(Math.Max(-120, 10 * Math.Log10(Math.Max(1e-12, pw))))));
+ }
+ return new DynEqReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1), dyn,
+ Math.Clamp((int)Math.Round(Pm(82)), 0, 8), R1(Pm(80)), E.DeviceSidechainSource(trackId, deviceIndex), V(21) > 0.5f,
+ R1(Db(19)), R1(Db(20)), V(16), bands, valid, sp.ToArray());
+ });
+
+ [McpServerTool(Name = "set_dynamic_eq_band"), Description(
+ "Edit one band of a Nota Dynamic EQ-8 (built-in effect kind 13) in one call — only the fields you pass change. type: "
+ + "\"Low cut\" | \"Low shelf\" | \"Bell\" | \"Notch\" | \"High shelf\" | \"High cut\" (only shelves and bells take gain and "
+ + "dynamics). mode: \"Static\" | \"Duck\" (acts as the band's level rises above the threshold) | \"Lift\" (acts as it falls "
+ + "below it). rangeDb is signed: negative cuts, positive boosts (a Duck normally cuts, a Lift boosts; the other sign is "
+ + "upward / downward expansion); full engagement is 6 dB past the threshold. key: \"Self\" or \"Ext\" (the key track — "
+ + "route one with set_device_sidechain). Each change is recorded like a hand edit. Returns the band as read back.")]
+ public Task<DynEqBand> SetDynamicEqBand(int trackId, int deviceIndex, [Description("Band 1..8")] int band,
+ bool? on = null, string? type = null, [Description("20..20000 Hz")] double? freqHz = null, [Description("−18..+18 dB")] double? gainDb = null,
+ [Description("0.1..18")] double? q = null, string? mode = null, [Description("−60..+6 dBFS")] double? thresholdDb = null,
+ [Description("−18..+18 dB")] double? rangeDb = null, [Description("0.1..300 ms")] double? attackMs = null,
+ [Description("5..2000 ms")] double? releaseMs = null, string? key = null) => Mutate(() =>
+ {
+ if (band < 1 || band > 8) throw new ArgumentException("band is 1..8");
+ int o = (band - 1) * 10;
+ void S(int p, double v)
+ {
+ E.BeginAutomationWrite(trackId, AutomationTarget.DeviceParam, deviceIndex, p, "");
+ E.DeviceSetParam(trackId, deviceIndex, p, (float)v);
+ E.EndAutomationWrite(trackId, AutomationTarget.DeviceParam, deviceIndex, p, "");
+ }
+ int Idx(string[] names, string v, string what)
+ {
+ int i = Array.FindIndex(names, s => string.Equals(s, v.Trim(), StringComparison.OrdinalIgnoreCase));
+ if (i < 0) throw new ArgumentException($"{what} must be one of: {string.Join(", ", names)}");
+ return i;
+ }
+ if (type is not null) S(o + 1, Idx(DynEqTypes, type, "type"));
+ if (freqHz is { } f) S(o + 2, f);
+ if (gainDb is { } g) S(o + 3, g);
+ if (q is { } qq) S(o + 4, qq);
+ if (thresholdDb is { } t) S(o + 6, t);
+ if (rangeDb is { } r) S(o + 7, r);
+ if (attackMs is { } a) S(o + 8, a);
+ if (releaseMs is { } rl) S(o + 9, rl);
+ if (mode is not null) S(o + 5, Idx(DynEqModes, mode, "mode"));
+ if (key is not null)
+ {
+ bool ext = Idx(new[] { "Self", "Ext" }, key, "key") == 1;
+ if (!ext && E.DeviceGetParam(trackId, deviceIndex, 81) >= 0.5f)
+ {
+ for (int b = 0; b < 8; b++) if (b != band - 1) S(84 + b, 1);
+ S(81, 0);
+ }
+ S(84 + band - 1, ext ? 1 : 0);
+ }
+ if (on is { } onv) S(o, onv ? 1 : 0);
+ int ty = Math.Clamp((int)Math.Round(E.DeviceGetParam(trackId, deviceIndex, o + 1)), 0, 5);
+ int md = Math.Clamp((int)Math.Round(E.DeviceGetParam(trackId, deviceIndex, o + 5)), 0, 2);
+ bool gain = ty is 1 or 2 or 4;
+ float Pm(int p) => E.DeviceGetParam(trackId, deviceIndex, p);
+ bool isDyn = Pm(83) >= 0.5f && Pm(o) > 0.5f && gain && md != 0;
+ return new DynEqBand(band, Pm(o) > 0.5f, DynEqTypes[ty], Math.Round(Pm(o + 2)), gain ? Math.Round(Pm(o + 3), 1) : 0, Math.Round(Pm(o + 4), 2),
+ gain ? DynEqModes[md] : "Static", Math.Round(Pm(o + 6), 1), Math.Round(Pm(o + 7), 1), Math.Round(Pm(o + 8), 1), Math.Round(Pm(o + 9)),
+ Pm(81) >= 0.5f || Pm(84 + band - 1) >= 0.5f ? "Ext" : "Self", isDyn, -120, 0, gain ? Math.Round(Pm(o + 3), 1) : 0);
+ });
+
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/Crush.h b/src/native/nota.engine/src/Crush.h
index e30f1c12..e1c1fa57 100644
--- a/src/native/nota.engine/src/Crush.h
+++ b/src/native/nota.engine/src/Crush.h
@@ -1,113 +1,197 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in Nota Crush (device kind 12) — a bit crusher with a drawn quantiser:
-// bit-depth reduction + sample-rate reduction, three modes (Digital hard truncate /
-// Analog soft clip / Fold wavefold), a GRIT panel (dither / jitter / noise floor),
-// an anti-alias toggle, a post filter, and dry/wet. All params normalized 0..1;
-// persistence / automation / clone flow generically through the base Device.
-// Header-only, allocation-free after construction. JUCE-free.
+// Built-in Nota Crush (device kind 12) — a bit crusher: bit-depth reduction and sample-rate
+// reduction with three characters (Digital hard truncate / Analog soft clip / Fold wavefold),
+// a GRIT stage (dither / jitter / noise floor), an anti-alias pre-filter, a post filter,
+// dry/wet, auto gain and a DC filter.
+//
+// in ─▶ drive ─▶ [anti-alias LP] ─▶ sample & hold (± jitter) ─▶ + dither ─▶ mode shape ─▶
+// quantise ─▶ + noise floor ─▶ post LP ─▶ [DC filter] ─▶ dry/wet ─▶ [auto gain] ─▶ out
+//
+// Anti-alias is a 4th-order Butterworth low-pass at the reduced rate's Nyquist, so what the
+// hold would fold back is taken out first. Auto gain rides the output back to the input's
+// loudness (300 ms RMS, ±24 dB). DC filter is a 10 Hz high-pass on the crushed path.
+//
+// All params are normalized 0..1 and APPEND ONLY: 0..10 are the original layout, Auto Gain
+// and DC Filter are appended and default off, so older projects open unchanged. Persistence /
+// automation / clone flow generically through the base Device.
+// Telemetry (scopeRead): kTele live values, then the spectrum — kBands log bands 20 Hz..20 kHz
+// of the driven input (level-matched to the output) and of the crushed output, in dB — from
+// an FFT over the last ~85 ms, analysed on the reading thread (≤ 30 Hz).
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = reset the meters (peak holds and the spectrum average).
+// Header-only, allocation-free after setSampleRate. JUCE-free.
#pragma once
#include "Device.h"
+#include "signalsmith-linear/fft.h"
+
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cmath>
+#include <complex>
#include <cstdint>
+#include <cstdio>
+#include <mutex>
+#include <string>
+#include <vector>
namespace nota {
class Crush : public Device {
public:
// Param layout — order is the persisted/automation layout. APPEND ONLY.
- enum { Bits = 0, Rate, Mode, Dither, Jitter, NoiseFloor, PostFilter, DryWet, AntiAlias, Output, Drive, kNumParams };
+ enum { Bits = 0, Rate, Mode, Dither, Jitter, NoiseFloor, PostFilter, DryWet, AntiAlias, Output, Drive,
+ AutoGain, DcFilter, kNumParams };
+
+ // Telemetry slots (scopeRead).
+ enum {
+ S_InPeak = 0, // dry input peak (300 ms fall), dBFS
+ S_OutPeak, // output peak (300 ms fall), dBFS
+ S_InRms, // dry input RMS (300 ms), dBFS
+ S_OutRms, // output RMS (300 ms), dBFS
+ S_Crest, // output crest factor: peak hold over 1 s − RMS, dB
+ S_SampleRate,
+ S_RateHz, // the reduced sample rate, Hz
+ S_Hold, // samples each value is held (sr / rate, fractional)
+ S_Bits, // effective bit depth, 1..24
+ S_Levels, // quantiser levels, 2^bits
+ S_QuantNoise, // theoretical quantisation noise of a full-scale sine, dB (−6.02·b − 1.76)
+ S_ThdN, // content added by the crush vs the level-matched input, ratio (0.046 = 4.6 %)
+ S_Images, // added content above the reduced Nyquist vs the whole output, dB (−120 none)
+ S_AutoGain, // the auto-gain correction applied now, dB
+ S_Cpu, // share of real time spent in process()
+ S_Latency, // samples
+ S_DrivenPeak, // peak after Drive (1 s hold), linear
+ S_Folds, // folds the driven peak makes in Fold mode (0 in the others)
+ S_Mode, // 0 Digital, 1 Analog, 2 Fold
+ S_Bands, // kBands
+ S_Nyquist, // the reduced rate's Nyquist, Hz
+ S_FilterHz, // the post filter's cutoff, Hz
+ S_Analysed, // 1 when the spectrum is valid
+ S_Signal, // 1 while signal comes in (above −70 dBFS)
+ S_OutPeakHold, // highest output peak since the meter reset, dBFS
+ S_InPeakHold, // highest input peak since the meter reset, dBFS
+ kTele = 32
+ };
+ static constexpr int kBands = 40;
+ static constexpr double kBandLo = 20.0, kBandHi = 20000.0;
+ static constexpr int kSpecAt = kTele; // input bands, then output bands
+ static constexpr int kScope = kTele + 2 * kBands;
Crush() {
- p_[Bits].store(0.55f); // ~8 bit
- p_[Rate].store(0.35f); // ~11 kHz
+ p_[Bits].store(0.55f); // ~13.7 bit
+ p_[Rate].store(0.35f); // ~1.9 kHz at 44.1 k
p_[Mode].store(0.0f); // Digital
p_[Dither].store(0.15f);
p_[Jitter].store(0.0f);
p_[NoiseFloor].store(0.0f);
- p_[PostFilter].store(0.85f); // ~12 kHz
+ p_[PostFilter].store(0.85f); // ~10 kHz
p_[DryWet].store(1.0f);
p_[AntiAlias].store(0.0f); // off
p_[Output].store(0.5f); // 0 dB
p_[Drive].store(0.333f); // ~0 dB pre-crush
+ p_[AutoGain].store(0.0f); // off
+ p_[DcFilter].store(0.0f); // off
+ setSampleRate(44100.0, 0);
}
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
+ std::lock_guard<std::mutex> lock(mx_);
sr_ = sr > 0 ? sr : 44100.0;
+ srA_.store((float)sr_, std::memory_order_relaxed);
holdL_ = holdR_ = 0.0f;
- cntL_ = cntR_ = 0;
+ phL_ = phR_ = perL_ = perR_ = 1.0; // the first sample is taken at once
lpL_ = lpR_ = 0.0f;
- antiL_ = antiR_ = 0.0f;
+ for (auto& s : aa_) s = {};
+ aaHz_ = -1.0;
+ dcX_[0] = dcX_[1] = dcY_[0] = dcY_[1] = 0.0f;
+ msIn_ = msOut_ = 0.0;
+ autoG_ = 1.0f;
+ fftN_ = sr_ > 50000.0 ? 8192 : 4096;
+ size_t ring = 1;
+ while (ring < (size_t)fftN_ * 2) ring <<= 1;
+ ringIn_.assign(ring, 0.0f); ringOut_.assign(ring, 0.0f);
+ ringMask_ = (uint32_t)(ring - 1);
+ ringW_.store(0, std::memory_order_relaxed);
+ fft_.resize((size_t)fftN_);
+ win_.assign((size_t)fftN_, 0.0f);
+ tIn_.assign((size_t)fftN_, 0.0f); tOut_.assign((size_t)fftN_, 0.0f);
+ fIn_.assign((size_t)fftN_ / 2, {}); fOut_.assign((size_t)fftN_ / 2, {});
+ for (int i = 0; i < fftN_; ++i) win_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * kPi * i / fftN_));
+ lastAnaS_ = -1.0; lastAnaW_ = 0; anaValid_ = false;
+ for (int b = 0; b < kBands; ++b) { aIn_[b] = aOut_[b] = 0.0; bandIn_[b] = bandOut_[b] = -120.0f; }
+ thdN_ = 0.0f; images_ = -120.0f;
+ resetMeters();
}
void process(float* buf, int32_t frames) override {
+ const auto t0 = std::chrono::steady_clock::now();
+ if (resetReq_.exchange(false, std::memory_order_acq_rel)) resetMeters();
+
const float bitsV = std::clamp(get(Bits), 0.0f, 1.0f);
const float rateV = std::clamp(get(Rate), 0.0f, 1.0f);
- const int mode = std::clamp((int)std::lround(get(Mode) * 2.0f), 0, 2);
+ const int mode = modeIndex();
const float dither = std::clamp(get(Dither), 0.0f, 1.0f);
const float jitter = std::clamp(get(Jitter), 0.0f, 1.0f);
const float nf = std::clamp(get(NoiseFloor), 0.0f, 1.0f);
const float filtV = std::clamp(get(PostFilter), 0.0f, 1.0f);
const float wet = std::clamp(get(DryWet), 0.0f, 1.0f);
const bool aa = get(AntiAlias) >= 0.5f;
+ const bool autoOn = get(AutoGain) >= 0.5f;
+ const bool dcOn = get(DcFilter) >= 0.5f;
const float outGain = std::pow(10.0f, (get(Output) - 0.5f) * 24.0f / 20.0f); // ±12 dB
- const float drive = std::pow(10.0f, (-12.0f + get(Drive) * 36.0f) / 20.0f); // -12..+24 dB pre-crush
+ const float drive = driveGain(); // -12..+24 dB pre-crush
- // Bit depth: 1..24 bits, exp-mapped so the knob feels natural.
- const float bits = 1.0f + bitsV * 23.0f;
- const float levels = std::pow(2.0f, bits);
- const float scale = levels - 1.0f;
+ // Bit depth: 1..24 bits.
+ const float bits = bitsOf(bitsV);
+ const float scale = std::pow(2.0f, bits) - 1.0f;
const float invScale = 1.0f / scale;
- // Sample-rate reduction: hold N samples. rateV 0→0.5 kHz, 1→sr/2.
- const double targetHz = expMap(rateV, 500.0, sr_ * 0.48);
- const int holdMax = std::max(1, (int)std::lround(sr_ / targetHz));
+ // Sample-rate reduction: a fractional sample & hold — a phase accumulator takes a new
+ // value every sr / rate samples (not rounded, so Rate sweeps smoothly). 0 → 0.5 kHz, 1 → 0.48·sr.
+ const double targetHz = rateHz(rateV);
+ const double inc = targetHz / sr_;
// Post filter: 1-pole lowpass, exp 200..20000 Hz.
const double filtHz = expMap(filtV, 200.0, 20000.0);
- const float filtCoef = (float)std::exp(-2.0 * 3.14159265358979323846 * filtHz / sr_);
+ const float filtCoef = (float)std::exp(-2.0 * kPi * filtHz / sr_);
const float filtGain = 1.0f - filtCoef;
- // Anti-alias filter: 1-pole lowpass at the Nyquist of the reduced rate.
- const double aaHz = std::min(targetHz * 0.45, sr_ * 0.45);
- const float aaCoef = (float)std::exp(-2.0 * 3.14159265358979323846 * aaHz / sr_);
- const float aaGain = 1.0f - aaCoef;
+ // Anti-alias: 4th-order Butterworth LP at the reduced rate's Nyquist (two biquads).
+ if (aa) {
+ const double hz = std::min(targetHz * 0.45, sr_ * 0.45);
+ if (std::fabs(hz - aaHz_) > 1e-3) computeAa(hz);
+ }
- // Dither amplitude: triangular PDF, ±0.5 LSB at full dither.
- const float dithAmp = dither * 0.5f * invScale;
+ const float dithAmp = dither * 0.5f * invScale; // triangular PDF, ±0.5 LSB at full
+ const float nfAmp = nf * 0.003f; // noise floor
+ const float dcR = (float)std::exp(-2.0 * kPi * 10.0 / sr_);
+ const double msC = 1.0 - std::exp(-1.0 / (0.300 * sr_)); // 300 ms RMS
+ const float gSlew = (float)(1.0 - std::exp(-1.0 / (0.050 * sr_)));
- // Noise floor amplitude.
- const float nfAmp = nf * 0.003f;
+ float inPk = 0.0f, outPk = 0.0f, drvPk = 0.0f;
+ uint32_t w = ringW_.load(std::memory_order_relaxed);
for (int32_t i = 0; i < frames; ++i) {
const float dryL = buf[i * 2], dryR = buf[i * 2 + 1];
+ inPk = std::max(inPk, std::max(std::fabs(dryL), std::fabs(dryR)));
- // --- anti-alias filter (before downsampling) ---
+ // --- drive + anti-alias filter (before downsampling) ---
float inL = dryL * drive, inR = dryR * drive;
- if (aa) {
- antiL_ += aaGain * (inL - antiL_);
- antiR_ += aaGain * (inR - antiR_);
- inL = antiL_; inR = antiR_;
- }
-
- // --- sample-rate reduction: sample & hold ---
- int holdL = holdMax, holdR = holdMax;
- if (jitter > 0.0f) {
- float jit = jitter * 0.5f;
- holdL = holdMax + (int)((whiteUni() * 2.0f - 1.0f) * jit * holdMax);
- holdR = holdMax + (int)((whiteUni() * 2.0f - 1.0f) * jit * holdMax);
- holdL = std::max(1, holdL); holdR = std::max(1, holdR);
- }
-
- if (--cntL_ <= 0) { cntL_ = holdL; holdL_ = inL; }
- if (--cntR_ <= 0) { cntR_ = holdR; holdR_ = inR; }
-
+ drvPk = std::max(drvPk, std::max(std::fabs(inL), std::fabs(inR)));
+ const float drvMono = 0.5f * (inL + inR);
+ if (aa) { inL = aaRun(0, inL); inR = aaRun(1, inR); }
+
+ // --- sample-rate reduction: sample & hold; Jitter stretches or shortens each hold
+ // by up to ±50 %, per channel ---
+ phL_ += inc; phR_ += inc;
+ if (phL_ >= perL_) { phL_ -= perL_; holdL_ = inL; perL_ = jitter > 0.0f ? 1.0 + (whiteUni() * 2.0f - 1.0f) * jitter * 0.5f : 1.0; }
+ if (phR_ >= perR_) { phR_ -= perR_; holdR_ = inR; perR_ = jitter > 0.0f ? 1.0 + (whiteUni() * 2.0f - 1.0f) * jitter * 0.5f : 1.0; }
float qL = holdL_, qR = holdR_;
// --- dither: triangular PDF noise before quantisation ---
@@ -118,20 +202,8 @@ public:
qR += (t1 - t2) * dithAmp;
}
- // --- mode-dependent shaping before quantisation ---
- switch (mode) {
- case 1: // Analog: soft clip
- qL = std::tanh(qL * 1.5f) / 0.905f;
- qR = std::tanh(qR * 1.5f) / 0.905f;
- break;
- case 2: // Fold: wavefold
- qL = wavefold(qL * 2.5f, 0.7f);
- qR = wavefold(qR * 2.5f, 0.7f);
- break;
- default: break; // Digital: no shaping
- }
-
- // --- bit-depth reduction: quantise ---
+ // --- mode shape, then quantise ---
+ qL = shape(mode, qL); qR = shape(mode, qR);
qL = std::round(qL * scale) * invScale;
qR = std::round(qR * scale) * invScale;
@@ -144,13 +216,117 @@ public:
// --- post filter ---
lpL_ += filtGain * (qL - lpL_);
lpR_ += filtGain * (qR - lpR_);
+ float cL = lpL_, cR = lpR_;
+
+ // --- DC filter ---
+ if (dcOn) {
+ const float yL = cL - dcX_[0] + dcR * dcY_[0]; dcX_[0] = cL; dcY_[0] = yL; cL = yL;
+ const float yR = cR - dcX_[1] + dcR * dcY_[1]; dcX_[1] = cR; dcY_[1] = yR; cR = yR;
+ }
+
+ // Analysis ring: the driven input and the crushed path (before the mix).
+ ringIn_[w & ringMask_] = drvMono;
+ ringOut_[w & ringMask_] = 0.5f * (cL + cR);
+ ++w;
+
+ // --- dry/wet, auto gain, output gain ---
+ float oL = dryL * (1.0f - wet) + cL * wet;
+ float oR = dryR * (1.0f - wet) + cR * wet;
+ msIn_ += msC * (0.5 * ((double)dryL * dryL + (double)dryR * dryR) - msIn_);
+ msOut_ += msC * (0.5 * ((double)oL * oL + (double)oR * oR) - msOut_);
+ float gT = 1.0f;
+ if (autoOn) {
+ if (msIn_ > 1e-9 && msOut_ > 1e-12) gT = (float)std::clamp(std::sqrt(msIn_ / msOut_), 0.063, 15.85); // ±24 dB
+ else gT = autoG_; // hold through silence
+ }
+ autoG_ += gSlew * (gT - autoG_);
+ oL *= autoG_ * outGain; oR *= autoG_ * outGain;
+ buf[i * 2] = oL; buf[i * 2 + 1] = oR;
+ outPk = std::max(outPk, std::max(std::fabs(oL), std::fabs(oR)));
+ }
+ ringW_.store(w, std::memory_order_release);
+
+ // Publish meters: peaks fall 20 dB per 300 ms after a hit; a 1 s hold feeds the crest.
+ if (frames > 0) {
+ const float fall = std::pow(10.0f, -(20.0f * frames / (0.3f * (float)sr_)) / 20.0f);
+ inPkM_ = std::max(inPk, inPkM_ * fall);
+ outPkM_ = std::max(outPk, outPkM_ * fall);
+ const float holdFall = std::pow(10.0f, -(3.0f * frames / (float)sr_) / 20.0f); // 3 dB/s
+ outPkHold1s_ = std::max(outPk, outPkHold1s_ * holdFall);
+ drvPkHold_ = std::max(drvPk, drvPkHold_ * holdFall);
+ inHold_ = std::max(inHold_, inPk); outHold_ = std::max(outHold_, outPk);
+ }
+ inPkA_.store(db(inPkM_), std::memory_order_relaxed);
+ outPkA_.store(db(outPkM_), std::memory_order_relaxed);
+ inRmsA_.store(dbMs(msIn_), std::memory_order_relaxed);
+ outRmsA_.store(dbMs(msOut_), std::memory_order_relaxed);
+ outHold1sA_.store(db(outPkHold1s_), std::memory_order_relaxed);
+ drvPkA_.store(drvPkHold_, std::memory_order_relaxed);
+ inHoldA_.store(db(inHold_), std::memory_order_relaxed);
+ outHoldA_.store(db(outHold_), std::memory_order_relaxed);
+ autoGA_.store(20.0f * std::log10(std::max(1e-6f, autoG_)), std::memory_order_relaxed);
+ if (frames > 0) {
+ 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((float)cpuS_, std::memory_order_relaxed);
+ }
+ }
- // --- dry/wet + output gain ---
- buf[i * 2] = (dryL * (1.0f - wet) + lpL_ * wet) * outGain;
- buf[i * 2 + 1] = (dryR * (1.0f - wet) + lpR_ * wet) * outGain;
+ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {
+ if (id == 0) {
+ resetReq_.store(true, std::memory_order_release);
+ std::lock_guard<std::mutex> lock(mx_);
+ lastAnaS_ = -1.0; // the next reading starts a fresh average
}
}
+ // Telemetry block, then the spectrum (input bands, output bands). Writes as much of that
+ // layout as fits in maxSamples. Called from the UI / MCP thread; lock-free against audio.
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ const bool bands = maxSamples > kTele;
+ float t[kTele] = {};
+ const double sr = sr_;
+ const float bits = bitsOf(get(Bits));
+ const double rate = rateHz(get(Rate));
+ t[S_InPeak] = inPkA_.load(std::memory_order_relaxed);
+ t[S_OutPeak] = outPkA_.load(std::memory_order_relaxed);
+ t[S_InRms] = inRmsA_.load(std::memory_order_relaxed);
+ t[S_OutRms] = outRmsA_.load(std::memory_order_relaxed);
+ const float hold1 = outHold1sA_.load(std::memory_order_relaxed);
+ t[S_Crest] = t[S_OutRms] > -119.0f && hold1 > -119.0f ? std::max(0.0f, hold1 - t[S_OutRms]) : 0.0f;
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ t[S_RateHz] = (float)rate;
+ t[S_Hold] = (float)std::max(1.0, sr / rate);
+ t[S_Bits] = bits;
+ t[S_Levels] = std::pow(2.0f, bits);
+ t[S_QuantNoise] = -(6.02f * bits + 1.76f);
+ t[S_AutoGain] = get(AutoGain) >= 0.5f ? autoGA_.load(std::memory_order_relaxed) : 0.0f;
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_Latency] = 0.0f;
+ t[S_DrivenPeak] = drvPkA_.load(std::memory_order_relaxed);
+ t[S_Mode] = (float)modeIndex();
+ t[S_Folds] = modeIndex() == 2 ? (float)foldCount(t[S_DrivenPeak]) : 0.0f;
+ t[S_Bands] = (float)kBands;
+ t[S_Nyquist] = (float)(rate * 0.5);
+ t[S_FilterHz] = (float)expMap(get(PostFilter), 200.0, 20000.0);
+ t[S_Signal] = t[S_InPeak] > -70.0f ? 1.0f : 0.0f;
+ t[S_InPeakHold] = inHoldA_.load(std::memory_order_relaxed);
+ t[S_OutPeakHold] = outHoldA_.load(std::memory_order_relaxed);
+
+ std::lock_guard<std::mutex> lock(mx_);
+ if (bands) t[S_Analysed] = analyse() ? 1.0f : 0.0f;
+ else t[S_Analysed] = anaValid_ ? 1.0f : 0.0f;
+ t[S_ThdN] = anaValid_ ? thdN_ : 0.0f;
+ t[S_Images] = anaValid_ ? images_ : -120.0f;
+
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ for (int b = 0; b < kBands && n < maxSamples; ++b) out[n++] = bandIn_[b];
+ for (int b = 0; b < kBands && n < maxSamples; ++b) out[n++] = bandOut_[b];
+ return n;
+ }
+
const char* displayName() const override { return "Nota Crush"; }
int32_t builtinKind() const override { return 12; }
@@ -161,6 +337,7 @@ public:
case Dither: return "Dither"; case Jitter: return "Jitter"; case NoiseFloor: return "Noise Floor";
case PostFilter: return "Post Filter"; case DryWet: return "Dry/Wet";
case AntiAlias: return "Anti-Alias"; case Output: return "Output"; case Drive: return "Drive";
+ case AutoGain: return "Auto Gain"; case DcFilter: return "DC Filter";
default: return "";
}
}
@@ -173,20 +350,186 @@ public:
if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
}
+ // 0 — a one-line status; 1 — the live reading; 2 — a guide to the parameter values.
+ std::string deviceText(int32_t id) const override {
+ char b[900];
+ static const char* modes[3] = { "Digital", "Analog", "Fold" };
+ if (id == 0) {
+ const double rate = rateHz(get(Rate));
+ std::string s = modes[modeIndex()];
+ std::snprintf(b, sizeof b, " - %.1f bit - rate %.0f Hz (hold %.1f) - drive %+.1f dB - wet %.0f %%",
+ bitsOf(get(Bits)), rate, std::max(1.0, sr_ / rate), driveDb(), get(DryWet) * 100.0f);
+ s += b;
+ if (get(Dither) > 0.001f) { std::snprintf(b, sizeof b, " - dither %.0f %%", get(Dither) * 100.0f); s += b; }
+ if (get(Jitter) > 0.001f) { std::snprintf(b, sizeof b, " - jitter %.0f %%", get(Jitter) * 100.0f); s += b; }
+ if (get(NoiseFloor) > 0.001f) { std::snprintf(b, sizeof b, " - noise %.0f %%", get(NoiseFloor) * 100.0f); s += b; }
+ std::snprintf(b, sizeof b, " - post filter %.0f Hz - output %+.1f dB", expMap(get(PostFilter), 200.0, 20000.0),
+ (get(Output) - 0.5f) * 24.0f);
+ s += b;
+ if (get(AntiAlias) >= 0.5f) s += " - anti-alias";
+ if (get(AutoGain) >= 0.5f) s += " - auto gain";
+ if (get(DcFilter) >= 0.5f) s += " - DC filter";
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ auto lv = [](float v) { char t[24]; if (v <= -119.0f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", v); return std::string(t); };
+ std::snprintf(b, sizeof b,
+ "in %s dBFS peak / %s RMS - out %s dBFS peak / %s RMS - crest %.1f dB - peaks since reset in %s, out %s - "
+ "%.1f bit (%.0f levels, quantisation noise %.0f dB) - %.0f Hz of %.0f (hold %.1f samples, Nyquist %.0f Hz) - "
+ "added content (THD+N) %.1f %% - images above Nyquist %s dB - driven peak x%.2f%s - auto gain %+.1f dB - "
+ "CPU %.2f %%",
+ lv(sc[S_InPeak]).c_str(), lv(sc[S_InRms]).c_str(), lv(sc[S_OutPeak]).c_str(), lv(sc[S_OutRms]).c_str(),
+ sc[S_Crest], lv(sc[S_InPeakHold]).c_str(), lv(sc[S_OutPeakHold]).c_str(), sc[S_Bits], sc[S_Levels],
+ sc[S_QuantNoise], sc[S_RateHz], sc[S_SampleRate], sc[S_Hold], sc[S_Nyquist], sc[S_ThdN] * 100.0f,
+ lv(sc[S_Images]).c_str(), sc[S_DrivenPeak], modeIndex() == 2 ? (" - " + std::to_string((int)sc[S_Folds]) + " folds").c_str() : "",
+ sc[S_AutoGain], sc[S_Cpu] * 100.0f);
+ return b;
+ }
+ if (id == 2) {
+ return "All params are normalized 0..1. Bits: 1 + v*23 bits (0.55 = 13.7 bit, 0.13 = 4 bit, 0.30 = 7.9 bit). "
+ "Rate: the reduced sample rate, exponential 500 Hz (0) .. 0.48 x the sample rate (1); each value is held "
+ "sr/rate samples (fractional) (0.35 = ~2 kHz at 44.1 k, 0.6 = ~5.5 kHz, 0.8 = ~11 kHz). Mode: 0 Digital (hard truncate), "
+ "0.5 Analog (tanh soft clip, +4 dB), 1 Fold (triangle wavefold - each +6 dB of Drive roughly doubles the folds). Dither: 0..1 = 0..+-0.5 LSB "
+ "triangular noise before quantising. Jitter: 0..1 = the hold length wanders up to +-50 %. Noise Floor: 0..1 "
+ "adds white noise up to -50 dBFS. Post Filter: 1-pole low-pass, exponential 200 Hz (0) .. 20 kHz (1). "
+ "Dry/Wet: 0..1. Anti-Alias: >= 0.5 low-passes the input at the reduced Nyquist (4th order) so less folds "
+ "back. Output: -12..+12 dB (0.5 = 0 dB). Drive: -12..+24 dB into the crusher (0.333 = 0 dB). Auto Gain: "
+ ">= 0.5 rides the output back to the input's loudness (300 ms RMS, +-24 dB). DC Filter: >= 0.5 a 10 Hz "
+ "high-pass on the crushed path.";
+ }
+ return {};
+ }
+
+ // ---- mappings (shared with the card through the guide above) -----------------------
+ static float bitsOf(float v) { return 1.0f + std::clamp(v, 0.0f, 1.0f) * 23.0f; }
+ double rateHz(float v) const { return expMap(v, 500.0, sr_ * 0.48); }
+ float driveDb() const { return -12.0f + get(Drive) * 36.0f; }
+ float driveGain() const { return std::pow(10.0f, driveDb() / 20.0f); }
+ int modeIndex() const { return std::clamp((int)std::lround(get(Mode) * 2.0f), 0, 2); }
+
private:
+ static constexpr double kPi = 3.14159265358979323846;
+
float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
-
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ static float dbMs(double ms) { return ms > 1e-12 ? (float)(10.0 * std::log10(ms)) : -120.0f; }
+
+ static float shape(int mode, float x) {
+ switch (mode) {
+ case 1: return std::tanh(x * 1.5f) / 0.905f; // Analog: soft clip
+ case 2: return wavefold(x * 2.5f, 0.7f); // Fold
+ default: return x; // Digital
+ }
+ }
+ // A triangle fold: straight through ±threshold, then reflected back and forth for as far as
+ // the input goes (a 4·threshold period), normalised to ±1. More drive, more folds.
static inline float wavefold(float x, float threshold) {
- const float limit = threshold * 4.0f;
- x = std::clamp(x, -limit, limit);
- int iter = 0;
- while (std::fabs(x) > threshold && iter < 8) {
- if (x > threshold) x = 2.0f * threshold - x;
- else if (x < -threshold) x = -2.0f * threshold - x;
- iter++;
+ const float period = 4.0f * threshold;
+ float u = std::fmod(x + threshold, period);
+ if (u < 0.0f) u += period;
+ return 1.0f - std::fabs(u - 2.0f * threshold) / threshold;
+ }
+ // How many times a peak of `pk` (after Drive) folds over in Fold mode.
+ static int foldCount(float pk) {
+ const float x = pk * 2.5f;
+ return x <= 0.7f ? 0 : std::min(99, (int)std::floor((x - 0.7f) / 1.4f) + 1);
+ }
+
+ // RBJ Butterworth sections (Q 0.5412 / 1.3066) for the 4th-order anti-alias low-pass.
+ struct Biquad { float b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0; };
+ struct BqState { float z1 = 0, z2 = 0; };
+ void computeAa(double hz) {
+ aaHz_ = hz;
+ static const double qs[2] = { 0.54119610, 1.30656296 };
+ for (int s = 0; s < 2; ++s) {
+ const double wv = 2.0 * kPi * hz / sr_, cw = std::cos(wv), al = std::sin(wv) / (2.0 * qs[s]), a0 = 1.0 + al;
+ auto& q = aaC_[s];
+ q.b0 = (float)((1.0 - cw) / 2.0 / a0); q.b1 = (float)((1.0 - cw) / a0); q.b2 = q.b0;
+ q.a1 = (float)(-2.0 * cw / a0); q.a2 = (float)((1.0 - al) / a0);
}
- return x / threshold;
+ }
+ float aaRun(int c, float x) {
+ for (int s = 0; s < 2; ++s) {
+ const auto& q = aaC_[s];
+ auto& z = aa_[(size_t)(c * 2 + s)];
+ const float y = q.b0 * x + z.z1;
+ z.z1 = q.b1 * x - q.a1 * y + z.z2;
+ z.z2 = q.b2 * x - q.a2 * y;
+ x = y;
+ }
+ return x;
+ }
+
+ void resetMeters() {
+ inPkM_ = outPkM_ = outPkHold1s_ = drvPkHold_ = 0.0f;
+ inHold_ = outHold_ = 0.0f;
+ }
+
+ // ---- spectrum analysis (reading thread, rate-limited, under mx_) ---------------------
+ static double nowSeconds() {
+ return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
+ }
+ bool analyse() const {
+ if (ringIn_.empty() || fftN_ <= 0) return false;
+ const double now = nowSeconds();
+ const uint32_t w = ringW_.load(std::memory_order_acquire);
+ if (lastAnaS_ >= 0 && (now - lastAnaS_ < 1.0 / 30.0 || w == lastAnaW_)) return anaValid_;
+ if (w < (uint32_t)fftN_) return anaValid_;
+ const int n = fftN_;
+ const uint32_t start = w - (uint32_t)n;
+ for (int i = 0; i < n; ++i) {
+ const uint32_t k = (start + (uint32_t)i) & ringMask_;
+ tIn_[(size_t)i] = ringIn_[k] * win_[(size_t)i];
+ tOut_[(size_t)i] = ringOut_[k] * win_[(size_t)i];
+ }
+ fft_.fft(tIn_.data(), fIn_.data());
+ fft_.fft(tOut_.data(), fOut_.data());
+ const int half = n / 2;
+
+ // Level-match the input to the output on the input's strongest bins (the mode's gain,
+ // the drive after the fold …), so what is left over is what the crush added.
+ double pkIn = 0.0;
+ for (int k = 1; k < half; ++k) pkIn = std::max(pkIn, (double)std::norm(fIn_[(size_t)k]));
+ double sIn = 0.0, sOut = 0.0;
+ if (pkIn > 0.0)
+ for (int k = 1; k < half; ++k)
+ if (std::norm(fIn_[(size_t)k]) >= pkIn * 0.1) { sIn += std::norm(fIn_[(size_t)k]); sOut += std::norm(fOut_[(size_t)k]); }
+ const double g = sIn > 1e-20 ? std::clamp(sOut / sIn, 1e-4, 1e4) : 1.0;
+
+ const double binHz = sr_ / n;
+ const double nyq = rateHz(get(Rate)) * 0.5;
+ double added = 0.0, addedHi = 0.0, totIn = 0.0, totOut = 0.0;
+ for (int k = 1; k < half; ++k) {
+ const double pi = std::norm(fIn_[(size_t)k]) * g, po = std::norm(fOut_[(size_t)k]);
+ const double ex = std::max(0.0, po - pi);
+ added += ex; totIn += pi; totOut += po;
+ if (k * binHz > nyq) addedHi += ex;
+ }
+ const double ref = 0.25 * (double)n * n * 0.25; // Hann: a full-scale sine's bin power
+ const bool stale = lastAnaS_ < 0 || now - lastAnaS_ > 1.2;
+ const double a = stale ? 1.0 : 1.0 - std::exp(-(now - lastAnaS_) / 0.25);
+ for (int b = 0; b < kBands; ++b) {
+ const double lo = kBandLo * std::pow(kBandHi / kBandLo, (double)b / kBands);
+ const double hi = kBandLo * std::pow(kBandHi / kBandLo, (double)(b + 1) / kBands);
+ int k0 = std::max(1, (int)std::ceil(lo / binHz)), k1 = std::min(half - 1, (int)std::ceil(hi / binHz) - 1);
+ if (k1 < k0) k0 = k1 = std::clamp((int)std::lround(std::sqrt(lo * hi) / binHz), 1, half - 1);
+ double si = 0.0, so = 0.0;
+ for (int k = k0; k <= k1; ++k) { si += std::norm(fIn_[(size_t)k]) * g; so += std::norm(fOut_[(size_t)k]); }
+ aIn_[b] += a * (si - aIn_[b]);
+ aOut_[b] += a * (so - aOut_[b]);
+ bandIn_[b] = aIn_[b] > ref * 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(aIn_[b] / ref)) : -120.0f;
+ bandOut_[b] = aOut_[b] > ref * 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(aOut_[b] / ref)) : -120.0f;
+ }
+ const float thd = totIn > ref * 1e-9 ? (float)std::sqrt(added / totIn) : 0.0f;
+ const float img = totOut > ref * 1e-9 && addedHi > totOut * 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(addedHi / totOut)) : -120.0f;
+ thdN_ = stale ? thd : thdN_ + (float)a * (thd - thdN_);
+ images_ = stale || images_ <= -119.0f || img <= -119.0f ? img : images_ + (float)a * (img - images_);
+ lastAnaS_ = now; lastAnaW_ = w;
+ anaValid_ = totIn > ref * 1e-9 || totOut > ref * 1e-9;
+ return anaValid_;
}
float whiteUni() { rng_ = rng_ * 1664525u + 1013904223u; return (float)((rng_ >> 8) & 0xFFFFFF) / 16777216.0f; }
@@ -194,10 +537,39 @@ private:
double sr_ = 44100.0;
std::atomic<float> p_[kNumParams] = {};
float holdL_ = 0.0f, holdR_ = 0.0f;
- int cntL_ = 0, cntR_ = 0;
+ double phL_ = 1.0, phR_ = 1.0, perL_ = 1.0, perR_ = 1.0;
float lpL_ = 0.0f, lpR_ = 0.0f;
- float antiL_ = 0.0f, antiR_ = 0.0f;
+ Biquad aaC_[2];
+ BqState aa_[4];
+ double aaHz_ = -1.0;
+ float dcX_[2] = {}, dcY_[2] = {};
+ double msIn_ = 0.0, msOut_ = 0.0;
+ float autoG_ = 1.0f;
uint32_t rng_ = 0xDEADBEEFu;
+
+ // Meters (audio thread) and their published copies.
+ float inPkM_ = 0.0f, outPkM_ = 0.0f, outPkHold1s_ = 0.0f, drvPkHold_ = 0.0f, inHold_ = 0.0f, outHold_ = 0.0f;
+ double cpuS_ = 0.0;
+ std::atomic<float> inPkA_{-120.0f}, outPkA_{-120.0f}, inRmsA_{-120.0f}, outRmsA_{-120.0f}, outHold1sA_{-120.0f};
+ std::atomic<float> drvPkA_{0.0f}, inHoldA_{-120.0f}, outHoldA_{-120.0f}, autoGA_{0.0f}, cpuA_{0.0f}, srA_{44100.0f};
+ std::atomic<bool> resetReq_{false};
+
+ // Spectrum: rings written by the audio thread, the analysis state under mx_.
+ std::vector<float> ringIn_, ringOut_;
+ uint32_t ringMask_ = 0;
+ std::atomic<uint32_t> ringW_{0};
+ int fftN_ = 0;
+ mutable std::mutex mx_;
+ mutable signalsmith::linear::RealFFT<float> fft_;
+ std::vector<float> win_;
+ mutable std::vector<float> tIn_, tOut_;
+ mutable std::vector<std::complex<float>> fIn_, fOut_;
+ mutable double aIn_[kBands] = {}, aOut_[kBands] = {};
+ mutable float bandIn_[kBands] = {}, bandOut_[kBands] = {};
+ mutable float thdN_ = 0.0f, images_ = -120.0f;
+ mutable double lastAnaS_ = -1.0;
+ mutable uint32_t lastAnaW_ = 0;
+ mutable bool anaValid_ = false;
};
} // namespace nota
diff --git a/src/native/nota.engine/src/DynamicEq.h b/src/native/nota.engine/src/DynamicEq.h
index d49d6ebe..b0b0bd44 100644
--- a/src/native/nota.engine/src/DynamicEq.h
+++ b/src/native/nota.engine/src/DynamicEq.h
@@ -1,29 +1,54 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Dynamic EQ-8 — an eight-band parametric equalizer where each band can also react
-// to level, like a per-band compressor/expander (dynamic-EQ
-// style). Static half mirrors Nota EQ-8: On / Type / Freq / Gain / Q, RBJ biquads,
-// stereo in place. Dynamic half adds, per band: a Mode (Off / Above / Below), a
-// Threshold, a signed Range (the extra dB applied at full engagement — negative
-// ducks, positive lifts), and Attack / Release. A per-band bandpass detector tracks
-// the energy in that band; the resulting gain (static + dynamic) drives the apply
-// biquad, recomputed at control rate. Only shelves/bells take dynamic gain.
+// Nota Dynamic EQ-8 (device kind 13) — an eight-band parametric equalizer where each band
+// can also react to level, like a per-band compressor / expander. The static half mirrors
+// Nota EQ-8: On / Type / Freq / Gain / Q, RBJ biquads, stereo in place. The dynamic half
+// adds, per band: a Mode, a Threshold, a signed Range (the extra dB at full engagement —
+// negative cuts, positive boosts), Attack / Release and a Key (the band's own signal or the
+// device's sidechain source).
//
-// scopeRead publishes the eight bands' momentary dynamic gain (dB, signed) so the UI
-// can draw the live "momentary" response curve and per-band GR bars — audio thread
-// writes, UI reads lock-free. Params are raw musical units (like EQ-8); persist /
-// clone / automation are generic through the base Device (builtinKind + params).
+// in ─▶ band 1 ─▶ band 2 ─▶ … ─▶ band 8 ─▶ output gain ─▶ out
+// key (self: the input · ext: the sidechain track) ─▶ band-pass at each band ─▶ envelope ─▶
+// level vs threshold ─▶ attack / release ─▶ dynamic gain added to the band's static gain
+//
+// Modes: Static (0) — a plain EQ band; Duck (1) — engages as the band's level rises ABOVE the
+// threshold; Lift (2) — engages as it falls BELOW it. Range carries the direction: the card
+// seeds Duck with a cut and Lift with a boost, either can be flipped (a Duck that boosts is
+// upward expansion, a Lift that cuts is downward expansion). The detector reaches full
+// engagement 6 dB past the threshold. Only shelves and bells take dynamic gain. Dynamics (a
+// master switch) parks every band on its static gain at once — an A/B of what the dynamics do.
+// Solo auditions one band alone.
+//
+// Params are the device's raw units (not 0..1) and APPEND ONLY: 0..79 are the eight bands
+// (10 fields each: On, Type, Freq, Gain, Q, Mode, Thr, Rng, Atk, Rel), 80 Output, 81
+// Sidechain (legacy: every band keyed from the sidechain), 82 Solo (band + 1, 0 = none) —
+// the original layout — then 83 Dynamics and 84..91 the per-band Key. Older projects open
+// unchanged: Dynamics defaults on, Key defaults to Self.
+//
+// Telemetry (scopeRead): 0..7 each band's momentary dynamic gain (dB, signed — the original
+// layout), 8..15 each band's detector level (dBFS, −120 when silent or off), then the live
+// values up to kTele, then the output spectrum — kSpec log bands 20 Hz..20 kHz in dB from an
+// FFT over the last ~85 ms, analysed on the reading thread (≤ 30 Hz).
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// Header-only, allocation-free after setSampleRate. JUCE-free.
#pragma once
#include "Device.h"
+#include "signalsmith-linear/fft.h"
+
#include <algorithm>
-#include <cstdio>
#include <atomic>
+#include <chrono>
#include <cmath>
+#include <complex>
#include <cstdint>
+#include <cstdio>
+#include <mutex>
+#include <string>
+#include <vector>
namespace nota {
@@ -36,18 +61,38 @@ public:
Mode = 5, Thresh = 6, Range = 7, Attack = 8, Release = 9 };
// Filter types (mirror Eq.h).
enum { LowCut = 0, LowShelf = 1, Bell = 2, Notch = 3, HighShelf = 4, HighCut = 5, kNumTypes = 6 };
- // Dynamic modes.
+ // Dynamic modes: Static, Duck (above the threshold), Lift (below it).
enum { DynOff = 0, DynAbove = 1, DynBelow = 2 };
static constexpr int kBandParams = kBands * kPerBand; // 80
- enum { Output = kBandParams, Sidechain = kBandParams + 1, Solo = kBandParams + 2 };
- static constexpr int kNumParams = kBandParams + 3; // 83
+ enum { Output = kBandParams, Sidechain = kBandParams + 1, Solo = kBandParams + 2,
+ Dynamics = kBandParams + 3, KeyBase = kBandParams + 4 };
+ static constexpr int kNumParams = KeyBase + kBands; // 92
// Solo param encoding: 0 = none, n = audition band n-1 (others muted).
+ // Telemetry slots (scopeRead).
+ enum {
+ S_Gain = 0, // 8 × momentary dynamic gain, dB (signed)
+ S_Level = 8, // 8 × detector level, dBFS (−120 silent / off)
+ S_SampleRate = 16,
+ S_Cpu, // share of real time spent in process()
+ S_Analysed, // 1 when the spectrum is valid
+ S_InPeak, // input peak (300 ms fall), dBFS
+ S_OutPeak, // output peak (300 ms fall), dBFS
+ S_KeyLive, // 1 while a sidechain buffer arrives
+ S_Bands, // kSpec
+ S_Latency, // samples (always 0)
+ kTele = 32
+ };
+ static constexpr int kSpec = 96;
+ static constexpr double kSpecLo = 20.0, kSpecHi = 20000.0;
+ static constexpr int kSpecAt = kTele;
+ static constexpr int kScope = kTele + kSpec;
+
DynamicEq() {
- // Neutral default: four musically-spread static bands enabled and flat, plus
- // ready HP/LP — no dynamics engaged, so adding the device is transparent. All
- // bands carry sensible dynamic defaults (thr/range/atk/rel) ready to switch on.
+ // Neutral default: musically spread bands, all flat — adding the device is
+ // transparent. Every band carries working dynamics (−24 dB, 6 dB cut, 10 / 120 ms)
+ // so switching a band to Duck or Lift reacts at once.
band(0, 1, LowCut, 30.0f, 0.0f, 0.71f);
band(1, 1, Bell, 120.0f, 0.0f, 1.00f);
band(2, 1, Bell, 800.0f, 0.0f, 0.90f);
@@ -59,71 +104,107 @@ public:
p_[Output].store(0.0f);
p_[Sidechain].store(0.0f);
p_[Solo].store(0.0f);
+ p_[Dynamics].store(1.0f);
+ for (int b = 0; b < kBands; ++b) p_[KeyBase + b].store(0.0f);
+ for (int b = 0; b < kBands; ++b) { lvlA_[b].store(-120.0f); gr_[b].store(0.0f); }
+ setSampleRate(44100.0, 0);
}
- void setSampleRate(double sr, int32_t /*maxBlock*/) override { sr_ = sr > 0 ? sr : 44100.0; }
-
- bool acceptsSidechain() const override { return true; }
- void setSidechain(const float* interleaved, int32_t frames) override {
- scLen_ = 0;
- if (!interleaved || frames <= 0) return;
- const int32_t n = std::min(frames, kMaxSc);
- for (int32_t i = 0; i < n; ++i) sc_[i] = 0.5f * (interleaved[i * 2] + interleaved[i * 2 + 1]);
- scLen_ = n;
+ void setSampleRate(double sr, int32_t /*maxBlock*/) override {
+ std::lock_guard<std::mutex> lock(mx_);
+ sr_ = sr > 0 ? sr : 44100.0;
+ srA_.store((float)sr_, std::memory_order_relaxed);
+ for (auto& ch : s_) for (auto& st : ch) st = {};
+ for (auto& st : detState_) st = {};
+ for (int b = 0; b < kBands; ++b) { detEnv_[b] = 0.0; dynDb_[b] = 0.0; lvlDisp_[b] = -120.0; }
+ inPk_ = outPk_ = 0.0f;
+ fftN_ = sr_ > 50000.0 ? 8192 : 4096;
+ size_t ring = 1;
+ while (ring < (size_t)fftN_ * 2) ring <<= 1;
+ ring_.assign(ring, 0.0f);
+ ringMask_ = (uint32_t)(ring - 1);
+ ringW_.store(0, std::memory_order_relaxed);
+ fft_.resize((size_t)fftN_);
+ win_.assign((size_t)fftN_, 0.0f);
+ tBuf_.assign((size_t)fftN_, 0.0f);
+ fBuf_.assign((size_t)fftN_ / 2, {});
+ for (int i = 0; i < fftN_; ++i) win_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * kPi * i / fftN_));
+ lastAnaS_ = -1.0; lastAnaW_ = 0; anaValid_ = false;
+ for (int b = 0; b < kSpec; ++b) { aSpec_[b] = 0.0; spec_[b] = -120.0f; }
}
+ bool acceptsSidechain() const override { return true; }
+ 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; }
+
void process(float* buf, int32_t frames) override {
+ const auto t0 = std::chrono::steady_clock::now();
const double sr = sr_;
- const bool scOn = p_[Sidechain].load(std::memory_order_relaxed) > 0.5f && scLen_ > 0;
- const double outGain = std::pow(10.0, clampd(p_[Output].load(std::memory_order_relaxed), -18.0, 18.0) / 20.0);
+ const float* sc = (scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;
+ const double scGain = std::pow(10.0, sidechainGainDb() / 20.0);
+ const bool allExt = get(Sidechain) >= 0.5f;
+ const bool dynMaster = get(Dynamics) >= 0.5f;
+ const double outGain = std::pow(10.0, clampd(get(Output), -18.0, 18.0) / 20.0);
- // Per-band static config + detector coefficients (recomputed per block).
- bool on[kBands], dyn[kBands], hasGain[kBands];
- int mode[kBands];
+ // Per-band config + detector coefficients (recomputed per block).
+ bool on[kBands], dyn[kBands], hasGain[kBands], ext[kBands];
+ int mode[kBands], type[kBands];
double f0[kBands], gStat[kBands], q[kBands], thr[kBands], range[kBands], atkC[kBands], relC[kBands];
Coeffs det[kBands];
for (int b = 0; b < kBands; ++b) {
- on[b] = p_[b * kPerBand + On].load(std::memory_order_relaxed) > 0.5f;
- const int ty = typeOf(b);
- hasGain[b] = (ty == LowShelf || ty == Bell || ty == HighShelf);
- f0[b] = clampd(p_[b * kPerBand + Freq].load(std::memory_order_relaxed), 20.0, sr * 0.49);
- gStat[b] = p_[b * kPerBand + Gain].load(std::memory_order_relaxed);
- q[b] = clampd(p_[b * kPerBand + Q].load(std::memory_order_relaxed), 0.1, 18.0);
+ on[b] = bp(b, On) > 0.5f;
+ type[b] = typeOf(b);
+ hasGain[b] = (type[b] == LowShelf || type[b] == Bell || type[b] == HighShelf);
+ f0[b] = clampd(bp(b, Freq), 20.0, sr * 0.49);
+ gStat[b] = clampd(bp(b, Gain), -18.0, 18.0);
+ q[b] = clampd(bp(b, Q), 0.1, 18.0);
mode[b] = modeOf(b);
- dyn[b] = on[b] && hasGain[b] && mode[b] != DynOff;
- thr[b] = clampd(p_[b * kPerBand + Thresh].load(std::memory_order_relaxed), -60.0, 6.0);
- range[b] = clampd(p_[b * kPerBand + Range].load(std::memory_order_relaxed), -18.0, 18.0);
- const double atkMs = clampd(p_[b * kPerBand + Attack].load(std::memory_order_relaxed), 0.1, 300.0);
- const double relMs = clampd(p_[b * kPerBand + Release].load(std::memory_order_relaxed), 5.0, 2000.0);
+ thr[b] = clampd(bp(b, Thresh), -60.0, 6.0);
+ range[b] = clampd(bp(b, Range), -18.0, 18.0);
+ const double atkMs = clampd(bp(b, Attack), 0.1, 300.0);
+ const double relMs = clampd(bp(b, Release), 5.0, 2000.0);
atkC[b] = 1.0 - std::exp(-1.0 / (atkMs * 0.001 * sr));
relC[b] = 1.0 - std::exp(-1.0 / (relMs * 0.001 * sr));
- if (dyn[b]) det[b] = bandpass(sr, f0[b], std::max(q[b], 0.5));
- if (!dyn[b]) dynDb_[b] = 0.0; // parked bands read flat
+ ext[b] = sc && (allExt || get(KeyBase + b) >= 0.5f);
+ det[b] = bandpass(sr, f0[b], std::max(q[b], 0.5));
}
// Solo: audition a single band (mute the rest, force the soloed one on).
- const int solo = std::clamp(static_cast<int>(std::lround(p_[Solo].load(std::memory_order_relaxed))), 0, kBands) - 1;
- if (solo >= 0) {
- for (int b = 0; b < kBands; ++b) { on[b] = (b == solo); if (!on[b]) dyn[b] = false; }
- on[solo] = true;
- dyn[solo] = hasGain[solo] && mode[solo] != DynOff;
+ const int solo = std::clamp(static_cast<int>(std::lround(get(Solo))), 0, kBands) - 1;
+ if (solo >= 0)
+ for (int b = 0; b < kBands; ++b) on[b] = (b == solo);
+ for (int b = 0; b < kBands; ++b) {
+ dyn[b] = dynMaster && on[b] && hasGain[b] && mode[b] != DynOff;
+ if (!dyn[b]) dynDb_[b] = 0.0; // parked bands read flat
}
- const double detC = 1.0 - std::exp(-1.0 / (0.005 * sr)); // ~5 ms detector envelope
+ const double detC = 1.0 - std::exp(-1.0 / (0.005 * sr)); // ~5 ms detector envelope
// Apply coefficients — recomputed at control rate (dynamic gain moves them).
Coeffs cf[kBands];
for (int b = 0; b < kBands; ++b)
- if (on[b]) cf[b] = coeffs(typeOf(b), sr, f0[b], gStat[b] + dynDb_[b], q[b]);
+ if (on[b]) cf[b] = coeffs(type[b], sr, f0[b], gStat[b] + dynDb_[b], q[b]);
+
+ double lvlMax[kBands];
+ for (int b = 0; b < kBands; ++b) lvlMax[b] = -120.0;
+ float inPk = 0.0f, outPk = 0.0f;
+ uint32_t w = ringW_.load(std::memory_order_relaxed);
+ const bool ringOk = !ring_.empty();
int ctrl = 0;
for (int32_t i = 0; i < frames; ++i) {
+ const float l = buf[i * 2], r = buf[i * 2 + 1];
+ inPk = std::max(inPk, std::max(std::fabs(l), std::fabs(r)));
+
// --- detection + per-band dynamic gain ---
- const float detMono = scOn ? sc_[std::min(i, scLen_ - 1)]
- : 0.5f * (buf[i * 2] + buf[i * 2 + 1]);
+ const double self = 0.5 * (l + r);
+ const double key = sc ? 0.5 * (sc[i * 2] + sc[i * 2 + 1]) * scGain : 0.0;
for (int b = 0; b < kBands; ++b) {
- if (!dyn[b]) continue;
- const double d = detState_[b].run(det[b], detMono);
+ if (!on[b]) continue;
+ const double d = detState_[b].run(det[b], ext[b] ? key : self);
detEnv_[b] += (std::fabs(d) - detEnv_[b]) * detC;
const double lvl = 20.0 * std::log10(detEnv_[b] + 1e-9);
+ if (lvl > lvlMax[b]) lvlMax[b] = lvl;
+ if (!dyn[b]) continue;
const double over = (mode[b] == DynAbove) ? (lvl - thr[b]) : (thr[b] - lvl);
const double engage = clampd(over / kKneeDb, 0.0, 1.0);
const double target = range[b] * engage;
@@ -135,7 +216,7 @@ public:
if (--ctrl <= 0) {
ctrl = kCtrl;
for (int b = 0; b < kBands; ++b)
- if (dyn[b]) cf[b] = coeffs(typeOf(b), sr, f0[b], gStat[b] + dynDb_[b], q[b]);
+ if (dyn[b]) cf[b] = coeffs(type[b], sr, f0[b], gStat[b] + dynDb_[b], q[b]);
}
// --- apply cascade, both channels ---
@@ -145,11 +226,33 @@ public:
if (on[b]) x = s_[ch][b].run(cf[b], x);
buf[i * 2 + ch] = static_cast<float>(x * outGain);
}
+ const float ol = buf[i * 2], orr = buf[i * 2 + 1];
+ outPk = std::max(outPk, std::max(std::fabs(ol), std::fabs(orr)));
+ if (ringOk) ring_[(w++) & ringMask_] = 0.5f * (ol + orr);
}
+ ringW_.store(w, std::memory_order_release);
+ scBuf_ = nullptr; scFrames_ = 0;
+ keyLive_.store(sc ? 1.0f : 0.0f, std::memory_order_relaxed);
- // Publish the momentary dynamic gain for the UI (signed dB, per band).
- for (int b = 0; b < kBands; ++b)
+ // Publish: the momentary dynamic gain (signed dB) and a peak-held detector level that
+ // falls 40 dB/s, so the threshold marker reads steadily at the UI's 60 Hz.
+ const double blockS = frames > 0 ? frames / sr : 0.0;
+ for (int b = 0; b < kBands; ++b) {
gr_[b].store(static_cast<float>(dynDb_[b]), std::memory_order_relaxed);
+ if (!on[b]) { lvlDisp_[b] = -120.0; detEnv_[b] = 0.0; }
+ else lvlDisp_[b] = std::max(std::max(lvlMax[b], -120.0), lvlDisp_[b] - 40.0 * blockS);
+ lvlA_[b].store(static_cast<float>(lvlDisp_[b]), std::memory_order_relaxed);
+ }
+ const float fall = (float)std::exp(-blockS / 0.3);
+ inPk_ = std::max(inPk, inPk_ * fall);
+ outPk_ = std::max(outPk, outPk_ * fall);
+ inPkA_.store(db(inPk_), std::memory_order_relaxed);
+ outPkA_.store(db(outPk_), std::memory_order_relaxed);
+ if (frames > 0) {
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / blockS) * 0.1;
+ cpuA_.store((float)cpuS_, std::memory_order_relaxed);
+ }
}
const char* displayName() const override { return "Nota Dynamic EQ-8"; }
@@ -160,8 +263,10 @@ public:
if (i == Output) return "Output";
if (i == Sidechain) return "Sidechain";
if (i == Solo) return "Solo";
- if (i < 0 || i >= kBandParams) return "";
+ if (i == Dynamics) return "Dynamics";
static thread_local char buf[16];
+ if (i >= KeyBase && i < kNumParams) { std::snprintf(buf, sizeof(buf), "%d Key", i - KeyBase + 1); return buf; }
+ if (i < 0 || i >= kBandParams) return "";
const int b = i / kPerBand, f = i % kPerBand;
const char* fld = f == On ? "On" : f == Type ? "Type" : f == Freq ? "Freq" : f == Gain ? "Gain"
: f == Q ? "Q" : f == Mode ? "Mode" : f == Thresh ? "Thr" : f == Range ? "Rng"
@@ -171,23 +276,22 @@ public:
}
float paramMin(int32_t i) const override {
if (i == Output) return -18.0f;
- if (i == Sidechain || i == Solo) return 0.0f;
+ if (i < 0 || i >= kBandParams) return 0.0f; // Sidechain, Solo, Dynamics, Key
switch (i % kPerBand) {
- case On: case Mode: return 0.0f;
- case Type: return 0.0f;
case Freq: return 20.0f;
case Gain: return -18.0f;
case Q: return 0.1f;
case Thresh: return -60.0f;
case Range: return -18.0f;
case Attack: return 0.1f;
- default: return 5.0f; // Release
+ case Release: return 5.0f;
+ default: return 0.0f; // On, Type, Mode
}
}
float paramMax(int32_t i) const override {
if (i == Output) return 18.0f;
- if (i == Sidechain) return 1.0f;
if (i == Solo) return kBands;
+ if (i < 0 || i >= kBandParams) return 1.0f; // Sidechain, Dynamics, Key
switch (i % kPerBand) {
case On: return 1.0f;
case Type: return kNumTypes - 1;
@@ -198,21 +302,41 @@ public:
case Thresh: return 6.0f;
case Range: return 18.0f;
case Attack: return 300.0f;
- default: return 2000.0f; // Release
+ default: return 2000.0f; // Release
}
}
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);
+ if (i >= 0 && i < kNumParams && std::isfinite(v)) p_[i].store(std::clamp(v, paramMin(i), paramMax(i)), std::memory_order_relaxed);
}
- // Telemetry: eight momentary dynamic-gain values (dB, signed), band 0..7.
+ // Telemetry block, then the output spectrum. Writes as much of that layout as fits in
+ // maxSamples (an 8-float read gets the eight gains, as before). UI / MCP thread.
int32_t scopeRead(float* out, int32_t maxSamples) const override {
if (!out || maxSamples <= 0) return 0;
- const int32_t n = std::min(maxSamples, kBands);
- for (int32_t b = 0; b < n; ++b) out[b] = gr_[b].load(std::memory_order_relaxed);
+ float t[kTele] = {};
+ for (int b = 0; b < kBands; ++b) {
+ t[S_Gain + b] = gr_[b].load(std::memory_order_relaxed);
+ t[S_Level + b] = lvlA_[b].load(std::memory_order_relaxed);
+ }
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_InPeak] = inPkA_.load(std::memory_order_relaxed);
+ t[S_OutPeak] = outPkA_.load(std::memory_order_relaxed);
+ t[S_KeyLive] = keyLive_.load(std::memory_order_relaxed);
+ t[S_Bands] = (float)kSpec;
+ t[S_Latency] = 0.0f;
+ int32_t n = 0;
+ if (maxSamples > kTele) {
+ std::lock_guard<std::mutex> lock(mx_);
+ t[S_Analysed] = analyse() ? 1.0f : 0.0f;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ for (int b = 0; b < kSpec && n < maxSamples; ++b) out[n++] = spec_[b];
+ return n;
+ }
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
return n;
}
@@ -223,11 +347,71 @@ public:
return g;
}
+ // 0 — a one-line status; 1 — the live reading; 2 — a guide to the parameter values.
+ std::string deviceText(int32_t id) const override {
+ static const char* types[kNumTypes] = { "Low cut", "Low shelf", "Bell", "Notch", "High shelf", "High cut" };
+ static const char* modes[3] = { "static", "duck", "lift" };
+ char b[320];
+ if (id == 0) {
+ int nOn = 0, nDyn = 0;
+ for (int k = 0; k < kBands; ++k) { if (bandOn(k)) ++nOn; if (bandDyn(k)) ++nDyn; }
+ std::snprintf(b, sizeof b, "%d bands on, %d dynamic - dynamics %s", nOn, nDyn, get(Dynamics) >= 0.5f ? "on" : "off (all static)");
+ std::string s = b;
+ for (int k = 0; k < kBands; ++k) {
+ if (!bandOn(k)) continue;
+ const int ty = typeOf(k);
+ const bool g = ty == LowShelf || ty == Bell || ty == HighShelf;
+ std::snprintf(b, sizeof b, " | B%d %s %.0f Hz", k + 1, types[ty], bp(k, Freq)); s += b;
+ if (g) { std::snprintf(b, sizeof b, " %+.1f dB", bp(k, Gain)); s += b; }
+ std::snprintf(b, sizeof b, " Q %.2f", bp(k, Q)); s += b;
+ if (g && modeOf(k) != DynOff) {
+ std::snprintf(b, sizeof b, " %s thr %.0f dB range %+.1f dB atk %.1f ms rel %.0f ms key %s",
+ modes[modeOf(k)], bp(k, Thresh), bp(k, Range), bp(k, Attack), bp(k, Release), keyExt(k) ? "ext" : "self");
+ s += b;
+ }
+ }
+ const int solo = std::clamp((int)std::lround(get(Solo)), 0, kBands);
+ if (solo > 0) { std::snprintf(b, sizeof b, " | solo B%d", solo); s += b; }
+ std::snprintf(b, sizeof b, " | output %+.1f dB", get(Output)); s += b;
+ if (scTrackId_.load(std::memory_order_relaxed) >= 0) s += " - sidechain routed";
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ auto lv = [](float v) { char t[24]; if (v <= -119.0f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", v); return std::string(t); };
+ std::snprintf(b, sizeof b, "in %s dBFS - out %s dBFS - key %s", lv(sc[S_InPeak]).c_str(), lv(sc[S_OutPeak]).c_str(),
+ sc[S_KeyLive] > 0.5f ? "live" : "none");
+ std::string s = b;
+ for (int k = 0; k < kBands; ++k) {
+ if (!bandOn(k)) continue;
+ std::snprintf(b, sizeof b, " | B%d level %s dBFS", k + 1, lv(sc[S_Level + k]).c_str()); s += b;
+ if (bandDyn(k)) {
+ std::snprintf(b, sizeof b, " (thr %.0f) gain now %+.1f of %+.1f dB", bp(k, Thresh), sc[S_Gain + k], bp(k, Range));
+ s += b;
+ }
+ }
+ std::snprintf(b, sizeof b, " | CPU %.2f %%", sc[S_Cpu] * 100.0f); s += b;
+ return s;
+ }
+ if (id == 2) {
+ return "Raw units. Band n (1..8) params are named \"n <field>\" at index (n-1)*10 + field: On (0/1), Type "
+ "(0 Low cut, 1 Low shelf, 2 Bell, 3 Notch, 4 High shelf, 5 High cut), Freq 20..20000 Hz, Gain -18..+18 dB "
+ "(shelves and bells only), Q 0.1..18 (the resonance on the cuts), Mode (0 Static, 1 Duck - engages as the "
+ "band's level rises above Thr, 2 Lift - engages as it falls below Thr), Thr -60..+6 dBFS, Rng -18..+18 dB "
+ "(the extra gain at full engagement, 6 dB past the threshold: negative cuts, positive boosts; Duck normally "
+ "cuts, Lift boosts), Atk 0.1..300 ms, Rel 5..2000 ms. Only shelves and bells are dynamic. 80 Output -18..+18 "
+ "dB. 81 Sidechain 0/1 keys every band from the sidechain source (legacy). 82 Solo 0 = none, n = hear band n "
+ "alone. 83 Dynamics 0/1 master switch (0 = every band static). 84..91 \"n Key\" 0 = the band hears this "
+ "track, 1 = the sidechain source track (set with set_device_sidechain).";
+ }
+ return {};
+ }
+
private:
static constexpr double kPi = 3.14159265358979323846;
static constexpr int kCtrl = 16; // control-rate coeff refresh (samples)
static constexpr double kKneeDb = 6.0; // detection range from threshold to full engagement
- static constexpr int kMaxSc = 8192;
struct Coeffs { double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0; };
struct State {
@@ -240,14 +424,18 @@ private:
}
};
- int typeOf(int b) const {
- return std::clamp(static_cast<int>(std::lround(p_[b * kPerBand + Type].load(std::memory_order_relaxed))), 0, kNumTypes - 1);
- }
- int modeOf(int b) const {
- return std::clamp(static_cast<int>(std::lround(p_[b * kPerBand + Mode].load(std::memory_order_relaxed))), 0, 2);
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ float bp(int b, int f) const { return p_[b * kPerBand + f].load(std::memory_order_relaxed); }
+ int typeOf(int b) const { return std::clamp(static_cast<int>(std::lround(bp(b, Type))), 0, kNumTypes - 1); }
+ int modeOf(int b) const { return std::clamp(static_cast<int>(std::lround(bp(b, Mode))), 0, 2); }
+ bool bandOn(int b) const { return bp(b, On) > 0.5f; }
+ bool keyExt(int b) const { return get(Sidechain) >= 0.5f || get(KeyBase + b) >= 0.5f; }
+ bool bandDyn(int b) const {
+ const int ty = typeOf(b);
+ return get(Dynamics) >= 0.5f && bandOn(b) && (ty == LowShelf || ty == Bell || ty == HighShelf) && modeOf(b) != DynOff;
}
void band(int b, float on, int type, float freq, float gain, float q,
- int mode = DynOff, float thr = -24.0f, float range = 0.0f, float atk = 10.0f, float rel = 120.0f) {
+ int mode = DynOff, float thr = -24.0f, float range = -6.0f, float atk = 10.0f, float rel = 120.0f) {
p_[b * kPerBand + On].store(on);
p_[b * kPerBand + Type].store(static_cast<float>(type));
p_[b * kPerBand + Freq].store(freq);
@@ -261,6 +449,7 @@ private:
}
static double clampd(double v, double lo, double hi) { return v < lo ? lo : (v > hi ? hi : v); }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
static Coeffs normC(double b0, double b1, double b2, double a0, double a1, double a2) {
return {b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0};
}
@@ -316,15 +505,75 @@ private:
(A + 1) - (A - 1) * cw + tsa, 2 * ((A - 1) - (A + 1) * cw), (A + 1) - (A - 1) * cw - tsa);
}
+ // ---- output spectrum (reading thread, rate-limited, under mx_) -----------------------
+ static double nowSeconds() {
+ return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
+ }
+ bool analyse() const {
+ if (ring_.empty() || fftN_ <= 0) return false;
+ const double now = nowSeconds();
+ const uint32_t w = ringW_.load(std::memory_order_acquire);
+ if (lastAnaS_ >= 0 && (now - lastAnaS_ < 1.0 / 30.0 || w == lastAnaW_)) return anaValid_;
+ if (w < (uint32_t)fftN_) return anaValid_;
+ const int n = fftN_;
+ const uint32_t start = w - (uint32_t)n;
+ for (int i = 0; i < n; ++i) tBuf_[(size_t)i] = ring_[(start + (uint32_t)i) & ringMask_] * win_[(size_t)i];
+ fft_.fft(tBuf_.data(), fBuf_.data());
+ const int half = n / 2;
+ const double binHz = sr_ / n;
+ const double ref = 0.25 * (double)n * n * 0.25; // Hann: a full-scale sine's bin power
+ const bool stale = lastAnaS_ < 0 || now - lastAnaS_ > 1.2;
+ const double a = stale ? 1.0 : 1.0 - std::exp(-(now - lastAnaS_) / 0.2);
+ double tot = 0.0;
+ for (int b = 0; b < kSpec; ++b) {
+ const double lo = kSpecLo * std::pow(kSpecHi / kSpecLo, (double)b / kSpec);
+ const double hi = kSpecLo * std::pow(kSpecHi / kSpecLo, (double)(b + 1) / kSpec);
+ int k0 = std::max(1, (int)std::ceil(lo / binHz)), k1 = std::min(half - 1, (int)std::ceil(hi / binHz) - 1);
+ if (k1 < k0) k0 = k1 = std::clamp((int)std::lround(std::sqrt(lo * hi) / binHz), 1, half - 1);
+ double s = 0.0;
+ for (int k = k0; k <= k1; ++k) s += std::norm(fBuf_[(size_t)k]);
+ tot += s;
+ aSpec_[b] += a * (s - aSpec_[b]);
+ spec_[b] = aSpec_[b] > ref * 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(aSpec_[b] / ref)) : -120.0f;
+ }
+ lastAnaS_ = now; lastAnaW_ = w;
+ anaValid_ = tot > ref * 1e-10;
+ return anaValid_;
+ }
+
double sr_ = 44100.0;
std::atomic<float> p_[kNumParams] = {};
State s_[2][kBands] = {}; // [channel][band] apply biquad state
State detState_[kBands] = {}; // detector bandpass state (mono)
double detEnv_[kBands] = {}; // detector envelope (linear)
double dynDb_[kBands] = {}; // smoothed dynamic gain per band (dB)
- std::atomic<float> gr_[kBands] = {}; // published momentary gain (dB)
- float sc_[kMaxSc] = {}; // sidechain mono
- int32_t scLen_ = 0;
+ double lvlDisp_[kBands] = {}; // peak-held detector level (dB)
+ std::atomic<float> gr_[kBands]; // published momentary gain (dB)
+ std::atomic<float> lvlA_[kBands]; // published detector level (dBFS)
+ float inPk_ = 0.0f, outPk_ = 0.0f;
+ double cpuS_ = 0.0;
+ std::atomic<float> inPkA_{-120.0f}, outPkA_{-120.0f}, cpuA_{0.0f}, srA_{44100.0f}, keyLive_{0.0f};
+
+ // Sidechain (the device's key source; the engine hands the buffer right before process).
+ std::atomic<int32_t> scTrackId_{-1};
+ const float* scBuf_ = nullptr;
+ int32_t scFrames_ = 0;
+
+ // Spectrum: a ring written by the audio thread, the analysis state under mx_.
+ std::vector<float> ring_;
+ uint32_t ringMask_ = 0;
+ std::atomic<uint32_t> ringW_{0};
+ int fftN_ = 0;
+ mutable std::mutex mx_;
+ mutable signalsmith::linear::RealFFT<float> fft_;
+ std::vector<float> win_;
+ mutable std::vector<float> tBuf_;
+ mutable std::vector<std::complex<float>> fBuf_;
+ mutable double aSpec_[kSpec] = {};
+ mutable float spec_[kSpec] = {};
+ mutable double lastAnaS_ = -1.0;
+ mutable uint32_t lastAnaW_ = 0;
+ mutable bool anaValid_ = false;
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 7329da6c..437ea3cf 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -3683,7 +3683,12 @@ Console.WriteLine("-- Nota Crush --");
Check(ce.DeviceName(ct, cd) == "Nota Crush", $"device name is Nota Crush (got '{ce.DeviceName(ct, cd)}')");
Check(ce.TrackDeviceBuiltinKind(ct, cd) == 12, $"builtin kind is 12 (got {ce.TrackDeviceBuiltinKind(ct, cd)})");
int pc = ce.DeviceParamCount(ct, cd);
- Check(pc == 11, $"Nota Crush exposes 11 params (got {pc})");
+ Check(pc == 13, $"Nota Crush exposes 13 params (got {pc})");
+ string[] crNames = { "Bits", "Rate", "Mode", "Dither", "Jitter", "Noise Floor", "Post Filter", "Dry/Wet", "Anti-Alias", "Output", "Drive", "Auto Gain", "DC Filter" };
+ bool crNamesOk = pc == crNames.Length;
+ for (int p = 0; p < Math.Min(pc, crNames.Length); p++) crNamesOk &= ce.DeviceParamName(ct, cd, p) == crNames[p];
+ Check(crNamesOk, "the original eleven params keep their order; Auto Gain and DC Filter are appended");
+ Check(ce.DeviceParamDefault(ct, cd, 11) == 0f && ce.DeviceParamDefault(ct, cd, 12) == 0f, "appended params default off (the old sound)");
// Param round-trip.
ce.DeviceSetParam(ct, cd, 0, 0.42f); // Bits
@@ -3696,30 +3701,37 @@ Console.WriteLine("-- Nota Crush --");
// Heavy crush → still finite, different from bypass.
ce.DeviceSetParam(ct, cd, 0, 0.1f); // ~3 bit
- ce.DeviceSetParam(ct, cd, 1, 0.05f); // ~1 kHz
+ ce.DeviceSetParam(ct, cd, 1, 0.05f); // ~600 Hz
ce.DeviceSetParam(ct, cd, 7, 1.0f); // full wet
var crushed = new float[8192 * 2];
ce.Seek(0); ce.Play(); ce.RenderOffline(crushed, 8192); ce.StopTransport();
bool fin = true; foreach (var s in crushed) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { fin = false; break; }
Check(fin && Rms(crushed, 8192) > 0.001f, $"heavy crush stays finite + audible (rms {Rms(crushed, 8192):F3})");
- // Each mode renders finite.
+ // Each mode renders finite, with and without anti-alias / auto gain / DC filter.
for (int m = 0; m < 3; m++)
- {
- ce.DeviceSetParam(ct, cd, 2, m / 2f); // Mode
- var mb = new float[8192 * 2];
- ce.Seek(0); ce.Play(); ce.RenderOffline(mb, 8192); ce.StopTransport();
- bool mfin = true; foreach (var s in mb) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { mfin = false; break; }
- Check(mfin && Rms(mb, 8192) > 0.001f, $"Crush mode {m} renders finite + audible (rms {Rms(mb, 8192):F3})");
- }
+ for (int x = 0; x < 2; x++)
+ {
+ ce.DeviceSetParam(ct, cd, 2, m / 2f); // Mode
+ ce.DeviceSetParam(ct, cd, 0, x == 1 ? 0.3f : 0.1f); // 8 bit under the anti-alias, else a quiet note rounds to zero
+ ce.DeviceSetParam(ct, cd, 8, x); ce.DeviceSetParam(ct, cd, 11, x); ce.DeviceSetParam(ct, cd, 12, x);
+ var mb = new float[8192 * 2];
+ ce.Seek(0); ce.Play(); ce.RenderOffline(mb, 8192); ce.StopTransport();
+ bool mfin = true; foreach (var s in mb) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { mfin = false; break; }
+ Check(mfin && Rms(mb, 8192) > 0.001f, $"Crush mode {m}{(x == 1 ? " + AA / auto gain / DC" : "")} renders finite + audible (rms {Rms(mb, 8192):F3})");
+ }
+ for (int p = 8; p <= 12; p++) if (p is 8 or 11 or 12) ce.DeviceSetParam(ct, cd, p, 0f);
+ ce.DeviceSetParam(ct, cd, 2, 0f);
- // Clone: duplicate track preserves params.
+ // Clone: duplicate track preserves params (the appended ones too).
ce.DeviceSetParam(ct, cd, 0, 0.55f);
+ ce.DeviceSetParam(ct, cd, 12, 1f);
int t2 = ce.DuplicateTrack(ct);
int cd2 = ce.TrackDeviceCount(t2) - 1;
- Check(t2 > 0 && Math.Abs(ce.DeviceGetParam(t2, cd2, 0) - 0.55f) < 1e-4, "duplicate track clones Crush params");
+ Check(t2 > 0 && Math.Abs(ce.DeviceGetParam(t2, cd2, 0) - 0.55f) < 1e-4 && ce.DeviceGetParam(t2, cd2, 12) > 0.5f, "duplicate track clones Crush params");
+ ce.DeviceSetParam(ct, cd, 12, 0f);
- // Automation: a device-param lane drives Bits.
+ // Automation: a device-param lane drives Bits, another an appended param (Auto Gain).
int lane = ce.AddAutomationLane(ct, AutomationTarget.DeviceParam, cd, 0);
Check(lane >= 0, "add Crush Bits automation lane");
ce.SetAutomationPoints(ct, lane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
@@ -3727,6 +3739,153 @@ Console.WriteLine("-- Nota Crush --");
ce.Seek(1.99); ce.Play(); ce.RenderOffline(ab, 4096); ce.StopTransport();
float after = ce.DeviceGetParam(ct, cd, 0);
Check(after > 0.7f, $"automation drives Crush Bits (Bits = {after:F2})");
+ int lane2 = ce.AddAutomationLane(ct, AutomationTarget.DeviceParam, cd, 11);
+ ce.SetAutomationPoints(ct, lane2, new[] { new AutomationPoint(0.0, 1f), new AutomationPoint(4.0, 1f) });
+ ce.Seek(1.0); ce.Play(); ce.RenderOffline(ab, 1024); ce.StopTransport();
+ Check(ce.DeviceGetParam(ct, cd, 11) > 0.5f, "automation drives an appended param (Auto Gain)");
+}
+{
+ // The 440 Hz smoke sine through Crush on an audio track: meters, spectrum, auto gain, DC.
+ using var ce = new NotaEngine();
+ ce.SetBpm(120);
+ int ct = ce.AddAudioTrack();
+ ce.AddAudioClip(ct, wav, 0.0);
+ int cd = ce.AddBuiltinDevice(ct, 12);
+ const int CrTele = 32, CrBands = 40, CrScope = CrTele + 2 * CrBands;
+ var sc = new float[CrScope];
+ float[] Render(int frames) { var b = new float[frames * 2]; ce.Seek(0); ce.Play(); ce.RenderOffline(b, frames); ce.StopTransport(); return b; }
+ void Clean()
+ {
+ ce.DeviceSetParam(ct, cd, 0, 1f); // 24 bit
+ ce.DeviceSetParam(ct, cd, 1, 1f); // full rate
+ ce.DeviceSetParam(ct, cd, 2, 0f); // Digital
+ ce.DeviceSetParam(ct, cd, 3, 0f); // no dither
+ ce.DeviceSetParam(ct, cd, 6, 1f); // filter 20 kHz
+ ce.DeviceSetParam(ct, cd, 10, 1f / 3f); // drive 0 dB
+ }
+ float[] Analyse()
+ {
+ ce.DeviceAction(ct, cd, 0, 0, 0); // fresh meters and spectrum average
+ Render(22050); Render(22050); // let the 300 ms RMS settle
+ int n = ce.DeviceScope(ct, cd, sc, CrScope);
+ Check(n == CrScope, $"Crush scope returns the telemetry and the spectrum ({n} of {CrScope})");
+ return sc;
+ }
+
+ Clean();
+ Analyse();
+ Check(sc[5] > 1000 && sc[0] > -12 && sc[0] < 0 && sc[1] > -12 && sc[2] < sc[0] && sc[3] > -30,
+ $"meters: sample rate {sc[5]}, in {sc[0]:F1} / out {sc[1]:F1} dBFS, RMS {sc[2]:F1} / {sc[3]:F1}");
+ Check(Math.Abs(sc[8] - 24f) < 0.01f && sc[7] > 2f && sc[7] < 2.2f && sc[22] > 0.5f, $"clean settings: 24 bit, hold {sc[7]:F2} at the top rate (0.48·sr), spectrum analysed");
+ float thdClean = sc[11];
+ Check(thdClean < 0.05f, $"a clean crush adds little (THD+N {thdClean * 100:F2} %)");
+ Check(Math.Abs(sc[4] - 3f) < 1.2f, $"crest of a sine reads ~3 dB ({sc[4]:F1})");
+ int peakBand = 0;
+ for (int b = 1; b < CrBands; b++) if (sc[CrTele + CrBands + b] > sc[CrTele + CrBands + peakBand]) peakBand = b;
+ double peakHz = 20 * Math.Pow(1000, (peakBand + 0.5) / CrBands);
+ Check(peakHz > 300 && peakHz < 650, $"the output spectrum peaks at the sine (band {peakBand}, ~{peakHz:0} Hz)");
+
+ // 4 bit at ~1 kHz: lots added, images above the reduced Nyquist; anti-alias cuts them.
+ ce.DeviceSetParam(ct, cd, 0, 0.13f);
+ ce.DeviceSetParam(ct, cd, 1, 0.185f);
+ Analyse();
+ float thdCrushed = sc[11], imgOff = sc[12];
+ Check(thdCrushed > 0.1f && thdCrushed > thdClean * 5 && imgOff > -40f && sc[7] > 30 && Math.Abs(sc[20] - sc[6] / 2) < 1,
+ $"4 bit @ {sc[6]:0} Hz adds content (THD+N {thdCrushed * 100:F0} %, images {imgOff:F1} dB, hold {sc[7]}, Nyquist {sc[20]:0})");
+ Check(sc[10] < -24 && sc[10] > -27, $"quantisation noise follows the bits ({sc[10]:F1} dB at 4 bit)");
+
+ // Fold with +12 dB of drive folds the 0.5-peak sine over.
+ ce.DeviceSetParam(ct, cd, 0, 1f); ce.DeviceSetParam(ct, cd, 1, 1f);
+ ce.DeviceSetParam(ct, cd, 2, 1f);
+ ce.DeviceSetParam(ct, cd, 10, 24f / 36f); // +12 dB
+ Analyse();
+ Check(sc[17] >= 2 && sc[16] > 1f, $"Fold reports its folds (driven peak ×{sc[16]:F2}, {sc[17]} folds)");
+
+ // Auto gain: −6 dB of drive in Digital (no clipping downstream), the output comes back to
+ // the clean level and the correction reads +6 dB.
+ Clean();
+ ce.DeviceSetParam(ct, cd, 11, 0f);
+ Render(8192); var reference = Render(22050);
+ ce.DeviceSetParam(ct, cd, 10, 6f / 36f);
+ Render(8192); var quiet = Render(22050);
+ ce.DeviceSetParam(ct, cd, 11, 1f);
+ Render(22050); var matched = Render(22050);
+ ce.DeviceScope(ct, cd, sc, CrTele);
+ float rRef = Rms(reference, 22050), rQuiet = Rms(quiet, 22050), rMatch = Rms(matched, 22050);
+ Check(rQuiet < rRef * 0.6f && Math.Abs(20 * Math.Log10(rMatch / rRef)) < 1.0 && Math.Abs(sc[13] - 6f) < 1f,
+ $"auto gain brings −6 dB of drive back (rms {rRef:F3} → {rQuiet:F3} → {rMatch:F3}; correction {sc[13]:+0.0} dB)");
+ ce.DeviceSetParam(ct, cd, 11, 0f);
+ Clean();
+
+ // Reset meters (action 0) clears the holds.
+ ce.DeviceScope(ct, cd, sc, CrTele);
+ float holdBefore = sc[24];
+ {
+ var z = new float[4096 * 2];
+ ce.Seek(3.0); ce.Play(); ce.RenderOffline(z, 4096); // past the clip: silence, the tails die out
+ ce.DeviceAction(ct, cd, 0, 0, 0);
+ ce.RenderOffline(z, 64); ce.StopTransport();
+ }
+ ce.DeviceScope(ct, cd, sc, CrTele);
+ Check(holdBefore > -20 && sc[24] < -100 && sc[25] < -100, $"device_action 0 resets the peak holds (out {holdBefore:F0} → {sc[24]:F0}, in {sc[25]:F0})");
+
+ // DC filter: a sine riding on +0.3 of DC keeps it through the crush, loses it with the filter.
+ string dcwav = Path.Combine(Path.GetTempPath(), "nota_smoke_crush_dc.wav");
+ Nota.SmokeTest.WavWriter.WriteStereo(dcwav, 2.0, 44100, i => { double v = 0.3 + 0.2 * Math.Sin(2 * Math.PI * 220 * i / 44100.0); return (v, v); });
+ int dt = ce.AddAudioTrack();
+ ce.AddAudioClip(dt, dcwav, 0.0);
+ int dd = ce.AddBuiltinDevice(dt, 12);
+ ce.SetTrackMute(ct, true);
+ ce.DeviceSetParam(dt, dd, 0, 1f); ce.DeviceSetParam(dt, dd, 1, 1f); ce.DeviceSetParam(dt, dd, 3, 0f); ce.DeviceSetParam(dt, dd, 6, 1f);
+ static double Mean(float[] b, int from, int to) { double s = 0; for (int i = from * 2; i < to * 2; i++) s += b[i]; return s / ((to - from) * 2); }
+ var dOff = Render(44100);
+ ce.DeviceSetParam(dt, dd, 12, 1f);
+ var dOn = Render(44100);
+ double mOff = Mean(dOff, 22050, 44100), mOn = Mean(dOn, 22050, 44100);
+ Check(mOff > 0.2 && Math.Abs(mOn) < 0.02, $"DC filter takes the offset out (mean {mOff:F3} → {mOn:F4})");
+ ce.SetTrackMute(ct, false);
+ ce.SetTrackMute(dt, true);
+
+ // Texts.
+ ce.DeviceSetParam(ct, cd, 2, 0.5f);
+ ce.DeviceSetParam(ct, cd, 8, 1f);
+ Render(8192);
+ string t0 = ce.DeviceText(ct, cd, 0), t1 = ce.DeviceText(ct, cd, 1), tg = ce.DeviceText(ct, cd, 2);
+ Check(t0.StartsWith("Analog") && t0.Contains("bit") && t0.Contains("anti-alias") && t1.Contains("THD+N") && t1.Contains("Nyquist") && tg.Contains("Auto Gain"),
+ $"device texts: status '{t0[..Math.Min(60, t0.Length)]}…', live, guide");
+
+ // MCP reading.
+ ce.DeviceSetParam(ct, cd, 0, 0.3f);
+ ce.DeviceSetParam(ct, cd, 1, 0.4f);
+ ce.DeviceAction(ct, cd, 0, 0, 0);
+ Render(8192);
+ var crtools = new Nota.Mcp.Tools.DeviceTools(ce, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ var cr = crtools.ReadCrush(ct, cd).Result;
+ Check(cr.Mode == "Analog" && Math.Abs(cr.Bits - 7.9) < 0.1 && cr.AntiAlias && !cr.AutoGain && cr.Spectrum.Length == 20 && cr.Signal
+ && cr.SpectrumValid && cr.InputPeakDb > -12 && cr.RateHz > 1000 && cr.NyquistHz > 500 && cr.SampleRate > 1000
+ && cr.Summary.Length > 0 && cr.Live.Length > 0 && cr.Spectrum.Any(b => b.OutputDb > -40),
+ $"MCP read_crush reports the settings, meters and spectrum ({cr.Bits} bit @ {cr.RateHz} Hz, THD+N {cr.ThdNPercent} %, images {cr.ImagesDb} dB)");
+
+ // Every factory preset names only real params and renders finite.
+ var crcat = new FactoryPresetCatalog();
+ int crPresets = 0; bool crNamesOk = true, crPresetsOk = true;
+ var crNames = new HashSet<string>();
+ for (int p = 0; p < ce.DeviceParamCount(ct, cd); p++) crNames.Add(ce.DeviceParamName(ct, cd, p));
+ foreach (var info in crcat.All())
+ {
+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 12) continue;
+ var doc = crcat.Document(info.Id);
+ if (doc is null) continue;
+ crPresets++;
+ foreach (var k in doc.NamedParams!.Keys) if (!crNames.Contains(k)) { crNamesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }
+ crcat.ApplyInPlace(ce, info.Id, ct, cd);
+ Render(4096);
+ var pb = Render(22050);
+ bool ok = Rms(pb, 22050) > 1e-4f;
+ foreach (var v in pb) if (!float.IsFinite(v) || Math.Abs(v) > 4f) { ok = false; break; }
+ if (!ok) { crPresetsOk = false; Console.WriteLine($" preset {info.DisplayName} not finite / silent / over (rms {Rms(pb, 22050):F4})"); }
+ }
+ Check(crPresets >= 25 && crNamesOk && crPresetsOk, $"{crPresets} Crush factory presets, all params known, all render finite and audible");
}
// ============================ Nota Dynamic EQ-8 =============================
@@ -3742,53 +3901,172 @@ Console.WriteLine("-- Nota Dynamic EQ-8 --");
Check(de.DeviceName(dt, dd) == "Nota Dynamic EQ-8", $"name is Nota Dynamic EQ-8 (got '{de.DeviceName(dt, dd)}')");
Check(de.TrackDeviceBuiltinKind(dt, dd) == 13, $"builtin kind is 13 (got {de.TrackDeviceBuiltinKind(dt, dd)})");
int dpc = de.DeviceParamCount(dt, dd);
- Check(dpc == 83, $"Dynamic EQ-8 exposes 83 params (got {dpc})");
+ Check(dpc == 92, $"Dynamic EQ-8 exposes 92 params (got {dpc})");
+ string[] fields = { "On", "Type", "Freq", "Gain", "Q", "Mode", "Thr", "Rng", "Atk", "Rel" };
+ bool layoutOk = true;
+ for (int b = 0; b < 8; b++) for (int f = 0; f < 10; f++) layoutOk &= de.DeviceParamName(dt, dd, b * 10 + f) == $"{b + 1} {fields[f]}";
+ layoutOk &= de.DeviceParamName(dt, dd, 80) == "Output" && de.DeviceParamName(dt, dd, 81) == "Sidechain" && de.DeviceParamName(dt, dd, 82) == "Solo";
+ Check(layoutOk, "the original 83 params keep their names and order");
+ bool appendedOk = de.DeviceParamName(dt, dd, 83) == "Dynamics" && de.DeviceParamDefault(dt, dd, 83) == 1f;
+ for (int b = 0; b < 8; b++) appendedOk &= de.DeviceParamName(dt, dd, 84 + b) == $"{b + 1} Key" && de.DeviceParamDefault(dt, dd, 84 + b) == 0f;
+ Check(appendedOk, "Dynamics (default on) and the eight band Keys (default Self) are appended");
// Band 4 (index 3) field bases: On=30 Type=31 Freq=32 Gain=33 Q=34 Mode=35 Thr=36 Rng=37.
de.DeviceSetParam(dt, dd, 36, -45f);
Check(Math.Abs(de.DeviceGetParam(dt, dd, 36) + 45f) < 1e-3, "Dynamic EQ param set/get round-trips");
+ de.DeviceSetParam(dt, dd, 36, -500f);
+ Check(Math.Abs(de.DeviceGetParam(dt, dd, 36) + 60f) < 1e-3, "an out-of-range value is clamped to the param's range");
+
+ float[] Render(int frames) { var b = new float[frames * 2]; de.Seek(0); de.Play(); de.RenderOffline(b, frames); de.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; }
// Default (flat static) passes audio.
- var pb = new float[8192 * 2];
- de.Seek(0); de.Play(); de.RenderOffline(pb, 8192); de.StopTransport();
+ var pb = Render(8192);
Check(Rms(pb, 8192) > 0.001f, $"Dynamic EQ passes audio (rms {Rms(pb, 8192):F3})");
- // Make band 4 a downward-dynamic bell that engages on the note; check GR telemetry.
+ // Band 4: a ducking bell on the note engages; check GR, the level and the full telemetry.
de.DeviceSetParam(dt, dd, 32, 500f); // Freq
- de.DeviceSetParam(dt, dd, 35, 1f); // Mode = Above (duck)
+ de.DeviceSetParam(dt, dd, 35, 1f); // Mode = Duck (above)
de.DeviceSetParam(dt, dd, 36, -55f); // Thr low → engages
de.DeviceSetParam(dt, dd, 37, -12f); // Rng
- var eb = new float[8192 * 2];
- de.Seek(0); de.Play(); de.RenderOffline(eb, 8192); de.StopTransport();
+ var eb = Render(8192);
var gr = new float[8];
int gn = de.DeviceScope(dt, dd, gr, 8);
- Check(gn == 8, $"GR telemetry returns 8 bands (got {gn})");
+ Check(gn == 8, $"an 8-slot reader still gets the eight band gains (got {gn})");
Check(gr[3] < -0.05f, $"dynamic band 4 reduces gain (GR {gr[3]:F2} dB)");
- bool defin = true; foreach (var s in eb) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { defin = false; break; }
- Check(defin && Rms(eb, 8192) > 0.001f, "dynamic engaged stays finite + audible");
+ Check(Finite(eb) && Rms(eb, 8192) > 0.001f, "dynamic engaged stays finite + audible");
+ const int DqTele = 32, DqScope = DqTele + 96;
+ var dsc = new float[DqScope];
+ Render(4096);
+ int dsn = de.DeviceScope(dt, dd, dsc, DqScope);
+ Check(dsn == DqScope && dsc[8 + 3] > -55f && dsc[16] > 1000 && dsc[20] > -60f,
+ $"telemetry: band levels, sample rate, output peak ({dsn} slots, band 4 level {dsc[11]:F1} dBFS, out {dsc[20]:F1})");
+ bool specOk = dsc[18] > 0.5f; float specMax = -120;
+ for (int i = 0; i < 96; i++) specMax = Math.Max(specMax, dsc[DqTele + i]);
+ Check(specOk && specMax > -60f, $"the output spectrum is analysed (peak band {specMax:F1} dB)");
+
+ // Dynamics off parks every band on its static gain.
+ de.DeviceSetParam(dt, dd, 83, 0f);
+ Render(8192);
+ de.DeviceScope(dt, dd, gr, 8);
+ Check(Math.Abs(gr[3]) < 1e-4f, $"Dynamics off leaves the bands static (GR {gr[3]:F3})");
+ de.DeviceSetParam(dt, dd, 83, 1f);
+
+ // Lift acts below the threshold: a threshold far above the level lifts by the range.
+ de.DeviceSetParam(dt, dd, 35, 2f); // Mode = Lift (below)
+ de.DeviceSetParam(dt, dd, 36, 0f);
+ de.DeviceSetParam(dt, dd, 37, 6f);
+ Render(8192);
+ de.DeviceScope(dt, dd, gr, 8);
+ Check(gr[3] > 3f, $"Lift boosts while the band is under the threshold (+{gr[3]:F2} dB)");
+ de.DeviceSetParam(dt, dd, 36, -60f);
+ Render(8192); Render(8192);
+ de.DeviceScope(dt, dd, gr, 8);
+ Check(gr[3] < 0.5f, $"… and lets go above it ({gr[3]:F2} dB)");
+ de.DeviceSetParam(dt, dd, 35, 1f); de.DeviceSetParam(dt, dd, 36, -55f); de.DeviceSetParam(dt, dd, 37, -12f);
// Solo band 4 (param 82 = band index+1): renders finite.
de.DeviceSetParam(dt, dd, 82, 4f);
- var sb = new float[8192 * 2];
- de.Seek(0); de.Play(); de.RenderOffline(sb, 8192); de.StopTransport();
- bool sfin = true; foreach (var s in sb) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { sfin = false; break; }
- Check(sfin, "solo band renders finite");
+ Check(Finite(Render(8192)), "solo band renders finite");
de.DeviceSetParam(dt, dd, 82, 0f);
- // Clone: duplicate track preserves params.
+ // Texts.
+ Render(8192);
+ string t0 = de.DeviceText(dt, dd, 0), t1 = de.DeviceText(dt, dd, 1), t2 = de.DeviceText(dt, dd, 2);
+ Check(t0.Contains("B4 Bell 500 Hz") && t0.Contains("duck") && t1.Contains("B4 level") && t1.Contains("gain now") && t2.Contains("Lift"),
+ $"device texts: status '{t0[..Math.Min(50, t0.Length)]}…', live, guide");
+
+ // MCP: read the bands and edit one.
+ var dqtools = new Nota.Mcp.Tools.DeviceTools(de, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ var dr = dqtools.ReadDynamicEq(dt, dd).Result;
+ Check(dr.Bands.Length == 8 && dr.Bands[3].Mode == "Duck" && dr.Bands[3].Dynamic && dr.Bands[3].GainNowDb < -0.05 && dr.Dynamics
+ && dr.SampleRate > 1000 && dr.Spectrum.Length == 24 && dr.Summary.Length > 0 && dr.Live.Length > 0,
+ $"MCP read_dynamic_eq reports the bands, their gain now and the spectrum (B4 {dr.Bands[3].GainNowDb} dB, level {dr.Bands[3].LevelDb})");
+ var db6 = dqtools.SetDynamicEqBand(dt, dd, 6, on: true, type: "high shelf", freqHz: 8000, gainDb: 2, mode: "Lift", thresholdDb: -30, rangeDb: 4, key: "Ext").Result;
+ Check(db6.On && db6.Type == "High shelf" && db6.FreqHz == 8000 && db6.Mode == "Lift" && db6.RangeDb == 4 && db6.Key == "Ext"
+ && Math.Abs(de.DeviceGetParam(dt, dd, 89) - 1f) < 1e-3, "MCP set_dynamic_eq_band edits a band (type, frequency, mode, range, key)");
+ bool threw = false;
+ try { dqtools.SetDynamicEqBand(dt, dd, 6, mode: "Sideways").Wait(); } catch { threw = true; }
+ Check(threw, "set_dynamic_eq_band rejects an unknown mode");
+ dqtools.SetDynamicEqBand(dt, dd, 6, on: false, key: "Self").Wait();
+
+ // Clone: duplicate track preserves params, the appended ones too.
de.DeviceSetParam(dt, dd, 33, 4.5f); // band 4 Gain
+ de.DeviceSetParam(dt, dd, 86, 1f); // band 3 Key
int dt2 = de.DuplicateTrack(dt);
int dd2 = de.TrackDeviceCount(dt2) - 1;
- Check(dt2 > 0 && Math.Abs(de.DeviceGetParam(dt2, dd2, 33) - 4.5f) < 1e-3, "duplicate track clones Dynamic EQ params");
+ Check(dt2 > 0 && Math.Abs(de.DeviceGetParam(dt2, dd2, 33) - 4.5f) < 1e-3 && de.DeviceGetParam(dt2, dd2, 86) > 0.5f,
+ "duplicate track clones Dynamic EQ params (appended Key included)");
+ de.DeviceSetParam(dt, dd, 86, 0f);
- // Automation: a device-param lane drives band 4 gain (raw dB points).
+ // Automation: a device-param lane drives band 4 gain (raw dB points) and the appended Dynamics.
int dlane = de.AddAutomationLane(dt, AutomationTarget.DeviceParam, dd, 33);
Check(dlane >= 0, "add Dynamic EQ gain automation lane");
de.SetAutomationPoints(dt, dlane, new[] { new AutomationPoint(0.0, -6f), new AutomationPoint(2.0, 6f) });
+ int dlane2 = de.AddAutomationLane(dt, AutomationTarget.DeviceParam, dd, 83);
+ de.SetAutomationPoints(dt, dlane2, new[] { new AutomationPoint(0.0, 0f), new AutomationPoint(4.0, 0f) });
var dab = new float[4096 * 2];
de.Seek(1.99); de.Play(); de.RenderOffline(dab, 4096); de.StopTransport();
float dafter = de.DeviceGetParam(dt, dd, 33);
Check(dafter > 3f, $"automation drives band gain ({dafter:F2} dB)");
+ Check(de.DeviceGetParam(dt, dd, 83) < 0.5f, "automation drives the appended Dynamics switch");
+ de.RemoveAutomationLane(dt, dlane2); de.RemoveAutomationLane(dt, dlane);
+ de.DeviceSetParam(dt, dd, 83, 1f);
+
+ // Every factory preset names only real params and renders finite and audible.
+ var dqcat = new FactoryPresetCatalog();
+ int dqPresets = 0; bool dqNamesOk = true, dqPresetsOk = true;
+ var dqNames = new HashSet<string>();
+ for (int p = 0; p < dpc; p++) dqNames.Add(de.DeviceParamName(dt, dd, p));
+ foreach (var info in dqcat.All())
+ {
+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 13) continue;
+ var doc = dqcat.Document(info.Id);
+ if (doc is null) continue;
+ dqPresets++;
+ foreach (var k in doc.NamedParams!.Keys) if (!dqNames.Contains(k)) { dqNamesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }
+ dqcat.ApplyInPlace(de, info.Id, dt, dd);
+ var b = Render(8192);
+ if (!Finite(b) || Rms(b, 8192) < 1e-4f) { dqPresetsOk = false; Console.WriteLine($" preset {info.DisplayName} not finite / silent (rms {Rms(b, 8192):F4})"); }
+ }
+ Check(dqPresets >= 25 && dqNamesOk && dqPresetsOk, $"{dqPresets} Dynamic EQ-8 factory presets, all params known, all render finite and audible");
+}
+{
+ // The key: band 4 hears the key track, not its own signal. The EQ'd track plays a 440 Hz
+ // sine; the key track is silent, then a loud 440 Hz sine.
+ string kwav = Path.Combine(Path.GetTempPath(), "nota_smoke_dyneq_key.wav");
+ Nota.SmokeTest.WavWriter.WriteStereo(kwav, 2.0, 44100, i => { double v = 0.5 * Math.Sin(2 * Math.PI * 440 * i / 44100.0); return (v, v); });
+ using var ke = new NotaEngine();
+ ke.SetBpm(120);
+ int silent = ke.AddAudioTrack();
+ int keyTrack = ke.AddAudioTrack();
+ ke.AddAudioClip(keyTrack, kwav, 0.0);
+ int kt = ke.AddAudioTrack();
+ ke.AddAudioClip(kt, kwav, 0.0);
+ int kd = ke.AddBuiltinDevice(kt, 13);
+ ke.DeviceSetParam(kt, kd, 32, 440f); ke.DeviceSetParam(kt, kd, 35, 1f); ke.DeviceSetParam(kt, kd, 36, -40f); ke.DeviceSetParam(kt, kd, 37, -9f);
+ var kgr = new float[16];
+ float Gr4()
+ {
+ // In 512-frame blocks: the key a device hears is its source's previous block.
+ var b = new float[512 * 2]; ke.Seek(0); ke.Play();
+ for (int k = 0; k < 80; k++) ke.RenderOffline(b, 512);
+ ke.StopTransport();
+ ke.DeviceScope(kt, kd, kgr, 16);
+ return kgr[3];
+ }
+ float self = Gr4();
+ ke.DeviceSetParam(kt, kd, 87, 1f); // band 4 Key = Ext
+ float extNone = Gr4(); // no key track routed → hears itself
+ ke.SetDeviceSidechainSource(kt, kd, silent);
+ Check(ke.DeviceSidechainSource(kt, kd) == silent, "the key track is stored on the device");
+ float extSilent = Gr4();
+ ke.SetDeviceSidechainSource(kt, kd, keyTrack);
+ float extLoud = Gr4();
+ Check(self < -3f && extNone < -3f && Math.Abs(extSilent) < 0.1f && extLoud < -3f && kgr[8 + 3] > -40f,
+ $"Ext keys the band from the key track (self {self:F1}, no key {extNone:F1}, silent key {extSilent:F2}, loud key {extLoud:F1} dB)");
+ ke.DeviceSetParam(kt, kd, 87, 0f);
+ Check(Gr4() < -3f, "Self ignores the routed key");
}
// ============================ Nota Ceiling =================================