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 Shutter

Egor Khindikaynen99d5a10f79e9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1da7bd14..27fa9cbd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,37 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Shutter shows the gate working, and gains a shape, trigger mode and a real key
+ switch.** The card moves onto the 700 × 260 frame of Utility, Valve and Vintage — a STATE
+ column (the input, or the key when a sidechain drives it, with the threshold tick, and the
+ reduction), a centre panel with **Signal**, **Envelope** and **Sidechain** tabs, a
+ **Detector** / **Meters** panel and a status strip. The threshold and return no longer sit
+ in a strip above everything — they are lines on the graph where the gate acts:
+ - **Signal** — the input and what passes over the last 250 ms, 1 s or 4 s (click the
+ window in the tab bar), with the threshold and the close level to drag up and down, Gate /
+ Duck, Lookahead, **Live** to freeze the picture, and how much of the window was open.
+ - **Envelope** — one opening drawn from attack, hold, release, shape and floor (upside
+ down for Duck); drag the nodes for the times and the floor for the range. New **Shape**:
+ Linear ramps, Log (the classic one-pole) or Snap (stays open, then shuts hard). New
+ **Retrig**: trigger mode, where each hit fires one attack → hold → release however long
+ the sound lasts — for gated reverbs and chopped pads. Openings per bar are counted.
+ - **Sidechain** — the key source list, the detector's band-pass (now 12 dB/oct) with its
+ HP / LP nodes over the reduction, Listen, and **SC EQ** to switch the band-pass out.
+ - **Detector / Meters** — source, threshold, return, floor and a state box (closed, attack,
+ open, hold, release with the gain); in / out / GR with the peak, SC HP / LP, range,
+ Listen and **Reset**. New switches: **External sidechain** (keep a routed key but listen
+ to the track itself) and **Peak hold** (the detector holds peaks, so low notes don't
+ chatter the gate).
+ - **30 factory presets**, up from six — drums (kick, snare, toms, hats, overheads, room,
+ gated reverb, drum trigger), voice (podcast, breaths, dialogue), guitar and bass, pads,
+ rhythmic chops and ducking (sidechain pump, bass under kick, voice-over). The five new
+ parameters are appended and default to the old behaviour, so older projects open
+ unchanged; every one of them automates (the detector's grouped under *Det* in the lane
+ menu), MIDI-learns, saves in a preset and is reachable over MCP. `get_device_text`
+ returns the status line, the live reading and a guide to the parameter values,
+ `device_action` 0 resets the meters and 1 sets the window, and the new `read_shutter`
+ returns the state, the gain and reduction, the levels, the open share, the openings per
+ bar and the window's history.
- **Nota Physical's editor is now the almanac's card, with a voice mode, a resonator mix and
the partials it actually rings.** The card moves onto the 700 × 260 frame the other
instruments use — an **Exciter** / **Resonator** tab panel with a one-line reading of the
@@ -214,6 +245,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
returns the compressor's status line.
### Fixed
+- **Nota Shutter's detector and Duck.** The detector's follower let go of the key within a
+ sample instead of over 3 ms, so the gate leaned on Hold to stay open on low notes; it now
+ follows the key as intended, and the level meters decay smoothly. In Duck, Attack now sets
+ how fast the signal goes down and Release how fast it comes back (they were swapped).
- **Nota Physical's 1→2 structure no longer blows up.** Resonator 1 fed resonator 2 at full
gain, so a partial landing on one of resonator 2's rang it up by thousands of times and the
track clipped. Resonator 2 now works as a set of resonant band-passes at the level of its
diff --git a/FEATURES.md b/FEATURES.md
index 9bc88ed6..9fd33995 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -411,8 +411,11 @@ and user presets, automation, persistence and cloning.
AUTO/MATCH, true-peak safe, sidechain (match to reference); loudness history and
IN/OUT/TP/correlation meters.
- **Nota Shutter** (19) — noise gate and ducker: Threshold/Return (hysteresis),
- Attack/Hold/Release, Floor, Lookahead, Flip (ducker), band-pass sidechain with Listen; a
- signal graph, IN/GR meters, LED.
+ Attack/Hold/Release with a Linear / Log / Snap shape, Floor (range), Lookahead, Flip
+ (ducker), Retrigger (trigger mode), a 12 dB/oct detector band-pass (switchable) with Listen,
+ Peak hold, internal or external key; Signal / Envelope / Sidechain graphs (drag the
+ threshold, the envelope nodes and the key filter), a STATE column, a state box, meters
+ with peak GR and openings per bar; 30 factory presets; MCP `read_shutter`.
- **Nota Chamber** (20) — hybrid reverb: a zero-latency convolution engine (16 synthesised
IRs — halls, rooms, plates, spring, spaces, FX — or your own WAV/FLAC/MP3, mono / stereo /
4-ch true stereo, dropped on the IR view) with Start/Decay trims, Attack, Size, Reverse,
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index 4c98f14f..2c9722d4 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -390,10 +390,11 @@ public sealed partial class ArrangementView
// Nota Prism (52) by band ("Low", "Mid", "High", "Crossover") and Nota Lens (37) by
// view ("Spectrum", "Scope", "Waterfall", "Cursor"), the Compressor its key
// ("SC HP", "SC Gain" …), the Auto Filter its sources ("Env", "LFO", "Mod"), Nota
- // Vintage its tone and wow ("Tone Low", "Wow Rate" …), Nota Valve its mic ("Mic Distance" …) and
- // Nota Utility its mono, phase and true-peak params ("Mono Freq", "Invert L", "TP Ceiling" …):
+ // Vintage its tone and wow ("Tone Low", "Wow Rate" …), Nota Valve its mic ("Mic Distance" …),
+ // Nota Utility its mono, phase and true-peak params ("Mono Freq", "Invert L", "TP Ceiling" …) and
+ // Nota Shutter its detector ("Det HP", "Det LP", "Det Filter"):
// a word shared by two or more params becomes a submenu.
- bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 4 or 6 or 7 or 8 or 20 or 21 or 22;
+ bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 4 or 6 or 7 or 8 or 19 or 20 or 21 or 22;
var names = new string[builtinPc];
for (int p = 0; p < builtinPc; p++) names[p] = e.DeviceParamName(t.Id, d, p);
static string Head(string n) { int sp = n.IndexOf(' '); return sp > 0 ? n[..sp] : ""; }
diff --git a/src/managed/Nota.App/Controls/ShutterViews.cs b/src/managed/Nota.App/Controls/ShutterViews.cs
new file mode 100644
index 00000000..7cf6be5f
--- /dev/null
+++ b/src/managed/Nota.App/Controls/ShutterViews.cs
@@ -0,0 +1,452 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Shutter (device kind 19) card windows, all read from the engine's telemetry
+// (Shutter.h scopeRead) so the picture is what the gate does:
+// · ShPill — a STATE column pill meter: a level rising from the bottom (input / key, with
+// the threshold tick) or a reduction hanging from the top.
+// · ShSignalView — the Signal tab: the input over the window as teal columns, the gated
+// output in brass, the threshold (brass dashed) and the close level (Ink dashed) where
+// they act. Drag a line up or down to set the threshold / the return.
+// · ShEnvelopeView — the Envelope tab: one opening drawn from the attack / hold / release /
+// shape / floor (inverted for Duck). Drag the nodes sideways for the times, the floor up
+// or down.
+// · ShKeyView — the Sidechain tab: the detector band-pass (teal, 12 dB/oct) with its HP /
+// LP nodes to drag, under the reduction over the window (brass).
+// Shared drag contract (ShDragView): left button only, a gesture per drag, double-click
+// resets the handle, right-click bubbles to the MIDI-learn menu.
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class ShPill : Control
+{
+ private double _v, _tick = double.NaN;
+ public bool FromTop { get; init; }
+ public IBrush Ink { get; init; } = NotaPalette.Accent;
+
+ public ShPill() { Width = 16; }
+
+ /// <summary>The fill 0..1 and the threshold tick 0..1 (NaN = none).</summary>
+ public void Set(double v, double tick)
+ {
+ v = Math.Clamp(v, 0, 1);
+ if (Math.Abs(v - _v) < 1e-3 && (tick.Equals(_tick) || Math.Abs(tick - _tick) < 1e-3)) return;
+ _v = v; _tick = tick; InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 4 || h < 8) return;
+ var rect = new Rect(0.5, 0.5, w - 1, h - 1);
+ double r = Math.Min(8, w / 2);
+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), rect, r, r);
+ using (ctx.PushClip(new RoundedRect(rect, r)))
+ {
+ double y = FromTop ? _v * h : (1 - _v) * h;
+ var fill = FromTop ? new Rect(0, 0, w, y) : new Rect(0, y, w, h - y);
+ ctx.FillRectangle(NotaPalette.Wash((SolidColorBrush)Ink, 0x48), fill);
+ if (_v > 0.004) ctx.FillRectangle(Ink, new Rect(1.5, Math.Clamp(y - 1, 0, h - 2), w - 3, 2));
+ if (!double.IsNaN(_tick))
+ {
+ double ty = (1 - Math.Clamp(_tick, 0, 1)) * h;
+ ctx.DrawLine(new Pen(NotaPalette.Threshold, 1, new DashStyle(new double[] { 2, 2 }, 0)), new Point(0, ty), new Point(w, ty));
+ }
+ }
+ }
+}
+
+/// <summary>A window with draggable handles: subclasses say which handle is under the pointer
+/// and what value a drag gives it.</summary>
+internal abstract class ShDragView : Control
+{
+ private int _drag = -1;
+ private Point _start;
+ private double _v0;
+
+ public event Action<int>? GestureBegin;
+ public event Action<int>? GestureEnd;
+ public event Action<int, double>? Changed;
+ public event Action<int>? ResetRequested;
+ /// <summary>The handle's current value (0..1), read when a drag starts.</summary>
+ public Func<int, double>? Value { get; set; }
+ public bool Dragging => _drag >= 0;
+ protected int Active => _drag;
+
+ protected ShDragView() { ClipToBounds = true; MinHeight = 36; }
+
+ /// <summary>The handle under <paramref name="p"/>, or −1.</summary>
+ protected abstract int Hit(Point p);
+ /// <summary>The handle's new value for a drag from <paramref name="start"/> (value v0) to <paramref name="p"/>.</summary>
+ protected abstract double DragTo(int handle, Point start, Point p, double v0);
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ int hdl = Hit(e.GetPosition(this));
+ if (hdl < 0) return;
+ if (e.ClickCount == 2) { ResetRequested?.Invoke(hdl); InvalidateVisual(); e.Handled = true; return; }
+ _drag = hdl; _start = e.GetPosition(this); _v0 = Value?.Invoke(hdl) ?? 0;
+ GestureBegin?.Invoke(hdl); e.Pointer.Capture(this); e.Handled = true;
+ Move(e.GetPosition(this));
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ var p = e.GetPosition(this);
+ if (_drag >= 0) { Move(p); return; }
+ Cursor = Hit(p) is var h && h >= 0 ? new Cursor(CursorFor(h)) : Cursor.Default;
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (_drag < 0) return;
+ int h = _drag; _drag = -1; e.Pointer.Capture(null); GestureEnd?.Invoke(h); InvalidateVisual();
+ }
+ protected virtual StandardCursorType CursorFor(int handle) => StandardCursorType.SizeNorthSouth;
+
+ private void Move(Point p)
+ {
+ double v = Math.Clamp(DragTo(_drag, _start, p, _v0), 0, 1);
+ Changed?.Invoke(_drag, v);
+ InvalidateVisual();
+ }
+
+ protected static void Text(DrawingContext ctx, string s, double x, double y, IBrush? ink = null)
+ => ctx.DrawText(NotaGraph.AxisText(s, ink), new Point(x, y));
+ protected static void TextR(DrawingContext ctx, string s, double right, double y, IBrush? ink = null)
+ {
+ var ft = NotaGraph.AxisText(s, ink);
+ ctx.DrawText(ft, new Point(right - ft.Width, y));
+ }
+ protected static void Grid(DrawingContext ctx, double w, double h, int cols)
+ {
+ for (int i = 1; i < 4; i++) ctx.DrawLine(NotaGraph.GridPen, new Point(0, h * i / 4), new Point(w, h * i / 4));
+ for (int i = 1; i < cols; i++) ctx.DrawLine(NotaGraph.GridPen, new Point(w * i / cols, 0), new Point(w * i / cols, h));
+ }
+}
+
+internal sealed class ShSignalView : ShDragView
+{
+ public const int HThreshold = 0, HReturn = 1;
+ private const double DbTop = 0, DbBot = -72;
+ private float[] _in = Array.Empty<float>(), _gate = Array.Empty<float>();
+ private int _n;
+ private double _thr = -38, _ret = -41;
+ private string _window = "";
+ private int _closing = -1;
+ private bool _duck;
+
+ public void Set(float[] src, int inAt, int gateAt, int n, double thrDb, double retDb, bool duck, string window)
+ {
+ if (_in.Length != n) { _in = new float[n]; _gate = new float[n]; }
+ if (n > 0 && inAt + n <= src.Length && gateAt + n <= src.Length) { Array.Copy(src, inAt, _in, 0, n); Array.Copy(src, gateAt, _gate, 0, n); }
+ _n = n; _thr = thrDb; _ret = retDb; _duck = duck; _window = window;
+ // Where the gate last closed: the newest column that went from open to shut.
+ _closing = -1;
+ for (int i = n - 1; i > 0; i--)
+ if (_gate[i] < 0.5f && _gate[i - 1] >= 0.5f) { _closing = i; break; }
+ InvalidateVisual();
+ }
+
+ private (double top, double bot) Band() => (14, Bounds.Height - 12);
+ private double Y(double db) { var (t, b) = Band(); return t + Math.Clamp((DbTop - db) / (DbTop - DbBot), 0, 1) * (b - t); }
+ private double DbAt(double y) { var (t, b) = Band(); return DbTop - Math.Clamp((y - t) / Math.Max(1, b - t), 0, 1) * (DbTop - DbBot); }
+
+ protected override int Hit(Point p)
+ {
+ double dt = Math.Abs(p.Y - Y(_thr)), dr = Math.Abs(p.Y - Y(_ret));
+ if (dt <= 6 && dt <= dr + 1) return HThreshold;
+ if (dr <= 6) return HReturn;
+ return HThreshold; // anywhere else: the threshold, the graph's main handle
+ }
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ double db = DbAt(p.Y);
+ return handle == HThreshold ? (db + 70) / 70 : (_thr - db) / 24;
+ }
+
+ 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);
+ Grid(ctx, w, h, 6);
+ double gx = 4, gw = w - 8;
+ double X(int i) => gx + (i + 0.5) / Math.Max(1, _n) * gw;
+
+ if (_n > 1)
+ {
+ // Input: a teal column per slice.
+ var inPen = new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x70), Math.Max(1, Math.Min(2.4, gw / _n * 0.55)));
+ double floorY = Y(DbBot);
+ for (int i = 0; i < _n; i++)
+ if (_in[i] > DbBot + 0.5) ctx.DrawLine(inPen, new Point(X(i), floorY), new Point(X(i), Y(_in[i])));
+
+ // Output: the input times the gate, in brass.
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ for (int i = 0; i < _n; i++)
+ {
+ double gain = Math.Max(1e-6, _gate[i]);
+ double db = _in[i] + 20 * Math.Log10(gain);
+ var pt = new Point(X(i), Y(Math.Max(DbBot, db)));
+ if (i == 0) c.BeginFigure(pt, false); else c.LineTo(pt);
+ }
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, g);
+ }
+
+ bool hotT = Active == HThreshold, hotR = Active == HReturn;
+ ctx.DrawLine(new Pen(NotaPalette.Accent, hotT ? 1.4 : 1, new DashStyle(new double[] { 4, 4 }, 0)), new Point(0, Y(_thr)), new Point(w, Y(_thr)));
+ ctx.DrawLine(new Pen(hotR ? NotaPalette.AccentDim : NotaPalette.BorderStrong, 1, new DashStyle(new double[] { 2, 4 }, 0)), new Point(0, Y(_ret)), new Point(w, Y(_ret)));
+
+ NotaGraph.Title(ctx, frame, _duck ? "Signal and duck" : "Signal and gate");
+ NotaGraph.Legend(ctx, w - 6, 3, ("input", NotaPalette.TealBright, NotaGraph.Mark.Area), ("output", NotaPalette.AccentBright, NotaGraph.Mark.Line));
+ var thrTxt = NotaNum.F($"threshold {_thr:0.0}");
+ double ty = Y(_thr) - 11;
+ if (ty < 14) ty = Y(_thr) + 2;
+ Text(ctx, thrTxt, 6, ty, NotaPalette.AccentBright);
+ Text(ctx, "−" + _window, 6, h - 11);
+ TextR(ctx, "now", w - 6, h - 11);
+ if (_closing > _n * 0.12 && _closing < _n * 0.85)
+ Text(ctx, _duck ? "released" : "closed", X(_closing) + 3, h - 11);
+ }
+}
+
+internal sealed class ShEnvelopeView : ShDragView
+{
+ public const int HAttack = 0, HHold = 1, HRelease = 2, HFloor = 3;
+ private double _atk = 1, _hold = 15, _rel = 120, _floor, _span = 250;
+ private int _shape = 1;
+ private bool _duck, _retrig;
+ private string _floorText = "", _atkText = "", _holdText = "", _relText = "";
+ private static readonly double[] Spans = { 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000 };
+
+ /// <summary>Times in ms, the floor as linear gain (0 = −∞), the shape 0 linear / 1 log /
+ /// 2 snap, duck = inverted, trigger mode, and the captions.</summary>
+ public void Set(double atkMs, double holdMs, double relMs, double floorLin, int shape, bool duck, bool retrig,
+ string floorText, string atkText, string holdText, string relText)
+ {
+ _atk = atkMs; _hold = holdMs; _rel = relMs; _floor = floorLin; _shape = shape; _duck = duck; _retrig = retrig;
+ _floorText = floorText; _atkText = atkText; _holdText = holdText; _relText = relText;
+ if (!Dragging)
+ {
+ double need = shape == 1 ? (atkMs * 3 + holdMs + relMs * 3) * 1.2 : (atkMs + holdMs + relMs) * 1.45; // Log keeps approaching
+ _span = Spans[^1];
+ foreach (double s in Spans) if (s >= need) { _span = s; break; }
+ }
+ InvalidateVisual();
+ }
+
+ private double Top => 16;
+ private double Bot => Bounds.Height - 14;
+ private double X0 => Bounds.Width * 0.12;
+ private double Xt(double ms) => X0 + ms / _span * Bounds.Width;
+ private double Yg(double g) => Top + (1 - Math.Clamp(g, 0, 1)) * (Bot - Top);
+ private double Gain(double engaged) => _duck ? 1 - (1 - _floor) * engaged : _floor + (1 - _floor) * engaged;
+ private double Shape(double e) => _shape == 2 ? 1 - Math.Pow(1 - e, 3) : e;
+
+ // Engaged fraction t ms after the opening: Linear / Snap ramp over exactly the times; Log is
+ // the one-pole the engine runs (the times are its time constants), so it keeps approaching.
+ private double E(double t)
+ {
+ if (t <= 0) return 0;
+ double ah = _atk + _hold;
+ if (_shape == 1)
+ {
+ double eh = 1 - Math.Exp(-ah / Math.Max(1e-3, _atk));
+ return t < ah ? 1 - Math.Exp(-t / Math.Max(1e-3, _atk)) : eh * Math.Exp(-(t - ah) / Math.Max(1e-3, _rel));
+ }
+ if (t < _atk) return t / Math.Max(1e-3, _atk);
+ if (t < ah) return 1;
+ return Math.Max(0, 1 - (t - ah) / Math.Max(1e-3, _rel));
+ }
+ private double Yt(double t) => Yg(Gain(Shape(E(t))));
+
+ private Point Node(int hdl) => hdl switch
+ {
+ HAttack => new Point(Xt(_atk), Yt(_atk)),
+ HHold => new Point(Xt(_atk + _hold), Yt(_atk + _hold)),
+ HRelease => new Point(Xt(_atk + _hold + _rel), Yt(_atk + _hold + _rel)),
+ _ => new Point(Bounds.Width - 14, Yg(_floor)),
+ };
+
+ protected override int Hit(Point p)
+ {
+ int best = -1; double bd = 14;
+ for (int k = 0; k < 4; k++)
+ {
+ var n = Node(k);
+ double d = Math.Abs(p.X - n.X) + Math.Abs(p.Y - n.Y) * 0.5;
+ if (d < bd) { bd = d; best = k; }
+ }
+ if (best >= 0) return best;
+ return Math.Abs(p.Y - Yg(_floor)) < 6 ? HFloor : -1;
+ }
+ protected override StandardCursorType CursorFor(int handle) => handle == HFloor ? StandardCursorType.SizeNorthSouth : StandardCursorType.SizeWestEast;
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ if (handle == HFloor)
+ {
+ double dy = (start.Y - p.Y) / Math.Max(40, Bot - Top);
+ return v0 + (_duck ? -dy : dy) * 0.9;
+ }
+ return v0 + (p.X - start.X) / Math.Max(60, Bounds.Width) * 0.8;
+ }
+
+ 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);
+ for (int i = 1; i < 4; i++) ctx.DrawLine(NotaGraph.GridPen, new Point(0, h * i / 4), new Point(w, h * i / 4));
+
+ double xa = Xt(_atk), xh = Xt(_atk + _hold), xr = Xt(_atk + _hold + _rel);
+ var mark = new Pen(NotaPalette.GraphBorder, 1, new DashStyle(new double[] { 3, 4 }, 0));
+ foreach (double x in new[] { X0, xa, xh, xr }) if (x < w) ctx.DrawLine(mark, new Point(x, 0), new Point(x, h));
+
+ // Floor (or the duck depth): teal dashed.
+ double yf = Yg(_floor);
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xA0), 1, new DashStyle(new double[] { 4, 4 }, 0)), new Point(0, yf), new Point(w, yf));
+
+ // One opening: rest → attack → hold → release → rest, sampled with the breakpoints kept exact.
+ var ts = new List<double>();
+ int px = Math.Max(40, (int)(w / 1.5));
+ for (int k = 0; k <= px; k++) ts.Add(((double)k / px * w - X0) / w * _span);
+ ts.Add(0); ts.Add(_atk); ts.Add(_atk + _hold); ts.Add(_atk + _hold + _rel);
+ ts.Sort();
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ bool first = true;
+ foreach (double t in ts)
+ {
+ var pt = new Point(Xt(Math.Max(t, -X0 / w * _span)), Yt(t));
+ if (first) { c.BeginFigure(pt, false); first = false; } else c.LineTo(pt);
+ }
+ c.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, g);
+ for (int k = 0; k < 3; k++) { var n = Node(k); if (n.X < w - 2) NotaGraph.Node(ctx, n, Active == k || Active < 0 && k == 0); }
+ NotaGraph.Node(ctx, Node(HFloor), Active == HFloor, NotaPalette.Teal);
+
+ NotaGraph.Title(ctx, frame, _duck ? "Duck envelope" : _retrig ? "Gate envelope · trigger" : "Gate envelope");
+ TextR(ctx, "open 0\u2009dB", w - 6, 3, NotaPalette.AccentBright);
+ double fy = _duck ? yf + 2 : yf - 11;
+ if (fy > h - 24) fy = yf - 11;
+ TextR(ctx, (_duck ? "duck " : "floor ") + _floorText, w - 22, fy, NotaPalette.TealBright);
+ double lx = Math.Max(4, X0 + (xa - X0) / 2 - 10);
+ Text(ctx, "atk " + _atkText, Math.Min(lx, w * 0.2), h - 11);
+ Text(ctx, "hold " + _holdText, Math.Clamp((xa + xh) / 2 - 12, w * 0.24, w * 0.5), h - 11);
+ Text(ctx, "rel " + _relText, Math.Clamp((xh + xr) / 2 - 12, w * 0.52, w - 70), h - 11);
+ }
+}
+
+internal sealed class ShKeyView : ShDragView
+{
+ public const int HHp = 0, HLp = 1;
+ private const double FMin = 20, FMax = 20000, DbRange = 36;
+ private double _hpHz = 80, _lpHz = 2500;
+ private bool _on = true;
+ private float[] _gate = Array.Empty<float>();
+ private int _n;
+ private string _legend = "";
+
+ public void Set(double hpHz, double lpHz, bool filterOn, float[] src, int gateAt, int n, string legend)
+ {
+ _hpHz = hpHz; _lpHz = lpHz; _on = filterOn; _legend = legend;
+ if (_gate.Length != n) _gate = new float[n];
+ if (n > 0 && gateAt + n <= src.Length) Array.Copy(src, gateAt, _gate, 0, n);
+ _n = n;
+ InvalidateVisual();
+ }
+
+ private double X(double f) => Math.Log(f / FMin) / Math.Log(FMax / FMin) * Bounds.Width;
+ private double FAt(double x) => FMin * Math.Pow(FMax / FMin, Math.Clamp(x / Math.Max(1, Bounds.Width), 0, 1));
+ private double Top => 16;
+ private double Bot => Bounds.Height - 14;
+ private double Yd(double db) => Top + Math.Clamp(-db / DbRange, 0, 1) * (Bot - Top);
+ private double Mag(double f)
+ {
+ if (!_on) return 0;
+ double a = Math.Pow(f / _hpHz, 2), b = Math.Pow(f / _lpHz, 2);
+ double hp = a / Math.Sqrt(1 + a * a), lp = 1 / Math.Sqrt(1 + b * b);
+ return 20 * Math.Log10(Math.Max(1e-6, hp * lp));
+ }
+
+ protected override int Hit(Point p)
+ {
+ if (!_on) return -1;
+ double dh = Math.Abs(p.X - X(_hpHz)), dl = Math.Abs(p.X - X(_lpHz));
+ return dh <= dl ? HHp : HLp;
+ }
+ protected override StandardCursorType CursorFor(int handle) => StandardCursorType.SizeWestEast;
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ double f = FAt(p.X);
+ return handle == HHp ? Math.Log(f / 20) / Math.Log(100) : Math.Log(f / 200) / Math.Log(100);
+ }
+
+ 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);
+ Grid(ctx, w, h, 5);
+
+ // The reduction over the window (time runs left → right), under the filter.
+ if (_n > 1)
+ {
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ for (int i = 0; i < _n; i++)
+ {
+ double red = 1 - Math.Clamp(_gate[i], 0, 1);
+ var pt = new Point((i + 0.5) / _n * w, Bot - red * (Bot - Top) * 0.85);
+ if (i == 0) c.BeginFigure(pt, false); else c.LineTo(pt);
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.Accent, 0xB0), 1.3, lineJoin: PenLineJoin.Round), g);
+ }
+
+ // The key band-pass.
+ var curve = new StreamGeometry();
+ int px = Math.Max(24, (int)(w / 2));
+ using (var c = curve.Open())
+ for (int i = 0; i <= px; i++)
+ {
+ double x = (double)i / px * w;
+ var pt = new Point(x, Yd(Mag(FAt(x))));
+ if (i == 0) c.BeginFigure(pt, false); else c.LineTo(pt);
+ }
+ ctx.DrawGeometry(null, NotaGraph.SecondaryPen(_on ? NotaPalette.Teal : NotaPalette.BorderStrong, 1.8), curve);
+ if (_on)
+ {
+ NotaGraph.Node(ctx, new Point(X(_hpHz), Yd(Mag(_hpHz))), Active == HHp, NotaPalette.Teal);
+ NotaGraph.Node(ctx, new Point(X(_lpHz), Yd(Mag(_lpHz))), Active == HLp, NotaPalette.Teal);
+ }
+
+ NotaGraph.Title(ctx, frame, _on ? "Detector filter" : "Detector · full band");
+ NotaGraph.Legend(ctx, w - 6, 3, ("key", NotaPalette.TealBright, NotaGraph.Mark.Line), (_legend, NotaPalette.AccentBright, NotaGraph.Mark.Line));
+ static string Hz(double f) => f >= 1000 ? NotaNum.F($"{f / 1000:0.0}\u2009k") : NotaNum.F($"{f:0}");
+ Text(ctx, "20", 4, h - 11);
+ TextR(ctx, "20\u2009k", w - 4, h - 11);
+ if (_on)
+ {
+ double hx = Math.Clamp(X(_hpHz) - 8, 22, w - 90);
+ double lx = Math.Clamp(X(_lpHz) - 8, hx + 30, w - 50);
+ Text(ctx, Hz(_hpHz), hx, h - 11, NotaPalette.TealBright);
+ Text(ctx, Hz(_lpHz), lx, h - 11, NotaPalette.TealBright);
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/ShutterViz.cs b/src/managed/Nota.App/Controls/ShutterViz.cs
deleted file mode 100644
index dd10a617..00000000
--- a/src/managed/Nota.App/Controls/ShutterViz.cs
+++ /dev/null
@@ -1,228 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Shutter (device kind 19) visualisations:
-// · ShutterSignal — the signature SIGNAL graph. It scrolls the input level (olive area) and
-// the gate-gain curve (brass, high = open / low = shut) with the Threshold + Return lines
-// drawn where they act, so a crossing that opens the shutter and a soft hit that doesn't
-// are both visible. Read-only; samples the device meters each UI tick.
-// · ShutterDetectorEQ — the detector band-pass: a curve with two draggable handles (HP / LP)
-// setting which part of the key drives the gate.
-// · AHRGlyph — a tiny attack/hold/release trapezoid.
-
-using System;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Input;
-using Avalonia.Media;
-using Nota.Application;
-
-namespace Nota.App;
-
-internal sealed class ShutterSignal : Control
-{
- private const int S_InDb = 0, S_GateGain = 1, kScope = 5;
- private const int N = 300;
- private const double DbTop = 0, DbBot = -60;
-
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush BorderB = NotaPalette.BorderDefault;
- private static readonly IBrush InFill = NotaPalette.Wash(NotaPalette.SignalInFill, 0x8C);
- private static readonly IPen InPen = new Pen(NotaPalette.Wash(NotaPalette.SignalIn, 0xA0), 1);
- private static readonly IPen GatePen = new Pen(NotaPalette.Accent, 1.8);
- private static readonly IBrush GateFill = NotaPalette.Wash(NotaPalette.Accent, 0x12);
- private static readonly IPen ThrPen = new Pen(NotaPalette.Threshold, 1) { DashStyle = new DashStyle(new double[] { 4, 3 }, 0) };
- private static readonly IPen RetPen = new Pen(NotaPalette.Wash(NotaPalette.TextTertiary, 0xB0), 1) { DashStyle = new DashStyle(new double[] { 2, 4 }, 0) };
- private static readonly IBrush Muted = NotaPalette.TextTertiary;
- private static readonly IBrush ThrC = NotaPalette.Threshold;
- private static readonly IBrush AxisB = NotaPalette.TextTertiary;
- private static readonly Typeface Face = NotaFonts.Mono;
-
- private readonly IAudioEngine _engine;
- private readonly int _track, _device;
- private readonly float[] _in = new float[N], _gate = new float[N];
- private readonly float[] _scope = new float[kScope];
- private int _w; private bool _primed;
- // threshold/return in dB, pushed from the body.
- private double _thrDb = -38, _retDb = -41;
-
- public ShutterSignal(IAudioEngine engine, int track, int device)
- {
- _engine = engine; _track = track; _device = device;
- MinHeight = 60; ClipToBounds = true;
- for (int i = 0; i < N; i++) { _in[i] = -120; _gate[i] = 1; }
- }
-
- public void SetLines(double thrDb, double retDb) { _thrDb = thrDb; _retDb = retDb; }
-
- public void Tick()
- {
- int n = _engine.DeviceScope(_track, _device, _scope, kScope);
- if (n >= kScope)
- {
- _in[_w] = _scope[S_InDb]; _gate[_w] = _scope[S_GateGain];
- _w = (_w + 1) % N; _primed = true;
- }
- InvalidateVisual();
- }
-
- private static double YDb(double db, double gy, double gh) => gy + Math.Clamp((DbTop - db) / (DbTop - DbBot), 0, 1) * gh;
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- double gx = 6, gy = 14, gw = w - 12, gh = h - gy - 12;
- if (gw <= 0 || gh <= 0) return;
-
- double X(int i) => gx + (double)i / (N - 1) * gw;
- int Idx(int i) => (_w + i) % N;
- double GateY(double g) => gy + gh * 0.08 + (1 - Math.Clamp(g, 0, 1)) * gh * 0.84; // open=high, shut=low
-
- if (_primed)
- {
- // input level area (olive)
- var area = new StreamGeometry();
- using (var g = area.Open())
- {
- g.BeginFigure(new Point(gx, gy + gh), true);
- for (int i = 0; i < N; i++) g.LineTo(new Point(X(i), YDb(_in[Idx(i)], gy, gh)));
- g.LineTo(new Point(gx + gw, gy + gh)); g.EndFigure(true);
- }
- ctx.DrawGeometry(null, InPen, area);
- }
-
- // threshold + return lines
- ctx.DrawLine(ThrPen, new Point(gx, YDb(_thrDb, gy, gh)), new Point(gx + gw, YDb(_thrDb, gy, gh)));
- ctx.DrawLine(RetPen, new Point(gx, YDb(_retDb, gy, gh)), new Point(gx + gw, YDb(_retDb, gy, gh)));
-
- if (_primed)
- {
- // gate-gain curve (brass) + faint fill under it
- var fill = new StreamGeometry();
- using (var g = fill.Open())
- {
- g.BeginFigure(new Point(gx, gy + gh), true);
- for (int i = 0; i < N; i++) g.LineTo(new Point(X(i), GateY(_gate[Idx(i)])));
- g.LineTo(new Point(gx + gw, gy + gh)); g.EndFigure(true);
- }
- Point gp = default; bool has = false;
- for (int i = 0; i < N; i++) { var p = new Point(X(i), GateY(_gate[Idx(i)])); if (has) ctx.DrawLine(GatePen, gp, p); gp = p; has = true; }
- }
-
- void Lbl(string s, double x, double y, IBrush b) => ctx.DrawText(new FormattedText(s, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));
- Lbl("SIGNAL", gx, 2, Muted);
- NotaGraph.Legend(ctx, gx + gw - 2, 2, ("input", NotaPalette.SignalIn, NotaGraph.Mark.Area),
- ("gate gain", NotaPalette.Accent, NotaGraph.Mark.Line), ("threshold", ThrC, NotaGraph.Mark.Dashed));
- Lbl($"THRESHOLD {_thrDb:0}", gx + 2, YDb(_thrDb, gy, gh) - 10, ThrC);
- Lbl("−250\u2009ms", gx, gy + gh + 1, AxisB);
- Lbl("now", gx + gw - 18, gy + gh + 1, AxisB);
- }
-}
-
-// Detector band-pass: HP (left) and LP (right) handles set which key band drives the gate.
-internal sealed class ShutterDetectorEQ : Control
-{
- private const double HpLo = 20, HpHi = 2000, LpLo = 200, LpHi = 20000;
- private const double FMin = 20, FMax = 20000;
-
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush BorderB = NotaPalette.GraphBorder;
- private static readonly IPen CurvePen = new Pen(NotaPalette.Teal, 1.4);
- private static readonly IBrush CurveFill = NotaPalette.Wash(NotaPalette.Teal, 0x14);
- private static readonly IBrush Handle = NotaPalette.TealBright;
- private static readonly IBrush Axis = NotaPalette.TextAxis;
- private static readonly Typeface Face = NotaFonts.Mono;
-
- private double _hp = 0.301, _lp = 0.548; // normalized DetHP / DetLP
- private int _drag; // 0 none, 1 hp, 2 lp
-
- public event Action<double>? HpChanged;
- public event Action<double>? LpChanged;
-
- public ShutterDetectorEQ() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.SizeWestEast); }
- public void Set(double hp, double lp) { _hp = hp; _lp = lp; InvalidateVisual(); }
-
- private static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
- private double XOf(double f, double w) { double lm = Math.Log10(FMin), s = Math.Log10(FMax) - lm; return (Math.Log10(f) - lm) / s * w; }
-
- protected override void OnPointerPressed(PointerPressedEventArgs e)
- {
- double w = Bounds.Width; double x = e.GetPosition(this).X;
- double hx = XOf(Exp(_hp, HpLo, HpHi), w), lx = XOf(Exp(_lp, LpLo, LpHi), w);
- _drag = Math.Abs(x - hx) <= Math.Abs(x - lx) ? 1 : 2;
- e.Pointer.Capture(this); Apply(x); e.Handled = true;
- }
- protected override void OnPointerMoved(PointerEventArgs e) { if (_drag != 0) Apply(e.GetPosition(this).X); }
- protected override void OnPointerReleased(PointerReleasedEventArgs e) { _drag = 0; e.Pointer.Capture(null); }
-
- private void Apply(double x)
- {
- double w = Bounds.Width; if (w <= 0) return;
- double lm = Math.Log10(FMin), s = Math.Log10(FMax) - lm;
- double f = Math.Pow(10, lm + Math.Clamp(x / w, 0, 1) * s);
- if (_drag == 1) { double v = Math.Clamp(Math.Log(f / HpLo) / Math.Log(HpHi / HpLo), 0, 1); _hp = v; HpChanged?.Invoke(v); }
- else if (_drag == 2) { double v = Math.Clamp(Math.Log(f / LpLo) / Math.Log(LpHi / LpLo), 0, 1); _lp = v; LpChanged?.Invoke(v); }
- 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 hpF = Exp(_hp, HpLo, HpHi), lpF = Exp(_lp, LpLo, LpHi);
- ctx.DrawLine(new Pen(NotaPalette.SurfaceCard, 1), new Point(0, h * 0.75), new Point(w, h * 0.75));
-
- // band-pass magnitude (1-pole HP × 1-pole LP), log-x.
- int n = (int)Math.Clamp(w, 24, 150);
- var pts = new Point[n];
- double lm = Math.Log10(FMin), sp = Math.Log10(FMax) - lm;
- for (int i = 0; i < n; i++)
- {
- double f = Math.Pow(10, lm + (double)i / (n - 1) * sp);
- double hp = (f / hpF) / Math.Sqrt(1 + (f / hpF) * (f / hpF));
- double lp = 1.0 / Math.Sqrt(1 + (f / lpF) * (f / lpF));
- double m = hp * lp;
- pts[i] = new Point((double)i / (n - 1) * w, h - 4 - m * (h - 10));
- }
- var geo = new StreamGeometry();
- using (var g = geo.Open())
- {
- g.BeginFigure(new Point(0, h), true);
- foreach (var p in pts) g.LineTo(p);
- g.LineTo(new Point(w, h)); g.EndFigure(true);
- }
- for (int i = 1; i < n; i++) ctx.DrawLine(CurvePen, pts[i - 1], pts[i]);
-
- double hx = XOf(hpF, w), lx = XOf(lpF, w);
- ctx.DrawEllipse(Handle, null, new Point(hx, h * 0.5), 2.6, 2.6);
- ctx.DrawEllipse(Handle, null, new Point(lx, h * 0.5), 2.6, 2.6);
- void Lbl(string s, double x, double y) => ctx.DrawText(new FormattedText(s, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 7, Axis), new Point(x, y));
- Lbl(hpF >= 1000 ? $"{hpF / 1000:0.0}k" : $"{hpF:0}", 2, h - 9);
- Lbl(lpF >= 1000 ? $"{lpF / 1000:0.0}k" : $"{lpF:0}", w - 24, h - 9);
- }
-}
-
-// Tiny attack/hold/release trapezoid glyph.
-internal sealed class AHRGlyph : Control
-{
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush BorderB = NotaPalette.GraphBorder;
- private static readonly IPen Line = new Pen(NotaPalette.Accent, NotaGraph.PrimaryWidth) { LineJoin = PenLineJoin.Round };
- private static readonly IPen Dash = new Pen(NotaPalette.BorderStrong, 1) { DashStyle = new DashStyle(new double[] { 2, 2 }, 0) };
-
- 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 x0 = 5, x1 = w * 0.28, x2 = w * 0.6, x3 = w - 5, top = 5, bot = h - 6;
- ctx.DrawLine(Line, new Point(x0, bot), new Point(x1, top));
- ctx.DrawLine(Line, new Point(x1, top), new Point(x2, top));
- ctx.DrawLine(Line, new Point(x2, top), new Point(x3, bot));
- ctx.DrawLine(Dash, new Point(x1, top), new Point(x1, bot));
- ctx.DrawLine(Dash, new Point(x2, top), new Point(x2, bot));
- }
-}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs
index f7372a7d..f68fd30e 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs
@@ -1,17 +1,23 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Shutter (device kind 19) body, built to the Shutter
-// mockup: a noise gate. A LIVE strip (Threshold · Return · Flip · Lookahead) over a body of
-// three columns — an ENVELOPE column (open/shut state + A/H/R glyph + Attack/Hold/Release/
-// Floor), the SIGNAL graph in the middle (input level + gate-gain curve + threshold/return
-// lines), and a METERS + DETECTOR rail on the right (in/GR meters, open LED, and an external
-// sidechain key through its own band-pass with a Listen monitor).
+// Detail · Devices — built-in Nota Shutter body (noise gate / ducker, device kind 19), a build
+// of the "Nota Shutter" mockup (700 × 260) on the Utility / Valve / Vintage frame: an always-
+// visible STATE column (input or key level with the threshold · reduction), a centre panel
+// with Signal / Envelope / Sidechain tabs — the input and the gated output over the window
+// with the threshold and the close level on it, one opening drawn from attack / hold /
+// release / shape / floor, the detector's band-pass under the reduction — a right panel with
+// Detector / Meters tabs, and a status strip. The pictures come from the engine (Shutter.h
+// scopeRead), so they show what the gate does. Every control is a device param, so
+// automation / MIDI learn / presets / A-B / persistence come for free; the window length,
+// Live (freeze) and Reset are view / meter actions, not params.
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -22,227 +28,688 @@ namespace Nota.App;
internal sealed class ShutterDeviceBody : IDeviceBody
{
- private const int Threshold = 0, Return = 1, Attack = 2, Hold = 3, Release = 4, Floor = 5,
- Lookahead = 6, Flip = 7, DetHP = 8, DetLP = 9, Listen = 10;
- private const int S_InDb = 0, S_GateGain = 1, S_GrDb = 2, S_DetDb = 3, S_Open = 4, kScope = 5;
-
- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;
- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
- private static readonly IBrush Border2 = NotaPalette.BorderDefault;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);
- private static readonly IBrush TealC = NotaPalette.Teal;
- private static readonly IBrush TealSubtle = NotaPalette.Wash(NotaPalette.Teal, 0x24);
- private static readonly IBrush TxtC = NotaPalette.TextPrimary;
- private static readonly IBrush MutedC = NotaPalette.TextTertiary;
- private static readonly IBrush LabelC = NotaPalette.TextSecondary;
- private static readonly IBrush Dim = NotaPalette.BorderStrong;
- private static readonly IBrush Green = NotaPalette.Success;
- // Gate reduction and the shut state are the device working, not an alert: red belongs to
- // recording and overload, so shut reads as quiet ink and reduction as brass data.
- private static readonly IBrush Red = NotaPalette.Accent;
- private static readonly IBrush ThrC = NotaPalette.Threshold;
- private static readonly IBrush HandleC = NotaPalette.TextSecondary;
+ // ── Parameter indices (must match Shutter.h) ─────────────────────────────
+ private const int Threshold = 0, Return = 1, Attack = 2, Hold = 3, Release = 4, Floor = 5, Lookahead = 6, Flip = 7,
+ DetHP = 8, DetLP = 9, Listen = 10, Shape = 11, Retrigger = 12, DetFilter = 13, PeakHold = 14, ExternalKey = 15;
+ // Scope layout (Shutter::S_* / kTele / kHist).
+ private const int S_InDb = 0, S_GateGain = 1, S_GrDb = 2, S_DetDb = 3, S_Open = 4, S_State = 5, S_OutDb = 6, S_OpenRatio = 7,
+ S_TrigPerBar = 8, S_Triggers = 9, S_SampleRate = 10, S_Cpu = 11, S_Latency = 12, S_ExtKey = 13, S_KeyDb = 14,
+ S_PeakGrDb = 18, S_WindowSec = 20, S_HistN = 21, kTele = 24, kHist = 128;
+ private const int kScope = kTele + 3 * kHist;
+ private const int H_In = kTele, H_Gate = kTele + kHist, H_Det = kTele + 2 * kHist;
+ private const int A_ResetMeters = 0, A_Window = 1;
- public double Width => 700;
+ private static readonly string[] Shapes = { "Linear", "Log", "Snap" };
+ private static readonly string[] StateNames = { "closed", "attack", "open", "hold", "release" };
+ private static readonly string[] WindowNames = { "250\u2009ms", "1\u2009s", "4\u2009s" };
- public string? Subtitle => "GATE"; // the processing type, shown as the header badge
+ public double Width => 700;
public bool FullBleed => true;
+ public string? Subtitle => "GATE";
public Control Build(DeviceCardContext ctx, int index)
{
var engine = ctx.Engine;
int track = ctx.TrackId, di = index;
float P(int p) => engine.DeviceGetParam(track, di, p);
- void SetP(int p, float v) => engine.DeviceSetParam(track, di, p, v);
void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ void Raw(int p, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ double Def(int p) => engine.DeviceParamDefault(track, di, p);
+ bool On(int p) => P(p) >= 0.5f;
+ int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1);
var readouts = new List<Action>();
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
var scope = new float[kScope];
- Control Cap(string t, IBrush? c = null, double w = 0) { var tb = new TextBlock { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, VerticalAlignment = VerticalAlignment.Center }; if (w > 0) tb.Width = w; return tb; }
+ var frozen = new float[kScope];
+ int scN = 0;
+ bool live = true;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+ float[] Hist() => live ? scope : frozen;
+ // ---- units ----------------------------------------------------------------
+ static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ static string MsF(double ms) => ms >= 100 ? NotaNum.F($"{ms:0}\u2009ms") : ms >= 10 ? NotaNum.F($"{ms:0.0}\u2009ms") : NotaNum.F($"{ms:0.0#}\u2009ms");
+ static string MsN(double ms) => ms >= 100 ? NotaNum.F($"{ms:0}") : ms >= 10 ? NotaNum.F($"{ms:0.#}") : NotaNum.F($"{ms:0.0#}");
+ static string DbF(double db) => db <= -119 ? "−∞\u2009dB" : NotaNum.F($"{db:0.0}\u2009dB");
+ static string HzF(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0}\u2009k") : NotaNum.F($"{hz:0}");
double ThrDb() => -70 + P(Threshold) * 70;
- double RetDb() => ThrDb() - P(Return) * 24;
-
- var signal = new ShutterSignal(engine, track, di) { VerticalAlignment = VerticalAlignment.Stretch };
- void SyncLines() => signal.SetLines(ThrDb(), RetDb());
- ctx.AddDeviceRefresher(signal.Tick);
-
- // ---- formatters ----
- static string ThrF(double v) => $"{-70 + v * 70:0.0}\u2009dB";
- static string RetF(double v) => $"{v * 24:0.0}\u2009dB";
- static string Ms(double v, double lo, double hi) { double m = Exp(v, lo, hi); return m >= 100 ? $"{m:0}\u2009ms" : m >= 10 ? $"{m:0.0}\u2009ms" : $"{m:0.00}\u2009ms"; }
- static string AttF(double v) => Ms(v, 0.01, 100);
- static string HoldF(double v) => Ms(v, 0.1, 500);
- static string RelF(double v) => Ms(v, 1, 2000);
- static string FloorF(double v) => v <= 0.001 ? "−∞\u2009dB" : $"{-70 + v * 70:0.0}\u2009dB";
-
- // ---- horizontal slider ----
- Control HRow(int p, string label, Func<double, string> fmt, double labW, double valW, bool teal = false, bool bipolar = false)
- {
- var row = DeviceCardKit.SliderRow(labW > 0 ? label : "", () => P(p), n => { SetP(p, (float)n); SyncLines(); }, () => fmt(P(p)), out var sync,
- begin: () => Begin(p), end: () => End(p), bipolar: bipolar, labelWidth: labW, valueWidth: valW);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);
+ double RetDb() => P(Return) * 24;
+ double AtkMs() => Exp(P(Attack), 0.01, 100);
+ double HoldMs() => Exp(P(Hold), 0.1, 500);
+ double RelMs() => Exp(P(Release), 1, 2000);
+ double FloorDb() => P(Floor) <= 0.001f ? -120 : -70 + P(Floor) * 70;
+ double FloorLin() => P(Floor) <= 0.001f ? 0 : Math.Pow(10, FloorDb() / 20);
+ int LookMs() => new[] { 0, 1, 5 }[Sel(Lookahead, 3)];
+ bool Duck() => On(Flip);
+ string ThrShort(double v) => NotaNum.F($"{-70 + v * 70:0.0}");
+ string RetF(double v) => NotaNum.F($"{v * 24:0.0}\u2009dB");
+ string RetShort(double v) => NotaNum.F($"{v * 24:0.0}");
+ string AtkF(double v) => MsF(Exp(v, 0.01, 100));
+ string HoldF(double v) => MsF(Exp(v, 0.1, 500));
+ string RelF(double v) => MsF(Exp(v, 1, 2000));
+ string FloorF(double v) => v <= 0.001 ? "−∞\u2009dB" : NotaNum.F($"{-70 + v * 70:0.0}\u2009dB");
+ string FloorShort(double v) => v <= 0.001 ? "−∞" : NotaNum.F($"{-70 + v * 70:0.0}");
+ string LookF(double v) => NotaNum.F($"{new[] { 0, 1, 5 }[Math.Clamp((int)Math.Round(v * 2), 0, 2)]}\u2009ms");
+ string HpF(double v) => HzF(Exp(v, 20, 2000));
+ string LpF(double v) => HzF(Exp(v, 200, 20000));
+ string Times() => NotaNum.F($"{MsN(AtkMs())} / {MsN(HoldMs())} / {MsN(RelMs())}\u2009ms");
+ string GrText() => Sc(S_GrDb) < 0.05 ? "GR 0.0\u2009dB" : Sc(S_GrDb) > 99 ? "GR −∞\u2009dB" : NotaNum.F($"GR −{Sc(S_GrDb):0.0}\u2009dB");
+ string WindowText() { double s = Sc(S_WindowSec); return s <= 0 ? "1\u2009s" : s < 1 ? NotaNum.F($"{s * 1000:0}\u2009ms") : NotaNum.F($"{s:0.#}\u2009s"); }
+ int WindowIdx() { double s = Sc(S_WindowSec); return s <= 0 ? 1 : s < 0.5 ? 0 : s < 2 ? 1 : 2; }
+ int State() => Math.Clamp((int)Math.Round(Sc(S_State)), 0, 4);
+
+ // Sidechain key: the source track and whether it is in use.
+ 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() => On(ExternalKey) && Src() >= 0;
+ string KeyName() => ExtOn() ? SrcName(Src()) : "Internal";
+
+ // ---- 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).
+ // `steps` > 1 snaps a discrete param (Lookahead).
+ Control K(int p, string name, Func<double, string> fmt, IBrush? arc = null, int steps = 0, string? tip = null)
+ {
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = Def(p), Width = 34, Height = 34 };
+ knob.ValueChanged += v =>
+ {
+ if (steps > 1) v = Math.Round(v * (steps - 1)) / (steps - 1);
+ Raw(p, v); val.Text = fmt(P(p)); RefreshAll();
+ };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ if (tip is not null) ToolTip.SetTip(knob, tip);
+ readouts.Add(() => { if (knob.Dragging) return; double c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; val.Text = fmt(P(p)); });
+ return KnobCell(name, knob, val, 44);
+ }
+
+ // 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);
- return row;
+ Learn(wrap, p);
+ ToolTip.SetTip(wrap, tip);
+ return wrap;
}
- // Segmented pill over a normalized param.
- Control Seg(int p, string[] opts, bool teal = false)
+ // Segmented pill over a normalized discrete param.
+ Control Seg(int p, string[] names, string tip)
{
- int n = opts.Length;
- var seg = DeviceCardKit.Segments(opts, () => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1), iv => SetP(p, n > 1 ? iv / (float)(n - 1) : 0f), out var sync);
+ int n = names.Length;
+ var seg = Segments(names, () => Sel(p, n), iv => { SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); RefreshAll(); }, out var sync, padX: 6);
readouts.Add(sync);
- MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ Learn(seg, p);
+ ToolTip.SetTip(seg, tip);
return seg;
}
+ Control ModeSeg() => Seg(Flip, new[] { "Gate", "Duck" }, "Mode — Gate lets the signal through above the threshold; Duck turns it down while the key is above it");
+
+ // Outlined chips: lit = brass edge + wash.
+ Control Chips(string[] names, Func<int, bool> lit, Action<int> pick, int learnParam, string tip)
+ {
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center };
+ var cells = new Border[names.Length];
+ var texts = new TextBlock[names.Length];
+ for (int i = 0; i < names.Length; i++)
+ {
+ int iv = i;
+ var tb = new TextBlock { Text = names[i], 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), Child = tb };
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; pick(iv); RefreshAll(); e.Handled = true; };
+ cells[i] = b; texts[i] = tb; row.Children.Add(b);
+ }
+ readouts.Add(() =>
+ {
+ for (int i = 0; i < names.Length; i++)
+ {
+ bool on = lit(i);
+ cells[i].BorderBrush = on ? Brass : NotaPalette.BorderStrong;
+ cells[i].Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
+ texts[i].Foreground = on ? AccentBright : TextSecondary;
+ texts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ });
+ Learn(row, learnParam);
+ ToolTip.SetTip(row, tip);
+ return row;
+ }
+
+ // A latching chip: lit when `lit()`, a click runs `click`. `fill` = a full-width button.
+ Border Latch(int p, Func<bool> lit, Action click, Func<string> text, string tip, bool fill = false)
+ {
+ var tb = new TextBlock { 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;
+ tb.Text = text();
+ }
+ 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;
+ }
+ Border ToggleLatch(int p, string text, string tip, bool fill = false)
+ => Latch(p, () => On(p), () => SetP(p, On(p) ? 0f : 1f), () => text, tip, fill);
+ Border ListenLatch(bool fill = false) => ToggleLatch(Listen, "Listen", "Listen — hear the key as the detector hears it (after its filter), to tune the band", fill);
+
+ // Slider row: caps label · track · mono value.
+ Control SliderRow(string label, int p, Func<double, string> fmt, bool modulation = false, double labW = 40)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => P(p), v => { Raw(p, v); RefreshAll(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: 34, modulation: modulation);
+ readouts.Add(sync);
+ Learn(bar, p);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(NotaNum.F($"{labW},*")), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label));
+ g.Children.Add(Col(bar, 1));
+ return g;
+ }
+
+ // The key source: [name ▾] lists Internal and the other tracks. Picking a track switches
+ // External Key on; Internal clears the source.
+ Control KeyDrop(bool stretch)
+ {
+ 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 box = new Border
+ {
+ Height = 16, MinWidth = 74, Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,
+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
+ Child = new DockPanel { Children = { Docked(chev, Dock.Right), name } },
+ };
+ if (stretch) box.HorizontalAlignment = HorizontalAlignment.Stretch;
+ readouts.Add(() =>
+ {
+ bool ext = ExtOn();
+ name.Text = KeyName();
+ name.Foreground = ext ? AccentBright : TextPrimary;
+ name.FontWeight = ext ? FontWeight.SemiBold : FontWeight.Normal;
+ box.BorderBrush = ext ? Brass : BorderDef;
+ chev.Foreground = ext ? NotaPalette.AccentDim : TextTertiary;
+ });
+ ToolTip.SetTip(box, "Key source — Internal keys off this track; pick another track to gate or duck against it");
+ Learn(box, ExternalKey);
+ box.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;
+ var fly = new MenuFlyout();
+ void Item(string label, int id)
+ {
+ bool cur = id < 0 ? !ExtOn() : ExtOn() && Src() == id;
+ var mi = new MenuItem { Header = label };
+ if (cur) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };
+ mi.Click += (_, _) =>
+ {
+ engine.SetDeviceSidechainSource(track, di, id);
+ if (id >= 0 && !On(ExternalKey)) SetP(ExternalKey, 1f);
+ ctx.NotifyChanged(); RefreshAll();
+ };
+ fly.Items.Add(mi);
+ }
+ Item("Internal — this track", -1);
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) Item(SrcName(ti.Id), ti.Id);
+ fly.ShowAt(box);
+ e.Handled = true;
+ };
+ return box;
+ }
- // ---- LIVE strip ----
- var live = new Border { Height = 34, Background = HdrBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new DockPanel { LastChildFill = false, Margin = new Thickness(9, 0), Children = {
- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = {
- Cap("LIVE"),
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 210, Children = { Cap("THRESH", MutedC, 56), new Border { Child = HRow(Threshold, "", ThrF, 0, 58), Width = 140 } } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Width = 130, Children = { Cap("RETURN", MutedC, 38), new Border { Child = HRow(Return, "", RetF, 0, 48), Width = 80 } } } } }, Dock.Left),
- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("FLIP"), Seg(Flip, new[] { "Gate", "Duck" }) } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("LOOK"), Seg(Lookahead, new[] { "0", "1", "5\u2009ms" }) } } } }, Dock.Right) } } };
-
- // ================= ENVELOPE column =================
- var state = new TextBlock { Text = "OPEN", FontSize = 20, FontWeight = FontWeight.SemiBold, Foreground = Green, LineHeight = 20 }.WithMono();
- var stateSub = new TextBlock { Text = "gate · GR 0.0\u2009dB", FontSize = 9, Foreground = MutedC }.WithMono();
- var envTop = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Children = {
- new StackPanel { VerticalAlignment = VerticalAlignment.Center, Spacing = 1, Children = { state, stateSub } },
- WithCol(new Border { Width = 64, Height = 38, Child = new AHRGlyph(), VerticalAlignment = VerticalAlignment.Center }, 1) } };
-
- var env = new StackPanel { Spacing = 5, Margin = new Thickness(9, 7) };
- env.Children.Add(new Grid { Height = 10, ColumnDefinitions = new ColumnDefinitions("Auto,*"), Children = { Cap("ENVELOPE"), WithCol(new TextBlock { Text = "attack · hold · release", FontSize = 8, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Right }, 1) } });
- env.Children.Add(envTop);
- env.Children.Add(new Border { Height = 1, Background = NotaPalette.SurfaceRaised, Margin = new Thickness(0, 1) });
- env.Children.Add(new Grid { Height = 12, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Children = { Cap("ATTACK", MutedC, 52), WithCol(HRow(Attack, "", AttF, 0, 0), 1), WithCol(new TextBlock { Text = AttF(P(Attack)), FontSize = 9, Foreground = TxtC, Width = 46, TextAlignment = TextAlignment.Right }.WithMono().Track(readouts, t => t.Text = AttF(P(Attack))), 2) } });
- env.Children.Add(new Grid { Height = 12, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Children = { Cap("HOLD", MutedC, 52), WithCol(HRow(Hold, "", HoldF, 0, 0), 1), WithCol(new TextBlock { Text = HoldF(P(Hold)), FontSize = 9, Foreground = TxtC, Width = 46, TextAlignment = TextAlignment.Right }.WithMono().Track(readouts, t => t.Text = HoldF(P(Hold))), 2) } });
- env.Children.Add(new Grid { Height = 12, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Children = { Cap("RELEASE", MutedC, 52), WithCol(HRow(Release, "", RelF, 0, 0), 1), WithCol(new TextBlock { Text = RelF(P(Release)), FontSize = 9, Foreground = TxtC, Width = 46, TextAlignment = TextAlignment.Right }.WithMono().Track(readouts, t => t.Text = RelF(P(Release))), 2) } });
- env.Children.Add(new Grid { Height = 12, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Children = { Cap("FLOOR", MutedC, 52), WithCol(HRow(Floor, "", FloorF, 0, 0), 1), WithCol(new TextBlock { Text = FloorF(P(Floor)), FontSize = 9, Foreground = TxtC, Width = 46, TextAlignment = TextAlignment.Right }.WithMono().Track(readouts, t => t.Text = FloorF(P(Floor))), 2) } });
- var envPanel = new Border { Width = 206, Child = env };
-
- // ================= middle signal graph =================
- var mid = new Border { Padding = new Thickness(0, 7, 0, 7), Child = signal };
-
- // ================= METERS + DETECTOR rail =================
- Control Meter(string label, out Border fill, out TextBlock val, IBrush baseCol, out Border tick)
- {
- val = new TextBlock { FontSize = 9, Foreground = LabelC, Width = 38, TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center }.WithMono();
- fill = new Border { Background = baseCol, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch, Width = 0 };
- tick = new Border { Width = 1, Background = ThrC, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch, IsVisible = false };
- var trk = new Panel { Height = 5, Children = { new Border { Background = Inset, CornerRadius = NotaRadius.Clip }, fill, tick } };
- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("22,*,Auto"), ColumnSpacing = 5, Height = 6, VerticalAlignment = VerticalAlignment.Center };
- g.Children.Add(Cap(label)); Grid.SetColumn(trk, 1); g.Children.Add(trk); Grid.SetColumn(val, 2); g.Children.Add(val);
- g.Tag = trk; // so refresher can read the track width
+ // External sidechain switch: on uses the routed key (picks the first other track when
+ // none is routed yet), off keeps the source but keys off this track.
+ Control ExtSwitch()
+ {
+ var sw = Switch("External sidechain", ExtOn, () =>
+ {
+ if (ExtOn()) SetP(ExternalKey, 0f);
+ else
+ {
+ if (Src() < 0)
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) { engine.SetDeviceSidechainSource(track, di, ti.Id); break; }
+ if (Src() >= 0) SetP(ExternalKey, 1f);
+ }
+ ctx.NotifyChanged(); RefreshAll();
+ }, out var sync);
+ readouts.Add(sync);
+ Learn(sw, ExternalKey);
+ ToolTip.SetTip(sw, "External sidechain — the detector listens to the key source instead of this track");
+ return sw;
+ }
+
+ 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;
}
- var inRow = Meter("IN", out var inFill, out var inVal, Green, out var inTick);
- var grRow = Meter("GR", out var grFill, out var grVal, Red, out var _);
- var inTrk = (Panel)((Grid)inRow).Tag!; var grTrk = (Panel)((Grid)grRow).Tag!;
-
- var led = new Border { Width = 8, Height = 8, CornerRadius = NotaRadius.Control, Background = Green, VerticalAlignment = VerticalAlignment.Center };
- var ledTxt = new TextBlock { Text = "OPEN", FontSize = 9, FontWeight = FontWeight.Bold, Foreground = Green, VerticalAlignment = VerticalAlignment.Center };
- var duty = new TextBlock { Text = "", FontSize = 8, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center }.WithMono();
- var ledRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 6, Children = { led, WithCol(ledTxt, 1), WithCol(duty, 2) } };
-
- // detector: EXT toggle + source combo + SC EQ (band-pass) + LISTEN.
- var scIds = new List<int> { -1 };
- var scCombo = new ComboBox { FontSize = 9, Height = 20, HorizontalAlignment = HorizontalAlignment.Stretch, Padding = new Thickness(6, 0) };
- scCombo.Items.Add("Internal (this track)");
- for (int i = 0; i < engine.TrackCount; i++)
- {
- if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;
- string kind = ti.IsReturn ? "Return" : ti.IsInstrument ? "Inst" : "Audio";
- scIds.Add(ti.Id); scCombo.Items.Add($"Key: {i + 1} · {kind}");
- }
- scCombo.SelectedIndex = Math.Max(0, scIds.IndexOf(engine.DeviceSidechainSource(track, di)));
- var extSw = MakeToggle(() => engine.DeviceSidechainSource(track, di) >= 0, on => {
- int src = on ? (scIds.Count > 1 ? scIds[1] : -1) : -1; engine.SetDeviceSidechainSource(track, di, src);
- scCombo.SelectedIndex = Math.Max(0, scIds.IndexOf(src));
- }, "EXT", readouts);
- scCombo.SelectionChanged += (_, _) => { int sel = scCombo.SelectedIndex; if (sel < 0 || sel >= scIds.Count) return; engine.SetDeviceSidechainSource(track, di, scIds[sel]); };
-
- var detEq = new ShutterDetectorEQ();
- detEq.Set(P(DetHP), P(DetLP));
- detEq.HpChanged += v => { Begin(DetHP); SetP(DetHP, (float)v); End(DetHP); };
- detEq.LpChanged += v => { Begin(DetLP); SetP(DetLP, (float)v); End(DetLP); };
- readouts.Add(() => detEq.Set(P(DetHP), P(DetLP)));
-
- var listenChip = new Border { BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(5, 0), Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = "LISTEN", FontSize = 8, FontWeight = FontWeight.Bold, VerticalAlignment = VerticalAlignment.Center } };
- void ListenSync() { bool on = P(Listen) >= 0.5f; listenChip.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent; listenChip.BorderBrush = on ? NotaPalette.BorderBrass : Dim; ((TextBlock)listenChip.Child!).Foreground = on ? NotaPalette.AccentHover : MutedC; }
- listenChip.PointerPressed += (_, e) => { e.Handled = true; SetP(Listen, P(Listen) >= 0.5f ? 0f : 1f); ListenSync(); };
- readouts.Add(ListenSync);
-
- var scEqBox = new Border { Background = Inset, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(4), Child =
- new DockPanel { LastChildFill = true, Children = {
- new Grid { Height = 11, [DockPanel.DockProperty] = Dock.Top, ColumnDefinitions = new ColumnDefinitions("*,Auto"), Children = { Cap("SC EQ", MutedC), WithCol(listenChip, 1) } },
- detEq } } };
-
- var detector = new Border { BorderBrush = TealC, BorderThickness = new Thickness(2, 0, 0, 0), Padding = new Thickness(7, 0, 0, 0), Child =
- new DockPanel { LastChildFill = true, Children = {
- new Grid { Height = 12, [DockPanel.DockProperty] = Dock.Top, ColumnDefinitions = new ColumnDefinitions("*,Auto"), Children = { Cap("DETECTOR", TealC), WithCol(extSw, 1) } },
- new Border { Height = 20, Margin = new Thickness(0, 4), [DockPanel.DockProperty] = Dock.Top, Child = scCombo },
- scEqBox } } };
-
- var rail = new Border { Width = 176, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 7), Child =
- new DockPanel { LastChildFill = true, Children = {
- new StackPanel { [DockPanel.DockProperty] = Dock.Top, Spacing = 5, Children = { Cap("METERS"), inRow, grRow, ledRow,
- new Border { Height = 1, Background = NotaPalette.SurfaceRaised, Margin = new Thickness(0, 2) } } },
- detector } } };
-
- // ================= assemble =================
- DockPanel.SetDock(envPanel, Dock.Left); DockPanel.SetDock(rail, Dock.Right);
- var body = new DockPanel { LastChildFill = true, Children = { envPanel, rail, mid } };
- DockPanel.SetDock(live, Dock.Top);
- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };
-
- // ---- live refresh from scope ----
+ Control KnobRow(Control[] knobs, 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 g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 52, ColumnSpacing = 6 };
+ g.Children.Add(Row(4, knobs));
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { i1, i2 } }, 1));
+ return g;
+ }
+ static Control TabBody(Control head, Control window, Control knobs) => new DockPanel
+ {
+ LastChildFill = true, Margin = new Thickness(8, 5, 8, 0),
+ Children = { Docked(head, Dock.Top), Docked(knobs, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 0), Child = window } },
+ };
+ void WireDrag(ShDragView v, Func<int, int> param)
+ {
+ v.Value = h => P(param(h));
+ v.Changed += (h, x) => { Raw(param(h), x); Refresh(); }; // the graph redraws from the new value at once
+ v.GestureBegin += h => Begin(param(h));
+ v.GestureEnd += h => End(param(h));
+ v.ResetRequested += h => { Reset(param(h)); RefreshAll(); };
+ }
+
+ // ======================================================================
+ // LEFT — STATE column (input or key level · reduction)
+ // ======================================================================
+ var stateTitle = Caps("STATE"); stateTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var inPill = new ShPill { Ink = Brass, VerticalAlignment = VerticalAlignment.Stretch };
+ var grPill = new ShPill { Ink = Teal, FromTop = true, VerticalAlignment = VerticalAlignment.Stretch };
+ var inLbl = Caps("IN"); inLbl.HorizontalAlignment = HorizontalAlignment.Center;
+ var grLbl = Caps("GR"); grLbl.HorizontalAlignment = HorizontalAlignment.Center;
+ ToolTip.SetTip(inPill, "The level the detector compares — this track's input, or the key when an external sidechain drives it; the dashed tick is the threshold");
+ ToolTip.SetTip(grPill, "Gain reduction — how far the gate has turned the signal down now");
+ var stateIn = Mono("", 7, AccentBright); stateIn.HorizontalAlignment = HorizontalAlignment.Center;
+ var stateGr = Mono("", 7, TextPrimary); stateGr.HorizontalAlignment = HorizontalAlignment.Center;
+ static double Norm60(double db) => Math.Clamp((db + 60) / 60, 0, 1);
readouts.Add(() =>
{
- int n = engine.DeviceScope(track, di, scope, kScope);
- if (n < kScope) return;
- bool open = scope[S_Open] >= 0.5f && scope[S_GateGain] > 0.5f;
- state.Text = open ? "OPEN" : "SHUT"; state.Foreground = open ? Green : NotaPalette.TextSecondary;
- stateSub.Text = $"gate · GR {scope[S_GrDb]:0.0}\u2009dB";
- led.Background = open ? Green : Dim; ledTxt.Text = open ? "OPEN" : "SHUT"; ledTxt.Foreground = open ? Green : MutedC;
- duty.Text = $"{scope[S_GateGain] * 100:0}\u2009% open";
- double inW = inTrk.Bounds.Width, grW = grTrk.Bounds.Width;
- inFill.Width = Math.Clamp((scope[S_InDb] + 60) / 60, 0, 1) * inW;
- inVal.Text = $"{scope[S_InDb]:0.0}";
- double tf = Math.Clamp((ThrDb() + 60) / 60, 0, 1);
- inTick.IsVisible = true; inTick.Margin = new Thickness(tf * inW, 0, 0, 0);
- grFill.Width = Math.Clamp(scope[S_GrDb] / 60, 0, 1) * grW;
- grVal.Text = scope[S_GrDb] > 59 ? "−∞" : $"{-scope[S_GrDb]:0.0}";
+ bool ext = Sc(S_ExtKey) > 0.5;
+ double lvl = ext ? Sc(S_KeyDb) : Sc(S_InDb);
+ inLbl.Text = ext ? "SC" : "IN";
+ inPill.Set(Norm60(lvl), Norm60(ThrDb()));
+ grPill.Set(Math.Clamp(Sc(S_GrDb) / 60, 0, 1), double.NaN);
+ stateIn.Text = lvl <= -119 ? "−∞" : NotaNum.F($"{lvl:0.0}");
+ stateGr.Text = Sc(S_GrDb) < 0.05 ? "0.0\u2009dB" : Sc(S_GrDb) > 99 ? "−∞\u2009dB" : NotaNum.F($"−{Sc(S_GrDb):0.0}\u2009dB");
+ stateTitle.Foreground = State() is 1 or 2 or 3 ? AccentBright : TextTertiary; // lit while the gate is open
});
+ Control PillCol(ShPill pill, TextBlock lbl) => new DockPanel { Children = { Docked(lbl, Dock.Bottom), new Border { Margin = new Thickness(0, 0, 0, 3), Child = pill } } };
+ var pills = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 9, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 4) };
+ pills.Children.Add(PillCol(inPill, inLbl));
+ pills.Children.Add(Col(PillCol(grPill, grLbl), 1));
+ var stateCol = new Border
+ {
+ Width = 56, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(stateTitle, Dock.Top), Docked(stateGr, Dock.Bottom), Docked(stateIn, Dock.Bottom), pills } },
+ };
+ DockPanel.SetDock(stateCol, Dock.Left);
- void RefreshAll() { foreach (var a in readouts) a(); }
- SyncLines();
- RefreshAll();
- return root;
- }
+ // ======================================================================
+ // CENTRE — Signal
+ // ======================================================================
+ ShSignalView? signal = null;
+ Control SignalTab()
+ {
+ signal = new ShSignalView();
+ WireDrag(signal, h => h == ShSignalView.HThreshold ? Threshold : Return);
+ ToolTip.SetTip(signal, "The input (teal) and what passes (brass) over the window, with the threshold (dashed brass) and where the gate closes again (dashed). Drag a line up or down; double-click resets it.");
+ Learn(signal, Threshold);
+
+ var liveBtn = Latch(-1, () => live, () => { live = !live; if (!live) Array.Copy(scope, frozen, kScope); }, () => live ? "Live" : "Frozen",
+ "Live — the graph follows the audio; click to freeze the picture");
+ var ret = Mono("", 7, AccentBright);
+ readouts.Add(() => ret.Text = NotaNum.F($"return {RetDb():0.0}\u2009dB"));
+ var head = HeadRow(Row(6, Caps("MODE"), ModeSeg(), new Border { Width = 2 }, Caps("LOOK"),
+ Seg(Lookahead, new[] { "0", "1", "5\u2009ms" }, "Lookahead — the gate opens this much before the transient arrives (the track is delayed by it)"), liveBtn), ret);
+ var knobs = KnobRow(new[]
+ {
+ K(Threshold, "THRESH", ThrShort),
+ K(Attack, "ATTACK", AtkF),
+ K(Hold, "HOLD", HoldF),
+ K(Release, "RELEASE", RelF),
+ },
+ () => NotaNum.F($"threshold {ThrDb():0.0}\u2009dB · return {RetDb():0.0}\u2009dB"),
+ () => NotaNum.F($"{(Duck() ? "ducked" : "open")} {Sc(S_OpenRatio) * 100:0}\u2009% of window · {GrText()}"));
+ return TabBody(head, signal, knobs);
+ }
- private static Control WithDock(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
- private static Control WithCol(Control c, int col) { Grid.SetColumn(c, col); return c; }
+ // ======================================================================
+ // CENTRE — Envelope
+ // ======================================================================
+ ShEnvelopeView? envView = null;
+ Control EnvelopeTab()
+ {
+ envView = new ShEnvelopeView();
+ WireDrag(envView, h => h switch { ShEnvelopeView.HAttack => Attack, ShEnvelopeView.HHold => Hold, ShEnvelopeView.HRelease => Release, _ => Floor });
+ ToolTip.SetTip(envView, "One opening: attack, hold, release in the chosen shape, down to the floor (inverted for Duck). Drag a node sideways for its time, the teal floor up or down; double-click resets.");
+ Learn(envView, Release);
- // Small teal toggle with a state getter/setter, registered to the refresher list.
- private static Control MakeToggle(Func<bool> get, Action<bool> set, string label, List<Action> readouts)
- {
- var b = DeviceCardKit.Switch(label, get, () => set(!get()), out var sync);
- readouts.Add(sync);
- return b;
- }
-}
+ var shapes = Chips(Shapes, i => Sel(Shape, 3) == i, i => SetP(Shape, i / 2f), Shape,
+ "Shape — Linear: straight ramps over the times; Log: the classic one-pole curve; Snap: stays open, then shuts hard");
+ var retrig = ToggleLatch(Retrigger, "Retrig", "Retrigger — trigger mode: each hit fires one attack → hold → release, however long the signal stays above the threshold");
+ var times = Mono("", 7, AccentBright);
+ readouts.Add(() => times.Text = Times());
+ var head = HeadRow(Row(6, Caps("SHAPE"), shapes, new Border { Width = 2 }, ModeSeg(), retrig), times);
+ var knobs = KnobRow(new[]
+ {
+ K(Attack, "ATTACK", AtkF),
+ K(Hold, "HOLD", HoldF),
+ K(Release, "RELEASE", RelF),
+ K(Floor, "FLOOR", FloorF, Teal, tip: "Floor — the level when closed (−∞ = silence); in Duck, how far the signal goes down"),
+ },
+ () => P(Floor) <= 0.001f ? (Duck() ? "ducks to silence" : "closes to silence") : NotaNum.F($"floor {FloorDb():0.0}\u2009dB instead of silence"),
+ () => NotaNum.F($"openings {Sc(S_TrigPerBar):0} / bar · {GrText()}"));
+ return TabBody(head, envView, knobs);
+ }
-internal static class ShutterExt
-{
- public static TextBlock Track(this TextBlock t, System.Collections.Generic.List<Action> readouts, Action<TextBlock> upd) { readouts.Add(() => upd(t)); return t; }
+ // ======================================================================
+ // CENTRE — Sidechain
+ // ======================================================================
+ ShKeyView? keyView = null;
+ Control SidechainTab()
+ {
+ keyView = new ShKeyView();
+ WireDrag(keyView, h => h == ShKeyView.HHp ? DetHP : DetLP);
+ ToolTip.SetTip(keyView, "The detector's band-pass (teal) — only this part of the key opens the gate — over the reduction in the window (brass). Drag the nodes sideways; double-click resets.");
+ Learn(keyView, DetHP);
+
+ var eq = Latch(DetFilter, () => On(DetFilter), () => SetP(DetFilter, On(DetFilter) ? 0f : 1f), () => On(DetFilter) ? "SC EQ on" : "SC EQ off",
+ "SC EQ — the detector hears the key through its band-pass; off = the full band");
+ var look = Mono("", 7, AccentBright);
+ readouts.Add(() => look.Text = NotaNum.F($"look {LookMs()}\u2009ms"));
+ var head = HeadRow(Row(6, Caps("KEY"), KeyDrop(false), ModeSeg(), ListenLatch(), eq), look);
+ var knobs = KnobRow(new[]
+ {
+ K(Threshold, "THRESH", ThrShort),
+ K(Floor, "RANGE", FloorF, tip: "Range — how far the gate closes or the duck goes down (−∞ = all the way)"),
+ K(Return, "RETURN", RetF, Teal, tip: "Return — how far under the threshold the key must fall before the gate closes (stops chatter)"),
+ K(Lookahead, "LOOK", LookF, Teal, steps: 3, tip: "Lookahead — 0, 1 or 5\u2009ms"),
+ },
+ () => NotaNum.F($"key {KeyName()} · {(On(DetFilter) ? "fires on " + HpF(P(DetHP)) + "…" + LpF(P(DetLP)) : "full band")}"),
+ () => NotaNum.F($"{(Duck() ? "ducks" : "closes")} to {(P(Floor) <= 0.001f ? "−∞\u2009dB" : NotaNum.F($"{FloorDb():0.0}\u2009dB"))} · {GrText()}"));
+ return TabBody(head, keyView, knobs);
+ }
+
+ // ======================================================================
+ // RIGHT — Detector / Meters
+ // ======================================================================
+ static Control LabelRow(string label, Control c, double labW = 40)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(NotaNum.F($"{labW},*")) };
+ g.Children.Add(new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center });
+ g.Children.Add(Col(c, 1));
+ return g;
+ }
+ 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 StateBox()
+ {
+ var t = Caps("STATE");
+ 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 b = 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(() =>
+ {
+ int st = State();
+ bool moving = st is 1 or 3 or 4;
+ string name = Duck() ? st switch { 2 => "ducking", 0 => "clear", _ => StateNames[st] } : StateNames[st];
+ l1.Text = NotaNum.F($"{name} · {Sc(S_GateGain) * 100:0}\u2009%");
+ l2.Text = P(Floor) > 0.001f && st == 0 ? NotaNum.F($"{GrText()} · floor {FloorDb():0.0}") : NotaNum.F($"{GrText()} · look {LookMs()}\u2009ms");
+ dot.Background = st == 2 ? Success : moving ? Brass : NotaPalette.BorderStrong;
+ l1.Foreground = moving ? AccentBright : TextPrimary;
+ b.BorderBrush = moving ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
+ t.Foreground = moving ? AccentBright : TextTertiary;
+ });
+ ToolTip.SetTip(b, "What the gate is doing now — closed, attack, open, hold or release — and its gain");
+ return b;
+ }
+
+ Control DetectorTab()
+ {
+ var floor = SliderRow("FLOOR", Floor, FloorShort, modulation: true);
+ return Spread(
+ LabelRow("SOURCE", KeyDrop(true)),
+ SliderRow("THRESH", Threshold, ThrShort),
+ SliderRow("RETURN", Return, RetShort),
+ new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = floor },
+ StateBox(),
+ new StackPanel { Spacing = 5, Children = {
+ ExtSwitch(),
+ Toggle(DetFilter, "Detector filter", "Detector filter — the key goes through the band-pass (Sidechain tab) before the detector"),
+ Toggle(PeakHold, "Peak hold", "Peak hold — the detector holds each peak longer, so low notes and slow waves don't chatter the gate") } });
+ }
+
+ Control MetersTab()
+ {
+ Control Line(Func<string> k, Func<string> v, IBrush? ink = null)
+ {
+ var key = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
+ var val = Mono("", 8, ink ?? TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => { key.Text = k(); val.Text = v(); });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ g.Children.Add(key);
+ g.Children.Add(Col(val, 1));
+ return g;
+ }
+ 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 = 2, Children = {
+ Caps("MEASUREMENTS"),
+ Line(() => Sc(S_ExtKey) > 0.5 ? "sc in" : "in", () => DbF(Sc(S_ExtKey) > 0.5 ? Sc(S_KeyDb) : Sc(S_InDb))),
+ Line(() => "out", () => DbF(Sc(S_OutDb))),
+ Line(() => "GR · peak", () => NotaNum.F($"{(Sc(S_GrDb) < 0.05 ? "0.0" : Sc(S_GrDb) > 99 ? "−∞" : NotaNum.F($"−{Sc(S_GrDb):0.0}"))} · {(Sc(S_PeakGrDb) < 0.05 ? "0.0" : Sc(S_PeakGrDb) > 99 ? "−∞" : NotaNum.F($"−{Sc(S_PeakGrDb):0.0}"))}\u2009dB"), AccentBright) } },
+ };
+ var sliders = new StackPanel { Spacing = 6, Children = {
+ SliderRow("SC HP", DetHP, HpF, modulation: true),
+ SliderRow("SC LP", DetLP, LpF, modulation: true),
+ SliderRow("RANGE", Floor, FloorShort) } };
+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };
+ btns.Children.Add(ListenLatch(fill: true));
+ btns.Children.Add(Col(Latch(-1, () => false, () => engine.DeviceAction(track, di, A_ResetMeters, 0, 0), () => "Reset",
+ "Reset — clear the peak reduction, the opening count and the history", fill: true), 1));
+ var body = new DockPanel { LastChildFill = false, Children = {
+ Docked(box, Dock.Top),
+ Docked(new Border { Margin = new Thickness(0, 6, 0, 0), Child = sliders }, Dock.Top),
+ Docked(new StackPanel { Spacing = 5, Children = {
+ ExtSwitch(),
+ Toggle(DetFilter, "Detector filter", "Detector filter — the key goes through the band-pass before the detector") } }, Dock.Bottom),
+ Docked(new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 5), Child = btns }, Dock.Bottom) } };
+ return new Border { Padding = new Thickness(8, 6), Child = body };
+ }
+
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ int centreTab = 0;
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[3];
+ var rightBodies = new Control?[2];
+ var extras = Mono("", 7, TextTertiary);
+ var extrasHost = new Border { Background = Brushes.Transparent, Child = extras, VerticalAlignment = VerticalAlignment.Stretch };
+ extrasHost.PointerPressed += (_, e) =>
+ {
+ if (centreTab != 0 || !e.GetCurrentPoint(extrasHost).Properties.IsLeftButtonPressed) return;
+ engine.DeviceAction(track, di, A_Window, (WindowIdx() + 1) % 3, 0);
+ e.Handled = true;
+ };
+ readouts.Add(() =>
+ {
+ extras.Text = centreTab switch
+ {
+ 1 => NotaNum.F($"one opening · {MsN(AtkMs() + HoldMs() + RelMs())}\u2009ms"),
+ 2 => NotaNum.F($"key: {KeyName()} · {(On(DetFilter) ? "filter " + HpF(P(DetHP)) + "…" + LpF(P(DetLP)) : "full band")}"),
+ _ => NotaNum.F($"window {WindowText()} · look {LookMs()}\u2009ms"),
+ };
+ extrasHost.Cursor = centreTab == 0 ? new Cursor(StandardCursorType.Hand) : Cursor.Default;
+ });
+ ToolTip.SetTip(extrasHost, "Signal tab: click to change the window — " + string.Join(" · ", WindowNames));
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => EnvelopeTab(), 2 => SidechainTab(), _ => SignalTab() };
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? MetersTab() : DetectorTab();
+
+ var centre = TabFrame(new[] { "Signal", "Envelope", "Sidechain" }, centreHost, CentreBody, false, t => { centreTab = t; Refresh(); }, extrasHost);
+ var rightFrame = TabFrame(new[] { "Detector", "Meters" }, rightHost, RightBody, true, _ => RefreshAll(), null);
+ var right = new Border { Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Margin = new Thickness(5, 0), ClipToBounds = true, Child = centre };
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ string floor = P(Floor) <= 0.001f ? "−∞" : NotaNum.F($"{FloorDb():0.0}\u2009dB");
+ var parts = new List<string> { Duck() ? "Duck" : "Gate" };
+ switch (centreTab)
+ {
+ case 1:
+ parts.Add(Shapes[Sel(Shape, 3)].ToLowerInvariant());
+ parts.Add(Times());
+ parts.Add("floor " + floor);
+ parts.Add(NotaNum.F($"threshold {ThrDb():0.0}"));
+ parts.Add(NotaNum.F($"return {RetDb():0.0}"));
+ if (On(Retrigger)) parts.Add("retrigger");
+ break;
+ case 2:
+ parts.Add("key " + KeyName());
+ parts.Add(NotaNum.F($"threshold {ThrDb():0.0}"));
+ parts.Add("range " + floor);
+ parts.Add(On(DetFilter) ? "SC " + HpF(P(DetHP)) + "…" + LpF(P(DetLP)) : "SC full band");
+ parts.Add(NotaNum.F($"look {LookMs()}\u2009ms"));
+ if (On(Listen)) parts.Add("listening");
+ break;
+ default:
+ parts.Add(NotaNum.F($"threshold {ThrDb():0.0}\u2009dB"));
+ parts.Add(NotaNum.F($"return {RetDb():0.0}"));
+ parts.Add(Times());
+ parts.Add("floor " + floor);
+ parts.Add(NotaNum.F($"look {LookMs()}\u2009ms"));
+ if (ExtOn()) parts.Add("key " + KeyName());
+ break;
+ }
+ if (On(PeakHold) && centreTab != 1) parts.Add("peak hold");
+ return string.Join(" · ", parts);
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#}\u2009kHz · latency {Sc(S_Latency):0}\u2009smp · CPU {Sc(S_Cpu) * 100:0.0}\u2009%") : "";
+ });
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft);
+ statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { stateCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, kScope);
+ int n = scN >= kScope ? Math.Clamp((int)Sc(S_HistN), 0, kHist) : 0;
+ var h = Hist();
+ if (centreTab == 0 && signal is not null)
+ signal.Set(h, H_In, H_Gate, n, ThrDb(), ThrDb() - RetDb(), Duck(), WindowText());
+ if (centreTab == 1 && envView is not null)
+ envView.Set(AtkMs(), HoldMs(), RelMs(), FloorLin(), Sel(Shape, 3), Duck(), On(Retrigger),
+ P(Floor) <= 0.001f ? "−∞\u2009dB" : NotaNum.F($"{FloorDb():0.0}\u2009dB"), MsN(AtkMs()), MsN(HoldMs()), MsF(RelMs()));
+ if (centreTab == 2 && keyView is not null)
+ keyView.Set(Exp(P(DetHP), 20, 2000), Exp(P(DetLP), 200, 20000), On(DetFilter), h, H_Gate, n, Duck() ? "duck" : "reduction");
+ RefreshAll();
+ }
+ // Graphs follow the params every tick, also while dragged (the envelope keeps its time span then).
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
+
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = 0;
+ var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? Card2 : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AccentBright : TextTertiary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ int iv = i;
+ var b = new Border
+ {
+ Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, _) => { 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 818c9599..58bba18c 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -932,14 +932,57 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("autogain", 18, "Fast Leveler", ("Target", 0.611f), ("Scale", 0f), ("Response", 0f), ("Max Gain", 0.5f), ("Safe", 1f));
Fx("autogain", 18, "Match Reference", ("Scale", 1f), ("Response", 1f), ("Window", 0.84f), ("Max Gain", 0.75f), ("Safe", 1f));
- // ---- Nota Shutter (kind 19) — noise gate, all params normalized 0..1. Threshold
- // 0..1 → −70..0 dB; Return 0..1 → 0..24 dB; Floor 0 = mute; Lookahead 0/0.5/1 = 0/1/5 ms.
- Fx("shutter", 19, "Tight Drums", ("Threshold", 0.457f), ("Return", 0.125f), ("Attack", 0.175f), ("Hold", 0.588f), ("Release", 0.63f), ("Floor", 0f));
- Fx("shutter", 19, "Gentle Cleanup", ("Threshold", 0.34f), ("Return", 0.25f), ("Attack", 0.4f), ("Hold", 0.7f), ("Release", 0.8f), ("Floor", 0.4f));
- Fx("shutter", 19, "Vocal Gate", ("Threshold", 0.5f), ("Return", 0.3f), ("Attack", 0.3f), ("Hold", 0.75f), ("Release", 0.72f), ("Floor", 0.3f), ("Det HP", 0.45f));
- Fx("shutter", 19, "Hard Slice", ("Threshold", 0.6f), ("Return", 0.1f), ("Attack", 0.05f), ("Hold", 0.3f), ("Release", 0.3f), ("Floor", 0f));
- Fx("shutter", 19, "Kick Duck", ("Threshold", 0.42f), ("Flip", 1f), ("Attack", 0.2f), ("Hold", 0.5f), ("Release", 0.55f), ("Floor", 0.55f));
- Fx("shutter", 19, "Trance Gate", ("Threshold", 0.55f), ("Return", 0.08f), ("Attack", 0.15f), ("Hold", 0.45f), ("Release", 0.4f), ("Floor", 0f), ("Lookahead", 1f));
+ // ---- Nota Shutter (kind 19) — noise gate / ducker, all params normalized 0..1 (unnamed ones
+ // reset to their defaults). Threshold −70 + 70v dB (.286 = −50, .357 = −45, .4 = −42,
+ // .457 = −38, .5 = −35, .543 = −32, .571 = −30, .6 = −28, .629 = −26, .714 = −20);
+ // Return 24v dB (.042 = 1, .083 = 2, .125 = 3, .167 = 4, .229 = 5.5, .25 = 6, .333 = 8,
+ // .417 = 10); Attack 0.01·10000^v ms (.075 = 0.02, .175 = 0.05, .25 = 0.1, .425 = 0.5,
+ // .5 = 1, .52 = 1.2, .575 = 2, .675 = 5, .75 = 10, .825 = 20, .869 = 30); Hold 0.1·5000^v
+ // ms (.27 = 1, .459 = 5, .541 = 10, .588 = 15, .622 = 20, .67 = 30, .704 = 40, .73 = 50,
+ // .785 = 80, .811 = 100, .859 = 150, .892 = 200, .94 = 300); Release 2000^v ms (.303 = 10,
+ // .394 = 20, .447 = 30, .515 = 50, .576 = 80, .606 = 100, .63 = 120, .659 = 150, .697 =
+ // 200, .721 = 240, .75 = 300, .788 = 400, .818 = 500, .879 = 800, .909 = 1000); Floor 0 =
+ // −∞, else −70 + 70v dB (.429 = −40, .543 = −32, .571 = −30, .657 = −24, .714 = −20,
+ // .743 = −18, .786 = −15, .829 = −12, .857 = −10, .886 = −8); Lookahead 0/.5/1 = 0/1/5 ms;
+ // Flip 1 = Duck; Det HP 20·100^v Hz (.088 = 30, .151 = 40, .239 = 60, .301 = 80, .349 =
+ // 100, .438 = 150, .588 = 300, 1 = 2 k); Det LP 200·100^v Hz (.088 = 300, .301 = 800,
+ // .438 = 1.5 k, .548 = 2.5 k, .651 = 4 k, .699 = 5 k, .801 = 8 k, .952 = 16 k); Shape
+ // 0 Linear/.5 Log/1 Snap; toggles 1 = on (Det Filter and External Key default on).
+ Fx("shutter", 19, "Init", ("Threshold", 0.457f));
+ // Drums
+ Fx("shutter", 19, "Tight Drums", ("Threshold", 0.457f), ("Return", 0.125f), ("Attack", 0.175f), ("Hold", 0.588f), ("Release", 0.63f), ("Floor", 0f));
+ Fx("shutter", 19, "Kick Gate", ("Threshold", 0.571f), ("Return", 0.167f), ("Attack", 0.175f), ("Hold", 0.67f), ("Release", 0.576f), ("Det HP", 0.088f), ("Det LP", 0.088f), ("Peak Hold", 1f));
+ Fx("shutter", 19, "Snare Gate", ("Threshold", 0.6f), ("Return", 0.208f), ("Attack", 0.25f), ("Hold", 0.704f), ("Release", 0.659f), ("Floor", 0.657f), ("Det HP", 0.438f), ("Det LP", 0.699f));
+ Fx("shutter", 19, "Tom Gate", ("Threshold", 0.4f), ("Return", 0.229f), ("Attack", 0.52f), ("Hold", 0.704f), ("Release", 0.721f), ("Floor", 0.743f), ("Shape", 0f), ("Peak Hold", 1f), ("Det HP", 0.239f), ("Det LP", 0.438f));
+ Fx("shutter", 19, "Hi-Hat Cleanup", ("Threshold", 0.5f), ("Return", 0.125f), ("Attack", 0.175f), ("Hold", 0.459f), ("Release", 0.447f), ("Floor", 0.714f), ("Det HP", 1f), ("Det LP", 0.952f));
+ Fx("shutter", 19, "Overhead Tamer", ("Threshold", 0.357f), ("Return", 0.25f), ("Attack", 0.5f), ("Hold", 0.73f), ("Release", 0.788f), ("Floor", 0.829f));
+ Fx("shutter", 19, "Room Mic Gate", ("Threshold", 0.429f), ("Return", 0.25f), ("Attack", 0.575f), ("Hold", 0.785f), ("Release", 0.818f), ("Floor", 0.786f));
+ Fx("shutter", 19, "Hard Slice", ("Threshold", 0.6f), ("Return", 0.1f), ("Attack", 0.05f), ("Hold", 0.3f), ("Release", 0.3f), ("Floor", 0f));
+ Fx("shutter", 19, "Gated Reverb", ("Threshold", 0.571f), ("Return", 0.083f), ("Attack", 0.175f), ("Hold", 0.892f), ("Release", 0.394f), ("Floor", 0f), ("Shape", 1f), ("Retrigger", 1f));
+ Fx("shutter", 19, "Drum Trigger", ("Threshold", 0.543f), ("Return", 0.125f), ("Attack", 0.075f), ("Hold", 0.622f), ("Release", 0.515f), ("Floor", 0f), ("Shape", 1f), ("Retrigger", 1f));
+ // Voice
+ Fx("shutter", 19, "Vocal Gate", ("Threshold", 0.5f), ("Return", 0.3f), ("Attack", 0.3f), ("Hold", 0.75f), ("Release", 0.72f), ("Floor", 0.3f), ("Det HP", 0.45f));
+ Fx("shutter", 19, "Gentle Cleanup", ("Threshold", 0.34f), ("Return", 0.25f), ("Attack", 0.4f), ("Hold", 0.7f), ("Release", 0.8f), ("Floor", 0.4f));
+ Fx("shutter", 19, "Podcast Voice", ("Threshold", 0.286f), ("Return", 0.333f), ("Attack", 0.675f), ("Hold", 0.859f), ("Release", 0.75f), ("Floor", 0.829f), ("Det HP", 0.349f), ("Det LP", 0.801f));
+ Fx("shutter", 19, "Breath Softener", ("Threshold", 0.5f), ("Return", 0.25f), ("Attack", 0.575f), ("Hold", 0.73f), ("Release", 0.659f), ("Floor", 0.886f), ("Det HP", 0.588f), ("Det LP", 0.651f));
+ Fx("shutter", 19, "Dialogue Room Tone", ("Threshold", 0.357f), ("Return", 0.333f), ("Attack", 0.675f), ("Hold", 0.892f), ("Release", 0.818f), ("Floor", 0.857f), ("Det HP", 0.349f), ("Det LP", 0.699f));
+ Fx("shutter", 19, "Soft Expander", ("Threshold", 0.429f), ("Return", 0.417f), ("Attack", 0.5f), ("Hold", 0.73f), ("Release", 0.75f), ("Floor", 0.857f), ("Det Filter", 0f));
+ // Instruments
+ Fx("shutter", 19, "Guitar Noise Gate", ("Threshold", 0.214f), ("Return", 0.25f), ("Attack", 0.25f), ("Hold", 0.622f), ("Release", 0.606f), ("Floor", 0f), ("Det LP", 0.651f), ("Peak Hold", 1f));
+ Fx("shutter", 19, "High-Gain Chug", ("Threshold", 0.357f), ("Return", 0.125f), ("Attack", 0.175f), ("Hold", 0.459f), ("Release", 0.394f), ("Floor", 0f), ("Lookahead", 1f), ("Shape", 1f), ("Peak Hold", 1f));
+ Fx("shutter", 19, "Bass DI Gate", ("Threshold", 0.286f), ("Return", 0.25f), ("Attack", 0.425f), ("Hold", 0.67f), ("Release", 0.63f), ("Floor", 0.571f), ("Det HP", 0.088f), ("Det LP", 0.301f), ("Peak Hold", 1f));
+ Fx("shutter", 19, "Pad Tail Cut", ("Threshold", 0.314f), ("Return", 0.167f), ("Attack", 0.75f), ("Hold", 0.811f), ("Release", 0.879f), ("Floor", 0.429f), ("Det Filter", 0f));
+ // Rhythmic · creative
+ Fx("shutter", 19, "Trance Gate", ("Threshold", 0.55f), ("Return", 0.08f), ("Attack", 0.15f), ("Hold", 0.45f), ("Release", 0.4f), ("Floor", 0f), ("Lookahead", 1f));
+ Fx("shutter", 19, "Stutter Chop", ("Threshold", 0.714f), ("Return", 0.042f), ("Attack", 0.175f), ("Hold", 0.27f), ("Release", 0.303f), ("Floor", 0f), ("Shape", 1f), ("Retrigger", 1f));
+ Fx("shutter", 19, "Soft Pulse", ("Threshold", 0.571f), ("Return", 0.125f), ("Attack", 0.825f), ("Hold", 0.541f), ("Release", 0.697f), ("Floor", 0.657f));
+ Fx("shutter", 19, "Reverse Swell", ("Threshold", 0.571f), ("Flip", 1f), ("Attack", 0.869f), ("Hold", 0.73f), ("Release", 0.909f), ("Floor", 0.429f), ("Shape", 0f));
+ // Ducking — route a key in the Sidechain tab
+ Fx("shutter", 19, "Kick Duck", ("Threshold", 0.42f), ("Flip", 1f), ("Attack", 0.2f), ("Hold", 0.5f), ("Release", 0.55f), ("Floor", 0.55f));
+ Fx("shutter", 19, "Sidechain Pump", ("Threshold", 0.629f), ("Return", 0.25f), ("Flip", 1f), ("Attack", 0.5f), ("Hold", 0.541f), ("Release", 0.721f), ("Floor", 0.543f), ("Lookahead", 1f));
+ Fx("shutter", 19, "Bass Under Kick", ("Threshold", 0.571f), ("Flip", 1f), ("Attack", 0.425f), ("Hold", 0.622f), ("Release", 0.63f), ("Floor", 0.857f), ("Det HP", 0.088f), ("Det LP", 0.088f));
+ Fx("shutter", 19, "Voice-Over Duck", ("Threshold", 0.429f), ("Return", 0.25f), ("Flip", 1f), ("Attack", 0.75f), ("Hold", 0.94f), ("Release", 0.879f), ("Floor", 0.829f), ("Det HP", 0.438f), ("Det LP", 0.651f));
+ Fx("shutter", 19, "Key Tuning (Listen)", ("Threshold", 0.457f), ("Listen", 1f), ("Det HP", 0.349f), ("Det LP", 0.349f));
// ---- Nota Chamber (kind 20) — hybrid reverb, all params normalized 0..1 (unnamed params
// reset to their defaults). IR = index/16 (0 Concert Hall · .0625 Stone Vault · .125
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 9f2c5b4c..930be03d 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -67,21 +67,21 @@ 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.")]
+ [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.")]
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). 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). Devices without a command ignore the call.")]
public Task DeviceAction(int trackId, int deviceIndex, [Description("Command id — see the device's list in this description")] int id,
int intArg = 0, float floatArg = 0) => Mutate(() => E.DeviceAction(trackId, deviceIndex, id, intArg, floatArg));
public sealed record Sidechain(bool Accepts, int SourceTrackId, bool TapPre, float GainDb, float Mix);
- [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1).")]
+ [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, Nota Shutter and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1).")]
public Task<Sidechain> GetDeviceSidechain(int trackId, int deviceIndex) => Read(() => new Sidechain(
E.DeviceAcceptsSidechain(trackId, deviceIndex), E.DeviceSidechainSource(trackId, deviceIndex),
E.DeviceSidechainTapPre(trackId, deviceIndex), E.DeviceSidechainGain(trackId, deviceIndex), E.DeviceSidechainMix(trackId, deviceIndex)));
- [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain.")]
+ [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). Nota Shutter (kind 19) gates or ducks against a key the same way (Flip = 1 for Duck; Det HP / Det LP shape the key; External Key on, its default). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain.")]
public Task SetDeviceSidechain(int trackId, int deviceIndex, [Description("Key source track id, or -1 for none")] int sourceTrackId,
bool? tapPre = null, float? gainDb = null) => Mutate(() =>
{
@@ -284,6 +284,46 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
outBands.ToArray(), V(3));
});
+ public sealed record ShutterPoint(double Ms, double InputDb, double Gain);
+ public sealed record ShutterReading(string Summary, string Live, string Mode, string State, double Gain, double ReductionDb,
+ double PeakReductionDb, double InputDb, double OutputDb, double DetectorDb, double KeyDb, bool ExternalKey, int KeySourceTrackId,
+ double ThresholdDb, double CloseDb, double FloorDb, double OpenShare, double WindowSeconds, int OpeningsLastBar, int OpeningsSinceReset,
+ int LatencySamples, ShutterPoint[] History, double SampleRate);
+
+ [McpServerTool(Name = "read_shutter"), Description(
+ "Read what a Nota Shutter (built-in effect kind 19 — noise gate / ducker) is doing right now: Gate or Duck, its state "
+ + "(closed / attack / open / hold / release), the gain it applies (0..1) and the reduction now and at its deepest since the "
+ + "last reset (dB, positive), the input, output, detector (filtered key) and key levels (dBFS, −120 = silence), whether an "
+ + "external sidechain drives it and the source track, the threshold, the level it closes at (threshold − return) and the "
+ + "floor (−120 = −∞), the share of the window it was open (ducking, for Duck), the openings in the last bar and since the "
+ + "reset, the look-ahead latency, and the window's history in 16 steps (ms before now, input peak dB, lowest gain). Levels "
+ + "move only while audio plays through the track. Use get_device_text id 2 for what each parameter value means, "
+ + "set_device_sidechain to route a key (External Key must be on, its default), device_action 0 to reset the meters.")]
+ public Task<ShutterReading> ReadShutter(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int tele = 24, hist = 128;
+ var sc = new float[tele + 3 * hist];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ static double R1(double v) => Math.Round(v, 1);
+ string[] states = { "closed", "attack", "open", "hold", "release" };
+ bool duck = E.DeviceGetParam(trackId, deviceIndex, 7) >= 0.5f;
+ double win = V(20) > 0 ? V(20) : 1;
+ var pts = new List<ShutterPoint>();
+ if (n >= sc.Length)
+ for (int k = 0; k < 16; k++)
+ {
+ int a = k * hist / 16, b = (k + 1) * hist / 16;
+ double pk = -120, g = 1;
+ for (int i = a; i < b; i++) { pk = Math.Max(pk, sc[tele + i]); g = Math.Min(g, sc[tele + hist + i]); }
+ pts.Add(new ShutterPoint(Math.Round((1 - (double)b / hist) * win * 1000), R1(pk), Math.Round(g, 3)));
+ }
+ return new ShutterReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ duck ? "Duck" : "Gate", states[Math.Clamp((int)Math.Round(V(5)), 0, 4)], Math.Round(V(1), 3), R1(V(2)), R1(V(18)),
+ R1(V(0)), R1(V(6)), R1(V(3)), R1(V(14)), V(13) > 0.5f, E.DeviceSidechainSource(trackId, deviceIndex),
+ R1(V(15)), R1(V(16)), R1(V(17)), Math.Round(V(7), 2), win, (int)V(8), (int)V(9), (int)V(12), pts.ToArray(), V(10));
+ });
+
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/Shutter.h b/src/native/nota.engine/src/Shutter.h
index 1e87e442..b9fac1fc 100644
--- a/src/native/nota.engine/src/Shutter.h
+++ b/src/native/nota.engine/src/Shutter.h
@@ -1,23 +1,41 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Nota Shutter (device kind 19, mockup "Nota Shutter") — a classic noise gate.
+// Nota Shutter (device kind 19, mockup "Nota Shutter") — a noise gate / ducker.
// The "shutter" opens when the detector crosses the Threshold and closes when it falls back
// past the Return (hysteresis, stops chatter); Attack / Hold / Release shape each opening,
-// Floor sets how far the closed signal drops (−∞ = mute, higher = ducking), Lookahead lets
-// the gate open just before a transient, and Flip turns the gate into a ducker. The detector
-// keys off this track or an external sidechain, through its own band-pass (HP/LP) with a
-// Listen monitor. A core Device (JUCE-free); params normalized 0..1, denormalized in
-// process(); persistence / automation / clone flow generically. Telemetry via scopeRead.
+// with a Shape (Linear ramps, Log = the classic one-pole, Snap = stays open then shuts hard),
+// Floor sets how far the closed signal drops (−∞ = mute, higher = a range), Lookahead lets
+// the gate open just before a transient, Flip turns the gate into a ducker and Retrigger
+// makes every hit fire one attack → hold → release envelope (trigger mode). The detector keys
+// off this track or an external sidechain (External Key), through its own 12 dB/oct band-pass
+// (Det Filter) with a Listen monitor, as a fast peak follower or with Peak Hold.
+//
+// key ─▶ [HP ─▶ LP] ─▶ peak follower ─▶ threshold / return / hold ─▶ envelope (shape)
+// in ─▶ look-ahead delay ─────────────────────────────────────────▶ × gain ─▶ out
+//
+// A core Device (JUCE-free), header-only, allocation-free after setSampleRate. Params are
+// normalized 0..1, denormalized in process(); APPEND ONLY (0..10 are the original layout, the
+// appended ones default to the old sound). Persistence / automation / clone flow generically.
+// Telemetry (scopeRead): kTele live values, then three kHist-column histories over the
+// window (input peak dB, gate gain 0..1, detector dB), oldest first.
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = reset the meters (peak GR, triggers, history), 1 = window (iarg 0 250 ms,
+// 1 1 s, 2 4 s).
#pragma once
#include "Device.h"
+#include "TransportInfo.h"
#include <algorithm>
+#include <array>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
#include <vector>
namespace nota {
@@ -30,16 +48,51 @@ public:
Attack, // open time (exp 0.01..100 ms)
Hold, // minimum open time after the detector drops (exp 0.1..500 ms)
Release, // close time (exp 1..2000 ms)
- Floor, // closed level (0..1 → −70..0 dB; 0 = full mute / −∞)
+ Floor, // closed level (0..1 → −70..0 dB; 0 = full mute / −∞) — the "range"
Lookahead, // 0/1/5 ms (discrete)
Flip, // 0 = Gate, 1 = Duck (invert)
DetHP, // detector high-pass (exp 20..2000 Hz)
DetLP, // detector low-pass (exp 200..20000 Hz)
Listen, // >=0.5 monitor the detector (band-passed key) instead of the gated audio
+ // ---- appended (redesign) ----
+ Shape, // 0 Linear / 0.5 Log (one-pole, the old sound) / 1 Snap
+ Retrigger, // >=0.5 trigger mode: each hit fires one attack → hold → release
+ DetFilter, // >=0.5 the detector band-pass is in (off = full-band key)
+ PeakHold, // >=0.5 the detector holds peaks (~40 ms fall instead of 3 ms)
+ ExternalKey, // >=0.5 key off the sidechain source when one is routed
kNumParams
};
- // Packed scope telemetry: instantaneous meters. The UI builds the scrolling SIGNAL graph.
- enum { S_InDb = 0, S_GateGain, S_GrDb, S_DetDb, S_Open, kScope };
+
+ // Telemetry slots (scopeRead). 0..4 keep the original layout.
+ enum {
+ S_InDb = 0, // input level (pre-gate), dBFS
+ S_GateGain, // gate gain now 0..1
+ S_GrDb, // gain reduction now, dB (>= 0)
+ S_DetDb, // detector level (filtered key), dBFS
+ S_Open, // 1 = the detector holds the gate open
+ S_State, // 0 closed, 1 attack, 2 open, 3 hold, 4 release
+ S_OutDb, // output level, dBFS
+ S_OpenRatio, // share of the window the gate was open, 0..1
+ S_TrigPerBar, // openings in the last bar
+ S_Triggers, // openings since the last reset
+ S_SampleRate,
+ S_Cpu, // share of real time spent in process()
+ S_Latency, // look-ahead, samples
+ S_ExtKey, // 1 = an external key is driving the detector
+ S_KeyDb, // key level before the detector filter, dBFS
+ S_ThrDb, // threshold, dBFS
+ S_RetDb, // close level (threshold − return), dBFS
+ S_FloorDb, // floor, dB (−120 = −∞)
+ S_PeakGrDb, // largest reduction since the last reset, dB
+ S_Bpm,
+ S_WindowSec, // history window, seconds
+ S_HistN, // columns per history
+ S_Envelope, // envelope phase 0..1 (1 = fully engaged)
+ kTele = 24
+ };
+ static constexpr int kHist = 128;
+ static constexpr int kHistAt = kTele; // input peak dB · gate gain · detector dB
+ static constexpr int kScope = kTele + 3 * kHist;
Shutter() {
p_[Threshold].store(0.457f); // −38 dB
@@ -53,6 +106,12 @@ public:
p_[DetHP].store(0.301f); // ~80 Hz
p_[DetLP].store(0.548f); // ~2.5 kHz
p_[Listen].store(0.0f);
+ p_[Shape].store(0.5f); // Log — the original one-pole
+ p_[Retrigger].store(0.0f);
+ p_[DetFilter].store(1.0f); // the original always filtered the key
+ p_[PeakHold].store(0.0f);
+ p_[ExternalKey].store(1.0f); // a routed key is used (the original behaviour)
+ for (auto& h : hist_) h.fill(0.0f);
setSampleRate(44100.0, 0);
}
@@ -60,8 +119,8 @@ public:
sr_ = sr > 0 ? sr : 44100.0;
laMax_ = (int)std::lround(sr_ * 0.006) + 2; // up to 5 ms look-ahead
laBuf_.assign((size_t)laMax_ * 2, 0.0f); laW_ = 0;
- detEnv_ = 0.0f; g_ = 1.0f; holdCtr_ = 0; open_ = false;
- dHp_ = dLp_ = 0.0f; inEnv_ = 0.0f;
+ resetState();
+ srA_.store((float)sr_, std::memory_order_relaxed);
}
// Sidechain: external key source (Compressor / Ceiling plumbing).
@@ -70,93 +129,207 @@ public:
void setSidechain(const float* interleaved, int32_t frames) override { scBuf_ = interleaved; scFrames_ = frames; }
bool acceptsSidechain() const override { return true; }
+ void setTransportInfo(const TransportInfo& ti) override {
+ if (ti.bpm > 1.0) bpm_ = ti.bpm;
+ if (ti.tsNum > 0) tsNum_ = ti.tsNum;
+ if (ti.tsDenom > 0) tsDen_ = ti.tsDenom;
+ }
+
// GR (dB, >=0) for the shell titlebar meter, like the Compressor.
float gainReductionDb() const override { return grDb_.load(std::memory_order_relaxed); }
int32_t latencySamples() const override { return laSamples(); }
+ void deviceAction(int32_t id, int32_t iarg, float) override {
+ if (id == A_ResetMeters) resetMetersReq_.store(true, std::memory_order_relaxed);
+ else if (id == A_Window) windowIdx_.store(std::clamp(iarg, 0, 2), std::memory_order_relaxed);
+ }
+
void process(float* buf, int32_t frames) override {
- const float thrLin = dbToLin(-70.0f + get(Threshold) * 70.0f);
- const float retLin = dbToLin(-70.0f + get(Threshold) * 70.0f - get(Return) * 24.0f);
+ const auto t0 = std::chrono::steady_clock::now();
+ if (resetMetersReq_.exchange(false, std::memory_order_relaxed)) {
+ peakGr_ = 0.0f; trigTotal_ = 0; trigN_ = 0;
+ for (auto& h : hist_) h.fill(0.0f);
+ for (int k = 0; k < kHist; ++k) hist_[0][(size_t)k] = -120.0f, hist_[1][(size_t)k] = 1.0f, hist_[2][(size_t)k] = -120.0f;
+ }
+
+ const float thrDb = -70.0f + get(Threshold) * 70.0f;
+ const float thrLin = dbToLin(thrDb);
+ const float retLin = dbToLin(thrDb - get(Return) * 24.0f);
const float atkMs = (float)expMap(get(Attack), 0.01, 100.0);
const float holdMs = (float)expMap(get(Hold), 0.1, 500.0);
const float relMs = (float)expMap(get(Release), 1.0, 2000.0);
const float floorLin = get(Floor) <= 0.001f ? 0.0f : dbToLin(-70.0f + get(Floor) * 70.0f);
const bool flip = get(Flip) >= 0.5f;
const bool listen = get(Listen) >= 0.5f;
+ const bool retrig = get(Retrigger) >= 0.5f;
+ const bool filt = get(DetFilter) >= 0.5f;
+ const int shape = shapeIdx();
const double detHpHz = expMap(get(DetHP), 20.0, 2000.0);
const double detLpHz = expMap(get(DetLP), 200.0, 20000.0);
+ // Envelope steps (coef = the one-pole pole, x + c·(y − x)): Log = one-pole, Linear / Snap = a straight ramp over the time.
const float gAtk = coef(atkMs), gRel = coef(relMs);
- const float dAtk = coef(0.05f), dRel = coef(3.0f); // detector follower (fast)
- const float inRel = coef(80.0f); // input meter envelope
+ const float rAtk = (float)(1.0 / std::max(1.0, atkMs * 0.001 * sr_));
+ const float rRel = (float)(1.0 / std::max(1.0, relMs * 0.001 * sr_));
+ const float dAtk = coef(0.05f), dRel = coef(get(PeakHold) >= 0.5f ? 40.0f : 3.0f); // detector follower
+ const float mRel = coef(80.0f); // level meters
const int holdSamps = std::max(0, (int)std::lround(holdMs * 0.001 * sr_));
- const float hpC = onePole(detHpHz), lpC = onePole(detLpHz);
+ const Svf hpF = svf(detHpHz), lpF = svf(detLpHz);
const int la = laSamples();
- const float* sc = (scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;
+ const bool useExt = get(ExternalKey) >= 0.5f;
+ const float* sc = (useExt && scBuf_ && scFrames_ >= frames) ? scBuf_ : nullptr;
const float scGain = std::pow(10.0f, sidechainGainDb() / 20.0f);
+ static constexpr double kWin[3] = { 0.25, 1.0, 4.0 };
+ const double winSec = kWin[std::clamp(windowIdx_.load(std::memory_order_relaxed), 0, 2)];
+ const int colLen = std::max(1, (int)std::lround(winSec * sr_ / kHist));
+ const float ratioC = coef((float)(winSec * 1000.0));
+
float grMax = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
const float l = buf[i * 2], r = buf[i * 2 + 1];
- // Detector source: external key if routed, else this track.
- float dl = sc ? sc[i * 2] * scGain : l;
- float dr = sc ? sc[i * 2 + 1] * scGain : r;
- float dmono = 0.5f * (dl + dr);
+ // Detector source: external key if routed and enabled, else this track.
+ const float dl = sc ? sc[i * 2] * scGain : l;
+ const float dr = sc ? sc[i * 2 + 1] * scGain : r;
+ const float dmono = 0.5f * (dl + dr);
+ const float akey = std::max(std::fabs(dl), std::fabs(dr));
+ keyEnv_ = akey > keyEnv_ ? akey : akey + mRel * (keyEnv_ - akey);
- // Detector band-pass (one-pole HP then LP), then a fast peak follower.
- dLp_ += (dmono - dLp_) * hpC; // low content
- float hp = dmono - dLp_; // remove below DetHP
- dHp_ += (hp - dHp_) * lpC; // remove above DetLP
- const float det = std::fabs(dHp_);
- if (det > detEnv_) detEnv_ = det + dAtk * (detEnv_ - det);
- else detEnv_ = det + dRel * (detEnv_ - det);
+ // Detector band-pass (12 dB/oct HP then LP), then a fast peak follower.
+ float key = dmono;
+ if (filt) { key = hpF.hp(key, hp_); key = lpF.lp(key, lp_); }
+ const float det = std::fabs(key);
+ detEnv_ = det > detEnv_ ? det + dAtk * (detEnv_ - det) : det + dRel * (detEnv_ - det);
- // Input meter envelope (pre-gate, for the olive graph).
+ // Input meter envelope (pre-gate).
const float ain = std::max(std::fabs(l), std::fabs(r));
- inEnv_ = ain > inEnv_ ? ain : ain + inRel * (inEnv_ - ain);
-
- // Hysteresis + hold state machine.
- if (detEnv_ > thrLin) { open_ = true; holdCtr_ = holdSamps; }
- else if (detEnv_ < retLin) { if (holdCtr_ > 0) --holdCtr_; else open_ = false; }
-
- bool wantOpen = flip ? !open_ : open_;
- const float target = wantOpen ? 1.0f : floorLin;
- g_ += (target - g_) * (target > g_ ? gAtk : gRel);
+ inEnv_ = ain > inEnv_ ? ain : ain + mRel * (inEnv_ - ain);
+
+ // Hysteresis + hold state machine. Retrigger = trigger mode: a crossing (re-armed by
+ // falling under the return) fires one hold, whatever the key does after.
+ const bool above = detEnv_ > thrLin, below = detEnv_ < retLin;
+ if (!retrig) {
+ if (above) { if (!open_) onTrigger(); open_ = true; holdCtr_ = holdSamps; }
+ else if (below) { if (holdCtr_ > 0) --holdCtr_; else open_ = false; }
+ armed_ = true;
+ } else {
+ if (above && armed_) { onTrigger(); open_ = true; holdCtr_ = holdSamps; armed_ = false; }
+ if (below) armed_ = true;
+ if (open_) { if (holdCtr_ > 0) --holdCtr_; else open_ = false; }
+ }
+ ++clock_;
+
+ // Envelope phase: 1 = engaged (gate open / duck down). Attack moves it up, release down.
+ const float tgt = open_ ? 1.0f : 0.0f;
+ if (shape == 1) env_ = tgt + (tgt > env_ ? gAtk : gRel) * (env_ - tgt);
+ else env_ = tgt > env_ ? std::min(tgt, env_ + rAtk) : std::max(tgt, env_ - rRel);
+ const float f = shape == 2 ? 1.0f - (1.0f - env_) * (1.0f - env_) * (1.0f - env_) : env_;
+ g_ = flip ? 1.0f - (1.0f - floorLin) * f : floorLin + (1.0f - floorLin) * f;
// Look-ahead: apply the (anticipating) gain to the delayed audio.
- laBuf_[laW_ * 2] = l; laBuf_[laW_ * 2 + 1] = r;
+ laBuf_[(size_t)laW_ * 2] = l; laBuf_[(size_t)laW_ * 2 + 1] = r;
int rp = laW_ - la; if (rp < 0) rp += laMax_;
- float ol = laBuf_[rp * 2], or_ = laBuf_[rp * 2 + 1];
+ const float ol = laBuf_[(size_t)rp * 2], or_ = laBuf_[(size_t)rp * 2 + 1];
if (++laW_ >= laMax_) laW_ = 0;
- if (listen) { buf[i * 2] = dHp_; buf[i * 2 + 1] = dHp_; }
- else { buf[i * 2] = ol * g_; buf[i * 2 + 1] = or_ * g_; }
+ float yl, yr;
+ if (listen) { yl = yr = key; }
+ else { yl = ol * g_; yr = or_ * g_; }
+ buf[i * 2] = yl; buf[i * 2 + 1] = yr;
+ const float aout = std::max(std::fabs(yl), std::fabs(yr));
+ outEnv_ = aout > outEnv_ ? aout : aout + mRel * (outEnv_ - aout);
const float gr = g_ < 0.999f ? -20.0f * std::log10(std::max(1e-5f, g_)) : 0.0f;
if (gr > grMax) grMax = gr;
+ openRatio_ = (env_ > 0.5f ? 1.0f : 0.0f) + ratioC * (openRatio_ - (env_ > 0.5f ? 1.0f : 0.0f));
+
+ // History column: input peak, the lowest gain, the detector peak.
+ colIn_ = std::max(colIn_, ain); colGate_ = std::min(colGate_, g_); colDet_ = std::max(colDet_, detEnv_);
+ if (++colN_ >= colLen) {
+ const int hw = histW_.load(std::memory_order_relaxed);
+ hist_[0][(size_t)hw] = db(colIn_);
+ hist_[1][(size_t)hw] = colGate_;
+ hist_[2][(size_t)hw] = db(colDet_);
+ histW_.store((hw + 1) % kHist, std::memory_order_release);
+ colIn_ = 0.0f; colGate_ = 1.0f; colDet_ = 0.0f; colN_ = 0;
+ }
}
+ // Openings in the last bar.
+ const double barSamples = (double)tsNum_ * (4.0 / (double)tsDen_) * 60.0 / bpm_ * sr_;
+ int inBar = 0;
+ for (int k = 0; k < trigN_; ++k) if ((double)(clock_ - trigAt_[(size_t)k]) <= barSamples) ++inBar;
+
+ int state;
+ if (open_) state = env_ < 0.99f ? 1 : retrig ? 3 : detEnv_ >= retLin ? 2 : 3;
+ else state = env_ > 0.01f ? 4 : 0;
+ if (grMax > peakGr_) peakGr_ = grMax;
+
// Publish meters.
inDb_.store(db(inEnv_), std::memory_order_relaxed);
+ outDb_.store(db(outEnv_), std::memory_order_relaxed);
+ keyDb_.store(db(keyEnv_), std::memory_order_relaxed);
gateGain_.store(g_, std::memory_order_relaxed);
grDb_.store(grMax, std::memory_order_relaxed);
+ peakGrA_.store(peakGr_, std::memory_order_relaxed);
detDb_.store(db(detEnv_), std::memory_order_relaxed);
openF_.store(open_ ? 1.0f : 0.0f, std::memory_order_relaxed);
+ stateA_.store((float)state, std::memory_order_relaxed);
+ envA_.store(env_, std::memory_order_relaxed);
+ ratioA_.store(openRatio_, std::memory_order_relaxed);
+ trigBarA_.store((float)inBar, std::memory_order_relaxed);
+ trigTotA_.store((float)trigTotal_, std::memory_order_relaxed);
+ extA_.store(sc ? 1.0f : 0.0f, std::memory_order_relaxed);
+ bpmA_.store((float)bpm_, std::memory_order_relaxed);
+ winA_.store((float)winSec, 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);
+ }
}
+ // Telemetry block, then the three histories (oldest first). 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 < kScope) return 0;
- out[S_InDb] = inDb_.load(std::memory_order_relaxed);
- out[S_GateGain] = gateGain_.load(std::memory_order_relaxed);
- out[S_GrDb] = grDb_.load(std::memory_order_relaxed);
- out[S_DetDb] = detDb_.load(std::memory_order_relaxed);
- out[S_Open] = openF_.load(std::memory_order_relaxed);
- return kScope;
+ if (!out || maxSamples <= 0) return 0;
+ float t[kTele] = {};
+ const float thrDb = -70.0f + get(Threshold) * 70.0f;
+ t[S_InDb] = inDb_.load(std::memory_order_relaxed);
+ t[S_GateGain] = gateGain_.load(std::memory_order_relaxed);
+ t[S_GrDb] = grDb_.load(std::memory_order_relaxed);
+ t[S_DetDb] = detDb_.load(std::memory_order_relaxed);
+ t[S_Open] = openF_.load(std::memory_order_relaxed);
+ t[S_State] = stateA_.load(std::memory_order_relaxed);
+ t[S_OutDb] = outDb_.load(std::memory_order_relaxed);
+ t[S_OpenRatio] = ratioA_.load(std::memory_order_relaxed);
+ t[S_TrigPerBar] = trigBarA_.load(std::memory_order_relaxed);
+ t[S_Triggers] = trigTotA_.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)laSamples();
+ t[S_ExtKey] = extA_.load(std::memory_order_relaxed);
+ t[S_KeyDb] = keyDb_.load(std::memory_order_relaxed);
+ t[S_ThrDb] = thrDb;
+ t[S_RetDb] = thrDb - get(Return) * 24.0f;
+ t[S_FloorDb] = get(Floor) <= 0.001f ? -120.0f : -70.0f + get(Floor) * 70.0f;
+ t[S_PeakGrDb] = peakGrA_.load(std::memory_order_relaxed);
+ t[S_Bpm] = bpmA_.load(std::memory_order_relaxed);
+ t[S_WindowSec] = winA_.load(std::memory_order_relaxed);
+ t[S_HistN] = (float)kHist;
+ t[S_Envelope] = envA_.load(std::memory_order_relaxed);
+
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ const int hw = histW_.load(std::memory_order_acquire);
+ for (int s = 0; s < 3; ++s)
+ for (int k = 0; k < kHist && n < maxSamples; ++k) out[n++] = hist_[(size_t)s][(size_t)((hw + k) % kHist)];
+ return n;
}
const char* displayName() const override { return "Nota Shutter"; }
@@ -164,8 +337,9 @@ public:
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
- static const char* nm[] = { "Threshold", "Return", "Attack", "Hold", "Release", "Floor",
- "Lookahead", "Flip", "Det HP", "Det LP", "Listen" };
+ static const char* nm[kNumParams] = { "Threshold", "Return", "Attack", "Hold", "Release", "Floor",
+ "Lookahead", "Flip", "Det HP", "Det LP", "Listen",
+ "Shape", "Retrigger", "Det Filter", "Peak Hold", "External Key" };
return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
float paramMin(int32_t /*i*/) const override { return 0.0f; }
@@ -173,32 +347,145 @@ public:
float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
+ // 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[768];
+ static const char* shapes[3] = { "linear", "log", "snap" };
+ static const char* states[5] = { "closed", "attack", "open", "hold", "release" };
+ const float thr = -70.0f + get(Threshold) * 70.0f;
+ if (id == 0) {
+ const bool ext = get(ExternalKey) >= 0.5f && sidechainSourceTrackId() >= 0;
+ std::string s = get(Flip) >= 0.5f ? "Duck" : "Gate";
+ std::snprintf(b, sizeof b, " - threshold %.1f dB - return %.1f dB - %s %s / %s / %s - %s",
+ thr, get(Return) * 24.0f, shapes[shapeIdx()], msText(expMap(get(Attack), 0.01, 100.0)).c_str(),
+ msText(expMap(get(Hold), 0.1, 500.0)).c_str(), msText(expMap(get(Release), 1.0, 2000.0)).c_str(),
+ get(Floor) <= 0.001f ? "floor -inf" : ("floor " + dbText(-70.0f + get(Floor) * 70.0f)).c_str());
+ s += b;
+ std::snprintf(b, sizeof b, " - look %d ms", kLookMs[lookIdx()]);
+ s += b;
+ if (get(Retrigger) >= 0.5f) s += " - retrigger";
+ s += ext ? " - external key" : " - internal key";
+ if (get(DetFilter) >= 0.5f)
+ s += " - key filter " + hzText(expMap(get(DetHP), 20.0, 2000.0)) + "..." + hzText(expMap(get(DetLP), 200.0, 20000.0));
+ else s += " - key full-band";
+ if (get(PeakHold) >= 0.5f) s += " - peak hold";
+ if (get(Listen) >= 0.5f) s += " - LISTEN (key monitor)";
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ const int st = std::clamp((int)std::lround(sc[S_State]), 0, 4);
+ std::snprintf(b, sizeof b,
+ "%s - gain %.0f %% - GR %.1f dB (peak %.1f dB) - in %.1f dB - out %.1f dB - detector %.1f dB vs threshold %.1f dB - "
+ "open %.0f %% of %.2g s - %.0f openings in the last bar (%.0f since reset) - %s key %.1f dB - latency %.0f smp",
+ states[st], sc[S_GateGain] * 100.0f, sc[S_GrDb], sc[S_PeakGrDb], sc[S_InDb], sc[S_OutDb], sc[S_DetDb], thr,
+ sc[S_OpenRatio] * 100.0f, sc[S_WindowSec], sc[S_TrigPerBar], sc[S_Triggers],
+ sc[S_ExtKey] > 0.5f ? "external" : "internal", sc[S_KeyDb], sc[S_Latency]);
+ return b;
+ }
+ if (id == 2) {
+ return "All params 0..1. Threshold: -70 + 70*v dBFS (0.457 = -38 dB). Return: 24*v dB below the threshold, where the gate "
+ "closes again (hysteresis). Attack 0.01*10000^v ms (0.175 = 0.05 ms, 0.5 = 1 ms). Hold 0.1*5000^v ms (0.588 = 15 ms). "
+ "Release 1*2000^v ms (0.63 = 120 ms). Floor (range): 0 = -inf (mute), else -70 + 70*v dB — the level when closed, "
+ "or how deep Duck goes. Lookahead: 0 = 0 ms, 0.5 = 1 ms, 1 = 5 ms (adds latency). Flip: 0 Gate, 1 Duck. "
+ "Det HP 20*100^v Hz (0.301 = 80 Hz). Det LP 200*100^v Hz (0.548 = 2.5 kHz). Listen: hear the filtered key. "
+ "Shape: 0 Linear (straight ramps), 0.5 Log (one-pole, the classic), 1 Snap (stays open, then shuts hard). "
+ "Retrigger: trigger mode, each hit fires one attack-hold-release. Det Filter: the key band-pass is in. "
+ "Peak Hold: the detector holds peaks (steadier on low notes). External Key: use the routed sidechain source. "
+ "Toggles: >= 0.5 = on.";
+ }
+ return {};
+ }
+
+ enum { A_ResetMeters = 0, A_Window = 1 };
+
private:
static constexpr double kPi = 3.14159265358979323846;
+ static constexpr int kLookMs[3] = { 0, 1, 5 };
+
+ // TPT state-variable filter (Q = 0.707) for the key band-pass.
+ struct Svf {
+ float g = 0.0f, k = 1.41421356f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
+ struct St { float ic1 = 0.0f, ic2 = 0.0f; };
+ float run(float x, St& s, bool high) const {
+ const float v3 = x - s.ic2;
+ const float v1 = a1 * s.ic1 + a2 * v3;
+ const float v2 = s.ic2 + a2 * s.ic1 + a3 * v3;
+ s.ic1 = 2.0f * v1 - s.ic1; s.ic2 = 2.0f * v2 - s.ic2;
+ return high ? x - k * v1 - v2 : v2;
+ }
+ float hp(float x, St& s) const { return run(x, s, true); }
+ float lp(float x, St& s) const { return run(x, s, false); }
+ };
+ Svf svf(double hz) const {
+ Svf f;
+ f.g = (float)std::tan(kPi * std::clamp(hz, 5.0, sr_ * 0.45) / sr_);
+ f.a1 = 1.0f / (1.0f + f.g * (f.g + f.k)); f.a2 = f.g * f.a1; f.a3 = f.g * f.a2;
+ return f;
+ }
+
float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ int shapeIdx() const { return std::clamp((int)std::lround(get(Shape) * 2.0f), 0, 2); }
+ int lookIdx() const { return std::clamp((int)std::lround(get(Lookahead) * 2.0f), 0, 2); }
static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
static float dbToLin(float dbv) { return std::pow(10.0f, dbv / 20.0f); }
- static float db(float lin) { return 20.0f * std::log10(std::max(1e-6f, lin)); }
- float coef(float ms) const { return (float)(1.0 - std::exp(-1.0 / (std::max(0.01f, ms) * 0.001 * sr_))); }
- float onePole(double hz) const { return (float)(1.0 - std::exp(-2.0 * kPi * std::clamp(hz, 5.0, sr_ * 0.45) / sr_)); }
- int laSamples() const {
- static const double ms[3] = { 0.0, 1.0, 5.0 };
- int idx = std::clamp((int)std::lround(get(Lookahead) * 2.0f), 0, 2);
- return std::clamp((int)std::lround(ms[idx] * 0.001 * sr_), 0, laMax_ - 1);
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ float coef(float ms) const { return (float)std::exp(-1.0 / (std::max(0.01f, ms) * 0.001 * sr_)); }
+ int laSamples() const { return std::clamp((int)std::lround(kLookMs[lookIdx()] * 0.001 * sr_), 0, std::max(0, laMax_ - 1)); }
+ static std::string msText(double ms) {
+ char b[32];
+ if (ms >= 100.0) std::snprintf(b, sizeof b, "%.0f ms", ms);
+ else if (ms >= 10.0) std::snprintf(b, sizeof b, "%.1f ms", ms);
+ else std::snprintf(b, sizeof b, "%.2f ms", ms);
+ return b;
+ }
+ static std::string hzText(double hz) {
+ char b[32];
+ if (hz >= 1000.0) std::snprintf(b, sizeof b, "%.1f kHz", hz / 1000.0); else std::snprintf(b, sizeof b, "%.0f Hz", hz);
+ return b;
+ }
+ static std::string dbText(float v) { char b[32]; std::snprintf(b, sizeof b, "%.1f dB", v); return b; }
+
+ void onTrigger() {
+ ++trigTotal_;
+ if (trigN_ < kTrig) trigAt_[(size_t)trigN_++] = clock_;
+ else { for (int k = 1; k < kTrig; ++k) trigAt_[(size_t)k - 1] = trigAt_[(size_t)k]; trigAt_[kTrig - 1] = clock_; }
+ }
+
+ void resetState() {
+ std::fill(laBuf_.begin(), laBuf_.end(), 0.0f); laW_ = 0;
+ detEnv_ = inEnv_ = outEnv_ = keyEnv_ = 0.0f; g_ = 1.0f; env_ = 0.0f;
+ holdCtr_ = 0; open_ = false; armed_ = true;
+ hp_ = {}; lp_ = {};
+ openRatio_ = 0.0f; colIn_ = 0.0f; colGate_ = 1.0f; colDet_ = 0.0f; colN_ = 0;
+ for (int k = 0; k < kHist; ++k) hist_[0][(size_t)k] = -120.0f, hist_[1][(size_t)k] = 1.0f, hist_[2][(size_t)k] = -120.0f;
}
double sr_ = 44100.0;
std::atomic<float> p_[kNumParams] = {};
std::vector<float> laBuf_; int laMax_ = 0, laW_ = 0;
- float detEnv_ = 0.0f, inEnv_ = 0.0f, g_ = 1.0f;
- float dHp_ = 0.0f, dLp_ = 0.0f;
- int holdCtr_ = 0; bool open_ = false;
+ float detEnv_ = 0.0f, inEnv_ = 0.0f, outEnv_ = 0.0f, keyEnv_ = 0.0f, g_ = 1.0f, env_ = 0.0f;
+ Svf::St hp_, lp_;
+ int holdCtr_ = 0; bool open_ = false, armed_ = true;
+ float openRatio_ = 0.0f, peakGr_ = 0.0f;
+ double bpm_ = 120.0; int tsNum_ = 4, tsDen_ = 4;
+ static constexpr int kTrig = 64;
+ std::array<int64_t, kTrig> trigAt_{}; int trigN_ = 0; int64_t clock_ = 0; int64_t trigTotal_ = 0;
+ float colIn_ = 0.0f, colGate_ = 1.0f, colDet_ = 0.0f; int colN_ = 0;
+ std::array<std::array<float, kHist>, 3> hist_{};
+ std::atomic<int> histW_{0};
+ double cpuS_ = 0.0;
std::atomic<int32_t> scTrackId_{-1};
const float* scBuf_ = nullptr; int32_t scFrames_ = 0;
+ std::atomic<bool> resetMetersReq_{false};
+ std::atomic<int> windowIdx_{1};
- std::atomic<float> inDb_{-120.0f}, gateGain_{1.0f}, grDb_{0.0f}, detDb_{-120.0f}, openF_{0.0f};
+ std::atomic<float> inDb_{-120.0f}, outDb_{-120.0f}, keyDb_{-120.0f}, gateGain_{1.0f}, grDb_{0.0f}, peakGrA_{0.0f},
+ detDb_{-120.0f}, openF_{0.0f}, stateA_{0.0f}, envA_{0.0f}, ratioA_{0.0f}, trigBarA_{0.0f}, trigTotA_{0.0f},
+ extA_{0.0f}, bpmA_{120.0f}, winA_{1.0f}, srA_{44100.0f}, cpuA_{0.0f};
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 484fa1b8..8660f9a1 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -3997,74 +3997,222 @@ Console.WriteLine("-- Nota EQ-3 --");
// ============================ Nota Shutter =================================
Console.WriteLine("-- Nota Shutter --");
{
- // Shutter = noise gate (kind 19). Own engine (it silences the signal, which would skew
- // the shared master mix used by later tests).
- using var ge = new NotaEngine();
- ge.SetBpm(120); ge.SetTimeSignature(4, 4);
- int gt = ge.AddInstrumentTrack();
- ge.AddMidiClip(gt, 0.0, 4.0);
- ge.SetClipNotes(gt, 0, new[] { new NotaNote(57, 0.0, 3.5, 0.5f) }); // sustained, moderate level
- int gd = ge.AddBuiltinDevice(gt, 19);
- Check(gd >= 0, "add built-in Nota Shutter");
- Check(ge.DeviceName(gt, gd) == "Nota Shutter", $"name is Nota Shutter (got '{ge.DeviceName(gt, gd)}')");
- Check(ge.TrackDeviceBuiltinKind(gt, gd) == 19, $"builtin kind is 19 (got {ge.TrackDeviceBuiltinKind(gt, gd)})");
- Check(ge.DeviceParamCount(gt, gd) == 11, $"Nota Shutter exposes 11 params (got {ge.DeviceParamCount(gt, gd)})");
-
- // Param round-trip.
- ge.DeviceSetParam(gt, gd, 0, 0.6f); // Threshold
- Check(Math.Abs(ge.DeviceGetParam(gt, gd, 0) - 0.6f) < 1e-4, "Shutter param set/get round-trips");
-
- var gb = new float[8192 * 2];
- var gsc = new float[5];
- // Open: threshold below the signal → gate stays open, audio passes.
- ge.DeviceSetParam(gt, gd, 0, 0.05f); // threshold very low
- ge.DeviceSetParam(gt, gd, 5, 0f); // floor mute
- ge.Seek(0); ge.Play(); for (int k = 0; k < 6; k++) ge.RenderOffline(gb, 8192); ge.StopTransport();
- bool gfin = true; foreach (var s in gb) if (!float.IsFinite(s)) { gfin = false; break; }
- float openRms = Rms(gb, 8192);
- Check(gfin && openRms > 0.001f, $"Shutter passes audio when open (rms {openRms:F3})");
- int gn = ge.DeviceScope(gt, gd, gsc, gsc.Length);
- Check(gn == 5, $"Shutter scope returns 5 meters (got {gn})");
-
- // Shut: threshold above the signal + mute floor → gate closes, output near-silent.
- ge.DeviceSetParam(gt, gd, 0, 0.98f); // threshold very high (above the note)
- ge.DeviceSetParam(gt, gd, 4, 0.2f); // fast release
- ge.Seek(0); ge.Play(); for (int k = 0; k < 6; k++) ge.RenderOffline(gb, 8192); ge.StopTransport();
- bool gfin2 = true; foreach (var s in gb) if (!float.IsFinite(s)) { gfin2 = false; break; }
- float shutRms = Rms(gb, 8192);
- Check(gfin2, "Shutter renders finite when gating");
- Check(shutRms < openRms * 0.5f, $"gate closes below threshold (shut {shutRms:F4} < open {openRms:F4})");
-
- // Duck (Flip) renders finite + audible.
- ge.DeviceSetParam(gt, gd, 0, 0.3f); ge.DeviceSetParam(gt, gd, 7, 1f); ge.DeviceSetParam(gt, gd, 5, 0.5f);
- ge.Seek(0); ge.Play(); ge.RenderOffline(gb, 8192); ge.StopTransport();
- bool dfin = true; foreach (var s in gb) if (!float.IsFinite(s)) { dfin = false; break; }
- Check(dfin, "Shutter duck (flip) renders finite");
- ge.DeviceSetParam(gt, gd, 7, 0f);
-
- // Sidechain: an external key source is accepted and keys the detector.
- int keyT = ge.AddInstrumentTrack();
- ge.AddMidiClip(keyT, 0.0, 4.0);
- ge.SetClipNotes(keyT, 0, new[] { new NotaNote(45, 0.0, 3.5, 1.0f) });
- ge.SetDeviceSidechainSource(gt, gd, keyT);
- Check(ge.DeviceSidechainSource(gt, gd) == keyT, "Shutter accepts an external key source");
- ge.DeviceSetParam(gt, gd, 0, 0.2f);
- ge.Seek(0); ge.Play(); ge.RenderOffline(gb, 8192); ge.StopTransport();
- bool sfin = true; foreach (var s in gb) if (!float.IsFinite(s)) { sfin = false; break; }
- Check(sfin, "Shutter with external key renders finite");
- ge.SetDeviceSidechainSource(gt, gd, -1);
-
- // Clone: duplicating the track carries Shutter params.
- ge.DeviceSetParam(gt, gd, 2, 0.66f); // Attack
- int gtD = ge.DuplicateTrack(gt); int gdD = ge.TrackDeviceCount(gtD) - 1;
- Check(gtD > 0 && Math.Abs(ge.DeviceGetParam(gtD, gdD, 2) - 0.66f) < 1e-3, "duplicate track clones Shutter params");
-
- // Automation drives Threshold.
- int glane = ge.AddAutomationLane(gt, AutomationTarget.DeviceParam, gd, 0);
- Check(glane >= 0, "add Shutter Threshold automation lane");
- ge.SetAutomationPoints(gt, glane, new[] { new AutomationPoint(0.0, 0.2f), new AutomationPoint(2.0, 0.9f) });
- ge.Seek(1.99); ge.Play(); ge.RenderOffline(gb, 4096); ge.StopTransport();
- Check(ge.DeviceGetParam(gt, gd, 0) > 0.7f, $"automation drives Shutter Threshold ({ge.DeviceGetParam(gt, gd, 0):F2})");
+ // Shutter = noise gate / ducker (kind 19). Own engine (it silences the signal, which would
+ // skew the shared master mix used by later tests). Audio: smooth 50 ms tone bursts peaking at
+ // −6 dBFS every 250 ms over a −54 dBFS hiss (8 openings a 4/4 bar at 120 BPM), and a steady tone
+ // after 0.5 s of silence (the gate keeps its state across a seek, so the silence re-arms it).
+ const int SThreshold = 0, SReturn = 1, SAttack = 2, SHold = 3, SRelease = 4, SFloor = 5, SLook = 6, SFlip = 7, SDetHP = 8,
+ SDetLP = 9, SListen = 10, SShape = 11, SRetrig = 12, SDetFilter = 13, SPeakHold = 14, SExtKey = 15;
+ const int TState = 5, TOpenRatio = 7, TTrigBar = 8, TTrig = 9, TLatency = 12, TExtKey = 13, TWindow = 20, TScope = 24 + 3 * 128;
+ string burstWav = Path.Combine(Path.GetTempPath(), "nota_smoke_shutter_bursts_" + Guid.NewGuid().ToString("N") + ".wav");
+ string toneWav = Path.Combine(Path.GetTempPath(), "nota_smoke_shutter_tone_" + Guid.NewGuid().ToString("N") + ".wav");
+ var rng = new Random(7);
+ Nota.SmokeTest.WavWriter.WriteStereo(burstWav, 4.0, 44100, i =>
+ {
+ double t = i / 44100.0;
+ double ph = t % 0.25;
+ double v = ph < 0.05 ? 0.5 * Math.Pow(Math.Sin(Math.PI * ph / 0.05), 2) * Math.Sin(2 * Math.PI * 220 * t) : 0.002 * (rng.NextDouble() * 2 - 1);
+ return (v, v);
+ });
+ Nota.SmokeTest.WavWriter.WriteStereo(toneWav, 4.0, 44100, i =>
+ {
+ double t = i / 44100.0;
+ double v = t < 0.5 ? 0 : 0.4 * Math.Min(1, (t - 0.5) / 0.005) * Math.Sin(2 * Math.PI * 330 * t);
+ return (v, v);
+ });
+ try
+ {
+ using var ge = new NotaEngine();
+ ge.SetBpm(120); ge.SetTimeSignature(4, 4);
+ int gt = ge.AddAudioTrack();
+ ge.AddAudioClip(gt, burstWav, 0.0);
+ int gd = ge.AddBuiltinDevice(gt, 19);
+ Check(gd >= 0, "add built-in Nota Shutter");
+ Check(ge.DeviceName(gt, gd) == "Nota Shutter", $"name is Nota Shutter (got '{ge.DeviceName(gt, gd)}')");
+ Check(ge.TrackDeviceBuiltinKind(gt, gd) == 19, $"builtin kind is 19 (got {ge.TrackDeviceBuiltinKind(gt, gd)})");
+ Check(ge.DeviceParamCount(gt, gd) == 16, $"Nota Shutter exposes 16 params (got {ge.DeviceParamCount(gt, gd)})");
+ string[] appended = { "Shape", "Retrigger", "Det Filter", "Peak Hold", "External Key" };
+ bool namesOk = true;
+ for (int k = 0; k < appended.Length; k++) namesOk &= ge.DeviceParamName(gt, gd, 11 + k) == appended[k];
+ Check(namesOk && ge.DeviceParamName(gt, gd, 0) == "Threshold" && ge.DeviceParamName(gt, gd, 10) == "Listen", "Shutter keeps params 0..10 and appends Shape … External Key");
+ // Appended params default to the old sound: Log shape, no retrigger, key filter in, no peak hold, a routed key used.
+ Check(Math.Abs(ge.DeviceParamDefault(gt, gd, SShape) - 0.5f) < 1e-4 && ge.DeviceParamDefault(gt, gd, SRetrig) < 0.5f
+ && ge.DeviceParamDefault(gt, gd, SDetFilter) > 0.5f && ge.DeviceParamDefault(gt, gd, SPeakHold) < 0.5f && ge.DeviceParamDefault(gt, gd, SExtKey) > 0.5f,
+ "Shutter's appended params default to the original behaviour");
+ ge.DeviceSetParam(gt, gd, SThreshold, 0.6f);
+ Check(Math.Abs(ge.DeviceGetParam(gt, gd, SThreshold) - 0.6f) < 1e-4, "Shutter param set/get round-trips");
+ ge.DeviceSetParam(gt, gd, SThreshold, 0.457f);
+
+ var gb = new float[4096 * 2];
+ var gsc = new float[TScope];
+ bool fin = true;
+ // Renders the first `blocks` × 4096 frames; returns the RMS after the first four (the gate
+ // keeps its state across the seek, so the start still shows the previous setting).
+ float Run(int blocks = 24)
+ {
+ double acc = 0; long nfr = 0;
+ ge.Seek(0); ge.Play();
+ for (int k = 0; k < blocks; k++)
+ {
+ ge.RenderOffline(gb, 4096);
+ foreach (var v in gb) if (!float.IsFinite(v)) fin = false;
+ if (k < Math.Min(4, blocks - 1)) continue;
+ foreach (var v in gb) acc += v * v;
+ nfr += gb.Length;
+ }
+ ge.StopTransport();
+ ge.DeviceScope(gt, gd, gsc, gsc.Length);
+ return (float)Math.Sqrt(acc / Math.Max(1, nfr));
+ }
+ ge.SetDeviceBypassed(gt, gd, true); float dryRms = Run(); ge.SetDeviceBypassed(gt, gd, false);
+
+ float defRms = Run();
+ Check(fin && defRms > dryRms * 0.8f, $"Shutter passes the bursts at the default threshold ({defRms:F4} vs dry {dryRms:F4})");
+ Check(ge.DeviceScope(gt, gd, gsc, gsc.Length) == TScope, $"Shutter scope returns {TScope} values");
+ Check(gsc[TTrig] >= 6 && gsc[TTrigBar] >= 6 && gsc[TTrigBar] <= 10, $"Shutter counts the openings ({gsc[TTrig]:0} total, {gsc[TTrigBar]:0} in the last bar ≈ 8)");
+ Check(gsc[TOpenRatio] > 0.05 && gsc[TOpenRatio] < 0.8, $"Shutter's open share follows the bursts ({gsc[TOpenRatio]:0.00})");
+
+ ge.DeviceSetParam(gt, gd, SThreshold, 0.98f);
+ float shutRms = Run();
+ Check(fin && shutRms < dryRms * 0.02f, $"gate closes below the threshold (shut {shutRms:F5} < dry {dryRms:F4})");
+ Check(Math.Round(gsc[TState]) == 0, $"Shutter reports closed ({gsc[TState]:0})");
+ ge.DeviceSetParam(gt, gd, SFloor, 0.714f); // −20 dB
+ float floorRms = Run();
+ Check(floorRms > dryRms * 0.07f && floorRms < dryRms * 0.14f, $"Floor −20 dB leaves a tenth ({floorRms / dryRms:0.000})");
+ ge.DeviceSetParam(gt, gd, SFloor, 0f);
+ ge.DeviceSetParam(gt, gd, SThreshold, 0.457f);
+
+ // Duck: the bursts pull themselves down to the floor.
+ ge.DeviceSetParam(gt, gd, SFlip, 1f); ge.DeviceSetParam(gt, gd, SFloor, 0.714f);
+ float duckRms = Run();
+ Check(fin && duckRms < dryRms * 0.5f && duckRms > 0, $"Duck turns the signal down while it is above the threshold ({duckRms / dryRms:0.00})");
+ ge.DeviceSetParam(gt, gd, SFlip, 0f); ge.DeviceSetParam(gt, gd, SFloor, 0f);
+
+ // Detector filter: with the band at 2 k … 2.5 k the 220 Hz bursts barely reach the detector.
+ ge.DeviceSetParam(gt, gd, SDetHP, 1f); ge.DeviceSetParam(gt, gd, SDetLP, 0.548f);
+ float filtOn = Run();
+ ge.DeviceSetParam(gt, gd, SDetFilter, 0f);
+ float filtOff = Run();
+ Check(filtOn < filtOff * 0.5f, $"Det Filter keeps the gate shut on an out-of-band key ({filtOn:F4} vs full band {filtOff:F4})");
+ ge.DeviceSetParam(gt, gd, SDetFilter, 1f); ge.DeviceSetParam(gt, gd, SDetHP, 0.301f);
+
+ // Peak hold and Listen render.
+ ge.DeviceSetParam(gt, gd, SPeakHold, 1f);
+ Check(Run() > 0.001f && fin, "Peak Hold renders finite and audible");
+ ge.DeviceSetParam(gt, gd, SPeakHold, 0f);
+ ge.DeviceSetParam(gt, gd, SListen, 1f); ge.DeviceSetParam(gt, gd, SThreshold, 0.98f);
+ float listenRms = Run();
+ Check(fin && listenRms > dryRms * 0.5f, $"Listen outputs the filtered key even with the gate shut ({listenRms:F4})");
+ ge.DeviceSetParam(gt, gd, SListen, 0f); ge.DeviceSetParam(gt, gd, SThreshold, 0.457f);
+
+ // Lookahead: 5 ms reported as latency.
+ ge.DeviceSetParam(gt, gd, SLook, 1f); Run(2);
+ Check(Math.Abs(gsc[TLatency] - 220) <= 2, $"Lookahead 5 ms = 220 samples of latency ({gsc[TLatency]:0})");
+ ge.DeviceSetParam(gt, gd, SLook, 0.5f);
+
+ // Text + actions (MCP surface).
+ string t0 = ge.DeviceText(gt, gd, 0), t1 = ge.DeviceText(gt, gd, 1), t2 = ge.DeviceText(gt, gd, 2);
+ Check(t0.StartsWith("Gate") && t0.Contains("threshold") && t1.Contains("GR") && t2.Contains("Shape"), $"Shutter device text 0/1/2 ('{t0}')");
+ ge.DeviceAction(gt, gd, 1, 0, 0); Run(1);
+ Check(Math.Abs(gsc[TWindow] - 0.25f) < 1e-3, $"device_action 1 sets the window to 250 ms ({gsc[TWindow]:0.00} s)");
+ ge.DeviceAction(gt, gd, 1, 1, 0);
+ ge.DeviceAction(gt, gd, 0, 0, 0);
+ ge.Seek(3.9); ge.Play(); ge.RenderOffline(gb, 512); ge.StopTransport(); ge.DeviceScope(gt, gd, gsc, gsc.Length);
+ Check(gsc[TTrig] == 0, $"device_action 0 resets the opening count ({gsc[TTrig]:0})");
+
+ // Retrigger (trigger mode) on a steady tone: one opening, then hold + release shut it.
+ int tt = ge.AddAudioTrack();
+ ge.AddAudioClip(tt, toneWav, 0.0);
+ int td = ge.AddBuiltinDevice(tt, 19);
+ ge.DeviceSetParam(gt, gd, SThreshold, 0.98f); // the burst track shuts itself: only the tone reaches the master
+ var tb = new float[4096 * 2];
+ float RunTone()
+ {
+ double acc = 0; long nfr = 0;
+ ge.Seek(0); ge.Play();
+ for (int k = 0; k < 10; k++) { ge.RenderOffline(tb, 4096); foreach (var v in tb) { if (!float.IsFinite(v)) fin = false; acc += v * v; } nfr += tb.Length; }
+ ge.StopTransport();
+ ge.DeviceScope(tt, td, gsc, gsc.Length);
+ return (float)Math.Sqrt(acc / Math.Max(1, nfr));
+ }
+ ge.DeviceSetParam(tt, td, SHold, 0.27f); ge.DeviceSetParam(tt, td, SRelease, 0.303f);
+ float toneOpen = RunTone();
+ ge.DeviceSetParam(tt, td, SRetrig, 1f);
+ float toneRetrig = RunTone();
+ Check(toneOpen > 0.1f && toneRetrig < toneOpen * 0.3f, $"Retrigger fires one opening on a held tone ({toneRetrig:F4} vs {toneOpen:F4})");
+
+ // Shapes: one retriggered opening on the held tone, released over 300 ms — the curve decides the energy.
+ ge.DeviceSetParam(tt, td, SRelease, 0.75f);
+ var shapeRms = new float[3];
+ for (int k = 0; k < 3; k++) { ge.DeviceSetParam(tt, td, SShape, k / 2f); shapeRms[k] = RunTone(); }
+ Check(fin && shapeRms.All(r => r > 0.001f), "every Shape renders finite and audible");
+ // Over the same 300 ms: a straight ramp gives the least, the one-pole (300 ms time constant) more, Snap stays up longest.
+ Check(shapeRms[1] > shapeRms[0] * 1.1f && shapeRms[2] > shapeRms[1] * 1.1f,
+ $"Linear < Log < Snap on the release ({shapeRms[0]:F4} linear / {shapeRms[1]:F4} log / {shapeRms[2]:F4} snap)");
+ ge.DeviceSetParam(tt, td, SShape, 0.5f); ge.DeviceSetParam(tt, td, SRelease, 0.63f);
+ ge.DeviceSetParam(tt, td, SRetrig, 0f);
+
+ // External key: the tone track gated by the bursts; External Key off keys off itself again.
+ ge.SetDeviceSidechainSource(tt, td, gt);
+ ge.SetDeviceSidechainTapPre(tt, td, true); // the key before the burst track's own (shut) gate
+ Check(ge.DeviceSidechainSource(tt, td) == gt, "Shutter accepts an external key source");
+ float keyed = RunTone();
+ Check(gsc[TExtKey] > 0.5f && fin && keyed > 0.01f && keyed < toneOpen * 0.8f, $"the external key opens and shuts the gate ({keyed:F4} vs {toneOpen:F4})");
+ ge.DeviceSetParam(tt, td, SExtKey, 0f);
+ float unkeyed = RunTone();
+ Check(gsc[TExtKey] < 0.5f && unkeyed > toneOpen * 0.95f, $"External Key off keys off the track itself ({unkeyed:F4})");
+ ge.DeviceSetParam(tt, td, SExtKey, 1f);
+ ge.SetDeviceSidechainSource(tt, td, -1);
+ ge.DeviceSetParam(gt, gd, SThreshold, 0.457f);
+
+ // Clone: duplicating the track carries the params, the appended ones too.
+ ge.DeviceSetParam(gt, gd, SAttack, 0.66f); ge.DeviceSetParam(gt, gd, SShape, 1f); ge.DeviceSetParam(gt, gd, SRetrig, 1f);
+ int gtD = ge.DuplicateTrack(gt); int gdD = ge.TrackDeviceCount(gtD) - 1;
+ Check(gtD > 0 && Math.Abs(ge.DeviceGetParam(gtD, gdD, SAttack) - 0.66f) < 1e-3 && ge.DeviceGetParam(gtD, gdD, SShape) > 0.99f
+ && ge.DeviceGetParam(gtD, gdD, SRetrig) > 0.5f, "duplicate track clones Shutter params");
+ ge.DeviceSetParam(gt, gd, SShape, 0.5f); ge.DeviceSetParam(gt, gd, SRetrig, 0f);
+
+ // Automation drives Threshold and an appended param (Floor is original; Shape is new).
+ int glane = ge.AddAutomationLane(gt, AutomationTarget.DeviceParam, gd, SThreshold);
+ Check(glane >= 0, "add Shutter Threshold automation lane");
+ ge.SetAutomationPoints(gt, glane, new[] { new AutomationPoint(0.0, 0.2f), new AutomationPoint(2.0, 0.9f) });
+ int slane = ge.AddAutomationLane(gt, AutomationTarget.DeviceParam, gd, SShape);
+ ge.SetAutomationPoints(gt, slane, new[] { new AutomationPoint(0.0, 1f), new AutomationPoint(8.0, 1f) });
+ ge.Seek(1.99); ge.Play(); ge.RenderOffline(gb, 4096); ge.StopTransport();
+ Check(ge.DeviceGetParam(gt, gd, SThreshold) > 0.7f, $"automation drives Shutter Threshold ({ge.DeviceGetParam(gt, gd, SThreshold):F2})");
+ Check(ge.DeviceGetParam(gt, gd, SShape) > 0.99f, $"automation drives Shutter Shape ({ge.DeviceGetParam(gt, gd, SShape):F2})");
+ ge.RemoveAutomationLane(gt, slane); ge.RemoveAutomationLane(gt, glane);
+
+ // Factory presets: ≥ 25, every named param exists, each applies in place and renders.
+ {
+ var names = new HashSet<string>();
+ for (int k = 0; k < ge.DeviceParamCount(gt, gd); k++) names.Add(ge.DeviceParamName(gt, gd, k));
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 19).ToList();
+ Check(mine.Count >= 25, $"Nota Shutter ships ≥ 25 factory presets ({mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !names.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Shutter preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ fin = true;
+ if (cat.ApplyInPlace(ge, p.Id, gt, gd).Length != 0) { pf++; continue; }
+ Run(4);
+ if (!fin) pf++;
+ }
+ Check(pf == 0, $"every Shutter preset applies and renders finite ({pf} failed)");
+ cat.ApplyInPlace(ge, "shutter/Tom Gate", gt, gd);
+ Check(ge.DeviceGetParam(gt, gd, SShape) < 0.01f && ge.DeviceGetParam(gt, gd, SPeakHold) > 0.5f && ge.DeviceGetParam(gt, gd, SFloor) > 0.7f,
+ "Tom Gate preset: Linear shape, peak hold, −18 dB floor");
+ cat.ApplyInPlace(ge, "shutter/Init", gt, gd);
+ Check(Math.Abs(ge.DeviceGetParam(gt, gd, SShape) - 0.5f) < 1e-4 && ge.DeviceGetParam(gt, gd, SPeakHold) < 0.5f && ge.DeviceGetParam(gt, gd, SFloor) < 0.001f,
+ "Init preset resets the leftovers to the defaults");
+ }
+ }
+ finally
+ {
+ try { File.Delete(burstWav); File.Delete(toneWav); } catch { }
+ }
}
// ============================ Nota Chamber =================================