Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
Redesign of Level
Egor Khindikaynena335c5b0e7e8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 10286978..be5bdf13 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,44 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.level, the effective attack and release, look-ahead latency and how often it kicked in.### Changed+- **Nota Level is redrawn as a full leveler.** The card follows the new mockup on the 700 × 260+ frame, in the language of EQ-8 and Forge:+ - **Correction.** Manual / Auto sit over a fader around 0 dB. Auto rides it in teal. In+ Manual you drag it, and switching to Manual starts from the gain Auto was riding. The gain+ applied shows in large type, with the reason when something holds it (max gain, max cut,+ true-peak, silence). **MATCH** (Manual) sets the fader to the distance to the target.+ **RESET** (Auto) restarts the measurement from the loudness now, so the ride catches up at+ once. Target and Trim sit under it. Click the Target value for the standards (−9 … −27+ LUFS: streaming, podcast, EBU R128, ATSC A/85 …) or to match another track's loudness.+ - **Loudness.** Mom / Short / Integ over the last 8 s: the input, the output and the target+ with its ±1 LU band. A dot marks the output now. Drag the line to move the target. Under+ it, IN · OUT · Δ · TP.+ - **Meters and response.** IN and OUT against the target, TP against the ceiling, and the+ correction. Fast / Slow, Window and Max Gain. **True-peak safe** with its ceiling in dBTP+ (drag it). A status strip says what the leveler is doing and shows the sample rate, scale,+ look-ahead and correlation.+ - **Scales.** Momentary 400 ms, Short-term 3 s, Integrated 12 s with BS.1770 gating.+ **Window** is now the glide time: Slow glides over all of it, Fast over a quarter.+ - **Silence holds.** Before the first signal, and while the input is too quiet to level+ (more than 20 LU under its own 12 s level, more than Max Gain + 12 LU under the target, or+ under −70 LUFS), the measurement and the gain hold. Pauses and release tails no longer get+ pumped up into noise.+ - **Look-ahead limiter.** True-peak safe is now a look-ahead limiter (5 ms on Fast, 20 ms on+ Slow) that never lets a true peak through above the ceiling. Its latency is reported, so+ delay compensation keeps the track in time.+ - **Compatibility.** The manual **Gain** is appended (0 dB by default), so projects, racks+ and presets saved before this open. Older projects that had Auto off held the correction+ they had reached. They now apply the manual Gain (0 dB), so press MATCH once.+ - **30 factory presets**, up from six: delivery targets (EBU R128, ATSC A/85, Apple Music,+ YouTube, Audiobook ACX, Cinema Dialogue, Game Audio …), speech riders, music and mixing+ (Gentle Rider, Gain Staging −18, Mix Bus −20, Music Bed −28 …) and static ones (True-Peak+ Guard, Static Boost +6). The six earlier presets keep their names.+ - **MCP: `read_level`, `set_level`, `level_match`.** `read_level` reports the mode and state,+ the target (or the reference), the loudness in and out on every scale, the distance to the+ target, the correction and what holds it, the limiter, true peak and latency. `set_level`+ edits Level in LUFS, dB and seconds and routes a reference. `level_match` is MATCH.+ `get_device_text` gives a summary, a live reading and a parameter guide. `device_action` 0+ is RESET and 1 is MATCH. Every parameter automates, MIDI-learns and saves in a preset.- **Nota Forge is redrawn, and every stage gets its own shape.** The card follows the newmockup on the 700 × 260 frame, in the language of EQ-8:- **Stages.** On the left the routing (Serial / Parallel / M/S / Multi) sits over the threediff --git a/FEATURES.md b/FEATURES.mdindex c87d90d0..5bd99148 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -443,9 +443,13 @@ and user presets, automation, persistence and cloning.band's curve, the brass sum and the output spectrum (engine FFT) — drag the crossover handles,or ride a band's gain in its zone; a status strip; 30 factory presets; MCP `read_eq3`,`set_eq3`.-- **Nota Level** (18) — automatic loudness matching (LUFS): LUFS measurement (BS.1770),- AUTO/MATCH, true-peak safe, sidechain (match to reference); loudness history and- IN/OUT/TP/correlation meters.+- **Nota Level** (18) — loudness leveler (BS.1770 LUFS): Auto rides the gain to a Target+ (−36 … 0 LUFS, standards menu) over Window (Fast / Slow), Manual holds a draggable fader and+ MATCH sets it to the distance to the target; Momentary / Short-term / Integrated (gated)+ scales; Max Gain, Trim; holds the gain in silence and release tails; True-peak safe+ look-ahead limiter (5 / 20 ms, PDC) with a Ceiling; match to a reference track (sidechain).+ An 8 s loudness graph (drag the target), IN / OUT / TP / correction meters and a status+ strip; 30 factory presets; MCP `read_level`, `set_level`, `level_match`.- **Nota Shutter** (19) — noise gate and ducker: Threshold/Return (hysteresis),Attack/Hold/Release with a Linear / Log / Snap shape, Floor (range), Lookahead, Flip(ducker), Retrigger (trigger mode), a 12 dB/oct detector band-pass (switchable) with Listen,diff --git a/src/managed/Nota.App/Controls/AutoGainViz.cs b/src/managed/Nota.App/Controls/AutoGainViz.csdeleted file mode 100644index 36a5e8f0..00000000--- a/src/managed/Nota.App/Controls/AutoGainViz.cs+++ /dev/null@@ -1,111 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.-//-// Nota AutoGain (device kind 18) loudness history — the signature viz. It samples the-// device's instantaneous meters each UI tick and scrolls them right→left: input loudness-// as an olive filled area, the gain-matched output as a brass line, and the target as a-// teal dashed line (which itself moves when a sidechain reference is driving the target).-// An annotation shows the live correction ("correcting +6.0 → +4.3 dB"). Read-only.--using System;-using Avalonia;-using Avalonia.Controls;-using Avalonia.Media;-using Nota.Application;--namespace Nota.App;--internal sealed class AutoGainHistory : Control-{- // scope layout — must match AutoGain.h enum.- private const int S_InLufs = 0, S_OutLufs = 1, S_Target = 3, S_Applied = 4, S_Desired = 8, kScope = 9;- private const int N = 480; // ~8 s of history at 60 Hz- private const double LTop = -4.0, LBot = -44.0;-- private static readonly IBrush Bg = NotaPalette.BgSunken;- private static readonly IBrush BorderB = NotaPalette.BorderDefault;- private static readonly IPen Grid = NotaGraph.GridPen;- private static readonly IBrush InFill = NotaPalette.Wash(NotaPalette.SignalInFill, 0x8C);- private static readonly IPen InPen = new Pen(NotaPalette.Wash(NotaPalette.SignalIn, 0xB0), 1);- private static readonly IPen OutPen = new Pen(NotaPalette.Accent, 1.8);- private static readonly IPen TargetPen = new Pen(NotaPalette.Teal, 1) { DashStyle = new DashStyle(new double[] { 4, 3 }, 0) };- private static readonly IBrush Muted = NotaPalette.TextTertiary;- private static readonly IBrush Correcting = NotaPalette.Ink("#C48A6A");- private static readonly IBrush TealBright = NotaPalette.TealBright;- private static readonly IBrush AxisB = NotaPalette.TextTertiary;- private static readonly Typeface Face = NotaFonts.Mono;-- private readonly IAudioEngine _engine;- private readonly int _track, _device;- private readonly float[] _in = new float[N], _out = new float[N], _tar = new float[N];- private readonly float[] _scope = new float[kScope];- private int _w; private bool _primed;- private float _desired, _applied;-- public AutoGainHistory(IAudioEngine engine, int track, int device)- {- _engine = engine; _track = track; _device = device;- MinHeight = 60; ClipToBounds = true;- for (int i = 0; i < N; i++) { _in[i] = -120; _out[i] = -120; _tar[i] = -14; }- }-- public void Tick()- {- int n = _engine.DeviceScope(_track, _device, _scope, kScope);- if (n >= kScope)- {- _in[_w] = _scope[S_InLufs]; _out[_w] = _scope[S_OutLufs]; _tar[_w] = _scope[S_Target];- _desired = _scope[S_Desired]; _applied = _scope[S_Applied];- _w = (_w + 1) % N; _primed = true;- }- InvalidateVisual();- }-- private static double Y(double lufs, double h) => Math.Clamp((LTop - lufs) / (LTop - LBot) * h, 0, h);-- public override void Render(DrawingContext ctx)- {- double w = Bounds.Width, h = Bounds.Height;- if (w <= 0 || h <= 0) return;- NotaGraph.Window(ctx, new Rect(0, 0, w, h));- double gx = 6, gy = 14, gw = w - 12, gh = h - gy - 12;- if (gw <= 0 || gh <= 0) return;-- foreach (double lu in new[] { -10.0, -20, -30 }) ctx.DrawLine(Grid, new Point(gx, gy + Y(lu, gh)), new Point(gx + gw, gy + Y(lu, gh)));-- double X(int i) => gx + (double)i / (N - 1) * gw;- int Idx(int i) => (_w + i) % N; // oldest → newest-- if (_primed)- {- // input area (olive)- var area = new StreamGeometry();- using (var g = area.Open())- {- g.BeginFigure(new Point(gx, gy + gh), true);- for (int i = 0; i < N; i++) g.LineTo(new Point(X(i), gy + Y(_in[Idx(i)], gh)));- g.LineTo(new Point(gx + gw, gy + gh)); g.EndFigure(true);- }- ctx.DrawGeometry(null, InPen, area);-- // target dashed teal (follows the reference when sidechained)- Point tp = default; bool has = false;- for (int i = 0; i < N; i += 3) { var p = new Point(X(i), gy + Y(_tar[Idx(i)], gh)); if (has) ctx.DrawLine(TargetPen, tp, p); tp = p; has = true; }-- // output brass line- Point op = default; has = false;- for (int i = 0; i < N; i++) { var p = new Point(X(i), gy + Y(_out[Idx(i)], gh)); if (has && _out[Idx(i)] > -119) ctx.DrawLine(OutPen, op, p); op = p; has = true; }- }-- void Lbl(string s, double x, double y, IBrush b) => ctx.DrawText(new FormattedText(s, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));- Lbl("LOUDNESS", gx, 2, Muted);- NotaGraph.Legend(ctx, gx + gw - 2, 2, ("input", NotaPalette.SignalIn, NotaGraph.Mark.Area),- ("output", NotaPalette.Accent, NotaGraph.Mark.Line), ("target", NotaPalette.Teal, NotaGraph.Mark.Dashed));- if (_primed && Math.Abs(_desired - _applied) > 0.15f)- Lbl($"correcting {_desired:+0.0;−0.0;0.0} → {_applied:+0.0;−0.0;0.0}\u2009dB", gx + 2, gy + 1, Correcting);- else if (_primed)- Lbl(Math.Abs(_applied) < 0.05f ? "matched" : "locked", gx + gw - 44, gy + 1, TealBright);- Lbl("−8\u2009s", gx, gy + gh + 1, AxisB);- Lbl("now", gx + gw - 18, gy + gh + 1, AxisB);- }-}diff --git a/src/managed/Nota.App/Controls/LevelViews.cs b/src/managed/Nota.App/Controls/LevelViews.csnew file mode 100644index 00000000..4fe2d18c--- /dev/null+++ b/src/managed/Nota.App/Controls/LevelViews.cs@@ -0,0 +1,282 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Level views (device kind 18) — the pictures on the Level card:+// LvHistoryView — the last 8 s of loudness: the input (ink), the output (brass) and the target+// (dashed teal, with a ±1 LU band) that moves with a reference track. A dot+// marks the output now. Drag up / down for Target (not while a reference+// drives it); double-click resets it.+// LvGainFader — the correction as a vertical fader around 0 dB (±Max Gain): teal while Auto+// rides it, a brass fill with a draggable cap in Manual.+// LvMeter — a 4px bar with an optional teal marker (the target, the ceiling, 0 dB).+// LvLegend — the graph legend drawn with NotaGraph's samples, for the panel bar.+// LevelMath holds the telemetry layout (AutoGain.h) and the unit mappings.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;++namespace Nota.App;++internal static class LevelMath+{+ // Params (AutoGain.h).+ public const int Target = 0, Scale = 1, Auto = 2, Trim = 3, Response = 4, WindowP = 5, MaxGain = 6, Safe = 7, Ceiling = 8, Gain = 9;+ // Scope (AutoGain.h).+ public const int S_InLufs = 0, S_OutLufs = 1, S_InMom = 2, S_Target = 3, S_Applied = 4, S_TruePeak = 5, S_Corr = 6,+ S_ScLufs = 7, S_Desired = 8, S_Measured = 9, S_OutMeasured = 10, S_OutMom = 11, S_Level = 12, S_LimGr = 13,+ S_Clamp = 14, S_Silent = 15, S_Latency = 16, S_SampleRate = 17, S_Primed = 18, S_Delta = 19, S_LimHold = 20, kScope = 21;++ public static readonly string[] ScaleNames = { "Mom", "Short", "Integ" };+ public static readonly string[] ScaleLong = { "momentary · 400\u2009ms", "short-term · 3\u2009s", "integrated · gated" };++ public const double LTop = 0, LBot = -40; // the graph and meter range, LUFS++ public static double TargetLufs(double v) => -36 + v * 36;+ public static double TargetNorm(double lufs) => Math.Clamp((lufs + 36) / 36, 0, 1);+ public static double TrimDb(double v) => (v - 0.5) * 24;+ public static double WindowS(double v) => 0.4 * Math.Pow(25, Math.Clamp(v, 0, 1));+ public static double WindowNorm(double s) => Math.Log(Math.Clamp(s, 0.4, 10) / 0.4) / Math.Log(25);+ public static double MaxGainDb(double v) => v * 24;+ public static double CeilingDb(double v) => -6 + v * 6;+ public static double GainDb(double v) => (v - 0.5) * 48;+ public static double GainNorm(double db) => Math.Clamp(0.5 + db / 48, 0, 1);+ public static int ScaleIndex(double v) => Math.Clamp((int)Math.Round(v * 2), 0, 2);++ public static string Lufs(double v) => v <= -119 ? "—" : NotaNum.F($"{v:0.0;−0.0;0.0}");+ public static string Sgn(double v) => NotaNum.F($"{v:+0.0;−0.0;0.0}");+}++internal sealed class LvHistoryView : Control+{+ private const int N = 480; // ~8 s at the 60 Hz UI tick+ private readonly float[] _in = new float[N], _out = new float[N], _tar = new float[N];+ private int _w, _count;+ private bool _on = true, _dragging, _canDrag = true;+ private string _lock = "", _targetLabel = "";+ private bool _locked;+ private double _y0, _v0;++ /// <summary>Target (0..1) at the start of a drag.</summary>+ public Func<double>? Value { get; set; }+ public event Action? GestureBegin;+ public event Action? GestureEnd;+ public event Action<double>? Changed;+ public event Action? ResetRequested;+ public bool Dragging => _dragging;++ public LvHistoryView()+ {+ ClipToBounds = true; MinHeight = 60;+ for (int i = 0; i < N; i++) { _in[i] = -120; _out[i] = -120; _tar[i] = -14; }+ }++ /// <summary>Push one tick of momentary loudness (in, out) and the target in effect.</summary>+ public void Push(float inLufs, float outLufs, float target)+ {+ _in[_w] = inLufs; _out[_w] = outLufs; _tar[_w] = target;+ _w = (_w + 1) % N; if (_count < N) _count++;+ }++ public void SetState(bool on, bool locked, string lockText, string targetLabel, bool canDrag)+ {+ _on = on; _locked = locked; _lock = lockText; _targetLabel = targetLabel; _canDrag = canDrag;+ Cursor = canDrag ? new Cursor(StandardCursorType.SizeNorthSouth) : Cursor.Default;+ InvalidateVisual();+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!_canDrag || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2) { ResetRequested?.Invoke(); e.Handled = true; return; }+ _v0 = Value?.Invoke() ?? 0.611; _y0 = e.GetPosition(this).Y; _dragging = true;+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (!_dragging) return;+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;+ // The line follows the pointer: the graph spans 40 LU, the target 36 LU of 0..1.+ double h = Math.Max(40, Bounds.Height - 20);+ double dLu = (_y0 - e.GetPosition(this).Y) / h * (LevelMath.LTop - LevelMath.LBot) * (fine ? 0.2 : 1);+ Changed?.Invoke(Math.Clamp(_v0 + dLu / 36, 0, 1));+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (!_dragging) return;+ _dragging = false; e.Pointer.Capture(null); GestureEnd?.Invoke();+ }++ 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 top = 1, bot = h - 1;+ double Y(double lufs) => top + Math.Clamp((LevelMath.LTop - lufs) / (LevelMath.LTop - LevelMath.LBot), 0, 1) * (bot - top);+ double X(int i) => 1 + (double)i / (N - 1) * (w - 2);+ int Idx(int i) => (_w + i) % N; // oldest → newest++ foreach (double lu in new[] { -10.0, -20, -30 }) ctx.DrawLine(NotaGraph.GridPen, new Point(0, Y(lu)), new Point(w, Y(lu)));+ for (int k = 1; k < 4; k++) ctx.DrawLine(NotaGraph.GridPen, new Point(w * k / 4, 0), new Point(w * k / 4, h));++ float tNow = _tar[(_w + N - 1) % N];+ // The ±1 LU band around the target now.+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Teal, 0x14), new Rect(0, Y(tNow + 1), w, Math.Max(1, Y(tNow - 1) - Y(tNow + 1))));++ int first = N - _count;+ // Input (ink), under the target and the output.+ Trace(ctx, _in, first, new Pen(NotaPalette.TextTertiary, 1));+ // Target, dashed teal (steps with a reference).+ var tp = new Pen(NotaPalette.TealBright, 1, new DashStyle(new double[] { 4, 3 }, 0));+ Trace(ctx, _tar, Math.Max(0, first), tp, allowSilent: true);+ // Output, brass.+ Trace(ctx, _out, first, NotaGraph.SecondaryPen(_on ? NotaPalette.Accent : NotaPalette.TextTertiary, NotaGraph.PrimaryWidth));++ NotaGraph.Title(ctx, frame, "Loudness");+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.TopRight, _lock, _locked ? NotaPalette.TealBright : NotaPalette.TextTertiary);+ foreach (double lu in new[] { -10.0, -20, -30 })+ {+ var ft = NotaGraph.AxisText(NotaNum.F($"{lu:0;−0}"));+ double y = Y(lu) + 1;+ if (Math.Abs(Y(tNow) - Y(lu)) > 9) ctx.DrawText(ft, new Point(4, y));+ }+ if (_targetLabel.Length > 0)+ {+ var ft = NotaGraph.AxisText(_targetLabel, NotaPalette.TealBright);+ double y = Y(tNow) - ft.Height - 1;+ if (y < 12) y = Y(tNow) + 2;+ ctx.DrawText(ft, new Point(w - 14 - ft.Width, y));+ }+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "−8 s");+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "now");++ float oNow = _out[(_w + N - 1) % N];+ if (_on && _count > 0 && oNow > -119) NotaGraph.Node(ctx, new Point(w - 4, Y(oNow)), true, NotaPalette.AccentBright);++ void Trace(DrawingContext dc, float[] src, int from, IPen pen, bool allowSilent = false)+ {+ var geo = new StreamGeometry();+ bool any = false;+ using (var g = geo.Open())+ {+ bool open = false;+ for (int i = Math.Max(0, from); i < N; i++)+ {+ float v = src[Idx(i)];+ if (!allowSilent && v <= -119) { if (open) { g.EndFigure(false); open = false; } continue; }+ var p = new Point(X(i), Y(v));+ if (!open) { g.BeginFigure(p, false); open = true; any = true; } else g.LineTo(p);+ }+ if (open) g.EndFigure(false);+ }+ if (any) dc.DrawGeometry(null, pen, geo);+ }+ }+}++internal sealed class LvGainFader : Control+{+ private double _db, _max = 12;+ private bool _manual, _on = true, _drag;+ private double _y0, _v0;++ /// <summary>The manual gain (dB) at the start of a drag.</summary>+ public Func<double>? Value { get; set; }+ public event Action? GestureBegin;+ public event Action? GestureEnd;+ public event Action<double>? Changed; // new gain in dB+ public event Action? ResetRequested;+ public bool Dragging => _drag;++ public LvGainFader() { Width = 14; }++ public void Set(double db, double maxDb, bool manual, bool on)+ {+ _db = db; _max = Math.Max(0.01, maxDb); _manual = manual; _on = on;+ Cursor = manual ? new Cursor(StandardCursorType.SizeNorthSouth) : Cursor.Default;+ InvalidateVisual();+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!_manual || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2) { ResetRequested?.Invoke(); e.Handled = true; return; }+ _v0 = Value?.Invoke() ?? _db; _y0 = e.GetPosition(this).Y; _drag = true;+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (!_drag) return;+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;+ // Full range (−max … +max) over ~140 px, fine steps with a modifier.+ double d = (_y0 - e.GetPosition(this).Y) / 140.0 * 2 * _max * (fine ? 0.1 : 1);+ Changed?.Invoke(Math.Round(Math.Clamp(_v0 + d, -_max, _max) * 10) / 10);+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (!_drag) return;+ _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke();+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 4) return;+ double cx = w / 2, top = 2.5, bot = h - 2.5;+ double Y(double db) => top + (0.5 - Math.Clamp(db / _max, -1, 1) / 2) * (bot - top);+ ctx.FillRectangle(NotaPalette.BgSunken, new Rect(cx - 2, 0, 4, h), 2);+ ctx.FillRectangle(NotaPalette.BorderStrong, new Rect(0, Math.Round(Y(0)), w, 1));+ IBrush fill = !_on ? NotaPalette.BorderStrong : _manual ? NotaPalette.Accent : NotaPalette.Teal;+ double y0 = Y(0), y1 = Y(_db);+ ctx.FillRectangle(fill, new Rect(cx - 2, Math.Min(y0, y1), 4, Math.Abs(y1 - y0)), 1);+ IBrush cap = !_on ? NotaPalette.TextDisabled : _manual ? NotaPalette.TextPrimary : NotaPalette.TealBright;+ ctx.FillRectangle(cap, new Rect(0, y1 - 2.5, w, 5), 2);+ }+}++internal sealed class LvMeter : Control+{+ private double _l, _r, _mark = double.NaN;+ private IBrush _ink = NotaPalette.Accent;++ public LvMeter() { Height = 4; }++ /// <summary>Fill from <paramref name="from"/> to <paramref name="to"/> (0..1), a teal marker at+ /// <paramref name="marker"/> (NaN hides it).</summary>+ public void Set(double from, double to, IBrush ink, double marker)+ {+ _l = Math.Clamp(Math.Min(from, to), 0, 1); _r = Math.Clamp(Math.Max(from, to), 0, 1); _ink = ink; _mark = marker;+ InvalidateVisual();+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ using (ctx.PushClip(new RoundedRect(new Rect(0, 0, w, h), 2)))+ {+ ctx.FillRectangle(NotaPalette.BgSunken, new Rect(0, 0, w, h));+ if (_r > _l) ctx.FillRectangle(_ink, new Rect(_l * w, 0, (_r - _l) * w, h));+ if (!double.IsNaN(_mark)) ctx.FillRectangle(NotaPalette.TealBright, new Rect(Math.Clamp(_mark, 0, 1) * (w - 1), 0, 1, h));+ }+ }+}++internal sealed class LvLegend : Control+{+ public LvLegend() { Height = 11; Width = 132; }++ public override void Render(DrawingContext ctx)+ => NotaGraph.Legend(ctx, Bounds.Width, 0, ("input", NotaPalette.TextTertiary, NotaGraph.Mark.Line),+ ("output", NotaPalette.AccentBright, NotaGraph.Mark.Line), ("target", NotaPalette.TealBright, NotaGraph.Mark.Dashed));+}diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.csindex 6650168e..07a16843 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs@@ -1,13 +1,20 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — built-in Nota AutoGain (device kind 18) body, built to the AutoGain-// mockup: a loudness-matching utility. A LIVE strip (Target LUFS · Scale · a REFERENCE-// sidechain picker · MATCH · AUTO) over a body of three columns — a CORRECTION column-// (Auto/Manual, the big applied-gain number with a boost/cut indicator, Trim), the LOUDNESS-// history graph in the middle, and a METERS + RESPONSE rail on the right. Routing a-// reference track (sidechain) makes the target follow that track's loudness instead of the-// Target param — so the TARGET control dims and the graph's target line moves with it.+// Detail · Devices — built-in Nota Level body (loudness leveler, device kind 18), a build of the+// "Nota Level" mockup (700 × 260) in the EQ-8 / Forge language. On the left the CORRECTION:+// Manual / Auto, a fader around 0 dB (Auto rides it in teal; in Manual drag it), the gain applied+// in large type with why it is held (max gain, true-peak), MATCH (Manual: set the gain to the+// distance to the target) / RESET (Auto: restart the measurement from now), Target and Trim.+// Click the Target value for the standards or a reference track — routed, the target follows+// that track's loudness (the device's sidechain). In the centre the Scale (Mom / Short / Integ)+// over 8 s of loudness — input, output and the target with its ±1 LU band (drag the line for+// Target) — and a readout row. On the right the METERS (IN / OUT against the target, TP against+// the ceiling, the correction), RESPONSE (Fast / Slow, Window, Max Gain) and TRUE-PEAK SAFE with+// its ceiling (drag the dBTP). A status strip says what the leveler is doing. Every control is a+// device param (normalized 0..1), so automation / MIDI learn / presets / A-B / persistence come+// for free; double-click resets. FullBleed — the shared shell draws the header (name · preset ·+// badge · bypass).using System;using System.Collections.Generic;@@ -18,220 +25,468 @@ using Avalonia.Layout;using Avalonia.Media;using Nota.Application;using static Nota.App.DeviceCardKit;+using static Nota.App.LevelMath;namespace Nota.App;internal sealed class AutoGainDeviceBody : IDeviceBody{- private const int Target = 0, Scale = 1, Auto = 2, Trim = 3, Response = 4, Window = 5, MaxGain = 6, Safe = 7, Ceiling = 8;- // scope layout — must match AutoGain.h.- private const int S_InLufs = 0, S_OutLufs = 1, S_InMom = 2, S_Target = 3, S_Applied = 4, S_TruePeak = 5, S_Corr = 6, S_ScLufs = 7, kScope = 9;-- 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 Amber = NotaPalette.Accent;- private static readonly IBrush AmberLit = NotaPalette.AccentBright;- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);- private static readonly IBrush TealC = NotaPalette.Teal;- private static readonly IBrush TealBright = NotaPalette.TealBright;- private static readonly IBrush TealSubtle = NotaPalette.Wash(NotaPalette.Teal, 0x24);- private static readonly IBrush TxtC = NotaPalette.TextPrimary;- private static readonly IBrush MutedC = NotaPalette.TextTertiary;- private static readonly IBrush LabelC = NotaPalette.TextSecondary;- private static readonly IBrush Dim = NotaPalette.BorderStrong;- private static readonly IBrush Green = NotaPalette.Success;- private static readonly IBrush Yellow = NotaPalette.Warning;- private static readonly IBrush HandleC = NotaPalette.TextSecondary;+ // Target standards offered by the Target value's menu.+ private static readonly (string Label, double Lufs)[] Standards =+ {+ ("−9\u2009LUFS · club", -9), ("−11\u2009LUFS · loud master", -11), ("−14\u2009LUFS · streaming", -14), ("−16\u2009LUFS · podcast, Apple", -16),+ ("−18\u2009LUFS · audiobook", -18), ("−23\u2009LUFS · EBU R128", -23), ("−24\u2009LUFS · ATSC A/85", -24), ("−27\u2009LUFS · cinema dialogue", -27),+ };public double Width => 700;-- public string? Subtitle => "LEVELER"; // the processing type, shown as the header badgepublic bool FullBleed => true;+ public string? Subtitle => "LEVELER";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);+ int pc = engine.DeviceParamCount(track, di);+ float P(int p) => p < pc ? engine.DeviceGetParam(track, di, p) : 0.5f;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) { if (p < pc) engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1)); }+ void SetP(int p, double 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;+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));var readouts = new List<Action>();- var scope = new float[kScope];- Control Cap(string t, IBrush? c = null, double w = 0) { var tb = new TextBlock { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, VerticalAlignment = VerticalAlignment.Center }; if (w > 0) tb.Width = w; return tb; }+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }+ var sc = new float[kScope];+ int scN = 0;+ double Sc(int i) => scN > i ? sc[i] : 0;+ bool Active() => !engine.DeviceBypassed(track, di);+ bool Manual() => !On(Auto);+ bool Primed() => Sc(S_Primed) > 0.5;+ double MaxG() => MaxGainDb(P(MaxGain));- var hist = new AutoGainHistory(engine, track, di) { VerticalAlignment = VerticalAlignment.Stretch };- ctx.AddDeviceRefresher(hist.Tick);+ // ---- reference track (the device's sidechain) ---------------------------------------+ string TrackName(int id)+ {+ 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 "—";+ }+ int Ref() => engine.DeviceSidechainSource(track, di);+ bool HasRef() => Ref() >= 0;- // ---- formatters ----- static string TargetF(double v) => $"{-36 + v * 36:0.0}\u2009LUFS";- static string TrimF(double v) => $"{(v - 0.5) * 24:+0.0;−0.0;0.0}";- static string WindowF(double v) => $"{0.4 * Math.Pow(25, v):0.0}\u2009s";- static string MaxF(double v) => $"{v * 24:0}";+ // ---- units ---------------------------------------------------------------------------+ static string TargetF(double v) => Lufs(TargetLufs(v)) + "\u2009LUFS";+ static string TrimF(double v) => Sgn(TrimDb(v)) + "\u2009dB";+ static string WindowF(double v) => NotaNum.F($"{WindowS(v):0.0}\u2009s");+ static string MaxF(double v) => NotaNum.F($"{MaxGainDb(v):0}\u2009dB");- // ---- horizontal slider (label | slot | value) ----- Control HRow(int p, string label, Func<double, string> fmt, double labW, double valW, bool teal = false, bool bipolar = false)+ // ---- small builders ------------------------------------------------------------------+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };+ static TextBlock Mono(string t, double fs, IBrush c)+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }+ static Border Island(Control child, double width = double.NaN) => new(){- var row = DeviceCardKit.SliderRow(labW > 0 ? label : "", () => P(p), n => { SetP(p, (float)n); }, () => fmt(P(p)), out var sync,- begin: () => Begin(p), end: () => End(p), bipolar: bipolar, labelWidth: labW, valueWidth: valW);- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);- readouts.Add(sync);- return row;+ Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,+ ClipToBounds = true, Child = child,+ };+ static Border Bar(Control child, Thickness pad) => new()+ { Height = 20, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Padding = pad, Child = child };+ 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 };++ // Slider row: caps 7 label · 3px track · mono 8 value (brass-light once off its default).+ // `valueHost` replaces the plain value (the Target's menu); `dim` greys the track.+ Control Slider(string label, int p, Func<double, string> fmt, string tip, double labelW, double valueW,+ bool bipolar = false, Func<bool>? dim = null, Func<(string Text, IBrush? Ink)>? valueOverride = null, Action<Control>? valueClick = null)+ {+ var lbl = Caps(label);+ lbl.TextTrimming = TextTrimming.None;+ var trk = new SliderTrack { Bipolar = bipolar, Reset = () => { Reset(p); RefreshAll(); }, VerticalAlignment = VerticalAlignment.Center };+ trk.Changed += v => { Raw(p, v); RefreshAll(); };+ trk.GestureBegin += () => Begin(p);+ trk.GestureEnd += () => End(p);+ var val = Mono("", 8, TextPrimary);+ val.TextAlignment = TextAlignment.Right;+ val.HorizontalAlignment = HorizontalAlignment.Right;+ Control valCtl = val;+ if (valueClick is not null)+ {+ var box = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = val };+ box.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;+ valueClick(box); e.Handled = true;+ };+ valCtl = box;+ }+ var g = new Grid { ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center, Background = Brushes.Transparent };+ g.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(labelW)));+ g.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));+ g.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(valueW)));+ g.Children.Add(lbl); g.Children.Add(Col(trk, 1)); g.Children.Add(Col(valCtl, 2));+ readouts.Add(() =>+ {+ if (!trk.Dragging) trk.Norm = P(p);+ bool d = dim?.Invoke() ?? false;+ trk.IsDim = d;+ var ov = valueOverride?.Invoke();+ if (ov is { } o && o.Text.Length > 0) { val.Text = o.Text; val.Foreground = o.Ink ?? TextPrimary; }+ else+ {+ val.Text = fmt(P(p));+ val.Foreground = d ? TextTertiary : Math.Abs(P(p) - Def(p)) > 0.003 ? AccentBright : TextPrimary;+ }+ });+ Learn(g, p);+ ToolTip.SetTip(g, tip);+ return g;}- // Segmented pill (n options over a normalized param). teal optional.- Control Seg(int p, string[] opts, bool teal = false, Action? after = null)+ Border Seg(string[] names, Func<int> cur, Action<int> pick, int p, string tip, double width){- int n = opts.Length;- var seg = DeviceCardKit.Segments(opts, () => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1), iv => { SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); after?.Invoke(); }, out var sync);+ var s = Segments(names, cur, i => { pick(i); RefreshAll(); }, out var sync, fill: true, padX: 2);+ s.Width = width;readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));- return seg;+ Learn(s, p);+ ToolTip.SetTip(s, tip);+ return s;}- // Teal toggle switch backed by a 0/1 param.- Control Toggle(int p, string label)+ // A dropdown menu under a control.+ void Menu(Control at, IEnumerable<(string Label, bool Current, Action Pick)?> items){- var host = Switch(label, () => P(p) >= 0.5f, () => SetP(p, P(p) >= 0.5f ? 0f : 1f), out var sync);- readouts.Add(sync);- MidiLearn.Bind(host, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));- return host;+ var fly = new MenuFlyout();+ foreach (var it in items)+ {+ if (it is not { } x) { fly.Items.Add(new Separator()); continue; }+ var mi = new MenuItem { Header = x.Label };+ if (x.Current) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };+ var pk = x.Pick;+ mi.Click += (_, _) => { pk(); RefreshAll(); };+ fly.Items.Add(mi);+ }+ fly.ShowAt(at);}- // ---- reference (sidechain) source combo ----- var scIds = new List<int> { -1 };- var scCombo = new ComboBox { FontSize = 9, Height = 20, Width = 104, Padding = new Thickness(6, 0), VerticalAlignment = VerticalAlignment.Center };- scCombo.Items.Add("Target → fixed");- for (int i = 0; i < engine.TrackCount; i++)+ void TargetMenu(Control at){- if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;- string kind = ti.IsReturn ? "Return" : ti.IsInstrument ? "Inst" : "Audio";- scIds.Add(ti.Id); scCombo.Items.Add($"Ref: {i + 1} · {kind}");+ var list = new List<(string, bool, Action)?>();+ foreach (var (label, lufs) in Standards)+ {+ double v = TargetNorm(lufs);+ list.Add((label, !HasRef() && Math.Abs(TargetLufs(P(Target)) - lufs) < 0.05, () =>+ {+ if (HasRef()) { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); }+ SetP(Target, v);+ }));+ }+ list.Add(null);+ list.Add(("Fixed target — no reference", !HasRef(), () => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); }));+ for (int i = 0; i < engine.TrackCount; i++)+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track)+ {+ int id = ti.Id;+ list.Add(("Match track: " + TrackName(id), Ref() == id, () => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); }));+ }+ Menu(at, list);}- scCombo.SelectedIndex = Math.Max(0, scIds.IndexOf(engine.DeviceSidechainSource(track, di)));-- // ---- LIVE strip ----- var targetGroup = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 210, Children = {- Cap("TARGET", MutedC, 40), new Border { Child = HRow(Target, "", TargetF, 0, 66), Width = 150 } } };- scCombo.SelectionChanged += (_, _) => { int sel = scCombo.SelectedIndex; if (sel < 0 || sel >= scIds.Count) return; engine.SetDeviceSidechainSource(track, di, scIds[sel]); Inactive.Set(targetGroup, scIds[sel] >= 0, interactive: true); };- Inactive.Set(targetGroup, engine.DeviceSidechainSource(track, di) >= 0, interactive: true);-- var match = new Border { Background = Amber, CornerRadius = NotaRadius.Control, Padding = new Thickness(12, 3), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,- Child = new TextBlock { Text = "MATCH", FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextOnAccent } };- match.PointerPressed += (_, e) => { e.Handled = true; SetP(Auto, 0f); foreach (var a in readouts) a(); }; // freeze the current correction-- 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 = {- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center, Children = {- Cap("LIVE"), targetGroup,- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("SCALE"), Seg(Scale, new[] { "Mom", "Short", "Integ" }, after: hist.Tick) } } } }, Dock.Left),- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = {- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("REF", TealC), scCombo } },- match, Toggle(Auto, "AUTO") } }, Dock.Right) } } };-- // ================= CORRECTION column =================- var applied = new TextBlock { Text = "0.0", FontSize = 22, FontWeight = FontWeight.SemiBold, Foreground = TealBright, LineHeight = 22 };- applied.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- // vertical boost/cut indicator (0 dB at centre)- var bar = new Border { Width = 8, Background = Inset, CornerRadius = NotaRadius.Control, VerticalAlignment = VerticalAlignment.Stretch };- var barCenter = new Border { Height = 1, Background = Dim, VerticalAlignment = VerticalAlignment.Center };- var barFill = new Border { Width = 8, Background = TealC, CornerRadius = NotaRadius.Control, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Height = 0 };- var barMarker = new Border { Width = 16, Height = 3, Background = TealBright, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top };- var barSlot = new Panel { Width = 30, Children = { new Border { Width = 8, HorizontalAlignment = HorizontalAlignment.Center, Child = bar }, barCenter, barFill, barMarker } };-- var correction = new DockPanel { LastChildFill = true, Margin = new Thickness(9, 7) };- correction.AddDock(new Grid { Height = 10, ColumnDefinitions = new ColumnDefinitions("*,Auto"), Children = { Cap("CORRECTION"), WithCol(new TextBlock { Text = "auto", FontSize = 8, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Right }, 1) } }, Dock.Top);- correction.AddDock(new Border { Margin = new Thickness(0, 5), Child = Seg(Auto, new[] { "Manual", "Auto" }) }, Dock.Top); // Manual=0, Auto=1- // trim at bottom- correction.AddDock(new Grid { Height = 12, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Margin = new Thickness(0, 5, 0, 0), Children = {- Cap("TRIM", MutedC, 30), WithCol(HRow(Trim, "", TrimF, 0, 0, bipolar: true), 1), WithCol(new TextBlock().WithMono(), 2) } }, Dock.Bottom);- // centre: indicator + number- var numCol = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Spacing = 1, Children = {- applied, new TextBlock { Text = "dB applied", FontSize = 9, Foreground = MutedC }.WithMono(),- new Border { Height = 8 },- new TextBlock { Text = "boost +12", FontSize = 8, Foreground = NotaPalette.TextDisabled }.WithMono(),- new TextBlock { Text = "0\u2009dB", FontSize = 8, Foreground = NotaPalette.TextDisabled }.WithMono(),- new TextBlock { Text = "cut −12", FontSize = 8, Foreground = NotaPalette.TextDisabled }.WithMono() } };- correction.Children.Add(new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 9, Children = { barSlot, WithCol(numCol, 1) } });- var corrPanel = new Border { Width = 206, Child = correction };-- // ================= middle graph + stats =================- var stats = new TextBlock { FontSize = 8, Foreground = NotaPalette.TextDisabled, HorizontalAlignment = HorizontalAlignment.Center }.WithMono();- var mid = new DockPanel { LastChildFill = true, Margin = new Thickness(0, 7, 8, 7) };- mid.AddDock(new Border { Height = 12, Child = stats, [DockPanel.DockProperty] = Dock.Bottom }, Dock.Bottom);- mid.Children.Add(new Border { Child = hist });-- // ================= METERS + RESPONSE rail =================- Control Meter(string label, out Action<float, string> set, IBrush baseCol, bool centered = false)- {- var val = new TextBlock { FontSize = 9, Foreground = LabelC, Width = 40, TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center }.WithMono();- var fill = new Border { Background = baseCol, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch };- var center = centered ? new Border { Width = 1, Background = Dim, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch } : null;- var trk = new Panel { Height = 5, Children = { } }; trk.Children.Add(new Border { Background = Inset, CornerRadius = NotaRadius.Clip }); if (center != null) trk.Children.Add(center); trk.Children.Add(fill);- set = (frac, text) => { double W = trk.Bounds.Width; if (centered) { double c = W * 0.5; double x = frac * c; fill.HorizontalAlignment = HorizontalAlignment.Left; fill.Margin = new Thickness(x >= 0 ? c : c + x, 0, 0, 0); fill.Width = Math.Abs(x); } else fill.Width = Math.Clamp(frac, 0, 1) * W; val.Text = text; };- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("22,*,Auto"), ColumnSpacing = 5, Height = 6, VerticalAlignment = VerticalAlignment.Center };- g.Children.Add(Cap(label)); Grid.SetColumn(trk, 1); g.Children.Add(trk); Grid.SetColumn(val, 2); g.Children.Add(val);- return g;++ // ======================================================================+ // LEFT — correction+ // ======================================================================+ var modeSeg = Seg(new[] { "Manual", "Auto" }, () => Manual() ? 0 : 1, i =>+ {+ if (i == 0 && !Manual())+ {+ // Hand over: Manual starts from the gain Auto was riding.+ double g = Math.Round(Math.Clamp(Sc(S_Level), -MaxG(), MaxG()) * 10) / 10;+ SetP(Gain, GainNorm(g));+ SetP(Auto, 0);+ }+ else if (i == 1) SetP(Auto, 1);+ }, Auto, "Auto rides the gain to the target over Window; Manual holds the fader where you put it (Match sets it to the distance to the target)", 84);+ var corrHead = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ corrHead.Children.Add(Caps("CORRECTION")); corrHead.Children.Add(Col(modeSeg, 1));++ var fader = new LvGainFader { Value = () => GainDb(P(Gain)), VerticalAlignment = VerticalAlignment.Stretch };+ fader.GestureBegin += () => Begin(Gain);+ fader.GestureEnd += () => End(Gain);+ fader.Changed += db => { Raw(Gain, GainNorm(db)); RefreshAll(); };+ fader.ResetRequested += () => { Reset(Gain); RefreshAll(); };+ Learn(fader, Gain);+ ToolTip.SetTip(fader, "The correction around 0\u2009dB, ±Max Gain. In Manual drag it (Shift for fine steps); double-click resets to 0\u2009dB. In Auto it shows the ride");++ var maxTop = Mono("", 7, TextDisabled);+ var modeTag = Mono("", 7, TextDisabled);+ var maxBot = Mono("", 7, TextDisabled);+ var big = Mono("", 26, AccentBright); big.FontWeight = FontWeight.Bold; big.LineHeight = 28; big.LetterSpacing = -0.5;+ var bigSub = new TextBlock { Text = "dB applied", FontSize = 8, Foreground = TextSecondary };+ var reason = Mono("", 7, TextTertiary); reason.Margin = new Thickness(0, 2, 0, 0);+ var matchTxt = new TextBlock { FontSize = 8, FontWeight = FontWeight.Bold, LetterSpacing = 0.5, Foreground = OnAccent };+ var match = new Border+ {+ Background = Brass, CornerRadius = NotaRadius.Badge, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand),+ VerticalAlignment = VerticalAlignment.Bottom, Child = matchTxt,+ };+ match.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(match).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ if (Manual())+ {+ if (!Primed()) return;+ double want = Math.Clamp(Sc(S_Target) - Sc(S_Measured) - TrimDb(P(Trim)), -MaxG(), MaxG());+ SetP(Gain, GainNorm(Math.Round(want * 10) / 10));+ }+ else engine.DeviceAction(track, di, 0, 0, 0);+ RefreshAll();+ };+ readouts.Add(() =>+ {+ matchTxt.Text = Manual() ? "MATCH" : "RESET";+ ToolTip.SetTip(match, Manual()+ ? "Match — set the manual gain to the distance between the measured input and the target"+ : "Reset — restart the measurement from the loudness now, so the ride catches up at once");+ });++ var topLine = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ topLine.Children.Add(maxTop); topLine.Children.Add(Col(modeTag, 1));+ var botLine = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), VerticalAlignment = VerticalAlignment.Bottom };+ botLine.Children.Add(maxBot); botLine.Children.Add(Col(match, 1));+ maxBot.VerticalAlignment = VerticalAlignment.Bottom;+ var numCol = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto") };+ numCol.Children.Add(GRow(topLine, 0));+ numCol.Children.Add(GRow(new StackPanel { Spacing = 1, Children = { big, bigSub, reason } }, 2));+ numCol.Children.Add(GRow(botLine, 4));+ var gainArea = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 9 };+ gainArea.Children.Add(fader); gainArea.Children.Add(Col(numCol, 1));++ var targetRow = Slider("TARGET", Target, TargetF,+ "Target loudness, −36 … 0 LUFS. Click the value for the standards or to match another track's loudness (a reference); drag the dashed line in the graph for the same",+ 38, 50, dim: HasRef,+ valueOverride: () => HasRef() ? ("REF " + TrackName(Ref()), TextSecondary) : ("", null),+ valueClick: TargetMenu);+ var trimRow = Slider("TRIM", Trim, TrimF, "Trim — a fixed offset after the correction, −12 … +12\u2009dB (the output then sits that far off the target)", 38, 50, bipolar: true);++ var leftBody = new DockPanel { Margin = new Thickness(8, 6), LastChildFill = true };+ leftBody.Children.Add(Docked(new StackPanel { Spacing = 5, Margin = new Thickness(0, 6, 0, 0), Children = { targetRow, trimRow } }, Dock.Bottom));+ leftBody.Children.Add(gainArea);+ var left = Island(new DockPanel { Children = { Docked(Bar(corrHead, new Thickness(8, 0, 3, 0)), Dock.Top), leftBody } }, 176);+ DockPanel.SetDock(left, Dock.Left);++ // ======================================================================+ // CENTRE — scale + loudness history+ // ======================================================================+ var scaleSeg = Seg(ScaleNames, () => ScaleIndex(P(Scale)), i => SetP(Scale, i / 2.0), Scale,+ "Scale — what the correction reads: Momentary (400\u2009ms, fast and nervous), Short-term (3\u2009s) or Integrated (12\u2009s with BS.1770 gating, the steadiest)", 118);+ var legend = new LvLegend { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };+ var centreHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 8 };+ centreHead.Children.Add(Caps("SCALE")); centreHead.Children.Add(Col(scaleSeg, 1)); centreHead.Children.Add(Col(legend, 2));++ var hist = new LvHistoryView { Value = () => P(Target) };+ hist.GestureBegin += () => Begin(Target);+ hist.GestureEnd += () => End(Target);+ hist.Changed += v => { Raw(Target, v); RefreshAll(); };+ hist.ResetRequested += () => { Reset(Target); RefreshAll(); };+ Learn(hist, Target);+ ToolTip.SetTip(hist, "The last 8\u2009s: input, output and the target with its ±1\u2009LU band (momentary loudness). Drag up / down to move the target; double-click resets it");++ IBrush Dim() => TextDisabled;+ var rIn = Mono("", 8, TextSecondary); var rOut = Mono("", 8, AccentBright); var rDelta = Mono("", 8, TextSecondary); var rTp = Mono("", 8, TextSecondary);+ var readRow = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 8, Height = 14, HorizontalAlignment = HorizontalAlignment.Center,+ Children = { rIn, Mono("·", 8, Dim()), rOut, Mono("·", 8, Dim()), rDelta, Mono("·", 8, Dim()), rTp },+ };+ var centreBody = new DockPanel { Margin = new Thickness(5), LastChildFill = true };+ centreBody.Children.Add(Docked(new Border { Margin = new Thickness(0, 4, 0, 0), Child = readRow }, Dock.Bottom));+ centreBody.Children.Add(hist);+ var centre = Island(new DockPanel { Children = { Docked(Bar(centreHead, new Thickness(6, 0)), Dock.Top), centreBody } });+ centre.Margin = new Thickness(5, 0);++ // ======================================================================+ // RIGHT — meters, response, true-peak safe+ // ======================================================================+ var scaleName = Mono("", 7, TextTertiary);+ var metersHead = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ metersHead.Children.Add(Caps("METERS")); metersHead.Children.Add(Col(scaleName, 1));++ (Control Row, LvMeter M, TextBlock V) MeterRow(string label, string tip)+ {+ var m = new LvMeter { VerticalAlignment = VerticalAlignment.Center };+ var v = Mono("", 8, TextPrimary); v.TextAlignment = TextAlignment.Right; v.HorizontalAlignment = HorizontalAlignment.Right;+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("24,*,34"), ColumnSpacing = 6, Background = Brushes.Transparent };+ var l = Caps(label); l.LetterSpacing = 0.4;+ g.Children.Add(l); g.Children.Add(Col(m, 1)); g.Children.Add(Col(v, 2));+ ToolTip.SetTip(g, tip);+ return (g, m, v);}- var inRow = Meter("IN", out var setIn, Green); var outRow = Meter("OUT", out var setOut, Green);- var tpRow = Meter("TP", out var setTp, Green); var corRow = Meter("COR", out var setCor, Green, centered: true);-- var rail = new Border { Width = 184, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 7),- Child = new StackPanel { Spacing = 5, Children = {- Cap("METERS"), inRow, outRow, tpRow, corRow,- new Border { Height = 1, Background = NotaPalette.SurfaceRaised, Margin = new Thickness(0, 1) },- new Border { BorderBrush = TealC, BorderThickness = new Thickness(2, 0, 0, 0), Padding = new Thickness(7, 0, 0, 0), Child =- new StackPanel { Spacing = 5, Children = {- Cap("RESPONSE", TealC),- Seg(Response, new[] { "Fast", "Slow" }, teal: true),- HRow(Window, "WINDOW", WindowF, 52, 30, teal: true),- HRow(MaxGain, "MAX GAIN", MaxF, 52, 24, teal: true),- Toggle(Safe, "TRUE-PEAK SAFE") } } } } } };-- // ================= assemble =================- DockPanel.SetDock(corrPanel, Dock.Left); DockPanel.SetDock(rail, Dock.Right);- var body = new DockPanel { LastChildFill = true, Children = { corrPanel, rail, mid } };- DockPanel.SetDock(live, Dock.Top);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };-- // ---- live refresh from scope ----- float MeterFrac(float lufs) => (float)Math.Clamp((lufs + 40) / 40.0, 0, 1); // −40..0+ var mIn = MeterRow("IN", "Input loudness on the chosen scale (LUFS); the teal mark is the target");+ var mOut = MeterRow("OUT", "Output loudness on the chosen scale (LUFS); the teal mark is the target");+ var mTp = MeterRow("TP", "Output true peak (dBTP); the teal mark is the ceiling while True-peak safe is on");+ var mCor = MeterRow("COR", "The correction applied, ±Max Gain around 0\u2009dB (trim not included)");++ var respSeg = Seg(new[] { "Fast", "Slow" }, () => On(Response) ? 1 : 0, i => SetP(Response, i), Response,+ "Response — Slow glides over the whole Window with a 20\u2009ms look-ahead; Fast over a quarter of it with 5\u2009ms", 76);+ var respRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ respRow.Children.Add(Caps("RESPONSE", Teal)); respRow.Children.Add(Col(respSeg, 1));+ var winRow = Slider("WINDOW", WindowP, WindowF, "Window — how long the ride takes to reach the target, 0.4 … 10\u2009s (Fast: a quarter of it)", 48, 36);+ var maxRow = Slider("MAX GAIN", MaxGain, MaxF, "Max gain — the most the correction may boost or cut, 0 … 24\u2009dB", 48, 36);++ var safeSw = Switch("True-peak safe", () => On(Safe), () => { SetP(Safe, On(Safe) ? 0 : 1); RefreshAll(); }, out var safeSync);+ readouts.Add(safeSync);+ Learn(safeSw, Safe);+ ToolTip.SetTip(safeSw, "True-peak safe — a look-ahead limiter keeps the output under the ceiling (adds 5 / 20\u2009ms of latency, compensated)");+ var ceilTxt = Mono("", 8, TextPrimary);+ var ceilBox = new Border+ {+ Background = Sunken, CornerRadius = NotaRadius.Clip, Padding = new Thickness(3, 0), VerticalAlignment = VerticalAlignment.Center,+ Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Child = ceilTxt,+ };+ bool cd = false; double cy0 = 0, cv0 = 0;+ ceilBox.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(ceilBox).Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2) { Reset(Ceiling); RefreshAll(); e.Handled = true; return; }+ cd = true; cy0 = e.GetPosition(ceilBox).Y; cv0 = P(Ceiling); Begin(Ceiling); e.Pointer.Capture(ceilBox); e.Handled = true;+ };+ ceilBox.PointerMoved += (_, e) =>+ {+ if (!cd) return;+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;+ double v = cv0 + (cy0 - e.GetPosition(ceilBox).Y) / 140.0 * (fine ? 0.1 : 1);+ Raw(Ceiling, Math.Round(Math.Clamp(v, 0, 1) * 60) / 60); // 0.1 dB steps+ RefreshAll();+ };+ ceilBox.PointerReleased += (_, e) => { if (cd) { cd = false; End(Ceiling); e.Pointer.Capture(null); } };+ Learn(ceilBox, Ceiling);+ ToolTip.SetTip(ceilBox, "Ceiling, −6 … 0\u2009dBTP — drag up / down (Shift for fine steps), double-click resets to −1.0");readouts.Add(() =>{- int n = engine.DeviceScope(track, di, scope, kScope);- if (n < kScope) return;- float ap = scope[S_Applied];- applied.Text = $"{ap:+0.0;−0.0;0.0}";- bool boost = ap >= 0;- applied.Foreground = boost ? TealBright : AmberLit;- // indicator: marker + fill from centre- double H = bar.Bounds.Height; double frac = Math.Clamp((12 - ap) / 24.0, 0, 1);- barMarker.Margin = new Thickness(0, Math.Clamp(frac * H - 1.5, 0, Math.Max(0, H - 3)), 0, 0);- double half = H * 0.5; double mag = Math.Clamp(Math.Abs(ap) / 12.0, 0, 1) * half;- barFill.Background = boost ? TealC : Amber;- barFill.Height = mag; barFill.VerticalAlignment = VerticalAlignment.Center;- barFill.Margin = boost ? new Thickness(0, 0, 0, mag) : new Thickness(0, mag, 0, 0);- setIn(MeterFrac(scope[S_InLufs]), $"{scope[S_InLufs]:0.0}");- setOut(MeterFrac(scope[S_OutLufs]), $"{scope[S_OutLufs]:0.0}");- setTp(MeterFrac(scope[S_TruePeak]), $"{scope[S_TruePeak]:0.0}");- setCor(scope[S_Corr], $"{scope[S_Corr]:+0.00;−0.00;0.00}");- stats.Text = $"IN {scope[S_InLufs]:0.0} · OUT {scope[S_OutLufs]:0.0} · Δ {scope[S_OutLufs] - scope[S_InLufs]:+0.0;−0.0;0.0}\u2009LUFS · TP {scope[S_TruePeak]:0.0}\u2009dB";+ ceilTxt.Text = NotaNum.F($"{CeilingDb(P(Ceiling)):0.0;−0.0;0.0}\u2009dBTP");+ ceilTxt.Foreground = !On(Safe) ? TextDisabled : Math.Abs(P(Ceiling) - Def(Ceiling)) > 0.003 ? AccentBright : TextPrimary;});+ var safeRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ safeRow.Children.Add(safeSw); safeRow.Children.Add(Col(ceilBox, 1));- void RefreshAll() { foreach (var a in readouts) a(); }- RefreshAll();- return root;- }+ var rightBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto,*,Auto,*,Auto,Auto,Auto,*,Auto"), Margin = new Thickness(8, 6) };+ rightBody.Children.Add(GRow(mIn.Row, 0));+ rightBody.Children.Add(GRow(mOut.Row, 2));+ rightBody.Children.Add(GRow(mTp.Row, 4));+ rightBody.Children.Add(GRow(mCor.Row, 6));+ rightBody.Children.Add(GRow(Rule(respRow), 8));+ rightBody.Children.Add(GRow(new Border { Margin = new Thickness(0, 4, 0, 0), Child = winRow }, 9));+ rightBody.Children.Add(GRow(new Border { Margin = new Thickness(0, 3, 0, 0), Child = maxRow }, 10));+ rightBody.Children.Add(GRow(Rule(safeRow), 12));+ var right = Island(new DockPanel { Children = { Docked(Bar(metersHead, new Thickness(8, 0)), Dock.Top), rightBody } }, 176);+ DockPanel.SetDock(right, Dock.Right);- 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; }-}+ // ======================================================================+ // Status strip+ // ======================================================================+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusRight = Mono("", 8, TextSecondary);+ 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);+ ToolTip.SetTip(statusLeft, "What the leveler is doing now");-internal static class AutoGainExt-{- public static TextBlock WithMono(this TextBlock t) { t.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return t; }+ // ---- live state ---------------------------------------------------------------------+ static double MeterX(double lufs) => Math.Clamp((lufs - LevelMath.LBot) / (LevelMath.LTop - LevelMath.LBot), 0, 1);+ readouts.Add(() =>+ {+ bool on = Active(), manual = Manual(), primed = Primed(), silent = Sc(S_Silent) > 0.5;+ double maxG = MaxG(), trim = TrimDb(P(Trim));+ double level = Sc(S_Level), lim = Sc(S_LimGr), g = level - lim; // the correction as heard (no trim)+ double target = Sc(S_Target), measured = Sc(S_Measured), outMeas = Sc(S_OutMeasured), tp = Sc(S_TruePeak);+ double delta = Sc(S_Delta);+ bool locked = on && primed && Math.Abs(delta) < 1;+ bool tpOver = tp > CeilingDb(P(Ceiling)) + 0.05 && On(Safe);+ int clamp = (int)Math.Round(Sc(S_Clamp));+ bool tpClamp = on && On(Safe) && Sc(S_LimHold) > 0.3;+ if (!primed) target = HasRef() ? target : TargetLufs(P(Target));++ // Correction column.+ fader.Set(!on ? 0 : manual ? Math.Clamp(GainDb(P(Gain)), -maxG, maxG) : g, maxG, manual, on);+ maxTop.Text = NotaNum.F($"+{maxG:0}");+ maxBot.Text = NotaNum.F($"−{maxG:0}");+ modeTag.Text = manual ? "fader" : "auto";+ big.Text = on ? Sgn(g) : "off";+ big.Foreground = on ? AccentBright : TextDisabled;+ string why = !on ? "" : !primed ? "waiting for signal" : silent ? "silence · holding"+ : tpClamp ? "limited by true-peak" : clamp == 1 && !manual ? "limited by max gain" : clamp == 2 && !manual ? "limited by max cut"+ : manual ? "manual" : "auto · " + (On(Response) ? "slow" : "fast");+ reason.Text = why;+ reason.Foreground = on && (tpClamp || (clamp > 0 && !manual)) ? AccentBright : TextTertiary;++ // Graph.+ string tl = HasRef() ? "REF " + Lufs(target) : Lufs(target) + "\u2009LUFS";+ hist.SetState(on, locked, !on ? "bypass" : !primed ? "waiting" : silent ? "holding" : locked ? "locked ±1\u2009LU" : "tracking", tl, !HasRef());+ rIn.Text = "IN " + Lufs(measured);+ rOut.Text = "OUT " + Lufs(outMeas);+ rDelta.Text = "Δ " + (primed ? Sgn(delta) : "—") + "\u2009LU";+ rDelta.Foreground = locked || !primed ? TextSecondary : AccentBright;+ rTp.Text = "TP " + Lufs(tp) + "\u2009dB";+ rTp.Foreground = tpOver ? Danger : TextSecondary;++ // Meters.+ int si = ScaleIndex(P(Scale));+ scaleName.Text = ScaleLong[si];+ double tx = MeterX(target);+ mIn.M.Set(0, MeterX(measured), TextTertiary, tx); mIn.V.Text = Lufs(measured);+ mOut.M.Set(0, MeterX(outMeas), on ? Brass : TextTertiary, tx); mOut.V.Text = Lufs(outMeas);+ mOut.V.Foreground = locked || !primed ? TextPrimary : AccentBright;+ mTp.M.Set(0, MeterX(tp), tpOver ? Danger : TextSecondary, On(Safe) ? MeterX(CeilingDb(P(Ceiling))) : double.NaN);+ mTp.V.Text = Lufs(tp); mTp.V.Foreground = tpOver ? Danger : TextPrimary;+ double cf = Math.Clamp(g / Math.Max(0.01, maxG), -1, 1) / 2;+ mCor.M.Set(0.5, 0.5 + cf, Teal, 0.5); mCor.V.Text = Sgn(on ? g : 0);++ // Status.+ string foot; IBrush footInk = TextSecondary;+ double matchG = Math.Clamp(target - measured - trim, -maxG, maxG);+ if (!on) foot = "Leveler bypassed: the output equals the input";+ else if (!primed) foot = "Waiting for signal — the gain holds until the input has been measured";+ else if (silent) foot = "Input silent: the measurement and the gain hold";+ else if (manual && Math.Abs(delta) >= 1) { foot = $"Output {Sgn(delta)}\u2009LU from the target · Match sets {Sgn(matchG)}\u2009dB"; footInk = AccentBright; }+ else if (tpClamp) { foot = $"True-peak limits the gain to the {NotaNum.F($"{CeilingDb(P(Ceiling)):0.0;−0.0;0.0}")}\u2009dBTP ceiling"; footInk = AccentBright; }+ else if (clamp > 0 && !manual) { foot = NotaNum.F($"Needs more than {maxG:0} dB: raise Max gain or Trim"); footInk = AccentBright; }+ else+ {+ foot = (locked ? "On target" : "Catching up") + " · " + ScaleLong[si] + " · window " + WindowF(P(WindowP));+ if (HasRef()) foot += " · matching " + TrackName(Ref());+ else if (Math.Abs(trim) > 0.05) foot += " · trim " + Sgn(trim) + "\u2009dB";+ }+ statusLeft.Text = foot; statusLeft.Foreground = footInk;+ double sr = Sc(S_SampleRate);+ string la = On(Safe) ? (On(Response) ? "look-ahead 20\u2009ms" : "look-ahead 5\u2009ms") : "look-ahead off";+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#}\u2009kHz · {ScaleNames[si].ToLowerInvariant()} · {la} · corr {Sc(S_Corr):+0.00;−0.00;0.00}") : la;+ });++ // ---- assemble ---------------------------------------------------------------+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { left, right, centre } };+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };++ // One history sample per UI tick (the graph spans N ticks ≈ 8 s); edits only repaint.+ void Tick()+ {+ scN = engine.DeviceScope(track, di, sc, kScope);+ bool on = Active();+ float tgt = Primed() || HasRef() ? (float)Sc(S_Target) : (float)TargetLufs(P(Target));+ hist.Push(on ? (float)Sc(S_InMom) : -120f, (float)(on ? Sc(S_OutMom) : Sc(S_InMom)), tgt);+ RefreshAll();+ hist.InvalidateVisual();+ }+ ctx.AddDeviceRefresher(Tick);+ Tick();+ return root;+ }}diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex 989b8297..75c4ad7f 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -1040,14 +1040,44 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsForge("Envelope Bite", FgG(9f, env: 60), FgS(1, FTape, 45));Forge("Slow Tide", FgG(9f, lfo: 40, freeHz: 0.2f), FgS(1, FTape, 50), FgS(2, FTube, 30, width: 130));- // ---- Nota AutoGain (kind 18) — loudness matching, all params normalized 0..1.- // Target 0..1 → −36..0 LUFS; Scale 0 Mom/0.5 Short/1 Integ; Response 0 Fast/1 Slow.- Fx("autogain", 18, "Stream −14 LUFS", ("Target", 0.611f), ("Scale", 0.5f), ("Response", 1f), ("Safe", 1f));- Fx("autogain", 18, "Podcast −16 LUFS", ("Target", 0.556f), ("Scale", 1f), ("Response", 1f), ("Window", 0.84f), ("Safe", 1f));- Fx("autogain", 18, "Broadcast −23 LUFS",("Target", 0.361f), ("Scale", 1f), ("Response", 1f), ("Max Gain", 0.6f), ("Safe", 1f));- Fx("autogain", 18, "Club −9 LUFS", ("Target", 0.75f), ("Scale", 0.5f), ("Response", 0f), ("Max Gain", 0.75f), ("Safe", 1f));- Fx("autogain", 18, "Fast Leveler", ("Target", 0.611f), ("Scale", 0f), ("Response", 0f), ("Max Gain", 0.5f), ("Safe", 1f));- Fx("autogain", 18, "Match Reference", ("Scale", 1f), ("Response", 1f), ("Window", 0.84f), ("Max Gain", 0.75f), ("Safe", 1f));+ // ---- Nota Level (kind 18) — loudness leveler, all params normalized 0..1 (unnamed ones reset+ // to their defaults). Written in units through Lv(): target LUFS, scale 0 Mom / 1 Short /+ // 2 Integ, fast Response, glide Window s, Max Gain dB, true-peak Safe with its Ceiling+ // dBTP, Trim dB; manual = Manual mode at Gain dB. The first six keep their names.+ Lv("Stream −14 LUFS", -14, 1);+ Lv("Podcast −16 LUFS", -16, 2);+ Lv("Broadcast −23 LUFS", -23, 2, maxG: 14.4f);+ Lv("Club −9 LUFS", -9, 1, fast: true, maxG: 18);+ Lv("Fast Leveler", -14, 0, fast: true, window: 3);+ Lv("Match Reference", -14, 2, window: 6, maxG: 18);+ // Delivery targets+ Lv("EBU R128 −23", -23, 2, window: 8);+ Lv("ATSC A/85 −24", -24, 2, window: 8, ceil: -2);+ Lv("Apple Music −16", -16, 1);+ Lv("YouTube −14", -14, 1);+ Lv("Loud Master −11", -11, 1, window: 4, ceil: -1);+ Lv("Audiobook −18 (ACX)", -18, 2, window: 8, ceil: -3);+ Lv("Cinema Dialogue −27", -27, 2, window: 10, ceil: -2);+ Lv("Game Audio −24", -24, 2, window: 8, ceil: -1);+ Lv("Radio Loud −12", -12, 1, fast: true, window: 3, maxG: 15);+ // Speech+ Lv("Voice Rider", -18, 1, fast: true, window: 4);+ Lv("Dialogue Leveler", -20, 1, fast: true, window: 3, maxG: 15);+ Lv("Interview Balance", -18, 1, window: 2, maxG: 18);+ Lv("Live Stream Rider", -16, 0, fast: true, window: 2);+ Lv("Quiet Source Boost", -14, 1, fast: true, window: 1.5f, maxG: 18);+ // Music and mixing+ Lv("Gentle Rider", -16, 2, window: 10, maxG: 6);+ Lv("Tight Rider", -14, 0, fast: true, window: 1, maxG: 12);+ Lv("Gain Staging −18", -18, 1, maxG: 24, safe: false);+ Lv("Mix Bus −20", -20, 1, window: 8, safe: false);+ Lv("Mastering Prep −18", -18, 2, window: 10, ceil: -3);+ Lv("Music Bed −28", -28, 1, window: 6, maxG: 18);+ Lv("Sample Normalizer −12", -12, 0, fast: true, window: 0.5f, maxG: 24);+ Lv("Match Reference Fast", -14, 1, fast: true, window: 2, maxG: 18);+ // Static+ Lv("True-Peak Guard", -14, 1, manual: 0, ceil: -1);+ Lv("Static Boost +6", -14, 1, manual: 6, maxG: 12, ceil: -1);// ---- Nota Shutter (kind 19) — noise gate / ducker, all params normalized 0..1 (unnamed ones// reset to their defaults). Threshold −70 + 70v dB (.286 = −50, .357 = −45, .4 = −42,@@ -1992,6 +2022,20 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsprivate void Fx(string group, int kind, string name, params (string Name, float Value)[] ps)=> Add(group, name, "builtin-effect", kind, isInstrument: false, isMidi: false, ps);+ // Nota Level in units → normalized pairs (see the Level block above).+ private void Lv(string name, float targetLufs, int scale, bool fast = false, float window = 6, float maxG = 12, bool safe = true,+ float ceil = -1, float trim = 0, float? manual = null)+ {+ var ps = new List<(string, float)>+ {+ ("Target", Math.Clamp((targetLufs + 36f) / 36f, 0f, 1f)), ("Scale", scale / 2f), ("Response", fast ? 0f : 1f),+ ("Window", (float)(Math.Log(Math.Clamp(window, 0.4f, 10f) / 0.4) / Math.Log(25))), ("Max Gain", maxG / 24f),+ ("Safe", safe ? 1f : 0f), ("Ceiling", (ceil + 6f) / 6f), ("Trim", 0.5f + trim / 24f),+ ("Auto", manual is null ? 1f : 0f), ("Gain", 0.5f + (manual ?? 0f) / 48f),+ };+ Fx("autogain", 18, name, ps.ToArray());+ }+// Nota Forge stage types (the S* Type step, × 1/5).private const int FTube = 0, FDiode = 1, FTape = 2, FFuzz = 3, FDigital = 4, FFold = 5;diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.csindex a3af6b95..00305aca 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 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. Nota Orbit (kind 9): id 0 = a one-line summary (waveform, free rate in Hz or the Sync division, shape / glide, phase with the mode it makes — tremolo, auto-pan or offset pan — amount, mix), 1 = the live reading (the LFO rate and period, locked to the song or free-running, its place in the two-cycle window, the L / R gain now, the pan and its swing, the floor, in / out levels, tempo and bar, CPU), 2 = a guide to what each 0..1 parameter value means incl. the Division table — or use read_orbit for the numbers. Nota EQ-3 (kind 16): id 0 = a one-line summary (slope, the two crossovers, each band's gain or kill, the fader range, output), 1 = the live reading (in / out peaks, each band's level after its gain and the gain in effect now, the crossovers in use, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_eq3 for the numbers and set_eq3 to play it in dB and Hz. Nota Forge (kind 17): id 0 = a one-line summary (routing, amount, wet, output, each stage on with its type, role, drive, out, feedback, bias, tone and width, the LFO → drive with its rate, env → tone, the master tone / bias / width offsets when set, oversampling and an aliasing warning), 1 = the live reading (in / out peak and RMS, THD of a −6 dB sine through the device and through each stage with its flavour, the LFO value, drive offset and rate, the envelope, the master tilt now, oversampling, latency, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_forge for the numbers and the curve, set_forge and set_forge_stage to play it in units. Nota EQ-8 (kind 0): id 0 = a one-line summary (bands on, scale, each band on with its type, frequency, gain, Q, slope for the cuts and channel when not stereo, output, auto gain, analyzer), 1 = the live reading (in / out peaks, the auto gain in effect, CPU), 2 = a guide to the parameter layout and units — or use read_eq8 for the numbers, set_eq8_band to edit a band and set_eq8 for the globals.")]+ [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. Nota Orbit (kind 9): id 0 = a one-line summary (waveform, free rate in Hz or the Sync division, shape / glide, phase with the mode it makes — tremolo, auto-pan or offset pan — amount, mix), 1 = the live reading (the LFO rate and period, locked to the song or free-running, its place in the two-cycle window, the L / R gain now, the pan and its swing, the floor, in / out levels, tempo and bar, CPU), 2 = a guide to what each 0..1 parameter value means incl. the Division table — or use read_orbit for the numbers. Nota EQ-3 (kind 16): id 0 = a one-line summary (slope, the two crossovers, each band's gain or kill, the fader range, output), 1 = the live reading (in / out peaks, each band's level after its gain and the gain in effect now, the crossovers in use, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_eq3 for the numbers and set_eq3 to play it in dB and Hz. Nota Forge (kind 17): id 0 = a one-line summary (routing, amount, wet, output, each stage on with its type, role, drive, out, feedback, bias, tone and width, the LFO → drive with its rate, env → tone, the master tone / bias / width offsets when set, oversampling and an aliasing warning), 1 = the live reading (in / out peak and RMS, THD of a −6 dB sine through the device and through each stage with its flavour, the LFO value, drive offset and rate, the envelope, the master tilt now, oversampling, latency, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_forge for the numbers and the curve, set_forge and set_forge_stage to play it in units. Nota Level (kind 18): id 0 = a one-line summary (the target or the reference track, scale, auto with its glide or manual with its gain, max gain, trim, true-peak safe with the ceiling and look-ahead), 1 = the live reading (state, input and output loudness on the scale, momentary and short-term, the target in effect, the distance to it, the correction, gain applied and wanted, limiter reduction, true peak, correlation, latency), 2 = a guide to what each 0..1 parameter value means — or use read_level for the numbers and set_level to play it in LUFS and dB. Nota EQ-8 (kind 0): id 0 = a one-line summary (bands on, scale, each band on with its type, frequency, gain, Q, slope for the cuts and channel when not stereo, output, auto gain, analyzer), 1 = the live reading (in / out peaks, the auto gain in effect, CPU), 2 = a guide to the parameter layout and units — or use read_eq8 for the numbers, set_eq8_band to edit a band and set_eq8 for the globals.")]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. Nota Crush (kind 12): id 0 resets the meters (the peak holds and the spectrum average). Nota Orbit (kind 9): id 0 restarts the LFO (free run: from phase 0; with Sync on and the transport playing it stays locked to the bar), id 1 resets the meters. Nota EQ-3 (kind 16): id 0 resets the meters (the peaks and the spectrum average). Nota Forge (kind 17): id 0 restarts the LFO (free run: from phase 0) and resets the meters. Nota EQ-8 (kind 0): id 0 resets the meters (the peaks and the spectrum averages). 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). Nota Orbit (kind 9): id 0 restarts the LFO (free run: from phase 0; with Sync on and the transport playing it stays locked to the bar), id 1 resets the meters. Nota EQ-3 (kind 16): id 0 resets the meters (the peaks and the spectrum average). Nota Forge (kind 17): id 0 restarts the LFO (free run: from phase 0) and resets the meters. Nota Level (kind 18): id 0 restarts the measurement from the loudness now (RESET — the ride catches up at once), id 1 is MATCH (switches to Manual with the gain set to the distance to the target; see level_match). Nota EQ-8 (kind 0): id 0 resets the meters (the peaks and the spectrum averages). 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));@@ -678,6 +678,125 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, Ireturn ForgeRead(trackId, deviceIndex);});+ public sealed record LevelReading(string Summary, string Live, string Mode, string State, double TargetLufs, string Reference,+ string Scale, string Response, double WindowSeconds, double GlideSeconds, double MaxGainDb, double TrimDb, double ManualGainDb,+ bool TruePeakSafe, double CeilingDbtp, double InputLufs, double OutputLufs, double InputMomentaryLufs, double OutputMomentaryLufs,+ double InputShortTermLufs, double OutputShortTermLufs, double TargetInEffectLufs, double DeltaLu, double CorrectionDb,+ double AppliedDb, double WantedDb, double LimiterDb, double TruePeakDbtp, double Correlation, string HeldBy, bool Primed,+ bool Silent, int LatencySamples, double SampleRate);++ private static readonly string[] LevelScales = { "Momentary", "ShortTerm", "Integrated" };++ [McpServerTool(Name = "read_level"), Description(+ "Read a Nota Level (built-in effect kind 18 — loudness leveler): the mode (Auto rides the gain to the target over the "+ + "glide; Manual holds ManualGainDb), its state (waiting for signal / silent, holding / on target within ±1 LU / tracking / "+ + "manual / held at ±max gain), the target (LUFS, or the reference track's loudness when one is routed as its sidechain), "+ + "the scale the correction reads (Momentary 400 ms / ShortTerm 3 s / Integrated 12 s with BS.1770 gating), Response, "+ + "Window and the glide it gives, Max Gain, Trim, True-peak safe with its ceiling, and the live numbers: input and output "+ + "loudness on the scale plus momentary and short-term, the distance to the target, the correction, the gain applied "+ + "(correction + trim − limiter), the limiter's reduction, true peak, correlation, what holds the gain (max gain, max cut, "+ + "true-peak), look-ahead latency. LUFS read −120 until measured; they move only while audio plays through the track.")]+ public Task<LevelReading> ReadLevel(int trackId, int deviceIndex) => Read(() => LevelRead(trackId, deviceIndex));++ private LevelReading LevelRead(int trackId, int deviceIndex)+ {+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 18) throw new ArgumentException("not a Nota Level (kind 18)");+ var sc = new float[21];+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);+ float V(int i) => n > i ? sc[i] : 0f;+ float L(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) : 0.5f;+ bool auto = Pm(2) >= 0.5f, fast = Pm(4) < 0.5f, primed = V(18) > 0.5f, silent = V(15) > 0.5f;+ int scale = Math.Clamp((int)Math.Round(Pm(1) * 2), 0, 2);+ double window = 0.4 * Math.Pow(25, Pm(5)), maxG = Pm(6) * 24;+ int clamp = (int)Math.Round(V(14));+ string held = V(20) > 0.3f && Pm(7) >= 0.5f ? "true-peak" : clamp == 1 ? "max gain" : clamp == 2 ? "max cut" : "";+ string state = !primed ? "waiting for signal" : silent ? "silent, holding" : !auto ? "manual"+ : clamp == 1 ? "held at +max gain" : clamp == 2 ? "held at -max gain" : Math.Abs(V(19)) < 1 ? "on target" : "tracking";+ int src = E.DeviceSidechainSource(trackId, deviceIndex);+ string reference = src >= 0 ? $"track {src}" + (E.GetTrackName(src) is { Length: > 0 } nm ? $" ({nm})" : "") : "none";+ return new LevelReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1), auto ? "Auto" : "Manual", state,+ R1(-36 + Pm(0) * 36), reference, LevelScales[scale], fast ? "Fast" : "Slow", Math.Round(window, 2), Math.Round(window * (fast ? 0.25 : 1), 2),+ R1(maxG), R1((Pm(3) - 0.5) * 24), R1((Pm(9) - 0.5) * 48), Pm(7) >= 0.5f, R1(-6 + Pm(8) * 6),+ R1(L(9)), R1(L(10)), R1(L(2)), R1(L(11)), R1(L(0)), R1(L(1)), R1(L(3)), R1(V(19)), R1(V(12)), R1(V(4)), R1(V(8)), R1(V(13)),+ R1(L(5)), Math.Round(V(6), 2), held, primed, silent, (int)V(16), V(17));+ }++ [McpServerTool(Name = "set_level"), Description(+ "Play a Nota Level (built-in effect kind 18) in units — only the fields you pass change; each change is recorded like a hand "+ + "edit (so it lands in automation while recording). mode \"Auto\" | \"Manual\" (switching to Manual keeps the gain Auto was "+ + "riding); targetLufs −36..0 (−14 streaming, −16 podcast, −23 EBU R128, −24 ATSC); scale \"Momentary\" | \"ShortTerm\" | "+ + "\"Integrated\"; response \"Fast\" | \"Slow\" (Fast glides over a quarter of Window with a 5 ms look-ahead, Slow over all "+ + "of it with 20 ms); windowSeconds 0.4..10; maxGainDb 0..24; trimDb ±12; manualGainDb ±24 (limited to ±max gain; implies "+ + "nothing about mode); truePeakSafe; ceilingDbtp −6..0; referenceTrackId — a track whose loudness becomes the target "+ + "(−1 = none, the fixed target). Returns the device as read back.")]+ public Task<LevelReading> SetLevel(int trackId, int deviceIndex, string? mode = null, double? targetLufs = null, string? scale = null,+ string? response = null, double? windowSeconds = null, double? maxGainDb = null, double? trimDb = null, double? manualGainDb = null,+ bool? truePeakSafe = null, double? ceilingDbtp = null, int? referenceTrackId = null) => Mutate(() =>+ {+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 18) throw new ArgumentException("not a Nota Level (kind 18)");+ void S(int p, double v) => ForgeSet(trackId, deviceIndex, p, v);+ if (targetLufs is { } t) S(0, (Math.Clamp(t, -36, 0) + 36) / 36);+ if (scale is not null)+ {+ int i = scale.Trim().ToLowerInvariant().Replace("-", "").Replace(" ", "") switch+ {+ "momentary" or "mom" => 0, "shortterm" or "short" => 1, "integrated" or "integ" => 2,+ _ => throw new ArgumentException("scale must be Momentary, ShortTerm or Integrated"),+ };+ S(1, i / 2.0);+ }+ if (response is not null)+ {+ bool f = response.Trim().ToLowerInvariant() switch+ {+ "fast" => true, "slow" => false, _ => throw new ArgumentException("response must be Fast or Slow"),+ };+ S(4, f ? 0 : 1);+ }+ if (windowSeconds is { } w) S(5, Math.Log(Math.Clamp(w, 0.4, 10) / 0.4) / Math.Log(25));+ if (maxGainDb is { } mg) S(6, Math.Clamp(mg, 0, 24) / 24);+ if (trimDb is { } tr) S(3, 0.5 + Math.Clamp(tr, -12, 12) / 24);+ if (manualGainDb is { } g) S(9, 0.5 + Math.Clamp(g, -24, 24) / 48);+ if (truePeakSafe is { } sf) S(7, sf ? 1 : 0);+ if (ceilingDbtp is { } c) S(8, (Math.Clamp(c, -6, 0) + 6) / 6);+ if (mode is not null)+ {+ bool manual = mode.Trim().ToLowerInvariant() switch+ {+ "manual" => true, "auto" => false, _ => throw new ArgumentException("mode must be Auto or Manual"),+ };+ bool wasAuto = E.DeviceGetParam(trackId, deviceIndex, 2) >= 0.5f;+ if (manual && wasAuto && manualGainDb is null)+ {+ var sc = new float[21];+ if (E.DeviceScope(trackId, deviceIndex, sc, sc.Length) > 12) S(9, 0.5 + Math.Round(sc[12], 1) / 48);+ }+ S(2, manual ? 0 : 1);+ }+ if (referenceTrackId is { } rt) E.SetDeviceSidechainSource(trackId, deviceIndex, rt < 0 ? -1 : rt);+ return LevelRead(trackId, deviceIndex);+ });++ [McpServerTool(Name = "level_match"), Description(+ "Nota Level (kind 18): switch to Manual with the gain set to the distance between the measured input and the target "+ + "(the card's MATCH) — a one-shot correction that then stays put. Needs audio to have been measured (read_level Primed). "+ + "Returns the device as read back.")]+ public Task<LevelReading> LevelMatch(int trackId, int deviceIndex) => Mutate(() =>+ {+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 18) throw new ArgumentException("not a Nota Level (kind 18)");+ var sc = new float[21];+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);+ if (n < 21 || sc[18] < 0.5f) throw new InvalidOperationException("nothing measured yet — play audio through the track first");+ double maxG = E.DeviceGetParam(trackId, deviceIndex, 6) * 24, trim = (E.DeviceGetParam(trackId, deviceIndex, 3) - 0.5) * 24;+ double want = Math.Clamp(sc[3] - sc[9] - trim, -maxG, maxG);+ ForgeSet(trackId, deviceIndex, 9, 0.5 + Math.Round(want, 1) / 48);+ ForgeSet(trackId, deviceIndex, 2, 0);+ return LevelRead(trackId, deviceIndex);+ });+public sealed record OrbitReading(string Summary, string Live, string Waveform, bool Sync, string Division, double RateHz, double PeriodMs,double ShapeOrGlide, double PhaseDeg, string Mode, double Amount, double Mix, double FloorDb, double GainLDb, double GainRDb,double Pan, double PanMin, double PanMax, double WindowPhase, bool Locked, bool Playing, double Bpm, double BarBeats,diff --git a/src/native/nota.engine/src/AutoGain.h b/src/native/nota.engine/src/AutoGain.hindex ec03ea1a..8475e8a6 100644--- a/src/native/nota.engine/src/AutoGain.h+++ b/src/native/nota.engine/src/AutoGain.h@@ -1,18 +1,34 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota AutoGain (device kind 18, mockup "Nota AutoGain") — a loudness-matching utility.-// It measures the incoming programme loudness (ITU-R BS.1770 K-weighting) and applies the-// gain needed to hit a TARGET (LUFS), so an A/B is fair and gain staging stops being a-// guess. AUTO tracks a moving window; turning AUTO off freezes the current correction-// (the card's MATCH button). A true-peak-safe stage keeps the boost from clipping.+// Nota Level (device kind 18, mockup "Nota Level") — a loudness leveler. It measures the+// incoming programme loudness (ITU-R BS.1770 K-weighting) on one of three scales and rides a+// gain so the output sits on a TARGET (LUFS), so an A/B is fair and gain staging stops being a+// guess.//-// Sidechain (added beyond the mockup): route a reference track and the target becomes that-// track's measured loudness — i.e. match THIS signal to the loudness of the reference. Uses-// the same Device sidechain plumbing as the Compressor / Ceiling.+// Scale Momentary (0.4 s) / Short-term (3 s) / Integrated (12 s, BS.1770 gating: an+// absolute −70 LUFS gate and a relative gate 10 LU under the level).+// Auto Auto rides the gain toward the target over Window (Fast = a quarter of it);+// Manual applies the Gain param (the card's fader; MATCH sets it to the distance to+// the target). Both are limited to ±Max Gain.+// Silence While the input (momentary) is too quiet to level — more than 20 LU under its own+// 12 s level, more than Max Gain + 12 LU under the target, or under −70 LUFS — the+// measurement and the gain hold, so pauses and release tails are not pumped up into+// noise. The 12 s level keeps following a lasting drop, so the hold never sticks.+// Before the first signal nothing moves.+// Safe A look-ahead true-peak limiter (5 ms on Fast, 20 ms on Slow — reported as latency+// so PDC keeps the track in time) holds the output under Ceiling (dBTP).//-// A core Device (JUCE-free); params normalized 0..1, denormalized in process(); persistence-// / automation / clone flow generically. Telemetry is published via scopeRead for the UI.+// Sidechain: route a reference track and the target becomes that track's loudness on the same+// scale — i.e. match THIS signal to the reference. Same Device sidechain plumbing as the+// Compressor / Ceiling.+//+// A core Device (JUCE-free); params normalized 0..1, denormalized in process(); persistence /+// automation / clone flow generically. Param order is the persisted layout — APPEND ONLY (Gain+// was appended by the redesign). Telemetry via scopeRead (the first nine slots keep their old+// meaning); deviceText: 0 summary, 1 live reading, 2 parameter guide; deviceAction: 0 re-seeds+// the measurement from the momentary loudness (RESET), 1 sets Gain to the distance to the+// target and switches to Manual (MATCH).#pragma once@@ -22,6 +38,9 @@#include <atomic>#include <cmath>#include <cstdint>+#include <cstdio>+#include <string>+#include <vector>namespace nota {@@ -29,154 +48,354 @@ class AutoGain : public Device {public:enum {Target = 0, // target loudness (0..1 → −36..0 LUFS)- Scale, // 0 Momentary (0.4 s) / 1 Short (Window) / 2 Integrated (slow)- Auto, // >=0.5 track continuously; else hold the current correction (MATCH)- Trim, // manual offset over the auto result (bipolar, ±12 dB)- Response, // 0 Fast / 1 Slow — how fast the correction glides- Window, // measurement window (0..1 → exp 0.4..10 s) used in Short scale+ Scale, // 0 Momentary (0.4 s) / 0.5 Short-term (3 s) / 1 Integrated (12 s, gated)+ Auto, // >= 0.5 Auto (ride to the target); else Manual (the Gain param)+ Trim, // offset after the correction (bipolar, ±12 dB)+ Response, // 0 Fast (glide = Window / 4, look-ahead 5 ms) / 1 Slow (glide = Window, 20 ms)+ Window, // correction glide time (0..1 → exp 0.4..10 s)MaxGain, // maximum |correction| (0..1 → 0..24 dB)- Safe, // >=0.5 true-peak safety limiter on the output- Ceiling, // safety ceiling (0..1 → −6..0 dBTP)+ Safe, // >= 0.5 look-ahead true-peak limiter on the output+ Ceiling, // limiter ceiling (0..1 → −6..0 dBTP)+ Gain, // manual gain (bipolar, ±24 dB, limited to ±Max Gain) — appendedkNumParams};- // Packed scope telemetry (scopeRead): instantaneous meters; the UI builds the scrolling- // loudness history and peak-holds from these.- enum { S_InLufs = 0, S_OutLufs, S_InMom, S_Target, S_Applied, S_TruePeak, S_Corr, S_ScLufs, S_Desired, kScope };+ // Packed scope telemetry (scopeRead). 0..8 are the original layout.+ enum {+ S_InLufs = 0, // input, short-term (3 s) LUFS+ S_OutLufs, // output, short-term LUFS+ S_InMom, // input, momentary LUFS+ S_Target, // the target in effect (the reference's loudness when routed)+ S_Applied, // gain applied: correction + trim − limiter (dB)+ S_TruePeak, // output true peak (dBTP, slow decay)+ S_Corr, // output L/R correlation −1..+1+ S_ScLufs, // reference loudness on the scale (−120 when none)+ S_Desired, // the correction the target asks for (clamped) + trim+ S_Measured, // input loudness on the chosen scale (gated) — what the correction reads+ S_OutMeasured, // output loudness on the chosen scale (measured + gain)+ S_OutMom, // output, momentary LUFS+ S_Level, // the correction alone (auto ride or manual gain), dB+ S_LimGr, // limiter reduction now (dB, >= 0)+ S_Clamp, // 0 none, 1 held at +Max Gain, 2 held at −Max Gain+ S_Silent, // 1 while the input is gated (silence: holding)+ S_Latency, // look-ahead latency (samples)+ S_SampleRate,+ S_Primed, // 1 once a signal has been measured+ S_Delta, // output − target (LU)+ S_LimHold, // limiter reduction, peak-held over ~1 s (dB)+ kScope+ };AutoGain() {p_[Target].store(0.611f); // −14 LUFS- p_[Scale].store(0.5f); // Short+ p_[Scale].store(0.5f); // Short-termp_[Auto].store(1.0f);p_[Trim].store(0.5f); // 0 dBp_[Response].store(1.0f); // Slow- p_[Window].store(0.626f); // ~3 s+ p_[Window].store(0.841f); // 6 sp_[MaxGain].store(0.5f); // 12 dBp_[Safe].store(1.0f);p_[Ceiling].store(0.833f); // −1 dBTP+ p_[Gain].store(0.5f); // 0 dBsetSampleRate(44100.0, 0);}void setSampleRate(double sr, int32_t /*maxBlock*/) override {sr_ = sr > 0 ? sr : 44100.0;+ srA_.store((float)sr_, std::memory_order_relaxed);computeKWeighting();kIn_[0] = kIn_[1] = kSc_[0] = kSc_[1] = kOut_[0] = kOut_[1] = KW{};- msWin_ = msScWin_ = msInShort_ = msOutShort_ = msInMom_ = 1e-7;+ msMom_ = msMomG_ = msShortG_ = msIntAbs_ = msInt_ = msShort_ = kFloor;+ msScMom_ = msScMeas_ = kFloor;+ msOutShort_ = msOutMom_ = kFloor;cLR_ = cLL_ = cRR_ = 1e-7;- appliedDb_ = 0.0f; safeEnv_ = 0.0f;- tp0_[0] = tp1_[0] = tp2_[0] = tp0_[1] = tp1_[1] = tp2_[1] = 0.0f;+ primed_ = scPrimed_ = false; sigRun_ = scRun_ = 0;+ levelDb_ = 0.0f; limGrSm_ = 0.0f; limHold_ = 0.0f; tpPk_ = 0.0f;+ for (int c = 0; c < 2; ++c) { tp0_[c] = tp1_[c] = tp2_[c] = 0.0f; ti0_[c] = ti1_[c] = ti2_[c] = 0.0f; }+ // Look-ahead buffers sized for the longest window at this rate (allocation-free after).+ wMax_ = (int)std::ceil(0.020 * sr_) + 1;+ cap_ = wMax_ + 4;+ dly_.assign((size_t)cap_ * 2, 0.0f);+ box_.assign((size_t)cap_, 1.0f);+ dqV_.assign((size_t)cap_, 1.0f);+ dqT_.assign((size_t)cap_, 0);+ curW_ = -1; // force a limiter reset on the next block+ latency_.store(0, std::memory_order_relaxed);}// Sidechain: the target may key off another track's loudness (Compressor plumbing).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 setSidechainSourceTrackId(int32_t id) override { scTrackId_.store(id, std::memory_order_relaxed); scPrimed_ = false; scRun_ = 0; }void setSidechain(const float* interleaved, int32_t frames) override { scBuf_ = interleaved; scFrames_ = frames; }bool acceptsSidechain() const override { return true; }+ // Latency follows Safe + Response (the engine recomputes PDC when a param moves it).+ int32_t latencySamples() const override { return get(Safe) >= 0.5f ? lookW() + 1 : 0; }++ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {+ if (id == 0) reseedReq_.store(true, std::memory_order_release);+ else if (id == 1 && primedA_.load(std::memory_order_relaxed)) {+ // MATCH: the gain that puts the measured input on the target (after Trim), in Manual.+ const float mg = get(MaxGain) * 24.0f;+ const float want = std::clamp(matchGainDb(), -mg, mg);+ p_[Gain].store(std::clamp(0.5f + want / 48.0f, 0.0f, 1.0f), std::memory_order_relaxed);+ p_[Auto].store(0.0f, std::memory_order_relaxed);+ }+ }++ // Gain that MATCH would set now (dB, before the ±Max Gain limit).+ float matchGainDb() const {+ return target_.load(std::memory_order_relaxed) - measured_.load(std::memory_order_relaxed) - trimDb();+ }+void process(float* buf, int32_t frames) override {- const double targetLufsP = -36.0 + (double)get(Target) * 36.0;- const int scale = std::clamp((int)std::lround(get(Scale) * 2.0f), 0, 2);+ const double targetP = -36.0 + (double)get(Target) * 36.0;+ const int scale = scaleIndex();const bool autoOn = get(Auto) >= 0.5f;- const float trimDb = (get(Trim) - 0.5f) * 24.0f;- const bool slow = get(Response) >= 0.5f;+ const float trim = trimDb();+ const bool fast = get(Response) < 0.5f;const double winSec = expMap(get(Window), 0.4, 10.0);- const float maxGainDb = get(MaxGain) * 24.0f;+ const float maxG = get(MaxGain) * 24.0f;+ const float manualDb = std::clamp((get(Gain) - 0.5f) * 48.0f, -maxG, maxG);const bool safe = get(Safe) >= 0.5f;- const float ceilLin = std::pow(10.0f, (-6.0f + get(Ceiling) * 6.0f) / 20.0f);-- // Measurement window (as a one-pole time constant) per Scale.- const double measTau = scale == 0 ? 0.4 : scale == 2 ? 10.0 : winSec;- const float measCoef = coefFor(measTau);- const float momCoef = coefFor(0.4), shortCoef = coefFor(3.0), corrCoef = coefFor(0.4);- // Gain glide + safety limiter time constants.- const float glide = coefFor(slow ? 2.0 : 0.25);- const float safeAtk = coefFor(0.002), safeRel = coefFor(0.10);+ const float ceilLin = std::pow(10.0f, ceilingDb() / 20.0f);++ const double measTau = scale == 0 ? 0.4 : scale == 1 ? 3.0 : 12.0;+ const float measC = coefFor(measTau), momC = coefFor(0.4), shortC = coefFor(3.0), corrC = coefFor(0.4);+ const float glide = coefFor(fast ? winSec * 0.25 : winSec);+ const float manGlide = coefFor(0.02);+ const float relC = coefFor(fast ? 0.06 : 0.2);+ const float holdDecay = coefFor(1.0);+ const int primeN = (int)(0.4 * sr_);+ // Hold gate: too quiet to level (see the header), as a K-weighted mean square.+ const double gateLufs = std::max(-70.0, (double)curTarget_ - maxG - 12.0);+ const double gateMs = std::pow(10.0, (gateLufs + 0.691) / 10.0);++ // Limiter window follows Safe + Response; a change restarts it (a brief gap, rare).+ const int W = safe ? lookW() : 0;+ if (W != curW_) resetLimiter(W);++ if (reseedReq_.exchange(false, std::memory_order_acq_rel)) {+ if (msMom_ > kGateMs) { msMomG_ = msShortG_ = msIntAbs_ = msInt_ = msMom_; primed_ = true; }+ if (msScMom_ > kGateMs) { msScMeas_ = msScMom_; scPrimed_ = true; }+ }const float* sc = (scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;- const bool useSc = sc != nullptr;+ const bool useSc = sc != nullptr && scTrackId_.load(std::memory_order_relaxed) >= 0;+ if (!useSc) scPrimed_ = false;- float applied = appliedDb_;+ float level = levelDb_;+ int clamp = 0;+ bool silent = false;+ float limGr = 0.0f;+ double desired = 0.0;for (int32_t i = 0; i < frames; ++i) {const float l = buf[i * 2], r = buf[i * 2 + 1];- // K-weighted input mean square (BS.1770) → measurement + display windows.+ // ---- measurement (K-weighted mean square) ----const float kl = kweight(kIn_[0], l), kr = kweight(kIn_[1], r);const double ms = (double)kl * kl + (double)kr * kr;- msWin_ += (ms - msWin_) * measCoef;- msInShort_ += (ms - msInShort_) * shortCoef;- msInMom_ += (ms - msInMom_) * momCoef;-- // Reference loudness: sidechain if routed, else the Target param.- double targetLufs = targetLufsP;+ msMom_ += (ms - msMom_) * momC;+ msShort_ += (ms - msShort_) * shortC;+ const bool audible = msMom_ >= gateMs;+ // msIntAbs_ (the 12 s level) follows everything audible, so the relative hold below+ // lets go after a lasting drop.+ if (audible && primed_) msIntAbs_ += (msMom_ - msIntAbs_) * coefInt_;+ silent = !audible || (primed_ && msMom_ < msIntAbs_ * kHoldGate);+ if (!silent) {+ if (!primed_) {+ if (++sigRun_ >= primeN) { msMomG_ = msShortG_ = msIntAbs_ = msInt_ = msMom_; primed_ = true; }+ } else {+ msMomG_ += (ms - msMomG_) * momC;+ msShortG_ += (ms - msShortG_) * shortC;+ if (msMom_ > msIntAbs_ * kRelGate) msInt_ += (msMom_ - msInt_) * coefInt_;+ }+ } else if (!audible) sigRun_ = 0;+ const double meas = scale == 0 ? msMomG_ : scale == 1 ? msShortG_ : msInt_;++ // ---- target: the param, or the reference's loudness on the same scale ----+ double targetLufs = targetP;if (useSc) {const float sl = kweight(kSc_[0], sc[i * 2]), sr2 = kweight(kSc_[1], sc[i * 2 + 1]);const double sms = (double)sl * sl + (double)sr2 * sr2;- msScWin_ += (sms - msScWin_) * measCoef;- targetLufs = lufs(msScWin_);+ msScMom_ += (sms - msScMom_) * momC;+ if (msScMom_ > kGateMs) {+ if (!scPrimed_) { if (++scRun_ >= primeN) { msScMeas_ = msScMom_; scPrimed_ = true; } }+ else msScMeas_ += (sms - msScMeas_) * measC;+ } else scRun_ = 0;+ if (scPrimed_) targetLufs = lufs(msScMeas_);}- const double inLufs = lufs(msWin_);- double desired = targetLufs - inLufs; // dB correction to hit target- desired = std::clamp(desired, -(double)maxGainDb, (double)maxGainDb);- desiredDb_ = (float)desired;-- if (autoOn) applied += (float)(desired - applied) * glide; // glide toward target- // else: hold the frozen correction (MATCH)-- const float gainDb = applied + trimDb;- const float gainLin = std::pow(10.0f, gainDb / 20.0f);-- float ol = l * gainLin, or_ = r * gainLin;-- // True-peak safety: a fast peak limiter guaranteeing |out| ≤ ceiling.- if (safe) {- const float pk = std::max(std::fabs(ol), std::fabs(or_));- if (pk > safeEnv_) safeEnv_ = pk + safeAtk * (safeEnv_ - pk);- else safeEnv_ = pk + safeRel * (safeEnv_ - pk);- if (safeEnv_ > ceilLin) { const float g = ceilLin / safeEnv_; ol *= g; or_ *= g; }+ // ---- correction ----+ desired = targetLufs - lufs(meas);+ clamp = desired > maxG ? 1 : desired < -maxG ? 2 : 0;+ desired = std::clamp(desired, -(double)maxG, (double)maxG);+ const bool hold = !primed_ || silent || (useSc && !scPrimed_);+ if (autoOn) { if (!hold) level += (float)(desired - level) * glide; }+ else level += (manualDb - level) * manGlide;+ level = std::clamp(level, -maxG, maxG);++ const float gLin = std::exp((level + trim) * kDbToLn);+ float xl = l * gLin, xr = r * gLin;++ // ---- look-ahead true-peak limiter ----+ float ol = xl, or_ = xr;+ if (W > 0) {+ // Peak of the last three samples and the 4× interpolation between the older two,+ // so the window below covers the in-between peak before it leaves the delay.+ const float pk = std::max(tpInterp(0, xl), tpInterp(1, xr));+ const float req = pk > ceilLin ? ceilLin / pk : 1.0f;+ // Sliding minimum over W samples (monotonic deque).+ while (dqN_ > 0 && dqV_[(dqH_ + dqN_ - 1) % cap_] >= req) --dqN_;+ dqV_[(dqH_ + dqN_) % cap_] = req; dqT_[(dqH_ + dqN_) % cap_] = t_; ++dqN_;+ while (dqT_[dqH_] <= t_ - W) { dqH_ = (dqH_ + 1) % cap_; --dqN_; }+ const float held = dqV_[dqH_];+ // Release upward only; attack is instant (the box below smooths it).+ env_ = held < env_ ? held : env_ + (held - env_) * relC;+ // Box average of the envelope over W: never above any req its window covers.+ boxSum_ += (double)env_ - (double)box_[boxI_];+ box_[boxI_] = env_; boxI_ = (boxI_ + 1) % W;+ const float g = (float)std::min(1.0, boxSum_ / (double)W);+ // Delay the audio by W + 1.+ const int D = W + 1;+ dly_[dW_ * 2] = xl; dly_[dW_ * 2 + 1] = xr;+ const int rd = (dW_ - D + cap_) % cap_;+ ol = dly_[rd * 2] * g; or_ = dly_[rd * 2 + 1] * g;+ dW_ = (dW_ + 1) % cap_;+ ++t_;+ limGr = std::max(0.0f, -20.0f * std::log10(std::max(1e-6f, g)));ol = std::clamp(ol, -ceilLin, ceilLin);or_ = std::clamp(or_, -ceilLin, ceilLin);}+ limGrSm_ += (limGr - limGrSm_) * measC;+ limHold_ = std::max(limGr, limHold_ + (0.0f - limHold_) * holdDecay);buf[i * 2] = ol; buf[i * 2 + 1] = or_;- // Output loudness + true peak + correlation (on what actually ships).+ // ---- output metering (what actually ships) ----const float ko = kweight(kOut_[0], ol), koR = kweight(kOut_[1], or_);- msOutShort_ += ((double)ko * ko + (double)koR * koR - msOutShort_) * shortCoef;+ const double oms = (double)ko * ko + (double)koR * koR;+ msOutShort_ += (oms - msOutShort_) * shortC;+ msOutMom_ += (oms - msOutMom_) * momC;tpPk_ = std::max(tpPk_ * 0.9995f, std::max(truePeak(0, ol), truePeak(1, or_)));- cLR_ += ((double)ol * or_ - cLR_) * corrCoef;- cLL_ += ((double)ol * ol - cLL_) * corrCoef;- cRR_ += ((double)or_ * or_ - cRR_) * corrCoef;+ cLR_ += ((double)ol * or_ - cLR_) * corrC;+ cLL_ += ((double)ol * ol - cLL_) * corrC;+ cRR_ += ((double)or_ * or_ - cRR_) * corrC;+ curTarget_ = (float)targetLufs;}- appliedDb_ = applied;+ levelDb_ = level;- // Publish meters.- inLufs_.store(lufs(msInShort_), std::memory_order_relaxed);+ // ---- publish ----+ const double meas = scale == 0 ? msMomG_ : scale == 1 ? msShortG_ : msInt_;+ const float measL = primed_ ? lufs(meas) : -120.0f;+ const float outMeas = primed_ ? measL + level + trim - limGrSm_ : -120.0f;+ inLufs_.store(lufs(msShort_), std::memory_order_relaxed);outLufs_.store(lufs(msOutShort_), std::memory_order_relaxed);- inMom_.store(lufs(msInMom_), std::memory_order_relaxed);- target_.store((float)(useSc ? lufs(msScWin_) : targetLufsP), std::memory_order_relaxed);- applied_.store(appliedDb_ + trimDb, std::memory_order_relaxed);+ inMom_.store(lufs(msMom_), std::memory_order_relaxed);+ outMom_.store(lufs(msOutMom_), std::memory_order_relaxed);+ target_.store(curTarget_, std::memory_order_relaxed);+ applied_.store(level + trim - limGr, std::memory_order_relaxed);truePeak_.store(db(tpPk_), std::memory_order_relaxed);const double corr = cLR_ / std::sqrt(std::max(1e-12, cLL_ * cRR_));corr_.store((float)std::clamp(corr, -1.0, 1.0), std::memory_order_relaxed);- scLufs_.store(useSc ? lufs(msScWin_) : -120.0f, std::memory_order_relaxed);- desired_.store(desiredDb_ + trimDb, std::memory_order_relaxed);+ scLufs_.store(useSc && scPrimed_ ? lufs(msScMeas_) : -120.0f, std::memory_order_relaxed);+ desired_.store((float)desired + trim, std::memory_order_relaxed);+ measured_.store(measL, std::memory_order_relaxed);+ outMeas_.store(outMeas, std::memory_order_relaxed);+ level_.store(level, std::memory_order_relaxed);+ limGr_.store(limGr, std::memory_order_relaxed);+ limHoldA_.store(limHold_, std::memory_order_relaxed);+ clamp_.store(autoOn ? clamp : 0, std::memory_order_relaxed);+ silent_.store(silent ? 1 : 0, std::memory_order_relaxed);+ primedA_.store(primed_ ? 1 : 0, std::memory_order_relaxed);+ latency_.store(W > 0 ? W + 1 : 0, std::memory_order_relaxed);scBuf_ = nullptr;}int32_t scopeRead(float* out, int32_t maxSamples) const override {- if (!out || maxSamples < kScope) return 0;- out[S_InLufs] = inLufs_.load(std::memory_order_relaxed);- out[S_OutLufs] = outLufs_.load(std::memory_order_relaxed);- out[S_InMom] = inMom_.load(std::memory_order_relaxed);- out[S_Target] = target_.load(std::memory_order_relaxed);- out[S_Applied] = applied_.load(std::memory_order_relaxed);- out[S_TruePeak] = truePeak_.load(std::memory_order_relaxed);- out[S_Corr] = corr_.load(std::memory_order_relaxed);- out[S_ScLufs] = scLufs_.load(std::memory_order_relaxed);- out[S_Desired] = desired_.load(std::memory_order_relaxed);- return kScope;+ if (!out || maxSamples <= 0) return 0;+ float t[kScope] = {};+ t[S_InLufs] = inLufs_.load(std::memory_order_relaxed);+ t[S_OutLufs] = outLufs_.load(std::memory_order_relaxed);+ t[S_InMom] = inMom_.load(std::memory_order_relaxed);+ t[S_Target] = target_.load(std::memory_order_relaxed);+ t[S_Applied] = applied_.load(std::memory_order_relaxed);+ t[S_TruePeak] = truePeak_.load(std::memory_order_relaxed);+ t[S_Corr] = corr_.load(std::memory_order_relaxed);+ t[S_ScLufs] = scLufs_.load(std::memory_order_relaxed);+ t[S_Desired] = desired_.load(std::memory_order_relaxed);+ t[S_Measured] = measured_.load(std::memory_order_relaxed);+ t[S_OutMeasured] = outMeas_.load(std::memory_order_relaxed);+ t[S_OutMom] = outMom_.load(std::memory_order_relaxed);+ t[S_Level] = level_.load(std::memory_order_relaxed);+ t[S_LimGr] = limGr_.load(std::memory_order_relaxed);+ t[S_Clamp] = (float)clamp_.load(std::memory_order_relaxed);+ t[S_Silent] = (float)silent_.load(std::memory_order_relaxed);+ t[S_Latency] = (float)latency_.load(std::memory_order_relaxed);+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);+ t[S_Primed] = (float)primedA_.load(std::memory_order_relaxed);+ t[S_Delta] = t[S_Primed] > 0.5f ? t[S_OutMeasured] - t[S_Target] : 0.0f;+ t[S_LimHold] = limHoldA_.load(std::memory_order_relaxed);+ const int n = std::min<int32_t>(maxSamples, kScope);+ for (int i = 0; i < n; ++i) out[i] = std::isfinite(t[i]) ? t[i] : 0.0f;+ return n;+ }++ std::string deviceText(int32_t id) const override {+ static const char* scaleNm[3] = { "momentary 400 ms", "short-term 3 s", "integrated (gated)" };+ char b[1400];+ const bool autoOn = get(Auto) >= 0.5f, safe = get(Safe) >= 0.5f, fast = get(Response) < 0.5f;+ const bool ref = scTrackId_.load(std::memory_order_relaxed) >= 0;+ if (id == 0) {+ std::string s;+ if (ref) std::snprintf(b, sizeof b, "target = the reference track (%d)", scTrackId_.load(std::memory_order_relaxed));+ else std::snprintf(b, sizeof b, "target %.1f LUFS", -36.0f + get(Target) * 36.0f);+ s += b;+ std::snprintf(b, sizeof b, " - %s - %s", scaleNm[scaleIndex()], autoOn ? "auto" : "manual");+ s += b;+ if (autoOn) std::snprintf(b, sizeof b, " (%s, glide %.1f s)", fast ? "fast" : "slow", expMap(get(Window), 0.4, 10.0) * (fast ? 0.25 : 1.0));+ else std::snprintf(b, sizeof b, " gain %+.1f dB", (get(Gain) - 0.5f) * 48.0f);+ s += b;+ std::snprintf(b, sizeof b, " - max gain %.0f dB", get(MaxGain) * 24.0f); s += b;+ if (std::fabs(trimDb()) > 0.05f) { std::snprintf(b, sizeof b, " - trim %+.1f dB", trimDb()); s += b; }+ if (safe) std::snprintf(b, sizeof b, " - true-peak safe %.1f dBTP, look-ahead %d ms", ceilingDb(), fast ? 5 : 20);+ else std::snprintf(b, sizeof b, " - true-peak safe off");+ s += b;+ return s;+ }+ if (id == 1) {+ float t[kScope];+ scopeRead(t, kScope);+ auto lv = [](float v) { char x[24]; if (v <= -119.0f) std::snprintf(x, sizeof x, "-inf"); else std::snprintf(x, sizeof x, "%.1f", v); return std::string(x); };+ const char* state = t[S_Primed] < 0.5f ? "waiting for signal"+ : t[S_Silent] > 0.5f ? "input silent, holding"+ : !autoOn ? "manual"+ : t[S_Clamp] > 0.5f ? (t[S_Clamp] < 1.5f ? "held at +max gain" : "held at -max gain")+ : std::fabs(t[S_Delta]) < 1.0f ? "on target" : "tracking";+ std::snprintf(b, sizeof b,+ "%s - in %s LUFS (%s), momentary %s, short %s - out %s LUFS, momentary %s, short %s - target %s - "+ "delta %+.1f LU - correction %+.1f dB, applied %+.1f dB (wanted %+.1f) - limiter %.1f dB (held %.1f) - "+ "true peak %s dBTP - correlation %+.2f - latency %.0f smp",+ state, lv(t[S_Measured]).c_str(), scaleNm[scaleIndex()], lv(t[S_InMom]).c_str(), lv(t[S_InLufs]).c_str(),+ lv(t[S_OutMeasured]).c_str(), lv(t[S_OutMom]).c_str(), lv(t[S_OutLufs]).c_str(), lv(t[S_Target]).c_str(),+ t[S_Delta], t[S_Level], t[S_Applied], t[S_Desired], std::max(0.0f, t[S_LimGr]), std::max(0.0f, t[S_LimHold]), lv(t[S_TruePeak]).c_str(),+ t[S_Corr], t[S_Latency]);+ return b;+ }+ if (id == 2) {+ return "All params are normalized 0..1. Target: -36..0 LUFS (v = (LUFS + 36) / 36: 0.361 = -23, 0.556 = -16, "+ "0.611 = -14, 0.75 = -9); ignored while a reference track is routed (sidechain) - then the target is that "+ "track's loudness. Scale round(v*2): 0 Momentary (0.4 s), 0.5 Short-term (3 s), 1 Integrated (12 s with "+ "BS.1770 gating). Auto >= 0.5 rides the gain to the target; below, Manual applies Gain. Trim: -12..+12 dB "+ "after the correction (0.5 = 0). Response: 0 Fast (glide = Window / 4, look-ahead 5 ms), 1 Slow (glide = "+ "Window, look-ahead 20 ms). Window: the glide time 0.4 * 25^v s (0.626 = 3 s, 0.841 = 6 s, 1 = 10 s). "+ "Max Gain: 0..24 dB (v * 24), limits the correction both ways. Safe >= 0.5: the look-ahead true-peak "+ "limiter. Ceiling: -6..0 dBTP (v * 6 - 6; 0.833 = -1). Gain: the manual gain -24..+24 dB (0.5 = 0), "+ "limited to +-Max Gain. The measurement and the gain hold while the input is too quiet to level: more than 20 LU "+ "under its own 12 s level, more than Max Gain + 12 LU under the target, or under -70 LUFS.";+ }+ return {};}const char* displayName() const override { return "Nota Level"; }@@ -184,7 +403,7 @@ public:int32_t paramCount() const override { return kNumParams; }const char* paramName(int32_t i) const override {- static const char* nm[] = { "Target", "Scale", "Auto", "Trim", "Response", "Window", "Max Gain", "Safe", "Ceiling" };+ static const char* nm[] = { "Target", "Scale", "Auto", "Trim", "Response", "Window", "Max Gain", "Safe", "Ceiling", "Gain" };return (i >= 0 && i < kNumParams) ? nm[i] : "";}float paramMin(int32_t /*i*/) const override { return 0.0f; }@@ -194,13 +413,33 @@ public:private:static constexpr double kPi = 3.14159265358979323846;+ static constexpr double kFloor = 1e-12;+ // −70 LUFS as a K-weighted mean square (LUFS = −0.691 + 10 log10 ms).+ static constexpr double kGateMs = 1.1724653045822964e-7;+ static constexpr double kRelGate = 0.1; // −10 LU (Integrated, BS.1770)+ static constexpr double kHoldGate = 0.01; // −20 LU (the hold)+ static constexpr float kDbToLn = 0.11512925464970228f;float get(int i) const { return p_[i].load(std::memory_order_relaxed); }+ int scaleIndex() const { return std::clamp((int)std::lround(get(Scale) * 2.0f), 0, 2); }+ float trimDb() const { return (get(Trim) - 0.5f) * 24.0f; }+ float ceilingDb() const { return -6.0f + get(Ceiling) * 6.0f; }+ int lookW() const { return std::max(1, (int)std::lround((get(Response) < 0.5f ? 0.005 : 0.020) * sr_)); }static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }float coefFor(double tauSec) const { return (float)(1.0 - std::exp(-1.0 / (std::max(1e-4, tauSec) * sr_))); }static float db(float lin) { return 20.0f * std::log10(std::max(1e-6f, lin)); }static float lufs(double ms) { return ms > 1e-10 ? (float)(-0.691 + 10.0 * std::log10(ms)) : -120.0f; }+ void resetLimiter(int W) {+ curW_ = W;+ std::fill(dly_.begin(), dly_.end(), 0.0f);+ std::fill(box_.begin(), box_.end(), 1.0f);+ boxSum_ = (double)std::max(0, W); boxI_ = 0;+ dqH_ = 0; dqN_ = 0; t_ = 0; dW_ = 0;+ env_ = 1.0f;+ for (int c = 0; c < 2; ++c) ti0_[c] = ti1_[c] = ti2_[c] = 0.0f;+ }+// BS.1770 K-weighting: high-shelf then 38 Hz high-pass, cascaded biquads (TDF-II).struct KW { float z1a = 0, z1b = 0, z2a = 0, z2b = 0; };float kweight(KW& s, float x) {@@ -228,42 +467,67 @@ private:a1_[1] = (float)(2.0 * (K * K - 1.0) / a0);a2_[1] = (float)((1.0 - K / Q + K * K) / a0);b0_[1] = (float)(1.0 / a0); b1_[1] = (float)(-2.0 / a0); b2_[1] = (float)(1.0 / a0); }+ coefInt_ = coefFor(12.0);}- // 4× oversampled true-peak via Catmull-Rom between output samples.+ static float catmull(float y0, float y1, float y2, float y3, float t) {+ const float b = 0.5f * (y2 - y0), d = 0.5f * (y3 - y1);+ return y1 + t * (b + t * ((3 * (y2 - y1) - 2 * b - d) + t * (2 * (y1 - y2) + b + d)));+ }+ // Output true-peak meter: 4× Catmull-Rom between the last samples.float truePeak(int c, float x) {float y0 = tp0_[c], y1 = tp1_[c], y2 = tp2_[c], y3 = x;float pk = std::fabs(y2);- for (int k = 1; k < 4; ++k) {- float t = k * 0.25f;- float a = y1, b = 0.5f * (y2 - y0), d = 0.5f * (y3 - y1), cc = y2;- float v = a + t * (b + t * ((3 * (cc - a) - 2 * b - d) + t * (2 * (a - cc) + b + d)));- pk = std::max(pk, std::fabs(v));- }+ for (int k = 1; k < 4; ++k) pk = std::max(pk, std::fabs(catmull(y0, y1, y2, y3, k * 0.25f)));tp0_[c] = y1; tp1_[c] = y2; tp2_[c] = y3;return pk;}+ // Limiter detector: the peak of the last three samples and the interpolation between the+ // older two (so every in-between peak is seen within two samples of its own).+ float tpInterp(int c, float x) {+ float y0 = ti0_[c], y1 = ti1_[c], y2 = ti2_[c], y3 = x;+ float pk = std::max(std::fabs(y1), std::max(std::fabs(y2), std::fabs(y3)));+ for (int k = 1; k < 4; ++k) pk = std::max(pk, std::fabs(catmull(y0, y1, y2, y3, k * 0.25f)));+ ti0_[c] = y1; ti1_[c] = y2; ti2_[c] = y3;+ return pk;+ }double sr_ = 44100.0;std::atomic<float> p_[kNumParams] = {};- // K-weighting coeffs (shared) + per-signal states.float b0_[2] = {}, b1_[2] = {}, b2_[2] = {}, a1_[2] = {}, a2_[2] = {};+ float coefInt_ = 0.0f;KW kIn_[2], kSc_[2], kOut_[2];float tp0_[2] = {}, tp1_[2] = {}, tp2_[2] = {};+ float ti0_[2] = {}, ti1_[2] = {}, ti2_[2] = {};- // Loudness EMAs (mean square) + correlation EMAs + limiter env.- double msWin_ = 1e-7, msScWin_ = 1e-7, msInShort_ = 1e-7, msOutShort_ = 1e-7, msInMom_ = 1e-7;+ // Loudness EMAs (mean square). *G = gated (hold in silence).+ double msMom_ = kFloor, msShort_ = kFloor, msMomG_ = kFloor, msShortG_ = kFloor, msIntAbs_ = kFloor, msInt_ = kFloor;+ double msScMom_ = kFloor, msScMeas_ = kFloor, msOutShort_ = kFloor, msOutMom_ = kFloor;double cLR_ = 1e-7, cLL_ = 1e-7, cRR_ = 1e-7;- float appliedDb_ = 0.0f, desiredDb_ = 0.0f, safeEnv_ = 0.0f, tpPk_ = 0.0f;+ bool primed_ = false, scPrimed_ = false;+ int sigRun_ = 0, scRun_ = 0;+ float levelDb_ = 0.0f, limGrSm_ = 0.0f, limHold_ = 0.0f, tpPk_ = 0.0f, curTarget_ = -14.0f;++ // Look-ahead limiter (sized in setSampleRate).+ std::vector<float> dly_, box_, dqV_;+ std::vector<int64_t> dqT_;+ int wMax_ = 0, cap_ = 1, curW_ = -1, boxI_ = 0, dqH_ = 0, dqN_ = 0, dW_ = 0;+ int64_t t_ = 0;+ double boxSum_ = 0.0;+ float env_ = 1.0f;++ std::atomic<bool> reseedReq_{false};// Sidechain source buffer (engine hands it in before process()).std::atomic<int32_t> scTrackId_{-1};const float* scBuf_ = nullptr; int32_t scFrames_ = 0;// Published meters.- std::atomic<float> inLufs_{-120.0f}, outLufs_{-120.0f}, inMom_{-120.0f}, target_{-14.0f},- applied_{0.0f}, truePeak_{-120.0f}, corr_{0.0f}, scLufs_{-120.0f}, desired_{0.0f};+ std::atomic<float> inLufs_{-120.0f}, outLufs_{-120.0f}, inMom_{-120.0f}, outMom_{-120.0f}, target_{-14.0f},+ applied_{0.0f}, truePeak_{-120.0f}, corr_{0.0f}, scLufs_{-120.0f}, desired_{0.0f}, measured_{-120.0f},+ outMeas_{-120.0f}, level_{0.0f}, limGr_{0.0f}, limHoldA_{0.0f}, srA_{44100.0f};+ std::atomic<int> clamp_{0}, silent_{1}, primedA_{0}, latency_{0};};} // namespace notadiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex e53c7918..5e76119c 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -5400,76 +5400,190 @@ Console.WriteLine("-- Nota Lens --");// ============================ Nota Level ===================================Console.WriteLine("-- Nota Level (AutoGain) --");{- // AutoGain = loudness-matching utility (kind 18). Own engine (it changes level, which- // would skew the shared master mix used by later tests).+ // Nota Level = loudness leveler (kind 18). Own engine (it changes level, which would skew the+ // shared master mix used by later tests). 10 params: the original 9 + Gain (manual) appended.using var ae = new NotaEngine();ae.SetBpm(120); ae.SetTimeSignature(4, 4);int at = ae.AddInstrumentTrack();- ae.AddMidiClip(at, 0.0, 16.0);- ae.SetClipNotes(at, 0, new[] { new NotaNote(57, 0.0, 15.5, 0.5f) }); // quiet, sustained source → needs boost+ ae.AddMidiClip(at, 0.0, 32.0);+ ae.SetClipNotes(at, 0, new[] { new NotaNote(57, 0.0, 31.5, 0.5f) }); // quiet, sustained source → needs boostint ag = ae.AddBuiltinDevice(at, 18);Check(ag >= 0, "add built-in Nota Level");Check(ae.DeviceName(at, ag) == "Nota Level", $"name is Nota Level (got '{ae.DeviceName(at, ag)}')");Check(ae.TrackDeviceBuiltinKind(at, ag) == 18, $"builtin kind is 18 (got {ae.TrackDeviceBuiltinKind(at, ag)})");- Check(ae.DeviceParamCount(at, ag) == 9, $"Nota Level exposes 9 params (got {ae.DeviceParamCount(at, ag)})");+ Check(ae.DeviceParamCount(at, ag) == 10 && ae.DeviceParamName(at, ag, 9) == "Gain",+ $"Nota Level exposes 10 params, Gain appended (got {ae.DeviceParamCount(at, ag)})");+ Check(Math.Abs(ae.DeviceParamDefault(at, ag, 9) - 0.5f) < 1e-4 && Math.Abs(ae.DeviceParamDefault(at, ag, 0) - 0.611f) < 1e-3,+ "Level defaults: Gain 0 dB, Target −14 LUFS");// Param round-trip.ae.DeviceSetParam(at, ag, 0, 0.75f); // Target- Check(Math.Abs(ae.DeviceGetParam(at, ag, 0) - 0.75f) < 1e-4, "AutoGain param set/get round-trips");+ Check(Math.Abs(ae.DeviceGetParam(at, ag, 0) - 0.75f) < 1e-4, "Level param set/get round-trips");ae.DeviceSetParam(at, ag, 0, 0.611f); // −14 LUFSae.DeviceSetParam(at, ag, 1, 0f); // Scale = Momentary (fast measurement)ae.DeviceSetParam(at, ag, 4, 0f); // Response = Fast+ ae.DeviceSetParam(at, ag, 5, 0f); // Window 0.4 s → glide 0.1 sae.DeviceSetParam(at, ag, 6, 1f); // Max Gain = 24 dB (allow a big boost)+ // Look-ahead: Safe on reports latency (Fast 5 ms, Slow 20 ms); Safe off none.+ var asc = new float[21];var ab = new float[8192 * 2];- var asc = new float[9];+ ae.Seek(0); ae.Play(); ae.RenderOffline(ab, 1024); ae.StopTransport();+ ae.DeviceScope(at, ag, asc, asc.Length);+ double sr0 = asc[17];+ Check(sr0 > 0 && Math.Abs(asc[16] - (Math.Round(0.005 * sr0) + 1)) < 1.5, $"Level Fast look-ahead latency ≈ 5 ms ({asc[16]} smp at {sr0} Hz)");+ Check(asc[18] < 0.5f && Math.Abs(asc[12]) < 1e-3, "Level holds the gain until the input has been measured");+// Let the meter/gain settle (Fast/Momentary settles < 1 s; render ~4.6 s inside the note).ae.Seek(0); ae.Play();for (int k = 0; k < 25; k++) ae.RenderOffline(ab, 8192);int an = ae.DeviceScope(at, ag, asc, asc.Length);ae.StopTransport();bool afin = true; foreach (var s in ab) if (!float.IsFinite(s)) { afin = false; break; }- Check(afin && Rms(ab, 8192) > 0.001f, $"AutoGain passes audio (rms {Rms(ab, 8192):F3})");- Check(an == 9, $"AutoGain scope returns 9 meters (got {an})");+ Check(afin && Rms(ab, 8192) > 0.001f, $"Level passes audio (rms {Rms(ab, 8192):F3})");+ Check(an == 21, $"Level scope returns 21 values (got {an})");+ Check(asc[18] > 0.5f, "Level has measured the input (primed)");// Quiet source matched up toward −14 → a real boost, and the output ends louder than the input.- Check(asc[4] > 4.0f, $"auto-gain boosts a quiet source toward target (applied {asc[4]:F1} dB)");- Check(asc[1] > asc[0] + 3.0f, $"gain-matched output is louder than input (out {asc[1]:F1} > in {asc[0]:F1} LUFS)");+ Check(asc[4] > 4.0f && asc[12] > 4.0f, $"auto boosts a quiet source toward target (applied {asc[4]:F1} dB, correction {asc[12]:F1})");+ Check(asc[1] > asc[0] + 3.0f, $"leveled output is louder than input (out {asc[1]:F1} > in {asc[0]:F1} LUFS)");+ Check(Math.Abs(asc[10] - asc[3]) < 2.5f || asc[20] > 0.3f, $"output sits on the target unless true-peak holds it (out {asc[10]:F1}, target {asc[3]:F1}, TP hold {asc[20]:F1})");- // True-peak safety keeps the boosted output from clipping.+ // True-peak safety keeps the boosted output under the ceiling (−1 dBTP).ae.DeviceSetParam(at, ag, 7, 1f); // Safe on- ae.Seek(0); ae.Play(); for (int k = 0; k < 4; k++) ae.RenderOffline(ab, 8192); ae.StopTransport();+ ae.DeviceSetParam(at, ag, 0, 1f); // Target 0 LUFS: push into the limiter+ ae.Seek(0); ae.Play(); for (int k = 0; k < 8; k++) ae.RenderOffline(ab, 8192); ae.StopTransport();float pk = 0; foreach (var s in ab) pk = Math.Max(pk, Math.Abs(s));- Check(pk <= 1.01f, $"true-peak safety holds the ceiling (peak {pk:F3})");-- // Manual (Auto off) holds the correction rather than tracking.- ae.DeviceSetParam(at, ag, 2, 0f); // Auto off- ae.Seek(0); ae.Play(); ae.RenderOffline(ab, 4096); ae.DeviceScope(at, ag, asc, asc.Length); ae.StopTransport();- Check(float.IsFinite(asc[4]), "manual mode renders finite (held correction)");+ float ceilLin = MathF.Pow(10, -1f / 20f);+ Check(pk <= ceilLin + 1e-3f, $"true-peak safety holds the −1 dBTP ceiling (peak {pk:F3})");+ ae.DeviceScope(at, ag, asc, asc.Length);+ Check(asc[20] > 0.1f, $"the limiter reports its reduction (held {asc[20]:F1} dB)");+ ae.DeviceSetParam(at, ag, 0, 0.611f);++ // Slow response → 20 ms look-ahead; Safe off → no latency.+ ae.DeviceSetParam(at, ag, 4, 1f);+ Check(Math.Abs(ae.TrackLatencySamples(at) - (Math.Round(0.02 * sr0) + 1)) < 1.5, $"Level Slow look-ahead ≈ 20 ms ({ae.TrackLatencySamples(at)} smp)");+ ae.DeviceSetParam(at, ag, 7, 0f);+ Check(ae.TrackLatencySamples(at) == 0, "Level with Safe off has no latency");+ ae.DeviceSetParam(at, ag, 7, 1f); ae.DeviceSetParam(at, ag, 4, 0f);++ // Manual: the Gain param is applied (limited to ±Max Gain); MATCH (action 1) sets it to the distance to the target.+ ae.DeviceSetParam(at, ag, 2, 0f); // Manual+ ae.DeviceSetParam(at, ag, 9, 0.5f + 6f / 48f); // +6 dB+ ae.Seek(0); ae.Play(); for (int k = 0; k < 3; k++) ae.RenderOffline(ab, 8192); ae.DeviceScope(at, ag, asc, asc.Length); ae.StopTransport();+ Check(Math.Abs(asc[12] - 6f) < 0.1f, $"manual mode applies the Gain param (+6 → {asc[12]:F2} dB)");+ ae.DeviceSetParam(at, ag, 6, 0.125f); // Max Gain 3 dB → the manual gain is limited+ ae.Seek(0); ae.Play(); for (int k = 0; k < 2; k++) ae.RenderOffline(ab, 8192); ae.DeviceScope(at, ag, asc, asc.Length); ae.StopTransport();+ Check(Math.Abs(asc[12] - 3f) < 0.1f, $"manual gain is limited to ±Max Gain ({asc[12]:F2} dB)");+ ae.DeviceSetParam(at, ag, 6, 1f);+ ae.Seek(0); ae.Play(); for (int k = 0; k < 4; k++) ae.RenderOffline(ab, 8192); ae.StopTransport();+ ae.DeviceScope(at, ag, asc, asc.Length);+ double want = asc[3] - asc[9] - 0; // target − measured − trim+ ae.DeviceAction(at, ag, 1, 0, 0f);+ Check(ae.DeviceGetParam(at, ag, 2) < 0.5f && Math.Abs((ae.DeviceGetParam(at, ag, 9) - 0.5f) * 48f - Math.Clamp(want, -24, 24)) < 0.3,+ $"device_action 1 (MATCH) sets Gain to the distance to the target ({(ae.DeviceGetParam(at, ag, 9) - 0.5f) * 48f:F1} vs {want:F1} dB)");+ ae.DeviceSetParam(at, ag, 2, 1f); // Auto again+ ae.DeviceAction(at, ag, 0, 0, 0f); // RESET — re-seed the measurement+ ae.Seek(0); ae.Play(); ae.RenderOffline(ab, 4096); ae.StopTransport();+ ae.DeviceScope(at, ag, asc, asc.Length);+ Check(asc[18] > 0.5f && float.IsFinite(asc[9]), "device_action 0 (RESET) re-seeds the measurement");++ // Silence: the gain holds instead of riding up into noise. A short note, then nothing.+ {+ int st = ae.AddInstrumentTrack();+ ae.AddMidiClip(st, 0.0, 16.0);+ ae.SetClipNotes(st, 0, new[] { new NotaNote(57, 0.0, 3.0, 0.5f) }); // 1.5 s at 120 BPM+ int sg = ae.AddBuiltinDevice(st, 18);+ ae.DeviceSetParam(st, sg, 1, 0f); ae.DeviceSetParam(st, sg, 4, 0f); ae.DeviceSetParam(st, sg, 5, 0.5f); ae.DeviceSetParam(st, sg, 6, 1f);+ var ssc = new float[21];+ ae.Seek(0); ae.Play();+ for (int k = 0; k < 7; k++) ae.RenderOffline(ab, 8192); // ~1.3 s: inside the note+ ae.DeviceScope(st, sg, ssc, ssc.Length); float during = ssc[12];+ for (int k = 0; k < 13; k++) ae.RenderOffline(ab, 8192); // ~2.4 s on: the release tail sinks under the hold gate+ ae.DeviceScope(st, sg, ssc, ssc.Length); float held = ssc[12];+ Check(ssc[15] > 0.5f, $"the fading tail reads as silence (in {ssc[2]:F1} LUFS)");+ for (int k = 0; k < 16; k++) ae.RenderOffline(ab, 8192); // ~3 s more of silence+ ae.DeviceScope(st, sg, ssc, ssc.Length);+ ae.StopTransport();+ Check(ssc[15] > 0.5f && Math.Abs(ssc[12] - held) < 0.05f,+ $"silence holds the gain instead of riding up ({during:F1} in the note, {held:F1} → {ssc[12]:F1} dB in silence, in {ssc[2]:F1} LUFS)");+ ae.RemoveTrack(st);+ }++ // Integrated scale renders finite.+ ae.DeviceSetParam(at, ag, 1, 1f);+ ae.Seek(0); ae.Play(); for (int k = 0; k < 4; k++) ae.RenderOffline(ab, 8192); ae.StopTransport();+ bool ifin = true; foreach (var s in ab) if (!float.IsFinite(s)) { ifin = false; break; }+ Check(ifin, "Level on the Integrated scale renders finite");+ ae.DeviceSetParam(at, ag, 1, 0f);// Sidechain: routing a reference track makes the target follow that track's loudness.int refT = ae.AddInstrumentTrack();- ae.AddMidiClip(refT, 0.0, 4.0);- ae.SetClipNotes(refT, 0, new[] { new NotaNote(57, 0.0, 3.5, 1.0f) }); // louder reference+ ae.AddMidiClip(refT, 0.0, 8.0);+ ae.SetClipNotes(refT, 0, new[] { new NotaNote(57, 0.0, 7.5, 1.0f) }); // louder referenceae.SetDeviceSidechainSource(at, ag, refT);- Check(ae.DeviceSidechainSource(at, ag) == refT, "AutoGain accepts a sidechain reference source");- ae.DeviceSetParam(at, ag, 2, 1f); // Auto back on+ Check(ae.DeviceSidechainSource(at, ag) == refT, "Level accepts a sidechain reference source");ae.Seek(0); ae.Play(); for (int k = 0; k < 6; k++) ae.RenderOffline(ab, 8192); ae.DeviceScope(at, ag, asc, asc.Length); ae.StopTransport();- Check(asc[7] > -119f, $"sidechain reference loudness is measured (scLufs {asc[7]:F1})");+ Check(asc[7] > -119f && Math.Abs(asc[3] - asc[7]) < 0.5f, $"the reference's loudness is the target (ref {asc[7]:F1}, target {asc[3]:F1})");bool sfin = true; foreach (var s in ab) if (!float.IsFinite(s)) { sfin = false; break; }- Check(sfin, "AutoGain with sidechain renders finite");+ Check(sfin, "Level with a reference renders finite");+ Check(ae.DeviceText(at, ag, 0).Contains("reference"), "summary names the reference");ae.SetDeviceSidechainSource(at, ag, -1);- // Clone: duplicating the track carries AutoGain params.+ // Device texts.+ Check(ae.DeviceText(at, ag, 0).Contains("target") && ae.DeviceText(at, ag, 1).Contains("LUFS") && ae.DeviceText(at, ag, 2).Contains("Gain"),+ "Level device texts: summary, live reading, parameter guide");++ // MCP: read / set in units, level_match.+ var ltools = new Nota.Mcp.Tools.DeviceTools(ae, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());+ var lr = ltools.SetLevel(at, ag, targetLufs: -16, scale: "Integrated", response: "Slow", windowSeconds: 6, maxGainDb: 18, trimDb: -1.5,+ truePeakSafe: true, ceilingDbtp: -2).Result;+ Check(Math.Abs(lr.TargetLufs + 16) < 0.1 && lr.Scale == "Integrated" && lr.Response == "Slow" && Math.Abs(lr.WindowSeconds - 6) < 0.05+ && Math.Abs(lr.MaxGainDb - 18) < 0.1 && Math.Abs(lr.TrimDb + 1.5) < 0.05 && Math.Abs(lr.CeilingDbtp + 2) < 0.05 && lr.Mode == "Auto"+ && lr.Summary.Contains("integrated") && lr.Live.Length > 0, "MCP set_level / read_level in units");+ lr = ltools.SetLevel(at, ag, mode: "Manual", manualGainDb: 4).Result;+ Check(lr.Mode == "Manual" && Math.Abs(lr.ManualGainDb - 4) < 0.1, "MCP set_level switches to Manual with a gain");+ ae.Seek(0); ae.Play(); for (int k = 0; k < 4; k++) ae.RenderOffline(ab, 8192); ae.StopTransport();+ lr = ltools.LevelMatch(at, ag).Result;+ Check(lr.Mode == "Manual" && lr.Primed, $"MCP level_match sets the manual gain ({lr.ManualGainDb:F1} dB)");+ ltools.SetLevel(at, ag, mode: "Auto").Wait();++ // Clone: duplicating the track carries Level params, Gain included.ae.DeviceSetParam(at, ag, 6, 0.7f); // Max Gain+ ae.DeviceSetParam(at, ag, 9, 0.6f); // Gainint atD = ae.DuplicateTrack(at); int agD = ae.TrackDeviceCount(atD) - 1;- Check(atD > 0 && Math.Abs(ae.DeviceGetParam(atD, agD, 6) - 0.7f) < 1e-3, "duplicate track clones AutoGain params");+ Check(atD > 0 && Math.Abs(ae.DeviceGetParam(atD, agD, 6) - 0.7f) < 1e-3 && Math.Abs(ae.DeviceGetParam(atD, agD, 9) - 0.6f) < 1e-3,+ "duplicate track clones Level params (Gain included)");- // Automation drives Target.+ // Automation drives Target and Gain.int alane = ae.AddAutomationLane(at, AutomationTarget.DeviceParam, ag, 0);- Check(alane >= 0, "add AutoGain Target automation lane");+ int alane2 = ae.AddAutomationLane(at, AutomationTarget.DeviceParam, ag, 9);+ Check(alane >= 0 && alane2 >= 0, "add Level Target + Gain automation lanes");ae.SetAutomationPoints(at, alane, new[] { new AutomationPoint(0.0, 0.3f), new AutomationPoint(2.0, 0.9f) });+ ae.SetAutomationPoints(at, alane2, new[] { new AutomationPoint(0.0, 0.5f), new AutomationPoint(2.0, 0.8f) });ae.Seek(1.99); ae.Play(); ae.RenderOffline(ab, 4096); ae.StopTransport();- Check(ae.DeviceGetParam(at, ag, 0) > 0.7f, $"automation drives AutoGain Target ({ae.DeviceGetParam(at, ag, 0):F2})");+ Check(ae.DeviceGetParam(at, ag, 0) > 0.7f && ae.DeviceGetParam(at, ag, 9) > 0.7f,+ $"automation drives Level Target ({ae.DeviceGetParam(at, ag, 0):F2}) and Gain ({ae.DeviceGetParam(at, ag, 9):F2})");+ ae.RemoveAutomationLane(at, alane2); ae.RemoveAutomationLane(at, alane);++ // Factory presets: at least 25, only real param names, each applies and renders finite.+ var lcat = new FactoryPresetCatalog();+ var lNames = new HashSet<string>();+ for (int p = 0; p < ae.DeviceParamCount(at, ag); p++) lNames.Add(ae.DeviceParamName(at, ag, p));+ int lPresets = 0; bool lNamesOk = true, lRenderOk = true;+ foreach (var info in lcat.All())+ {+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 18) continue;+ var doc = lcat.Document(info.Id);+ if (doc is null) continue;+ lPresets++;+ foreach (var k in doc.NamedParams!.Keys) if (!lNames.Contains(k)) { lNamesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }+ lcat.ApplyInPlace(ae, info.Id, at, ag);+ ae.Seek(0); ae.Play(); ae.RenderOffline(ab, 8192); ae.StopTransport();+ foreach (var v in ab) if (!float.IsFinite(v)) { lRenderOk = false; Console.WriteLine($" non-finite output in {info.DisplayName}"); break; }+ }+ Check(lPresets >= 25, $"Nota Level ships at least 25 factory presets (got {lPresets})");+ Check(lNamesOk, "every Level preset names real params");+ Check(lRenderOk, "every Level preset renders finite");}// ============================ Nota Forge ===================================