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 flanger

Egor Khindikaynenc9946fc590b0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be5bdf13..84bc7f2e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,30 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **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:
+ - **LFO.** Sine, Tri or Saw; a free rate from 0.02 to 8 Hz or a synced note value from 2/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°.
+ - **Comb response.** The live frequency response of both channels, left in brass and right
+ in teal, with the first notch marked. Drag the graph left or right to move the notch
+ (Delay), up or down for Feedback; double-click resets both. Under it, the delay of both
+ channels over two LFO cycles with a running head.
+ - **Delay line.** Delay (0.1–8 ms), Depth, a bipolar Feedback (±95 %) with − / 0 / + snaps,
+ and Mix, plus the range the first notch sweeps and how deep the notches cut. Negative
+ feedback also flips the wet signal's polarity, so the comb mirrors instead of flattening
+ out. The header names the mode: positive, negative, resonant or through.
+ - A status line says what you'll hear — the notch sweep in Hz and the delay range, or a
+ warning when the comb rings or Mix is at zero.
+ All nine controls are device parameters, so automation, MIDI learn, A/B compare and project
+ save work as everywhere else. **31 factory presets**, from Jet Plane and Hollow Bar to Tin
+ Robot, Laser Zap and Vibrato.
+- **MCP: `read_flanger` and `set_flanger`.** Read what a Nota Flanger is doing (the settings in
+ units, the live delay per channel, the notch and its sweep, the null depth and the peaks)
+ and set it in units — waveform, rate or division, stereo degrees, delay in ms, depth,
+ feedback and mix in percent.
- **MCP: `read_physical`.** Ask a Nota Physical track what it is: a one-line summary of the
patch, a guide to every parameter's values, the sounding voices, the last struck pitch, the
output peak and both resonators' 16 partials as the engine tunes them (Hz, level, ring
diff --git a/FEATURES.md b/FEATURES.md
index 5bd99148..ab8ba8ce 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -482,6 +482,13 @@ and user presets, automation, persistence and cloning.
A permanent SCALE rail, Freeze, a note grid, a linear or log frequency axis, an L+R / L / R
source that can read Mid/Side, and a status line with peak, crest, momentary LUFS and L/R
correlation. Readable from MCP with `read_analyzer`.
+- **Nota Flanger** (23) — a comb filter on a short LFO-swept delay: Delay 0.1–8 ms, Depth,
+ bipolar Feedback ±95 % (positive = jet; negative flips the wet polarity so the comb mirrors
+ into a hollow tone; − / 0 / + snaps), Mix; Sine / Tri / Saw LFO, free (0.02–8 Hz) or synced
+ (2/1 … 1/16 with dotted and triplet values, locked to the bar), Stereo offset 0–180°. A live
+ 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 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/FlangerViews.cs b/src/managed/Nota.App/Controls/FlangerViews.cs
new file mode 100644
index 00000000..e8cf1d68
--- /dev/null
+++ b/src/managed/Nota.App/Controls/FlangerViews.cs
@@ -0,0 +1,301 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Flanger views (device kind 23) — the pictures on the Flanger card:
+// FlangerCombView — the live comb response of both channels (L brass, R teal) over 20 Hz …
+// 20 kHz, −36 … +12 dB, with the first notch marked. Where the teeth get
+// denser than a pixel the curve draws each column's max…min, so the comb
+// stays honest at high frequencies. Drag left / right moves the notch (Delay),
+// up / down the Feedback; double-click resets both.
+// FlangerSweepView — the delay τ of both channels over two LFO cycles, a running head and
+// the dots where each channel is now.
+// FlangerBar — a thin range / level bar (the NOTCH sweep and the NULL depth).
+// FlangerMath mirrors Flanger.h so the picture matches the sound.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class FlangerMath
+{
+ public static readonly string[] Waves = { "Sine", "Tri", "Saw" };
+ public static readonly string[] WaveNames = { "SINE", "TRIANGLE", "SAW" };
+ // Sync divisions, slowest → fastest (Flanger::kDivBeats / kDivNames).
+ public static readonly double[] DivBeats = { 8, 4, 2, 1.5, 1, 2.0 / 3, 0.5, 1.0 / 3, 0.25 };
+ public static readonly string[] DivNames = { "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/8T", "1/16" };
+ public const double DepthScale = 0.92, FbMax = 0.95;
+
+ 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 double FreeHz(double v) => 0.02 * Math.Pow(400, Math.Clamp(v, 0, 1));
+ public static double BaseMs(double v) => 0.1 * Math.Pow(80, 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));
+
+ /// <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 Tau(double baseMs, double depth, int wave, double p) => baseMs * (1 + DepthScale * 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 (Flanger.h).</summary>
+ public static double Mag(double dry, double wet, double fb, double th)
+ {
+ double c = Math.Cos(th), s = Math.Sin(th), wetAbs = wet;
+ if (fb < 0) wet = -wet;
+ double nr = wet * c, ni = -wet * 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 + wetAbs, 0.001);
+ }
+
+ /// <summary>The first notch's phase θ in (0, 2π] and its depth (linear) — π for positive feedback, 2π for negative.</summary>
+ public static (double Theta, double Mag) Notch(double mix, double fb)
+ {
+ var (dry, wet) = DryWet(mix);
+ double best = Math.PI, bm = double.MaxValue;
+ for (int i = 1; i <= 180; i++)
+ {
+ double th = i / 180.0 * 2 * Math.PI, m = Mag(dry, wet, fb, th);
+ if (m < bm) { bm = m; best = th; }
+ }
+ return (best, bm);
+ }
+
+ 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 Ms(double t) => t >= 10 ? NotaNum.F($"{t:0.0}") : NotaNum.F($"{t:0.00}");
+ 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 FlangerCombView : Control
+{
+ private double _tauL = 2.5, _tauR = 2.5, _mix = 0.5, _fb = 0.7;
+ private bool _on = true, _drag;
+ private Point _start;
+ private double _d0, _f0;
+
+ /// <summary>Delay and Feedback (normalized 0..1) at the start of a drag.</summary>
+ public Func<(double Delay, double Feedback)>? Value { get; set; }
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+ public event Action<double, double>? Changed;
+ public event Action? ResetRequested;
+
+ public FlangerCombView() { ClipToBounds = true; MinHeight = 40; Cursor = new Cursor(StandardCursorType.SizeAll); }
+
+ public void Set(double tauL, double tauR, double mix, double fb, bool on)
+ {
+ _tauL = tauL; _tauR = tauR; _mix = mix; _fb = fb; _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.735, 0.868);
+ _d0 = v.Delay; _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 notch follows the hand: it sits at θ / 2πτ, so moving it right by a share of the
+ // 3-decade axis shortens τ by the same log share of Delay's 80:1 range.
+ double d = Math.Clamp(_d0 - (p.X - _start.X) * k / Math.Max(120, Bounds.Width) * Math.Log(1000) / Math.Log(80), 0, 1);
+ double f = Math.Clamp(_f0 - (p.Y - _start.Y) * k / Math.Max(60, Bounds.Height), 0, 1);
+ Changed?.Invoke(d, 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(f / 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)
+ {
+ var (th, _) = FlangerMath.Notch(_mix, _fb);
+ double nf = th / (2 * Math.PI) / (_tauL / 1000);
+ if (nf is > 20 and < 20000)
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1, new DashStyle(new double[] { 2, 3 }, 0)), new Point(X(nf), 0), new Point(X(nf), h));
+ }
+
+ // R first so L reads on top where they meet.
+ Curve(_tauR, _on ? NotaPalette.TealBright : NotaPalette.TextAxis, 1.2, 0.75);
+ Curve(_tauL, _on ? NotaPalette.Accent : NotaPalette.TextAxis, 1.6, 1);
+
+ 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 Curve(double tauMs, IBrush ink, double width, double opacity)
+ {
+ double t = tauMs / 1000, k = 2 * Math.PI * t;
+ var (dry, wet) = FlangerMath.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, f0 = 20 * Math.Pow(1000, (double)i / n);
+ if (!_on) { Pt(g, i, x, Y(0)); continue; }
+ double f1 = 20 * Math.Pow(1000, (double)(i + 1) / n), span = k * (f1 - f0);
+ if (span <= 1.2 || i == n) { Pt(g, i, x, Y(Db(FlangerMath.Mag(dry, wet, _fb, k * f0)))); continue; }
+ double mn = double.MaxValue, mx = double.MinValue;
+ int m = Math.Min(64, (int)Math.Ceiling(span / 0.4));
+ for (int j = 0; j <= m; j++)
+ {
+ double v = FlangerMath.Mag(dry, wet, _fb, k * (f0 + (f1 - f0) * j / m));
+ if (v < mn) mn = v; if (v > mx) mx = v;
+ }
+ Pt(g, i, x, Y(Db(mx)));
+ g.LineTo(new Point(x, Y(Db(mn))));
+ }
+ g.EndFigure(false);
+ }
+ using (ctx.PushOpacity(opacity)) ctx.DrawGeometry(null, NotaGraph.SecondaryPen(ink, width), geo);
+ }
+ static void Pt(StreamGeometryContext g, int i, double x, double y)
+ {
+ if (i == 0) g.BeginFigure(new Point(x, y), false); else g.LineTo(new Point(x, y));
+ }
+ }
+}
+
+internal sealed class FlangerSweepView : Control
+{
+ private double _base = 2.5, _depth = 0.8, _off = 0.25, _head, _tauL = 2.5, _tauR = 2.5, _periodMs = 5000;
+ private int _wave = 1;
+ private bool _on = true;
+
+ public FlangerSweepView() { ClipToBounds = true; Height = 34; }
+
+ public void Set(double baseMs, double depth, int wave, double offCycles, double head, double tauL, double tauR, double periodMs, bool on)
+ {
+ _base = baseMs; _depth = depth; _wave = wave; _off = offCycles; _head = head; _tauL = tauL; _tauR = tauR; _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 top = _base * 1.95;
+ double X(double p) => p / 2 * w;
+ double Y(double t) => h * (34 - Math.Clamp(t / top, 0, 1.2) * 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("τ " + FlangerMath.Ms(top) + " ms", size: 6);
+ ctx.DrawText(tl, new Point(5, 1));
+ var bl = NotaGraph.AxisText("0 ms", 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(_tauR)), NotaPalette.TealBright);
+ DrawDot(new Point(hx, Y(_tauL)), 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 t = _on ? FlangerMath.Tau(_base, _depth, _wave, p + off) : _base;
+ var pt = new Point(X(p), Y(t));
+ 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);
+ }
+ }
+}
+
+internal sealed class FlangerBar : Control
+{
+ private double _l, _w;
+ public IBrush Ink { get; set; } = NotaPalette.BorderStrong;
+
+ public FlangerBar() { Height = 4; }
+
+ public void Set(double left, double width)
+ {
+ left = Math.Clamp(left, 0, 1); width = Math.Clamp(width, 0, 1 - left);
+ if (Math.Abs(left - _l) < 1e-4 && Math.Abs(width - _w) < 1e-4) return;
+ _l = left; _w = width; InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new RoundedRect(new Rect(0, 0, w, h), h / 2);
+ ctx.DrawRectangle(NotaPalette.BgSunken, null, r);
+ if (_w > 0)
+ using (ctx.PushClip(r)) ctx.DrawRectangle(Ink, null, new Rect(w * _l, 0, Math.Max(1, w * _w), h));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/FlangerDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/FlangerDeviceBody.cs
new file mode 100644
index 00000000..20925588
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Bodies/FlangerDeviceBody.cs
@@ -0,0 +1,360 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — built-in Nota Flanger body (comb filter on a short modulated delay, device
+// kind 23), a build of the "Nota Flanger" mockup (700 × 260) in the Level / EQ-8 / 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 comb response
+// of L and R (drag: the notch left / right = Delay, up / down = Feedback) and, under it, the delay
+// τ of both channels over two cycles with a running head, a DELAY LINE column (Delay, Depth, the
+// bipolar Feedback with its − / 0 / + snaps, Mix, and the first notch's sweep and null depth)
+// with the mode the feedback makes, and a status strip. The live τ comes from the engine
+// (Flanger.h scopeRead); the comb 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 Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Nota.Application;
+using static Nota.App.DeviceCardKit;
+
+namespace Nota.App;
+
+internal sealed class FlangerDeviceBody : IDeviceBody
+{
+ // ── Parameter indices (must match Flanger.h) ─────────────────────────────
+ private const int Rate = 0, Delay = 1, Depth = 2, Feedback = 3, Mix = 4, Waveform = 5, Sync = 6, Division = 7, Stereo = 8;
+ // Scope layout (Flanger::S_* / kTele).
+ private const int S_TauL = 3, S_TauR = 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 (Flanger.h) --------------------------------------------------
+ bool On() => !engine.DeviceBypassed(track, di);
+ bool Synced() => P(Sync) >= 0.5f;
+ int WaveI() => FlangerMath.WaveIndex(P(Waveform));
+ int DivI() => FlangerMath.DivIndex(P(Division));
+ double Bpm() => engine.Bpm > 0 ? engine.Bpm : 120;
+ double RateHz() => Synced() ? Bpm() / 60 / FlangerMath.DivBeats[DivI()] : FlangerMath.FreeHz(P(Rate));
+ double PeriodMs() => 1000 / Math.Max(1e-3, RateHz());
+ double BaseMs() => FlangerMath.BaseMs(P(Delay));
+ double Fb() => FlangerMath.Fb(P(Feedback));
+ double TauMin() => BaseMs() * (1 - FlangerMath.DepthScale * P(Depth));
+ double TauMax() => BaseMs() * (1 + FlangerMath.DepthScale * P(Depth));
+ // τ now: the engine's, or the centre before the first block.
+ double TauL() => Sc(S_TauL) > 0 ? Sc(S_TauL) : BaseMs();
+ double TauR() => Sc(S_TauR) > 0 ? Sc(S_TauR) : BaseMs();
+ 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" : "through";
+ }
+
+ 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 = 46, double valueW = 36,
+ 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(FlangerMath.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 delay: 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 = FlangerMath.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(FlangerMath.FreeHz(v)) + " Hz", "Rate — the free LFO rate, 0.02 … 8 Hz", 38, 46);
+ var divRow = Slider("RATE", Division, v => FlangerMath.DivNames[FlangerMath.DivIndex(v)],
+ "Rate — the note value of one LFO cycle, 2/1 … 1/16 with dotted (D) and triplet (T) values", 38, 46,
+ snap: v => FlangerMath.DivNorm(FlangerMath.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 — COMB RESPONSE, and τ over two cycles
+ // ======================================================================
+ var tauWord = 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), tauWord },
+ };
+ var comb = new FlangerCombView { Value = () => (P(Delay), P(Feedback)) };
+ comb.GestureBegin += () => { Begin(Delay); Begin(Feedback); };
+ comb.GestureEnd += () => { End(Delay); End(Feedback); };
+ comb.Changed += (d, f) => { Raw(Delay, d); Raw(Feedback, f); RefreshAll(); };
+ comb.ResetRequested += () => { Reset(Delay); Reset(Feedback); RefreshAll(); };
+ Learn(comb, Delay);
+ ToolTip.SetTip(comb, "The comb the delay carves into the spectrum, L brass and R teal, with the first notch dashed. Drag left / right to move the notch (Delay), up / down for Feedback; double-click resets both.");
+
+ var sweep = new FlangerSweepView { Margin = new Thickness(0, 4, 0, 0) };
+ ToolTip.SetTip(sweep, "The delay τ of both channels over two LFO cycles, and where each is now");
+ var centreBody = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { Docked(sweep, Dock.Bottom), comb } };
+ var centre = Island(HeadRow(Caps("COMB RESPONSE"), legend), centreBody);
+ centre.Margin = new Thickness(5, 0);
+
+ // ======================================================================
+ // RIGHT — DELAY LINE: Delay · Depth · Feedback · Mix · snaps · notch 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 hollows the tone, past 85\u2009% the comb rings");
+
+ var delayRow = Slider("DELAY", Delay, v => FlangerMath.Ms(FlangerMath.BaseMs(v)) + " ms", "Delay — the centre of the sweep, 0.1 … 8 ms: shorter puts the notches higher");
+ var depthRow = Slider("DEPTH", Depth, v => PctF(v), "Depth — how far the LFO swings the delay around its centre");
+ var fbRow = Slider("FEEDBACK", Feedback, v => FbF(FlangerMath.Fb(v)),
+ "Feedback — the delayed signal fed back in, ±95 %: positive for the classic jet, negative for a hollow tone", modulation: true, bipolar: true,
+ snap: v => FlangerMath.FbNorm(Math.Round(FlangerMath.Fb(v) * 100) / 100));
+ var mixRow = Slider("MIX", Mix, v => PctF(v), "Mix — 50 % gives the deepest notches; 100 % is the delayed signal alone, a vibrato");
+
+ Border Snap(string text, double fb)
+ {
+ var tb = Mono(text, 7, TextTertiary); tb.HorizontalAlignment = HorizontalAlignment.Center;
+ var b = new Border
+ {
+ BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(0, 1),
+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb,
+ };
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ SetP(Feedback, FlangerMath.FbNorm(fb)); RefreshAll(); e.Handled = true;
+ };
+ readouts.Add(() =>
+ {
+ bool on = Math.Abs(Fb() - fb) < 0.005;
+ b.Background = on ? NotaPalette.TrackOff : Brushes.Transparent;
+ tb.Foreground = on ? TextPrimary : TextTertiary;
+ });
+ Learn(b, Feedback);
+ ToolTip.SetTip(b, fb < 0 ? "Feedback −70\u2009%: hollow" : fb > 0 ? "Feedback +70\u2009%: the classic jet" : "Feedback 0: a plain comb");
+ return b;
+ }
+ var snaps = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 1, Margin = new Thickness(46, 0, 0, 0) };
+ snaps.Children.Add(Snap("−", -0.7));
+ snaps.Children.Add(Col(Snap("0", 0), 1));
+ snaps.Children.Add(Col(Snap("+", 0.7), 2));
+
+ 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("46,*,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 notchBar = new FlangerBar { Ink = NotaPalette.BorderStrong, VerticalAlignment = VerticalAlignment.Center };
+ var notchVal = 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("NOTCH", notchBar, notchVal, "The first notch now, over the range the sweep moves it (20 Hz … 20 kHz)"),
+ 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(delayRow);
+ rightBody.Children.Add(GRow(depthRow, 2));
+ rightBody.Children.Add(GRow(fbRow, 4));
+ rightBody.Children.Add(GRow(mixRow, 6));
+ rightBody.Children.Add(GRow(snaps, 8));
+ rightBody.Children.Add(GRow(reads, 10));
+ var right = Island(HeadRow(Caps("DELAY LINE"), 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 = "Flanger 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 +{FlangerMath.PeakDb(P(Mix), fb):0.0} dB, the comb rings");
+ warn = true;
+ }
+ else if (P(Depth) < 0.01f) foot = "Depth at zero: the comb stands still, a static effect";
+ else
+ {
+ var (th, _) = FlangerMath.Notch(P(Mix), fb);
+ double lo = th / (2 * Math.PI) / (TauMax() / 1000), hi = th / (2 * Math.PI) / (TauMin() / 1000);
+ foot = "Notch sweeps " + FlangerMath.HzF(lo) + " ↔ " + FlangerMath.HzF(hi) + " Hz · τ "
+ + FlangerMath.Ms(TauMin()) + "–" + FlangerMath.Ms(TauMax()) + " ms";
+ }
+ 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 tl = TauL(), tr = TauR(), fb = Fb(), mix = P(Mix);
+ tauWord.Text = on ? "τL " + FlangerMath.Ms(tl) + " · τR " + FlangerMath.Ms(tr) + " ms" : "bypass";
+ comb.Set(tl, tr, mix, fb, on);
+ sweep.Set(BaseMs(), P(Depth), WaveI(), P(Stereo) * 0.5, Sc(S_WinPhase), tl, tr, PeriodMs(), on);
+
+ var (th, nm) = FlangerMath.Notch(mix, fb);
+ double nf = th / (2 * Math.PI) / (tl / 1000);
+ double lo = th / (2 * Math.PI) / (TauMax() / 1000), hi = th / (2 * Math.PI) / (TauMin() / 1000);
+ double nullDb = 20 * Math.Log10(Math.Max(nm, 1e-4));
+ notchBar.Set(on ? PctAxis(lo) : 0, on ? PctAxis(hi) - PctAxis(lo) : 0);
+ notchVal.Text = on ? FlangerMath.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 ebcd6f18..4b72e327 100644
--- a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
+++ b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
@@ -41,6 +41,7 @@ internal sealed class DeviceCardFactory
[20] = new ChamberDeviceBody(),
[21] = new PrismDeviceBody(),
[22] = new LensDeviceBody(),
+ [23] = new FlangerDeviceBody(),
};
/// <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 75c4ad7f..3239101c 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1652,6 +1652,48 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("autopan", 9, "Mix Motion", ("Sync", 1f), ("Division", 0.267f), ("Waveform", 0.25f), ("Amount", 0.35f), ("Phase", 0.5f), ("Mix", 0.6f));
Fx("autopan", 9, "Offset Swirl", ("Sync", 1f), ("Division", 0.4f), ("Amount", 0.60f), ("Phase", 0.375f));
+ // ---- Nota Flanger (kind 23) — comb filter on a modulated delay. Written in units through Fl():
+ // waveform (FSine / FTri / FSaw), Delay ms 0.1..8, Depth 0..1, Feedback −0.95..+0.95, Mix
+ // 0..1 (0.5 = the deepest notches, 1 = wet only / vibrato), Stereo 0..180°, and either a free
+ // rate in Hz (0.02..8) or a Sync division (2/1 1/1 1/2 1/4D 1/4 1/4T 1/8 1/8T 1/16).
+ // Classic
+ Fl("Jet Plane", FTri, 2.5f, 0.80f, 0.70f, 0.50f, 90, hz: 0.20f);
+ Fl("Slow Jet", FTri, 3.0f, 0.90f, 0.75f, 0.50f, 90, hz: 0.08f);
+ Fl("Takeoff", FTri, 4.0f, 1.00f, 0.85f, 0.50f, 45, hz: 0.05f);
+ Fl("Tape Flange", FSine, 1.2f, 0.95f, 0.00f, 0.50f, 0, hz: 0.15f);
+ Fl("Gentle Sweep", FSine, 2.0f, 0.60f, 0.30f, 0.40f, 90, hz: 0.25f);
+ Fl("Subtle Motion", FSine, 1.5f, 0.40f, 0.20f, 0.30f, 120, hz: 0.30f);
+ Fl("Wide Stereo", FTri, 2.5f, 0.80f, 0.60f, 0.50f, 180, hz: 0.15f);
+ Fl("Mono Sweep", FTri, 2.5f, 0.80f, 0.70f, 0.50f, 0, hz: 0.20f);
+ // Negative feedback — hollow
+ Fl("Hollow Bar", FSine, 1.2f, 0.60f, -0.65f, 0.50f, 180, div: "1/1");
+ Fl("Hollow Tube", FSine, 3.0f, 0.50f, -0.70f, 0.50f, 90, hz: 0.30f);
+ Fl("Negative Jet", FTri, 2.0f, 0.85f, -0.80f, 0.50f, 90, hz: 0.12f);
+ Fl("Inside Out", FSine, 5.0f, 0.40f, -0.50f, 0.50f, 60, hz: 0.40f);
+ Fl("Half-Bar Hollow", FSine, 2.0f, 0.70f, -0.60f, 0.50f, 180, div: "1/2");
+ // Resonant / FX
+ Fl("Tin Robot", FTri, 0.6f, 0.35f, 0.90f, 0.60f, 0, div: "1/8");
+ Fl("Metal Ring", FSine, 0.4f, 0.20f, 0.93f, 0.60f, 30, hz: 0.50f);
+ Fl("Laser Zap", FSaw, 0.8f, 1.00f, 0.90f, 0.50f, 0, hz: 4.00f);
+ Fl("Comb Drone", FSine, 5.0f, 0.05f, 0.92f, 0.60f, 0, hz: 0.05f);
+ Fl("Siren", FSaw, 1.5f, 0.90f, 0.80f, 0.50f, 90, hz: 1.00f);
+ // Synced
+ Fl("Quarter Swirl", FTri, 2.0f, 0.70f, 0.60f, 0.50f, 90, div: "1/4");
+ Fl("Two-Bar Sweep", FTri, 3.0f, 0.90f, 0.75f, 0.50f, 90, div: "2/1");
+ Fl("Eighth Pulse", FSaw, 1.5f, 0.60f, 0.50f, 0.50f, 0, div: "1/8");
+ Fl("Dotted Drift", FSine, 2.5f, 0.70f, 0.55f, 0.50f, 120, div: "1/4D");
+ Fl("Triplet Shimmer", FTri, 1.0f, 0.50f, 0.60f, 0.45f, 90, div: "1/8T");
+ // Vibrato and chorus-like
+ Fl("Vibrato", FSine, 3.0f, 0.25f, 0.00f, 1.00f, 0, hz: 4.00f);
+ Fl("Flange Chorus", FTri, 6.0f, 0.35f, 0.10f, 0.45f, 180, hz: 0.60f);
+ Fl("Doubler Wobble", FSine, 7.0f, 0.15f, 0.00f, 0.40f, 180, hz: 0.35f);
+ // Sources
+ Fl("Drum Bus Jet", FTri, 1.5f, 0.90f, 0.60f, 0.35f, 90, div: "2/1");
+ Fl("Guitar Classic", FTri, 1.8f, 0.75f, 0.55f, 0.50f, 90, hz: 0.30f);
+ Fl("Vocal Air", FSine, 0.8f, 0.50f, 0.30f, 0.30f, 120, hz: 0.20f);
+ 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 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
@@ -2036,6 +2078,21 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("autogain", 18, name, ps.ToArray());
}
+ // Nota Flanger waveforms and Sync divisions (Flanger::kDivNames), and its presets in units.
+ private const int FSine = 0, FTri = 1, FSaw = 2;
+ private static readonly string[] FlDivs = { "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/8T", "1/16" };
+
+ private void Fl(string name, int wave, float delayMs, float depth, float fb, float mix, float stereoDeg, float hz = 0.2f, string? div = null)
+ {
+ int d = div is null ? 1 : Array.IndexOf(FlDivs, div);
+ if (d < 0) throw new ArgumentException($"unknown Flanger division {div}");
+ Fx("flanger", 23, name,
+ ("Rate", (float)(Math.Log(Math.Clamp(hz, 0.02f, 8f) / 0.02) / Math.Log(400))),
+ ("Delay", (float)(Math.Log(Math.Clamp(delayMs, 0.1f, 8f) / 0.1) / Math.Log(80))),
+ ("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));
+ }
+
// 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 00305aca..762ad6fa 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"),
+ (22, "Nota Lens"), (23, "Nota Flanger"),
};
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.")]
+ [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.")]
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). 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. 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));
@@ -837,6 +837,89 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
V(21) > 0.5f, V(11));
});
+ public sealed record FlangerReading(string Summary, string Live, string Waveform, bool Sync, string Division, double RateHz,
+ double PeriodMs, double StereoDeg, double DelayMs, double DepthPercent, double FeedbackPercent, double MixPercent, string Mode,
+ double TauMinMs, double TauMaxMs, double TauLMs, double TauRMs, 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[] FlangerWaves = { "Sine", "Triangle", "Saw" };
+ private static readonly string[] FlangerDivs = { "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/8T", "1/16" };
+
+ [McpServerTool(Name = "read_flanger"), Description(
+ "Read what a Nota Flanger (built-in effect kind 23 — a comb filter on a short LFO-swept delay) is doing: the LFO "
+ + "waveform, free rate (Hz) or Sync division, the period, Stereo (the right LFO's offset, 0..180°), Delay (the centre of "
+ + "the sweep, ms), Depth, Feedback (−95..+95 %) and the mode it makes (positive = jet, negative = hollow, resonant past "
+ + "85 %, through near 0), Mix; the sweep's delay range (ms), live τ per channel, the first notch now and the range it "
+ + "sweeps (Hz), the notch depth and the comb's 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 Delay, 2 Depth, 3 Feedback, 4 Mix, 5 Waveform, 6 Sync, "
+ + "7 Division, 8 Stereo — set them in units with set_flanger; device_action 0 restarts the LFO, 1 clears the delay "
+ + "line, 2 resets the meters.")]
+ public Task<FlangerReading> ReadFlanger(int trackId, int deviceIndex) => Read(() => FlangerRead(trackId, deviceIndex));
+
+ private FlangerReading FlangerRead(int trackId, int deviceIndex)
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 23) throw new ArgumentException("not a Nota Flanger (kind 23)");
+ 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);
+ double fb = (Pm(3) - 0.5) * 1.9;
+ string mode = Math.Abs(fb) >= 0.85 ? "resonant" : fb <= -0.15 ? "negative" : fb >= 0.15 ? "positive" : "through";
+ double rate = V(6);
+ return new FlangerReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ FlangerWaves[wave], Pm(6) >= 0.5f, FlangerDivs[div], Math.Round(rate, 3), rate > 0 ? Math.Round(1000 / rate) : 0,
+ Math.Round(Pm(8) * 180), R2(0.1 * Math.Pow(80, Pm(1))), R1(Pm(2) * 100), R1(fb * 100), R1(Pm(4) * 100), mode,
+ R2(V(12)), R2(V(13)), R2(V(3)), R2(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_flanger"), Description(
+ "Play a Nota Flanger (built-in effect kind 23) in units — only the fields you pass change; each change is recorded like "
+ + "a hand edit (so it lands in automation while recording). waveform \"Sine\" | \"Triangle\" | \"Saw\"; rateHz 0.02..8 "
+ + "(sets free run); division \"2/1\" \"1/1\" \"1/2\" \"1/4D\" \"1/4\" \"1/4T\" \"1/8\" \"1/8T\" \"1/16\" (sets Sync); "
+ + "sync true / false; stereoDeg 0..180 (0 = both channels sweep together, 180 = opposite); delayMs 0.1..8 (the centre "
+ + "of the sweep — shorter = higher notches); depthPercent 0..100; feedbackPercent −95..+95 (positive = jet, negative = "
+ + "hollow, past ±85 the comb rings); mixPercent 0..100 (50 = the deepest notches, 100 = wet only, a vibrato). Returns "
+ + "the device as read back.")]
+ public Task<FlangerReading> SetFlanger(int trackId, int deviceIndex, string? waveform = null, double? rateHz = null,
+ string? division = null, bool? sync = null, double? stereoDeg = null, double? delayMs = null, double? depthPercent = null,
+ double? feedbackPercent = null, double? mixPercent = null) => Mutate(() =>
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 23) throw new ArgumentException("not a Nota Flanger (kind 23)");
+ void S(int p, double v) => ForgeSet(trackId, deviceIndex, p, v);
+ 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(FlangerDivs, division.Trim().ToUpperInvariant());
+ if (d < 0) throw new ArgumentException("division must be one of " + string.Join(", ", FlangerDivs));
+ S(6, 1); S(7, d / 8.0);
+ }
+ if (stereoDeg is { } st) S(8, Math.Clamp(st, 0, 180) / 180);
+ if (delayMs is { } dm) S(1, Math.Log(Math.Clamp(dm, 0.1, 8) / 0.1) / Math.Log(80));
+ if (depthPercent is { } dp) S(2, dp / 100);
+ if (feedbackPercent is { } fp) S(3, 0.5 + Math.Clamp(fp, -95, 95) / 190);
+ if (mixPercent is { } mp) S(4, mp / 100);
+ return FlangerRead(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 11d9a88f..62e43379 100644
--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
@@ -254,6 +254,7 @@ public sealed partial class BrowserViewModel : ObservableObject
new() { Name = "Nota Vintage", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 8, Sub = "vintage saturator" },
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 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 e057c151..4fc89fa4 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -22,6 +22,7 @@
#include "Shutter.h"
#include "Chamber.h"
#include "Lens.h"
+#include "Flanger.h"
#include "Prism.h"
#include "Ceiling.h"
#include "Strata.h"
@@ -446,6 +447,7 @@ int32_t Engine::addTrackBuiltinDevice(int32_t trackId, int32_t kind) {
else if (kind == 20) dev = std::make_shared<Chamber>();
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 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
@@ -511,6 +513,7 @@ std::shared_ptr<Device> Engine::cloneDevice(const Device& src) const {
case 20: d = std::make_shared<Chamber>(); break;
case 21: d = std::make_shared<Prism>(); break;
case 22: d = std::make_shared<Lens>(); break;
+ case 23: d = std::make_shared<Flanger>(); break;
default: d = src.clone(); break; // hosted plugin
}
if (!d) return nullptr;
@@ -588,6 +591,7 @@ static std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {
case 20: return std::make_shared<Chamber>();
case 21: return std::make_shared<Prism>();
case 22: return std::make_shared<Lens>();
+ case 23: return std::make_shared<Flanger>();
default: return nullptr; // Rack / plugin: no simple per-param default
}
}
diff --git a/src/native/nota.engine/src/Flanger.h b/src/native/nota.engine/src/Flanger.h
new file mode 100644
index 00000000..3dc264e9
--- /dev/null
+++ b/src/native/nota.engine/src/Flanger.h
@@ -0,0 +1,441 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Built-in Nota Flanger (device kind 23, mockup "Nota Flanger") — a comb filter on a short,
+// LFO-modulated delay line. Per channel:
+//
+// w[n] = x[n] + Feedback · w[n − τ] (the delay line, fed back)
+// wet = ±w[n − τ] (the wet polarity follows the feedback's sign)
+// out = (dry · x + wet_gain · wet) / (dry + wet_gain)
+//
+// so the wet path is ±e^{−jωτ} / (1 − fb·e^{−jωτ}) and, summed with the dry signal, carves a
+// harmonic series of notches that the LFO sweeps up and down. Positive feedback sharpens the
+// peaks at the multiples of 1/τ (the classic "jet"); negative feedback flips the wet polarity
+// with it, so the comb mirrors — peaks on the odd multiples of 1/2τ, notches on the multiples
+// of 1/τ (a hollow, tube-like tone). Without the flip, negative feedback against a positive
+// wet path would all but cancel the comb. Near ±95 % the comb rings metallically. The polarity
+// glides with the other params, so sweeping Feedback through 0 doesn't click.
+//
+// τ(t) = Delay · (1 + 0.92 · Depth · lfo(t)) Delay 0.1 … 8 ms (exponential)
+// LFO: Sine / Triangle / Saw, free (Rate 0.02 … 8 Hz) or Sync (Division 2/1 … 1/16 incl. dotted
+// and triplets). 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°.
+// Mix: 0 = dry, 0.5 = dry and wet equal (the deepest notches), 1 = wet only (a pure vibrato).
+//
+// The delay is read with 4-point Hermite interpolation (no linear-interp dulling of the highs),
+// never shorter than 2 samples. Delay, Depth, Feedback and Mix are smoothed over ~15 ms so
+// automation doesn't zipper.
+//
+// All params are normalized 0..1 and APPEND ONLY. Persistence / automation / clone flow
+// generically through the base Device.
+// Telemetry (scopeRead): kTele live values (levels, τ now per channel, the LFO's place in its
+// two-cycle window, the rate, the tempo, the comb's notch / 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 delay line (stops a
+// ringing comb), 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 Flanger : public Device {
+public:
+ // Param layout — order is the persisted/automation layout. APPEND ONLY.
+ enum { Rate = 0, Delay, Depth, Feedback, Mix, Waveform, Sync, Division, Stereo, 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_TauL, // the left delay now, ms
+ S_TauR, // the right delay now, ms
+ 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_BaseMs, // the Delay param, ms (the centre of the sweep)
+ S_TauMin, // the sweep's shortest / longest delay, ms
+ S_TauMax,
+ S_NotchHz, // the first notch of the left comb now, Hz
+ S_NotchMinHz, // the first notch's sweep, Hz (at τ max … τ min)
+ S_NotchMaxHz,
+ S_NullDb, // how deep the notches go, dB
+ S_PeakDb, // the comb's peaks, 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)
+ kTele = 32
+ };
+
+ static constexpr int kDivs = 9;
+ // Sync divisions, slowest → fastest: beats per cycle, and their names.
+ static constexpr double kDivBeats[kDivs] = { 8.0, 4.0, 2.0, 1.5, 1.0, 2.0 / 3.0, 0.5, 1.0 / 3.0, 0.25 };
+ static constexpr const char* kDivNames[kDivs] = { "2/1", "1/1", "1/2", "1/4D", "1/4", "1/4T", "1/8", "1/8T", "1/16" };
+ static constexpr int kDefaultDiv = 1; // 1/1
+
+ // Ranges (mirrored by the card and MCP).
+ static constexpr double kRateLo = 0.02, kRateHi = 8.0; // Hz, exponential
+ static constexpr double kDelayLo = 0.1, kDelayHi = 8.0; // ms, exponential
+ static constexpr double kFbMax = 0.95; // feedback ±95 %
+ static constexpr double kDepthScale = 0.92; // τ swings Delay · (1 ± 0.92 · Depth)
+
+ Flanger() {
+ p_[Rate].store(0.384f); // 0.20 Hz
+ p_[Delay].store(0.735f); // 2.5 ms
+ p_[Depth].store(0.80f);
+ p_[Feedback].store((float)(0.5 + 0.70 / (2.0 * kFbMax))); // +70 %
+ p_[Mix].store(0.50f);
+ p_[Waveform].store(0.5f); // Triangle
+ p_[Sync].store(0.0f); // Free (Hz)
+ p_[Division].store((float)kDefaultDiv / (kDivs - 1));
+ p_[Stereo].store(0.5f); // 90°
+ 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;
+ clearLine();
+ 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)) clearLine();
+ if (resetReq_.exchange(false, std::memory_order_acquire)) resetMeters();
+
+ const int wave = waveIndex();
+ const double base = baseMs();
+ 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 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 msToS = sr_ * 0.001;
+ const double maxD = (double)(kBuf - 4);
+
+ const double wetSignT = fb < 0.0 ? -wetT : wetT;
+ if (snap_) { baseS_ = base; depthS_ = depth; fbS_ = fb; dryS_ = dryT; wetS_ = wetSignT; snap_ = false; }
+
+ float inPk = 0.0f, outPkL = 0.0f, outPkR = 0.0f;
+ double tauL = 0.0, tauR = 0.0;
+ 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;
+ }
+ baseS_ += sm * (base - baseS_);
+ depthS_ += sm * (depth - depthS_);
+ fbS_ += sm * (fb - fbS_);
+ dryS_ += sm * (dryT - dryS_);
+ wetS_ += sm * (wetSignT - wetS_);
+
+ const double lfoL = lfo(wave, frac_);
+ const double lfoR = lfo(wave, frac_ + phOff);
+ tauL = baseS_ * (1.0 + kDepthScale * depthS_ * lfoL);
+ tauR = baseS_ * (1.0 + kDepthScale * depthS_ * lfoR);
+ const double dL = std::clamp(tauL * msToS, 2.0, maxD);
+ const double dR = std::clamp(tauR * msToS, 2.0, maxD);
+
+ const float xL = buf[i * 2], xR = buf[i * 2 + 1];
+ inPk = std::max(inPk, std::max(std::fabs(xL), std::fabs(xR)));
+ const float yL = readLine(lineL_, dL), yR = readLine(lineR_, dR);
+ lineL_[w_] = sanitize(xL + (float)fbS_ * yL);
+ lineR_[w_] = sanitize(xR + (float)fbS_ * yR);
+ w_ = (w_ + 1) & kMask;
+
+ const double norm = 1.0 / std::max(dryS_ + std::fabs(wetS_), 1e-3);
+ const float oL = (float)((dryS_ * xL + wetS_ * yL) * norm);
+ const float oR = (float)((dryS_ * xR + wetS_ * 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);
+ tauLA_.store((float)tauL, std::memory_order_relaxed);
+ tauRA_.store((float)tauR, 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 bms = baseMs(), dep = std::clamp((double)get(Depth), 0.0, 1.0);
+ 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_TauL] = tauLA_.load(std::memory_order_relaxed);
+ t[S_TauR] = tauRA_.load(std::memory_order_relaxed);
+ if (t[S_TauL] <= 0.0f) t[S_TauL] = t[S_TauR] = (float)bms; // 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] = srA_.load(std::memory_order_relaxed);
+ t[S_BaseMs] = (float)bms;
+ t[S_TauMin] = (float)(bms * (1.0 - kDepthScale * dep));
+ t[S_TauMax] = (float)(bms * (1.0 + kDepthScale * dep));
+ const Comb cb = comb();
+ t[S_NotchHz] = (float)(cb.notchTheta / (2.0 * kPi) / (std::max(1e-6f, t[S_TauL]) * 0.001));
+ t[S_NotchMinHz] = (float)(cb.notchTheta / (2.0 * kPi) / (std::max(1e-6f, t[S_TauMax]) * 0.001));
+ t[S_NotchMaxHz] = (float)(cb.notchTheta / (2.0 * kPi) / (std::max(1e-6f, t[S_TauMin]) * 0.001));
+ t[S_NullDb] = (float)cb.nullDb;
+ t[S_PeakDb] = (float)cb.peakDb;
+ 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;
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ return n;
+ }
+
+ const char* displayName() const override { return "Nota Flanger"; }
+ int32_t builtinKind() const override { return 23; }
+
+ int32_t paramCount() const override { return kNumParams; }
+ const char* paramName(int32_t i) const override {
+ switch (i) {
+ case Rate: return "Rate"; case Delay: return "Delay"; 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";
+ 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[1400];
+ if (id == 0) {
+ std::string s = waves[waveIndex()];
+ 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 - delay %.2f ms - depth %.0f %% - feedback %+.0f %% (%s) - mix %.0f %%",
+ stereoDeg(), baseMs(), get(Depth) * 100.0f, 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 - delay L %.2f ms, R %.2f ms "
+ "(sweep %.2f .. %.2f ms) - first notch %.0f Hz (sweeps %.0f .. %.0f Hz), %.1f dB deep - comb 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_TauL], sc[S_TauR], sc[S_TauMin], sc[S_TauMax], 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;
+ for (int i = 0; i < kDivs; ++i) {
+ std::snprintf(b, sizeof b, "%s%.3f = %s", i ? ", " : "", (double)i / (kDivs - 1), kDivNames[i]);
+ divs += 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.537 = 0.5 Hz, 0.653 = 1 Hz, 0.769 = 2 Hz, 0.884 = 4 Hz). Delay: the "
+ "centre of the sweep, exponential 0.1 ms (0) .. 8 ms (1) (0.263 = 0.32 ms, 0.409 = 0.6 ms, 0.525 = 1 ms, "
+ "0.567 = 1.2 ms, 0.683 = 2 ms, 0.735 = 2.5 ms, 0.776 = 3 ms, 0.841 = 4 ms, 0.892 = 5 ms). Depth: how far "
+ "the delay swings, 0..1 - tau = Delay * (1 +/- 0.92 * Depth). Feedback: bipolar, (v - 0.5) * 1.9 = -95 % .. "
+ "+95 % (0.5 = none, 0.868 = +70 %, 0.132 = -70 %); positive sharpens the peaks at multiples of 1/delay "
+ "(jet), negative also flips the wet polarity so the peaks move to the odd multiples of 1/(2 delay) "
+ "(hollow); past 85 % the comb rings. Mix: 0 = dry, 0.5 = dry and wet equal (the "
+ "deepest notches), 1 = wet only (a pitch vibrato). 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). 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); }
+ double rateFreeHz() const { return expMap(get(Rate), kRateLo, kRateHi); }
+ double baseMs() const { return expMap(get(Delay), kDelayLo, kDelayHi); }
+ 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; }
+
+ // |dry ± wet·H(θ)| / (dry + wet), H = e^{−jθ} / (1 − fb·e^{−jθ}), θ = ωτ — the comb's magnitude
+ // (the wet polarity follows the feedback's sign, as in process()).
+ static double combMag(double dry, double wet, double fb, double th) {
+ const double c = std::cos(th), s = std::sin(th);
+ return combMagSigned(dry, fb < 0.0 ? -wet : wet, fb, c, s);
+ }
+
+private:
+ static double combMagSigned(double dry, double wet, double fb, double c, double s) {
+ const double nr = wet * c, ni = -wet * 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 + std::fabs(wet), 0.001);
+ }
+ static constexpr double kPi = 3.14159265358979323846;
+ static constexpr int kBuf = 16384; // ≥ 15.4 ms at 768 kHz
+ static constexpr int kMask = kBuf - 1;
+
+ struct Comb { double notchTheta, nullDb, peakDb; };
+ // The first notch (the phase θ = ωτ in (0, 2π] where the comb dips deepest — π for positive
+ // feedback, 2π for negative), its depth and the peak level.
+ Comb comb() const {
+ const double mix = std::clamp((double)get(Mix), 0.0, 1.0), fb = feedback();
+ const double dry = std::min(1.0, 2.0 * (1.0 - mix)), wet = std::min(1.0, 2.0 * mix);
+ double best = kPi, bm = 1e9;
+ for (int i = 1; i <= 180; ++i) {
+ const double th = i / 180.0 * 2.0 * kPi, m = combMag(dry, wet, fb, th);
+ if (m < bm) { bm = m; best = th; }
+ }
+ const double pk = combMag(dry, wet, fb, fb >= 0.0 ? 0.0 : kPi);
+ return { best, 20.0 * std::log10(std::max(bm, 1e-4)), 20.0 * std::log10(std::max(pk, 1e-4)) };
+ }
+
+ const char* modeWord() const {
+ const double fb = feedback();
+ return std::fabs(fb) >= 0.85 ? "resonant" : fb <= -0.15 ? "negative" : fb >= 0.15 ? "positive" : "through";
+ }
+
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ static float sanitize(float v) { return std::isfinite(v) && std::fabs(v) > 1e-20f ? std::clamp(v, -64.0f, 64.0f) : 0.0f; }
+
+ // 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;
+ }
+
+ // 4-point Hermite read `d` samples behind the write head (d ≥ 2, so every tap is written).
+ float readLine(const float* line, double d) const {
+ const double r = (double)w_ - d;
+ const double fl = std::floor(r);
+ const float t = (float)(r - fl);
+ const int i0 = (int)((int64_t)fl & kMask);
+ const float ym1 = line[(i0 - 1) & kMask], y0 = line[i0], y1 = line[(i0 + 1) & kMask], y2 = line[(i0 + 2) & kMask];
+ const float c1 = 0.5f * (y1 - ym1);
+ const float c2 = ym1 - 2.5f * y0 + 2.0f * y1 - 0.5f * y2;
+ const float c3 = 0.5f * (y2 - ym1) + 1.5f * (y0 - y1);
+ return ((c3 * t + c2) * t + c1) * t + y0;
+ }
+
+ void clearLine() { std::memset(lineL_, 0, sizeof lineL_); std::memset(lineR_, 0, sizeof lineR_); w_ = 0; }
+ void resetMeters() { inPkM_ = outPkLM_ = outPkRM_ = 0.0f; }
+
+ double sr_ = 44100.0;
+ std::atomic<float> p_[kNumParams] = {};
+ float lineL_[kBuf] = {}, lineR_[kBuf] = {};
+ int w_ = 0;
+ int64_t cycle_ = 0;
+ double frac_ = 0.0;
+ bool snap_ = true;
+ double baseS_ = 2.5, depthS_ = 0.8, fbS_ = 0.7, 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> tauLA_{0.0f}, tauRA_{0.0f}, fracA_{0.0f}, rateA_{0.2f}, 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 5e76119c..1184b864 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -8842,6 +8842,202 @@ Console.WriteLine("-- Nota Orbit (effect kind 9) --");
}
}
+// ===================== Nota Flanger (effect kind 23) =====================
+Console.WriteLine("-- Nota Flanger (effect kind 23) --");
+{
+ // Params (Flanger.h): 0 Rate, 1 Delay, 2 Depth, 3 Feedback, 4 Mix, 5 Waveform, 6 Sync, 7 Division, 8 Stereo.
+ // Scope: 0 in, 1 out L, 2 out R (dBFS) · 3 / 4 τ L / R ms · 5 window phase · 6 rate Hz · 7 BPM · 8 playing ·
+ // 9 locked · 10 sample rate · 11 base ms · 12 / 13 τ 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.
+ using var fe = new NotaEngine();
+ int ft = fe.AddAudioTrack();
+ fe.AddAudioClip(ft, wav, 0.0); // 1 s sine @ 440 Hz
+ int fdi = fe.AddBuiltinDevice(ft, 23);
+ Check(fdi >= 0, "add Nota Flanger device");
+ Check(fe.DeviceName(ft, fdi) == "Nota Flanger", $"device is Nota Flanger (got '{fe.DeviceName(ft, fdi)}')");
+ Check(fe.TrackDeviceBuiltinKind(ft, fdi) == 23, "device reports builtin kind 23");
+ int fpc = fe.DeviceParamCount(ft, fdi);
+ Check(fpc == 9, $"Nota Flanger exposes 9 params ({fpc})");
+ var fnames = Enumerable.Range(0, fpc).Select(i => fe.DeviceParamName(ft, fdi, i)).ToArray();
+ Check(string.Join(",", fnames) == "Rate,Delay,Depth,Feedback,Mix,Waveform,Sync,Division,Stereo", $"param layout ({string.Join(",", fnames)})");
+ Check(Math.Abs(fe.DeviceParamDefault(ft, fdi, 1) - 0.735f) < 1e-3f && Math.Abs(fe.DeviceParamDefault(ft, fdi, 3) - (0.5f + 0.7f / 1.9f)) < 1e-3f
+ && Math.Abs(fe.DeviceParamDefault(ft, fdi, 8) - 0.5f) < 1e-3f, "defaults: 2.5 ms, feedback +70 %, stereo 90° (the Jet Plane)");
+ fe.DeviceSetParam(ft, fdi, 2, 0.42f);
+ Check(Math.Abs(fe.DeviceGetParam(ft, fdi, 2) - 0.42f) < 1e-4f, "device param set/get round-trips");
+
+ var fbuf = new float[4096 * 2];
+ var fsc = new float[32];
+ bool FFinite() { foreach (var v in fbuf) if (!float.IsFinite(v) || Math.Abs(v) > 8f) return false; return true; }
+ void FRender(int frames = 4096, double at = 0.2) { fe.Seek(at); fe.Play(); fe.RenderOffline(fbuf, frames); fe.StopTransport(); }
+ int FScope() => fe.DeviceScope(ft, fdi, fsc, fsc.Length);
+ // A tail window (skip the first 2048 frames so the ~15 ms param glide and the line have settled).
+ float Tail() { double sum = 0; for (int i = 2048 * 2; i < 4096 * 2; i++) sum += fbuf[i] * (double)fbuf[i]; return (float)Math.Sqrt(sum / (2048 * 2)); }
+ fe.SetBpm(120);
+
+ // Every waveform renders audible + finite, incl. extreme feedback both ways.
+ for (int wv = 0; wv < 3; wv++)
+ foreach (float fbn in new[] { 0f, 0.5f, 1f })
+ {
+ fe.DeviceSetParam(ft, fdi, 5, wv / 2f);
+ fe.DeviceSetParam(ft, fdi, 3, fbn);
+ FRender();
+ Check(Rms(fbuf, 4096) > 1e-3f && FFinite(), $"Flanger wave {wv} feedback {(fbn - 0.5f) * 190:+0;-0} % is audible + stable");
+ }
+
+ // The comb is real: a static 440 Hz sine drops into the notch at τ = 1/880 s and passes at τ = 1/440 s.
+ fe.DeviceSetParam(ft, fdi, 2, 0f); // Depth 0 → static comb
+ fe.DeviceSetParam(ft, fdi, 3, 0.5f); // no feedback
+ fe.DeviceSetParam(ft, fdi, 4, 0.5f); // dry = wet
+ float DelayNorm(double ms) => (float)(Math.Log(ms / 0.1) / Math.Log(80));
+ fe.DeviceSetParam(ft, fdi, 1, DelayNorm(1000.0 / 880));
+ FRender();
+ float notch = Tail();
+ fe.DeviceSetParam(ft, fdi, 1, DelayNorm(1000.0 / 440));
+ FRender();
+ float pass = Tail();
+ Check(notch < pass * 0.1f, $"440 Hz falls into the notch at τ 1.14 ms ({20 * Math.Log10(notch / Math.Max(1e-9f, pass)):0.0} dB vs the peak)");
+ FScope();
+ Check(Math.Abs(fsc[3] - 1000f / 440) < 0.01f && Math.Abs(fsc[14] - 220f) < 3f,
+ $"scope: τ {fsc[3]:0.000} ms, first notch {fsc[14]:0} Hz (= 1 / 2τ)");
+ Check(fsc[17] < -30f, $"dry = wet without feedback nulls deep ({fsc[17]:0.0} dB)");
+ // Negative feedback mirrors the comb: the notch moves to 1/τ, the peak to 1/2τ.
+ fe.DeviceSetParam(ft, fdi, 3, 0.5f - 0.7f / 1.9f); // −70 %
+ FRender(); FRender();
+ float negNotch = Tail(); // τ = 1/440 s → 440 Hz is now a notch
+ fe.DeviceSetParam(ft, fdi, 1, DelayNorm(1000.0 / 880));
+ FRender(); FRender();
+ float negPeak = Tail();
+ Check(negNotch < negPeak * 0.2f, $"negative feedback mirrors the comb (440 Hz at τ 2.27 ms {20 * Math.Log10(negNotch / Math.Max(1e-9f, negPeak)):0.0} dB vs τ 1.14 ms)");
+ FScope();
+ Check(Math.Abs(fsc[14] - 880f) < 5f && fsc[17] < -12f, $"scope: negative feedback's first notch at 1/τ ({fsc[14]:0} Hz, {fsc[17]:0.0} dB)");
+ fe.DeviceSetParam(ft, fdi, 3, 0.5f + 0.9f / 1.9f); // +90 %
+ FScope();
+ Check(fsc[18] > 10f, $"feedback +90 % raises the comb's peaks ({fsc[18]:+0.0} dB)");
+ fe.DeviceSetParam(ft, fdi, 3, 0.5f);
+
+ // Mix 0 is dry.
+ fe.DeviceSetParam(ft, fdi, 4, 0f);
+ fe.DeviceSetParam(ft, fdi, 1, DelayNorm(1000.0 / 880));
+ FRender(); FRender(); // twice: let the ~15 ms Mix glide land
+ float dry0 = Tail();
+ fe.SetDeviceBypassed(ft, fdi, true); FRender(); float byp = Tail(); fe.SetDeviceBypassed(ft, fdi, false);
+ Check(Math.Abs(dry0 - byp) < byp * 0.01f, $"Mix 0 passes the dry signal ({dry0:0.0000} vs bypass {byp:0.0000})");
+ fe.DeviceSetParam(ft, fdi, 4, 0.5f);
+
+ // Depth + Stereo: the LFO sweeps τ, and the right channel runs offset from the left.
+ fe.DeviceSetParam(ft, fdi, 1, 0.735f);
+ fe.DeviceSetParam(ft, fdi, 2, 1f);
+ fe.DeviceSetParam(ft, fdi, 0, 1f); // 8 Hz
+ fe.DeviceSetParam(ft, fdi, 8, 1f); // 180°
+ fe.DeviceSetParam(ft, fdi, 5, 0f); // Sine: half a cycle later is the mirror
+ FRender(3001); FRender(3001);
+ FScope();
+ Check(Math.Abs(fsc[12] - 2.5f * 0.08f) < 0.01f && Math.Abs(fsc[13] - 2.5f * 1.92f) < 0.01f,
+ $"sweep range = Delay · (1 ± 0.92 · Depth) ({fsc[12]:0.00} … {fsc[13]:0.00} ms)");
+ Check(Math.Abs((fsc[3] - 2.5f) + (fsc[4] - 2.5f)) < 0.05f && Math.Abs(fsc[3] - fsc[4]) > 0.1f,
+ $"Stereo 180°: the channels swing opposite (τL {fsc[3]:0.00}, τR {fsc[4]:0.00} ms)");
+ fe.DeviceSetParam(ft, fdi, 8, 0f);
+ FRender(3001);
+ FScope();
+ Check(Math.Abs(fsc[3] - fsc[4]) < 1e-3f, $"Stereo 0°: both channels sweep together ({fsc[3]:0.000} / {fsc[4]:0.000})");
+
+ // Sync: the rate follows the tempo and the LFO locks to the song position.
+ fe.DeviceSetParam(ft, fdi, 6, 1f);
+ fe.DeviceSetParam(ft, fdi, 7, 4f / 8f); // 1/4 → 2 Hz at 120 BPM
+ FRender(); FScope();
+ Check(Math.Abs(fsc[6] - 2f) < 1e-3f && fsc[9] > 0.5f, $"Sync 1/4 at 120 BPM runs at 2 Hz, locked ({fsc[6]:0.000})");
+ Check(fe.DeviceText(ft, fdi, 0).Contains("sync 1/4"), $"status names the division ('{fe.DeviceText(ft, fdi, 0)}')");
+ fe.SetBpm(90);
+ FRender(); FScope();
+ Check(Math.Abs(fsc[6] - 1.5f) < 1e-3f, $"the synced rate follows a tempo change (90 BPM → {fsc[6]:0.000} Hz)");
+ fe.SetBpm(120);
+ fe.DeviceSetParam(ft, fdi, 6, 0f);
+
+ // Actions: restart the LFO, clear a ringing line.
+ fe.DeviceSetParam(ft, fdi, 0, 1f);
+ FRender(); FScope();
+ Check(fsc[23] >= 1f, $"free run: cycles run ({fsc[23]:0})");
+ fe.DeviceAction(ft, fdi, 0, 0, 0f);
+ FRender(32); FScope();
+ Check(fsc[23] < 1f && fsc[5] < 0.05f, $"device_action 0 restarts the LFO (cycle {fsc[23]:0}, phase {fsc[5]:0.000})");
+ fe.DeviceSetParam(ft, fdi, 2, 0f);
+ fe.DeviceSetParam(ft, fdi, 3, 1f); // +95 %: a long ring
+ fe.DeviceSetParam(ft, fdi, 4, 1f); // wet only
+ FRender(4096, 0.9); // fill the line from inside the clip
+ FRender(512, 3.0); float ring = Rms(fbuf, 512); // past the clip: the ring alone
+ FRender(4096, 0.9);
+ fe.DeviceAction(ft, fdi, 1, 0, 0f);
+ FRender(512, 3.0); float cleared = Rms(fbuf, 512);
+ Check(ring > 1e-3f && cleared < 1e-6f, $"device_action 1 clears the ringing line (ring {ring:0.0000} → {cleared:0.0e0})");
+ for (int i = 0; i < fpc; i++) fe.DeviceSetParam(ft, fdi, i, fe.DeviceParamDefault(ft, fdi, i));
+
+ Check(fe.DeviceText(ft, fdi, 1).Contains("notch") && fe.DeviceText(ft, fdi, 2).Contains("1/8T"),
+ "device text 1 = live reading, 2 = parameter guide with the division table");
+
+ // Clone.
+ fe.DeviceSetParam(ft, fdi, 3, 0.2f);
+ fe.DeviceSetParam(ft, fdi, 8, 0.9f);
+ int fdup = fe.DuplicateTrack(ft);
+ Check(fdup > 0 && fe.TrackDeviceBuiltinKind(fdup, fdi) == 23 && Math.Abs(fe.DeviceGetParam(fdup, fdi, 3) - 0.2f) < 1e-4f
+ && Math.Abs(fe.DeviceGetParam(fdup, fdi, 8) - 0.9f) < 1e-4f, "duplicate track clones the Flanger params");
+ fe.RemoveTrack(fdup);
+
+ // Automation drives Feedback.
+ int flane = fe.AddAutomationLane(ft, AutomationTarget.DeviceParam, fdi, 3);
+ Check(flane >= 0, "add Flanger Feedback automation lane");
+ fe.SetAutomationPoints(ft, flane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
+ fe.Seek(1.99); fe.Play(); fe.RenderOffline(fbuf, 4096); fe.StopTransport();
+ Check(fe.DeviceGetParam(ft, fdi, 3) > 0.8f, $"automation drives Flanger Feedback ({fe.DeviceGetParam(ft, fdi, 3):F2})");
+ fe.RemoveAutomationLane(ft, flane);
+ for (int i = 0; i < fpc; i++) fe.DeviceSetParam(ft, fdi, i, fe.DeviceParamDefault(ft, fdi, i));
+
+ // MCP: listed, read and set in units.
+ {
+ var ftools = new Nota.Mcp.Tools.DeviceTools(fe, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ Check(ftools.ListDeviceKinds().Any(k => k.Kind == 23 && k.Name == "Nota Flanger"), "MCP lists Nota Flanger (kind 23)");
+ FRender();
+ var r0 = ftools.ReadFlanger(ft, fdi).Result;
+ Check(r0.Waveform == "Triangle" && !r0.Sync && Math.Abs(r0.DelayMs - 2.5) < 0.02 && Math.Abs(r0.FeedbackPercent - 70) < 0.6
+ && r0.Mode == "positive" && Math.Abs(r0.StereoDeg - 90) < 0.6 && r0.Summary.Length > 0 && r0.Live.Length > 0,
+ $"MCP read_flanger reports the defaults ({r0.Waveform}, {r0.DelayMs} ms, {r0.FeedbackPercent} %, {r0.Mode})");
+ var r1 = ftools.SetFlanger(ft, fdi, waveform: "saw", division: "1/8T", delayMs: 1, depthPercent: 40, feedbackPercent: -80,
+ mixPercent: 60, stereoDeg: 180).Result;
+ Check(r1.Waveform == "Saw" && r1.Sync && r1.Division == "1/8T" && Math.Abs(r1.DelayMs - 1) < 0.01 && Math.Abs(r1.DepthPercent - 40) < 0.1
+ && Math.Abs(r1.FeedbackPercent + 80) < 0.6 && r1.Mode == "negative" && Math.Abs(r1.MixPercent - 60) < 0.1 && r1.StereoDeg == 180,
+ $"MCP set_flanger writes in units ({r1.Waveform}, {r1.Division}, {r1.DelayMs} ms, {r1.FeedbackPercent} %)");
+ var r2 = ftools.SetFlanger(ft, fdi, rateHz: 0.5).Result;
+ Check(!r2.Sync && Math.Abs(0.02 * Math.Pow(400, fe.DeviceGetParam(ft, fdi, 0)) - 0.5) < 1e-3, "set_flanger rateHz switches to free run");
+ bool threw = false;
+ try { ftools.SetFlanger(ft, fdi, division: "1/5").GetAwaiter().GetResult(); } catch (ArgumentException) { threw = true; }
+ Check(threw, "set_flanger rejects an unknown division");
+ for (int i = 0; i < fpc; i++) fe.DeviceSetParam(ft, fdi, i, fe.DeviceParamDefault(ft, fdi, i));
+ }
+
+ // Factory presets: ≥ 25, every named param exists, each applies in place and renders.
+ {
+ var names = new HashSet<string>(fnames);
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 23).ToList();
+ Check(mine.Count >= 25, $"Nota Flanger 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 Flanger preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(fe, p.Id, ft, fdi).Length != 0) { pf++; continue; }
+ FRender();
+ if (!FFinite() || Rms(fbuf, 4096) < 1e-3f) pf++;
+ }
+ Check(pf == 0, $"every Flanger preset applies and renders ({pf} failed)");
+ cat.ApplyInPlace(fe, "flanger/Tin Robot", ft, fdi);
+ Check(fe.DeviceGetParam(ft, fdi, 6) > 0.5f && Math.Abs(fe.DeviceGetParam(ft, fdi, 7) - 6f / 8f) < 1e-3f
+ && Math.Abs(fe.DeviceGetParam(ft, fdi, 3) - (0.5f + 0.9f / 1.9f)) < 1e-3f, "Tin Robot preset: synced 1/8, feedback +90 %");
+ cat.ApplyInPlace(fe, "flanger/Jet Plane", ft, fdi);
+ bool isDefault = Enumerable.Range(0, fpc).All(i => Math.Abs(fe.DeviceGetParam(ft, fdi, i) - fe.DeviceParamDefault(ft, fdi, i)) < 2e-3f);
+ Check(isDefault, "Jet Plane preset = the device defaults");
+ }
+}
+
// ===================== Nota Auto Shift (effect kind 10) ===================
Console.WriteLine("-- Nota Auto Shift (effect kind 10) --");
{