Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

Redesign of Ceiling

Egor Khindikaynen4081c6da9b16
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef5cc1b8..1e15e44f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,36 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Ceiling shows its level, its reduction and its loudness, and gains True Peak, Delta, a
+ key high-pass and a loudness target.** The card moves onto the 700 × 260 frame of Beat Repeat
+ and Shutter — a LIMIT column (input with the ceiling, reduction, output), a centre panel with
+ **Level**, **Reduction** and **Loudness** tabs, a **Meters** / **Detector** panel and a status
+ strip. The slider row over the graph becomes Gain / Ceiling / Release knobs under it,
+ Character a switch over it, Look-ahead and Link move to the right panel:
+ - **Level** — the last 4 s: the input, the part over the ceiling in red and the output, with
+ the reduction under it; drag the ceiling line. Shows how far in went to out and how much
+ of the time the input was over the ceiling.
+ - **Reduction** — the reduction over 4 s, scaled to its depth, with its mean; teal where a
+ transient got through to the clip (Punch lets the attack by). Shows the release the auto
+ stage is actually using and how many transients reached the clip.
+ - **Loudness** — momentary, short-term and integrated LUFS over the last 60 s around a
+ **Target** (−23 broadcast … −8 very loud; drag the line for any value), with the loudness
+ range (LRA) and PLR. Meters shows the integrated reading against the target.
+ - New **True peak**: the detector reads the 4× inter-sample peak, so the ceiling holds in
+ dBTP. New **Delta**: hear only what the limiter removes. New **SC HP**: take the lows out
+ of the detector so the bass stops pumping the mix. The key source picker stays.
+ - Auto release now slows smoothly as the reduction deepens (×1 at 1 dB up to ×5 at 7 dB)
+ instead of jumping at 2 dB. Peak holds, max GR and the clip count live in the engine;
+ **Reset peaks** clears them, **Reset** on the Loudness tab starts the loudness again.
+ - **32 factory presets**, up from six — mastering for streaming, Apple Music, podcast,
+ broadcast R128, club and CD, bus and drum limiting, track peak catchers, zero-latency live
+ use and squash effects. The four new parameters are appended and default to the old sound,
+ so older projects and presets open unchanged. Every parameter automates, MIDI-learns,
+ saves in a preset and is reachable over MCP. `get_device_text` returns the status line, the
+ live reading and a guide to the parameter values, `device_action` 0 resets the peaks and 1
+ the loudness, and the new `read_ceiling` returns the reduction, the peaks and their holds,
+ true peak, LUFS M / S / I with the distance to the target, LRA, PLR, the release in use,
+ the clip count and both windows.
- **Nota Beat Repeat shows what it captures and repeats, and gains a triplet grid, a filter
type and a Repeat you can latch.** The card moves onto the 700 × 260 frame of Shutter and
Auto Shift — a REPEAT column (the input and the repeats' level, the repeat count), a centre
@@ -315,6 +345,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
returns the compressor's status line.
### Fixed
+- **Nota Ceiling's integrated loudness and true peak.** The integrated LUFS gated 100 ms
+ slices instead of the 400 ms blocks BS.1770 asks for, so quiet passages were weighed wrong;
+ it now gates overlapping 400 ms blocks. The true-peak meter interpolated with a spline that
+ read inter-sample peaks up to 1 dB low; it now uses a 4× windowed-sinc interpolator.
- **Nota Beat Repeat's first pass and filter width.** With Pitch above 0 the capture pass
read ahead of the audio just written, so the first slice of every burst played stale audio
from seconds earlier; the capture now plays through as it is and the pitch applies to the
diff --git a/FEATURES.md b/FEATURES.md
index 395b50a1..994e812e 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -400,9 +400,12 @@ and user presets, automation, persistence and cloning.
- **Nota Crush** (12) — bit crusher: Bit Depth, Sample Rate, Drive, Wet, Anti-Alias;
Digital/Analog/Fold modes; GRIT (Dither/Jitter/Noise); an OUTPUT filter; quantizer and
aliasing-spectrum visualisers.
-- **Nota Ceiling** (14) — look-ahead brickwall limiter: drive, ceiling, release (with
- auto), Clean/Punch/Glue characters, lookahead, stereo link, sidechain; a LIVE strip with
- GR, input/output history, LUFS-S / LUFS-I / true peak.
+- **Nota Ceiling** (14) — look-ahead brick-wall limiter: Gain, Ceiling, Release (with a
+ program-dependent auto stage), Clean / Punch / Glue characters, look-ahead, stereo link,
+ True Peak (4× inter-sample detection), Delta (hear what it removes), a key high-pass and an
+ external key; a BS.1770 / R128 loudness meter (LUFS M / S / I, LRA, PLR, true peak) against
+ a Target. Level / Reduction / Loudness graphs (drag the ceiling and the target), a LIMIT
+ column, Meters / Detector panels; 32 factory presets; MCP `read_ceiling`.
- **Nota Dynamic EQ-8** (13) — 8-band parametric with dynamics: each band Static/Duck/Lift,
threshold, range, attack/release, sidechain, Solo band; a dual curve (static plus
momentary) and a band table with GR.
diff --git a/src/managed/Nota.App/Controls/CeilingScope.cs b/src/managed/Nota.App/Controls/CeilingScope.cs
deleted file mode 100644
index 42df9240..00000000
--- a/src/managed/Nota.App/Controls/CeilingScope.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Ceiling (mockup 3o) visualizers. A shared ring of the last ~4 seconds of
-// per-tick meters (input peak / limited output / gain reduction, all dB) feeds two
-// controls: the LEVEL plot (input behind, output in brass, the excess above the
-// ceiling in red, the ceiling drawn as a bright line) and the GAIN REDUCTION lane
-// (bars hanging from the top in teal, amber past −3 dB). The device body samples
-// the engine scope each 60 Hz tick and pushes one column; both controls redraw.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-/// <summary>Rolling 4-second history of the limiter's meters, newest at the head.</summary>
-internal sealed class CeilingMeters
-{
- public const int N = 160; // columns (~4 s at 60 Hz, decimated)
- public readonly float[] In = Fill(-120), Out = Fill(-120), Gr = new float[N];
- public float Ceiling = -1f; // current ceiling dB, for the plot line
-
- private static float[] Fill(float v) { var a = new float[N]; for (int i = 0; i < N; i++) a[i] = v; return a; }
-
- public void Push(float inDb, float outDb, float grDb)
- {
- Array.Copy(In, 1, In, 0, N - 1); In[N - 1] = inDb;
- Array.Copy(Out, 1, Out, 0, N - 1); Out[N - 1] = outDb;
- Array.Copy(Gr, 1, Gr, 0, N - 1); Gr[N - 1] = grDb;
- }
-}
-
-internal sealed class CeilingLevelPlot : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush Border = NotaPalette.GraphBorder;
- private static readonly IBrush InC = NotaPalette.SignalInFill;
- private static readonly IBrush OutC = NotaPalette.Wash(NotaPalette.Accent, 0xD9);
- private static readonly IBrush OverC = NotaPalette.Wash(NotaPalette.Danger, 0x99);
- private static readonly IBrush CeilC = NotaPalette.AccentBright;
- private static readonly IBrush Axis = NotaPalette.TextAxis;
- private static readonly Typeface Face = NotaFonts.Mono;
- private const double Lo = -30, Hi = 3; // dBFS display range
-
- private readonly CeilingMeters _m;
- public CeilingLevelPlot(CeilingMeters m) { _m = m; }
- public void Tick() => InvalidateVisual();
- private static double Frac(double db) => Math.Clamp((db - Lo) / (Hi - Lo), 0, 1);
-
- 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 padT = 14, padB = 12, padX = 6;
- double x0 = padX, x1 = w - padX, top = padT, bot = h - padB;
- double plotH = Math.Max(1, bot - top), plotW = Math.Max(1, x1 - x0);
- int n = CeilingMeters.N; double bw = plotW / n;
-
- double ceilY = bot - Frac(_m.Ceiling) * plotH;
- for (int i = 0; i < n; i++)
- {
- double bx = x0 + i * bw, bwi = Math.Max(0.6, bw - 0.6);
- double inF = Frac(_m.In[i]), outF = Frac(_m.Out[i]);
- double inY = bot - inF * plotH, outY = bot - outF * plotH;
- if (inF > 0.001) ctx.FillRectangle(InC, new Rect(bx, inY, bwi, bot - inY));
- if (inY < ceilY) ctx.FillRectangle(OverC, new Rect(bx, inY, bwi, ceilY - inY)); // excess above ceiling
- if (outF > 0.001) ctx.FillRectangle(OutC, new Rect(bx, outY, bwi, bot - outY));
- }
- // Ceiling line + label.
- ctx.DrawLine(new Pen(CeilC, 1), new Point(x0, ceilY), new Point(x1, ceilY));
-
- void Txt(string t, double x, double y, IBrush b, double fs = 8) =>
- ctx.DrawText(new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, fs, b), new Point(x, y));
- Txt("LEVEL — 4\u2009s", x0 + 1, 2, NotaPalette.TextTertiary);
- Txt("input", x1 - 118, 2, InC); Txt("output", x1 - 78, 2, OutC); Txt("over", x1 - 30, 2, OverC);
- Txt($"ceiling {_m.Ceiling:0.0}", x1 - 54, ceilY - 9, CeilC, 7);
- Txt("−4\u2009s", 1, bot + 1, Axis); Txt("now", x1 - 18, bot + 1, Axis);
- }
-}
-
-internal sealed class CeilingGrLane : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush Border = NotaPalette.GraphBorder;
- private static readonly IBrush Teal = NotaPalette.Teal;
- private static readonly IBrush Amber = NotaPalette.Warning;
- private static readonly Typeface Face = NotaFonts.Mono;
- private const double MaxGr = 6.0;
-
- private readonly CeilingMeters _m;
- public CeilingGrLane(CeilingMeters m) { _m = m; }
- public void Tick() => InvalidateVisual();
-
- 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 top = 13, bot = h - 3, padX = 6;
- double x0 = padX, x1 = w - padX, laneH = Math.Max(1, bot - top), plotW = Math.Max(1, x1 - x0);
- int n = CeilingMeters.N; double bw = plotW / n;
- for (int i = 0; i < n; i++)
- {
- double frac = Math.Clamp(_m.Gr[i] / MaxGr, 0, 1);
- if (frac < 0.002) continue;
- double bx = x0 + i * bw, bwi = Math.Max(0.6, bw - 0.6);
- ctx.FillRectangle(_m.Gr[i] > 3.0 ? Amber : Teal, new Rect(bx, top, bwi, frac * laneH));
- }
- void Txt(string t, double x, double y, IBrush b) =>
- ctx.DrawText(new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));
- Txt("GAIN REDUCTION", x0 + 1, 2, Teal);
- Txt("0 … −6\u2009dB", x1 - 48, 2, NotaPalette.TextDisabled);
- }
-}
diff --git a/src/managed/Nota.App/Controls/CeilingViews.cs b/src/managed/Nota.App/Controls/CeilingViews.cs
new file mode 100644
index 00000000..936d4594
--- /dev/null
+++ b/src/managed/Nota.App/Controls/CeilingViews.cs
@@ -0,0 +1,257 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Ceiling (device kind 14) card windows, read from the engine's telemetry
+// (Ceiling.h scopeRead) so the picture is what the limiter does:
+// · CeLevelView — the Level tab: the last 4 s as columns — the input behind (teal), the part
+// over the ceiling (red), the limited output (brass) — with the ceiling line, and the
+// reduction hanging under it in a strip. Drag the ceiling line up or down.
+// · CeReductionView — the Reduction tab: the reduction over 4 s hanging from 0 dB, teal where
+// a transient got through to the clip, the window's mean dashed; the scale follows the
+// deepest reduction (3 / 6 / 12 / 24 dB).
+// · CeLoudnessView — the Loudness tab: momentary (teal), short-term (brass) and integrated
+// (Ink) over the last 60 s around the Target, with the ±1 LU band. Drag the target line.
+// Drag contract from ShDragView: left button only, a gesture per drag, double-click resets
+// the handle, right-click bubbles to the MIDI-learn menu.
+
+using System;
+using Avalonia;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class CeLevelView : ShDragView
+{
+ public const int HCeiling = 0;
+ private float[] _in = Array.Empty<float>(), _out = Array.Empty<float>(), _gr = Array.Empty<float>();
+ private int _n;
+ private double _ceil = -1, _hi = 6, _heldHi = double.NaN;
+ private const double Lo = -36, StripH = 16;
+ /// <summary>Maps a ceiling (dB) to the handle's 0..1 value and back — set by the card.</summary>
+ public Func<double, double> CeilToNorm { get; set; } = db => (db + 12) / 12;
+ public Func<double, double> NormToCeil { get; set; } = n => -12 + 12 * n;
+ public string Title { get; set; } = "Level and reduction";
+
+ /// <summary>The level cells (input, output, max GR — each <paramref name="n"/> long from
+ /// <paramref name="inAt"/>, <paramref name="outAt"/>, <paramref name="grAt"/>) and the ceiling in dB.</summary>
+ public void Set(float[] src, int inAt, int outAt, int grAt, int n, double ceilDb)
+ {
+ if (_in.Length != n) { _in = new float[n]; _out = new float[n]; _gr = new float[n]; }
+ if (n > 0 && Math.Max(inAt, Math.Max(outAt, grAt)) + n <= src.Length)
+ {
+ Array.Copy(src, inAt, _in, 0, n);
+ Array.Copy(src, outAt, _out, 0, n);
+ Array.Copy(src, grAt, _gr, 0, n);
+ }
+ _n = n; _ceil = ceilDb;
+ // Top of the scale: 0 dBFS plus room for the loudest input, in 6 dB steps (+6 … +24);
+ // held while the ceiling is dragged so the line doesn't jump.
+ double pk = -120; for (int i = 0; i < _n; i++) pk = Math.Max(pk, _in[i]);
+ double hi = Math.Clamp(Math.Ceiling(Math.Max(0, pk) / 6) * 6 + 6, 6, 30);
+ _hi = Dragging && !double.IsNaN(_heldHi) ? _heldHi : hi;
+ _heldHi = _hi;
+ InvalidateVisual();
+ }
+
+ private (double top, double bot) Plot() => (16, Bounds.Height - StripH - 16);
+ private double Y(double db) { var (t, b) = Plot(); return b - Math.Clamp((db - Lo) / (_hi - Lo), 0, 1) * (b - t); }
+
+ protected override int Hit(Point p) => Math.Abs(p.Y - Y(_ceil)) <= 5 && p.Y < Bounds.Height - StripH - 12 ? HCeiling : -1;
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ var (t, b) = Plot();
+ double db = Lo + (b - p.Y) / Math.Max(1, b - t) * (_hi - Lo);
+ return CeilToNorm(Math.Clamp(db, -12, 0));
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ var (top, bot) = Plot();
+ double x0 = 6, x1 = w - 6;
+ // 0 dBFS reference.
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, Y(0)), new Point(x1, Y(0)));
+ double cy = Y(_ceil);
+ if (_n > 0)
+ {
+ double cw = (x1 - x0) / _n, gap = cw > 5 ? 1 : 0.5;
+ var inFill = NotaPalette.Wash(NotaPalette.Teal, 0x55);
+ var overFill = NotaPalette.Danger;
+ for (int i = 0; i < _n; i++)
+ {
+ double x = x0 + i * cw, bw = Math.Max(0.6, cw - gap);
+ if (_in[i] > Lo)
+ {
+ double iy = Y(_in[i]);
+ ctx.DrawRectangle(inFill, null, new Rect(x, iy, bw, bot - iy), 1, 1);
+ if (iy < cy - 0.5) ctx.DrawRectangle(overFill, null, new Rect(x, iy, bw, cy - iy), 1, 1);
+ }
+ if (_out[i] > Lo)
+ {
+ double oy = Y(_out[i]);
+ ctx.DrawRectangle(NotaPalette.Accent, null, new Rect(x, oy, bw, bot - oy), 1, 1);
+ }
+ // Reduction strip under the plot (0 … −12 dB hanging).
+ double g = Math.Clamp(_gr[i] / 12.0, 0, 1);
+ if (g > 0.005)
+ ctx.FillRectangle(NotaPalette.AccentBright, new Rect(x, h - StripH - 2, bw, g * (StripH - 3)));
+ }
+ }
+ ctx.DrawLine(NotaGraph.FramePen, new Point(x0, h - StripH - 4), new Point(x1, h - StripH - 4));
+ // Ceiling line (drag it).
+ ctx.DrawLine(new Pen(NotaPalette.AccentBright, Dragging ? 1.6 : 1), new Point(x0, cy), new Point(x1, cy));
+ TextR(ctx, NotaNum.F($"{_ceil:0.0}"), x1 - 2, cy - 10, NotaPalette.AccentBright);
+ Text(ctx, "0", x0 + 2, Y(0) - 9);
+ NotaGraph.Title(ctx, frame, Title);
+ NotaGraph.Legend(ctx, w - 6, 3, ("in", NotaPalette.TealBright, NotaGraph.Mark.Area),
+ ("out", NotaPalette.AccentBright, NotaGraph.Mark.Area), ("over", NotaPalette.DangerBright, NotaGraph.Mark.Area));
+ Text(ctx, "−4 s", x0 + 2, h - StripH - 15);
+ TextR(ctx, "now", x1 - 2, h - StripH - 15);
+ }
+}
+
+internal sealed class CeReductionView : Avalonia.Controls.Control
+{
+ private float[] _gr = Array.Empty<float>(), _clip = Array.Empty<float>();
+ private int _n;
+ private double _avg, _scale = 12;
+ public double Scale => _scale;
+
+ public CeReductionView() { ClipToBounds = true; MinHeight = 36; }
+
+ public void Set(float[] src, int grAt, int clipAt, int n, double avg)
+ {
+ if (_gr.Length != n) { _gr = new float[n]; _clip = new float[n]; }
+ if (n > 0 && Math.Max(grAt, clipAt) + n <= src.Length)
+ {
+ Array.Copy(src, grAt, _gr, 0, n);
+ Array.Copy(src, clipAt, _clip, 0, n);
+ }
+ _n = n; _avg = avg;
+ double mx = 0; for (int i = 0; i < _n; i++) mx = Math.Max(mx, _gr[i]);
+ _scale = mx <= 2.7 ? 3 : mx <= 5.5 ? 6 : mx <= 11 ? 12 : 24;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 6, x1 = w - 26, top = 16, bot = h - 13;
+ double Y(double gr) => top + Math.Clamp(gr / _scale, 0, 1) * (bot - top);
+ for (int q = 1; q < 4; q++)
+ {
+ double y = top + (bot - top) * q / 4;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, y), new Point(x1, y));
+ ctx.DrawText(NotaGraph.AxisText(NotaNum.F($"−{_scale * q / 4:0.#}")), new Point(x1 + 4, y - 5));
+ }
+ ctx.DrawText(NotaGraph.AxisText("0"), new Point(x1 + 4, top));
+ if (_n > 0)
+ {
+ double cw = (x1 - x0) / _n, gap = cw > 5 ? 1 : 0.5;
+ for (int i = 0; i < _n; i++)
+ {
+ if (_gr[i] < 0.02) continue;
+ double x = x0 + i * cw;
+ ctx.DrawRectangle(_clip[i] > 0.5f ? NotaPalette.Teal : NotaPalette.AccentBright, null,
+ new Rect(x, top, Math.Max(0.6, cw - gap), Y(_gr[i]) - top), 1, 1);
+ }
+ }
+ if (_avg > 0.05)
+ {
+ double ay = Y(_avg);
+ ctx.DrawLine(new Pen(NotaPalette.AccentDim, 1, new DashStyle(new double[] { 3, 3 }, 0)), new Point(x0, ay), new Point(x1, ay));
+ }
+ NotaGraph.Title(ctx, frame, "Reduction");
+ NotaGraph.Legend(ctx, w - 6, 3, ("GR", NotaPalette.AccentBright, NotaGraph.Mark.Area),
+ ("to the clip", NotaPalette.TealBright, NotaGraph.Mark.Area), ("mean", NotaPalette.AccentDim, NotaGraph.Mark.Dashed));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "−4 s");
+ ctx.DrawText(NotaGraph.AxisText("now"), new Point(x1 - 16, h - 11));
+ }
+}
+
+internal sealed class CeLoudnessView : ShDragView
+{
+ public const int HTarget = 0;
+ private float[] _m = Array.Empty<float>(), _s = Array.Empty<float>(), _i = Array.Empty<float>();
+ private int _n;
+ private double _target = -14, _center = -14;
+ private const double Span = 10; // ± LU around the target
+ public Func<double, double> TargetToNorm { get; set; } = t => (t + 30) / 25;
+
+ public void Set(float[] src, int mAt, int sAt, int iAt, int n, double target)
+ {
+ if (_m.Length != n) { _m = new float[n]; _s = new float[n]; _i = new float[n]; }
+ if (n > 0 && Math.Max(mAt, Math.Max(sAt, iAt)) + n <= src.Length)
+ {
+ Array.Copy(src, mAt, _m, 0, n);
+ Array.Copy(src, sAt, _s, 0, n);
+ Array.Copy(src, iAt, _i, 0, n);
+ }
+ _n = n; _target = target;
+ if (!Dragging) _center = target;
+ InvalidateVisual();
+ }
+
+ private double Y(double lufs) { double h = Bounds.Height, t = 14, b = h - 13; return t + (b - t) * (0.5 - (lufs - _center) / (2 * Span)); }
+
+ protected override int Hit(Point p) => Math.Abs(p.Y - Y(_target)) <= 5 ? HTarget : -1;
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ double h = Bounds.Height, t = 14, b = h - 13;
+ double lufs = _center + (0.5 - (p.Y - t) / Math.Max(1, b - t)) * 2 * Span;
+ return TargetToNorm(Math.Clamp(Math.Round(lufs), -30, -5));
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 6, x1 = w - 6;
+ for (int q = 1; q < 4; q++) ctx.DrawLine(NotaGraph.GridPen, new Point(x0 + (x1 - x0) * q / 4, 14), new Point(x0 + (x1 - x0) * q / 4, h - 13));
+ foreach (double d in new[] { -4.0, 4.0 }) ctx.DrawLine(NotaGraph.GridPen, new Point(x0, Y(_center + d)), new Point(x1, Y(_center + d)));
+ // Tolerance band ±1 LU and the target.
+ double ty = Y(_target);
+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Accent, 0x14), new Rect(x0, Y(_target + 1), x1 - x0, Y(_target - 1) - Y(_target + 1)));
+ ctx.DrawLine(new Pen(Dragging ? NotaPalette.AccentBright : NotaPalette.AccentDim, 1, new DashStyle(new double[] { 3, 3 }, 0)), new Point(x0, ty), new Point(x1, ty));
+
+ void Curve(float[] v, IPen pen)
+ {
+ if (_n < 2) return;
+ StreamGeometry? g = null; StreamGeometryContext? gc = null;
+ bool open = false;
+ double cw = (x1 - x0) / (_n - 1);
+ for (int i = 0; i < _n; i++)
+ {
+ if (v[i] <= -69f) { if (open) { gc!.EndFigure(false); open = false; } continue; }
+ var pt = new Point(x0 + i * cw, Math.Clamp(Y(v[i]), 14, h - 13));
+ if (g is null) { g = new StreamGeometry(); gc = g.Open(); }
+ if (!open) { gc!.BeginFigure(pt, false); open = true; } else gc!.LineTo(pt);
+ }
+ if (g is null) return;
+ if (open) gc!.EndFigure(false);
+ gc!.Dispose();
+ ctx.DrawGeometry(null, pen, g);
+ }
+ Curve(_m, NotaGraph.SecondaryPen(NotaPalette.Teal, 1));
+ Curve(_s, NotaGraph.PrimaryPen);
+ Curve(_i, NotaGraph.SecondaryPen(NotaPalette.TextPrimary, 1.2));
+ if (_n > 0 && _s[_n - 1] > -69f) NotaGraph.Node(ctx, new Point(x1, Math.Clamp(Y(_s[_n - 1]), 14, h - 13)), true);
+
+ Text(ctx, NotaNum.F($"{_center + 4:0}"), x0 + 2, Y(_center + 4) - 9);
+ Text(ctx, NotaNum.F($"{_target:0}"), x0 + 2, ty - 9, NotaPalette.AccentBright);
+ Text(ctx, NotaNum.F($"{_center - 4:0}"), x0 + 2, Y(_center - 4) - 9);
+ NotaGraph.Title(ctx, frame, "Loudness");
+ NotaGraph.Legend(ctx, w - 6, 3, ("M", NotaPalette.TealBright, NotaGraph.Mark.Line), ("S", NotaPalette.AccentBright, NotaGraph.Mark.Line),
+ ("I", NotaPalette.TextPrimary, NotaGraph.Mark.Line), ("target", NotaPalette.AccentDim, NotaGraph.Mark.Dashed));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "−60 s");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "now");
+ }
+}
diff --git a/src/managed/Nota.App/Controls/Knob.cs b/src/managed/Nota.App/Controls/Knob.cs
index c522b045..72533abe 100644
--- a/src/managed/Nota.App/Controls/Knob.cs
+++ b/src/managed/Nota.App/Controls/Knob.cs
@@ -58,8 +58,10 @@ public sealed class Knob : Control
/// <summary>Brass value arc instead of neutral grey.</summary>
public bool Accent { get; init; }
- /// <summary>Overrides the value-arc colour (e.g. teal for modulation knobs).</summary>
- public IBrush? ArcColor { get; init; }
+ /// <summary>Overrides the value-arc colour (e.g. teal for modulation knobs); may change live
+ /// (a knob that turns into a modulation depth when its mode switches).</summary>
+ public IBrush? ArcColor { get => _arc; set { if (ReferenceEquals(_arc, value)) return; _arc = value; InvalidateVisual(); } }
+ private IBrush? _arc;
/// <summary>Drawn as inactive (no brass) while still taking input — see Inactive.</summary>
public bool IsDim { get => _dim; set { if (_dim == value) return; _dim = value; InvalidateVisual(); } }
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs
index 1423091a..a1bc6ab1 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs
@@ -1,18 +1,23 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Ceiling (kind 14) body, mockup 3o on the shared
-// shell (700×260, full-bleed). A LIVE strip (big GR number + hanging GR bar over
-// Ceiling / Gain / Release, plus an Auto-release switch) sits above a body of the
-// 4-second LEVEL history + GAIN REDUCTION lane | a CHARACTER + loudness rail
-// (peak in/out · max GR · LUFS-S / LUFS-I · true peak, then teal Lookahead / Stereo
-// link, a side-chain source picker and Reset peaks). Params are the device's raw
-// units; the meters come from the packed device scope (dB).
+// Detail · Devices — built-in Nota Ceiling body (look-ahead limiter, device kind 14), a build of
+// the "Nota Ceiling" mockup (700 × 260) on the Beat Repeat / Shutter frame: an always-visible
+// LIMIT column (input · reduction · output), a centre panel with Level / Reduction / Loudness
+// tabs — the input, the part over the ceiling and the output over 4 s with the reduction under
+// it (drag the ceiling), the reduction with the transients that reached the clip, momentary /
+// short-term / integrated loudness over 60 s around the Target (drag it) — with Character over
+// the graph and Gain / Ceiling / Release under it, a right panel with Meters / Detector tabs,
+// and a status strip. The pictures come from the engine (Ceiling.h scopeRead). Every control
+// is a device param (raw units), so automation / MIDI learn / presets / A-B / persistence come
+// for free; the key source is the device's sidechain routing, the resets are device actions.
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -23,184 +28,653 @@ namespace Nota.App;
internal sealed class CeilingDeviceBody : IDeviceBody
{
- private const int Ceil = 0, Gain = 1, Release = 2, AutoRelease = 3, Character = 4, Lookahead = 5, StereoLink = 6;
- // Packed scope layout (Ceiling::scopeRead).
- private const int S_InPeak = 0, S_OutPeak = 1, S_Gr = 2, S_LufsM = 3, S_LufsS = 4, S_LufsI = 5, S_TruePeak = 6;
- private static readonly (string n, string sub)[] Chars =
- { ("Clean", "transparent"), ("Punch", "lets transients through"), ("Glue", "slow, dense") };
+ // ── Parameter indices (must match Ceiling.h) ─────────────────────────────
+ private const int Ceil = 0, Gain = 1, Release = 2, AutoRelease = 3, Character = 4, Lookahead = 5, StereoLink = 6,
+ TruePeak = 7, DeltaP = 8, ScHp = 9, Target = 10, kParams = 11;
+ // Scope layout (Ceiling::S_* / kTele / kLvl / kLoud).
+ private const int S_InPeak = 0, S_OutPeak = 1, S_Gr = 2, S_LufsM = 3, S_LufsS = 4, S_LufsI = 5, S_TruePeak = 6,
+ S_PeakInHold = 7, S_PeakOutHold = 8, S_MaxGrHold = 9, S_TpHold = 10, S_Lra = 11, S_Plr = 12, S_OverPct = 13,
+ S_AvgGr = 14, S_WinMaxGr = 15, S_RelNow = 16, S_RelMin = 17, S_RelMax = 18, S_Clips = 19, S_SampleRate = 20,
+ S_Cpu = 21, S_Latency = 22, S_WinInPeak = 23, S_WinOutPeak = 24, S_Delta = 29, S_Measured = 30,
+ kTele = 40, kLvl = 64, kLoud = 120;
+ private const int L_In = 0, L_Out = 1, L_GrMax = 2, L_Clip = 3, L_GrAvg = 6;
+ private const int kLvlAt = kTele, kLoudAt = kTele + 7 * kLvl, kScope = kLoudAt + 3 * kLoud;
+ private const int A_ResetPeaks = 0, A_ResetLoudness = 1;
- public double Width => 700;
+ private static readonly string[] CharNames = { "Clean", "Punch", "Glue" };
+ private static readonly string[] CharWords = { "transparent", "lets the attack through", "slow and dense" };
+ private static readonly (string Name, float Lufs)[] Targets =
+ {
+ ("−23\u2009LUFS · broadcast", -23), ("−18\u2009LUFS · audiobook", -18), ("−16\u2009LUFS · podcast", -16), ("−14\u2009LUFS · streaming", -14),
+ ("−11\u2009LUFS · loud", -11), ("−9\u2009LUFS · club", -9), ("−8\u2009LUFS · very loud", -8),
+ };
- public string? Subtitle => "LIMITER"; // the processing type, shown as the header badge
+ public double Width => 700;
public bool FullBleed => true;
+ public string? Subtitle => "LIMITER";
public Control Build(DeviceCardContext ctx, int index)
{
- var engine = ctx.Engine; int track = ctx.TrackId, di = index;
+ var engine = ctx.Engine;
+ int track = ctx.TrackId, di = index;
+ var mn = new float[kParams];
+ var mx = new float[kParams];
+ for (int p = 0; p < kParams; p++) { mn[p] = engine.DeviceParamMin(track, di, p); mx[p] = engine.DeviceParamMax(track, di, p); if (mx[p] <= mn[p]) mx[p] = mn[p] + 1; }
float P(int p) => engine.DeviceGetParam(track, di, p);
- float Mn(int p) => engine.DeviceParamMin(track, di, p);
- float Mx(int p) => engine.DeviceParamMax(track, di, p);
- void SetR(int p, float v) => engine.DeviceSetParam(track, di, p, v);
- int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p)), 0, n - 1);
+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void Raw(int p, float v) => engine.DeviceSetParam(track, di, p, Math.Clamp(v, mn[p], mx[p]));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ bool On(int p) => P(p) >= 0.5f;
+ int CharI() => Math.Clamp((int)Math.Round(P(Character)), 0, 2);
+
+ // ---- 0..1 mappings per param (release and the key high-pass are log) ----------
+ double ToN(int p, double v) => p switch
+ {
+ Release or ScHp => Math.Log(Math.Clamp(v, mn[p], mx[p]) / mn[p]) / Math.Log(mx[p] / mn[p]),
+ _ => (v - mn[p]) / (mx[p] - mn[p]),
+ };
+ double FromN(int p, double n)
+ {
+ n = Math.Clamp(n, 0, 1);
+ return p switch
+ {
+ Release or ScHp => mn[p] * Math.Pow(mx[p] / mn[p], n),
+ _ => mn[p] + n * (mx[p] - mn[p]),
+ };
+ }
+ double N(int p) => ToN(p, P(p));
+ void SetN(int p, double n) => Raw(p, (float)FromN(p, n));
+ double DefN(int p) => ToN(p, engine.DeviceParamDefault(track, di, p));
var readouts = new List<Action>();
- var scope = new float[8];
-
- // Rolling meter history for the two plots.
- var meters = new CeilingMeters();
- var levelPlot = new CeilingLevelPlot(meters) { VerticalAlignment = VerticalAlignment.Stretch };
- var grLane = new CeilingGrLane(meters) { Height = 46 };
-
- // Peak-holds are latched on the UI side so "Reset peaks" is trivial.
- float peakInHold = -120, peakOutHold = -120, maxGrHold = 0, truePeakHold = -120;
-
- Control Lbl(string t, double fs, IBrush c, bool bold = true) => new TextBlock { Text = t, FontSize = fs,
- FontWeight = bold ? FontWeight.Bold : FontWeight.Normal, Foreground = c, VerticalAlignment = VerticalAlignment.Center };
-
- // Horizontal slider (label · track · value) over a raw param; optional log scale.
- Control HSlider(int p, string name, Func<double, string> fmt, bool log, IBrush accent, double tw, double lw = 0)
- {
- double mn = Mn(p), mx = Mx(p);
- double lmn = log ? Math.Log(mn) : mn, lspan = (log ? Math.Log(mx) : mx) - lmn;
- double NormOf(double v) { double x = log ? Math.Log(Math.Clamp(v, mn, mx)) : Math.Clamp(v, mn, mx); return (x - lmn) / Math.Max(1e-9, lspan); }
- double ValOf(double n) { double x = lmn + Math.Clamp(n, 0, 1) * lspan; return log ? Math.Exp(x) : x; }
- var row = DeviceCardKit.SliderRow(name, () => NormOf(P(p)), n => { SetR(p, (float)ValOf(n)); }, () => fmt(P(p)), out var sync,
- begin: () => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, ""),
- end: () => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, ""),
- labelWidth: lw, trackWidth: tw, valueWidth: 40);
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
+ var scope = new float[kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+ double ScDb(int i) => scN > i ? scope[i] : -120;
+
+ // ---- units ----------------------------------------------------------------
+ static string Sgn(double v) => NotaNum.F($"{v:+0.0;−0.0;0.0}");
+ static string Lvl(double db) => db <= -119 ? "—" : Sgn(db);
+ static string Lufs(double v) => v <= -119 ? "—" : NotaNum.F($"{v:0.0}");
+ static string GrF(double gr) => gr > 0.05 ? NotaNum.F($"−{gr:0.0}") : "0.0";
+ static string MsF(double ms) => ms < 10 ? NotaNum.F($"{ms:0.0} ms") : NotaNum.F($"{ms:0} ms");
+ static string HzF(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0} k") : NotaNum.F($"{hz:0} Hz");
+ bool Tp() => On(TruePeak);
+ string CeilF(double v) => NotaNum.F($"{v:0.0} dB") + (Tp() ? "\u2009TP" : "");
+ string GainF(double v) => Sgn(v);
+ string RelF(double v) => On(AutoRelease) ? "auto" : MsF(v);
+ string LookF(double v) => MsF(v);
+ static string LinkF(double v) => NotaNum.F($"{v:0} %");
+ string HpF(double v) => v <= 20.5 ? "off" : HzF(v);
+ static string TargetF(double v) => NotaNum.F($"{v:0} LUFS");
+ bool HaveI() => ScDb(S_LufsI) > -119;
+ double FromTarget() => Sc(S_LufsI) - P(Target);
+ string TargetWords()
+ {
+ if (!HaveI()) return "measuring…";
+ double d = FromTarget();
+ return Math.Abs(d) <= 1 ? "on target" : d > 0 ? NotaNum.F($"{d:0.0}\u2009LU loud") : NotaNum.F($"{-d:0.0}\u2009LU quiet");
+ }
+
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static StackPanel Row(double sp, params Control[] cs)
+ { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+
+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
+ // `lit` lights the label and value (the knob that matters now); `arc` recolours the arc.
+ Control K(int p, string name, Func<double, string> fmt, string tip, Func<bool>? lit = null, Func<bool>? teal = null)
+ {
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(N(p), 1.0) { Accent = true, Default = DefN(p), Width = 34, Height = 34 };
+ knob.ValueChanged += v => { SetN(p, v); val.Text = fmt(P(p)); RefreshAll(); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ ToolTip.SetTip(knob, tip);
+ var cell = KnobCell(name, knob, val, 52);
+ TextBlock? label = null;
+ if (cell is Panel pl) foreach (var c in pl.Children) if (c is TextBlock tb && tb != val) { label = tb; break; }
+ readouts.Add(() =>
+ {
+ knob.ArcColor = teal?.Invoke() == true ? Teal : null;
+ if (!knob.Dragging) { double c = N(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; }
+ val.Text = fmt(P(p));
+ bool on = lit?.Invoke() ?? false;
+ val.Foreground = on ? AccentBright : TextPrimary;
+ if (label is not null) label.Foreground = on ? AccentBright : TextTertiary;
+ });
+ return cell;
+ }
+
+ // On/off switch bound to a param (>= 0.5 = on).
+ Control Toggle(int p, string label, string tip)
+ {
+ var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); RefreshAll(); }, out var sync);
readouts.Add(sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), name);
- return row;
- }
- Control Toggle(int p, string label, IBrush tint)
- {
- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold } };
- void Hi() { bool on = P(p) > 0.5f; b.Background = on ? NotaPalette.AccentSubtle : Sunken; b.BorderBrush = on ? NotaPalette.BorderBrass : BorderDef; ((TextBlock)b.Child!).Foreground = on ? NotaPalette.AccentHover : TextTertiary; }
- b.PointerPressed += (_, _) => { SetR(p, P(p) > 0.5f ? 0f : 1f); Hi(); };
- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), label);
- readouts.Add(Hi); Hi(); return b;
- }
-
- string DbT(double v) => $"{v:0.0}\u2009dB";
- string Db1(double v) => $"{v:+0.0;−0.0;0.0}";
- string Ms(double v) => v < 10 ? $"{v:0.0}\u2009ms" : $"{v:0}\u2009ms";
- string Pct(double v) => $"{v:0}\u2009%";
- string MDb(double v) => v <= -119 ? "—" : $"{v:+0.0;−0.0;0.0}";
-
- // ---------- LIVE strip: GR readout + Ceiling/Gain/Release + auto-release ----------
- var grNum = new TextBlock { Text = "0.0", FontSize = 14, FontWeight = FontWeight.SemiBold, Foreground = Teal, VerticalAlignment = VerticalAlignment.Center };
- grNum.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var grFill = new Border { Height = 8, Background = Teal, CornerRadius = NotaRadius.Control, HorizontalAlignment = HorizontalAlignment.Left };
- var grBar = new Border { Width = 96, Height = 8, Background = Sunken, CornerRadius = NotaRadius.Control, ClipToBounds = true, VerticalAlignment = VerticalAlignment.Center, Child = grFill };
- var live = new Border { Height = 34, Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(9, 0), Children = {
- Lbl("GR", 8, TextTertiary), grNum, grBar,
- HSlider(Ceil, "CEILING", DbT, false, Brass, 58), HSlider(Gain, "GAIN", Db1, false, Brass, 52), HSlider(Release, "RELEASE", Ms, true, Brass, 52),
- Toggle(AutoRelease, "AUTO RELEASE", Teal) } } };
-
- // ---------- graphs column: level plot fills, GR lane docked below ----------
- var grLaneWrap = new Border { Height = 46, Margin = new Thickness(0, 5, 0, 0), Child = grLane };
- DockPanel.SetDock(grLaneWrap, Dock.Bottom);
- var graphs = new DockPanel { LastChildFill = true, Children = { grLaneWrap, levelPlot } };
- var graphsHost = new Border { Margin = new Thickness(8, 7, 0, 7), Child = graphs };
-
- // ---------- right rail: CHARACTER + loudness + advanced + sidechain ----------
- var charHi = new List<Action>();
- Control CharChip(int i)
- {
- var name = new TextBlock { Text = Chars[i].n, FontSize = 9, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };
- var sub = new TextBlock { Text = Chars[i].sub, FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right };
- var row = new DockPanel { LastChildFill = false, Children = { name } };
- DockPanel.SetDock(sub, Dock.Right); row.Children.Add(sub);
- var b = new Border { Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(7, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = row };
- void Hi() { bool on = Sel(Character, 3) == i; b.Background = on ? Brass : Brushes.Transparent; b.BorderBrush = on ? Brass : BorderDef; name.Foreground = on ? NotaPalette.TextOnAccent : TextSecondary; sub.Foreground = on ? NotaPalette.TextOnAccent : TextTertiary; }
- b.PointerPressed += (_, _) => { SetR(Character, i); foreach (var a in charHi) a(); };
- charHi.Add(Hi); readouts.Add(Hi); Hi();
- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, Character), engine.DeviceParamName(track, di, Character));
+ Learn(wrap, p);
+ ToolTip.SetTip(wrap, tip);
+ return wrap;
+ }
+
+ // A latching chip: lit when `lit()`, a click runs `click`. `fill` = a full-width button.
+ Border Chip(int p, Func<bool> lit, Action click, string text, string tip, bool fill = false)
+ {
+ var tb = new TextBlock { Text = text, FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ if (fill) b.HorizontalAlignment = HorizontalAlignment.Stretch;
+ void Hi()
+ {
+ bool on = lit();
+ b.Background = on ? NotaPalette.AccentSubtle : fill ? Raised : Brushes.Transparent;
+ b.BorderBrush = on ? Brass : fill ? Brushes.Transparent : NotaPalette.BorderStrong;
+ tb.Foreground = on ? AccentBright : fill ? TextPrimary : TextSecondary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); RefreshAll(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ if (p >= 0) Learn(b, p);
+ readouts.Add(Hi); Hi();
return b;
}
- var charStack = new StackPanel { Spacing = 3, Children = { Lbl("CHARACTER", 8, TextTertiary) } };
- for (int i = 0; i < 3; i++) charStack.Children.Add(CharChip(i));
-
- // Loudness meta grid (2 columns, 3 rows).
- var metaGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), RowDefinitions = new RowDefinitions("Auto,Auto,Auto"), ColumnSpacing = 8, RowSpacing = 3 };
- TextBlock MetaCell(string label, int col, int row, out TextBlock value)
- {
- var l = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
- var v = new TextBlock { FontSize = 9, Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };
- v.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var d = new DockPanel { LastChildFill = false, Children = { l } };
- DockPanel.SetDock(v, Dock.Right); d.Children.Add(v);
- Grid.SetColumn(d, col); Grid.SetRow(d, row); metaGrid.Children.Add(d);
- value = v; return l;
- }
- MetaCell("PEAK IN", 0, 0, out var vPeakIn); MetaCell("PEAK OUT", 1, 0, out var vPeakOut);
- MetaCell("MAX GR", 0, 1, out var vMaxGr); MetaCell("LUFS-S", 1, 1, out var vLufsS);
- MetaCell("LUFS-I", 0, 2, out var vLufsI); MetaCell("TRUE PK", 1, 2, out var vTruePeak);
-
- // Advanced (teal — detector shaping).
- var advBox = new Border { BorderThickness = new Thickness(2, 0, 0, 0), BorderBrush = Teal, Padding = new Thickness(6, 0, 0, 0),
- Child = new StackPanel { Spacing = 3, Children = {
- HSlider(Lookahead, "LOOK", Ms, false, Teal, 96, lw: 34), HSlider(StereoLink, "LINK", Pct, false, Teal, 96, lw: 34) } } };
-
- // Side-chain source picker (compact) + Reset peaks.
- var scIds = new List<int> { -1 };
- var scCombo = new ComboBox { FontSize = 9, Height = 20, MinWidth = 96 };
- scCombo.Items.Add("SC: Internal");
- for (int i = 0; i < engine.TrackCount; i++) { if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue; scIds.Add(ti.Id); scCombo.Items.Add($"SC: {i + 1} · {(ti.IsReturn ? "Ret" : ti.IsInstrument ? "Instr" : "Aud")}"); }
- scCombo.SelectedIndex = Math.Max(0, scIds.IndexOf(engine.DeviceSidechainSource(track, di)));
- scCombo.SelectionChanged += (_, _) => { int s = scCombo.SelectedIndex; if (s >= 0 && s < scIds.Count) { engine.SetDeviceSidechainSource(track, di, scIds[s]); ctx.NotifyChanged(); } };
- var resetBtn = new Border { CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderStrong, Background = Card2, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
- Child = new TextBlock { Text = "Reset peaks", FontSize = 9, Foreground = TextSecondary } };
- resetBtn.PointerPressed += (_, _) => { peakInHold = -120; peakOutHold = -120; maxGrHold = 0; truePeakHold = -120; };
- var bottomRow = new DockPanel { LastChildFill = false, Children = { scCombo } };
- DockPanel.SetDock(resetBtn, Dock.Right); bottomRow.Children.Add(resetBtn);
-
- IBrush Div() => NotaPalette.SurfaceRaised;
- var rail = new Border { Width = 224, Background = NotaPalette.SurfaceInset, BorderBrush = BorderDef, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 7),
- Child = new StackPanel { Spacing = 5, Children = {
- charStack,
- new Border { Height = 1, Background = Div() },
- metaGrid,
- new Border { Height = 1, Background = Div() },
- advBox,
- new StackPanel { VerticalAlignment = VerticalAlignment.Bottom, Children = { bottomRow } } } } };
- DockPanel.SetDock(rail, Dock.Right);
-
- var body = new DockPanel { LastChildFill = true, Children = { rail, graphsHost } };
-
- // ---------- live refresh ----------
+ Control ParamChip(int p, string text, string tip) => Chip(p, () => On(p), () => SetP(p, On(p) ? 0f : 1f), text, tip);
+
+ // Slider row: caps label · track · mono value.
+ Control SliderRow(string label, int p, Func<double, string> fmt, bool modulation = false, Func<bool>? lit = null)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => N(p), v => { SetN(p, v); RefreshAll(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: 38, modulation: modulation);
+ readouts.Add(sync);
+ Learn(bar, p);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("34,*"), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label));
+ g.Children.Add(Col(bar, 1));
+ if (lit is not null)
+ readouts.Add(() =>
+ {
+ bool on = lit();
+ foreach (var c in bar.Children) if (c is TextBlock tb && tb.TextAlignment == TextAlignment.Right) tb.Foreground = on ? AccentBright : TextPrimary;
+ });
+ return g;
+ }
+
+ // A dropdown: [label value ▾] opens `items`; the current one is dotted.
+ Border Drop(string caps, Func<string> text, Func<bool> hot, Func<IEnumerable<(string Label, bool Current, Action Pick)>> items, string tip, int learnParam = -1)
+ {
+ var name = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var chev = new Glyph(GlyphKind.ChevronDown, 7) { Margin = new Thickness(6, 0, 0, 0) };
+ var inner = new DockPanel { Children = { Docked(chev, Dock.Right) } };
+ if (caps.Length > 0) inner.Children.Add(Docked(new Border { Padding = new Thickness(0, 0, 6, 0), Child = Caps(caps) }, Dock.Left));
+ inner.Children.Add(name);
+ var box = new Border
+ {
+ Height = 16, Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,
+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = inner,
+ };
+ readouts.Add(() =>
+ {
+ bool h = hot();
+ name.Text = text();
+ name.Foreground = h ? AccentBright : TextPrimary;
+ box.BorderBrush = h ? Brass : BorderDef;
+ chev.Foreground = h ? NotaPalette.AccentDim : TextTertiary;
+ });
+ ToolTip.SetTip(box, tip);
+ if (learnParam >= 0) Learn(box, learnParam);
+ box.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;
+ var fly = new MenuFlyout();
+ foreach (var (label, cur, pick) in items())
+ {
+ var mi = new MenuItem { Header = label };
+ if (cur) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };
+ var pk = pick;
+ mi.Click += (_, _) => { pk(); RefreshAll(); };
+ fly.Items.Add(mi);
+ }
+ fly.ShowAt(box);
+ e.Handled = true;
+ };
+ return box;
+ }
+
+ // Key source: Internal, or another track (the device's sidechain routing).
+ string SrcName(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 Src() => engine.DeviceSidechainSource(track, di);
+ bool ExtOn() => Src() >= 0;
+ string KeyName() => ExtOn() ? SrcName(Src()) : "Internal";
+ Control KeyDrop() => Drop("SC", KeyName, ExtOn, () =>
+ {
+ var list = new List<(string, bool, Action)>
+ {
+ ("Internal — this track", !ExtOn(), () => { 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((SrcName(id), Src() == id, () => { engine.SetDeviceSidechainSource(track, di, id); ctx.NotifyChanged(); }));
+ }
+ return list;
+ }, "Key source — Internal limits on this track's own peaks; pick another track to duck this one when that one peaks");
+
+ Control TargetDrop() => Drop("", () => TargetF(P(Target)), () => false, () =>
+ {
+ var list = new List<(string, bool, Action)>();
+ foreach (var (label, v) in Targets) { float vv = v; list.Add((label, Math.Abs(P(Target) - vv) < 0.05f, () => SetP(Target, vv))); }
+ return list;
+ }, "Target — the loudness the meters compare against: −14 for streaming, −16 podcasts, −23 broadcast. It does not change the sound; drag the dashed line for any value", Target);
+
+ static Grid HeadRow(Control left, Control right)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 18, ColumnSpacing = 6 };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
+ }
+ Control CharSeg(bool words = true)
+ {
+ var seg = Segments(CharNames, CharI, i => { SetP(Character, i); RefreshAll(); }, out var sync, padX: 6);
+ readouts.Add(sync);
+ Learn(seg, Character);
+ ToolTip.SetTip(seg, "Character — Clean: transparent, the fastest attack; Punch: a slower attack lets the transient through to the clip; Glue: a slow release and a soft knee under the ceiling");
+ var wordsTb = new TextBlock { FontSize = 7, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ readouts.Add(() => wordsTb.Text = CharWords[CharI()]);
+ return words ? Row(6, Caps("CHARACTER"), seg, wordsTb) : Row(6, Caps("CHARACTER"), seg);
+ }
+ Control Info(Func<string> text, IBrush? ink = null)
+ {
+ var t = Mono("", 7, ink ?? AccentBright);
+ readouts.Add(() => t.Text = text());
+ return t;
+ }
+
+ // The knob row under every graph: Gain, Ceiling, Release, the two chips, two info lines.
+ int centreTab = 0;
+ Control KnobRow(Func<string> info1, Func<string> info2)
+ {
+ var i1 = Mono("", 7, TextTertiary); i1.HorizontalAlignment = HorizontalAlignment.Right;
+ var i2 = Mono("", 7, TextTertiary); i2.HorizontalAlignment = HorizontalAlignment.Right;
+ i1.TextTrimming = i2.TextTrimming = TextTrimming.CharacterEllipsis;
+ readouts.Add(() => { i1.Text = info1(); i2.Text = info2(); });
+ var chips = new StackPanel
+ {
+ Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children =
+ {
+ ParamChip(AutoRelease, "Auto rel", "Auto release — the release slows as the reduction deepens (up to 5× at 7\u2009dB), so dense passages don't pump"),
+ ParamChip(TruePeak, "True peak", "True peak — the detector reads the inter-sample peak (4×), so the ceiling holds in dBTP after conversion"),
+ },
+ };
+ var knobs = Row(2,
+ K(Gain, "GAIN", GainF, "Gain — how hard the signal is driven into the ceiling", lit: () => centreTab != 1),
+ K(Ceil, "CEILING", v => NotaNum.F($"{v:0.0}\u2009dB"), "Ceiling — the output never goes above it (in dBTP with True peak on)"),
+ K(Release, "RELEASE", RelF, "Release — how fast the gain comes back (the character scales it; Auto rel lets the signal decide)",
+ lit: () => centreTab == 1, teal: () => On(AutoRelease)));
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), Height = 52, ColumnSpacing = 8 };
+ g.Children.Add(knobs);
+ g.Children.Add(Col(chips, 1));
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { i1, i2 } }, 2));
+ return g;
+ }
+ static Control TabBody(Control head, Control window, Control knobs) => new DockPanel
+ {
+ LastChildFill = true, Margin = new Thickness(8, 5, 8, 0),
+ Children = { Docked(head, Dock.Top), Docked(knobs, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 0), Child = window } },
+ };
+ void WireDrag(ShDragView v, int param)
+ {
+ v.Value = _ => N(param);
+ v.Changed += (_, x) => { SetN(param, x); RefreshAll(); };
+ v.GestureBegin += _ => Begin(param);
+ v.GestureEnd += _ => End(param);
+ v.ResetRequested += _ => { Reset(param); RefreshAll(); };
+ Learn(v, param);
+ }
+ string ReleaseRange()
+ {
+ if (!On(AutoRelease)) return "release " + MsF(Sc(S_RelNow) > 0 ? Sc(S_RelNow) : P(Release));
+ double lo = Sc(S_RelMin), hi = Sc(S_RelMax);
+ return Math.Abs(hi - lo) < 1 ? "release " + MsF(lo) + " · auto" : NotaNum.F($"release {lo:0}…{hi:0} ms by the signal");
+ }
+ string ClipText()
+ {
+ int n = (int)Sc(S_Clips);
+ string times = n == 1 ? "time" : "times";
+ return CharI() == 1 ? NotaNum.F($"attack passed to the clip · {n} {times}") : NotaNum.F($"reached the clip · {n} {times}");
+ }
+
+ // ======================================================================
+ // LEFT — LIMIT column (input · reduction · output)
+ // ======================================================================
+ var colTitle = Caps("LIMIT"); colTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var inPill = new ShPill { Ink = Teal, VerticalAlignment = VerticalAlignment.Stretch, Width = 12 };
+ var grPill = new ShPill { Ink = AccentBright, FromTop = true, VerticalAlignment = VerticalAlignment.Stretch, Width = 12 };
+ var outPill = new ShPill { Ink = Brass, VerticalAlignment = VerticalAlignment.Stretch, Width = 12 };
+ ToolTip.SetTip(inPill, "The input after Gain, with the ceiling marked");
+ ToolTip.SetTip(grPill, "Gain reduction, 0 … 24\u2009dB");
+ ToolTip.SetTip(outPill, "The output");
+ var colGr = Mono("", 7, AccentBright); colGr.HorizontalAlignment = HorizontalAlignment.Center;
+ var colOut = Mono("", 7, TextPrimary); colOut.HorizontalAlignment = HorizontalAlignment.Center;
+ static double NormLvl(double db) => Math.Clamp((db + 48) / 60, 0, 1); // −48 … +12 dBFS
+ readouts.Add(() =>
+ {
+ inPill.Set(NormLvl(ScDb(S_InPeak)), NormLvl(P(Ceil)));
+ grPill.Set(Math.Clamp(Sc(S_Gr) / 24, 0, 1), double.NaN);
+ outPill.Set(NormLvl(ScDb(S_OutPeak)), double.NaN);
+ colGr.Text = GrF(Sc(S_Gr));
+ colOut.Text = Lvl(ScDb(S_OutPeak));
+ colTitle.Foreground = Sc(S_Gr) > 0.1 ? AccentBright : TextTertiary; // lit while it limits
+ });
+ Control PillCol(ShPill pill, string lbl)
+ {
+ var l = Caps(lbl); l.HorizontalAlignment = HorizontalAlignment.Center;
+ return new DockPanel { Children = { Docked(l, Dock.Bottom), new Border { Margin = new Thickness(0, 0, 0, 3), HorizontalAlignment = HorizontalAlignment.Center, Child = pill } } };
+ }
+ var pills = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto"), ColumnSpacing = 5, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 4) };
+ pills.Children.Add(PillCol(inPill, "IN"));
+ pills.Children.Add(Col(PillCol(grPill, "GR"), 1));
+ pills.Children.Add(Col(PillCol(outPill, "OUT"), 2));
+ var leftCol = new Border
+ {
+ Width = 64, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(colTitle, Dock.Top), Docked(colOut, Dock.Bottom), Docked(colGr, Dock.Bottom), pills } },
+ };
+ DockPanel.SetDock(leftCol, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — Level / Reduction / Loudness
+ // ======================================================================
+ CeLevelView? level = null;
+ Control LevelTab()
+ {
+ level = new CeLevelView { CeilToNorm = db => ToN(Ceil, db) };
+ WireDrag(level, Ceil);
+ ToolTip.SetTip(level, "The last 4 s: the input (teal), the part over the ceiling (red) and the output (brass), with the reduction under it. Drag the ceiling line; double-click resets.");
+ var head = HeadRow(CharSeg(), Info(() => "ceiling " + CeilF(P(Ceil))));
+ var knobs = KnobRow(
+ () => ScDb(S_WinInPeak) <= -119 ? "no signal" : NotaNum.F($"in {Lvl(ScDb(S_WinInPeak))} → out {Lvl(ScDb(S_WinOutPeak))}"),
+ () => NotaNum.F($"over {Sc(S_OverPct) * 100:0} % of the time"));
+ return TabBody(head, level, knobs);
+ }
+
+ CeReductionView? reduction = null;
+ Control ReductionTab()
+ {
+ reduction = new CeReductionView();
+ ToolTip.SetTip(reduction, "The gain reduction over the last 4 s: teal where a transient got through to the clip, the dashed line is the mean");
+ var head = HeadRow(CharSeg(), Info(() => NotaNum.F($"avg {GrF(Sc(S_AvgGr))} · max {GrF(Sc(S_WinMaxGr))}")));
+ var knobs = KnobRow(ReleaseRange, ClipText);
+ return TabBody(head, reduction, knobs);
+ }
+
+ CeLoudnessView? loudness = null;
+ Control LoudnessTab()
+ {
+ loudness = new CeLoudnessView { TargetToNorm = t => ToN(Target, t) };
+ WireDrag(loudness, Target);
+ ToolTip.SetTip(loudness, "Momentary (teal), short-term (brass) and integrated (Ink) loudness over the last 60 s around the target, ±1 LU shaded. Drag the target line; double-click resets.");
+ var head = HeadRow(Row(6, CharSeg(false), Caps("TARGET"), TargetDrop()),
+ Info(() => HaveI() ? NotaNum.F($"{FromTarget():+0.0;−0.0;0.0}\u2009LU from target") : "measuring…"));
+ var knobs = KnobRow(
+ () => NotaNum.F($"LRA {Sc(S_Lra):0.0}\u2009LU · PLR {(HaveI() ? NotaNum.F($"{Sc(S_Plr):0.0}") : "—")}"),
+ () => NotaNum.F($"GR on average {GrF(Sc(S_AvgGr))}\u2009dB"));
+ return TabBody(head, loudness, knobs);
+ }
+
+ // ======================================================================
+ // RIGHT — Meters / Detector
+ // ======================================================================
+ static Control Spread(params Control[] rows)
+ {
+ var defs = new List<string>();
+ for (int i = 0; i < rows.Length; i++) { if (i > 0) defs.Add("*"); defs.Add("Auto"); }
+ var g = new Grid { RowDefinitions = new RowDefinitions(string.Join(",", defs)) };
+ for (int i = 0; i < rows.Length; i++) g.Children.Add(GRow(rows[i], i * 2));
+ return new Border { Padding = new Thickness(8, 6), Child = g };
+ }
+ Control MeterGrid(params (string Key, Func<string> Val, Func<IBrush> Ink)[] cells)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,*,Auto"), ColumnSpacing = 6, RowSpacing = 3 };
+ for (int i = 0; i < (cells.Length + 1) / 2; i++) g.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
+ for (int i = 0; i < cells.Length; i++)
+ {
+ var (key, val, ink) = cells[i];
+ int r = i / 2, c = (i % 2) * 2;
+ var k = new TextBlock { Text = key, FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(c > 0 ? 4 : 0, 0, 0, 0) };
+ var v = Mono("", 8, TextPrimary); v.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => { v.Text = val(); v.Foreground = ink(); });
+ g.Children.Add(GRow(Col(k, c), r));
+ g.Children.Add(GRow(Col(v, c + 1), r));
+ }
+ return new Border { Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 5), Child = g };
+ }
+ IBrush OverInk(double db, double limit) => db > limit + 0.05 ? NotaPalette.DangerBright : TextPrimary;
+ Control ResetRow(bool loud)
+ {
+ var reset = Chip(-1, () => false, () => engine.DeviceAction(track, di, loud ? A_ResetLoudness : A_ResetPeaks, 0, 0),
+ loud ? "Reset" : "Reset peaks", loud ? "Reset — start the integrated loudness, the range and the peaks again" : "Reset peaks — clear the peak holds, the max reduction and the clip count", fill: true);
+ reset.HorizontalAlignment = HorizontalAlignment.Right;
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6 };
+ g.Children.Add(KeyDrop());
+ g.Children.Add(Col(reset, 1));
+ return new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = g };
+ }
+ Control DeltaSwitch() => Toggle(DeltaP, "Delta · hear what it removes", "Delta — play the difference between the input and the output: what the limiter takes away");
+ Control LookRow() => SliderRow("LOOK", Lookahead, LookF, lit: () => false);
+ Control LinkRow() => SliderRow("LINK", StereoLink, LinkF);
+
+ Control MetersTab() => Spread(
+ MeterGrid(
+ ("peak in", () => Lvl(ScDb(S_PeakInHold)), () => OverInk(ScDb(S_PeakInHold), 0)),
+ ("peak out", () => Lvl(ScDb(S_PeakOutHold)), () => TextPrimary),
+ ("max GR", () => GrF(Sc(S_MaxGrHold)), () => AccentBright),
+ ("LUFS-S", () => Lufs(ScDb(S_LufsS)), () => TextPrimary),
+ ("LUFS-I", () => Lufs(ScDb(S_LufsI)), () => TextPrimary),
+ ("true pk", () => Lvl(ScDb(S_TpHold)), () => OverInk(ScDb(S_TpHold), P(Ceil)))),
+ LookRow(), LinkRow(), ResetRow(false), DeltaSwitch());
+
+ Control LoudMetersTab()
+ {
+ var big = Mono("", 16, AccentBright);
+ var unit = new TextBlock { Text = "LUFS", FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 2) };
+ var verdict = Mono("", 8, Success); verdict.HorizontalAlignment = HorizontalAlignment.Right; verdict.VerticalAlignment = VerticalAlignment.Bottom;
+ readouts.Add(() =>
+ {
+ big.Text = HaveI() ? NotaNum.F($"{Sc(S_LufsI):0.0}") : "—";
+ verdict.Text = TargetWords();
+ verdict.Foreground = HaveI() && Math.Abs(FromTarget()) <= 1 ? Success : HaveI() ? NotaPalette.Warning : TextTertiary;
+ });
+ var line = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 4 };
+ line.Children.Add(big); line.Children.Add(Col(unit, 1)); line.Children.Add(Col(verdict, 2));
+ var box = new Border
+ {
+ Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 1, Children = { Caps("INTEGRATED"), line } },
+ };
+ ToolTip.SetTip(box, "Integrated loudness since the last Reset, gated (BS.1770), against the Target");
+ return Spread(box,
+ MeterGrid(
+ ("LUFS-S", () => Lufs(ScDb(S_LufsS)), () => TextPrimary),
+ ("LUFS-M", () => Lufs(ScDb(S_LufsM)), () => TextPrimary),
+ ("true pk", () => Lvl(ScDb(S_TpHold)), () => OverInk(ScDb(S_TpHold), P(Ceil))),
+ ("max GR", () => GrF(Sc(S_MaxGrHold)), () => AccentBright)),
+ LookRow(), ResetRow(true));
+ }
+
+ Control DetectorTab()
+ {
+ var t = Caps("DETECTOR");
+ var dot = new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Pill, VerticalAlignment = VerticalAlignment.Center };
+ var l1 = Mono("", 9, TextPrimary);
+ var l2 = Mono("", 8, TextSecondary);
+ l1.TextTrimming = l2.TextTrimming = TextTrimming.CharacterEllipsis;
+ var box = new Border
+ {
+ Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 2, Children = { t, Row(5, dot, l1), l2 } },
+ };
+ readouts.Add(() =>
+ {
+ bool d = On(DeltaP);
+ t.Text = d ? "DELTA" : "DETECTOR";
+ t.Foreground = d ? AccentBright : TextTertiary;
+ l1.Text = d ? "hearing what it removes" : (Tp() ? "true peak · 4×" : "sample peak") + (ExtOn() ? " · key" : "");
+ l2.Text = d ? "the difference in − out" : NotaNum.F($"{KeyName()} · HP {HpF(P(ScHp))} · latency {Sc(S_Latency):0} smp");
+ l1.Foreground = d ? AccentBright : TextPrimary;
+ dot.Background = d ? Brass : Sc(S_Gr) > 0.1 ? Success : NotaPalette.BorderStrong;
+ box.BorderBrush = d ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
+ });
+ ToolTip.SetTip(box, "What the limiter listens to — or, with Delta on, that you are hearing only what it takes away");
+ return Spread(
+ LookRow(), LinkRow(),
+ SliderRow("SC HP", ScHp, HpF, modulation: true, lit: () => P(ScHp) > 20.5f),
+ ResetRow(false), box, DeltaSwitch());
+ }
+
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[3];
+ var rightBodies = new Control?[3];
+ int rightTab = 0;
+ var extras = Mono("", 7, TextTertiary);
+ readouts.Add(() =>
+ {
+ extras.Text = centreTab switch
+ {
+ 1 => NotaNum.F($"0 … −{(reduction?.Scale ?? 12):0} dB"),
+ 2 => "window 60 s",
+ _ => "window 4 s",
+ };
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => ReductionTab(), 2 => LoudnessTab(), _ => LevelTab() };
+ // Meters shows the loudness readings while the Loudness tab is up.
+ Control RightBody(int t)
+ {
+ int slot = t == 1 ? 2 : centreTab == 2 ? 1 : 0;
+ return rightBodies[slot] ??= slot switch { 2 => DetectorTab(), 1 => LoudMetersTab(), _ => MetersTab() };
+ }
+
+ var centre = TabFrame(new[] { "Level", "Reduction", "Loudness" }, centreHost, CentreBody, false, t =>
+ {
+ centreTab = t;
+ rightHost.Content = RightBody(rightTab);
+ Refresh();
+ }, extras);
+ var rightFrame = TabFrame(new[] { "Meters", "Detector" }, rightHost, RightBody, true, t => { rightTab = t; RefreshAll(); }, null);
+ var right = new Border { Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Margin = new Thickness(5, 0), ClipToBounds = true, Child = centre };
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ var parts = new List<string> { CharNames[CharI()] };
+ if (centreTab == 2) parts.Add("target " + TargetF(P(Target)));
+ parts.Add("gain " + GainF(P(Gain)));
+ parts.Add("ceiling " + CeilF(P(Ceil)));
+ parts.Add("release " + (On(AutoRelease) ? "auto" : MsF(P(Release))));
+ parts.Add("look " + LookF(P(Lookahead)));
+ if (centreTab != 2) parts.Add("link " + LinkF(P(StereoLink)));
+ if (P(ScHp) > 20.5f) parts.Add("SC HP " + HzF(P(ScHp)));
+ if (ExtOn()) parts.Add("key " + KeyName());
+ if (On(DeltaP)) parts.Add("delta");
+ return string.Join(" · ", parts);
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · latency {Sc(S_Latency):0} smp · CPU {Sc(S_Cpu) * 100:0.0} %") : "";
+ });
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft);
+ statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { leftCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
void Refresh()
{
- int cnt = engine.DeviceScope(track, di, scope, scope.Length);
- float grDb = 0, inDb = -120, outDb = -120, lufsS = -120, lufsI = -120, tpDb = -120;
- if (cnt >= 7) { inDb = scope[S_InPeak]; outDb = scope[S_OutPeak]; grDb = scope[S_Gr]; lufsS = scope[S_LufsS]; lufsI = scope[S_LufsI]; tpDb = scope[S_TruePeak]; }
- meters.Ceiling = P(Ceil);
- meters.Push(inDb, outDb, grDb);
- levelPlot.Tick(); grLane.Tick();
-
- grNum.Text = $"{-grDb:0.0}"; grNum.Foreground = grDb > 3.0f ? NotaPalette.Warning : Teal;
- grFill.Width = Math.Clamp(grDb / 6.0, 0, 1) * 96; grFill.Background = grDb > 3.0f ? NotaPalette.Warning : Teal;
-
- if (inDb > peakInHold) peakInHold = inDb;
- if (outDb > peakOutHold) peakOutHold = outDb;
- if (grDb > maxGrHold) maxGrHold = grDb;
- if (tpDb > truePeakHold) truePeakHold = tpDb;
- vPeakIn.Text = MDb(peakInHold); vPeakIn.Foreground = peakInHold > 0 ? NotaPalette.Danger : TextPrimary;
- vPeakOut.Text = MDb(peakOutHold);
- vMaxGr.Text = maxGrHold > 0.05f ? $"−{maxGrHold:0.0}" : "0.0"; vMaxGr.Foreground = maxGrHold > 3 ? NotaPalette.Warning : TextPrimary;
- vLufsS.Text = lufsS <= -119 ? "—" : $"{lufsS:0.0}";
- vLufsI.Text = lufsI <= -119 ? "—" : $"{lufsI:0.0}";
- float ceil = P(Ceil);
- vTruePeak.Text = MDb(truePeakHold);
- vTruePeak.Foreground = truePeakHold <= ceil + 0.05f ? Success : NotaPalette.Danger;
-
- foreach (var a in readouts) a();
+ scN = engine.DeviceScope(track, di, scope, kScope);
+ int n = scN >= kScope ? kLvl : 0;
+ if (centreTab == 0 && level is not null)
+ level.Set(scope, kLvlAt + L_In * kLvl, kLvlAt + L_Out * kLvl, kLvlAt + L_GrMax * kLvl, n, P(Ceil));
+ if (centreTab == 1 && reduction is not null)
+ reduction.Set(scope, kLvlAt + L_GrMax * kLvl, kLvlAt + L_Clip * kLvl, n, Sc(S_AvgGr));
+ if (centreTab == 2 && loudness is not null)
+ loudness.Set(scope, kLoudAt, kLoudAt + kLoud, kLoudAt + 2 * kLoud, scN >= kScope ? kLoud : 0, P(Target));
+ RefreshAll();
}
ctx.AddDeviceRefresher(Refresh);
Refresh();
+ return root;
- DockPanel.SetDock(live, Dock.Top);
- return new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = 0;
+ var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? Card2 : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AccentBright : TextTertiary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ int iv = i;
+ var b = new Border
+ {
+ Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };
+ btns[i] = b;
+ bar.Children.Add(b);
+ }
+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };
+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Dock.Right); barDock.Children.Add(ex); }
+ if (!centered) DockPanel.SetDock(bar, Dock.Left);
+ barDock.Children.Add(bar);
+ var barBorder = new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };
+ DockPanel.SetDock(barBorder, Dock.Top);
+ Hi();
+ host.Content = body(sel);
+ return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
+ }
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index a299640d..590e0117 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1601,13 +1601,45 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("dyneq", 13, "Warm Master", ("2 Type", 1f), ("2 Freq", 110f), ("2 Gain", 1.8f), ("7 Freq", 10000f), ("7 Mode", 1f), ("7 Thr", -18f), ("7 Rng", -3f), ("7 Atk", 20f), ("7 Rel", 250f));
Fx("dyneq", 13, "Punch Tighten", ("3 Freq", 800f), ("3 Q", 1.2f), ("3 Mode", 1f), ("3 Thr", -22f), ("3 Rng", -5f), ("3 Atk", 3f), ("3 Rel", 90f));
- // ---- Nota Ceiling (kind 14) — raw units. Character 0 Clean/1 Punch/2 Glue.
- Fx("ceiling", 14, "Master Safe", ("Ceiling", -1.0f), ("Gain", 0f), ("Release", 120f), ("Character", 0f), ("Lookahead", 3f), ("StereoLink", 100f));
- Fx("ceiling", 14, "Loud Master", ("Ceiling", -1.0f), ("Gain", 4.5f), ("Release", 100f), ("Character", 0f), ("Lookahead", 3f), ("StereoLink", 100f));
- Fx("ceiling", 14, "Streaming −1", ("Ceiling", -1.0f), ("Gain", 2f), ("Release", 150f), ("Character", 2f), ("Lookahead", 4f), ("StereoLink", 100f), ("AutoRelease", 1f));
- Fx("ceiling", 14, "Drum Punch", ("Ceiling", -0.3f), ("Gain", 6f), ("Release", 60f), ("Character", 1f), ("Lookahead", 1.5f), ("StereoLink", 60f));
- Fx("ceiling", 14, "Glue Bus", ("Ceiling", -0.5f), ("Gain", 3f), ("Release", 250f), ("Character", 2f), ("Lookahead", 5f), ("StereoLink", 100f), ("AutoRelease", 1f));
- Fx("ceiling", 14, "Transparent Safety", ("Ceiling", 0f), ("Gain", 0f), ("Release", 80f), ("Character", 0f), ("Lookahead", 2f), ("StereoLink", 100f));
+ // ---- Nota Ceiling (kind 14) — look-ahead limiter, raw units (unnamed params reset to their
+ // defaults: Ceiling −1 dB, Gain 0, Release 120 ms, Look-ahead 3 ms, Link 100 %, SC HP
+ // 20 Hz = off, Target −14 LUFS). Character 0 Clean / 1 Punch / 2 Glue; AutoRelease,
+ // True Peak, Delta 1 = on. Target only moves the loudness meters, not the sound.
+ Fx("ceiling", 14, "Init");
+ // Mastering
+ Fx("ceiling", 14, "Master Safe", ("Ceiling", -1.0f), ("Gain", 0f), ("Release", 120f), ("Character", 0f), ("Lookahead", 3f), ("StereoLink", 100f));
+ Fx("ceiling", 14, "Transparent Safety", ("Ceiling", 0f), ("Gain", 0f), ("Release", 80f), ("Character", 0f), ("Lookahead", 2f), ("StereoLink", 100f));
+ Fx("ceiling", 14, "Loud Master", ("Ceiling", -1.0f), ("Gain", 4.5f), ("Release", 100f), ("Character", 0f), ("Lookahead", 3f), ("StereoLink", 100f));
+ Fx("ceiling", 14, "Streaming −1", ("Ceiling", -1.0f), ("Gain", 2f), ("Release", 150f), ("Character", 2f), ("Lookahead", 4f), ("StereoLink", 100f), ("AutoRelease", 1f));
+ Fx("ceiling", 14, "Streaming −14", ("Ceiling", -1.0f), ("Gain", 5f), ("Release", 600f), ("Character", 2f), ("Lookahead", 5f), ("True Peak", 1f), ("Target", -14f));
+ Fx("ceiling", 14, "Apple Music −16", ("Ceiling", -1.0f), ("Gain", 3f), ("Release", 300f), ("Character", 2f), ("Lookahead", 5f), ("True Peak", 1f), ("AutoRelease", 1f), ("Target", -16f));
+ Fx("ceiling", 14, "Podcast −16", ("Ceiling", -1.0f), ("Gain", 6f), ("Release", 150f), ("Character", 0f), ("Lookahead", 5f), ("True Peak", 1f), ("AutoRelease", 1f), ("SC HP", 80f), ("Target", -16f));
+ Fx("ceiling", 14, "Broadcast R128 −23", ("Ceiling", -1.0f), ("Gain", 0f), ("Release", 250f), ("Character", 0f), ("Lookahead", 5f), ("True Peak", 1f), ("Target", -23f));
+ Fx("ceiling", 14, "Club Master −8", ("Ceiling", -0.3f), ("Gain", 9f), ("Release", 60f), ("Character", 0f), ("Lookahead", 2f), ("True Peak", 1f), ("AutoRelease", 1f), ("SC HP", 40f), ("Target", -8f));
+ Fx("ceiling", 14, "CD Brickwall", ("Ceiling", -0.1f), ("Gain", 6f), ("Release", 50f), ("Character", 0f), ("Lookahead", 1.5f), ("Target", -9f));
+ Fx("ceiling", 14, "Gentle Master", ("Ceiling", -1.0f), ("Gain", 1.5f), ("Release", 300f), ("Character", 2f), ("Lookahead", 6f), ("AutoRelease", 1f), ("True Peak", 1f));
+ Fx("ceiling", 14, "Vinyl Pre-Master", ("Ceiling", -3.0f), ("Gain", 1f), ("Release", 200f), ("Character", 2f), ("Lookahead", 5f), ("True Peak", 1f), ("SC HP", 60f), ("Target", -16f));
+ Fx("ceiling", 14, "Bass-Heavy Master", ("Ceiling", -1.0f), ("Gain", 4f), ("Release", 180f), ("Character", 0f), ("Lookahead", 4f), ("True Peak", 1f), ("AutoRelease", 1f), ("SC HP", 120f));
+ Fx("ceiling", 14, "Wide Mix Unlinked", ("Ceiling", -1.0f), ("Gain", 3f), ("Release", 120f), ("Character", 0f), ("Lookahead", 3f), ("StereoLink", 30f));
+ // Buses and tracks
+ Fx("ceiling", 14, "Drum Punch", ("Ceiling", -0.3f), ("Gain", 6f), ("Release", 60f), ("Character", 1f), ("Lookahead", 1.5f), ("StereoLink", 60f));
+ Fx("ceiling", 14, "Drum Bus", ("Ceiling", -0.3f), ("Gain", 9f), ("Release", 60f), ("Character", 1f), ("Lookahead", 1f), ("StereoLink", 60f), ("True Peak", 1f), ("AutoRelease", 1f), ("SC HP", 90f));
+ Fx("ceiling", 14, "Glue Bus", ("Ceiling", -0.5f), ("Gain", 3f), ("Release", 250f), ("Character", 2f), ("Lookahead", 5f), ("StereoLink", 100f), ("AutoRelease", 1f));
+ Fx("ceiling", 14, "Mix Bus Glue", ("Ceiling", -1.0f), ("Gain", 2f), ("Release", 400f), ("Character", 2f), ("Lookahead", 6f), ("AutoRelease", 1f), ("SC HP", 50f));
+ Fx("ceiling", 14, "Kick Clipper", ("Ceiling", -1.0f), ("Gain", 6f), ("Release", 20f), ("Character", 1f), ("Lookahead", 0f));
+ Fx("ceiling", 14, "Snare Crack", ("Ceiling", -1.0f), ("Gain", 8f), ("Release", 30f), ("Character", 1f), ("Lookahead", 0.5f), ("StereoLink", 80f));
+ Fx("ceiling", 14, "808 Safety", ("Ceiling", -1.0f), ("Gain", 2f), ("Release", 250f), ("Character", 0f), ("Lookahead", 8f));
+ Fx("ceiling", 14, "Vocal Peak Catcher", ("Ceiling", -3.0f), ("Gain", 3f), ("Release", 80f), ("Character", 0f), ("Lookahead", 2f), ("AutoRelease", 1f));
+ Fx("ceiling", 14, "Guitar Wall", ("Ceiling", -1.0f), ("Gain", 6f), ("Release", 200f), ("Character", 2f), ("Lookahead", 3f), ("SC HP", 100f));
+ Fx("ceiling", 14, "Synth Lead Tamer", ("Ceiling", -2.0f), ("Gain", 4f), ("Release", 90f), ("Character", 0f), ("Lookahead", 2f), ("StereoLink", 70f));
+ Fx("ceiling", 14, "Headroom −6", ("Ceiling", -6.0f), ("Gain", 0f), ("Release", 150f), ("Character", 0f), ("Lookahead", 3f), ("True Peak", 1f));
+ // Live and effects
+ Fx("ceiling", 14, "Live Zero Latency", ("Ceiling", -0.5f), ("Gain", 0f), ("Release", 100f), ("Character", 2f), ("Lookahead", 0f));
+ Fx("ceiling", 14, "Soft Clip Warmth", ("Ceiling", -1.0f), ("Gain", 4f), ("Release", 50f), ("Character", 2f), ("Lookahead", 0f));
+ Fx("ceiling", 14, "Pumping Smash", ("Ceiling", -1.0f), ("Gain", 14f), ("Release", 400f), ("Character", 2f), ("Lookahead", 0f), ("SC HP", 20f));
+ Fx("ceiling", 14, "Brickwall Crush", ("Ceiling", -1.0f), ("Gain", 20f), ("Release", 25f), ("Character", 0f), ("Lookahead", 1f));
+ Fx("ceiling", 14, "Lo-Fi Squash", ("Ceiling", -6.0f), ("Gain", 24f), ("Release", 10f), ("Character", 1f), ("Lookahead", 0f), ("StereoLink", 0f));
+ Fx("ceiling", 14, "Hear the Squash", ("Ceiling", -1.0f), ("Gain", 8f), ("Release", 120f), ("Character", 0f), ("Lookahead", 3f), ("Delta", 1f));
// ---- Nota Strata (kind 15) — looper settings only (recorded audio isn't a preset).
// Quantize 0 Off / 1 Bar / 2 1-4.
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index e6613aee..4571a685 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.")]
+ [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers.")]
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). 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. 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));
@@ -430,6 +430,64 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
V(24) > 0.5f, R1(win), steps.ToArray(), V(15));
});
+ public sealed record CeilingCell(double Seconds, double InputDb, double OutputDb, double ReductionDb, bool Clipped);
+ public sealed record CeilingLoudness(double Seconds, double MomentaryLufs, double ShortTermLufs, double IntegratedLufs);
+ public sealed record CeilingReading(string Summary, string Live, string Character, double CeilingDb, bool TruePeakMode, bool Delta,
+ double ReductionDb, double AvgReductionDb, double MaxReductionDb, double MaxReductionHoldDb, double InputDb, double OutputDb,
+ double PeakInHoldDb, double PeakOutHoldDb, double TruePeakHoldDb, double OverShare, double ReleaseMs, double ReleaseMinMs,
+ double ReleaseMaxMs, int Clips, double MomentaryLufs, double ShortTermLufs, double IntegratedLufs, double TargetLufs,
+ double FromTargetLu, double LraLu, double PlrDb, double MeasuredSeconds, int LatencySamples, double SampleRate,
+ CeilingCell[] Level, CeilingLoudness[] Loudness);
+
+ [McpServerTool(Name = "read_ceiling"), Description(
+ "Read what a Nota Ceiling (built-in effect kind 14 — look-ahead brick-wall limiter with a loudness meter) is doing right "
+ + "now: the character, the ceiling (dBTP when TruePeakMode), Delta (playing what it removes), the gain reduction now, its "
+ + "mean (while there is signal) and deepest over the last 4 s and since the peak reset, the input / output peaks now and "
+ + "held since the reset, the output true-peak hold, the share of the last 4 s the input was over the ceiling (0..1), the "
+ + "release in use and its range, transients that reached the clip stage, LUFS momentary / short-term / integrated, the "
+ + "target and the distance to it (LU, + = louder), loudness range (LRA, LU), PLR (true-peak hold − integrated), seconds "
+ + "measured, latency; plus the level window (the last 4 s in 16 steps: input, output, reduction, clipped) and the loudness "
+ + "window (the last 60 s in 20 steps). Levels are dBFS / LUFS, −120 = silence or not measured yet. The meters move only "
+ + "while audio runs through the track. Use device_action 0 to reset the peaks, 1 the loudness; get_device_text id 2 for "
+ + "what each parameter value means.")]
+ public Task<CeilingReading> ReadCeiling(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int tele = 40, lvl = 64, loud = 120, lvlAt = tele, loudAt = tele + 7 * lvl;
+ var sc = new float[loudAt + 3 * loud];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float Db(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ string[] chars = { "Clean", "Punch", "Glue" };
+ float Pm(int p) => E.DeviceGetParam(trackId, deviceIndex, p);
+ var cells = new List<CeilingCell>();
+ var louds = new List<CeilingLoudness>();
+ if (n >= sc.Length)
+ {
+ for (int k = 0; k < 16; k++)
+ {
+ double pin = -120, pout = -120, gr = 0; bool clip = false;
+ for (int i = k * lvl / 16; i < (k + 1) * lvl / 16; i++)
+ {
+ pin = Math.Max(pin, sc[lvlAt + i]); pout = Math.Max(pout, sc[lvlAt + lvl + i]);
+ gr = Math.Max(gr, sc[lvlAt + 2 * lvl + i]); clip |= sc[lvlAt + 3 * lvl + i] > 0.5f;
+ }
+ cells.Add(new CeilingCell(Math.Round(-4.0 + (k + 1) * 0.25, 2), R1(pin), R1(pout), R1(gr), clip));
+ }
+ for (int k = 0; k < 20; k++)
+ {
+ int i = (k + 1) * loud / 20 - 1;
+ louds.Add(new CeilingLoudness(-60 + (k + 1) * 3, R1(sc[loudAt + i]), R1(sc[loudAt + loud + i]), R1(sc[loudAt + 2 * loud + i])));
+ }
+ }
+ double target = Pm(10), lufsI = Db(5);
+ return new CeilingReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ chars[Math.Clamp((int)Math.Round(Pm(4)), 0, 2)], R1(Pm(0)), Pm(7) >= 0.5f, Pm(8) >= 0.5f,
+ R1(V(2)), R1(V(14)), R1(V(15)), R1(V(9)), R1(Db(0)), R1(Db(1)), R1(Db(7)), R1(Db(8)), R1(Db(10)), Math.Round(V(13), 3),
+ Math.Round(V(16)), Math.Round(V(17)), Math.Round(V(18)), (int)V(19), R1(Db(3)), R1(Db(4)), R1(lufsI), R1(target),
+ lufsI > -119 ? R1(lufsI - target) : 0, R1(V(11)), R1(V(12)), R1(V(30)), (int)V(22), V(20), cells.ToArray(), louds.ToArray());
+ });
+
public sealed record AnalyzerBand(double Hz, double Db);
public sealed record AnalyzerPeak(double Hz, double Db, string Note);
public sealed record AnalyzerReading(string Summary, string Scope, string Cursors, AnalyzerBand[] Bands, AnalyzerPeak[] Peaks);
diff --git a/src/native/nota.engine/src/Ceiling.h b/src/native/nota.engine/src/Ceiling.h
index ed748a1e..5df3165a 100644
--- a/src/native/nota.engine/src/Ceiling.h
+++ b/src/native/nota.engine/src/Ceiling.h
@@ -1,39 +1,105 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Nota Ceiling (mockup 3o) — a look-ahead brick-wall limiter (device kind 14).
-// Input gain drives the signal into a hard ceiling; a look-ahead delay lets the
-// gain duck *before* each peak reaches the output, a smoothed release (with an
-// optional program-dependent auto stage) governs recovery, and a final safety
-// clip guarantees the sample peak never passes the ceiling. Three voicing
-// "characters" (Clean / Punch / Glue) reshape attack/release, and a stereo-link
-// blend trades a glued centre for independent channels. A filtered side-chain
-// detector is supported like the Compressor. On top of limiting it runs a full
-// BS.1770 loudness meter — momentary/short-term/integrated LUFS plus a 4× true
-// peak — so the card can answer "is this deliverable" without a second plug-in.
-// A core Device (JUCE-free); params are atomic / lock-free, appended by index.
+// Nota Ceiling — a look-ahead brick-wall limiter (device kind 14).
+// Input gain drives the signal into a hard ceiling; a look-ahead delay lets the gain duck
+// *before* each peak reaches the output, a smoothed release (with an optional program-
+// dependent auto stage that slows as the reduction deepens) governs recovery, and a final
+// safety clip guarantees the sample peak never passes the ceiling. Three voicing characters
+// (Clean / Punch / Glue) reshape attack / release, and a stereo-link blend trades a glued
+// centre for independent channels.
+//
+// in ─▶ gain ─▶ look-ahead delay ────────────────▶ × gain ─▶ [Glue soft clip] ─▶ clip ─▶ out
+// │ ▲ │
+// (key) ─▶ SC HP ─▶ peak / 4× true peak ─▶ envelope ─┘ Delta: in − out ◀──┘
+//
+// True Peak makes the detector read the 4× interpolated peak, so the inter-sample overs a
+// DAC or a codec would make are held under the ceiling too. SC HP takes the lows out of the
+// detector (the bass stops pumping the mix). Delta plays what the limiter takes away. A
+// filtered side-chain from another track is supported like the Compressor. On top of the
+// limiting it runs a full BS.1770 / EBU R128 loudness meter — momentary / short-term /
+// integrated LUFS, loudness range (LRA), a 4× true peak and PLR — against a Target, so the
+// card can answer "is this deliverable" without a second plug-in.
+//
+// Params are the device's raw units (not 0..1) and APPEND ONLY: 0..6 are the original
+// layout, 7.. are appended and default to the old sound, so older projects open unchanged.
+// Telemetry (scopeRead): kTele live values, then the 4-second level window (kLvl cells ×
+// 7 series: input peak, output peak, max GR, clipped, over-the-ceiling share, release, mean
+// GR) and the 60-second loudness window (kLoud cells × M / S / I), oldest → newest.
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = reset peaks (holds, max GR, clip count, the level window), 1 = reset the
+// loudness (integrated, LRA, the loudness window) and the peaks.
+// A core Device (JUCE-free); params are atomic / lock-free; allocation-free after setSampleRate.
#pragma once
#include "Device.h"
#include <algorithm>
+#include <array>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
#include <vector>
namespace nota {
class Ceiling : public Device {
public:
- enum { Ceil = 0, Gain, Release, AutoRelease, Character, Lookahead, StereoLink, kNumParams };
- // Packed scope telemetry (scopeRead): instantaneous per-block meters. The UI
- // builds the scrolling 4-second history and the peak-holds from these.
- enum { S_InPeak = 0, S_OutPeak, S_Gr, S_LufsM, S_LufsS, S_LufsI, S_TruePeak, kScope };
+ enum { Ceil = 0, Gain, Release, AutoRelease, Character, Lookahead, StereoLink,
+ TruePeak, Delta, ScHp, Target, kNumParams };
+
+ // Telemetry slots (scopeRead). 0..6 keep the original layout.
+ enum {
+ S_InPeak = 0, // input peak after Gain, this block, dBFS
+ S_OutPeak, // output peak, this block, dBFS
+ S_Gr, // gain reduction, this block, dB (>= 0)
+ S_LufsM, // momentary loudness (400 ms), LUFS
+ S_LufsS, // short-term loudness (3 s), LUFS
+ S_LufsI, // integrated (gated) loudness since the loudness reset, LUFS
+ S_TruePeak, // output true peak (4×), this block, dBTP
+ S_PeakInHold, // highest input peak since the peak reset, dBFS
+ S_PeakOutHold, // highest output peak since the peak reset
+ S_MaxGrHold, // deepest reduction since the peak reset, dB
+ S_TpHold, // highest output true peak since the peak reset, dBTP
+ S_Lra, // loudness range, LU (0 until there is enough)
+ S_Plr, // peak-to-loudness ratio: true-peak hold − integrated, dB
+ S_OverPct, // share of the level window the input was over the ceiling, 0..1
+ S_AvgGr, // mean reduction over the level window (while there is signal), dB
+ S_WinMaxGr, // deepest reduction in the level window, dB
+ S_RelNow, // the release in use now, ms (character and auto stage included)
+ S_RelMin, // shortest release used in the window, ms
+ S_RelMax, // longest release used in the window, ms
+ S_Clips, // transients that reached the clip stage since the peak reset
+ S_SampleRate,
+ S_Cpu, // share of real time spent in process()
+ S_Latency, // samples
+ S_WinInPeak, // highest input peak in the level window, dBFS
+ S_WinOutPeak, // highest output peak in the level window, dBFS
+ S_LvlCells, // kLvl
+ S_LoudCells, // kLoud
+ S_LvlSeconds, // the level window's length, s
+ S_LoudSeconds, // the loudness window's length, s
+ S_Delta, // 1 while Delta plays the difference
+ S_Measured, // seconds of audio in the integrated reading
+ S_MaxM, // highest momentary loudness since the loudness reset
+ S_MaxS, // highest short-term loudness since the loudness reset
+ kTele = 40
+ };
+ static constexpr int kLvl = 64, kLvlSeries = 7, kLoud = 120, kLoudSeries = 3;
+ static constexpr double kLvlSeconds = 4.0, kLoudSeconds = 60.0;
+ // Level window series (each kLvl long, after kTele).
+ enum { L_In = 0, L_Out, L_GrMax, L_Clip, L_Over, L_Rel, L_GrAvg };
+ static constexpr int kLvlAt = kTele;
+ static constexpr int kLoudAt = kTele + kLvlSeries * kLvl;
+ static constexpr int kScope = kLoudAt + kLoudSeries * kLoud;
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
sr_ = sr > 0 ? sr : 44100.0;
+ srA_.store((float)sr_, std::memory_order_relaxed);
laMax_ = static_cast<int>(sr_ * 0.010) + 2; // 10 ms max look-ahead
laBuf_.assign(static_cast<size_t>(laMax_) * 2, 0.0f); laW_ = 0;
@@ -45,35 +111,51 @@ public:
shortN_ = std::max(1, (int)std::lround(sr_ * 3.000)); // short-term 3 s
msRing_.assign(static_cast<size_t>(shortN_), 0.0f); msW_ = 0;
momSum_ = 0.0; shortSum_ = 0.0;
- hopN_ = std::max(1, (int)std::lround(sr_ * 0.100)); // integrate every 100 ms
+ hopN_ = std::max(1, (int)std::lround(sr_ * 0.100)); // gate / LRA every 100 ms
hop_ = 0;
histCount_.assign(kHistBins, 0.0);
histSum_.assign(kHistBins, 0.0);
- blockSum_ = 0.0; blockN_ = 0;
- for (int c = 0; c < 2; ++c) { tp0_[c] = tp1_[c] = tp2_[c] = 0.0f; }
+ lraHist_.assign(kHistBins, 0.0);
+ tpOut_ = {}; tpDet_ = {};
+ for (auto& s : hpZ_) s[0] = s[1] = 0.0f;
+ hpHz_ = -1.0f;
env_ = 1.0f; grPrev_ = 0.0f;
+ lvlCellN_ = std::max(1, (int)std::lround(sr_ * kLvlSeconds / kLvl));
+ clipHoldN_ = std::max(1, (int)std::lround(sr_ * 0.020));
+ clearLevel(); clearLoudness();
}
void process(float* buf, int32_t frames) override {
+ const auto t0 = std::chrono::steady_clock::now();
+ if (resetPeaksReq_.exchange(false, std::memory_order_acq_rel)) clearLevel();
+ if (resetLoudReq_.exchange(false, std::memory_order_acq_rel)) { clearLoudness(); clearLevel(); }
+
const double sr = sr_;
- const int ch = std::clamp((int)std::lround(p_[Character].load(std::memory_order_relaxed)), 0, 2);
+ const int ch = std::clamp((int)std::lround(get(Character)), 0, 2);
// Clean / Punch / Glue — attack ms, release multiplier, soft-clip amount.
static const float chAtk[3] = { 0.20f, 2.0f, 0.6f };
static const float chRel[3] = { 1.0f, 0.65f, 2.6f };
static const float chSoft[3] = { 0.0f, 0.0f, 0.6f };
- const float ceilDb = p_[Ceil].load(std::memory_order_relaxed);
+ const float ceilDb = get(Ceil);
const float ceilLin = std::pow(10.0f, ceilDb / 20.0f);
- const float inGain = std::pow(10.0f, p_[Gain].load(std::memory_order_relaxed) / 20.0f);
- const float relMs = std::max(1.0f, p_[Release].load(std::memory_order_relaxed)) * chRel[ch];
- const bool autoRel = p_[AutoRelease].load(std::memory_order_relaxed) > 0.5f;
- const float link = std::clamp(p_[StereoLink].load(std::memory_order_relaxed) * 0.01f, 0.0f, 1.0f);
+ const float inGain = std::pow(10.0f, get(Gain) / 20.0f);
+ const float relMs = std::max(1.0f, get(Release)) * chRel[ch];
+ const bool autoRel = get(AutoRelease) > 0.5f;
+ const float link = std::clamp(get(StereoLink) * 0.01f, 0.0f, 1.0f);
const float soft = chSoft[ch];
- int la = std::clamp((int)std::lround(p_[Lookahead].load(std::memory_order_relaxed) * 0.001 * sr), 0, laMax_ - 1);
+ const bool tpMode = get(TruePeak) > 0.5f;
+ const bool delta = get(Delta) > 0.5f;
+ const int la = lookaheadSamples();
+
+ // Side-chain high-pass on the detector (RBJ, Q 0.707); off at its bottom (20 Hz).
+ const float hpHz = std::clamp(get(ScHp), 20.0f, 500.0f);
+ const bool hpOn = hpHz > 20.5f;
+ if (hpOn && std::fabs(hpHz - hpHz_) > 1e-3f) computeHp(hpHz);
const double atkC = std::exp(-1.0 / (std::max(0.05f, chAtk[ch]) * 0.001 * sr));
- const double relC = std::exp(-1.0 / (relMs * 0.001 * sr));
- const double relCs = std::exp(-1.0 / (relMs * 5.0 * 0.001 * sr)); // slow auto stage
+ double relC = std::exp(-1.0 / (relMs * 0.001 * sr));
+ float relEff = relMs;
const float* sc = (scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;
const float scGain = std::pow(10.0f, sidechainGainDb() / 20.0f);
@@ -81,16 +163,35 @@ public:
float inPk = 0.0f, outPk = 0.0f, tpPk = 0.0f, maxGr = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
+ // Control rate: the auto stage slows the release as the reduction deepens
+ // (×1 at 1 dB … ×5 at 7 dB and deeper), so dense passages don't pump.
+ if ((i & 15) == 0) {
+ const float t = autoRel ? std::clamp((grPrev_ - 1.0f) / 6.0f, 0.0f, 1.0f) : 0.0f;
+ const float r = relMs * (1.0f + 4.0f * t);
+ if (std::fabs(r - relEff) > 0.01f || i == 0) { relEff = r; relC = std::exp(-1.0 / (relEff * 0.001 * sr)); }
+ }
+
float l = buf[i * 2] * inGain, r = buf[i * 2 + 1] * inGain;
const float aL = std::fabs(l), aR = std::fabs(r);
- float det = std::max(aL, aR);
- if (sc) det = std::max(det, std::max(std::fabs(sc[i * 2]), std::fabs(sc[i * 2 + 1])) * scGain);
- if (det > inPk) inPk = det;
+
+ // Detector: optionally high-passed, sample or 4× true peak, plus the key.
+ float xl = l, xr = r;
+ if (hpOn) { xl = hp(0, xl); xr = hp(1, xr); }
+ float dL = tpMode ? tpDetect(0, xl) : std::fabs(xl);
+ float dR = tpMode ? tpDetect(1, xr) : std::fabs(xr);
+ float det = std::max(dL, dR);
+ if (sc) {
+ float kl = sc[i * 2] * scGain, kr = sc[i * 2 + 1] * scGain;
+ if (hpOn) { kl = hp(2, kl); kr = hp(3, kr); }
+ det = std::max(det, std::max(std::fabs(kl), std::fabs(kr)));
+ }
+ const float aIn = std::max(aL, aR);
+ if (aIn > inPk) inPk = aIn;
// Peak follower with fast attack; look-ahead delay is what makes it duck
- // before the transient. Auto-release adds a slow stage on deep reduction.
+ // before the transient.
if (det > env_) env_ = (float)(atkC * env_ + (1.0 - atkC) * det);
- else { double rc = (autoRel && grPrev_ > 2.0f) ? relCs : relC; env_ = (float)(rc * env_ + (1.0 - rc) * det); }
+ else env_ = (float)(relC * env_ + (1.0 - relC) * det);
float gain = env_ > ceilLin ? ceilLin / env_ : 1.0f; // linked target gain
grPrev_ = gain < 1.0f ? -20.0f * std::log10(std::max(1e-6f, gain)) : 0.0f;
@@ -100,8 +201,8 @@ public:
// its own headroom so a hard pan doesn't pull the other side down.
float gL = gain, gR = gain;
if (link < 0.999f) {
- float tL = aL > ceilLin ? ceilLin / aL : 1.0f;
- float tR = aR > ceilLin ? ceilLin / aR : 1.0f;
+ float tL = dL > ceilLin ? ceilLin / dL : 1.0f;
+ float tR = dR > ceilLin ? ceilLin / dR : 1.0f;
gL = link * gain + (1.0f - link) * std::min(gain < 1.0f ? gain : 1.0f, tL);
gR = link * gain + (1.0f - link) * std::min(gain < 1.0f ? gain : 1.0f, tR);
}
@@ -109,19 +210,37 @@ public:
// Look-ahead: apply the gain (already ducked) to the delayed sample.
laBuf_[laW_ * 2] = l; laBuf_[laW_ * 2 + 1] = r;
int rp = laW_ - la; if (rp < 0) rp += laMax_;
- float ol = laBuf_[rp * 2] * gL, or_ = laBuf_[rp * 2 + 1] * gR;
+ const float dryL = laBuf_[rp * 2], dryR = laBuf_[rp * 2 + 1];
+ float ol = dryL * gL, or_ = dryR * gR;
if (++laW_ >= laMax_) laW_ = 0;
- // Character soft-clip (Glue) then the hard safety ceiling — brick wall.
+ // Character soft-clip (Glue) then the hard safety ceiling — brick wall. A
+ // transient that reaches the clip (Punch lets the attack through) is counted.
if (soft > 0.0f) { ol = softClip(ol, ceilLin, soft); or_ = softClip(or_, ceilLin, soft); }
+ const bool clipping = std::max(std::fabs(ol), std::fabs(or_)) > ceilLin * 1.0001f;
ol = std::clamp(ol, -ceilLin, ceilLin);
or_ = std::clamp(or_, -ceilLin, ceilLin);
- buf[i * 2] = ol; buf[i * 2 + 1] = or_;
+ if (clipping) {
+ if (clipHold_ <= 0) ++clips_;
+ clipHold_ = clipHoldN_;
+ cClip_ = 1.0f;
+ } else if (clipHold_ > 0) --clipHold_;
- outPk = std::max(outPk, std::max(std::fabs(ol), std::fabs(or_)));
+ buf[i * 2] = delta ? dryL - ol : ol;
+ buf[i * 2 + 1] = delta ? dryR - or_ : or_;
+
+ const float aOut = std::max(std::fabs(ol), std::fabs(or_));
+ outPk = std::max(outPk, aOut);
tpPk = std::max(tpPk, std::max(truePeak(0, ol), truePeak(1, or_)));
- // K-weighted loudness on the output (what actually ships).
+ // Level window cell.
+ cIn_ = std::max(cIn_, aIn); cOut_ = std::max(cOut_, aOut);
+ cGrMax_ = std::max(cGrMax_, grPrev_); cGrSum_ += grPrev_;
+ if (aIn > ceilLin) ++cOver_;
+ cRelSum_ += relEff;
+ if (++cN_ >= lvlCellN_) pushLevelCell();
+
+ // K-weighted loudness on the limited output (what actually ships).
float kl = kWeight(0, ol), kr = kWeight(1, or_);
float ms = kl * kl + kr * kr;
shortSum_ += ms - msRing_[msW_];
@@ -129,39 +248,112 @@ public:
int momTail = msW_ - momN_; if (momTail < 0) momTail += shortN_;
momSum_ += ms - msRing_[momTail];
if (++msW_ >= shortN_) msW_ = 0;
- blockSum_ += ms; ++blockN_;
- if (++hop_ >= hopN_) { hop_ = 0; integrateBlock(); }
+ ++loudSamples_;
+ if (++hop_ >= hopN_) { hop_ = 0; onHop(); }
}
// Publish meters (dB; peaks in dBFS, GR positive-down).
- inPeak_.store(db(inPk), std::memory_order_relaxed);
- outPeak_.store(db(outPk), std::memory_order_relaxed);
- truePeak_.store(db(tpPk), std::memory_order_relaxed);
+ const float inDb = db(inPk), outDb = db(outPk), tpDb = db(tpPk);
+ inPeak_.store(inDb, std::memory_order_relaxed);
+ outPeak_.store(outDb, std::memory_order_relaxed);
+ truePeak_.store(tpDb, std::memory_order_relaxed);
gr_.store(maxGr, std::memory_order_relaxed);
- lufsM_.store(lufs(momSum_ / std::max(1, momN_)), std::memory_order_relaxed);
- lufsS_.store(lufs(shortSum_ / std::max(1, shortN_)), std::memory_order_relaxed);
+ if (frames > 0) {
+ pkInHold_ = std::max(pkInHold_, inDb); pkOutHold_ = std::max(pkOutHold_, outDb);
+ maxGrHold_ = std::max(maxGrHold_, maxGr); tpHold_ = std::max(tpHold_, tpDb);
+ }
+ pkInHoldA_.store(pkInHold_, std::memory_order_relaxed);
+ pkOutHoldA_.store(pkOutHold_, std::memory_order_relaxed);
+ maxGrHoldA_.store(maxGrHold_, std::memory_order_relaxed);
+ tpHoldA_.store(tpHold_, std::memory_order_relaxed);
+ clipsA_.store((float)clips_, std::memory_order_relaxed);
+ relNowA_.store(relEff, std::memory_order_relaxed);
+ deltaA_.store(delta ? 1.0f : 0.0f, std::memory_order_relaxed);
scBuf_ = nullptr;
+ if (frames > 0) {
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store((float)cpuS_, std::memory_order_relaxed);
+ }
}
// GR (dB, >=0) for the shell titlebar meter, like the Compressor.
float gainReductionDb() const override { return gr_.load(std::memory_order_relaxed); }
- int32_t scopeRead(float* out, int32_t maxSamples) const override {
- if (!out || maxSamples < kScope) return 0;
- out[S_InPeak] = inPeak_.load(std::memory_order_relaxed);
- out[S_OutPeak] = outPeak_.load(std::memory_order_relaxed);
- out[S_Gr] = gr_.load(std::memory_order_relaxed);
- out[S_LufsM] = lufsM_.load(std::memory_order_relaxed);
- out[S_LufsS] = lufsS_.load(std::memory_order_relaxed);
- out[S_LufsI] = lufsI_.load(std::memory_order_relaxed);
- out[S_TruePeak] = truePeak_.load(std::memory_order_relaxed);
- return kScope;
+ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {
+ if (id == 0) resetPeaksReq_.store(true, std::memory_order_release);
+ else if (id == 1) resetLoudReq_.store(true, std::memory_order_release);
}
- int32_t latencySamples() const override {
- return std::clamp((int)std::lround(p_[Lookahead].load(std::memory_order_relaxed) * 0.001 * sr_), 0, laMax_ - 1);
+ // Telemetry block, then the level window and the loudness window, oldest → newest.
+ // Writes as much of that layout as fits in maxSamples. Lock-free; torn reads are fine.
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ float t[kTele] = {};
+ t[S_InPeak] = inPeak_.load(std::memory_order_relaxed);
+ t[S_OutPeak] = outPeak_.load(std::memory_order_relaxed);
+ t[S_Gr] = gr_.load(std::memory_order_relaxed);
+ t[S_LufsM] = lufsM_.load(std::memory_order_relaxed);
+ t[S_LufsS] = lufsS_.load(std::memory_order_relaxed);
+ t[S_LufsI] = lufsI_.load(std::memory_order_relaxed);
+ t[S_TruePeak] = truePeak_.load(std::memory_order_relaxed);
+ t[S_PeakInHold] = pkInHoldA_.load(std::memory_order_relaxed);
+ t[S_PeakOutHold] = pkOutHoldA_.load(std::memory_order_relaxed);
+ t[S_MaxGrHold] = maxGrHoldA_.load(std::memory_order_relaxed);
+ t[S_TpHold] = tpHoldA_.load(std::memory_order_relaxed);
+ t[S_Lra] = lraA_.load(std::memory_order_relaxed);
+ t[S_Plr] = t[S_LufsI] > -119.0f && t[S_TpHold] > -119.0f ? t[S_TpHold] - t[S_LufsI] : 0.0f;
+ t[S_RelNow] = relNowA_.load(std::memory_order_relaxed);
+ t[S_Clips] = clipsA_.load(std::memory_order_relaxed);
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_Latency] = (float)latencySamples();
+ t[S_LvlCells] = (float)kLvl;
+ t[S_LoudCells] = (float)kLoud;
+ t[S_LvlSeconds] = (float)kLvlSeconds;
+ t[S_LoudSeconds] = (float)kLoudSeconds;
+ t[S_Delta] = deltaA_.load(std::memory_order_relaxed);
+ t[S_Measured] = measuredA_.load(std::memory_order_relaxed);
+ t[S_MaxM] = maxMA_.load(std::memory_order_relaxed);
+ t[S_MaxS] = maxSA_.load(std::memory_order_relaxed);
+
+ // Window statistics from the level cells.
+ const int lh = lvlHead_.load(std::memory_order_relaxed);
+ double overSum = 0.0, grSum = 0.0; int grN = 0, cells = 0;
+ float winGr = 0.0f, winIn = -120.0f, winOut = -120.0f, relMin = 1e9f, relMax = 0.0f;
+ for (int k = 0; k < kLvl; ++k) {
+ const int c = (lh + k) % kLvl;
+ if (lvl_[L_In][c] <= -119.0f && lvl_[L_Rel][c] <= 0.0f) continue; // empty cell
+ ++cells;
+ overSum += lvl_[L_Over][c];
+ winGr = std::max(winGr, lvl_[L_GrMax][c]);
+ winIn = std::max(winIn, lvl_[L_In][c]);
+ winOut = std::max(winOut, lvl_[L_Out][c]);
+ if (lvl_[L_In][c] > -70.0f) { grSum += lvl_[L_GrAvg][c]; ++grN; }
+ if (lvl_[L_GrMax][c] > 0.1f && lvl_[L_Rel][c] > 0.0f) {
+ relMin = std::min(relMin, lvl_[L_Rel][c]); relMax = std::max(relMax, lvl_[L_Rel][c]);
+ }
+ }
+ t[S_OverPct] = cells > 0 ? (float)(overSum / cells) : 0.0f;
+ t[S_AvgGr] = grN > 0 ? (float)(grSum / grN) : 0.0f;
+ t[S_WinMaxGr] = winGr;
+ t[S_WinInPeak] = winIn;
+ t[S_WinOutPeak] = winOut;
+ if (relMax <= 0.0f) relMin = relMax = t[S_RelNow];
+ t[S_RelMin] = relMin; t[S_RelMax] = relMax;
+
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ for (int s = 0; s < kLvlSeries; ++s)
+ for (int k = 0; k < kLvl && n < maxSamples; ++k) out[n++] = lvl_[s][(lh + k) % kLvl];
+ const int dh = loudHead_.load(std::memory_order_relaxed);
+ for (int s = 0; s < kLoudSeries; ++s)
+ for (int k = 0; k < kLoud && n < maxSamples; ++k) out[n++] = loud_[s][(dh + k) % kLoud];
+ return n;
}
+ int32_t latencySamples() const override { return lookaheadSamples(); }
+
// Side-chain: the detector may also key off another track (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); }
@@ -172,22 +364,80 @@ public:
int32_t builtinKind() const override { return 14; }
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
- static const char* nm[] = { "Ceiling", "Gain", "Release", "AutoRelease", "Character", "Lookahead", "StereoLink" };
+ static const char* nm[kNumParams] = { "Ceiling", "Gain", "Release", "AutoRelease", "Character", "Lookahead", "StereoLink",
+ "True Peak", "Delta", "SC HP", "Target" };
return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
float paramMin(int32_t i) const override {
- switch (i) { case Ceil: return -12.0f; case Gain: return -12.0f; case Release: return 1.0f; default: return 0.0f; }
+ switch (i) { case Ceil: return -12.0f; case Gain: return -12.0f; case Release: return 1.0f; case ScHp: return 20.0f;
+ case Target: return -30.0f; default: return 0.0f; }
}
float paramMax(int32_t i) const override {
switch (i) { case Ceil: return 0.0f; case Gain: return 24.0f; case Release: return 1000.0f; case Character: return 2.0f;
- case Lookahead: return 10.0f; case StereoLink: return 100.0f; default: return 1.0f; }
+ case Lookahead: return 10.0f; case StereoLink: return 100.0f; case ScHp: return 500.0f; case Target: return -5.0f;
+ default: return 1.0f; }
}
float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
- void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(v, std::memory_order_relaxed); }
+ void setParam(int32_t i, float v) override {
+ if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, paramMin(i), paramMax(i)), std::memory_order_relaxed);
+ }
+
+ // 0 — a one-line status; 1 — the live reading; 2 — a guide to the parameter values.
+ std::string deviceText(int32_t id) const override {
+ char b[1000];
+ static const char* chars[3] = { "Clean", "Punch", "Glue" };
+ if (id == 0) {
+ std::string s = chars[std::clamp((int)std::lround(get(Character)), 0, 2)];
+ std::snprintf(b, sizeof b, " - gain %+.1f dB - ceiling %.1f dB%s", get(Gain), get(Ceil), get(TruePeak) > 0.5f ? " TP" : "");
+ s += b;
+ if (get(AutoRelease) > 0.5f) std::snprintf(b, sizeof b, " - release auto (from %.0f ms)", get(Release));
+ else std::snprintf(b, sizeof b, " - release %.0f ms", get(Release));
+ s += b;
+ std::snprintf(b, sizeof b, " - look-ahead %.1f ms - link %.0f %%", get(Lookahead), get(StereoLink)); s += b;
+ if (get(ScHp) > 20.5f) { std::snprintf(b, sizeof b, " - SC HP %.0f Hz", get(ScHp)); s += b; }
+ if (scTrackId_.load(std::memory_order_relaxed) >= 0) {
+ std::snprintf(b, sizeof b, " - key from track %d", scTrackId_.load(std::memory_order_relaxed)); s += b;
+ }
+ std::snprintf(b, sizeof b, " - target %.0f LUFS", get(Target)); s += b;
+ if (get(Delta) > 0.5f) s += " - DELTA (playing what it removes)";
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ auto lv = [](float v) { char t[24]; if (v <= -119.0f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", v); return std::string(t); };
+ const float fromTarget = sc[S_LufsI] > -119.0f ? sc[S_LufsI] - get(Target) : 0.0f;
+ std::snprintf(b, sizeof b,
+ "GR %.1f dB (window avg %.1f, max %.1f; max since reset %.1f) - in %s dBFS, out %s dBFS - peaks since reset "
+ "in %s, out %s, true peak %s dBTP - over the ceiling %.0f %% of the last 4 s - release now %.0f ms (%.0f..%.0f) - "
+ "%.0f transients reached the clip - LUFS M %s, S %s, I %s (%.0f s measured, %s LU from target %.0f) - "
+ "LRA %.1f LU - PLR %.1f dB - latency %.0f samples",
+ sc[S_Gr], sc[S_AvgGr], sc[S_WinMaxGr], sc[S_MaxGrHold], lv(sc[S_InPeak]).c_str(), lv(sc[S_OutPeak]).c_str(),
+ lv(sc[S_PeakInHold]).c_str(), lv(sc[S_PeakOutHold]).c_str(), lv(sc[S_TpHold]).c_str(), sc[S_OverPct] * 100.0f,
+ sc[S_RelNow], sc[S_RelMin], sc[S_RelMax], sc[S_Clips], lv(sc[S_LufsM]).c_str(), lv(sc[S_LufsS]).c_str(),
+ lv(sc[S_LufsI]).c_str(), sc[S_Measured], sc[S_LufsI] > -119.0f ? lv(fromTarget).c_str() : "n/a",
+ get(Target), sc[S_Lra], sc[S_Plr], sc[S_Latency]);
+ std::string s = b;
+ if (sc[S_Delta] > 0.5f) s += " - DELTA on";
+ return s;
+ }
+ if (id == 2) {
+ return "Params are in their own units (not 0..1). Ceiling: -12..0 dB, the output never passes it (dBTP with True Peak). "
+ "Gain: -12..+24 dB into the limiter. Release: 1..1000 ms (times the character: Clean x1, Punch x0.65, Glue x2.6). "
+ "AutoRelease: >= 0.5 slows the release as the reduction deepens (x1 at 1 dB .. x5 at 7 dB). Character: 0 Clean "
+ "(transparent, 0.2 ms attack), 1 Punch (2 ms attack - lets the attack through to the clip), 2 Glue (slow, with a "
+ "soft knee under the ceiling). Lookahead: 0..10 ms (the latency). StereoLink: 0..100 % (100 = one gain for both "
+ "channels). True Peak: >= 0.5 detects the 4x inter-sample peak. Delta: >= 0.5 plays what the limiter removes "
+ "(in - out). SC HP: 20..500 Hz high-pass on the detector (20 = off). Target: -30..-5 LUFS, the loudness the "
+ "meters compare against (-14 streaming, -16 podcast, -23 broadcast); it does not change the sound.";
+ }
+ return {};
+ }
Ceiling() {
p_[Ceil].store(-1.0f); p_[Gain].store(0.0f); p_[Release].store(120.0f); p_[AutoRelease].store(0.0f);
p_[Character].store(0.0f); p_[Lookahead].store(3.0f); p_[StereoLink].store(100.0f);
+ p_[TruePeak].store(0.0f); p_[Delta].store(0.0f); p_[ScHp].store(20.0f); p_[Target].store(-14.0f);
setSampleRate(44100.0, 0);
}
@@ -196,28 +446,78 @@ private:
static constexpr int kHistBins = 800; // −70.0 … +10.0 LUFS at 0.1 LU
static constexpr double kHistLo = -70.0;
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ // The look-ahead in samples; True Peak needs at least the interpolator's delay so the
+ // inter-sample reading still lands before its sample does.
+ int lookaheadSamples() const {
+ int la = (int)std::lround(get(Lookahead) * 0.001 * sr_);
+ if (get(TruePeak) > 0.5f) la = std::max(la, kTpDelay);
+ return std::clamp(la, 0, laMax_ - 1);
+ }
+
static float softClip(float x, float ceil, float amt) {
// Gentle tanh knee that engages near the ceiling; blended by amount.
float s = ceil * std::tanh(x / std::max(1e-6f, ceil));
return x + amt * (s - x);
}
- static float db(float lin) { return 20.0f * std::log10(std::max(1e-6f, lin)); }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
static float lufs(double ms) { return ms > 1e-10 ? (float)(-0.691 + 10.0 * std::log10(ms)) : -120.0f; }
- // 4× oversampled true-peak estimate via Catmull-Rom between output samples.
- float truePeak(int c, float x) {
- float y0 = tp0_[c], y1 = tp1_[c], y2 = tp2_[c], y3 = x; // x_{-2..+1}
- 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);
- float 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));
+ // 4× true peak (BS.1770-4 Annex 2 style): a 16-tap windowed-sinc interpolator per phase over
+ // a short history; the peak is the highest of the sample and the three points after it. The
+ // reading is kTpDelay samples behind its input (the filter's centre).
+ static constexpr int kTpTaps = 16, kTpDelay = 8;
+ struct TpState { std::array<float, kTpTaps> h {}; int w = 0; };
+ static const std::array<std::array<float, kTpTaps>, 3>& tpCoefs() {
+ static const auto c = [] {
+ std::array<std::array<float, kTpTaps>, 3> k {};
+ for (int p = 0; p < 3; ++p) {
+ const double t = (p + 1) * 0.25;
+ double sum = 0.0;
+ for (int i = 0; i < kTpTaps; ++i) {
+ const double u = i - (kTpDelay - 1) - t;
+ const double sinc = std::fabs(u) < 1e-9 ? 1.0 : std::sin(kPi * u) / (kPi * u);
+ const double win = std::fabs(u) < 8.5 ? 0.5 * (1.0 + std::cos(kPi * u / 8.5)) : 0.0;
+ k[(size_t)p][(size_t)i] = (float)(sinc * win); sum += sinc * win;
+ }
+ for (auto& v : k[(size_t)p]) v = (float)(v / sum);
+ }
+ return k;
+ }();
+ return c;
+ }
+ static float tpPush(TpState& s, float x) {
+ s.h[(size_t)s.w] = x;
+ s.w = (s.w + 1) % kTpTaps; // s.w is now the oldest sample
+ const auto& c = tpCoefs();
+ float pk = std::fabs(s.h[(size_t)((s.w + kTpDelay - 1) % kTpTaps)]);
+ for (int p = 0; p < 3; ++p) {
+ float acc = 0.0f;
+ for (int i = 0; i < kTpTaps; ++i) acc += c[(size_t)p][(size_t)i] * s.h[(size_t)((s.w + i) % kTpTaps)];
+ pk = std::max(pk, std::fabs(acc));
}
- tp0_[c] = y1; tp1_[c] = y2; tp2_[c] = y3;
return pk;
}
+ // Output true-peak meter.
+ float truePeak(int c, float x) { return tpPush(tpOut_[(size_t)c], x); }
+ // Detector true peak (before the look-ahead, so the gain is down before the over arrives);
+ // the plain sample peak is taken now, the inter-sample one kTpDelay samples later.
+ float tpDetect(int c, float x) { return std::max(std::fabs(x), tpPush(tpDet_[(size_t)c], x)); }
+
+ void computeHp(float hz) {
+ hpHz_ = hz;
+ const double w = 2.0 * kPi * hz / sr_, cw = std::cos(w), al = std::sin(w) / (2.0 * 0.7071);
+ const double a0 = 1.0 + al;
+ hb0_ = (float)((1.0 + cw) / 2.0 / a0); hb1_ = (float)(-(1.0 + cw) / a0); hb2_ = hb0_;
+ ha1_ = (float)(-2.0 * cw / a0); ha2_ = (float)((1.0 - al) / a0);
+ }
+ float hp(int c, float x) {
+ auto& z = hpZ_[(size_t)c];
+ const float y = hb0_ * x + z[0];
+ z[0] = hb1_ * x - ha1_ * y + z[1];
+ z[1] = hb2_ * x - ha2_ * y;
+ return y;
+ }
// Cascaded K-weighting biquads (Transposed Direct Form II), per channel.
float kWeight(int c, float x) {
@@ -244,50 +544,134 @@ private:
{ double f0 = 38.13547087602444, Q = 0.5003270373238773;
double K = std::tan(kPi * f0 / sr_);
double a0 = 1.0 + K / Q + K * K;
- b0_[1] = 1.0f; b1_[1] = -2.0f; b2_[1] = 1.0f;
a1_[1] = (float)(2.0 * (K * K - 1.0) / a0);
a2_[1] = (float)((1.0 - K / Q + K * K) / a0);
- // fold a0 into b's
b0_[1] = (float)(1.0 / a0); b1_[1] = (float)(-2.0 / a0); b2_[1] = (float)(1.0 / a0); }
}
- // One 400 ms gating block -> histogram -> gated integrated loudness.
- void integrateBlock() {
- double blockMs = blockSum_ / std::max(1, blockN_);
- blockSum_ = 0.0; blockN_ = 0;
- double L = lufs(blockMs);
- if (L <= -70.0) return; // absolute gate
- int bin = std::clamp((int)((L - kHistLo) * 10.0), 0, kHistBins - 1);
- histCount_[bin] += 1.0; histSum_[bin] += blockMs;
-
- // Ungated mean over gated set, then a relative gate 10 LU below it.
- double sumMs = 0.0, n = 0.0;
- for (int b = 0; b < kHistBins; ++b) { sumMs += histSum_[b]; n += histCount_[b]; }
- if (n < 1.0) return;
- double relGate = lufs(sumMs / n) - 10.0;
- int gb = std::clamp((int)((relGate - kHistLo) * 10.0), 0, kHistBins - 1);
- double gSum = 0.0, gN = 0.0;
- for (int b = gb; b < kHistBins; ++b) { gSum += histSum_[b]; gN += histCount_[b]; }
- if (gN >= 1.0) lufsI_.store(lufs(gSum / gN), std::memory_order_relaxed);
+ // Every 100 ms: publish M / S, gate the 400 ms block (75 % overlap) into the integrated
+ // reading, feed the short-term value to the loudness range, and step the 60 s window.
+ void onHop() {
+ const float m = loudSamples_ >= momN_ ? lufs(momSum_ / momN_) : -120.0f;
+ const float s = loudSamples_ >= momN_ ? lufs(shortSum_ / std::max<int64_t>(1, std::min<int64_t>(loudSamples_, shortN_))) : -120.0f;
+ lufsM_.store(m, std::memory_order_relaxed);
+ lufsS_.store(s, std::memory_order_relaxed);
+ if (m > maxM_) { maxM_ = m; maxMA_.store(m, std::memory_order_relaxed); }
+ if (loudSamples_ >= shortN_ && s > maxS_) { maxS_ = s; maxSA_.store(s, std::memory_order_relaxed); }
+
+ if (loudSamples_ >= momN_ && m > -70.0f) { // absolute gate
+ const int bin = std::clamp((int)((m - kHistLo) * 10.0), 0, kHistBins - 1);
+ histCount_[bin] += 1.0; histSum_[bin] += momSum_ / momN_;
+ double sumMs = 0.0, n = 0.0;
+ for (int k = 0; k < kHistBins; ++k) { sumMs += histSum_[k]; n += histCount_[k]; }
+ if (n >= 1.0) {
+ const double relGate = lufs(sumMs / n) - 10.0; // relative gate
+ const int gb = std::clamp((int)std::ceil((relGate - kHistLo) * 10.0), 0, kHistBins - 1);
+ double gSum = 0.0, gN = 0.0;
+ for (int k = gb; k < kHistBins; ++k) { gSum += histSum_[k]; gN += histCount_[k]; }
+ if (gN >= 1.0) lufsI_.store(lufs(gSum / gN), std::memory_order_relaxed);
+ }
+ measuredA_.store((float)((double)loudSamples_ / sr_), std::memory_order_relaxed);
+ }
+ // Loudness range (EBU Tech 3342): short-term values, −70 absolute and −20 LU relative
+ // gates, the spread between the 10th and the 95th percentile.
+ if (loudSamples_ >= shortN_ && s > -70.0f) {
+ const int bin = std::clamp((int)((s - kHistLo) * 10.0), 0, kHistBins - 1);
+ lraHist_[bin] += 1.0;
+ double e = 0.0, n = 0.0;
+ for (int k = 0; k < kHistBins; ++k) if (lraHist_[k] > 0.0) {
+ e += lraHist_[k] * std::pow(10.0, (kHistLo + (k + 0.5) * 0.1) / 10.0); n += lraHist_[k];
+ }
+ if (n >= 2.0) {
+ const double gate = 10.0 * std::log10(e / n) - 20.0;
+ const int gb = std::clamp((int)std::ceil((gate - kHistLo) * 10.0), 0, kHistBins - 1);
+ double cnt = 0.0;
+ for (int k = gb; k < kHistBins; ++k) cnt += lraHist_[k];
+ if (cnt >= 2.0) {
+ double acc = 0.0; int lo = -1, hi = -1;
+ for (int k = gb; k < kHistBins; ++k) {
+ acc += lraHist_[k];
+ if (lo < 0 && acc >= 0.10 * cnt) lo = k;
+ if (hi < 0 && acc >= 0.95 * cnt) { hi = k; break; }
+ }
+ if (lo >= 0 && hi >= 0) lraA_.store((float)((hi - lo) * 0.1), std::memory_order_relaxed);
+ }
+ }
+ }
+ // 60 s window: one cell every 5 hops (0.5 s).
+ if (++hopInCell_ >= 5) {
+ hopInCell_ = 0;
+ const int h = loudHead_.load(std::memory_order_relaxed);
+ loud_[0][h] = m; loud_[1][h] = s; loud_[2][h] = lufsI_.load(std::memory_order_relaxed);
+ loudHead_.store((h + 1) % kLoud, std::memory_order_relaxed);
+ }
+ }
+
+ void pushLevelCell() {
+ const int h = lvlHead_.load(std::memory_order_relaxed);
+ lvl_[L_In][h] = db(cIn_); lvl_[L_Out][h] = db(cOut_);
+ lvl_[L_GrMax][h] = cGrMax_; lvl_[L_Clip][h] = cClip_;
+ lvl_[L_Over][h] = (float)cOver_ / (float)std::max(1, cN_);
+ lvl_[L_Rel][h] = (float)(cRelSum_ / std::max(1, cN_));
+ lvl_[L_GrAvg][h] = (float)(cGrSum_ / std::max(1, cN_));
+ lvlHead_.store((h + 1) % kLvl, std::memory_order_relaxed);
+ cIn_ = cOut_ = cGrMax_ = cClip_ = 0.0f; cGrSum_ = cRelSum_ = 0.0; cOver_ = 0; cN_ = 0;
+ }
+
+ void clearLevel() {
+ for (int s = 0; s < kLvlSeries; ++s) lvl_[s].fill(0.0f);
+ lvl_[L_In].fill(-120.0f); lvl_[L_Out].fill(-120.0f);
+ cIn_ = cOut_ = cGrMax_ = cClip_ = 0.0f; cGrSum_ = cRelSum_ = 0.0; cOver_ = 0; cN_ = 0;
+ pkInHold_ = pkOutHold_ = tpHold_ = -120.0f; maxGrHold_ = 0.0f; clips_ = 0; clipHold_ = 0;
+ pkInHoldA_.store(-120.0f); pkOutHoldA_.store(-120.0f); tpHoldA_.store(-120.0f); maxGrHoldA_.store(0.0f); clipsA_.store(0.0f);
+ }
+ void clearLoudness() {
+ std::fill(histCount_.begin(), histCount_.end(), 0.0);
+ std::fill(histSum_.begin(), histSum_.end(), 0.0);
+ std::fill(lraHist_.begin(), lraHist_.end(), 0.0);
+ for (auto& s : loud_) s.fill(-120.0f);
+ loudSamples_ = 0; hopInCell_ = 0; maxM_ = maxS_ = -120.0f;
+ std::fill(msRing_.begin(), msRing_.end(), 0.0f); momSum_ = shortSum_ = 0.0; msW_ = 0; hop_ = 0;
+ lufsI_.store(-120.0f); lufsM_.store(-120.0f); lufsS_.store(-120.0f); lraA_.store(0.0f);
+ measuredA_.store(0.0f); maxMA_.store(-120.0f); maxSA_.store(-120.0f);
}
double sr_ = 44100.0;
std::vector<float> laBuf_; int laMax_ = 0, laW_ = 0;
float env_ = 1.0f, grPrev_ = 0.0f;
- // K-weighting state (2 stages × 2 channels).
+ // K-weighting state (2 stages × 2 channels); true-peak interpolators; side-chain HP.
float b0_[2] = {}, b1_[2] = {}, b2_[2] = {}, a1_[2] = {}, a2_[2] = {};
float z1_[2][2] = {}, z2_[2][2] = {};
- float tp0_[2] = {}, tp1_[2] = {}, tp2_[2] = {};
+ std::array<TpState, 2> tpOut_ {}, tpDet_ {};
+ float hb0_ = 1.0f, hb1_ = 0.0f, hb2_ = 0.0f, ha1_ = 0.0f, ha2_ = 0.0f, hpHz_ = -1.0f;
+ std::array<std::array<float, 2>, 4> hpZ_ {};
+ // Loudness.
std::vector<float> msRing_; int msW_ = 0, momN_ = 0, shortN_ = 0;
double momSum_ = 0.0, shortSum_ = 0.0;
- int hopN_ = 0, hop_ = 0;
- std::vector<double> histCount_, histSum_;
- double blockSum_ = 0.0; int blockN_ = 0;
+ int hopN_ = 0, hop_ = 0, hopInCell_ = 0;
+ int64_t loudSamples_ = 0;
+ std::vector<double> histCount_, histSum_, lraHist_;
+ float maxM_ = -120.0f, maxS_ = -120.0f;
+
+ // Level window cell accumulators, holds, clip counting.
+ int lvlCellN_ = 1, cN_ = 0, cOver_ = 0, clipHoldN_ = 1, clipHold_ = 0;
+ float cIn_ = 0.0f, cOut_ = 0.0f, cGrMax_ = 0.0f, cClip_ = 0.0f;
+ double cGrSum_ = 0.0, cRelSum_ = 0.0;
+ float pkInHold_ = -120.0f, pkOutHold_ = -120.0f, maxGrHold_ = 0.0f, tpHold_ = -120.0f;
+ int64_t clips_ = 0;
+ double cpuS_ = 0.0;
+
+ std::array<std::array<float, kLvl>, kLvlSeries> lvl_ {};
+ std::array<std::array<float, kLoud>, kLoudSeries> loud_ {};
+ std::atomic<int> lvlHead_{0}, loudHead_{0};
std::atomic<float> inPeak_{-120.0f}, outPeak_{-120.0f}, truePeak_{-120.0f}, gr_{0.0f};
- std::atomic<float> lufsM_{-120.0f}, lufsS_{-120.0f}, lufsI_{-120.0f};
+ std::atomic<float> lufsM_{-120.0f}, lufsS_{-120.0f}, lufsI_{-120.0f}, lraA_{0.0f};
+ std::atomic<float> pkInHoldA_{-120.0f}, pkOutHoldA_{-120.0f}, maxGrHoldA_{0.0f}, tpHoldA_{-120.0f}, clipsA_{0.0f};
+ std::atomic<float> relNowA_{120.0f}, deltaA_{0.0f}, srA_{44100.0f}, cpuA_{0.0f}, measuredA_{0.0f}, maxMA_{-120.0f}, maxSA_{-120.0f};
+ std::atomic<bool> resetPeaksReq_{false}, resetLoudReq_{false};
std::atomic<int32_t> scTrackId_{-1};
const float* scBuf_ = nullptr; int32_t scFrames_ = 0;
std::atomic<float> p_[kNumParams] = {};
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 2d17368f..7329da6c 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -3804,7 +3804,13 @@ Console.WriteLine("-- Nota Ceiling --");
Check(le.DeviceName(lt, ld) == "Nota Ceiling", $"name is Nota Ceiling (got '{le.DeviceName(lt, ld)}')");
Check(le.TrackDeviceBuiltinKind(lt, ld) == 14, $"builtin kind is 14 (got {le.TrackDeviceBuiltinKind(lt, ld)})");
int lpc = le.DeviceParamCount(lt, ld);
- Check(lpc == 7, $"Nota Ceiling exposes 7 params (got {lpc})");
+ Check(lpc == 11, $"Nota Ceiling exposes 11 params (got {lpc})");
+ string[] lnames = { "Ceiling", "Gain", "Release", "AutoRelease", "Character", "Lookahead", "StereoLink", "True Peak", "Delta", "SC HP", "Target" };
+ bool lnamesOk = lpc == lnames.Length;
+ for (int p = 0; p < Math.Min(lpc, lnames.Length); p++) lnamesOk &= le.DeviceParamName(lt, ld, p) == lnames[p];
+ Check(lnamesOk, "the original seven params keep their order; True Peak, Delta, SC HP, Target are appended");
+ Check(le.DeviceParamDefault(lt, ld, 7) == 0f && le.DeviceParamDefault(lt, ld, 8) == 0f && Math.Abs(le.DeviceParamDefault(lt, ld, 9) - 20f) < 1e-3f
+ && Math.Abs(le.DeviceParamDefault(lt, ld, 10) + 14f) < 1e-3f, "appended params default to the old sound (sample peak, no delta, SC HP off, target −14)");
// Param round-trip (Ceiling = 0, Gain = 1).
le.DeviceSetParam(lt, ld, 0, -2.5f);
@@ -3820,11 +3826,18 @@ Console.WriteLine("-- Nota Ceiling --");
float ceilLin = (float)Math.Pow(10, -6.0 / 20.0);
Check(lfin && Rms(lb, 8192) > 0.001f, $"Ceiling passes audio (rms {Rms(lb, 8192):F3})");
Check(peak <= ceilLin + 1e-3f, $"output stays under the −6 dB ceiling (peak {20 * Math.Log10(Math.Max(1e-6f, peak)):F2} dB)");
- var sc = new float[8];
- int sn = le.DeviceScope(lt, ld, sc, 8);
- Check(sn == 7, $"Ceiling scope returns 7 meters (got {sn})");
- Check(sc[2] > 1.0f, $"limiter reports gain reduction (GR {sc[2]:F2} dB)");
+ const int CeTele = 40, CeLvl = 64, CeLoud = 120, CeScope = CeTele + 7 * CeLvl + 3 * CeLoud;
+ var sc = new float[CeScope];
+ int sn = le.DeviceScope(lt, ld, sc, CeScope);
+ Check(sn == CeScope, $"Ceiling scope returns the telemetry, the 4 s level and the 60 s loudness windows ({sn} of {CeScope})");
+ Check(le.DeviceScope(lt, ld, new float[7], 7) == 7, "a 7-slot reader still gets the original meters");
+ Check(sc[2] > 1.0f && sc[9] >= sc[2] - 0.01f, $"limiter reports gain reduction and holds its max (GR {sc[2]:F2}, max {sc[9]:F2} dB)");
Check(le.DeviceGainReduction(lt, ld) > 0.5f, "GR surfaces on the shell meter");
+ bool cellsOk = false;
+ for (int i = 0; i < CeLvl; i++) cellsOk |= sc[CeTele + 2 * CeLvl + i] > 1f && sc[CeTele + i] > sc[CeTele + CeLvl + i];
+ Check(cellsOk, "the level window has cells where the input tops the output and the reduction shows");
+ Check(sc[13] > 0.05f && sc[23] > -6f, $"over-the-ceiling share and the window's input peak ({sc[13] * 100:0} %, {sc[23]:F1} dB)");
+ Check(sc[20] > 1000 && sc[22] > 0, $"sample rate and latency reported ({sc[20]}, {sc[22]} smp)");
// Each character renders finite + audible.
le.DeviceSetParam(lt, ld, 1, 12f);
@@ -3837,15 +3850,22 @@ Console.WriteLine("-- Nota Ceiling --");
Check(mfin && Rms(mb, 8192) > 0.001f, $"Ceiling character {c} renders finite + audible (rms {Rms(mb, 8192):F3})");
}
le.DeviceSetParam(lt, ld, 4, 0f);
+ Check(le.DeviceParamCount(lt, ld) == 11, "param count stable after render");
- // Sidechain: the limiter accepts a source (Compressor plumbing).
- Check(le.DeviceParamCount(lt, ld) == 7, "param count stable after render");
+ // Reset peaks (action 0) clears the holds.
+ le.DeviceAction(lt, ld, 0, 0, 0);
+ { var z = new float[64 * 2]; le.Seek(3.9); le.RenderOffline(z, 64); }
+ le.DeviceScope(lt, ld, sc, CeScope);
+ Check(sc[9] < 0.01f && sc[7] < -100f && sc[19] == 0, $"device_action 0 resets the peaks (max GR {sc[9]:F2}, peak in {sc[7]:F1}, clips {sc[19]})");
- // Clone: duplicate track preserves params.
+ // Clone: duplicate track preserves params (appended ones too).
le.DeviceSetParam(lt, ld, 2, 220f); // Release
+ le.DeviceSetParam(lt, ld, 9, 150f); // SC HP
int lt2 = le.DuplicateTrack(lt);
int ld2 = le.TrackDeviceCount(lt2) - 1;
- Check(lt2 > 0 && Math.Abs(le.DeviceGetParam(lt2, ld2, 2) - 220f) < 1e-2, "duplicate track clones Ceiling params");
+ Check(lt2 > 0 && Math.Abs(le.DeviceGetParam(lt2, ld2, 2) - 220f) < 1e-2 && Math.Abs(le.DeviceGetParam(lt2, ld2, 9) - 150f) < 1e-2,
+ "duplicate track clones Ceiling params");
+ le.DeviceSetParam(lt, ld, 9, 20f);
// Automation: a device-param lane drives Gain (raw dB points).
int llane = le.AddAutomationLane(lt, AutomationTarget.DeviceParam, ld, 1);
@@ -3855,6 +3875,137 @@ Console.WriteLine("-- Nota Ceiling --");
le.Seek(1.99); le.Play(); le.RenderOffline(lab, 4096); le.StopTransport();
float lafter = le.DeviceGetParam(lt, ld, 1);
Check(lafter > 12f, $"automation drives Ceiling Gain ({lafter:F2} dB)");
+ int llane2 = le.AddAutomationLane(lt, AutomationTarget.DeviceParam, ld, 7);
+ le.SetAutomationPoints(lt, llane2, new[] { new AutomationPoint(0.0, 1f), new AutomationPoint(4.0, 1f) });
+ le.Seek(1.0); le.Play(); le.RenderOffline(lab, 1024); le.StopTransport();
+ Check(le.DeviceGetParam(lt, ld, 7) > 0.5f, "automation drives an appended param (True Peak)");
+}
+{
+ // A sine at fs/4 sampled 45° off its peaks: every sample sits 3 dB under the wave's real
+ // (inter-sample) peak — what a sample-peak limiter misses and True Peak must catch.
+ string tpwav = Path.Combine(Path.GetTempPath(), "nota_smoke_ceiling_tp.wav");
+ Nota.SmokeTest.WavWriter.WriteStereo(tpwav, 2.0, 44100, i =>
+ {
+ double v = 0.5 * Math.Sin(2 * Math.PI * 11025 * i / 44100.0 + Math.PI / 4);
+ return (v, v);
+ });
+ using var ce = new NotaEngine();
+ ce.SetBpm(120);
+ int ct = ce.AddAudioTrack();
+ ce.AddAudioClip(ct, tpwav, 0.0);
+ int cd = ce.AddBuiltinDevice(ct, 14);
+ const int CeTele = 40, CeLvl = 64, CeLoud = 120, CeScope = CeTele + 7 * CeLvl + 3 * CeLoud;
+ var csc = new float[CeScope];
+ float[] Render(int frames) { var b = new float[frames * 2]; ce.Seek(0); ce.Play(); ce.RenderOffline(b, frames); ce.StopTransport(); return b; }
+ float TpHold(bool tp)
+ {
+ ce.DeviceSetParam(ct, cd, 7, tp ? 1f : 0f);
+ Render(8192); // settle the envelope on the new detector
+ ce.DeviceAction(ct, cd, 0, 0, 0);
+ Render(22050);
+ ce.DeviceScope(ct, cd, csc, CeScope);
+ return csc[10];
+ }
+ ce.DeviceSetParam(ct, cd, 0, -1f);
+ ce.DeviceSetParam(ct, cd, 1, 12f);
+ float tpOff = TpHold(false), tpOn = TpHold(true);
+ Check(tpOff > 0.5f && tpOn < tpOff - 1.5f && tpOn < 0.5f,
+ $"True Peak holds the inter-sample peak near the ceiling ({tpOff:F1} dBTP sample-peak mode → {tpOn:F1} dBTP)");
+ ce.DeviceSetParam(ct, cd, 7, 0f);
+
+ // Delta: without limiting the difference is silent; driven, it carries what is removed.
+ ce.DeviceSetParam(ct, cd, 0, 0f);
+ ce.DeviceSetParam(ct, cd, 1, 0f);
+ ce.DeviceSetParam(ct, cd, 8, 1f);
+ Render(22050);
+ var d0 = Render(22050);
+ ce.DeviceSetParam(ct, cd, 1, 18f);
+ Render(8192);
+ var d1 = Render(22050);
+ Check(Rms(d0, 22050) < 1e-3f && Rms(d1, 22050) > 0.05f, $"Delta plays what it removes (clean {Rms(d0, 22050):F4}, driven {Rms(d1, 22050):F3})");
+ ce.DeviceSetParam(ct, cd, 8, 0f);
+
+ // SC HP: a 11 kHz tone passes a 500 Hz key high-pass, so the reduction is unchanged — but a
+ // 440 Hz tone (the smoke sine) loses level in the key and the reduction eases.
+ int st = ce.AddAudioTrack();
+ ce.AddAudioClip(st, wav, 0.0);
+ int sd = ce.AddBuiltinDevice(st, 14);
+ ce.SetTrackMute(ct, true);
+ ce.DeviceSetParam(st, sd, 1, 12f);
+ float Gr(float hp)
+ {
+ ce.DeviceSetParam(st, sd, 9, hp);
+ Render(8192);
+ ce.DeviceAction(st, sd, 0, 0, 0);
+ Render(22050);
+ ce.DeviceScope(st, sd, csc, CeScope);
+ return csc[9];
+ }
+ float grFlat = Gr(20f), grHp = Gr(500f);
+ Check(grFlat > 3f && grHp < grFlat - 1f, $"SC HP takes the lows out of the detector (GR {grFlat:F1} → {grHp:F1} dB)");
+ ce.DeviceSetParam(st, sd, 9, 20f);
+
+ // Loudness (measured before the track fader): the unlimited 440 Hz sine reads a steady
+ // loudness, and 6 dB less Gain reads 6 LU less (the K-weighting is flat at 440 Hz).
+ ce.DeviceSetParam(st, sd, 1, 0f);
+ ce.DeviceSetParam(st, sd, 0, 0f);
+ float Integrated(float gain)
+ {
+ ce.DeviceSetParam(st, sd, 1, gain);
+ Render(4096);
+ ce.DeviceAction(st, sd, 1, 0, 0);
+ Render(44100);
+ ce.DeviceScope(st, sd, csc, CeScope);
+ return csc[5];
+ }
+ float i6 = Integrated(-6f), i0 = Integrated(0f);
+ Check(i0 > -12f && i0 < 0f && Math.Abs(i0 - i6 - 6f) < 0.3f && Math.Abs(csc[3] - i0) < 1f,
+ $"integrated loudness reads the sine and follows the level ({i0:F1} LUFS, −6 dB → {i6:F1})");
+ Check(csc[11] >= 0 && csc[12] > 0 && csc[30] > 0.5f, $"LRA, PLR and the measured time are reported ({csc[11]:F1} LU, {csc[12]:F1} dB, {csc[30]:F1} s)");
+ bool loudCells = false;
+ for (int i = 0; i < CeLoud; i++) loudCells |= csc[CeTele + 7 * CeLvl + CeLoud + i] > -60f;
+ Check(loudCells, "the 60 s loudness window fills");
+ ce.DeviceAction(st, sd, 1, 0, 0);
+ { var z = new float[64 * 2]; ce.Seek(0); ce.Play(); ce.RenderOffline(z, 64); ce.StopTransport(); }
+ ce.DeviceScope(st, sd, csc, CeScope);
+ Check(csc[5] < -100f && csc[11] == 0f, $"device_action 1 resets the loudness (I {csc[5]:F1}, LRA {csc[11]:F1})");
+
+ // Texts.
+ ce.DeviceSetParam(st, sd, 7, 1f);
+ ce.DeviceSetParam(st, sd, 10, -16f);
+ string t0 = ce.DeviceText(st, sd, 0), t1 = ce.DeviceText(st, sd, 1), t2 = ce.DeviceText(st, sd, 2);
+ Check(t0.StartsWith("Clean") && t0.Contains("TP") && t0.Contains("target -16") && t1.Contains("LUFS") && t1.Contains("LRA") && t2.Contains("SC HP"),
+ $"device texts: status '{t0[..Math.Min(60, t0.Length)]}…', live, guide");
+
+ // MCP reading.
+ ce.DeviceSetParam(st, sd, 1, 12f);
+ Render(44100);
+ var cetools = new Nota.Mcp.Tools.DeviceTools(ce, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ var cr = cetools.ReadCeiling(st, sd).Result;
+ Check(cr.Character == "Clean" && cr.TruePeakMode && cr.TargetLufs == -16 && cr.Level.Length == 16 && cr.Loudness.Length == 20
+ && cr.MaxReductionHoldDb > 1 && cr.IntegratedLufs > -70 && cr.SampleRate > 1000 && cr.Summary.Length > 0 && cr.Live.Length > 0
+ && cr.Level.Any(c => c.ReductionDb > 1),
+ $"MCP read_ceiling reports the reduction, loudness and windows (GR max {cr.MaxReductionHoldDb}, I {cr.IntegratedLufs}, {cr.FromTargetLu:+0.0;-0.0} LU)");
+
+ // Every factory preset names only real params and renders finite, under its ceiling.
+ var cecat = new FactoryPresetCatalog();
+ int cePresets = 0; bool ceNamesOk = true, cePresetsOk = true;
+ var ceNames = new HashSet<string>();
+ for (int p = 0; p < ce.DeviceParamCount(st, sd); p++) ceNames.Add(ce.DeviceParamName(st, sd, p));
+ foreach (var info in cecat.All())
+ {
+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 14) continue;
+ var doc = cecat.Document(info.Id);
+ if (doc is null) continue;
+ cePresets++;
+ foreach (var k in doc.NamedParams!.Keys) if (!ceNames.Contains(k)) { ceNamesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }
+ cecat.ApplyInPlace(ce, info.Id, st, sd);
+ Render(4096);
+ var pb = Render(22050);
+ float lim = (float)Math.Pow(10, ce.DeviceGetParam(st, sd, 0) / 20.0) * (ce.DeviceGetParam(st, sd, 8) > 0.5f ? 8f : 1.0001f);
+ foreach (var v in pb) if (!float.IsFinite(v) || Math.Abs(v) > lim) { cePresetsOk = false; Console.WriteLine($" preset {info.DisplayName} not finite / over ({v})"); break; }
+ }
+ Check(cePresets >= 25 && ceNamesOk && cePresetsOk, $"{cePresets} Ceiling factory presets, all params known, all render finite and under the ceiling");
}
// ============================ Nota Strata ==================================