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.

Add phaser

Egor Khindikaynen33e788dfa966
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84bc7f2e..0f9cf445 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,31 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Nota Phaser.** A new built-in audio effect (kind 24): a chain of all-pass stages whose
+ corner an LFO sweeps, cutting moving notches into the spectrum — from a gentle 4-stage swirl to a
+ deep, whistling 12-stage sweep. The card follows the new mockup on the 700 × 260 frame:
+ - **LFO.** Sine, Tri or Saw; a free rate from 0.02 to 8 Hz or a synced note value from 4/1 to
+ 1/16 with dotted and triplet values, locked to the bar while the transport plays. The rate
+ reads large with its period, and **Stereo** offsets the right channel's sweep by up to 180°.
+ - **All-pass response.** The live frequency response of both channels, left in brass and right
+ in teal, with the corner dashed and every notch ticked on the top edge. Drag the graph left or
+ right to move Center, up or down for Feedback; double-click resets both. Under it, the corner
+ frequency of both channels over two LFO cycles with a running head.
+ - **Stages.** 2, 4, 6, 8 or 12 stages (half as many notches), Center (50 Hz – 5 kHz), Depth up
+ to ±3 octaves, a bipolar Feedback (±95 %) and Mix, plus the range the corner sweeps with the
+ first notch and how deep the notches cut. The loop is solved without a unit delay, so the
+ sound matches the drawn curve; negative feedback flips the wet polarity, moving and widening
+ the notches (one fewer). Changing the stage count fades instead of clicking. The header names
+ the mode: positive, negative, resonant or clean.
+ - A status line says what you'll hear — stages, notches and the corner's sweep in Hz and
+ octaves, or a warning when the phaser whistles or Mix is at zero.
+ All ten controls are device parameters, so automation, MIDI learn, A/B compare and project save
+ work as everywhere else. **35 factory presets**, from Script 45 and Small Stone to Deep Space,
+ Hollow Step, Whistler and Rotary Fast.
+- **MCP: `read_phaser` and `set_phaser`.** Read what a Nota Phaser is doing (the settings in units,
+ the live corner per channel, the notches and their sweep, the null depth and the peaks) and set
+ it in units — stages, waveform, rate or division, stereo degrees, center in Hz, depth in
+ octaves, feedback and mix in percent.
- **Nota Flanger.** A new built-in audio effect (kind 23): a comb filter on a short delay
that an LFO sweeps up and down — the classic jet whoosh, a hollow tube tone, or a metallic
ring. The card follows the new mockup on the 700 × 260 frame:
diff --git a/FEATURES.md b/FEATURES.md
index ab8ba8ce..c0d54c18 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -489,6 +489,13 @@ and user presets, automation, persistence and cloning.
comb-response graph of L and R (drag the notch for Delay, up / down for Feedback), the delay
of both channels over two cycles, the first notch's sweep and null depth, and a status
strip; 31 factory presets; MCP `read_flanger` / `set_flanger`.
+- **Nota Phaser** (24) — 2 / 4 / 6 / 8 / 12 LFO-swept all-pass stages (half as many notches) with
+ delay-free feedback: Center 50 Hz – 5 kHz, Depth ±3 oct, bipolar Feedback ±95 % (negative flips
+ the wet polarity: the notches move and widen), Mix; Sine / Tri / Saw LFO, free (0.02–8 Hz) or
+ synced (4/1 … 1/16 with dotted and triplet values, locked to the bar), Stereo offset 0–180°. A
+ live all-pass response of L and R with the notches ticked (drag for Center, up / down for
+ Feedback), the corner of both channels over two cycles, the sweep and null depth, and a status
+ strip; 35 factory presets; MCP `read_phaser` / `set_phaser`.
- **Nota Chorus** — modulation (chorus) effect.
- **Forge**, **Valve** and **Vintage** each carry an **OVERSAMPLE** selector
(Off/2×/4×/8×) to suppress aliasing under heavy drive.
diff --git a/src/managed/Nota.App/Controls/PhaserViews.cs b/src/managed/Nota.App/Controls/PhaserViews.cs
new file mode 100644
index 00000000..56728ba7
--- /dev/null
+++ b/src/managed/Nota.App/Controls/PhaserViews.cs
@@ -0,0 +1,283 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Phaser views (device kind 24) — the pictures on the Phaser card:
+// PhaserResponseView — the live all-pass response of both channels (L brass, R teal) over 20 Hz …
+// 20 kHz, −36 … +12 dB, the left corner dashed and every notch ticked on
+// the top edge. Drag left / right moves Center, up / down the Feedback;
+// double-click resets both.
+// PhaserSweepView — the corner frequency of both channels over two LFO cycles (20 Hz … 20 kHz,
+// log), a running head and the dots where each channel is now.
+// PhaserMath mirrors Phaser.h so the picture matches the sound. The NOTCH / NULL bars reuse FlangerBar.
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class PhaserMath
+{
+ public static readonly string[] Waves = { "Sine", "Tri", "Saw" };
+ // Sync divisions, slowest → fastest (Phaser::kDivBeats / kDivNames).
+ public static readonly double[] DivBeats = { 16, 8, 4, 2, 1.5, 1, 2.0 / 3, 0.5, 0.25 };
+ public static readonly string[] DivNames = { "4/1", "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/16" };
+ public static readonly int[] StageCounts = { 2, 4, 6, 8, 12 };
+ public const double FbMax = 0.95, DepthOct = 3;
+
+ public static int WaveIndex(double v) => Math.Clamp((int)Math.Round(v * 2), 0, 2);
+ public static int DivIndex(double v) => Math.Clamp((int)Math.Round(v * (DivBeats.Length - 1)), 0, DivBeats.Length - 1);
+ public static double DivNorm(int i) => (double)Math.Clamp(i, 0, DivBeats.Length - 1) / (DivBeats.Length - 1);
+ public static int StageIndex(double v) => Math.Clamp((int)Math.Round(v * (StageCounts.Length - 1)), 0, StageCounts.Length - 1);
+ public static int StagesOf(double v) => StageCounts[StageIndex(v)];
+ public static double FreeHz(double v) => 0.02 * Math.Pow(400, Math.Clamp(v, 0, 1));
+ public static double CenterHz(double v) => 50 * Math.Pow(100, Math.Clamp(v, 0, 1));
+ public static double Fb(double v) => (Math.Clamp(v, 0, 1) - 0.5) * 2 * FbMax;
+ public static double FbNorm(double fb) => Math.Clamp(0.5 + fb / (2 * FbMax), 0, 1);
+ public static (double Dry, double Wet) DryWet(double mix) => (Math.Min(1, 2 * (1 - mix)), Math.Min(1, 2 * mix));
+ public static int NotchCount(int n, double fb) => fb < 0 ? n / 2 - 1 : n / 2;
+
+ /// <summary>The LFO in [−1, 1] at phase <paramref name="p"/> (cycles, wraps) — all shapes start at 0 rising.</summary>
+ public static double Lfo(int wave, double p)
+ {
+ double f = p - Math.Floor(p);
+ if (wave == 0) return Math.Sin(2 * Math.PI * f);
+ if (wave == 1) return f < 0.25 ? 4 * f : f < 0.75 ? 2 - 4 * f : 4 * f - 4;
+ double g = f + 0.5;
+ return 2 * (g - Math.Floor(g)) - 1;
+ }
+
+ public static double Fc(double centerHz, double depth, int wave, double p) => centerHz * Math.Pow(2, DepthOct * depth * Lfo(wave, p));
+
+ /// <summary>|dry ± wet·H(θ)| / (dry + wet), H = e^{−jθ} / (1 − fb·e^{−jθ}); the wet polarity
+ /// follows the feedback's sign (Phaser.h).</summary>
+ public static double Mag(double dry, double wet, double fb, double th)
+ {
+ double c = Math.Cos(th), s = Math.Sin(th), w = fb < 0 ? -wet : wet;
+ double nr = w * c, ni = -w * s, dr = 1 - fb * c, di = fb * s, den = dr * dr + di * di;
+ double re = dry + (nr * dr + ni * di) / den, im = (ni * dr - nr * di) / den;
+ return Math.Sqrt(re * re + im * im) / Math.Max(dry + wet, 0.001);
+ }
+
+ /// <summary>The chain's phase lag at <paramref name="f"/>: N · 2·atan(tan(πf/sr) / tan(πfc/sr)).</summary>
+ public static double Lag(double f, double fc, int n, double sr)
+ {
+ double ny = sr * 0.5 * 0.9999;
+ return n * 2 * Math.Atan(Math.Tan(Math.PI * Math.Min(f, ny) / sr) / Math.Max(1e-9, Math.Tan(Math.PI * Math.Min(fc, ny) / sr)));
+ }
+
+ /// <summary>Where the notches sit for a corner <paramref name="fc"/> (lag = odd multiples of π, or even with negative feedback).</summary>
+ public static List<double> Notches(double fc, int n, double fb, double sr)
+ {
+ var r = new List<double>();
+ double tc = Math.Tan(Math.PI * Math.Min(fc, 0.49999 * sr) / sr);
+ if (fb < 0) for (int k = 1; k < n / 2; k++) r.Add(sr / Math.PI * Math.Atan(tc * Math.Tan(Math.PI * k / n)));
+ else for (int k = 0; k < n / 2; k++) r.Add(sr / Math.PI * Math.Atan(tc * Math.Tan(Math.PI * (2 * k + 1) / (2 * n))));
+ return r;
+ }
+
+ public static double FirstNotch(double fc, int n, double fb, double sr)
+ {
+ var l = Notches(fc, n, fb, sr);
+ return l.Count > 0 ? l[0] : 0;
+ }
+
+ public static double NullDb(double mix, double fb)
+ {
+ var (dry, wet) = DryWet(mix);
+ return 20 * Math.Log10(Math.Max(1e-4, Mag(dry, wet, fb, fb < 0 ? 2 * Math.PI : Math.PI)));
+ }
+
+ public static double PeakDb(double mix, double fb)
+ {
+ var (dry, wet) = DryWet(mix);
+ return 20 * Math.Log10(Math.Max(1e-4, Mag(dry, wet, fb, fb >= 0 ? 0 : Math.PI)));
+ }
+
+ public static string HzF(double f) => f >= 10000 ? NotaNum.F($"{f / 1000:0.0}k") : f >= 1000 ? NotaNum.F($"{f / 1000:0.00}k") : NotaNum.F($"{f:0}");
+}
+
+internal sealed class PhaserResponseView : Control
+{
+ private double _fcL = 800, _fcR = 800, _mix = 0.5, _fb = 0.4, _sr = 48000;
+ private int _stages = 4;
+ private bool _on = true, _drag;
+ private Point _start;
+ private double _c0, _f0;
+
+ /// <summary>Center and Feedback (normalized 0..1) at the start of a drag.</summary>
+ public Func<(double Center, double Feedback)>? Value { get; set; }
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+ public event Action<double, double>? Changed;
+ public event Action? ResetRequested;
+
+ public PhaserResponseView() { ClipToBounds = true; MinHeight = 40; Cursor = new Cursor(StandardCursorType.SizeAll); }
+
+ public void Set(double fcL, double fcR, int stages, double mix, double fb, double sr, bool on)
+ {
+ _fcL = fcL; _fcR = fcR; _stages = stages; _mix = mix; _fb = fb; _sr = sr > 0 ? sr : 48000; _on = on;
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { ResetRequested?.Invoke(); e.Handled = true; return; }
+ var v = Value?.Invoke() ?? (0.602, 0.711);
+ _c0 = v.Center; _f0 = v.Feedback; _start = e.GetPosition(this); _drag = true;
+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (!_drag) return;
+ var p = e.GetPosition(this);
+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;
+ double k = fine ? 0.2 : 1;
+ // The corner follows the hand: a share of the 3-decade axis is the same log share of
+ // Center's 2-decade range.
+ double c = Math.Clamp(_c0 + (p.X - _start.X) * k / Math.Max(120, Bounds.Width) * 1.5, 0, 1);
+ double f = Math.Clamp(_f0 - (p.Y - _start.Y) * k / Math.Max(60, Bounds.Height), 0, 1);
+ Changed?.Invoke(c, f);
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_drag) return;
+ _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke(); InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double X(double f) => Math.Log(Math.Max(f, 1e-3) / 20) / Math.Log(1000) * w;
+ double Y(double db) => h * (0.07 + (12 - Math.Clamp(db, -36, 12)) / 48 * 0.86);
+
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, Y(0)), new Point(w, Y(0)));
+ foreach (double db in new[] { 12.0, -24.0 }) ctx.DrawLine(NotaGraph.GridPen, new Point(0, Y(db)), new Point(w, Y(db)));
+ foreach (double hz in new[] { 100.0, 1000.0, 10000.0 }) ctx.DrawLine(NotaGraph.GridPen, new Point(X(hz), 0), new Point(X(hz), h));
+
+ if (_on && _fcL is > 20 and < 20000)
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1, new DashStyle(new double[] { 2, 3 }, 0)), new Point(X(_fcL), 0), new Point(X(_fcL), h));
+
+ // R first so L reads on top where they meet.
+ Curve(_fcR, _on ? NotaPalette.TealBright : NotaPalette.TextAxis, 1.2, 0.75);
+ Curve(_fcL, _on ? NotaPalette.Accent : NotaPalette.TextAxis, 1.6, 1);
+
+ if (_on)
+ {
+ Ticks(_fcR, NotaPalette.TealBright);
+ Ticks(_fcL, NotaPalette.AccentBright);
+ }
+
+ void Label(string s, double x, double y)
+ {
+ var ft = NotaGraph.AxisText(s);
+ ctx.DrawText(ft, new Point(x, y - ft.Height / 2));
+ }
+ Label("+12", 4, Y(12) + 6);
+ Label("0 dB", 4, Y(0) - 6);
+ Label("−24", 4, Y(-24) - 6);
+ foreach (var (hz, s) in new[] { (100.0, "100"), (1000.0, "1k"), (10000.0, "10k") })
+ {
+ var ft = NotaGraph.AxisText(s);
+ ctx.DrawText(ft, new Point(X(hz) + 3, h - 3 - ft.Height));
+ }
+
+ void Ticks(double fc, IBrush ink)
+ {
+ foreach (double f in PhaserMath.Notches(fc, _stages, _fb, _sr))
+ if (f is > 20 and < 20000) ctx.FillRectangle(ink, new Rect(Math.Round(X(f)), 0, 1, 5));
+ }
+ void Curve(double fc, IBrush ink, double width, double opacity)
+ {
+ var (dry, wet) = PhaserMath.DryWet(_mix);
+ double Db(double g) => 20 * Math.Log10(Math.Max(g, 1e-4));
+ int n = Math.Max(64, (int)w);
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ for (int i = 0; i <= n; i++)
+ {
+ double x = i * w / n, f = 20 * Math.Pow(1000, (double)i / n);
+ double y = _on ? Y(Db(PhaserMath.Mag(dry, wet, _fb, PhaserMath.Lag(f, fc, _stages, _sr)))) : Y(0);
+ if (i == 0) g.BeginFigure(new Point(x, y), false); else g.LineTo(new Point(x, y));
+ }
+ g.EndFigure(false);
+ }
+ using (ctx.PushOpacity(opacity)) ctx.DrawGeometry(null, NotaGraph.SecondaryPen(ink, width), geo);
+ }
+ }
+}
+
+internal sealed class PhaserSweepView : Control
+{
+ private double _center = 800, _depth = 0.7, _off = 0.25, _head, _fcL = 800, _fcR = 800, _periodMs = 2500;
+ private int _wave;
+ private bool _on = true;
+
+ public PhaserSweepView() { ClipToBounds = true; Height = 34; }
+
+ public void Set(double centerHz, double depth, int wave, double offCycles, double head, double fcL, double fcR, double periodMs, bool on)
+ {
+ _center = centerHz; _depth = depth; _wave = wave; _off = offCycles; _head = head; _fcL = fcL; _fcR = fcR; _periodMs = periodMs; _on = on;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double X(double p) => p / 2 * w;
+ double Y(double f) => h * (34 - Math.Clamp(Math.Log(Math.Max(f, 1e-3) / 20) / Math.Log(1000), 0, 1) * 28) / 40;
+ ctx.DrawLine(new Pen(NotaPalette.GraphBorder, 1, new DashStyle(new double[] { 2, 3 }, 0)), new Point(X(1), 0), new Point(X(1), h));
+
+ Curve(_off, _on ? NotaPalette.TealBright : NotaPalette.TextAxis, 1.2, 0.75);
+ Curve(0, _on ? NotaPalette.Accent : NotaPalette.TextAxis, 1.4, 1);
+
+ var tl = NotaGraph.AxisText("fc 20k", size: 6);
+ ctx.DrawText(tl, new Point(5, 1));
+ var bl = NotaGraph.AxisText("20", size: 6);
+ ctx.DrawText(bl, new Point(5, h - 1 - bl.Height));
+ string span = "2 × " + (_periodMs >= 1000 ? NotaNum.F($"{_periodMs / 1000:0.0} s") : NotaNum.F($"{_periodMs:0} ms"));
+ var br = NotaGraph.AxisText(span, size: 6);
+ ctx.DrawText(br, new Point(w - 5 - br.Width, h - 1 - br.Height));
+
+ if (_on)
+ {
+ double hx = X(Math.Clamp(_head, 0, 2));
+ ctx.DrawLine(new Pen(NotaPalette.TextTertiary, 1), new Point(hx, 0), new Point(hx, h));
+ DrawDot(new Point(hx, Y(_fcR)), NotaPalette.TealBright);
+ DrawDot(new Point(hx, Y(_fcL)), NotaPalette.AccentBright);
+ }
+
+ void DrawDot(Point p, IBrush ink) => ctx.DrawEllipse(ink, new Pen(NotaGraph.Ground, 2), p, 3, 3);
+ void Curve(double off, IBrush ink, double width, double opacity)
+ {
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ int n = Math.Max(64, (int)w);
+ for (int i = 0; i <= n; i++)
+ {
+ double p = 2.0 * i / n;
+ double f = _on ? PhaserMath.Fc(_center, _depth, _wave, p + off) : _center;
+ var pt = new Point(X(p), Y(f));
+ if (i == 0) g.BeginFigure(pt, false); else g.LineTo(pt);
+ }
+ g.EndFigure(false);
+ }
+ using (ctx.PushOpacity(opacity)) ctx.DrawGeometry(null, NotaGraph.SecondaryPen(ink, width), geo);
+ }
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/PhaserDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/PhaserDeviceBody.cs
new file mode 100644
index 00000000..c71f1bd7
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Bodies/PhaserDeviceBody.cs
@@ -0,0 +1,342 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — built-in Nota Phaser body (a chain of LFO-swept all-pass stages, device kind
+// 24), a build of the "Nota Phaser" mockup (700 × 260) in the Flanger / Orbit language: an LFO
+// column (waveform, Hz or Sync, the rate as a big readout with its period, Rate and the Stereo phase
+// offset between the channels), a centre panel with the live all-pass response of L and R with the
+// notches ticked (drag: left / right = Center, up / down = Feedback) and, under it, the corner
+// frequency of both channels over two cycles with a running head, a STAGES column (2 / 4 / 6 / 8 /
+// 12, Center, Depth in octaves, the bipolar Feedback, Mix, and the first notch's sweep and null
+// depth) with the mode the feedback makes, and a status strip. The live fc comes from the engine
+// (Phaser.h scopeRead); the response is drawn from the same formula the DSP runs. Every control is
+// a device param (normalized 0..1), so automation / MIDI learn / presets / A-B / persistence come
+// for free. FullBleed — the shared shell draws the header (name · preset · badge · bypass).
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.LogicalTree;
+using Avalonia.Media;
+using Nota.Application;
+using static Nota.App.DeviceCardKit;
+
+namespace Nota.App;
+
+internal sealed class PhaserDeviceBody : IDeviceBody
+{
+ // ── Parameter indices (must match Phaser.h) ──────────────────────────────
+ private const int Rate = 0, Center = 1, Depth = 2, Feedback = 3, Mix = 4, Waveform = 5, Sync = 6, Division = 7, Stereo = 8, Stages = 9;
+ // Scope layout (Phaser::S_* / kTele).
+ private const int S_FcL = 3, S_FcR = 4, S_WinPhase = 5, S_SampleRate = 10, kTele = 32;
+
+ public double Width => 700;
+ public bool FullBleed => true;
+ public string? Subtitle => "MODULATION"; // the processing type, shown as the header badge
+
+ 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 Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void Raw(int p, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, double v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+
+ var readouts = new List<Action>();
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
+ var scope = new float[kTele];
+ int scN = 0;
+ double Sc(int i, double dflt = 0) => scN > i ? scope[i] : dflt;
+
+ // ---- state and units (Phaser.h) ---------------------------------------------------
+ bool On() => !engine.DeviceBypassed(track, di);
+ bool Synced() => P(Sync) >= 0.5f;
+ int WaveI() => PhaserMath.WaveIndex(P(Waveform));
+ int DivI() => PhaserMath.DivIndex(P(Division));
+ int StagesN() => PhaserMath.StagesOf(P(Stages));
+ double Bpm() => engine.Bpm > 0 ? engine.Bpm : 120;
+ double Sr() => Sc(S_SampleRate) > 0 ? Sc(S_SampleRate) : 48000;
+ double RateHz() => Synced() ? Bpm() / 60 / PhaserMath.DivBeats[DivI()] : PhaserMath.FreeHz(P(Rate));
+ double PeriodMs() => 1000 / Math.Max(1e-3, RateHz());
+ double CenterHz() => PhaserMath.CenterHz(P(Center));
+ double Fb() => PhaserMath.Fb(P(Feedback));
+ double FcMin() => CenterHz() * Math.Pow(2, -PhaserMath.DepthOct * P(Depth));
+ double FcMax() => CenterHz() * Math.Pow(2, PhaserMath.DepthOct * P(Depth));
+ // fc now: the engine's, or the centre before the first block.
+ double FcL() => Sc(S_FcL) > 0 ? Sc(S_FcL) : CenterHz();
+ double FcR() => Sc(S_FcR) > 0 ? Sc(S_FcR) : CenterHz();
+ string Mode()
+ {
+ if (!On()) return "bypass";
+ double fb = Fb(), a = Math.Abs(fb);
+ return a >= 0.85 ? "resonant" : fb <= -0.15 ? "negative" : fb >= 0.15 ? "positive" : "clean";
+ }
+
+ static string HzF(double hz) => hz >= 10 ? NotaNum.F($"{hz:0.0}") : NotaNum.F($"{hz:0.00}");
+ static string PctF(double v) => NotaNum.F($"{v * 100:0} %");
+ static string FbF(double fb) => (fb > 0.005 ? "+" : fb < -0.005 ? "−" : "") + NotaNum.F($"{Math.Abs(fb) * 100:0} %");
+ static string PeriodF(double ms) => ms >= 1000 ? NotaNum.F($"{ms / 1000:0.00} s") : NotaNum.F($"{ms:0} ms");
+
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null) => new()
+ { Text = t, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.7, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+
+ // Slider row: caps label · track · mono value.
+ Grid Slider(string label, int p, Func<double, string> fmt, string tip, double labelW = 44, double valueW = 44,
+ bool modulation = false, bool bipolar = false, Func<double, double>? snap = null)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => P(p), v => { Raw(p, snap is null ? v : snap(v)); RefreshAll(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: valueW, modulation: modulation, bipolar: bipolar);
+ readouts.Add(sync);
+ Learn(bar, p);
+ ToolTip.SetTip(bar, tip);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions($"{labelW},*"), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label));
+ g.Children.Add(Col(bar, 1));
+ return g;
+ }
+
+ Border Island(Control head, Control body, double width = double.NaN)
+ {
+ var headBar = new Border
+ {
+ Height = 20, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(8, 0, 3, 0), Child = head,
+ };
+ return new Border
+ {
+ Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ ClipToBounds = true, Child = new DockPanel { LastChildFill = true, Children = { Docked(headBar, Dock.Top), body } },
+ };
+ }
+ static Grid HeadRow(Control left, Control right)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
+ }
+ // A legend sample: a drawn 8px stroke and its word (never a typed dash).
+ static Control LegendItem(string word, IBrush ink) => new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center,
+ Children = { new Border { Width = 8, Height = 1.5, Background = ink, VerticalAlignment = VerticalAlignment.Center }, Mono(word, 7, ink) },
+ };
+
+ // ======================================================================
+ // LEFT — LFO: waveform · Hz / Sync · the rate · Rate · Stereo
+ // ======================================================================
+ var syncSeg = Segments(new[] { "Hz", "Sync" }, () => Synced() ? 1 : 0, i => { SetP(Sync, i); RefreshAll(); }, out var syncSync, fill: true, padX: 0);
+ syncSeg.Width = 76;
+ readouts.Add(syncSync);
+ Learn(syncSeg, Sync);
+ ToolTip.SetTip(syncSeg, "Hz runs the LFO free; Sync takes its rate from the tempo and locks it to the bar while the transport plays");
+
+ var waveSeg = Segments(PhaserMath.Waves, WaveI, i => { SetP(Waveform, i / 2.0); RefreshAll(); }, out var waveSync, fill: true, padX: 0);
+ readouts.Add(waveSync);
+ Learn(waveSeg, Waveform);
+ ToolTip.SetTip(waveSeg, "The LFO shape that sweeps the stages: Sine glides, Tri sweeps evenly, Saw rises and drops back");
+
+ var big = Mono("", 26, AccentBright); big.FontWeight = FontWeight.Bold; big.LineHeight = 28;
+ var bigSub = new TextBlock { FontSize = 8, Foreground = TextSecondary };
+ var period = Mono("", 7, TextTertiary); period.Margin = new Thickness(0, 2, 0, 0);
+ readouts.Add(() =>
+ {
+ double hz = RateHz();
+ if (Synced())
+ {
+ big.Text = PhaserMath.DivNames[DivI()];
+ bigSub.Text = NotaNum.F($"note · {Bpm():0.##} BPM");
+ period.Text = HzF(hz) + " Hz · period " + PeriodF(PeriodMs());
+ }
+ else
+ {
+ big.Text = HzF(hz);
+ bigSub.Text = "Hz · free";
+ period.Text = "period " + PeriodF(PeriodMs());
+ }
+ big.Foreground = On() ? AccentBright : NotaPalette.TextAxis;
+ });
+ var bigBlock = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center, Children = { big, bigSub, period } };
+ ToolTip.SetTip(bigBlock, "The LFO rate: in Hz, or the note value it takes from the tempo");
+
+ var rateRow = Slider("RATE", Rate, v => HzF(PhaserMath.FreeHz(v)) + " Hz", "Rate — the free LFO rate, 0.02 … 8 Hz", 38, 46);
+ var divRow = Slider("RATE", Division, v => PhaserMath.DivNames[PhaserMath.DivIndex(v)],
+ "Rate — the note value of one LFO cycle, 4/1 … 1/16 with dotted (D) and triplet (T) values", 38, 46,
+ snap: v => PhaserMath.DivNorm(PhaserMath.DivIndex(v)));
+ readouts.Add(() => { rateRow.IsVisible = !Synced(); divRow.IsVisible = Synced(); });
+ var stereoRow = Slider("STEREO", Stereo, v => NotaNum.F($"{v * 180:0}°"),
+ "Stereo — the right LFO against the left: 0° sweeps both together, 90° spreads them, 180° moves them opposite", 38, 46,
+ modulation: true, snap: v => Math.Round(v * 180) / 180);
+
+ var leftBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,Auto"), RowSpacing = 6, Margin = new Thickness(8, 6) };
+ leftBody.Children.Add(waveSeg);
+ leftBody.Children.Add(GRow(bigBlock, 1));
+ leftBody.Children.Add(GRow(new Panel { Children = { rateRow, divRow } }, 2));
+ leftBody.Children.Add(GRow(stereoRow, 3));
+ var left = Island(HeadRow(Caps("LFO"), syncSeg), leftBody, 176);
+ DockPanel.SetDock(left, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — ALL-PASS RESPONSE, and fc over two cycles
+ // ======================================================================
+ var fcWord = Mono("", 7, TextTertiary);
+ var legend = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 8, Margin = new Thickness(0, 0, 5, 0),
+ Children = { LegendItem("L", AccentBright), LegendItem("R", NotaPalette.TealBright), fcWord },
+ };
+ var response = new PhaserResponseView { Value = () => (P(Center), P(Feedback)) };
+ response.GestureBegin += () => { Begin(Center); Begin(Feedback); };
+ response.GestureEnd += () => { End(Center); End(Feedback); };
+ response.Changed += (c, f) => { Raw(Center, c); Raw(Feedback, f); RefreshAll(); };
+ response.ResetRequested += () => { Reset(Center); Reset(Feedback); RefreshAll(); };
+ Learn(response, Center);
+ ToolTip.SetTip(response, "The notches the stages cut into the spectrum, L brass and R teal, with the corner dashed and each notch ticked on top. Drag left / right to move Center, up / down for Feedback; double-click resets both.");
+
+ var sweep = new PhaserSweepView { Margin = new Thickness(0, 4, 0, 0) };
+ ToolTip.SetTip(sweep, "The corner frequency of both channels over two LFO cycles (20 Hz … 20 kHz), and where each is now");
+ var centreBody = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { Docked(sweep, Dock.Bottom), response } };
+ var centre = Island(HeadRow(Caps("ALL-PASS RESPONSE"), legend), centreBody);
+ centre.Margin = new Thickness(5, 0);
+
+ // ======================================================================
+ // RIGHT — STAGES: 2…12 · Center · Depth · Feedback · Mix · sweep / null readouts
+ // ======================================================================
+ var modeWord = Mono("", 7, TextSecondary);
+ modeWord.Margin = new Thickness(0, 0, 5, 0);
+ readouts.Add(() =>
+ {
+ string m = Mode();
+ modeWord.Text = m;
+ modeWord.Foreground = m == "resonant" ? AccentBright : m == "negative" ? NotaPalette.TealBright : TextSecondary;
+ });
+ ToolTip.SetTip(modeWord, "What the feedback makes: positive sharpens the peaks, negative moves and widens the notches, past 85 % the phaser whistles");
+
+ var stageSeg = Segments(PhaserMath.StageCounts.Select(n => n.ToString()).ToArray(), () => PhaserMath.StageIndex(P(Stages)),
+ i => { SetP(Stages, i / (double)(PhaserMath.StageCounts.Length - 1)); RefreshAll(); }, out var stageSync, fill: true, padX: 0);
+ foreach (var tb in stageSeg.GetLogicalDescendants().OfType<TextBlock>()) tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ readouts.Add(stageSync);
+ Learn(stageSeg, Stages);
+ ToolTip.SetTip(stageSeg, "All-pass stages: every two cut one notch — 2 is a gentle swirl, 12 a deep, dense sweep");
+
+ var centerRow = Slider("CENTER", Center, v => PhaserMath.HzF(PhaserMath.CenterHz(v)) + " Hz",
+ "Center — the middle of the sweep, 50 Hz … 5 kHz: higher moves the notches up");
+ var depthRow = Slider("DEPTH", Depth, v => NotaNum.F($"±{v * PhaserMath.DepthOct:0.0} oct"),
+ "Depth — how far the LFO swings the stages around Center, up to ±3 octaves");
+ var fbRow = Slider("FEEDBACK", Feedback, v => FbF(PhaserMath.Fb(v)),
+ "Feedback — the chain's output fed back in, ±95 %: positive sharpens the peaks, negative moves and widens the notches", modulation: true, bipolar: true,
+ snap: v => PhaserMath.FbNorm(Math.Round(PhaserMath.Fb(v) * 100) / 100));
+ var mixRow = Slider("MIX", Mix, v => PctF(v), "Mix — 50 % gives the deepest notches; 100 % is the phase-shifted signal alone");
+
+ double PctAxis(double f) => Math.Clamp(Math.Log(Math.Max(f, 1e-3) / 20) / Math.Log(1000), 0, 1);
+ Control ReadRow(string label, FlangerBar bar, TextBlock value, string tip)
+ {
+ value.TextAlignment = TextAlignment.Right; value.Width = 44;
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("44,*,Auto") };
+ g.Children.Add(Caps(label));
+ g.Children.Add(Col(bar, 1));
+ g.Children.Add(Col(new Border { Margin = new Thickness(6, 0, 0, 0), Child = value }, 2));
+ ToolTip.SetTip(g, tip);
+ return g;
+ }
+ var sweepBar = new FlangerBar { Ink = NotaPalette.BorderStrong, VerticalAlignment = VerticalAlignment.Center };
+ var sweepVal = Mono("", 8, TextPrimary);
+ var nullBar = new FlangerBar { Ink = NotaPalette.TealBright, VerticalAlignment = VerticalAlignment.Center };
+ var nullVal = Mono("", 8, TextPrimary);
+ var reads = new Border
+ {
+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0),
+ Child = new StackPanel
+ {
+ Spacing = 4, Children =
+ {
+ ReadRow("SWEEP", sweepBar, sweepVal, "The range the corner sweeps (20 Hz … 20 kHz on the bar), and the first notch now"),
+ ReadRow("NULL", nullBar, nullVal, "How deep the notches cut, dB (0 … −36 on the bar)"),
+ },
+ },
+ };
+
+ var rightBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto,*,Auto,*,Auto,*,Auto"), Margin = new Thickness(8, 6) };
+ rightBody.Children.Add(stageSeg);
+ rightBody.Children.Add(GRow(centerRow, 2));
+ rightBody.Children.Add(GRow(depthRow, 4));
+ rightBody.Children.Add(GRow(fbRow, 6));
+ rightBody.Children.Add(GRow(mixRow, 8));
+ rightBody.Children.Add(GRow(reads, 10));
+ var right = Island(HeadRow(Caps("STAGES"), modeWord), rightBody, 176);
+ DockPanel.SetDock(right, Dock.Right);
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ readouts.Add(() =>
+ {
+ double fb = Fb(), afb = Math.Abs(fb);
+ bool warn = false;
+ string foot;
+ if (!On()) foot = "Phaser bypassed: the signal passes unchanged";
+ else if (P(Mix) < 0.01f) { foot = "Mix at zero: only the dry signal is heard"; warn = true; }
+ else if (afb >= 0.85)
+ {
+ foot = "Feedback " + FbF(fb) + NotaNum.F($": peaks up to +{PhaserMath.PeakDb(P(Mix), fb):0.0} dB, the phaser whistles");
+ warn = true;
+ }
+ else if (P(Depth) < 0.01f) foot = "Depth at zero: the notches stand still";
+ else
+ {
+ int n = StagesN();
+ foot = n + " stages · " + PhaserMath.NotchCount(n, fb) + (PhaserMath.NotchCount(n, fb) == 1 ? " notch" : " notches") + " · fc "
+ + PhaserMath.HzF(FcMin()) + " ↔ " + PhaserMath.HzF(FcMax()) + NotaNum.F($" Hz ({2 * PhaserMath.DepthOct * P(Depth):0.0} oct)");
+ }
+ statusLeft.Text = foot;
+ statusLeft.Foreground = warn ? AccentBright : TextSecondary;
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = (sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · ") : "") + NotaNum.F($"{Bpm():0.##} BPM · ") + (Synced() ? "retrig bar" : "free run");
+ });
+ 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 = { left, right, centre } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, kTele);
+ bool on = On();
+ double fl = FcL(), fr = FcR(), fb = Fb(), mix = P(Mix), sr = Sr();
+ int n = StagesN();
+ fcWord.Text = on ? "fcL " + PhaserMath.HzF(fl) + " · fcR " + PhaserMath.HzF(fr) + " Hz" : "bypass";
+ response.Set(fl, fr, n, mix, fb, sr, on);
+ sweep.Set(CenterHz(), P(Depth), WaveI(), P(Stereo) * 0.5, Sc(S_WinPhase), fl, fr, PeriodMs(), on);
+
+ double nf = PhaserMath.FirstNotch(fl, n, fb, sr);
+ double nullDb = PhaserMath.NullDb(mix, fb);
+ sweepBar.Set(on ? PctAxis(FcMin()) : 0, on ? PctAxis(FcMax()) - PctAxis(FcMin()) : 0);
+ sweepVal.Text = on && nf > 0 ? PhaserMath.HzF(nf) + " Hz" : "—";
+ nullBar.Set(0, on ? Math.Clamp(-nullDb / 36, 0, 1) : 0);
+ nullVal.Text = on ? NotaNum.F($"{nullDb:0.0} dB") : "—";
+ RefreshAll();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
index 4b72e327..96b3586d 100644
--- a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
+++ b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
@@ -42,6 +42,7 @@ internal sealed class DeviceCardFactory
[21] = new PrismDeviceBody(),
[22] = new LensDeviceBody(),
[23] = new FlangerDeviceBody(),
+ [24] = new PhaserDeviceBody(),
};
/// <summary>Resolve the body for a device: -1 = hosted plugin, a mapped built-in kind,
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 3239101c..81005847 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1694,6 +1694,52 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fl("Bass Swirl", FSine, 4.0f, 0.50f, 0.40f, 0.35f, 0, hz: 0.15f);
Fl("Pad Space", FSine, 3.0f, 0.90f, 0.50f, 0.50f, 180, hz: 0.07f);
+ // ---- Nota Phaser (kind 24) — LFO-swept all-pass stages. Written in units through Ph(): stages
+ // (2 / 4 / 6 / 8 / 12), waveform (FSine / FTri / FSaw), Center Hz 50..5000, Depth 0..1 (= ±3 oct),
+ // Feedback −0.95..+0.95, Mix 0..1 (0.5 = the deepest notches), Stereo 0..180°, and either a free
+ // rate in Hz (0.02..8) or a Sync division (4/1 2/1 1/1 1/2 1/4D 1/4 1/4T 1/8 1/16).
+ // Classic
+ Ph("Script 45", 4, FSine, 800, 0.70f, 0.40f, 0.50f, 90, hz: 0.40f);
+ Ph("Slow Swirl", 4, FSine, 700, 0.80f, 0.30f, 0.50f, 90, hz: 0.12f);
+ Ph("Small Stone", 4, FTri, 900, 0.75f, 0.60f, 0.50f, 90, hz: 0.50f);
+ Ph("Two-Stage Shimmer", 2, FSine, 1200, 0.60f, 0.20f, 0.50f, 120, hz: 0.80f);
+ Ph("Vintage Six", 6, FTri, 650, 0.70f, 0.50f, 0.50f, 90, hz: 0.30f);
+ Ph("Eight Stage Sweep", 8, FSine, 700, 0.75f, 0.50f, 0.50f, 90, hz: 0.20f);
+ Ph("Gentle Motion", 4, FSine, 1000, 0.40f, 0.10f, 0.35f, 60, hz: 0.25f);
+ Ph("Wide Stereo", 6, FSine, 800, 0.70f, 0.40f, 0.50f, 180, hz: 0.20f);
+ Ph("Mono Swoosh", 4, FTri, 800, 0.80f, 0.50f, 0.50f, 0, hz: 0.30f);
+ // Deep / resonant
+ Ph("Deep Space", 12, FTri, 600, 0.80f, 0.75f, 0.50f, 180, div: "1/1");
+ Ph("Whistler", 8, FSine, 1000, 0.70f, 0.90f, 0.50f, 90, hz: 0.15f);
+ Ph("Resonant Twelve", 12, FSine, 500, 0.60f, 0.88f, 0.50f, 90, hz: 0.10f);
+ Ph("Jet Phase", 12, FTri, 800, 1.00f, 0.80f, 0.50f, 45, hz: 0.06f);
+ Ph("Laser Sweep", 8, FSaw, 1500, 1.00f, 0.85f, 0.50f, 0, hz: 3.00f);
+ // Negative feedback
+ Ph("Hollow Step", 6, FSaw, 1500, 0.40f, -0.60f, 0.50f, 0, div: "1/4");
+ Ph("Hollow Drift", 8, FSine, 700, 0.70f, -0.50f, 0.50f, 120, hz: 0.18f);
+ Ph("Inverse Twelve", 12, FTri, 900, 0.60f, -0.70f, 0.50f, 90, hz: 0.25f);
+ Ph("Nasal Tube", 4, FSine, 2000, 0.50f, -0.80f, 0.50f, 90, hz: 0.35f);
+ // Synced
+ Ph("Quarter Pulse", 4, FTri, 900, 0.70f, 0.50f, 0.50f, 90, div: "1/4");
+ Ph("Two-Bar Sweep", 8, FSine, 700, 0.90f, 0.60f, 0.50f, 90, div: "2/1");
+ Ph("Four-Bar Rise", 12, FSaw, 600, 1.00f, 0.60f, 0.50f, 180, div: "4/1");
+ Ph("Eighth Chop", 6, FSaw, 1200, 0.60f, 0.50f, 0.55f, 0, div: "1/8");
+ Ph("Dotted Wander", 6, FSine, 800, 0.70f, 0.40f, 0.50f, 120, div: "1/4D");
+ Ph("Triplet Flutter", 4, FTri, 1500, 0.40f, 0.30f, 0.45f, 90, div: "1/4T");
+ Ph("Half-Bar Swell", 8, FSine, 700, 0.80f, 0.55f, 0.50f, 90, div: "1/2");
+ // Fast / FX
+ Ph("Rotary Fast", 4, FSine, 1100, 0.35f, 0.20f, 0.50f, 90, hz: 6.00f);
+ Ph("Rotary Slow", 4, FSine, 1000, 0.40f, 0.20f, 0.50f, 90, hz: 0.80f);
+ Ph("Bubble Trouble", 6, FTri, 1800, 0.50f, 0.70f, 0.55f, 60, hz: 4.00f);
+ Ph("Static Notch", 8, FSine, 1000, 0.00f, 0.60f, 0.50f, 0, hz: 0.20f);
+ // Sources
+ Ph("Guitar Classic", 4, FSine, 800, 0.70f, 0.45f, 0.50f, 90, hz: 0.50f);
+ Ph("Electric Piano", 4, FSine, 900, 0.55f, 0.25f, 0.40f, 120, hz: 0.30f);
+ Ph("Pad Drift", 8, FSine, 600, 0.90f, 0.40f, 0.50f, 180, hz: 0.07f);
+ Ph("Drum Bus Swirl", 6, FTri, 1500, 0.60f, 0.30f, 0.35f, 90, div: "2/1");
+ Ph("Bass Motion", 4, FSine, 250, 0.50f, 0.30f, 0.35f, 0, hz: 0.20f);
+ Ph("Vocal Air", 2, FSine, 2500, 0.50f, 0.20f, 0.30f, 120, hz: 0.25f);
+
// ---- Nota Auto Shift (kind 10) — pitch correction, all params normalized 0..1 (unnamed ones
// reset to their defaults). Key round(11v) (0 C, .182 D, .364 E, .455 F, .636 G, .818 A);
// Scale 0 Chromatic/.25 Major/.5 Minor/.75 Penta Maj/1 Penta Min; Custom Scale 1 = the
@@ -2093,6 +2139,24 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
("Waveform", wave / 2f), ("Sync", div is null ? 0f : 1f), ("Division", d / 8f), ("Stereo", stereoDeg / 180f));
}
+ // Nota Phaser Sync divisions (Phaser::kDivNames) and stage counts, and its presets in units.
+ private static readonly string[] PhDivs = { "4/1", "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/16" };
+ private static readonly int[] PhStages = { 2, 4, 6, 8, 12 };
+
+ private void Ph(string name, int stages, int wave, float centerHz, float depth, float fb, float mix, float stereoDeg, float hz = 0.4f, string? div = null)
+ {
+ int d = div is null ? 2 : Array.IndexOf(PhDivs, div);
+ if (d < 0) throw new ArgumentException($"unknown Phaser division {div}");
+ int st = Array.IndexOf(PhStages, stages);
+ if (st < 0) throw new ArgumentException($"Phaser stages must be 2, 4, 6, 8 or 12 ({stages})");
+ Fx("phaser", 24, name,
+ ("Rate", (float)(Math.Log(Math.Clamp(hz, 0.02f, 8f) / 0.02) / Math.Log(400))),
+ ("Center", (float)(Math.Log(Math.Clamp(centerHz, 50f, 5000f) / 50.0) / Math.Log(100))),
+ ("Depth", depth), ("Feedback", 0.5f + Math.Clamp(fb, -0.95f, 0.95f) / 1.9f), ("Mix", mix),
+ ("Waveform", wave / 2f), ("Sync", div is null ? 0f : 1f), ("Division", d / 8f), ("Stereo", stereoDeg / 180f),
+ ("Stages", st / 4f));
+ }
+
// Nota Forge stage types (the S* Type step, × 1/5).
private const int FTube = 0, FDiode = 1, FTape = 2, FFuzz = 3, FDigital = 4, FFold = 5;
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 762ad6fa..0ec34a5a 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -20,7 +20,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
(6, "Nota Valve"), (7, "Auto Filter"), (8, "Nota Vintage"), (9, "Nota Orbit"), (10, "Auto Shift"),
(11, "Beat Repeat"), (12, "Crush"), (13, "Dynamic EQ-8"), (14, "Ceiling"), (15, "Strata"),
(16, "Nota EQ-3"), (17, "Forge"), (18, "Nota Level"), (19, "Nota Shutter"), (20, "Nota Chamber"), (21, "Nota Prism"),
- (22, "Nota Lens"), (23, "Nota Flanger"),
+ (22, "Nota Lens"), (23, "Nota Flanger"), (24, "Nota Phaser"),
};
public sealed record DeviceKind(int Kind, string Name);
@@ -67,10 +67,10 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
- [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Dynamic EQ-8 (kind 13): id 0 = a one-line summary (bands on and dynamic, the Dynamic switch, each band on with its type, frequency, gain, Q and — for a dynamic band — mode, threshold, range, attack / release and key, solo, output, whether a key track is routed), 1 = the live reading (in / out peaks, whether a key arrives, each band's detector level and — for a dynamic band — its threshold and the gain it has now of its range, CPU), 2 = a guide to the parameter layout and units — or use read_dynamic_eq for the numbers and set_dynamic_eq_band to edit a band. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers. Nota Crush (kind 12): id 0 = a one-line summary (mode, bits, rate with the hold, drive, wet, dither / jitter / noise, post filter, output, anti-alias, auto gain, DC filter), 1 = the live reading (in / out peak and RMS, crest, peak holds, bits with the level count and quantisation noise, the reduced rate, hold and Nyquist, THD+N, images above the Nyquist, the driven peak and folds, auto gain, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_crush for the numbers. Nota Orbit (kind 9): id 0 = a one-line summary (waveform, free rate in Hz or the Sync division, shape / glide, phase with the mode it makes — tremolo, auto-pan or offset pan — amount, mix), 1 = the live reading (the LFO rate and period, locked to the song or free-running, its place in the two-cycle window, the L / R gain now, the pan and its swing, the floor, in / out levels, tempo and bar, CPU), 2 = a guide to what each 0..1 parameter value means incl. the Division table — or use read_orbit for the numbers. Nota EQ-3 (kind 16): id 0 = a one-line summary (slope, the two crossovers, each band's gain or kill, the fader range, output), 1 = the live reading (in / out peaks, each band's level after its gain and the gain in effect now, the crossovers in use, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_eq3 for the numbers and set_eq3 to play it in dB and Hz. Nota Forge (kind 17): id 0 = a one-line summary (routing, amount, wet, output, each stage on with its type, role, drive, out, feedback, bias, tone and width, the LFO → drive with its rate, env → tone, the master tone / bias / width offsets when set, oversampling and an aliasing warning), 1 = the live reading (in / out peak and RMS, THD of a −6 dB sine through the device and through each stage with its flavour, the LFO value, drive offset and rate, the envelope, the master tilt now, oversampling, latency, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_forge for the numbers and the curve, set_forge and set_forge_stage to play it in units. Nota Level (kind 18): id 0 = a one-line summary (the target or the reference track, scale, auto with its glide or manual with its gain, max gain, trim, true-peak safe with the ceiling and look-ahead), 1 = the live reading (state, input and output loudness on the scale, momentary and short-term, the target in effect, the distance to it, the correction, gain applied and wanted, limiter reduction, true peak, correlation, latency), 2 = a guide to what each 0..1 parameter value means — or use read_level for the numbers and set_level to play it in LUFS and dB. Nota EQ-8 (kind 0): id 0 = a one-line summary (bands on, scale, each band on with its type, frequency, gain, Q, slope for the cuts and channel when not stereo, output, auto gain, analyzer), 1 = the live reading (in / out peaks, the auto gain in effect, CPU), 2 = a guide to the parameter layout and units — or use read_eq8 for the numbers, set_eq8_band to edit a band and set_eq8 for the globals. Nota Flanger (kind 23): id 0 = a one-line summary, 1 = the live reading (delay per channel, the notch and its sweep, levels), 2 = a guide to the parameter values — or use read_flanger / set_flanger.")]
+ [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Dynamic EQ-8 (kind 13): id 0 = a one-line summary (bands on and dynamic, the Dynamic switch, each band on with its type, frequency, gain, Q and — for a dynamic band — mode, threshold, range, attack / release and key, solo, output, whether a key track is routed), 1 = the live reading (in / out peaks, whether a key arrives, each band's detector level and — for a dynamic band — its threshold and the gain it has now of its range, CPU), 2 = a guide to the parameter layout and units — or use read_dynamic_eq for the numbers and set_dynamic_eq_band to edit a band. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers. Nota Crush (kind 12): id 0 = a one-line summary (mode, bits, rate with the hold, drive, wet, dither / jitter / noise, post filter, output, anti-alias, auto gain, DC filter), 1 = the live reading (in / out peak and RMS, crest, peak holds, bits with the level count and quantisation noise, the reduced rate, hold and Nyquist, THD+N, images above the Nyquist, the driven peak and folds, auto gain, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_crush for the numbers. Nota Orbit (kind 9): id 0 = a one-line summary (waveform, free rate in Hz or the Sync division, shape / glide, phase with the mode it makes — tremolo, auto-pan or offset pan — amount, mix), 1 = the live reading (the LFO rate and period, locked to the song or free-running, its place in the two-cycle window, the L / R gain now, the pan and its swing, the floor, in / out levels, tempo and bar, CPU), 2 = a guide to what each 0..1 parameter value means incl. the Division table — or use read_orbit for the numbers. Nota EQ-3 (kind 16): id 0 = a one-line summary (slope, the two crossovers, each band's gain or kill, the fader range, output), 1 = the live reading (in / out peaks, each band's level after its gain and the gain in effect now, the crossovers in use, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_eq3 for the numbers and set_eq3 to play it in dB and Hz. Nota Forge (kind 17): id 0 = a one-line summary (routing, amount, wet, output, each stage on with its type, role, drive, out, feedback, bias, tone and width, the LFO → drive with its rate, env → tone, the master tone / bias / width offsets when set, oversampling and an aliasing warning), 1 = the live reading (in / out peak and RMS, THD of a −6 dB sine through the device and through each stage with its flavour, the LFO value, drive offset and rate, the envelope, the master tilt now, oversampling, latency, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_forge for the numbers and the curve, set_forge and set_forge_stage to play it in units. Nota Level (kind 18): id 0 = a one-line summary (the target or the reference track, scale, auto with its glide or manual with its gain, max gain, trim, true-peak safe with the ceiling and look-ahead), 1 = the live reading (state, input and output loudness on the scale, momentary and short-term, the target in effect, the distance to it, the correction, gain applied and wanted, limiter reduction, true peak, correlation, latency), 2 = a guide to what each 0..1 parameter value means — or use read_level for the numbers and set_level to play it in LUFS and dB. Nota EQ-8 (kind 0): id 0 = a one-line summary (bands on, scale, each band on with its type, frequency, gain, Q, slope for the cuts and channel when not stereo, output, auto gain, analyzer), 1 = the live reading (in / out peaks, the auto gain in effect, CPU), 2 = a guide to the parameter layout and units — or use read_eq8 for the numbers, set_eq8_band to edit a band and set_eq8 for the globals. Nota Flanger (kind 23): id 0 = a one-line summary, 1 = the live reading (delay per channel, the notch and its sweep, levels), 2 = a guide to the parameter values — or use read_flanger / set_flanger. Nota Phaser (kind 24): id 0 = a one-line summary (stages and notches, LFO, center, depth, feedback and its mode, mix), 1 = the live reading (fc per channel, the first notch and its sweep, null and peak depth, levels), 2 = a guide to the parameter values — or use read_phaser / set_phaser.")]
public Task<string> GetDeviceText(int trackId, int deviceIndex, int id) => Read(() => E.DeviceText(trackId, deviceIndex, id));
- [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Nota Shutter (kind 19): id 0 resets the meters (peak reduction, the opening count, the history); id 1 sets the history window read_shutter and the card show (intArg 0 = 250 ms, 1 = 1 s, 2 = 4 s). Nota Auto Shift (kind 10): id 0 resets the analysis (the sung-note histogram and the pitch history); id 1 is Learn — intArg 1 starts listening (clears the histogram), 0 stops and sets Key + Scale (Major / Minor) to the best match and Key Source to Manual, 2 cancels. Nota Beat Repeat (kind 11): id 0 resets (stops the repeat, clears the timeline, the meters and the burst count); id 1 fires a repeat now, as if the interval hit (ignores Chance; while the transport plays — to hold one, set the Repeat param to 1). Nota Ceiling (kind 14): id 0 resets the peaks (the peak and true-peak holds, the max reduction, the clip count and the 4 s level window); id 1 resets the loudness (integrated, LRA, the 60 s window) and the peaks. Nota Crush (kind 12): id 0 resets the meters (the peak holds and the spectrum average). Nota Orbit (kind 9): id 0 restarts the LFO (free run: from phase 0; with Sync on and the transport playing it stays locked to the bar), id 1 resets the meters. Nota EQ-3 (kind 16): id 0 resets the meters (the peaks and the spectrum average). Nota Forge (kind 17): id 0 restarts the LFO (free run: from phase 0) and resets the meters. Nota Level (kind 18): id 0 restarts the measurement from the loudness now (RESET — the ride catches up at once), id 1 is MATCH (switches to Manual with the gain set to the distance to the target; see level_match). Nota EQ-8 (kind 0): id 0 resets the meters (the peaks and the spectrum averages). Nota Flanger (kind 23): id 0 restarts the LFO (free run: from phase 0), id 1 clears the delay line (stops a ringing comb), id 2 resets the meters. Devices without a command ignore the call.")]
+ [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Nota Shutter (kind 19): id 0 resets the meters (peak reduction, the opening count, the history); id 1 sets the history window read_shutter and the card show (intArg 0 = 250 ms, 1 = 1 s, 2 = 4 s). Nota Auto Shift (kind 10): id 0 resets the analysis (the sung-note histogram and the pitch history); id 1 is Learn — intArg 1 starts listening (clears the histogram), 0 stops and sets Key + Scale (Major / Minor) to the best match and Key Source to Manual, 2 cancels. Nota Beat Repeat (kind 11): id 0 resets (stops the repeat, clears the timeline, the meters and the burst count); id 1 fires a repeat now, as if the interval hit (ignores Chance; while the transport plays — to hold one, set the Repeat param to 1). Nota Ceiling (kind 14): id 0 resets the peaks (the peak and true-peak holds, the max reduction, the clip count and the 4 s level window); id 1 resets the loudness (integrated, LRA, the 60 s window) and the peaks. Nota Crush (kind 12): id 0 resets the meters (the peak holds and the spectrum average). Nota Orbit (kind 9): id 0 restarts the LFO (free run: from phase 0; with Sync on and the transport playing it stays locked to the bar), id 1 resets the meters. Nota EQ-3 (kind 16): id 0 resets the meters (the peaks and the spectrum average). Nota Forge (kind 17): id 0 restarts the LFO (free run: from phase 0) and resets the meters. Nota Level (kind 18): id 0 restarts the measurement from the loudness now (RESET — the ride catches up at once), id 1 is MATCH (switches to Manual with the gain set to the distance to the target; see level_match). Nota EQ-8 (kind 0): id 0 resets the meters (the peaks and the spectrum averages). Nota Flanger (kind 23): id 0 restarts the LFO (free run: from phase 0), id 1 clears the delay line (stops a ringing comb), id 2 resets the meters. Nota Phaser (kind 24): id 0 restarts the LFO (free run: from phase 0), id 1 clears the all-pass stages (stops a whistling loop), id 2 resets the meters. 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));
@@ -920,6 +920,98 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
return FlangerRead(trackId, deviceIndex);
});
+ public sealed record PhaserReading(string Summary, string Live, int Stages, int Notches, string Waveform, bool Sync, string Division,
+ double RateHz, double PeriodMs, double StereoDeg, double CenterHz, double DepthOctaves, double FeedbackPercent, double MixPercent,
+ string Mode, double FcMinHz, double FcMaxHz, double FcLHz, double FcRHz, double NotchHz, double NotchMinHz, double NotchMaxHz,
+ double NullDb, double PeakDb, double WindowPhase, bool Locked, bool Playing, double Bpm, double InputPeakDb,
+ double OutputPeakLDb, double OutputPeakRDb, bool Signal, double SampleRate);
+
+ private static readonly string[] PhaserWaves = { "Sine", "Triangle", "Saw" };
+ private static readonly string[] PhaserDivs = { "4/1", "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/16" };
+ private static readonly int[] PhaserStages = { 2, 4, 6, 8, 12 };
+
+ [McpServerTool(Name = "read_phaser"), Description(
+ "Read what a Nota Phaser (built-in effect kind 24 — a chain of 2 / 4 / 6 / 8 / 12 all-pass stages an LFO sweeps; "
+ + "notches = stages / 2, one fewer with negative feedback) is doing: the stages and notches, the LFO waveform, free rate "
+ + "(Hz) or Sync division, the period, Stereo (the right LFO's offset, 0..180°), Center (the middle of the sweep, Hz), "
+ + "Depth (± octaves), Feedback (−95..+95 %) and the mode it makes (positive, negative, resonant past 85 %, clean near 0), "
+ + "Mix; the corner's sweep range and live fc per channel (Hz), the first notch now and the range it sweeps, the notch "
+ + "depth and the peak level (dB), the LFO's place in its two-cycle window, whether it is locked to the song (Sync + "
+ + "playing), tempo and input / L / R output peaks (dBFS, −120 = silence). Live values move only while audio runs through "
+ + "the track. Params: 0 Rate, 1 Center, 2 Depth, 3 Feedback, 4 Mix, 5 Waveform, 6 Sync, 7 Division, 8 Stereo, 9 Stages — "
+ + "set them in units with set_phaser; device_action 0 restarts the LFO, 1 clears the stages, 2 resets the meters.")]
+ public Task<PhaserReading> ReadPhaser(int trackId, int deviceIndex) => Read(() => PhaserRead(trackId, deviceIndex));
+
+ private PhaserReading PhaserRead(int trackId, int deviceIndex)
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 24) throw new ArgumentException("not a Nota Phaser (kind 24)");
+ var sc = new float[32];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float Db(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ static double R2(double v) => Math.Round(v, 2);
+ float Pm(int p) => E.DeviceGetParam(trackId, deviceIndex, p);
+ int wave = Math.Clamp((int)Math.Round(Pm(5) * 2), 0, 2);
+ int div = Math.Clamp((int)Math.Round(Pm(7) * 8), 0, 8);
+ int stages = PhaserStages[Math.Clamp((int)Math.Round(Pm(9) * 4), 0, 4)];
+ double fb = (Pm(3) - 0.5) * 1.9;
+ string mode = Math.Abs(fb) >= 0.85 ? "resonant" : fb <= -0.15 ? "negative" : fb >= 0.15 ? "positive" : "clean";
+ double rate = V(6);
+ return new PhaserReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ stages, fb < 0 ? stages / 2 - 1 : stages / 2, PhaserWaves[wave], Pm(6) >= 0.5f, PhaserDivs[div],
+ Math.Round(rate, 3), rate > 0 ? Math.Round(1000 / rate) : 0, Math.Round(Pm(8) * 180),
+ Math.Round(50 * Math.Pow(100, Pm(1))), R2(Pm(2) * 3), R1(fb * 100), R1(Pm(4) * 100), mode,
+ Math.Round(V(12)), Math.Round(V(13)), Math.Round(V(3)), Math.Round(V(4)), Math.Round(V(14)), Math.Round(V(15)), Math.Round(V(16)),
+ R1(V(17)), R1(V(18)), Math.Round(V(5), 3), V(9) > 0.5f, V(8) > 0.5f, Math.Round(V(7), 2),
+ R1(Db(0)), R1(Db(1)), R1(Db(2)), V(22) > 0.5f, V(10));
+ }
+
+ [McpServerTool(Name = "set_phaser"), Description(
+ "Play a Nota Phaser (built-in effect kind 24) in units — only the fields you pass change; each change is recorded like a "
+ + "hand edit (so it lands in automation while recording). stages 2 | 4 | 6 | 8 | 12 (notches = stages / 2); waveform "
+ + "\"Sine\" | \"Triangle\" | \"Saw\"; rateHz 0.02..8 (sets free run); division \"4/1\" \"2/1\" \"1/1\" \"1/2\" \"1/4D\" "
+ + "\"1/4\" \"1/4T\" \"1/8\" \"1/16\" (sets Sync); sync true / false; stereoDeg 0..180 (0 = both channels sweep together, "
+ + "180 = opposite); centerHz 50..5000 (the middle of the sweep); depthOctaves 0..3 (± around Center); feedbackPercent "
+ + "−95..+95 (positive sharpens the peaks, negative moves and widens the notches, past ±85 it whistles); mixPercent 0..100 "
+ + "(50 = the deepest notches). Returns the device as read back.")]
+ public Task<PhaserReading> SetPhaser(int trackId, int deviceIndex, int? stages = null, string? waveform = null, double? rateHz = null,
+ string? division = null, bool? sync = null, double? stereoDeg = null, double? centerHz = null, double? depthOctaves = null,
+ double? feedbackPercent = null, double? mixPercent = null) => Mutate(() =>
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 24) throw new ArgumentException("not a Nota Phaser (kind 24)");
+ void S(int p, double v) => ForgeSet(trackId, deviceIndex, p, v);
+ if (stages is { } st)
+ {
+ int i = Array.IndexOf(PhaserStages, st);
+ if (i < 0) throw new ArgumentException("stages must be 2, 4, 6, 8 or 12");
+ S(9, i / 4.0);
+ }
+ if (waveform is not null)
+ {
+ int w = waveform.Trim().ToLowerInvariant() switch
+ {
+ "sine" or "sin" => 0, "triangle" or "tri" => 1, "saw" or "sawtooth" => 2,
+ _ => throw new ArgumentException("waveform must be Sine, Triangle or Saw"),
+ };
+ S(5, w / 2.0);
+ }
+ if (rateHz is { } hz) { S(6, 0); S(0, Math.Log(Math.Clamp(hz, 0.02, 8) / 0.02) / Math.Log(400)); }
+ if (sync is { } sy) S(6, sy ? 1 : 0);
+ if (division is not null)
+ {
+ int d = Array.IndexOf(PhaserDivs, division.Trim().ToUpperInvariant());
+ if (d < 0) throw new ArgumentException("division must be one of " + string.Join(", ", PhaserDivs));
+ S(6, 1); S(7, d / 8.0);
+ }
+ if (stereoDeg is { } sd) S(8, Math.Clamp(sd, 0, 180) / 180);
+ if (centerHz is { } ch) S(1, Math.Log(Math.Clamp(ch, 50, 5000) / 50) / Math.Log(100));
+ if (depthOctaves is { } dp) S(2, Math.Clamp(dp, 0, 3) / 3);
+ if (feedbackPercent is { } fp) S(3, 0.5 + Math.Clamp(fp, -95, 95) / 190);
+ if (mixPercent is { } mp) S(4, mp / 100);
+ return PhaserRead(trackId, deviceIndex);
+ });
+
public sealed record DynEqBand(int Band, bool On, string Type, double FreqHz, double GainDb, double Q, string Mode, double ThresholdDb,
double RangeDb, double AttackMs, double ReleaseMs, string Key, bool Dynamic, double LevelDb, double GainNowDb, double ResponseDb);
public sealed record DynEqSpectrumBand(double Hz, double Db);
diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
index 62e43379..69429834 100644
--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
@@ -255,6 +255,7 @@ public sealed partial class BrowserViewModel : ObservableObject
new() { Name = "Nota Forge", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 17, Sub = "saturator" },
new() { Name = "Nota Orbit", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 9, Sub = "auto-pan" },
new() { Name = "Nota Flanger", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 23, Sub = "flanger" },
+ new() { Name = "Nota Phaser", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 24, Sub = "phaser" },
new() { Name = "Nota Auto Shift", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 10, Sub = "pitch correction" },
new() { Name = "Nota Beat Repeat", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 11, Sub = "glitch & repeats" },
new() { Name = "Nota Crush", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 12, Sub = "bit crusher" },
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index 4fc89fa4..e79ed602 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -23,6 +23,7 @@
#include "Chamber.h"
#include "Lens.h"
#include "Flanger.h"
+#include "Phaser.h"
#include "Prism.h"
#include "Ceiling.h"
#include "Strata.h"
@@ -448,6 +449,7 @@ int32_t Engine::addTrackBuiltinDevice(int32_t trackId, int32_t kind) {
else if (kind == 21) dev = std::make_shared<Prism>();
else if (kind == 22) dev = std::make_shared<Lens>();
else if (kind == 23) dev = std::make_shared<Flanger>();
+ else if (kind == 24) dev = std::make_shared<Phaser>();
else return -1;
dev->setSampleRate(transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0, kMaxBlock);
if (kind == 5) if (auto* rk = dynamic_cast<RackDevice*>(dev.get())) rk->addChain(-1); // one pass-through chain
@@ -514,6 +516,7 @@ std::shared_ptr<Device> Engine::cloneDevice(const Device& src) const {
case 21: d = std::make_shared<Prism>(); break;
case 22: d = std::make_shared<Lens>(); break;
case 23: d = std::make_shared<Flanger>(); break;
+ case 24: d = std::make_shared<Phaser>(); break;
default: d = src.clone(); break; // hosted plugin
}
if (!d) return nullptr;
@@ -592,6 +595,7 @@ static std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {
case 21: return std::make_shared<Prism>();
case 22: return std::make_shared<Lens>();
case 23: return std::make_shared<Flanger>();
+ case 24: return std::make_shared<Phaser>();
default: return nullptr; // Rack / plugin: no simple per-param default
}
}
diff --git a/src/native/nota.engine/src/Phaser.h b/src/native/nota.engine/src/Phaser.h
new file mode 100644
index 00000000..f9b6532f
--- /dev/null
+++ b/src/native/nota.engine/src/Phaser.h
@@ -0,0 +1,481 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Built-in Nota Phaser (device kind 24, mockup "Nota Phaser") — a chain of first-order all-pass
+// stages whose corner frequency an LFO sweeps. Per channel:
+//
+// A(z) = Π_N (a + z⁻¹) / (1 + a·z⁻¹), a = (tan(π·fc/sr) − 1) / (tan(π·fc/sr) + 1)
+// w = x + Feedback · y (the chain's output fed back, solved delay-free)
+// y = A · w
+// wet = ±y (the wet polarity follows the feedback's sign)
+// out = (dry · x + wet_gain · wet) / (dry + wet_gain)
+//
+// Each stage turns the phase 0 → −π, so N stages reach −Nπ and, summed with the dry signal, cut
+// N/2 notches where the phase is an odd multiple of π (positive feedback) — or N/2 − 1 where it
+// is an even multiple (negative feedback flips the wet polarity with it, so the notches move and
+// widen instead of the comb flattening out). The loop is solved without a unit delay: every stage
+// is y = a·x + s, so the chain is y = g·w + S (g = aᴺ) and y = (g·x + S) / (1 − fb·g), which
+// makes the response exactly A / (1 − fb·A) — the curve the card draws.
+//
+// fc(t) = Center · 2^(3 · Depth · lfo(t)) Center 50 Hz … 5 kHz (exponential), ±3 oct at Depth 1
+// LFO: Sine / Triangle / Saw, free (Rate 0.02 … 8 Hz) or Sync (Division 4/1 … 1/16 incl. dotted
+// and triplet). In Sync the LFO locks to the song position while the transport plays and restarts
+// on the bar (a cycle longer than a bar restarts on the span of bars that holds it); stopped, it
+// free-runs at the synced rate. Stereo offsets the right channel's LFO 0 … 180°.
+// Stages: 2 / 4 / 6 / 8 / 12. A change fades the wet path out and back in (~6 ms) so it doesn't click.
+// Mix: 0 = dry, 0.5 = dry and wet equal (the deepest notches), 1 = wet only (phase shift alone).
+//
+// Center, Depth, Feedback and Mix glide over ~15 ms so automation doesn't zipper; the coefficients
+// are recomputed every 4 samples.
+//
+// All params are normalized 0..1 and APPEND ONLY. Persistence / automation / clone flow
+// generically through the base Device.
+// Telemetry (scopeRead): kTele live values (levels, fc now per channel, the LFO's place in its
+// two-cycle window, the rate, the tempo, the notches / null / peak).
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = restart the LFO (free run: from phase 0), 1 = clear the stages (stops a
+// whistling loop), 2 = reset the meters.
+// Header-only, allocation-free, JUCE-free.
+
+#pragma once
+
+#include "Device.h"
+#include "TransportInfo.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <string>
+
+namespace nota {
+
+class Phaser : public Device {
+public:
+ // Param layout — order is the persisted/automation layout. APPEND ONLY.
+ enum { Rate = 0, Center, Depth, Feedback, Mix, Waveform, Sync, Division, Stereo, Stages, kNumParams };
+
+ // Telemetry slots (scopeRead).
+ enum {
+ S_InPeak = 0, // input peak (300 ms fall), dBFS
+ S_OutPeakL, // output peak, left (300 ms fall), dBFS
+ S_OutPeakR, // output peak, right, dBFS
+ S_FcL, // the left corner frequency now, Hz
+ S_FcR, // the right corner frequency now, Hz
+ S_WinPhase, // the LFO's place in its two-cycle window, 0..2 (cycles)
+ S_RateHz, // the LFO rate now, Hz (Sync: from the tempo)
+ S_Bpm, // the tempo the Sync rate follows
+ S_Playing, // 1 while the transport plays
+ S_Locked, // 1 while Sync is on and the LFO is locked to the song position
+ S_SampleRate,
+ S_CenterHz, // the Center param, Hz (the middle of the sweep)
+ S_FcMin, // the sweep's lowest / highest corner, Hz
+ S_FcMax,
+ S_NotchHz, // the first notch of the left channel now, Hz
+ S_NotchMinHz, // the first notch's sweep, Hz (at fc min … fc max)
+ S_NotchMaxHz,
+ S_NullDb, // how deep the notches go, dB
+ S_PeakDb, // the peaks between them, dB
+ S_DivBeats, // the Sync division, beats per cycle
+ S_BarBeats, // beats per bar (the restart span's unit)
+ S_Cpu, // share of real time spent in process()
+ S_Signal, // 1 while signal comes in (above −70 dBFS)
+ S_Cycles, // LFO cycles since load / the last restart (free run) or the song cycle (Sync)
+ S_Stages, // the all-pass stages running
+ S_Notches, // the notches they cut (N/2, or N/2 − 1 with negative feedback)
+ kTele = 32
+ };
+
+ static constexpr int kDivs = 9;
+ // Sync divisions, slowest → fastest: beats per cycle, and their names.
+ static constexpr double kDivBeats[kDivs] = { 16.0, 8.0, 4.0, 2.0, 1.5, 1.0, 2.0 / 3.0, 0.5, 0.25 };
+ static constexpr const char* kDivNames[kDivs] = { "4/1", "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/16" };
+ static constexpr int kDefaultDiv = 2; // 1/1
+
+ static constexpr int kStageOpts = 5;
+ static constexpr int kStageCounts[kStageOpts] = { 2, 4, 6, 8, 12 };
+ static constexpr int kMaxStages = 12;
+
+ // Ranges (mirrored by the card and MCP).
+ static constexpr double kRateLo = 0.02, kRateHi = 8.0; // Hz, exponential
+ static constexpr double kCenterLo = 50.0, kCenterHi = 5000.0; // Hz, exponential
+ static constexpr double kFbMax = 0.95; // feedback ±95 %
+ static constexpr double kDepthOct = 3.0; // fc swings ±3 oct at Depth 1
+
+ Phaser() {
+ p_[Rate].store(0.5f); // 0.40 Hz
+ p_[Center].store(0.602f); // 800 Hz
+ p_[Depth].store(0.70f); // ±2.1 oct
+ p_[Feedback].store((float)(0.5 + 0.40 / (2.0 * kFbMax))); // +40 %
+ p_[Mix].store(0.50f);
+ p_[Waveform].store(0.0f); // Sine
+ p_[Sync].store(0.0f); // Free (Hz)
+ p_[Division].store((float)kDefaultDiv / (kDivs - 1));
+ p_[Stereo].store(0.5f); // 90°
+ p_[Stages].store(0.25f); // 4 stages
+ setSampleRate(44100.0, 0);
+ }
+
+ void setSampleRate(double sr, int32_t /*maxBlock*/) override {
+ sr_ = sr > 0 ? sr : 44100.0;
+ srA_.store((float)sr_, std::memory_order_relaxed);
+ cycle_ = 0; frac_ = 0.0;
+ clearStages();
+ snap_ = true;
+ resetMeters();
+ }
+
+ // Musical clock for Sync (engine calls this before process()).
+ void setTransport(double beatStart, double spb, bool playing) override {
+ beatStart_ = beatStart; spb_ = spb > 0 ? spb : 0.0; playing_ = playing;
+ }
+ void setTransportInfo(const TransportInfo& ti) override {
+ if (ti.tsNum > 0 && ti.tsDenom > 0) barBeats_ = std::clamp(ti.tsNum * 4.0 / ti.tsDenom, 0.5, 64.0);
+ }
+
+ void process(float* buf, int32_t frames) override {
+ const auto t0 = std::chrono::steady_clock::now();
+ if (restartReq_.exchange(false, std::memory_order_acquire)) { cycle_ = 0; frac_ = 0.0; }
+ if (clearReq_.exchange(false, std::memory_order_acquire)) clearStages();
+ if (resetReq_.exchange(false, std::memory_order_acquire)) resetMeters();
+
+ const int wave = waveIndex();
+ const double lc = std::log2(centerHz());
+ const double depth = std::clamp((double)get(Depth), 0.0, 1.0);
+ const double fb = feedback();
+ const double mix = std::clamp((double)get(Mix), 0.0, 1.0);
+ const double dryT = std::min(1.0, 2.0 * (1.0 - mix)), wetT = std::min(1.0, 2.0 * mix);
+ const double phOff = stereoDeg() / 360.0;
+ const int stT = stageCount();
+ const bool sync = get(Sync) >= 0.5f;
+ const double div = kDivBeats[divIndex()];
+ const double spb = spb_ > 0.0 ? spb_ : sr_ * 0.5; // 120 BPM until the engine says otherwise
+ const double rateHz = sync ? sr_ / (spb * div) : rateFreeHz();
+ const double inc = rateHz / sr_;
+ const bool locked = sync && playing_ && spb_ > 0.0;
+ const double span = barBeats_ * std::max(1.0, std::ceil(div / barBeats_ - 1e-9));
+ const double sm = 1.0 - std::exp(-1.0 / (0.015 * sr_)); // ~15 ms parameter glide
+ const double fade = 1.0 / (0.003 * sr_); // ~3 ms each way for a stage change
+ const double fcHi = std::log2(0.45 * sr_), fcLo = std::log2(10.0);
+
+ const double wetSignT = fb < 0.0 ? -wetT : wetT;
+ if (snap_) { lcS_ = lc; depthS_ = depth; fbS_ = fb; dryS_ = dryT; wetS_ = wetSignT; stages_ = stT; stGain_ = 1.0; snap_ = false; }
+
+ float inPk = 0.0f, outPkL = 0.0f, outPkR = 0.0f;
+ for (int32_t i = 0; i < frames; ++i) {
+ if (locked) {
+ const double beat = beatStart_ + (double)i / spb_;
+ const double spans = std::floor(beat / span);
+ const double c = (beat - spans * span) / div;
+ const double k = std::floor(c);
+ cycle_ = (int64_t)spans * 4096 + (int64_t)k;
+ frac_ = c - k;
+ }
+ lcS_ += sm * (lc - lcS_);
+ depthS_ += sm * (depth - depthS_);
+ fbS_ += sm * (fb - fbS_);
+ dryS_ += sm * (dryT - dryS_);
+ wetS_ += sm * (wetSignT - wetS_);
+
+ // A stage-count change: fade the wet path out, switch on silence, fade back in.
+ if (stT != stages_) {
+ stGain_ -= fade;
+ if (stGain_ <= 0.0) {
+ stGain_ = 0.0;
+ for (int s = std::min(stages_, stT); s < kMaxStages; ++s) sL_[s] = sR_[s] = 0.0;
+ stages_ = stT;
+ }
+ } else if (stGain_ < 1.0) stGain_ = std::min(1.0, stGain_ + fade);
+
+ if ((ctl_++ & 3) == 0) {
+ const double swing = kDepthOct * depthS_;
+ fcL_ = std::exp2(std::clamp(lcS_ + swing * lfo(wave, frac_), fcLo, fcHi));
+ fcR_ = std::exp2(std::clamp(lcS_ + swing * lfo(wave, frac_ + phOff), fcLo, fcHi));
+ aL_ = coef(fcL_); aR_ = coef(fcR_);
+ }
+
+ const float xL = buf[i * 2], xR = buf[i * 2 + 1];
+ inPk = std::max(inPk, std::max(std::fabs(xL), std::fabs(xR)));
+ const double yL = chain(sL_, aL_, xL, fbS_);
+ const double yR = chain(sR_, aR_, xR, fbS_);
+
+ const double wg = wetS_ * stGain_;
+ const double norm = 1.0 / std::max(dryS_ + std::fabs(wetS_), 1e-3);
+ const float oL = (float)((dryS_ * xL + wg * yL) * norm);
+ const float oR = (float)((dryS_ * xR + wg * yR) * norm);
+ buf[i * 2] = oL; buf[i * 2 + 1] = oR;
+ outPkL = std::max(outPkL, std::fabs(oL));
+ outPkR = std::max(outPkR, std::fabs(oR));
+
+ if (!locked) {
+ frac_ += inc;
+ if (frac_ >= 1.0) { const double wr = std::floor(frac_); frac_ -= wr; cycle_ += (int64_t)wr; }
+ }
+ }
+
+ if (frames > 0) {
+ const float fall = std::pow(10.0f, -(20.0f * frames / (0.3f * (float)sr_)) / 20.0f);
+ inPkM_ = std::max(inPk, inPkM_ * fall);
+ outPkLM_ = std::max(outPkL, outPkLM_ * fall);
+ outPkRM_ = std::max(outPkR, outPkRM_ * fall);
+ fcLA_.store((float)fcL_, std::memory_order_relaxed);
+ fcRA_.store((float)fcR_, std::memory_order_relaxed);
+ }
+ inPkA_.store(db(inPkM_), std::memory_order_relaxed);
+ outPkLA_.store(db(outPkLM_), std::memory_order_relaxed);
+ outPkRA_.store(db(outPkRM_), std::memory_order_relaxed);
+ cycleA_.store(cycle_, std::memory_order_relaxed);
+ fracA_.store((float)frac_, std::memory_order_relaxed);
+ rateA_.store((float)rateHz, std::memory_order_relaxed);
+ bpmA_.store((float)(60.0 * sr_ / spb), std::memory_order_relaxed);
+ playingA_.store(playing_ ? 1 : 0, std::memory_order_relaxed);
+ lockedA_.store(locked ? 1 : 0, std::memory_order_relaxed);
+ barA_.store((float)barBeats_, std::memory_order_relaxed);
+ if (frames > 0) {
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store((float)cpuS_, std::memory_order_relaxed);
+ }
+ }
+
+ enum { A_Restart = 0, A_Clear = 1, A_ResetMeters = 2 }; // deviceAction ids
+ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {
+ if (id == A_Restart) restartReq_.store(true, std::memory_order_release);
+ else if (id == A_Clear) clearReq_.store(true, std::memory_order_release);
+ else if (id == A_ResetMeters) resetReq_.store(true, std::memory_order_release);
+ }
+
+ // Telemetry block. Called from the UI / MCP thread; lock-free against audio.
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ float t[kTele] = {};
+ const int64_t cyc = cycleA_.load(std::memory_order_relaxed);
+ const double fr = fracA_.load(std::memory_order_relaxed);
+ const int64_t base = cyc - (((cyc % 2) + 2) % 2); // the window starts on an even cycle
+ const double sr = srA_.load(std::memory_order_relaxed);
+ const double ch = centerHz(), dep = std::clamp((double)get(Depth), 0.0, 1.0);
+ const double fb = feedback();
+ const int n = stageCount();
+ t[S_InPeak] = inPkA_.load(std::memory_order_relaxed);
+ t[S_OutPeakL] = outPkLA_.load(std::memory_order_relaxed);
+ t[S_OutPeakR] = outPkRA_.load(std::memory_order_relaxed);
+ t[S_FcL] = fcLA_.load(std::memory_order_relaxed);
+ t[S_FcR] = fcRA_.load(std::memory_order_relaxed);
+ if (t[S_FcL] <= 0.0f) t[S_FcL] = t[S_FcR] = (float)ch; // before the first block
+ t[S_WinPhase] = (float)((double)(cyc - base) + fr);
+ t[S_RateHz] = rateA_.load(std::memory_order_relaxed);
+ t[S_Bpm] = bpmA_.load(std::memory_order_relaxed);
+ t[S_Playing] = (float)playingA_.load(std::memory_order_relaxed);
+ t[S_Locked] = (float)lockedA_.load(std::memory_order_relaxed);
+ t[S_SampleRate] = (float)sr;
+ t[S_CenterHz] = (float)ch;
+ t[S_FcMin] = (float)(ch * std::exp2(-kDepthOct * dep));
+ t[S_FcMax] = (float)(ch * std::exp2(kDepthOct * dep));
+ t[S_NotchHz] = (float)firstNotchHz(t[S_FcL], n, fb, sr);
+ t[S_NotchMinHz] = (float)firstNotchHz(t[S_FcMin], n, fb, sr);
+ t[S_NotchMaxHz] = (float)firstNotchHz(t[S_FcMax], n, fb, sr);
+ const double mix = std::clamp((double)get(Mix), 0.0, 1.0);
+ const double dry = std::min(1.0, 2.0 * (1.0 - mix)), wet = std::min(1.0, 2.0 * mix);
+ t[S_NullDb] = (float)(20.0 * std::log10(std::max(mag(dry, wet, fb, fb < 0.0 ? 2.0 * kPi : kPi), 1e-4)));
+ t[S_PeakDb] = (float)(20.0 * std::log10(std::max(mag(dry, wet, fb, fb >= 0.0 ? 0.0 : kPi), 1e-4)));
+ t[S_DivBeats] = (float)kDivBeats[divIndex()];
+ t[S_BarBeats] = barA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_Signal] = t[S_InPeak] > -70.0f ? 1.0f : 0.0f;
+ t[S_Cycles] = (float)cyc;
+ t[S_Stages] = (float)n;
+ t[S_Notches] = (float)notchCount(n, fb);
+ int32_t k = 0;
+ for (int i = 0; i < kTele && k < maxSamples; ++i) out[k++] = t[i];
+ return k;
+ }
+
+ const char* displayName() const override { return "Nota Phaser"; }
+ int32_t builtinKind() const override { return 24; }
+
+ int32_t paramCount() const override { return kNumParams; }
+ const char* paramName(int32_t i) const override {
+ switch (i) {
+ case Rate: return "Rate"; case Center: return "Center"; case Depth: return "Depth";
+ case Feedback: return "Feedback"; case Mix: return "Mix"; case Waveform: return "Waveform";
+ case Sync: return "Sync"; case Division: return "Division"; case Stereo: return "Stereo";
+ case Stages: return "Stages";
+ default: return "";
+ }
+ }
+ float paramMin(int32_t /*i*/) const override { return 0.0f; }
+ float paramMax(int32_t /*i*/) const override { return 1.0f; }
+ float getParam(int32_t i) const override {
+ return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f;
+ }
+ void setParam(int32_t i, float v) override {
+ if (i >= 0 && i < kNumParams) p_[i].store(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 {
+ static const char* waves[3] = { "Sine", "Triangle", "Saw" };
+ char b[1600];
+ if (id == 0) {
+ const int n = stageCount();
+ std::string s;
+ std::snprintf(b, sizeof b, "%d stages (%d notches) - %s", n, notchCount(n, feedback()), waves[waveIndex()]);
+ s += b;
+ if (get(Sync) >= 0.5f) std::snprintf(b, sizeof b, " - sync %s", kDivNames[divIndex()]);
+ else std::snprintf(b, sizeof b, " - %.2f Hz", rateFreeHz());
+ s += b;
+ std::snprintf(b, sizeof b, " - stereo %.0f deg - center %.0f Hz - depth +/-%.1f oct - feedback %+.0f %% (%s) - mix %.0f %%",
+ stereoDeg(), centerHz(), kDepthOct * get(Depth), feedback() * 100.0, modeWord(), get(Mix) * 100.0f);
+ s += b;
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ auto lv = [](float v) { char t[24]; if (v <= -119.0f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", v); return std::string(t); };
+ std::snprintf(b, sizeof b,
+ "LFO %.2f Hz (period %.0f ms)%s - window phase %.2f of 2 cycles - fc L %.0f Hz, R %.0f Hz "
+ "(sweep %.0f .. %.0f Hz) - %d stages, %d notches - first notch %.0f Hz (sweeps %.0f .. %.0f Hz), "
+ "%.1f dB deep - peaks %+.1f dB - in %s dBFS - out L %s, R %s dBFS - %.1f BPM, bar %.2g beats - "
+ "transport %s - CPU %.2f %%",
+ sc[S_RateHz], 1000.0 / std::max(1e-3f, sc[S_RateHz]),
+ sc[S_Locked] > 0.5f ? " locked to the song" : get(Sync) >= 0.5f ? " free-running at the synced rate" : "",
+ sc[S_WinPhase], sc[S_FcL], sc[S_FcR], sc[S_FcMin], sc[S_FcMax], (int)sc[S_Stages], (int)sc[S_Notches],
+ sc[S_NotchHz], sc[S_NotchMinHz], sc[S_NotchMaxHz], sc[S_NullDb], sc[S_PeakDb], lv(sc[S_InPeak]).c_str(),
+ lv(sc[S_OutPeakL]).c_str(), lv(sc[S_OutPeakR]).c_str(), sc[S_Bpm], sc[S_BarBeats],
+ sc[S_Playing] > 0.5f ? "playing" : "stopped", sc[S_Cpu] * 100.0f);
+ return b;
+ }
+ if (id == 2) {
+ std::string divs, sts;
+ for (int i = 0; i < kDivs; ++i) {
+ std::snprintf(b, sizeof b, "%s%.3f = %s", i ? ", " : "", (double)i / (kDivs - 1), kDivNames[i]);
+ divs += b;
+ }
+ for (int i = 0; i < kStageOpts; ++i) {
+ std::snprintf(b, sizeof b, "%s%.2f = %d", i ? ", " : "", (double)i / (kStageOpts - 1), kStageCounts[i]);
+ sts += b;
+ }
+ return "All params are normalized 0..1. Rate: the free LFO rate, exponential 0.02 Hz (0) .. 8 Hz (1) "
+ "(0.269 = 0.1 Hz, 0.384 = 0.2 Hz, 0.5 = 0.4 Hz, 0.537 = 0.5 Hz, 0.653 = 1 Hz, 0.769 = 2 Hz, 0.884 = 4 Hz). "
+ "Center: the middle of the sweep, exponential 50 Hz (0) .. 5 kHz (1) (0.151 = 100 Hz, 0.301 = 200 Hz, "
+ "0.5 = 500 Hz, 0.602 = 800 Hz, 0.65 = 1 kHz, 0.801 = 2 kHz, 1 = 5 kHz). Depth: how far the LFO swings the "
+ "corner, 0..1 = 0 .. +/-3 octaves - fc = Center * 2^(3 * Depth * lfo). Feedback: bipolar, (v - 0.5) * 1.9 = "
+ "-95 % .. +95 % (0.5 = none, 0.711 = +40 %, 0.184 = -60 %); positive sharpens the peaks between the notches, "
+ "negative also flips the wet polarity so the notches move and widen (one fewer); past 85 % the phaser "
+ "whistles. Mix: 0 = dry, 0.5 = dry and wet equal (the deepest notches), 1 = wet only (phase shift, almost no "
+ "notches). Waveform: 0 Sine, 0.5 Triangle, 1 Saw. Stereo: the right LFO's offset from the left, 0..1 = "
+ "0..180 deg (0 = mono sweep, 0.5 = 90 deg, 1 = opposite). Stages (all-pass stages; notches = stages / 2): "
+ + sts + ". Sync: >= 0.5 takes the rate from the tempo (Division) and locks the LFO to the song position "
+ "while the transport plays, restarting on the bar. Division (with Sync): " + divs + ".";
+ }
+ return {};
+ }
+
+ // ---- shared with the card / MCP through the guide above ----------------------------
+ int waveIndex() const { return std::clamp((int)std::lround(get(Waveform) * 2.0f), 0, 2); }
+ int divIndex() const { return std::clamp((int)std::lround(get(Division) * (kDivs - 1)), 0, kDivs - 1); }
+ int stageIndex() const { return std::clamp((int)std::lround(get(Stages) * (kStageOpts - 1)), 0, kStageOpts - 1); }
+ int stageCount() const { return kStageCounts[stageIndex()]; }
+ double rateFreeHz() const { return expMap(get(Rate), kRateLo, kRateHi); }
+ double centerHz() const { return expMap(get(Center), kCenterLo, kCenterHi); }
+ double feedback() const { return (std::clamp((double)get(Feedback), 0.0, 1.0) - 0.5) * 2.0 * kFbMax; }
+ double stereoDeg() const { return std::clamp((double)get(Stereo), 0.0, 1.0) * 180.0; }
+ static int notchCount(int n, double fb) { return fb < 0.0 ? n / 2 - 1 : n / 2; }
+
+ // |dry ± wet·H(θ)| / (dry + wet), H = e^{−jθ} / (1 − fb·e^{−jθ}), θ = the chain's phase lag —
+ // the phaser's magnitude (the wet polarity follows the feedback's sign, as in process()).
+ static double mag(double dry, double wet, double fb, double th) {
+ const double w = fb < 0.0 ? -wet : wet, c = std::cos(th), s = std::sin(th);
+ const double nr = w * c, ni = -w * s, dr = 1.0 - fb * c, di = fb * s, den = dr * dr + di * di;
+ const double re = dry + (nr * dr + ni * di) / den, im = (ni * dr - nr * di) / den;
+ return std::sqrt(re * re + im * im) / std::max(dry + wet, 0.001);
+ }
+ // The chain's phase lag at f for a corner fc: N · 2·atan(tan(πf/sr) / tan(πfc/sr)) (bilinear all-pass).
+ static double phaseLag(double f, double fc, int n, double sr) {
+ const double nyq = 0.5 * sr;
+ const double tf = std::tan(kPi * std::min(f, nyq * 0.9999) / sr), tc = std::tan(kPi * std::min(fc, nyq * 0.9999) / sr);
+ return n * 2.0 * std::atan(tf / std::max(tc, 1e-9));
+ }
+ // The frequency where the chain's lag reaches θ (inverse of phaseLag).
+ static double freqAtLag(double th, double fc, int n, double sr) {
+ const double tc = std::tan(kPi * std::min(fc, 0.49999 * sr) / sr);
+ return sr / kPi * std::atan(tc * std::tan(th / (2.0 * n)));
+ }
+ // The first notch: lag π (positive feedback) or 2π (negative).
+ static double firstNotchHz(double fc, int n, double fb, double sr) {
+ return freqAtLag(fb < 0.0 ? 2.0 * kPi : kPi, fc, n, sr);
+ }
+
+private:
+ static constexpr double kPi = 3.14159265358979323846;
+
+ const char* modeWord() const {
+ const double fb = feedback();
+ return std::fabs(fb) >= 0.85 ? "resonant" : fb <= -0.15 ? "negative" : fb >= 0.15 ? "positive" : "clean";
+ }
+
+ double coef(double fc) const {
+ const double t = std::tan(kPi * fc / sr_);
+ return (t - 1.0) / (t + 1.0);
+ }
+
+ // One channel through the chain with its feedback loop solved delay-free: each stage is
+ // y = a·x + s (s' = x − a·y), so the chain is y = g·w + S and w = x + fb·y.
+ double chain(double* s, double a, double x, double fb) const {
+ const int n = stages_;
+ double g = 1.0, S = 0.0;
+ for (int k = 0; k < n; ++k) { S = a * S + s[k]; g *= a; }
+ const double y = (g * x + S) / (1.0 - fb * g);
+ double v = x + fb * y;
+ for (int k = 0; k < n; ++k) {
+ const double o = a * v + s[k];
+ s[k] = sanitize(v - a * o);
+ v = o;
+ }
+ return v;
+ }
+
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ static double sanitize(double v) { return std::isfinite(v) && std::fabs(v) > 1e-20 ? std::clamp(v, -64.0, 64.0) : 0.0; }
+
+ // LFO in [−1, 1] at phase p (cycles; wraps) — the mockup's shapes: all start at 0 rising.
+ static double lfo(int wave, double p) {
+ const double f = p - std::floor(p);
+ if (wave == 0) return std::sin(2.0 * kPi * f);
+ if (wave == 1) return f < 0.25 ? 4.0 * f : f < 0.75 ? 2.0 - 4.0 * f : 4.0 * f - 4.0;
+ const double g = f + 0.5;
+ return 2.0 * (g - std::floor(g)) - 1.0;
+ }
+
+ void clearStages() { for (int k = 0; k < kMaxStages; ++k) sL_[k] = sR_[k] = 0.0; }
+ void resetMeters() { inPkM_ = outPkLM_ = outPkRM_ = 0.0f; }
+
+ double sr_ = 44100.0;
+ std::atomic<float> p_[kNumParams] = {};
+ double sL_[kMaxStages] = {}, sR_[kMaxStages] = {};
+ double aL_ = 0.0, aR_ = 0.0, fcL_ = 800.0, fcR_ = 800.0;
+ uint32_t ctl_ = 0;
+ int stages_ = 4;
+ double stGain_ = 1.0;
+ int64_t cycle_ = 0;
+ double frac_ = 0.0;
+ bool snap_ = true;
+ double lcS_ = 9.64, depthS_ = 0.7, fbS_ = 0.4, dryS_ = 1.0, wetS_ = 1.0;
+ double beatStart_ = 0.0, spb_ = 0.0, barBeats_ = 4.0;
+ bool playing_ = false;
+ float inPkM_ = 0.0f, outPkLM_ = 0.0f, outPkRM_ = 0.0f;
+ double cpuS_ = 0.0;
+ std::atomic<bool> restartReq_{false}, clearReq_{false}, resetReq_{false};
+ std::atomic<float> srA_{44100.0f}, inPkA_{-120.0f}, outPkLA_{-120.0f}, outPkRA_{-120.0f};
+ std::atomic<float> fcLA_{0.0f}, fcRA_{0.0f}, fracA_{0.0f}, rateA_{0.4f}, bpmA_{120.0f}, barA_{4.0f}, cpuA_{0.0f};
+ std::atomic<int64_t> cycleA_{0};
+ std::atomic<int> playingA_{0}, lockedA_{0};
+};
+
+} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 1184b864..4155bed7 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -9038,6 +9038,234 @@ Console.WriteLine("-- Nota Flanger (effect kind 23) --");
}
}
+// ===================== Nota Phaser (effect kind 24) =====================
+Console.WriteLine("-- Nota Phaser (effect kind 24) --");
+{
+ // Params (Phaser.h): 0 Rate, 1 Center, 2 Depth, 3 Feedback, 4 Mix, 5 Waveform, 6 Sync, 7 Division, 8 Stereo, 9 Stages.
+ // Scope: 0 in, 1 out L, 2 out R (dBFS) · 3 / 4 fc L / R Hz · 5 window phase · 6 rate Hz · 7 BPM · 8 playing ·
+ // 9 locked · 10 sample rate · 11 center Hz · 12 / 13 fc min / max · 14 notch Hz · 15 / 16 notch sweep ·
+ // 17 null dB · 18 peak dB · 19 division beats · 20 bar beats · 21 CPU · 22 signal · 23 cycles · 24 stages · 25 notches.
+ using var pe = new NotaEngine();
+ int pt = pe.AddAudioTrack();
+ pe.AddAudioClip(pt, wav, 0.0); // 1 s sine @ 440 Hz
+ int pdi = pe.AddBuiltinDevice(pt, 24);
+ Check(pdi >= 0, "add Nota Phaser device");
+ Check(pe.DeviceName(pt, pdi) == "Nota Phaser", $"device is Nota Phaser (got '{pe.DeviceName(pt, pdi)}')");
+ Check(pe.TrackDeviceBuiltinKind(pt, pdi) == 24, "device reports builtin kind 24");
+ int ppc = pe.DeviceParamCount(pt, pdi);
+ Check(ppc == 10, $"Nota Phaser exposes 10 params ({ppc})");
+ var pnames = Enumerable.Range(0, ppc).Select(i => pe.DeviceParamName(pt, pdi, i)).ToArray();
+ Check(string.Join(",", pnames) == "Rate,Center,Depth,Feedback,Mix,Waveform,Sync,Division,Stereo,Stages", $"param layout ({string.Join(",", pnames)})");
+ Check(Math.Abs(pe.DeviceParamDefault(pt, pdi, 1) - 0.602f) < 1e-3f && Math.Abs(pe.DeviceParamDefault(pt, pdi, 3) - (0.5f + 0.4f / 1.9f)) < 1e-3f
+ && Math.Abs(pe.DeviceParamDefault(pt, pdi, 9) - 0.25f) < 1e-3f, "defaults: 800 Hz, feedback +40 %, 4 stages (Script 45)");
+ pe.DeviceSetParam(pt, pdi, 2, 0.42f);
+ Check(Math.Abs(pe.DeviceGetParam(pt, pdi, 2) - 0.42f) < 1e-4f, "device param set/get round-trips");
+
+ var pbuf = new float[4096 * 2];
+ var psc = new float[32];
+ bool PFinite() { foreach (var v in pbuf) if (!float.IsFinite(v) || Math.Abs(v) > 8f) return false; return true; }
+ void PRender(int frames = 4096, double at = 0.2) { pe.Seek(at); pe.Play(); pe.RenderOffline(pbuf, frames); pe.StopTransport(); }
+ int PScope() => pe.DeviceScope(pt, pdi, psc, psc.Length);
+ float PTail() { double sum = 0; for (int i = 2048 * 2; i < 4096 * 2; i++) sum += pbuf[i] * (double)pbuf[i]; return (float)Math.Sqrt(sum / (2048 * 2)); }
+ pe.SetBpm(120);
+
+ // Every waveform and stage count renders audible + finite, incl. extreme feedback both ways.
+ for (int wv = 0; wv < 3; wv++)
+ foreach (float fbn in new[] { 0f, 0.5f, 1f })
+ {
+ pe.DeviceSetParam(pt, pdi, 5, wv / 2f);
+ pe.DeviceSetParam(pt, pdi, 3, fbn);
+ PRender();
+ Check(Rms(pbuf, 4096) > 1e-3f && PFinite(), $"Phaser wave {wv} feedback {(fbn - 0.5f) * 190:+0;-0} % is audible + stable");
+ }
+ for (int st = 0; st < 5; st++)
+ {
+ pe.DeviceSetParam(pt, pdi, 9, st / 4f);
+ PRender(); PScope();
+ int n = new[] { 2, 4, 6, 8, 12 }[st];
+ Check(Rms(pbuf, 4096) > 1e-3f && PFinite() && (int)psc[24] == n, $"{n} stages render audible + stable (scope {psc[24]:0})");
+ }
+
+ // The notches are real: 4 static stages, no feedback, dry = wet. With fc = 440 Hz the chain's lag at 440 Hz is
+ // 2π (a peak); with the corner where tan(π·440/sr) = tan(πfc/sr)·tan(π/8) the lag is π — the first notch.
+ double psr = 48000;
+ PScope(); if (psc[10] > 0) psr = psc[10];
+ float CenterNorm(double hz) => (float)(Math.Log(hz / 50) / Math.Log(100));
+ double notchFc = psr / Math.PI * Math.Atan(Math.Tan(Math.PI * 440 / psr) / Math.Tan(Math.PI / 8));
+ pe.DeviceSetParam(pt, pdi, 9, 0.25f); // 4 stages
+ pe.DeviceSetParam(pt, pdi, 2, 0f); // Depth 0 → static
+ pe.DeviceSetParam(pt, pdi, 3, 0.5f); // no feedback
+ pe.DeviceSetParam(pt, pdi, 4, 0.5f); // dry = wet
+ pe.DeviceSetParam(pt, pdi, 1, CenterNorm(notchFc));
+ PRender(); PRender();
+ float pNotch = PTail();
+ PScope();
+ Check(Math.Abs(psc[14] - 440f) < 3f && (int)psc[25] == 2, $"scope: first notch {psc[14]:0} Hz at fc {psc[3]:0} Hz, {psc[25]:0} notches");
+ Check(psc[17] < -30f, $"dry = wet without feedback nulls deep ({psc[17]:0.0} dB)");
+ pe.DeviceSetParam(pt, pdi, 1, CenterNorm(440));
+ PRender(); PRender();
+ float pPass = PTail();
+ Check(pNotch < pPass * 0.1f, $"440 Hz falls into the first notch ({20 * Math.Log10(pNotch / Math.Max(1e-9f, pPass)):0.0} dB vs the peak)");
+ // Negative feedback flips the wet polarity: the 2π lag becomes a notch, π a peak.
+ pe.DeviceSetParam(pt, pdi, 3, 0.5f - 0.6f / 1.9f); // −60 %
+ PRender(); PRender();
+ float negNotch = PTail();
+ pe.DeviceSetParam(pt, pdi, 1, CenterNorm(notchFc));
+ PRender(); PRender();
+ float negPeak = PTail();
+ Check(negNotch < negPeak * 0.2f, $"negative feedback moves the notch ({20 * Math.Log10(negNotch / Math.Max(1e-9f, negPeak)):0.0} dB)");
+ PScope();
+ Check((int)psc[25] == 1 && psc[17] < -12f, $"scope: negative feedback cuts one notch fewer ({psc[25]:0}, {psc[17]:0.0} dB)");
+ pe.DeviceSetParam(pt, pdi, 3, 0.5f + 0.9f / 1.9f); // +90 %
+ PScope();
+ Check(psc[18] > 10f, $"feedback +90 % raises the peaks ({psc[18]:+0.0} dB)");
+ pe.DeviceSetParam(pt, pdi, 3, 0.5f);
+
+ // Mix 0 is dry.
+ pe.DeviceSetParam(pt, pdi, 4, 0f);
+ PRender(); PRender();
+ float pdry = PTail();
+ pe.SetDeviceBypassed(pt, pdi, true); PRender(); float pbyp = PTail(); pe.SetDeviceBypassed(pt, pdi, false);
+ Check(Math.Abs(pdry - pbyp) < pbyp * 0.01f, $"Mix 0 passes the dry signal ({pdry:0.0000} vs bypass {pbyp:0.0000})");
+ pe.DeviceSetParam(pt, pdi, 4, 0.5f);
+
+ // Depth + Stereo: the LFO sweeps fc ±3 oct, and the right channel runs offset from the left.
+ pe.DeviceSetParam(pt, pdi, 1, 0.602f);
+ pe.DeviceSetParam(pt, pdi, 2, 1f);
+ pe.DeviceSetParam(pt, pdi, 0, 1f); // 8 Hz
+ pe.DeviceSetParam(pt, pdi, 8, 1f); // 180°
+ pe.DeviceSetParam(pt, pdi, 5, 0f); // Sine: half a cycle later is the mirror
+ PRender(3001); PRender(3001);
+ PScope();
+ Check(Math.Abs(psc[12] - psc[11] / 8f) < 1f && Math.Abs(psc[13] - psc[11] * 8f) < 5f,
+ $"sweep range = Center · 2^(±3 · Depth) ({psc[12]:0} … {psc[13]:0} Hz)");
+ double lc = Math.Log2(psc[11]);
+ Check(Math.Abs((Math.Log2(psc[3]) - lc) + (Math.Log2(psc[4]) - lc)) < 0.05 && Math.Abs(psc[3] - psc[4]) > 10f,
+ $"Stereo 180°: the channels swing opposite (fcL {psc[3]:0}, fcR {psc[4]:0} Hz)");
+ pe.DeviceSetParam(pt, pdi, 8, 0f);
+ PRender(3001);
+ PScope();
+ Check(Math.Abs(psc[3] - psc[4]) < 1e-2f, $"Stereo 0°: both channels sweep together ({psc[3]:0.0} / {psc[4]:0.0})");
+
+ // Sync: the rate follows the tempo and the LFO locks to the song position.
+ pe.DeviceSetParam(pt, pdi, 6, 1f);
+ pe.DeviceSetParam(pt, pdi, 7, 5f / 8f); // 1/4 → 2 Hz at 120 BPM
+ PRender(); PScope();
+ Check(Math.Abs(psc[6] - 2f) < 1e-3f && psc[9] > 0.5f, $"Sync 1/4 at 120 BPM runs at 2 Hz, locked ({psc[6]:0.000})");
+ Check(pe.DeviceText(pt, pdi, 0).Contains("sync 1/4"), $"status names the division ('{pe.DeviceText(pt, pdi, 0)}')");
+ pe.DeviceSetParam(pt, pdi, 7, 0f); // 4/1 → 0.125 Hz
+ PRender(); PScope();
+ Check(Math.Abs(psc[6] - 0.125f) < 1e-4f, $"Sync 4/1 at 120 BPM runs at 0.125 Hz ({psc[6]:0.0000})");
+ pe.SetBpm(90);
+ pe.DeviceSetParam(pt, pdi, 7, 5f / 8f);
+ PRender(); PScope();
+ Check(Math.Abs(psc[6] - 1.5f) < 1e-3f, $"the synced rate follows a tempo change (90 BPM → {psc[6]:0.000} Hz)");
+ pe.SetBpm(120);
+ pe.DeviceSetParam(pt, pdi, 6, 0f);
+
+ // A stage change mid-signal fades instead of clicking: no sample-to-sample jump beyond the sine's own slope.
+ pe.DeviceSetParam(pt, pdi, 2, 0f);
+ pe.DeviceSetParam(pt, pdi, 9, 0f);
+ PRender();
+ pe.Seek(0.3); pe.Play(); pe.RenderOffline(pbuf, 512);
+ pe.DeviceSetParam(pt, pdi, 9, 1f);
+ pe.RenderOffline(pbuf, 4096); pe.StopTransport();
+ float jump = 0f; for (int i = 2; i < 4096 * 2; i += 2) jump = Math.Max(jump, Math.Abs(pbuf[i] - pbuf[i - 2]));
+ Check(jump < 0.12f && PFinite(), $"switching 2 → 12 stages doesn't click (max step {jump:0.000})");
+
+ // Actions: restart the LFO, clear a whistling loop.
+ pe.DeviceSetParam(pt, pdi, 0, 1f);
+ PRender(); PScope();
+ Check(psc[23] >= 1f, $"free run: cycles run ({psc[23]:0})");
+ pe.DeviceAction(pt, pdi, 0, 0, 0f);
+ PRender(32); PScope();
+ Check(psc[23] < 1f && psc[5] < 0.05f, $"device_action 0 restarts the LFO (cycle {psc[23]:0}, phase {psc[5]:0.000})");
+ pe.DeviceSetParam(pt, pdi, 1, 0f); // 50 Hz: the loop rings longest
+ pe.DeviceSetParam(pt, pdi, 3, 1f); // +95 %
+ pe.DeviceSetParam(pt, pdi, 4, 1f); // wet only
+ pe.DeviceSetParam(pt, pdi, 9, 1f); // 12 stages
+ PRender(4096, 0.9);
+ PRender(256, 3.0); float pring = Rms(pbuf, 256);
+ PRender(4096, 0.9);
+ pe.DeviceAction(pt, pdi, 1, 0, 0f);
+ PRender(256, 3.0); float pcleared = Rms(pbuf, 256);
+ Check(pring > 1e-5f && pcleared < 1e-7f, $"device_action 1 clears the ringing stages (ring {pring:0.0e0} → {pcleared:0.0e0})");
+ for (int i = 0; i < ppc; i++) pe.DeviceSetParam(pt, pdi, i, pe.DeviceParamDefault(pt, pdi, i));
+
+ Check(pe.DeviceText(pt, pdi, 1).Contains("notch") && pe.DeviceText(pt, pdi, 2).Contains("1/4T") && pe.DeviceText(pt, pdi, 2).Contains("= 12"),
+ "device text 1 = live reading, 2 = parameter guide with the division and stage tables");
+
+ // Clone.
+ pe.DeviceSetParam(pt, pdi, 3, 0.2f);
+ pe.DeviceSetParam(pt, pdi, 9, 0.75f);
+ int pdup = pe.DuplicateTrack(pt);
+ Check(pdup > 0 && pe.TrackDeviceBuiltinKind(pdup, pdi) == 24 && Math.Abs(pe.DeviceGetParam(pdup, pdi, 3) - 0.2f) < 1e-4f
+ && Math.Abs(pe.DeviceGetParam(pdup, pdi, 9) - 0.75f) < 1e-4f, "duplicate track clones the Phaser params");
+ pe.RemoveTrack(pdup);
+
+ // Automation drives Center and Stages.
+ int plane = pe.AddAutomationLane(pt, AutomationTarget.DeviceParam, pdi, 1);
+ Check(plane >= 0, "add Phaser Center automation lane");
+ pe.SetAutomationPoints(pt, plane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
+ int plane2 = pe.AddAutomationLane(pt, AutomationTarget.DeviceParam, pdi, 9);
+ pe.SetAutomationPoints(pt, plane2, new[] { new AutomationPoint(0.0, 0f), new AutomationPoint(2.0, 1f) });
+ pe.Seek(1.99); pe.Play(); pe.RenderOffline(pbuf, 4096); pe.StopTransport();
+ PScope();
+ Check(pe.DeviceGetParam(pt, pdi, 1) > 0.8f && (int)psc[24] == 12, $"automation drives Phaser Center ({pe.DeviceGetParam(pt, pdi, 1):F2}) and Stages ({psc[24]:0})");
+ pe.RemoveAutomationLane(pt, plane2);
+ pe.RemoveAutomationLane(pt, plane);
+ for (int i = 0; i < ppc; i++) pe.DeviceSetParam(pt, pdi, i, pe.DeviceParamDefault(pt, pdi, i));
+
+ // MCP: listed, read and set in units.
+ {
+ var ptools = new Nota.Mcp.Tools.DeviceTools(pe, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ Check(ptools.ListDeviceKinds().Any(k => k.Kind == 24 && k.Name == "Nota Phaser"), "MCP lists Nota Phaser (kind 24)");
+ PRender();
+ var r0 = ptools.ReadPhaser(pt, pdi).Result;
+ Check(r0.Waveform == "Sine" && !r0.Sync && r0.Stages == 4 && r0.Notches == 2 && Math.Abs(r0.CenterHz - 800) < 2
+ && Math.Abs(r0.FeedbackPercent - 40) < 0.6 && r0.Mode == "positive" && Math.Abs(r0.StereoDeg - 90) < 0.6
+ && Math.Abs(r0.RateHz - 0.4) < 0.01 && r0.Summary.Length > 0 && r0.Live.Length > 0,
+ $"MCP read_phaser reports the defaults ({r0.Stages} st, {r0.CenterHz} Hz, {r0.FeedbackPercent} %, {r0.Mode})");
+ var r1 = ptools.SetPhaser(pt, pdi, stages: 12, waveform: "tri", division: "1/4T", centerHz: 1500, depthOctaves: 1.5,
+ feedbackPercent: -60, mixPercent: 60, stereoDeg: 180).Result;
+ Check(r1.Stages == 12 && r1.Notches == 5 && r1.Waveform == "Triangle" && r1.Sync && r1.Division == "1/4T"
+ && Math.Abs(r1.CenterHz - 1500) < 2 && Math.Abs(r1.DepthOctaves - 1.5) < 0.01 && Math.Abs(r1.FeedbackPercent + 60) < 0.6
+ && r1.Mode == "negative" && Math.Abs(r1.MixPercent - 60) < 0.1 && r1.StereoDeg == 180,
+ $"MCP set_phaser writes in units ({r1.Stages} st, {r1.Division}, {r1.CenterHz} Hz, {r1.FeedbackPercent} %)");
+ var r2 = ptools.SetPhaser(pt, pdi, rateHz: 0.5).Result;
+ Check(!r2.Sync && Math.Abs(0.02 * Math.Pow(400, pe.DeviceGetParam(pt, pdi, 0)) - 0.5) < 1e-3, "set_phaser rateHz switches to free run");
+ bool threw = false, threw2 = false;
+ try { ptools.SetPhaser(pt, pdi, division: "1/5").GetAwaiter().GetResult(); } catch (ArgumentException) { threw = true; }
+ try { ptools.SetPhaser(pt, pdi, stages: 5).GetAwaiter().GetResult(); } catch (ArgumentException) { threw2 = true; }
+ Check(threw && threw2, "set_phaser rejects an unknown division or stage count");
+ for (int i = 0; i < ppc; i++) pe.DeviceSetParam(pt, pdi, i, pe.DeviceParamDefault(pt, pdi, i));
+ }
+
+ // Factory presets: ≥ 25, every named param exists, each applies in place and renders.
+ {
+ var names = new HashSet<string>(pnames);
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 24).ToList();
+ Check(mine.Count >= 25, $"Nota Phaser 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 Phaser preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(pe, p.Id, pt, pdi).Length != 0) { pf++; continue; }
+ PRender();
+ if (!PFinite() || Rms(pbuf, 4096) < 1e-3f) pf++;
+ }
+ Check(pf == 0, $"every Phaser preset applies and renders ({pf} failed)");
+ cat.ApplyInPlace(pe, "phaser/Deep Space", pt, pdi);
+ Check(pe.DeviceGetParam(pt, pdi, 6) > 0.5f && Math.Abs(pe.DeviceGetParam(pt, pdi, 7) - 2f / 8f) < 1e-3f
+ && Math.Abs(pe.DeviceGetParam(pt, pdi, 9) - 1f) < 1e-3f, "Deep Space preset: synced 1/1, 12 stages");
+ cat.ApplyInPlace(pe, "phaser/Script 45", pt, pdi);
+ bool isDefault = Enumerable.Range(0, ppc).All(i => Math.Abs(pe.DeviceGetParam(pt, pdi, i) - pe.DeviceParamDefault(pt, pdi, i)) < 2e-3f);
+ Check(isDefault, "Script 45 preset = the device defaults");
+ }
+}
+
// ===================== Nota Auto Shift (effect kind 10) ===================
Console.WriteLine("-- Nota Auto Shift (effect kind 10) --");
{