Skip to content

armgit / nota

Public Imported from GitHub
0

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

Redesign of Beat Repeat

Egor Khindikaynen1f5cae8e9f82
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cacf585..ef5cc1b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,39 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Beat Repeat shows what it captures and repeats, and gains a triplet grid, a filter
+ type and a Repeat you can latch.** The card moves onto the 700 × 260 frame of Shutter and
+ Auto Shift — a REPEAT column (the input and the repeats' level, the repeat count), a centre
+ panel with **Timeline**, **Slices** and **Filter** tabs, a **Character** / **Output** panel
+ and a status strip. Interval and Grid move out of the button grid into the row over the
+ graph; Chance, Gate, Offset and Variation become knobs under it:
+ - **Timeline** — two intervals on the grid, each step a bar of the input level: dry steps
+ dim, the captured slice in full brass, every repeat a step dimmer as it decays, with the
+ trigger points, bar numbers and the playhead.
+ - **Slices** — the last interval's sound with the gate shaded from the offset and the
+ captured slice in brass; drag the offset line or the gate's end. New **Triplet** switch
+ turns any grid into triplets (the old 1/8T and 1/16T settings still load as they were).
+ - **Filter** — the repeat filter's curve, now **LP**, **BP** or **HP**, with Width in real
+ octaves; drag the node for the frequency and a band edge for the width. New **Narrow with
+ repeats**: each repeat narrows the band and follows the pitch down.
+ - **Character / Output** — pitch, pitch decay, decay and volume; a state box (waiting,
+ capture, repeat n of N, held); in / repeat / out meters, Mix, **Repeat** and **Reset**.
+ New **Latch** makes the Repeat button stay on after a click. Repeat now holds the slice
+ it caught until you let go, instead of catching a new one every gate.
+ - Bars follow the time signature (1 bar in 3/4 is three beats). Variation now lets the grid
+ float up to six doubling / halving steps per trigger. Slice edges are faded so repeats
+ don't click.
+ - **31 factory presets**, up from six — stutters, glitch, pitch drops (Tape Drop, Dive
+ Bomb), filtered repeats, drum and vocal chops, and performance presets for the Repeat
+ button. The four new parameters are appended and default to the old sound, so older
+ projects open unchanged. Parameter 15 is renamed from *Latch* to **Repeat** (it always
+ meant "repeat now"), so a user preset saved with the old *Latch* on now turns on the new
+ Latch switch instead. Every parameter automates (the filter's grouped under *Filter* in
+ the lane menu), MIDI-learns, saves in a preset and is reachable over MCP.
+ `get_device_text` returns the status line, the live reading and a guide to the parameter
+ values, `device_action` 0 resets and 1 fires a repeat now, and the new `read_beat_repeat`
+ returns the state, the pass, the slice, the repeat's gain / pitch / filter, the levels,
+ bar and beat, and the timeline.
- **Nota Auto Shift is a full vocal tuner: it keeps the voice's character, learns the key and
can follow a MIDI part.** The card moves onto the 700 × 260 frame of Shutter, Utility and
Valve — a PITCH column (where the voice sits and the correction now), a centre panel with
@@ -282,6 +315,11 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
returns the compressor's status line.
### Fixed
+- **Nota Beat Repeat's first pass and filter width.** With Pitch above 0 the capture pass
+ read ahead of the audio just written, so the first slice of every burst played stale audio
+ from seconds earlier; the capture now plays through as it is and the pitch applies to the
+ repeats. The filter's Width was labelled in octaves but raised the Q, so turning it up made
+ the band narrower; it is now the band in octaves (Filtered Chops is retuned to match).
- **Nota Auto Shift's timing, Mix and Follow.** The shifter delayed the voice by about 16 ms
without telling the engine, so a tuned vocal sat late against the other tracks; the delay is
now reported and compensated. Mix blended that delayed voice with an undelayed dry one, which
diff --git a/FEATURES.md b/FEATURES.md
index 42ccd77f..395b50a1 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -389,8 +389,12 @@ and user presets, automation, persistence and cloning.
mix, output, oversampling. Tabs: Curve (the transfer curve, the input on it) / Wear (pitch
drift over 4 s in cents) / Output (harmonics against the hiss floor) and Tone / Output, with
a STATE column and a status strip. 30 factory presets. MCP: `read_vintage`.
-- **Nota Beat Repeat** (9) — beat repeat with Mix/Insert/Gate modes, Chance, Gate, Repeat,
- Latch, INTERVAL/GRID, Pitch/Decay/Volume, FILTER, Mix; a TIMELINE visualiser.
+- **Nota Beat Repeat** (11) — tempo-synced repeater: Interval (1/8 … 4 bars, bars follow the
+ time signature), Offset, Grid with Triplet, Variation, Chance, Gate; Mix / Insert / Gate
+ modes; Pitch and Pitch Decay, Decay, Volume; a repeat filter (LP / BP / HP, width in
+ octaves, optionally narrowing with each repeat); Repeat (hold or Latch) and Mix. Timeline /
+ Slices / Filter graphs (drag the offset, the gate and the filter), a REPEAT column, a state
+ box and meters; 31 factory presets; MCP `read_beat_repeat`.
- **Nota Orbit** (10, formerly Auto Pan) — auto-pan and tremolo, L/R phase (0° = tremolo …
180° = pan), 5 LFO shapes, Shape, Mix.
- **Nota Crush** (12) — bit crusher: Bit Depth, Sample Rate, Drive, Wet, Anti-Alias;
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index 33a0aab3..265d7e2e 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -392,10 +392,11 @@ public sealed partial class ArrangementView
// ("SC HP", "SC Gain" …), the Auto Filter its sources ("Env", "LFO", "Mod"), Nota
// Vintage its tone and wow ("Tone Low", "Wow Rate" …), Nota Valve its mic ("Mic Distance" …),
// Nota Utility its mono, phase and true-peak params ("Mono Freq", "Invert L", "TP Ceiling" …),
- // Nota Shutter its detector ("Det HP", "Det LP", "Det Filter") and Nota Auto Shift its
- // scale notes, detector and MIDI target ("Note C#", "Det Low", "MIDI Glide" …):
+ // Nota Shutter its detector ("Det HP", "Det LP", "Det Filter"), Nota Auto Shift its
+ // scale notes, detector and MIDI target ("Note C#", "Det Low", "MIDI Glide" …) and Nota
+ // Beat Repeat its repeat filter ("Filter Freq", "Filter Type", "Filter Narrow" …):
// a word shared by two or more params becomes a submenu.
- bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 4 or 6 or 7 or 8 or 10 or 19 or 20 or 21 or 22;
+ bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 4 or 6 or 7 or 8 or 10 or 11 or 19 or 20 or 21 or 22;
var names = new string[builtinPc];
for (int p = 0; p < builtinPc; p++) names[p] = e.DeviceParamName(t.Id, d, p);
static string Head(string n) { int sp = n.IndexOf(' '); return sp > 0 ? n[..sp] : ""; }
diff --git a/src/managed/Nota.App/Controls/BeatRepeatViews.cs b/src/managed/Nota.App/Controls/BeatRepeatViews.cs
new file mode 100644
index 00000000..674c4e0c
--- /dev/null
+++ b/src/managed/Nota.App/Controls/BeatRepeatViews.cs
@@ -0,0 +1,323 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Beat Repeat (device kind 11) card windows, read from the engine's telemetry
+// (BeatRepeat.h scopeRead) so the picture is what the repeater does:
+// · BrTimelineView — the Timeline tab: two intervals as grid steps, each a bar of the input
+// level — dry steps dim, the captured slice in full brass, every repeat a step dimmer as it
+// decays — with the trigger points, the bar numbers and the playhead.
+// · BrSlicesView — the Slices tab: the last interval's input (teal) on the grid, the gate
+// window from the offset shaded, the captured slice in brass. Drag the offset line or the
+// gate's end sideways (16ths of the interval); double-click resets.
+// · BrFilterView — the Filter tab: the repeat filter (LP / BP / HP) for the first repeat in
+// brass and a later one (teal dashed) when the band narrows and follows the pitch. Drag
+// the node for the frequency, a band edge for the width.
+// Drag contract from ShDragView: left button only, a gesture per drag, double-click resets
+// the handle, right-click bubbles to the MIDI-learn menu.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class BrTimelineView : Control
+{
+ private float[] _lvl = Array.Empty<float>(), _kind = Array.Empty<float>(), _gain = Array.Empty<float>();
+ private int _n;
+ private double _winBeats = 8, _intervalBeats = 4, _gridBeats = 0.25, _barBeats = 4, _offset, _phase;
+ private bool _playing;
+ private string _title = "Capture and repeat";
+
+ public BrTimelineView() { ClipToBounds = true; MinHeight = 36; }
+
+ /// <summary>The cells (level dB · kind 0 dry / 1 capture / 2 repeat · repeat gain) over the
+ /// window, its length and the interval / grid / bar in beats, the trigger offset (0..1 of the
+ /// interval) and the playhead (0..1 of the window).</summary>
+ public void Set(float[] src, int at, int n, double winBeats, double intervalBeats, double gridBeats, double barBeats,
+ double offset, double phase, bool playing, string title)
+ {
+ if (_lvl.Length != n) { _lvl = new float[n]; _kind = new float[n]; _gain = new float[n]; }
+ if (n > 0 && at + 3 * n <= src.Length)
+ {
+ Array.Copy(src, at, _lvl, 0, n);
+ Array.Copy(src, at + n, _kind, 0, n);
+ Array.Copy(src, at + 2 * n, _gain, 0, n);
+ }
+ _n = n; _winBeats = Math.Max(0.25, winBeats); _intervalBeats = Math.Max(0.125, intervalBeats);
+ _gridBeats = Math.Max(1.0 / 64, gridBeats); _barBeats = Math.Max(1, barBeats); _offset = offset; _phase = phase;
+ _playing = playing; _title = title;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 6, x1 = w - 6, top = 16, bot = h - 13;
+ double X(double beats) => x0 + beats / _winBeats * (x1 - x0);
+
+ // Grid steps over the window (at most 64 drawn; finer grids share a column).
+ int steps = (int)Math.Clamp(Math.Round(_winBeats / _gridBeats), 1, 64);
+ double sw = (x1 - x0) / steps;
+ double gap = sw > 8 ? 3 : sw > 4 ? 1 : 0.5;
+ if (_n > 0)
+ for (int s = 0; s < steps; s++)
+ {
+ int a = (int)Math.Floor((double)s * _n / steps), b = Math.Max(a + 1, (int)Math.Floor((double)(s + 1) * _n / steps));
+ double lvl = -120, g = 0; int kind = 0;
+ for (int i = a; i < b && i < _n; i++)
+ {
+ lvl = Math.Max(lvl, _lvl[i]);
+ int k = (int)Math.Round(_kind[i]);
+ if (k > kind || k == kind && _gain[i] > g) { kind = Math.Max(kind, k); g = Math.Max(g, _gain[i]); }
+ }
+ double v = Math.Clamp((lvl + 48) / 48, 0, 1);
+ double bh = Math.Max(2, v * (bot - top));
+ var r = new Rect(x0 + s * sw + gap / 2, bot - bh, Math.Max(1, sw - gap), bh);
+ IBrush fill = kind switch
+ {
+ 1 => NotaPalette.Accent,
+ 2 => NotaPalette.Wash(NotaPalette.Accent, (byte)Math.Clamp(60 + 150 * g, 50, 210)),
+ _ => NotaPalette.Wash(NotaPalette.TextTertiary, 0x38),
+ };
+ ctx.DrawRectangle(fill, null, r, 2, 2);
+ }
+
+ // Interval boundaries (dashed) and the trigger points (brass ticks at the top).
+ var dash = new Pen(NotaPalette.BorderStrong, 1, new DashStyle(new double[] { 2, 3 }, 0));
+ for (double b = _intervalBeats; b < _winBeats - 1e-6; b += _intervalBeats) ctx.DrawLine(dash, new Point(X(b), top - 2), new Point(X(b), bot));
+ for (double b = _offset * _intervalBeats; b < _winBeats - 1e-6; b += _intervalBeats)
+ {
+ double x = X(b);
+ ctx.DrawLine(new Pen(NotaPalette.Accent, 1.4), new Point(x, top - 3), new Point(x, top + 3));
+ }
+
+ // Playhead.
+ if (_playing)
+ {
+ double px = x0 + Math.Clamp(_phase, 0, 1) * (x1 - x0);
+ ctx.DrawLine(new Pen(NotaPalette.AccentBright, 2), new Point(px, top - 4), new Point(px, bot));
+ }
+
+ NotaGraph.Title(ctx, frame, _title);
+ NotaGraph.Legend(ctx, w - 6, 3, ("capture", NotaPalette.AccentBright, NotaGraph.Mark.Area),
+ ("repeat · decay", NotaPalette.AccentDim, NotaGraph.Mark.Area), ("dry", NotaPalette.TextTertiary, NotaGraph.Mark.Area));
+
+ // Bar numbers along the bottom (the window starts on a bar when the interval is ≥ a bar).
+ int bars = (int)Math.Ceiling(_winBeats / _barBeats - 1e-6);
+ if (bars >= 1 && _winBeats >= _barBeats)
+ for (int b = 0; b <= bars; b++)
+ {
+ double bx = X(b * _barBeats);
+ if (bx > x1 - 4) { NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, NotaNum.F($"{b + 1}")); break; }
+ ctx.DrawText(NotaGraph.AxisText(NotaNum.F($"{b + 1}")), new Point(bx, h - 11));
+ }
+ else
+ {
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "beat 1");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, NotaNum.F($"{_winBeats:0.##}\u2009beats"));
+ }
+ }
+}
+
+internal sealed class BrSlicesView : ShDragView
+{
+ public const int HOffset = 0, HGate = 1;
+ private float[] _wave = Array.Empty<float>();
+ private int _n;
+ private double _offset, _gate = 0.5, _slice = 1.0 / 16, _gridFrac = 1.0 / 16;
+ private bool _repeating;
+
+ /// <summary>The interval's input peaks, the offset and gate as fractions of the interval
+ /// (steps / 16), the slice and grid step as fractions of it, and whether a repeat plays.</summary>
+ public void Set(float[] src, int at, int n, double offset, double gate, double slice, double gridFrac, bool repeating)
+ {
+ if (_wave.Length != n) _wave = new float[n];
+ if (n > 0 && at + n <= src.Length) Array.Copy(src, at, _wave, 0, n);
+ _n = n; _offset = offset; _gate = gate; _slice = slice; _gridFrac = Math.Max(1.0 / 256, gridFrac); _repeating = repeating;
+ InvalidateVisual();
+ }
+
+ private double X0 => 4;
+ private double W => Math.Max(1, Bounds.Width - 8);
+ private double Xf(double frac) => X0 + Math.Clamp(frac, 0, 1) * W;
+ private double GateEnd => Math.Min(1, _offset + Math.Max(_gate, _slice));
+
+ protected override int Hit(Point p)
+ {
+ double dOff = Math.Abs(p.X - Xf(_offset)), dGate = Math.Abs(p.X - Xf(GateEnd));
+ if (dGate <= 8 && dGate < dOff) return HGate;
+ return HOffset; // anywhere else: the offset, the window's main handle
+ }
+ protected override StandardCursorType CursorFor(int handle) => StandardCursorType.SizeWestEast;
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ double f = Math.Clamp((p.X - X0) / W, 0, 1);
+ double v = handle == HOffset ? f : f - _offset;
+ return Math.Round(Math.Clamp(v, 0, 1) * 16) / 16; // 16ths of the interval
+ }
+
+ 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 = 16, bot = h - 13, mid = (top + bot) / 2, amp = (bot - top) / 2;
+
+ // Gate window shaded from the offset.
+ ctx.FillRectangle(NotaPalette.AccentSubtle, new Rect(Xf(_offset), 0, Math.Max(1, Xf(GateEnd) - Xf(_offset)), h));
+
+ // Grid steps (dim) and the 16ths of the interval inside the gate (dashed).
+ int steps = (int)Math.Clamp(Math.Round(1 / _gridFrac), 1, 128);
+ for (int s = 1; s < steps; s++)
+ {
+ double f = (double)s / steps;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(Xf(f), 0), new Point(Xf(f), h));
+ }
+ ctx.DrawLine(NotaGraph.GridPen, new Point(0, mid), new Point(w, mid));
+
+ // The interval's input (teal), the captured slice (brass).
+ if (_n > 1)
+ {
+ var inPen = new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xB0), Math.Max(1, Math.Min(2, W / _n * 0.6)));
+ var slicePen = new Pen(NotaPalette.AccentBright, Math.Max(1.2, Math.Min(2.2, W / _n * 0.7)));
+ double s0 = _offset, s1 = Math.Min(1, _offset + _slice);
+ for (int i = 0; i < _n; i++)
+ {
+ double f = (i + 0.5) / _n;
+ double a = Math.Clamp(_wave[i], 0, 1.2) / 1.2;
+ a = a > 0 ? Math.Max(0.02, Math.Sqrt(a)) : 0; // perceptual: quiet material stays visible
+ if (a <= 0) continue;
+ double x = Xf(f);
+ bool inSlice = f >= s0 && f < s1;
+ ctx.DrawLine(inSlice ? slicePen : inPen, new Point(x, mid - a * amp), new Point(x, mid + a * amp));
+ }
+ }
+
+ bool hotO = Active == HOffset, hotG = Active == HGate;
+ ctx.DrawLine(new Pen(NotaPalette.Accent, hotO ? 1.6 : 1.1), new Point(Xf(_offset), 0), new Point(Xf(_offset), h));
+ ctx.DrawLine(new Pen(hotG ? NotaPalette.Accent : NotaPalette.AccentDim, hotG ? 1.6 : 1.1, new DashStyle(new double[] { 3, 3 }, 0)),
+ new Point(Xf(GateEnd), 0), new Point(Xf(GateEnd), h));
+
+ NotaGraph.Title(ctx, frame, _repeating ? "Captured sound · repeating" : "Captured sound");
+ NotaGraph.Legend(ctx, w - 6, 3, ("slice", NotaPalette.AccentBright, NotaGraph.Mark.Line), ("input", NotaPalette.TealBright, NotaGraph.Mark.Line));
+ int off = (int)Math.Round(_offset * 16), gate = (int)Math.Round(_gate * 16);
+ double ox = Math.Clamp(Xf(_offset) + 3, 4, w - 110);
+ Text(ctx, NotaNum.F($"offset {off}/16"), ox, h - 11, NotaPalette.AccentBright);
+ double gx = Math.Clamp(Xf(GateEnd) + 3, ox + 62, w - 70);
+ if (gx < w - 60) Text(ctx, NotaNum.F($"gate {gate}/16"), gx, h - 11, NotaPalette.AccentDim);
+ TextR(ctx, "16/16", w - 4, h - 11);
+ }
+}
+
+internal sealed class BrFilterView : ShDragView
+{
+ public const int HFreq = 0, HWidthLo = 1, HWidthHi = 2;
+ private const double FMin = 50, FMax = 18000, DbTop = 12, DbBot = -36;
+ private double _hz = 949, _oct = 2, _laterHz = 949, _laterOct = 2;
+ private int _type = 1, _laterRepeat;
+ private bool _on;
+
+ /// <summary>The filter for the first repeat (Hz, octaves), the type 0 LP / 1 BP / 2 HP,
+ /// and a later repeat's band (<paramref name="laterRepeat"/> = 0 hides it).</summary>
+ public void Set(bool on, int type, double hz, double oct, int laterRepeat, double laterHz, double laterOct)
+ {
+ _on = on; _type = type; _hz = hz; _oct = oct; _laterRepeat = laterRepeat; _laterHz = laterHz; _laterOct = laterOct;
+ InvalidateVisual();
+ }
+
+ private double X(double f) => Math.Log(Math.Clamp(f, FMin, FMax) / FMin) / Math.Log(FMax / FMin) * Bounds.Width;
+ private double FAt(double x) => FMin * Math.Pow(FMax / FMin, Math.Clamp(x / Math.Max(1, Bounds.Width), 0, 1));
+ private double Top => 16;
+ private double Bot => Bounds.Height - 13;
+ private double Yd(double db) => Top + Math.Clamp((DbTop - db) / (DbTop - DbBot), 0, 1) * (Bot - Top);
+
+ private static double Q(double oct, int type)
+ {
+ double n2 = Math.Pow(2, oct), q = Math.Sqrt(n2) / (n2 - 1);
+ return type == 1 ? q : Math.Max(0.5, q);
+ }
+ private static double Mag(double f, double fc, double oct, int type)
+ {
+ double x = f / fc, q = Q(oct, type);
+ double den = Math.Sqrt(Math.Pow(1 - x * x, 2) + Math.Pow(x / q, 2));
+ double m = type switch { 0 => 1 / den, 2 => x * x / den, _ => x / q / den };
+ return 20 * Math.Log10(Math.Max(1e-6, m));
+ }
+ private (double lo, double hi) Band(double hz, double oct) => (hz / Math.Pow(2, oct / 2), hz * Math.Pow(2, oct / 2));
+
+ protected override int Hit(Point p)
+ {
+ if (!_on) return -1;
+ var (lo, hi) = Band(_hz, _oct);
+ double dF = Math.Abs(p.X - X(_hz)), dL = Math.Abs(p.X - X(lo)), dH = Math.Abs(p.X - X(hi));
+ if (_type == 1 && dL < dF && dL <= 8) return HWidthLo;
+ if (_type == 1 && dH < dF && dH <= 8) return HWidthHi;
+ return HFreq;
+ }
+ protected override StandardCursorType CursorFor(int handle) => StandardCursorType.SizeWestEast;
+ protected override double DragTo(int handle, Point start, Point p, double v0)
+ {
+ double f = FAt(p.X);
+ if (handle == HFreq) return Math.Log(f / FMin) / Math.Log(FMax / FMin);
+ double oct = 2 * Math.Abs(Math.Log2(f / _hz));
+ return (oct - 0.5) / 3;
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ Grid(ctx, w, h, 5);
+ ctx.DrawLine(new Pen(NotaPalette.GraphBorder, 1), new Point(0, Yd(0)), new Point(w, Yd(0)));
+
+ StreamGeometry Curve(double hz, double oct)
+ {
+ var g = new StreamGeometry();
+ int px = Math.Max(24, (int)(w / 2));
+ using var c = g.Open();
+ for (int i = 0; i <= px; i++)
+ {
+ double x = (double)i / px * w;
+ var pt = new Point(x, Yd(Mag(FAt(x), hz, oct, _type)));
+ if (i == 0) c.BeginFigure(pt, false); else c.LineTo(pt);
+ }
+ return g;
+ }
+
+ if (_on && _laterRepeat > 1)
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Teal, 1.2, new DashStyle(new double[] { 3, 3 }, 0)), Curve(_laterHz, _laterOct));
+ ctx.DrawGeometry(null, _on ? NotaGraph.PrimaryPen : NotaGraph.SecondaryPen(NotaPalette.BorderStrong, 1.6), Curve(_hz, _oct));
+
+ if (_on)
+ {
+ var node = new Point(X(_hz), Yd(Mag(_hz, _hz, _oct, _type)));
+ if (_type == 1)
+ {
+ var (lo, hi) = Band(_hz, _oct);
+ double y = Yd(-3);
+ var edgePen = new Pen(Active is HWidthLo or HWidthHi ? NotaPalette.Accent : NotaPalette.AccentDim, 1, new DashStyle(new double[] { 2, 3 }, 0));
+ ctx.DrawLine(edgePen, new Point(X(lo), y), new Point(X(hi), y));
+ Text(ctx, NotaNum.F($"{_oct:0.0}\u2009oct"), Math.Clamp(X(lo) + 2, 4, w - 50), y + 2, NotaPalette.AccentDim);
+ }
+ NotaGraph.Node(ctx, node, Active == HFreq || Active < 0);
+ }
+
+ NotaGraph.Title(ctx, frame, _on ? "Repeat filter" : "Repeat filter · off");
+ if (_on && _laterRepeat > 1)
+ NotaGraph.Legend(ctx, w - 6, 3, ("repeat 1", NotaPalette.AccentBright, NotaGraph.Mark.Line),
+ (NotaNum.F($"repeat {_laterRepeat}"), NotaPalette.TealBright, NotaGraph.Mark.Dashed));
+ static string Hz(double f) => f >= 1000 ? NotaNum.F($"{f / 1000:0.0}\u2009k") : NotaNum.F($"{f:0}\u2009Hz");
+ Text(ctx, "50", 4, h - 11);
+ TextR(ctx, "18\u2009k", w - 4, h - 11);
+ if (_on) Text(ctx, Hz(_hz), Math.Clamp(X(_hz) - 14, 22, w - 60), h - 11, NotaPalette.AccentBright);
+ }
+}
diff --git a/src/managed/Nota.App/Controls/BeatRepeatViz.cs b/src/managed/Nota.App/Controls/BeatRepeatViz.cs
deleted file mode 100644
index d03d455d..00000000
--- a/src/managed/Nota.App/Controls/BeatRepeatViz.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Beat Repeat timeline (mockup 3h): the interval window drawn as 64 slots — empty
-// slots are wells, the captured slice is full brass, and each repeat generation is one
-// step dimmer so the decay is visible — with beat/bar ticks and the live playhead. It
-// shows the effect (capture → repeats → fade), not a flat rectangle.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class BeatRepeatViz : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.GraphBorder;
- private static readonly IBrush Well = NotaPalette.SurfaceInset;
- private static readonly IBrush WellBd = NotaPalette.Wash(NotaPalette.BorderStrong, 0x40);
- private static readonly IBrush Muted = NotaPalette.TextTertiary;
- private static readonly IBrush Faint = NotaPalette.TextAxis;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush Sub = NotaPalette.TextSecondary;
- private static readonly IBrush BarLine = NotaPalette.TextAxis;
- private static Color Brass => NotaPalette.Accent.Color;
- private static readonly Typeface Mono = NotaFonts.Mono;
- private static readonly Typeface Bold = NotaFonts.SansBold;
-
- private float[] _slots = Array.Empty<float>();
- private int _n;
- private double _intervalBeats = 4, _bpm = 120, _phase;
-
- public BeatRepeatViz() { MinWidth = 200; MinHeight = 90; }
-
- public void Set(float[] slots, int n, double intervalBeats, double bpm, double phase)
- { _slots = slots; _n = n; _intervalBeats = Math.Max(0.25, intervalBeats); _bpm = bpm; _phase = Math.Clamp(phase, 0, 1); InvalidateVisual(); }
-
- private static IBrush BrassA(double v) => new SolidColorBrush(Color.FromArgb((byte)(255 * Math.Clamp(0.30 + 0.70 * v, 0, 1)), Brass.R, Brass.G, Brass.B));
-
- public override void Render(DrawingContext g)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- NotaGraph.Window(g, new Rect(0, 0, w, h));
-
- double pad = 6;
- double headY = pad, x0 = pad, x1 = w - pad;
- double top = pad + 13, bot = h - pad - 21, labY = bot + 1, ly = h - pad - 8;
-
- // Header: capture readout + BPM.
- g.DrawText(new FormattedText("TIMELINE", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Bold, 8, Muted), new Point(x0, headY));
- int onsets = 0; for (int k = 1; k < _n; k++) if (_slots[k] > 1e-3f && _slots[k - 1] <= 1e-3f) onsets++;
- if (_n > 0 && _slots.Length > 0 && _slots[0] > 1e-3f) onsets++;
- double bars = _intervalBeats / 4.0;
- string capBar = bars >= 1 ? $"{bars:0.#} bar" : $"1/{4.0 / _intervalBeats:0}";
- g.DrawText(new FormattedText($"capture {capBar} → {onsets} rep", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, AmberLit), new Point(x0 + 62, headY));
- var bpm = new FormattedText($"{_bpm:0}\u2009BPM", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Muted);
- g.DrawText(bpm, new Point(x1 - bpm.Width, headY));
-
- // Slots.
- int n = Math.Max(1, _n);
- double sw = (x1 - x0) / n;
- for (int k = 0; k < n; k++)
- {
- float v = k < _slots.Length ? _slots[k] : 0f;
- var r = new Rect(x0 + k * sw + 0.5, top, Math.Max(1, sw - 1), bot - top);
- if (v <= 1e-3f) g.DrawRectangle(Well, new Pen(WellBd, 1), r, 1, 1);
- else g.DrawRectangle(BrassA(v), null, r, 1, 1);
- }
-
- // Beat / bar ticks + bar numbers.
- int beats = (int)Math.Round(_intervalBeats);
- for (int b = 1; b < beats; b++)
- {
- double x = x0 + (b / _intervalBeats) * (x1 - x0);
- g.DrawLine(new Pen(b % 4 == 0 ? BarLine : WellBd, 1), new Point(x, top), new Point(x, bot));
- }
- int barsN = Math.Max(1, (int)Math.Round(_intervalBeats / 4.0));
- for (int b = 0; b < barsN; b++)
- g.DrawText(new FormattedText((b + 1).ToString(), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Faint), new Point(x0 + (b / (double)barsN) * (x1 - x0) + 1, labY));
-
- // Playhead.
- double px = x0 + _phase * (x1 - x0);
- g.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x55), 3), new Point(px, top), new Point(px, bot));
- g.DrawLine(new Pen(AmberLit, 1.5), new Point(px, top), new Point(px, bot));
-
- // Legend.
- void Swatch(double x, byte a, string label)
- {
- g.DrawRectangle(new SolidColorBrush(Color.FromArgb(a, Brass.R, Brass.G, Brass.B)), null, new Rect(x, ly, 8, 8), 2, 2);
- g.DrawText(new FormattedText(label, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Sub), new Point(x + 11, ly - 1));
- }
- Swatch(x0, 255, "captured");
- Swatch(x0 + 78, 0x66, "repeat · decay");
- double phx = x0 + 192;
- g.DrawRectangle(AmberLit, null, new Rect(phx, ly, 2, 8));
- g.DrawText(new FormattedText("playhead", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Sub), new Point(phx + 6, ly - 1));
- }
-}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/BeatRepeatDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/BeatRepeatDeviceBody.cs
index 0309bbc7..5279cf62 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/BeatRepeatDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/BeatRepeatDeviceBody.cs
@@ -1,198 +1,706 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Beat Repeat (device kind 11) body, mockup 3h: a full
-// 700×260 shell with a LIVE strip (mode + chance + gate + Repeat/Latch), a GRID rail
-// (Interval / Grid buttons stating their musical consequence + Offset/Variation), the
-// TIMELINE viz (captured slice → fading repeats → playhead) and a REPEAT CHARACTER rail
-// (Pitch/Pitch Decay/Decay/Volume, a collapsing Filter, and Mix). Generic device params.
+// Detail · Devices — built-in Nota Beat Repeat body (tempo-synced repeater, device kind 11), a
+// build of the "Nota Beat Repeat" mockup (700 × 260) on the Shutter / Auto Shift frame: an
+// always-visible REPEAT column (the input and the repeats' level · the repeat count), a centre
+// panel with Timeline / Slices / Filter tabs — capture and repeats over two intervals on the
+// grid, the interval's sound with the offset, gate and slice on it (drag them), the repeat
+// filter with a later repeat's band — a right panel with Character / Output tabs, and a status
+// strip. Interval and Grid sit in the row over the graph; Chance, Gate, Offset and Variation
+// are knobs under it. The pictures come from the engine (BeatRepeat.h scopeRead). Every
+// control is a device param, so automation / MIDI learn / presets / A-B / persistence come for
+// free; Reset and the one-shot trigger are device actions.
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
+using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Nota.Application;
+using static Nota.App.DeviceCardKit;
namespace Nota.App;
internal sealed class BeatRepeatDeviceBody : IDeviceBody
{
- // Param indices — must match BeatRepeat.h.
- private const int Interval = 0, Offset = 1, GridP = 2, Variation = 3, Chance = 4, Gate = 5,
- Pitch = 6, PitchDecay = 7, Volume = 8, Decay = 9, FilterOn = 10,
- FilterFreq = 11, FilterWidth = 12, Mode = 13, MixP = 14, Latch = 15;
- private static readonly double[] Intervals = { 0.5, 1, 2, 4, 8, 16 };
- private static readonly string[] IntervalLbl = { "1/8", "1/4", "1/2", "1 Bar", "2 Bar", "4 Bar" };
- private static readonly string[] IntervalEvery = { "every 1/2 beat", "every 1 beat", "every 1/2 bar", "every 1 bar", "every 2 bars", "every 4 bars" };
- private static readonly double[] Grids = { 1, 0.5, 0.25, 0.125, 1.0 / 3.0, 1.0 / 6.0 };
- private static readonly string[] GridLbl = { "1/4", "1/8", "1/16", "1/32", "1/8T", "1/16T" };
- private static readonly string[] ModeLbl = { "Mix", "Insert", "Gate" };
-
- private static readonly IBrush Hdr = NotaPalette.SurfaceCard;
- private static readonly IBrush Rail = NotaPalette.SurfaceInset;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush Bd = NotaPalette.BorderDefault;
- private static readonly IBrush CardBg = NotaPalette.SurfaceRaised;
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush TealB = NotaPalette.Teal;
- private static readonly IBrush Txt = NotaPalette.TextPrimary;
- private static readonly IBrush MutedB = NotaPalette.TextTertiary;
- private static readonly IBrush Sub = NotaPalette.TextSecondary;
- private static readonly IBrush Hue = NotaPalette.BorderStrong;
- private static readonly IBrush Ink = NotaPalette.TextOnAccent;
+ // ── Parameter indices (must match BeatRepeat.h) ──────────────────────────
+ private const int Interval = 0, Offset = 1, GridP = 2, Variation = 3, Chance = 4, Gate = 5, Pitch = 6, PitchDecay = 7,
+ Volume = 8, Decay = 9, FilterOn = 10, FilterFreq = 11, FilterWidth = 12, Mode = 13, MixP = 14, RepeatP = 15,
+ LatchP = 16, Triplet = 17, FilterType = 18, FilterNarrow = 19;
+ // Scope layout (BeatRepeat::S_* / kTele / kCells / kWave).
+ private const int S_InDb = 0, S_RepDb = 1, S_OutDb = 2, S_State = 3, S_Pass = 4, S_Passes = 5, S_WinPhase = 7,
+ S_WinBeats = 8, S_IntervalBeats = 9, S_SliceBeats = 10, S_SliceMs = 11, S_Bpm = 12, S_Bar = 13, S_BeatInBar = 14,
+ S_SampleRate = 15, S_Cpu = 16, S_Latency = 17, S_Forced = 18, S_PitchSt = 20, S_Playing = 24, S_BarBeats = 26,
+ kTele = 32, kCells = 64, kWave = 128;
+ private const int kCellAt = kTele, kWaveAt = kTele + 3 * kCells, kScope = kWaveAt + kWave;
+ private const int A_Reset = 0;
- public double Width => 700;
+ private static readonly string[] IntervalSeg = { "1/8", "1/4", "1/2", "1", "2", "4" };
+ private static readonly string[] IntervalName = { "1/8", "1/4", "1/2", "1 Bar", "2 Bars", "4 Bars" };
+ private static readonly string[] IntervalEvery = { "every 1/8", "every 1/4", "every 1/2", "every bar", "every 2 bars", "every 4 bars" };
+ private static readonly string[] GridSeg = { "1/4", "1/8", "1/16", "1/32" };
+ private static readonly double[] GridStraight = { 1, 0.5, 0.25, 0.125 };
+ private static readonly string[] ModeNames = { "Mix", "Insert", "Gate" };
+ private static readonly string[] FilterNames = { "Off", "LP", "BP", "HP" };
- public string? Subtitle => "REPEATER"; // the processing type, shown as the header badge
+ public double Width => 700;
public bool FullBleed => true;
+ public string? Subtitle => "REPEAT";
public Control Build(DeviceCardContext ctx, int index)
{
var engine = ctx.Engine;
int track = ctx.TrackId, di = index;
float P(int p) => engine.DeviceGetParam(track, di, p);
- void SetP(int p, float v) => engine.DeviceSetParam(track, di, p, v);
void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- int Idx(int p, int n) => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1);
+ void Raw(int p, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ double Def(int p) => engine.DeviceParamDefault(track, di, p);
+ bool On(int p) => P(p) >= 0.5f;
+ int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1);
+
+ var readouts = new List<Action>();
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
+ var scope = new float[kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+
+ // ---- units ----------------------------------------------------------------
static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
- static TextBlock Mono(string t, IBrush c, double fs = 9) { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
- static TextBlock Cap(string t, IBrush? c = null) => new() { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedB, VerticalAlignment = VerticalAlignment.Center };
+ static string HzF(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0}\u2009k") : NotaNum.F($"{hz:0}\u2009Hz");
+ static string DbF(double db) => db <= -119 ? "−∞\u2009dB" : NotaNum.F($"{db:0.0}\u2009dB");
+ static string PctF(double v) => NotaNum.F($"{v * 100:0}\u2009%");
+ static string StF(double st) => NotaNum.F($"{st:+0.#;−0.#;0}\u2009st");
+ static int Steps16(double v) => Math.Clamp((int)Math.Round(v * 16), 0, 16);
+ int OffSteps() => Steps16(P(Offset)) % 16;
+ int GateSteps() => Steps16(P(Gate));
+ int VarSteps() => Math.Clamp((int)Math.Round(P(Variation) * 6), 0, 6);
+ double BarBeats() => Sc(S_BarBeats) > 0 ? Sc(S_BarBeats) : 4;
+ double IntervalBeats() { double b = BarBeats(); return new[] { 0.5, 1, 2, b, 2 * b, 4 * b }[Sel(Interval, 6)]; }
+ double Bpm() => Sc(S_Bpm) > 1 ? Sc(S_Bpm) : Math.Max(1, engine.Bpm);
+ // Grid: 0..3 straight, 4/5 the legacy 1/8T and 1/16T; Triplet turns a straight grid to triplets.
+ int GridBase() { int g = Sel(GridP, 6); return g >= 4 ? g - 3 : g; }
+ bool Trip() => Sel(GridP, 6) >= 4 || On(Triplet);
+ double GridBeats() => GridStraight[GridBase()] * (Trip() ? 2.0 / 3.0 : 1);
+ string GridName() => GridSeg[GridBase()] + (Trip() ? "T" : "");
+ double SliceMs(double beats) => beats * 60000.0 / Bpm();
+ string MsF(double ms) => ms >= 1000 ? NotaNum.F($"{ms / 1000:0.00}\u2009s") : NotaNum.F($"{ms:0}\u2009ms");
+ double PitchSt() => (P(Pitch) - 0.5) * 24;
+ double PDecaySt() => P(PitchDecay) * 6;
+ double FreqHz() => Exp(P(FilterFreq), 50, 18000);
+ double WidthOct() => 0.5 + P(FilterWidth) * 3;
+ int FType() => Sel(FilterType, 3);
+ string FilterText() => On(FilterOn) ? NotaNum.F($"{FilterNames[FType() + 1]} {HzF(FreqHz())} · {WidthOct():0.0}\u2009oct") : "filter off";
+ int Passes() => Math.Max(1, (int)Math.Round(Math.Max(GridBeats(), GateSteps() / 16.0 * IntervalBeats()) / GridBeats()));
+ string WindowText() { double b = IntervalBeats() * 2, bb = BarBeats(); return b >= bb ? NotaNum.F($"{b / bb:0.#} {(b / bb > 1.01 ? "bars" : "bar")}") : NotaNum.F($"{b:0.##} beats"); }
+ string IntervalText() { double b = IntervalBeats(), bb = BarBeats(); return b >= bb ? NotaNum.F($"{b / bb:0.#} {(b / bb > 1.01 ? "bars" : "bar")}") : IntervalName[Sel(Interval, 6)]; }
+ int State() => Math.Clamp((int)Math.Round(Sc(S_State)), 0, 2);
+ int RepeatNo() => State() == 2 ? Math.Max(1, (int)Sc(S_Pass) - 1) : 0;
+
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static StackPanel Row(double sp, params Control[] cs)
+ { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+
+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
+ // `steps` > 1 snaps a discrete param; `lit` lights the label and value (the knob that matters now).
+ Control K(int p, string name, Func<double, string> fmt, IBrush? arc = null, int steps = 0, string? tip = null, Func<bool>? lit = null)
+ {
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = Def(p), Width = 34, Height = 34 };
+ knob.ValueChanged += v =>
+ {
+ if (steps > 1) v = Math.Round(v * (steps - 1)) / (steps - 1);
+ Raw(p, v); val.Text = fmt(P(p)); RefreshAll();
+ };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ if (tip is not null) ToolTip.SetTip(knob, tip);
+ var cell = KnobCell(name, knob, val, 52);
+ TextBlock? label = null;
+ if (lit is not null && cell is Panel pn) foreach (var c in pn.Children) if (c is TextBlock tb && tb != val) { label = tb; break; }
+ readouts.Add(() =>
+ {
+ if (!knob.Dragging) { double c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; }
+ val.Text = fmt(P(p));
+ if (lit is not null)
+ {
+ bool on = lit();
+ val.Foreground = on ? AccentBright : TextPrimary;
+ if (label is not null) label.Foreground = on ? AccentBright : TextTertiary;
+ }
+ });
+ return cell;
+ }
- // ---- timeline viz ----
- var viz = new BeatRepeatViz { VerticalAlignment = VerticalAlignment.Stretch };
- var slots = new float[64];
- void SyncViz()
+ // On/off switch bound to a param (>= 0.5 = on).
+ Control Toggle(int p, string label, string tip)
{
- int n = engine.DeviceScope(track, di, slots, slots.Length);
- double phase = engine.DeviceGainReduction(track, di);
- viz.Set(slots, n, Intervals[Idx(Interval, 6)], engine.Bpm, phase);
+ var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); RefreshAll(); }, out var sync);
+ readouts.Add(sync);
+ Learn(wrap, p);
+ ToolTip.SetTip(wrap, tip);
+ return wrap;
}
- ctx.AddDeviceRefresher(SyncViz);
- // ---- horizontal slider (label · track · value) ----
- Control Slider(string label, int p, Func<double, string> fmt, IBrush fill, double labelW = 46, bool bipolar = false)
+ // Segmented pill: `get` / `pick` over the names; learns `learnParam`.
+ Control Seg(string[] names, Func<int> get, Action<int> pick, int learnParam, string tip, double padX = 6)
{
- var row = DeviceCardKit.SliderRow(label, () => P(p), n => { SetP(p, (float)n); SyncViz(); }, () => fmt(P(p)), out var sync,
- begin: () => Begin(p), end: () => End(p), bipolar: bipolar, labelWidth: labelW, valueWidth: 38);
- ctx.AddDeviceRefresher(sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);
- return row;
+ var seg = Segments(names, get, iv => { pick(iv); RefreshAll(); }, out var sync, padX: padX);
+ readouts.Add(sync);
+ Learn(seg, learnParam);
+ ToolTip.SetTip(seg, tip);
+ return seg;
}
- // Compact inline slider for the LIVE strip (fixed width, no flexible column).
- Control MiniSlider(string label, int p, Func<double, string> fmt, double w)
+ Control ModeSeg() => Seg(ModeNames, () => Sel(Mode, 3), i => SetP(Mode, i / 2f), Mode,
+ "Mode — Mix: the repeats play over the dry; Insert: they replace it while they play; Gate: only the burst sounds");
+ Control IntervalSegC() => Seg(IntervalSeg, () => Sel(Interval, 6), i => SetP(Interval, i / 5f), Interval,
+ "Interval — how often it rolls Chance: 1/8, 1/4, 1/2 note, or every 1, 2, 4 bars", 5);
+ // Grid picks a straight value and keeps the triplet state (a legacy 1/8T / 1/16T turns into the Triplet switch).
+ void PickGrid(int baseIdx, bool trip)
{
- var row = DeviceCardKit.SliderRow(label, () => P(p), n => SetP(p, (float)n), () => fmt(P(p)), out var sync,
- begin: () => Begin(p), end: () => End(p), trackWidth: w, valueWidth: 28);
- ctx.AddDeviceRefresher(sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);
- return row;
+ Begin(GridP); Raw(GridP, baseIdx / 5f); End(GridP);
+ if (On(Triplet) != trip) SetP(Triplet, trip ? 1f : 0f);
}
+ Control GridSegC() => Seg(GridSeg, GridBase, i => PickGrid(i, Trip()), GridP,
+ "Grid — the length of the slice that repeats", 5);
- // ---- segmented / toggles / buttons ----
- Control Seg(string[] names, Func<int> get, Action<int> set)
+ // A latching chip: lit when `lit()`, a click runs `click`. `fill` = a full-width button.
+ Border Latch(int p, Func<bool> lit, Action click, Func<string> text, string tip, bool fill = false)
{
- var seg = DeviceCardKit.Segments(names, get, set, out var sync);
- ctx.AddDeviceRefresher(sync);
- return seg;
+ var tb = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ if (fill) b.HorizontalAlignment = HorizontalAlignment.Stretch;
+ void Hi()
+ {
+ bool on = lit();
+ b.Background = on ? NotaPalette.AccentSubtle : fill ? Raised : Brushes.Transparent;
+ b.BorderBrush = on ? Brass : fill ? Brushes.Transparent : NotaPalette.BorderStrong;
+ tb.Foreground = on ? AccentBright : fill ? TextPrimary : TextSecondary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ tb.Text = text();
+ }
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); RefreshAll(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ if (p >= 0) Learn(b, p);
+ readouts.Add(Hi); Hi();
+ return b;
}
- Control PillToggle(string label, int p, IBrush accent, out Action sync)
+ Control TripletChip() => Latch(Triplet, Trip, () => PickGrid(GridBase(), !Trip()), () => "Triplet", "Triplet — the grid in triplets (a third shorter)");
+
+ // Repeat: held while pressed; with Latch on, a click turns it on and the next one off.
+ Border RepeatButton(bool fill)
{
- var b = DeviceCardKit.Switch(label, () => P(p) >= 0.5f, () => SetP(p, P(p) >= 0.5f ? 0f : 1f), out sync);
- ctx.AddDeviceRefresher(sync);
- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ var tb = new TextBlock { Text = "Repeat", FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ if (fill) b.HorizontalAlignment = HorizontalAlignment.Stretch;
+ bool held = false;
+ void Hi()
+ {
+ bool on = On(RepeatP);
+ b.Background = on ? Brass : NotaPalette.AccentSubtle;
+ b.BorderBrush = Brass;
+ tb.Foreground = on ? OnAccent : AccentBright;
+ tb.FontWeight = FontWeight.SemiBold;
+ }
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ e.Handled = true;
+ if (On(LatchP)) { SetP(RepeatP, On(RepeatP) ? 0f : 1f); RefreshAll(); return; }
+ held = true; Begin(RepeatP); Raw(RepeatP, 1); e.Pointer.Capture(b); RefreshAll();
+ };
+ void Release()
+ {
+ if (!held) return;
+ held = false; Raw(RepeatP, 0); End(RepeatP); RefreshAll();
+ }
+ b.PointerReleased += (_, e) => { if (held) { e.Pointer.Capture(null); Release(); } };
+ b.PointerCaptureLost += (_, _) => Release();
+ ToolTip.SetTip(b, "Repeat — repeat the current slice now, for as long as it is held (with Latch: click on, click off)");
+ Learn(b, RepeatP);
+ readouts.Add(Hi); Hi();
return b;
}
- Control TagBtn(string label, IBrush border, IBrush bg, IBrush fg, Action<bool> onPress)
+
+ // Slider row: caps label · track · mono value.
+ Control SliderRow(string label, int p, Func<double, string> fmt, bool bipolar = false, bool modulation = false, double labW = 40, Func<bool>? lit = null)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => P(p), v => { Raw(p, v); RefreshAll(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: 34, bipolar: bipolar, modulation: modulation);
+ readouts.Add(sync);
+ Learn(bar, p);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(NotaNum.F($"{labW},*")), VerticalAlignment = VerticalAlignment.Center };
+ var cap = Caps(label);
+ g.Children.Add(cap);
+ g.Children.Add(Col(bar, 1));
+ if (lit is not null)
+ readouts.Add(() =>
+ {
+ bool on = lit();
+ foreach (var c in bar.Children) if (c is TextBlock tb && tb.TextAlignment == TextAlignment.Right) tb.Foreground = on ? AccentBright : TextPrimary;
+ });
+ return g;
+ }
+
+ // A dropdown over a discrete choice: [value ▾] opens the list.
+ Control Drop(int learnParam, string[] names, Func<int> get, Action<int> pick, string tip)
+ {
+ var name = new TextBlock { FontSize = 8, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center };
+ var chev = new Glyph(GlyphKind.ChevronDown, 7) { Margin = new Thickness(8, 0, 0, 0), Foreground = TextTertiary };
+ var box = new Border
+ {
+ Height = 16, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,
+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
+ Child = new DockPanel { Children = { Docked(chev, Dock.Right), name } },
+ };
+ readouts.Add(() => name.Text = names[Math.Clamp(get(), 0, names.Length - 1)]);
+ ToolTip.SetTip(box, tip);
+ Learn(box, learnParam);
+ box.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;
+ var fly = new MenuFlyout();
+ int cur = get();
+ for (int i = 0; i < names.Length; i++)
+ {
+ int iv = i;
+ var mi = new MenuItem { Header = names[i] };
+ if (i == cur) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };
+ mi.Click += (_, _) => { pick(iv); RefreshAll(); };
+ fly.Items.Add(mi);
+ }
+ fly.ShowAt(box);
+ e.Handled = true;
+ };
+ return box;
+ }
+ // Grid dropdown: the four straight values and their triplets.
+ string[] gridDropNames = { "1/4", "1/8", "1/16", "1/32", "1/4T", "1/8T", "1/16T", "1/32T" };
+ int GridDropIdx() => GridBase() + (Trip() ? 4 : 0);
+
+ static Grid HeadRow(Control left, Control right)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 18, ColumnSpacing = 6 };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
+ }
+ Control KnobRow(Control[] knobs, Func<string> info1, Func<string> info2)
+ {
+ var i1 = Mono("", 7, TextTertiary); i1.HorizontalAlignment = HorizontalAlignment.Right;
+ var i2 = Mono("", 7, TextTertiary); i2.HorizontalAlignment = HorizontalAlignment.Right;
+ i1.TextTrimming = i2.TextTrimming = TextTrimming.CharacterEllipsis;
+ readouts.Add(() => { i1.Text = info1(); i2.Text = info2(); });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 52, ColumnSpacing = 6 };
+ g.Children.Add(Row(2, knobs));
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { i1, i2 } }, 1));
+ return g;
+ }
+ static Control TabBody(Control head, Control window, Control knobs) => new DockPanel
+ {
+ LastChildFill = true, Margin = new Thickness(8, 5, 8, 0),
+ Children = { Docked(head, Dock.Top), Docked(knobs, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 0), Child = window } },
+ };
+ void WireDrag(ShDragView v, Func<int, int> param)
+ {
+ v.Value = h => P(param(h));
+ v.Changed += (h, x) => { Raw(param(h), x); Refresh(); };
+ v.GestureBegin += h => Begin(param(h));
+ v.GestureEnd += h => End(param(h));
+ v.ResetRequested += h => { Reset(param(h)); RefreshAll(); };
+ }
+
+ // ---- shared knob formats ----
+ string ChanceF(double v) => PctF(v);
+ string GateF(double v) => NotaNum.F($"{Steps16(v)}/16");
+ string OffsetF(double v) => NotaNum.F($"{Steps16(v) % 16}/16");
+ string VarF(double v) { int s = Math.Clamp((int)Math.Round(v * 6), 0, 6); return s == 0 ? "off" : NotaNum.F($"{s}"); }
+ string PitchF(double v) => StF((v - 0.5) * 24);
+ string PDecF(double v) => PctF(v);
+ string DecayF(double v) => PctF(v);
+ string VolF(double v) { double d = (v - 0.5) * 24; return NotaNum.F($"{d:+0.0;−0.0;0.0}\u2009dB"); }
+ string FreqF(double v) => HzF(Exp(v, 50, 18000));
+ string WidthF(double v) => NotaNum.F($"{0.5 + v * 3:0.0}\u2009oct");
+
+ // ======================================================================
+ // LEFT — REPEAT column (input · repeats)
+ // ======================================================================
+ var colTitle = Caps("REPEAT"); colTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var inPill = new ShPill { Ink = Brass, VerticalAlignment = VerticalAlignment.Stretch };
+ var repPill = new ShPill { Ink = Teal, VerticalAlignment = VerticalAlignment.Stretch };
+ var inLbl = Caps("IN"); inLbl.HorizontalAlignment = HorizontalAlignment.Center;
+ var repLbl = Caps("REP"); repLbl.HorizontalAlignment = HorizontalAlignment.Center;
+ ToolTip.SetTip(inPill, "The input level");
+ ToolTip.SetTip(repPill, "The repeats' level — after pitch, filter, decay and volume");
+ var colIn = Mono("", 7, AccentBright); colIn.HorizontalAlignment = HorizontalAlignment.Center;
+ var colRep = Mono("", 7, TextPrimary); colRep.HorizontalAlignment = HorizontalAlignment.Center;
+ static double Norm60(double db) => Math.Clamp((db + 60) / 60, 0, 1);
+ readouts.Add(() =>
+ {
+ inPill.Set(Norm60(Sc(S_InDb)), double.NaN);
+ repPill.Set(Norm60(Sc(S_RepDb)), double.NaN);
+ colIn.Text = Sc(S_InDb) <= -119 ? "−∞" : NotaNum.F($"{Sc(S_InDb):0.0}");
+ colRep.Text = State() == 2 ? NotaNum.F($"rep {RepeatNo()}") : State() == 1 ? "capture" : "rep —";
+ colTitle.Foreground = State() > 0 ? AccentBright : TextTertiary; // lit while a burst runs
+ });
+ Control PillCol(ShPill pill, TextBlock lbl) => new DockPanel { Children = { Docked(lbl, Dock.Bottom), new Border { Margin = new Thickness(0, 0, 0, 3), Child = pill } } };
+ var pills = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 9, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 4) };
+ pills.Children.Add(PillCol(inPill, inLbl));
+ pills.Children.Add(Col(PillCol(repPill, repLbl), 1));
+ var leftCol = new Border
+ {
+ Width = 56, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(colTitle, Dock.Top), Docked(colRep, Dock.Bottom), Docked(colIn, Dock.Bottom), pills } },
+ };
+ DockPanel.SetDock(leftCol, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — Timeline
+ // ======================================================================
+ BrTimelineView? timeline = null;
+ Control TimelineTab()
+ {
+ timeline = new BrTimelineView();
+ ToolTip.SetTip(timeline, "Two intervals on the grid: each step is the input's level — dim when dry, full brass where the slice is captured, dimmer with every repeat as it decays. Brass ticks mark where the interval fires.");
+ var slice = Mono("", 7, AccentBright);
+ readouts.Add(() => slice.Text = "slice " + MsF(SliceMs(GridBeats())));
+ var head = HeadRow(Row(6, ModeSeg(), new Border { Width = 2 }, Caps("INTERVAL"),
+ Drop(Interval, IntervalName, () => Sel(Interval, 6), i => SetP(Interval, i / 5f), "Interval — how often it rolls Chance"),
+ Caps("GRID"),
+ Drop(GridP, gridDropNames, GridDropIdx, i => PickGrid(i % 4, i >= 4), "Grid — the length of the slice that repeats")), slice);
+ var knobs = KnobRow(new[]
+ {
+ K(Chance, "CHANCE", ChanceF, tip: "Chance — how likely each interval fires a repeat", lit: () => true),
+ K(Gate, "GATE", GateF, steps: 17, tip: "Gate — how long the burst lasts, in 16ths of the interval"),
+ K(Offset, "OFFSET", OffsetF, steps: 17, tip: "Offset — where in the interval it fires, in 16ths"),
+ K(Variation, "VARIATION", VarF, Teal, tip: "Variation — the grid floats up to this many steps (double / half) on each trigger"),
+ },
+ () => NotaNum.F($"capture {GridName()} → {Passes() - 1} {(Passes() - 1 == 1 ? "repeat" : "repeats")}"),
+ () => NotaNum.F($"{IntervalEvery[Sel(Interval, 6)]} · decay {P(Decay) * 100:0}\u2009%"));
+ return TabBody(head, timeline, knobs);
+ }
+
+ // ======================================================================
+ // CENTRE — Slices
+ // ======================================================================
+ BrSlicesView? slices = null;
+ Control SlicesTab()
{
- var b = new Border { BorderBrush = border, BorderThickness = new Thickness(1), Background = bg, CornerRadius = NotaRadius.Control, Padding = new Thickness(9, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
- Child = new TextBlock { Text = label, FontSize = 9, Foreground = fg } };
- b.PointerPressed += (_, e) => { e.Handled = true; onPress(true); };
- b.PointerReleased += (_, _) => onPress(false);
+ slices = new BrSlicesView();
+ WireDrag(slices, h => h == BrSlicesView.HGate ? Gate : Offset);
+ ToolTip.SetTip(slices, "The last interval's sound (teal) on the grid: the gate from the offset is shaded and the captured slice is brass. Drag the offset line or the gate's end sideways; double-click resets.");
+ Learn(slices, Offset);
+ var head = HeadRow(Row(6, Caps("INTERVAL"), IntervalSegC(), Caps("GRID"), GridSegC(), TripletChip()), new Border());
+ var knobs = KnobRow(new[]
+ {
+ K(Offset, "OFFSET", OffsetF, steps: 17, tip: "Offset — where in the interval it fires, in 16ths", lit: () => true),
+ K(Gate, "GATE", GateF, steps: 17, tip: "Gate — how long the burst lasts, in 16ths of the interval", lit: () => true),
+ K(Chance, "CHANCE", ChanceF, tip: "Chance — how likely each interval fires a repeat"),
+ K(Variation, "VARIATION", VarF, Teal, tip: "Variation — the grid floats up to this many steps (double / half) on each trigger"),
+ },
+ () => NotaNum.F($"takes {GridName()} at {OffSteps()}/16 · {Passes()} {(Passes() == 1 ? "step" : "steps")}"),
+ () => VarSteps() == 0 ? "the grid holds still" : NotaNum.F($"grid floats ±{VarSteps()} {(VarSteps() == 1 ? "step" : "steps")}"));
+ return TabBody(head, slices, knobs);
+ }
+
+ // ======================================================================
+ // CENTRE — Filter
+ // ======================================================================
+ BrFilterView? filter = null;
+ int LaterRepeat() => Math.Clamp(Passes() - 1, 1, 4);
+ double LaterPitch() => PitchSt() - PDecaySt() * (LaterRepeat() - 1);
+ Control FilterTab()
+ {
+ filter = new BrFilterView();
+ WireDrag(filter, h => h == BrFilterView.HFreq ? FilterFreq : FilterWidth);
+ ToolTip.SetTip(filter, "The repeat filter — only the repeats go through it. Brass: the first repeat; teal dashed: a later one when the band narrows and follows the pitch. Drag the node for the frequency, a band edge for the width; double-click resets.");
+ Learn(filter, FilterFreq);
+ var type = Seg(FilterNames, () => On(FilterOn) ? FType() + 1 : 0,
+ i => { if (i == 0) SetP(FilterOn, 0f); else { SetP(FilterType, (i - 1) / 2f); if (!On(FilterOn)) SetP(FilterOn, 1f); } },
+ FilterType, "Filter — Off, or a low-pass, band-pass or high-pass on the repeats");
+ var narrow = Latch(FilterNarrow, () => On(FilterNarrow), () => SetP(FilterNarrow, On(FilterNarrow) ? 0f : 1f), () => "Narrow with repeats",
+ "Narrow with repeats — each repeat narrows the band and moves it with the pitch");
+ var drop = Mono("", 7, AccentBright);
+ readouts.Add(() => drop.Text = PDecaySt() > 0.01 ? NotaNum.F($"{StF(PitchSt())} → {StF(LaterPitch())} by repeat {LaterRepeat()}") : "pitch " + StF(PitchSt()));
+ var head = HeadRow(Row(6, Caps("FILTER"), type, narrow), drop);
+ var knobs = KnobRow(new[]
+ {
+ K(FilterFreq, "FREQ", FreqF, tip: "Freq — the filter's frequency", lit: () => On(FilterOn)),
+ K(FilterWidth, "WIDTH", WidthF, tip: "Width — the band in octaves (low- and high-pass: less is more resonant)", lit: () => On(FilterOn)),
+ K(Pitch, "PITCH", PitchF, Teal, tip: "Pitch — the repeats transposed, ±12 semitones"),
+ K(PitchDecay, "P. DECAY", PDecF, tip: "Pitch decay — each repeat drops lower, up to 6 semitones a repeat"),
+ },
+ () =>
+ {
+ if (!On(FilterOn)) return "the repeats pass unfiltered";
+ double lo = FreqHz() / Math.Pow(2, WidthOct() / 2), hi = FreqHz() * Math.Pow(2, WidthOct() / 2);
+ return FType() == 1 ? NotaNum.F($"band {HzF(lo)}…{HzF(hi)}") : NotaNum.F($"{(FType() == 0 ? "below" : "above")} {HzF(FreqHz())}");
+ },
+ () => On(FilterNarrow) ? "each repeat lower and narrower" : PDecaySt() > 0.01 ? "each repeat lower, same band" : "the same on every repeat");
+ return TabBody(head, filter, knobs);
+ }
+
+ // ======================================================================
+ // RIGHT — Character / Output
+ // ======================================================================
+ static Control Spread(params Control[] rows)
+ {
+ var defs = new List<string>();
+ for (int i = 0; i < rows.Length; i++) { if (i > 0) defs.Add("*"); defs.Add("Auto"); }
+ var g = new Grid { RowDefinitions = new RowDefinitions(string.Join(",", defs)) };
+ for (int i = 0; i < rows.Length; i++) g.Children.Add(GRow(rows[i], i * 2));
+ return new Border { Padding = new Thickness(8, 6), Child = g };
+ }
+
+ Control StateBox()
+ {
+ var t = Caps("STATE");
+ var dot = new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Pill, VerticalAlignment = VerticalAlignment.Center };
+ var l1 = Mono("", 9, TextPrimary);
+ var l2 = Mono("", 8, TextSecondary);
+ l1.TextTrimming = l2.TextTrimming = TextTrimming.CharacterEllipsis;
+ var b = new Border
+ {
+ Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 2, Children = { t, Row(5, dot, l1), l2 } },
+ };
+ readouts.Add(() =>
+ {
+ int st = State();
+ bool forced = Sc(S_Forced) > 0.5;
+ int passes = (int)Sc(S_Passes);
+ string total = passes > 0 ? NotaNum.F($"/{Math.Max(1, passes - 1)}") : "";
+ l1.Text = st switch
+ {
+ 2 when forced => NotaNum.F($"{(On(LatchP) ? "latch" : "held")} · repeat {RepeatNo()}"),
+ 2 => NotaNum.F($"repeat · {RepeatNo()}{total}"),
+ 1 => "capture · " + MsF(Sc(S_SliceMs)),
+ _ => Sc(S_Playing) > 0.5 ? "waiting · " + IntervalEvery[Sel(Interval, 6)] : "stopped",
+ };
+ l2.Text = forced
+ ? NotaNum.F($"slice {MsF(Sc(S_SliceMs))} · {StF(Sc(S_PitchSt))}")
+ : NotaNum.F($"bar {Math.Max(1, Sc(S_Bar)):0} · beat {Math.Max(1, Sc(S_BeatInBar)):0.0} · mix {P(MixP) * 100:0}\u2009%");
+ dot.Background = forced ? Brass : st > 0 ? Success : NotaPalette.BorderStrong;
+ l1.Foreground = forced ? AccentBright : TextPrimary;
+ b.BorderBrush = forced ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
+ t.Foreground = forced ? AccentBright : TextTertiary;
+ });
+ ToolTip.SetTip(b, "What the repeater is doing now — waiting for the interval, capturing the slice, or repeating it — and where the transport is");
return b;
}
- // ---- INTERVAL / GRID button grid (3×2) with a live readout ----
- Control BtnGrid(int p, string[] labels, string headLabel, Func<string> readout, out Action syncReadout)
+ Control Toggles() => new StackPanel { Spacing = 5, Children = {
+ Toggle(FilterOn, "Repeat filter", "Repeat filter — the repeats go through the filter (Filter tab)"),
+ Toggle(LatchP, "Latch", "Latch — the Repeat button stays on after a click instead of only while held") } };
+
+ Control CharacterTab()
+ {
+ var vol = SliderRow("VOLUME", Volume, VolF, bipolar: true, modulation: true);
+ return Spread(
+ SliderRow("PITCH", Pitch, PitchF, bipolar: true, modulation: true),
+ SliderRow("P. DECAY", PitchDecay, PDecF),
+ SliderRow("DECAY", Decay, DecayF, lit: () => P(Decay) > 0.001f),
+ new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = vol },
+ StateBox(),
+ Toggles());
+ }
+
+ Control OutputTab()
{
- var readTb = Mono(readout(), Sub, 8);
- var head = new DockPanel { LastChildFill = false, Margin = new Thickness(0, 0, 0, 3), Children = { Cap(headLabel), WithRight(readTb) } };
- var grid = new Grid { ColumnSpacing = 3, RowSpacing = 3 };
- for (int c = 0; c < 3; c++) grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
- for (int r = 0; r < 2; r++) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
- var cells = new Border[labels.Length]; var texts = new TextBlock[labels.Length];
- void Sync() { int cur = Idx(p, labels.Length); for (int i = 0; i < labels.Length; i++) { bool on = i == cur; cells[i].Background = on ? Amber : Inset; cells[i].BorderBrush = on ? Amber : Bd; texts[i].Foreground = on ? Ink : Sub; } readTb.Text = readout(); }
- for (int i = 0; i < labels.Length; i++)
+ Control Line(string k, Func<string> v, IBrush? ink = null)
+ {
+ var key = new TextBlock { Text = k, FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
+ var val = Mono("", 8, ink ?? TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => val.Text = v());
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ g.Children.Add(key);
+ g.Children.Add(Col(val, 1));
+ return g;
+ }
+ var box = new Border
+ {
+ Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 3, Children = {
+ Caps("MEASUREMENTS"),
+ Line("in", () => DbF(Sc(S_InDb))),
+ Line("repeat", () => DbF(Sc(S_RepDb))),
+ Line("out", () => DbF(Sc(S_OutDb)), AccentBright) } },
+ };
+ var sliders = new StackPanel { Spacing = 6, Children = {
+ SliderRow("VOLUME", Volume, VolF, bipolar: true, modulation: true),
+ SliderRow("MIX", MixP, PctF, lit: () => true) } };
+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };
+ btns.Children.Add(RepeatButton(fill: true));
+ btns.Children.Add(Col(Latch(-1, () => false, () => engine.DeviceAction(track, di, A_Reset, 0, 0), () => "Reset",
+ "Reset — stop the repeat and clear the timeline and the meters", fill: true), 1));
+ var body = new DockPanel { LastChildFill = false, Children = {
+ Docked(box, Dock.Top),
+ Docked(new Border { Margin = new Thickness(0, 6, 0, 0), Child = sliders }, Dock.Top),
+ Docked(Toggles(), Dock.Bottom),
+ Docked(new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 5), Child = btns }, Dock.Bottom) } };
+ return new Border { Padding = new Thickness(8, 6), Child = body };
+ }
+
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ int centreTab = 0;
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[3];
+ var rightBodies = new Control?[2];
+ var extras = Mono("", 7, TextTertiary);
+ readouts.Add(() =>
+ {
+ extras.Text = centreTab switch
+ {
+ 1 => NotaNum.F($"{IntervalText()} · slice {MsF(SliceMs(GridBeats()))}"),
+ 2 => "repeats only",
+ _ => NotaNum.F($"{WindowText()} · {Bpm():0.##} BPM"),
+ };
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => SlicesTab(), 2 => FilterTab(), _ => TimelineTab() };
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? OutputTab() : CharacterTab();
+
+ var centre = TabFrame(new[] { "Timeline", "Slices", "Filter" }, centreHost, CentreBody, false, t => { centreTab = t; Refresh(); }, extras);
+ var rightFrame = TabFrame(new[] { "Character", "Output" }, rightHost, RightBody, true, _ => RefreshAll(), null);
+ var right = new Border { Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Margin = new Thickness(5, 0), ClipToBounds = true, Child = centre };
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ var parts = new List<string> { ModeNames[Sel(Mode, 3)] };
+ switch (centreTab)
+ {
+ case 1:
+ parts.Add(IntervalEvery[Sel(Interval, 6)]);
+ parts.Add("grid " + GridName());
+ parts.Add(NotaNum.F($"offset {OffSteps()}/16"));
+ parts.Add(NotaNum.F($"gate {GateSteps()}/16"));
+ parts.Add("chance " + PctF(P(Chance)));
+ if (VarSteps() > 0) parts.Add(NotaNum.F($"var {VarSteps()}"));
+ break;
+ case 2:
+ parts.Add(FilterText());
+ parts.Add("pitch " + StF(PitchSt()));
+ parts.Add("p. decay " + PctF(P(PitchDecay)));
+ if (On(FilterNarrow) && On(FilterOn)) parts.Add("narrowing");
+ parts.Add("mix " + PctF(P(MixP)));
+ break;
+ default:
+ parts.Add(IntervalEvery[Sel(Interval, 6)]);
+ parts.Add("grid " + GridName());
+ parts.Add("chance " + PctF(P(Chance)));
+ parts.Add(NotaNum.F($"gate {GateSteps()}/16"));
+ parts.Add("decay " + PctF(P(Decay)));
+ break;
+ }
+ if (On(RepeatP)) parts.Add("repeat held");
+ return string.Join(" · ", parts);
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#}\u2009kHz · latency {Sc(S_Latency):0}\u2009smp · CPU {Sc(S_Cpu) * 100:0.0}\u2009%") : "";
+ });
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft);
+ statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { leftCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, kScope);
+ bool full = scN >= kScope;
+ double ib = IntervalBeats();
+ if (centreTab == 0 && timeline is not null)
+ timeline.Set(scope, kCellAt, full ? kCells : 0, ib * 2, ib, GridBeats(), BarBeats(), OffSteps() / 16.0,
+ Sc(S_WinPhase), Sc(S_Playing) > 0.5, State() == 2 ? NotaNum.F($"Capture and repeat · {RepeatNo()}") : "Capture and repeat");
+ if (centreTab == 1 && slices is not null)
+ {
+ double sliceBeats = Sc(S_SliceBeats) > 0 && State() > 0 ? Sc(S_SliceBeats) : GridBeats();
+ slices.Set(scope, kWaveAt, full ? kWave : 0, OffSteps() / 16.0, GateSteps() / 16.0, sliceBeats / ib, GridBeats() / ib, State() > 0);
+ }
+ if (centreTab == 2 && filter is not null)
+ {
+ int later = On(FilterNarrow) || PDecaySt() > 0.01 ? LaterRepeat() : 0;
+ double lo = WidthOct(), lh = FreqHz();
+ if (On(FilterNarrow)) { lo = Math.Max(0.2, lo * Math.Pow(0.75, later - 1)); lh = Math.Clamp(lh * Math.Pow(2, (LaterPitch() - PitchSt()) / 12), 20, 20000); }
+ filter.Set(On(FilterOn), FType(), FreqHz(), WidthOct(), On(FilterNarrow) ? later : 0, lh, lo);
+ }
+ RefreshAll();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
+
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = 0;
+ var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? Card2 : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AccentBright : TextTertiary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
{
int iv = i;
- var t = Mono(labels[i], Sub); t.HorizontalAlignment = HorizontalAlignment.Center;
- var c = new Border { Height = 18, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Cursor = new Cursor(StandardCursorType.Hand), Child = t };
- c.PointerPressed += (_, e) => { e.Handled = true; SetP(p, iv / (float)(labels.Length - 1)); Sync(); SyncViz(); };
- cells[i] = c; texts[i] = t; Grid.SetColumn(c, i % 3); Grid.SetRow(c, i / 3); grid.Children.Add(c);
+ var b = new Border
+ {
+ Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };
+ btns[i] = b;
+ bar.Children.Add(b);
}
- syncReadout = Sync; Sync(); ctx.AddDeviceRefresher(Sync);
- return new StackPanel { Children = { head, grid } };
- }
- static Control WithRight(Control c) { DockPanel.SetDock(c, Dock.Right); return c; }
-
- // ---- formatters ----
- static string PctF(double v) => $"{v * 100:0}\u2009%";
- static string StF(double v) => $"{(v - 0.5) * 24:+0;−0;0}\u2009st";
- static string DbF(double v) => $"{(v - 0.5) * 24:+0.0;−0.0;0.0}\u2009dB";
- static string StepF(double v) => $"{(int)Math.Round(v * 16)}/16";
- string HzF(double v) { double f = Exp(v, 50, 18000); return f >= 1000 ? $"{f / 1000:0.0}k" : $"{f:0}\u2009Hz"; }
- static string OctF(double v) => $"{0.5 + v * 3:0.0}\u2009oct";
- static string VarF(double v) => v <= 0.001 ? "off" : $"{v * 100:0}\u2009%";
- string SliceF() { double spb = 60.0 / Math.Max(1e-3, engine.Bpm); return $"slice {Grids[Idx(GridP, 6)] * spb * 1000:0}\u2009ms"; }
-
- // ============ LIVE strip ============
- var modeSeg = Seg(ModeLbl, () => Idx(Mode, 3), i => SetP(Mode, i / 2f));
- MidiLearn.Bind(modeSeg, MidiTarget.DeviceParam(track, di, Mode), engine.DeviceParamName(track, di, Mode));
- var repeatBtn = TagBtn("Repeat ⏎", Amber, NotaPalette.Wash(NotaPalette.Accent, 0x24), AmberLit, held => SetP(Latch, held ? 1f : 0f));
- var latchBtn = PillToggle("Latch", Latch, Amber, out _);
- var liveLeft = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = {
- modeSeg, MiniSlider("CHANCE", Chance, PctF, 66), MiniSlider("GATE", Gate, StepF, 56) } };
- var liveRight = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right, Children = { repeatBtn, latchBtn } };
- var liveStrip = new Border { Height = 34, Background = Hdr, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child = new DockPanel { LastChildFill = false, Children = { liveLeft, liveRight } } };
-
- // ============ GRID rail (174) ============
- var intervalGrid = BtnGrid(Interval, IntervalLbl, "INTERVAL", () => IntervalEvery[Idx(Interval, 6)], out _);
- var gridGrid = BtnGrid(GridP, GridLbl, "GRID", SliceF, out _);
- var offsetVar = new StackPanel { Spacing = 4, [DockPanel.DockProperty] = Dock.Bottom, Children = {
- Slider("OFFSET", Offset, StepF, Amber, 52), Slider("VARIATION", Variation, VarF, TealB, 52) } };
- var gridInner = new DockPanel { LastChildFill = true, Children = { offsetVar, new StackPanel { Spacing = 6, Children = { intervalGrid, gridGrid } } } };
- var gridPanel = new Border { Width = 174, Background = Rail, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(8, 6), Child = gridInner };
-
- // ============ REPEAT CHARACTER rail (186) ============
- var freqW = Slider("FREQ", FilterFreq, HzF, Amber, 40);
- var widthW = Slider("WIDTH", FilterWidth, OctF, Amber, 40);
- var filterBlock = new StackPanel { Spacing = 4, Children = { freqW, widthW } };
- void FilterSync() => Inactive.Set(filterBlock, P(FilterOn) < 0.5f);
- var filterToggle = PillToggle("FILTER", FilterOn, Amber, out _);
- ctx.AddDeviceRefresher(FilterSync); FilterSync();
- var mix = Slider("MIX", MixP, PctF, Amber, 52);
- DockPanel.SetDock(mix, Dock.Bottom);
- var railTop = new StackPanel { Spacing = 4, Children = {
- Cap("REPEAT CHARACTER"),
- Slider("Pitch", Pitch, StF, Amber, 52, bipolar: true),
- Slider("Pitch Dec", PitchDecay, PctF, Amber, 52),
- Slider("Decay", Decay, PctF, Amber, 52),
- Slider("Volume", Volume, DbF, Amber, 52, bipolar: true),
- new Border { Height = 1, Background = CardBg, Margin = new Thickness(0, 2) },
- filterToggle, filterBlock } };
- var rail = new Border { Width = 186, Background = Rail, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6),
- Child = new DockPanel { LastChildFill = true, Children = { mix, railTop } } };
-
- // ============ timeline (fill) ============
- var tracePanel = new Border { Padding = new Thickness(8, 6), Child = viz };
-
- DockPanel.SetDock(gridPanel, Dock.Left); DockPanel.SetDock(rail, Dock.Right);
- var body = new DockPanel { LastChildFill = true, Children = { gridPanel, rail, tracePanel } };
- DockPanel.SetDock(liveStrip, Dock.Top);
- SyncViz();
- return new DockPanel { LastChildFill = true, Children = { liveStrip, body } };
+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };
+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Dock.Right); barDock.Children.Add(ex); }
+ if (!centered) DockPanel.SetDock(bar, Dock.Left);
+ barDock.Children.Add(bar);
+ var barBorder = new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };
+ DockPanel.SetDock(barBorder, Dock.Top);
+ Hi();
+ host.Content = body(sel);
+ return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
+ }
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index cdf360b3..a299640d 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1526,14 +1526,63 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("autoshift", 10, "MIDI Scale Follow", ("Key Source", 1f), ("MIDI Mode", 1f), ("MIDI Latch", 1f), ("Amount", 0.9f), ("Speed", 0.25f), ("Human", 0.3f), ("Formant", 1f));
Fx("autoshift", 10, "MIDI Melody Replace",("Key Source", 1f), ("MIDI Oct Lock", 1f), ("Range", 1f), ("Amount", 1f), ("Speed", 0.1f), ("MIDI Glide", 0.273f), ("Formant", 1f));
- // ---- Nota Beat Repeat (kind 11) — all params normalized 0..1. Interval 0 1/8..1 4 Bar
- // (.6=1 Bar); Grid 0 1/4..1 1/16T (.4=1/16); Mode 0 Mix/.5 Insert/1 Gate.
- Fx("beatrepeat", 11, "Classic Stutter", ("Interval", 0.6f), ("Grid", 0.4f), ("Gate", 0.5f), ("Chance", 1f), ("Mode", 0.5f), ("Volume", 0.5f));
- Fx("beatrepeat", 11, "Glitch Gate", ("Interval", 0.4f), ("Grid", 0.6f), ("Gate", 0.7f), ("Chance", 0.6f), ("Variation", 0.3f), ("Mode", 1f), ("Volume", 0.5f));
- Fx("beatrepeat", 11, "Pitch Drop", ("Interval", 0.6f), ("Grid", 0.4f), ("Gate", 0.6f), ("Chance", 1f), ("Pitch", 0.5f), ("Pitch Decay", 0.6f), ("Mode", 0.5f), ("Volume", 0.5f));
- Fx("beatrepeat", 11, "Filtered Chops", ("Interval", 0.6f), ("Grid", 0.4f), ("Gate", 0.5f), ("Chance", 1f), ("Filter On", 1f), ("Filter Freq", 0.4f), ("Filter Width", 0.6f), ("Mode", 0.5f), ("Volume", 0.5f));
- Fx("beatrepeat", 11, "Triplet Tumble", ("Interval", 0.6f), ("Grid", 0.8f), ("Gate", 0.6f), ("Chance", 0.8f), ("Variation", 0.4f), ("Decay", 0.3f), ("Mode", 0.5f), ("Volume", 0.5f));
- Fx("beatrepeat", 11, "Half-Bar Roll", ("Interval", 0.4f), ("Grid", 0.2f), ("Gate", 1f), ("Chance", 1f), ("Decay", 0.4f), ("Mode", 0f), ("Volume", 0.5f));
+ // ---- Nota Beat Repeat (kind 11) — tempo-synced repeater, all params normalized 0..1 (unnamed
+ // ones reset to their defaults). Interval 0 1/8 · .2 1/4 · .4 1/2 · .6 1 bar · .8 2 bars ·
+ // 1 4 bars; Grid 0 1/4 · .2 1/8 · .4 1/16 · .6 1/32 (Triplet 1 = triplets); Offset / Gate
+ // n/16 = n × .0625; Variation n steps = n/6 (.167 = 1, .333 = 2, .5 = 3); Pitch .5 + st/24
+ // (0 = −12, .208 = −7, .292 = −5, .375 = −3, .792 = +7, 1 = +12); Pitch Decay st/6 per repeat
+ // (.083 = 0.5, .167 = 1, .333 = 2); Volume .5 + dB/24 (.333 = −4, .375 = −3, .417 = −2,
+ // .583 = +2); Decay = the per-repeat fade (0..55 %); Filter Freq 50·360^v Hz (.353 = 400,
+ // .422 = 600, .5 = 949, .55 = 1.3 k, .6 = 1.7 k, .664 = 2.5 k, .813 = 6 k); Filter Width
+ // .5 + 3v oct (.1 = 0.8, .167 = 1, .333 = 1.5, .5 = 2); Filter Type 0 LP / .5 BP / 1 HP;
+ // Mode 0 Mix / .5 Insert / 1 Gate; Latch 1 = the Repeat button latches.
+ Fx("beatrepeat", 11, "Init", ("Interval", 0.6f));
+ // Stutters
+ Fx("beatrepeat", 11, "Classic Stutter", ("Interval", 0.6f), ("Grid", 0.4f), ("Gate", 0.5f), ("Chance", 1f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Half-Bar Roll", ("Interval", 0.4f), ("Grid", 0.2f), ("Gate", 1f), ("Chance", 1f), ("Decay", 0.4f), ("Mode", 0f));
+ Fx("beatrepeat", 11, "Snare Stutter", ("Interval", 0.2f), ("Offset", 0.25f), ("Grid", 0.4f), ("Gate", 0.25f), ("Chance", 0.6f), ("Variation", 0.333f),
+ ("Pitch", 0.375f), ("Pitch Decay", 0.2f), ("Decay", 0.14f), ("Volume", 0.417f), ("Mode", 0.5f), ("Latch", 1f));
+ Fx("beatrepeat", 11, "End-of-Bar Fill", ("Interval", 0.6f), ("Offset", 0.75f), ("Grid", 0.6f), ("Gate", 0.25f), ("Chance", 1f), ("Decay", 0.2f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Build-Up Roll", ("Interval", 0.8f), ("Offset", 0.5f), ("Grid", 0.4f), ("Gate", 0.5f), ("Mode", 0.5f),
+ ("Filter On", 1f), ("Filter Type", 1f), ("Filter Freq", 0.422f), ("Filter Width", 0.333f), ("Filter Narrow", 1f));
+ Fx("beatrepeat", 11, "Stutter Mix", ("Interval", 0.6f), ("Grid", 0.2f), ("Gate", 0.375f), ("Decay", 0.45f), ("Volume", 0.375f), ("Mode", 0f), ("Mix", 0.8f));
+ // Glitch
+ Fx("beatrepeat", 11, "Glitch Gate", ("Interval", 0.4f), ("Grid", 0.6f), ("Gate", 0.7f), ("Chance", 0.6f), ("Variation", 0.333f), ("Mode", 1f));
+ Fx("beatrepeat", 11, "Triplet Tumble", ("Interval", 0.6f), ("Grid", 0.2f), ("Triplet", 1f), ("Gate", 0.6f), ("Chance", 0.8f), ("Variation", 0.333f), ("Decay", 0.3f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Random Glitch", ("Interval", 0.2f), ("Grid", 0.4f), ("Gate", 0.5f), ("Chance", 0.35f), ("Variation", 0.5f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Micro Buzz", ("Interval", 0.4f), ("Grid", 0.6f), ("Variation", 0.167f), ("Gate", 0.5f), ("Chance", 0.7f), ("Decay", 0.1f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Buffer Shuffle", ("Interval", 0.2f), ("Grid", 0.4f), ("Variation", 0.667f), ("Chance", 0.8f), ("Gate", 1f), ("Decay", 0.1f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Sparse Surprise", ("Interval", 1f), ("Offset", 0.75f), ("Grid", 0.2f), ("Gate", 0.25f), ("Chance", 0.5f), ("Variation", 0.333f), ("Pitch Decay", 0.167f), ("Mode", 0.5f));
+ // Pitch
+ Fx("beatrepeat", 11, "Pitch Drop", ("Interval", 0.6f), ("Grid", 0.4f), ("Gate", 0.6f), ("Chance", 1f), ("Pitch Decay", 0.6f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Tape Drop", ("Interval", 0.6f), ("Grid", 0.2f), ("Gate", 0.5f), ("Pitch", 0.292f), ("Pitch Decay", 0.7f), ("Mode", 0f),
+ ("Filter On", 1f), ("Filter Type", 0.5f), ("Filter Freq", 0.5f), ("Filter Width", 0.5f), ("Filter Narrow", 1f));
+ Fx("beatrepeat", 11, "Octave Up Flutter", ("Interval", 0.4f), ("Grid", 0.6f), ("Gate", 0.375f), ("Pitch", 1f), ("Decay", 0.3f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Fifth Echo", ("Interval", 0.6f), ("Offset", 0.5f), ("Grid", 0.2f), ("Gate", 0.5f), ("Pitch", 0.792f), ("Decay", 0.35f), ("Volume", 0.375f), ("Mode", 0f));
+ Fx("beatrepeat", 11, "Dive Bomb", ("Interval", 0.6f), ("Offset", 0.5f), ("Grid", 0.6f), ("Gate", 0.5f), ("Pitch Decay", 1f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Chipmunk Roll", ("Interval", 0.8f), ("Offset", 0.5f), ("Grid", 0.4f), ("Gate", 0.75f), ("Pitch", 1f), ("Pitch Decay", 0.167f), ("Mode", 0.5f));
+ // Filter
+ Fx("beatrepeat", 11, "Filtered Chops", ("Interval", 0.6f), ("Grid", 0.4f), ("Gate", 0.5f), ("Chance", 1f), ("Filter On", 1f), ("Filter Freq", 0.4f), ("Filter Width", 0.1f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Telephone Repeats", ("Interval", 0.6f), ("Grid", 0.2f), ("Gate", 0.5f), ("Decay", 0.3f), ("Mode", 0f),
+ ("Filter On", 1f), ("Filter Type", 0.5f), ("Filter Freq", 0.55f), ("Filter Width", 0.333f));
+ Fx("beatrepeat", 11, "Low-Pass Fade", ("Interval", 0.6f), ("Grid", 0.2f), ("Gate", 0.75f), ("Pitch Decay", 0.083f), ("Decay", 0.4f), ("Mode", 0f),
+ ("Filter On", 1f), ("Filter Type", 0f), ("Filter Freq", 0.6f), ("Filter Width", 0.5f), ("Filter Narrow", 1f));
+ Fx("beatrepeat", 11, "High-Pass Riser", ("Interval", 0.8f), ("Offset", 0.5f), ("Grid", 0.4f), ("Gate", 1f), ("Mode", 0.5f),
+ ("Filter On", 1f), ("Filter Type", 1f), ("Filter Freq", 0.5f), ("Filter Width", 0.333f), ("Filter Narrow", 1f));
+ Fx("beatrepeat", 11, "Radio Stutter", ("Interval", 0.4f), ("Grid", 0.6f), ("Gate", 0.25f), ("Chance", 0.7f), ("Variation", 0.167f), ("Volume", 0.583f), ("Mode", 0.5f),
+ ("Filter On", 1f), ("Filter Type", 0.5f), ("Filter Freq", 0.6f), ("Filter Width", 0.1f));
+ // Drums · vocals
+ Fx("beatrepeat", 11, "Hat Roll", ("Interval", 0.2f), ("Offset", 0.5f), ("Grid", 0.6f), ("Gate", 0.5f), ("Chance", 0.5f), ("Volume", 0.375f), ("Mode", 0f),
+ ("Filter On", 1f), ("Filter Type", 1f), ("Filter Freq", 0.813f), ("Filter Width", 0.5f));
+ Fx("beatrepeat", 11, "Kick Stutter", ("Interval", 0.6f), ("Grid", 0.2f), ("Gate", 0.125f), ("Mode", 0.5f),
+ ("Filter On", 1f), ("Filter Type", 0f), ("Filter Freq", 0.422f), ("Filter Width", 0.5f));
+ Fx("beatrepeat", 11, "Vocal Chop", ("Interval", 0.4f), ("Offset", 0.5f), ("Grid", 0.2f), ("Gate", 0.5f), ("Chance", 0.5f), ("Variation", 0.167f), ("Decay", 0.25f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Vocal Echo Tail", ("Interval", 0.6f), ("Offset", 0.875f), ("Grid", 0.2f), ("Gate", 0.125f), ("Decay", 0.55f), ("Volume", 0.333f), ("Mode", 0f), ("Mix", 0.7f),
+ ("Filter On", 1f), ("Filter Type", 0.5f), ("Filter Freq", 0.6f), ("Filter Width", 0.5f));
+ // Performance — play the Repeat button (or automate Repeat)
+ Fx("beatrepeat", 11, "Hold to Stutter", ("Chance", 0f), ("Grid", 0.4f), ("Mode", 0.5f));
+ Fx("beatrepeat", 11, "Latch Freeze", ("Chance", 0f), ("Grid", 0.2f), ("Mode", 0.5f), ("Latch", 1f));
+ Fx("beatrepeat", 11, "Gate Only Bursts", ("Interval", 0.6f), ("Offset", 0.5f), ("Grid", 0.4f), ("Gate", 0.5f), ("Mode", 1f));
// ---- Nota Crush (kind 12) — all params normalized 0..1. Mode 0 Digital/.5 Analog/1 Fold.
Fx("crush", 12, "Broken Radio", ("Bits", 0.35f), ("Rate", 0.30f), ("Mode", 0f), ("Dither", 0.15f), ("Jitter", 0.10f), ("Noise Floor", 0.05f), ("Post Filter", 0.70f), ("Dry/Wet", 0.78f), ("Output", 0.5f));
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 5935cc4a..e6613aee 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -67,10 +67,10 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
- [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers.")]
+ [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.")]
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. 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). 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));
@@ -380,6 +380,56 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
(int)V(12), (int)V(13), (int)V(10), R1(win), pts.ToArray(), V(8));
});
+ public sealed record BeatRepeatStep(double Beat, double InputDb, string Kind, double RepeatGain);
+ public sealed record BeatRepeatReading(string Summary, string Live, string Mode, string State, int Pass, int Passes, bool RepeatHeld,
+ double IntervalBeats, double SliceBeats, double SliceMs, double RepeatGain, double RepeatPitchSt, double FilterHz, double FilterOctaves,
+ double InputDb, double RepeatDb, double OutputDb, double Bpm, int Bar, double BeatInBar, double IntervalPhase, int Bursts, int Skipped,
+ bool Playing, double WindowBeats, BeatRepeatStep[] Timeline, double SampleRate);
+
+ [McpServerTool(Name = "read_beat_repeat"), Description(
+ "Read what a Nota Beat Repeat (built-in effect kind 11 — tempo-synced repeater / stutter) is doing right now: the mode "
+ + "(Mix / Insert / Gate), its state (idle / capturing / repeating), which pass of the burst it is on (1 = the capture, 2.. = "
+ + "repeats) out of how many (0 = held by Repeat until released), the interval and the slice (beats, slice also in ms; the "
+ + "slice includes Variation's random step), the current repeat's gain, pitch (semitones) and filter (Hz, octaves), the input, "
+ + "repeat and output levels (dBFS, −120 = silence), tempo, bar and beat, the interval phase (0..1), bursts and skipped "
+ + "intervals since the last reset, and the timeline — the last two intervals in 32 steps (beat, input peak dB, dry / capture "
+ + "/ repeat, repeat gain). Levels and the timeline move only while the transport plays through the track. Use get_device_text "
+ + "id 2 for what each parameter value means, device_action 0 to reset, 1 to fire a repeat now; set the Repeat param to 1 to "
+ + "hold one.")]
+ public Task<BeatRepeatReading> ReadBeatRepeat(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int tele = 32, cells = 64, wave = 128;
+ var sc = new float[tele + 3 * cells + wave];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ static double R1(double v) => Math.Round(v, 1);
+ string[] modes = { "Mix", "Insert", "Gate" };
+ string[] states = { "idle", "capturing", "repeating" };
+ string[] kinds = { "dry", "capture", "repeat" };
+ int mode = Math.Clamp((int)Math.Round(E.DeviceGetParam(trackId, deviceIndex, 13) * 2), 0, 2);
+ double win = V(8) > 0 ? V(8) : 8;
+ var steps = new List<BeatRepeatStep>();
+ if (n >= tele + 3 * cells)
+ for (int k = 0; k < 32; k++)
+ {
+ int a = k * cells / 32, b = (k + 1) * cells / 32;
+ double pk = -120, g = 0; int kind = 0;
+ for (int i = a; i < b; i++)
+ {
+ pk = Math.Max(pk, sc[tele + i]);
+ int kk = Math.Clamp((int)Math.Round(sc[tele + cells + i]), 0, 2);
+ if (kk > kind) kind = kk;
+ g = Math.Max(g, sc[tele + 2 * cells + i]);
+ }
+ steps.Add(new BeatRepeatStep(Math.Round((double)a / cells * win, 3), R1(pk), kinds[kind], Math.Round(g, 3)));
+ }
+ return new BeatRepeatReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ modes[mode], states[Math.Clamp((int)Math.Round(V(3)), 0, 2)], (int)V(4), (int)V(5), V(18) > 0.5f,
+ Math.Round(V(9), 3), Math.Round(V(10), 4), R1(V(11)), Math.Round(V(19), 3), R1(V(20)), Math.Round(V(21)), Math.Round(V(22), 2),
+ R1(V(0)), R1(V(1)), R1(V(2)), Math.Round(V(12), 2), (int)V(13), Math.Round(V(14), 2), Math.Round(V(6), 3), (int)V(23), (int)V(29),
+ V(24) > 0.5f, R1(win), steps.ToArray(), V(15));
+ });
+
public sealed record AnalyzerBand(double Hz, double Db);
public sealed record AnalyzerPeak(double Hz, double Db, string Note);
public sealed record AnalyzerReading(string Summary, string Scope, string Cursors, AnalyzerBand[] Bands, AnalyzerPeak[] Peaks);
diff --git a/src/native/nota.engine/src/BeatRepeat.h b/src/native/nota.engine/src/BeatRepeat.h
index 44b7ef07..0f90948e 100644
--- a/src/native/nota.engine/src/BeatRepeat.h
+++ b/src/native/nota.engine/src/BeatRepeat.h
@@ -1,36 +1,119 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in Nota Beat Repeat (device kind 11) — a tempo-synced glitch/stutter effect in
-// the spirit of classic beat-repeat units. Every Interval (bar-synced, + Offset) it rolls
-// Chance to engage; when it does it captures a Grid-length slice of the incoming audio
-// and loops it for the Gate duration, optionally transposing (Pitch + Pitch Decay),
-// fading (Decay), band-filtering and re-leveling (Volume) the repeats. Three output
-// modes — Mix (repeats over the dry), Insert (repeats replace the dry while active) and
-// Gate (only the repeats sound). Grid can be randomized per trigger by Variation.
+// Built-in Nota Beat Repeat (device kind 11, mockup "Nota Beat Repeat") — a tempo-synced
+// glitch / stutter effect in the spirit of classic beat-repeat units. Every Interval (bar-
+// synced, shifted by Offset) it rolls Chance; when it fires it captures a Grid-length slice
+// of the incoming audio (the capture pass plays through as it is) and then loops it for the
+// rest of the Gate, each repeat transposed (Pitch, then Pitch Decay per repeat), faded
+// (Decay), filtered (Filter On · Type LP / BP / HP · Freq · Width in octaves, optionally
+// narrowing and following the pitch down with every repeat) and re-levelled (Volume). Three
+// output modes — Mix (repeats over the dry), Insert (repeats replace the dry while active)
+// and Gate (only the burst sounds). Variation lets the grid float a few steps per trigger,
+// Triplet turns the grid into triplets, Repeat forces a repeat of the current slice for as
+// long as it is on (Latch makes the card's button latch instead of momentary).
//
-// Needs the musical clock: the engine hands it the block's beat position via
-// setTransport() (see Device::setTransport) right before process(). The interval phase
-// + an "active" flag are published through gainReductionDb() so the editor's bar viz
-// scrubs live. Header-only, allocation-free, JUCE-free. Params normalized 0..1.
+// in ─▶ ring ──▶ [capture: dry] ─▶ [repeat: read slice · pitch · filter · decay · volume]
+// │ │
+// └──────────────── dry ─▶ mode (Mix / Insert / Gate) ◀┘ ─▶ dry/wet Mix ─▶ out
+//
+// Needs the musical clock: the engine hands it the block's beat position via setTransport()
+// and the time signature via setTransportInfo() right before process(). Header-only,
+// allocation-free after setSampleRate, JUCE-free. Params normalized 0..1, APPEND ONLY
+// (0..15 are the original layout; the appended ones default to the old sound).
+// Telemetry (scopeRead): kTele live values, then the timeline window (kCells columns of
+// input peak dB · kind 0 dry / 1 capture / 2 repeat · repeat gain) and the last interval's
+// input peaks (kWave columns), both left → right in musical time.
+// The interval phase is also published through gainReductionDb() (older viewers).
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = reset (stop the repeat, clear the timeline and meters), 1 = trigger a
+// repeat now (as if the interval fired, ignoring Chance).
#pragma once
#include "Device.h"
+#include "TransportInfo.h"
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
+#include <vector>
namespace nota {
class BeatRepeat : public Device {
public:
// Param layout — order is the persisted/automation layout. APPEND ONLY.
- // v2 appends Mix (dry/wet) and Latch (force a repeat now, held or latched).
- enum { Interval = 0, Offset, Grid, Variation, Chance, Gate, Pitch, PitchDecay,
- Volume, Decay, FilterOn, FilterFreq, FilterWidth, Mode, Mix, Latch, kNumParams };
+ enum {
+ Interval = 0, // 1/8 · 1/4 · 1/2 · 1 bar · 2 bars · 4 bars (6 steps)
+ Offset, // trigger point inside the interval, 16ths of it
+ Grid, // slice: 1/4 · 1/8 · 1/16 · 1/32 · (legacy 1/8T · 1/16T) — 6 steps
+ Variation, // the grid floats ±round(6v) steps (×2 / ÷2) per trigger
+ Chance, // probability an interval fires
+ Gate, // burst length, 16ths of the interval
+ Pitch, // repeat transpose ±12 st (bipolar)
+ PitchDecay, // 0..6 st lower per repeat
+ Volume, // repeat level ±12 dB (bipolar)
+ Decay, // per-repeat fade (0..55 %)
+ FilterOn, // >=0.5 the repeats go through the filter
+ FilterFreq, // 50..18000 Hz (exp)
+ FilterWidth, // 0.5..3.5 octaves
+ Mode, // 0 Mix · 0.5 Insert · 1 Gate
+ Mix, // effect dry/wet
+ Repeat, // >=0.5 repeat the current slice now, for as long as it is on (was "Latch")
+ // ---- appended (redesign) ----
+ Latch, // >=0.5 the card's Repeat button latches (UI mode, saved with the device)
+ Triplet, // >=0.5 the grid is in triplets (×2/3)
+ FilterType, // 0 LP · 0.5 BP (the old filter) · 1 HP
+ FilterNarrow, // >=0.5 each repeat narrows the band and follows the pitch down
+ kNumParams
+ };
+
+ // Telemetry slots (scopeRead).
+ enum {
+ S_InDb = 0, // input level, dBFS
+ S_RepDb, // repeat (wet) level, dBFS (−120 when not repeating)
+ S_OutDb, // output level, dBFS
+ S_State, // 0 idle (dry), 1 capture, 2 repeat
+ S_Pass, // pass in the burst (1 = the capture, 2.. = repeats)
+ S_Passes, // passes the burst will take (gate / slice; 0 = until released)
+ S_Phase, // interval phase 0..1 (offset applied)
+ S_WinPhase, // timeline window phase 0..1
+ S_WinBeats, // timeline window, beats (2 intervals)
+ S_IntervalBeats,
+ S_SliceBeats, // the current / last burst's slice, beats (after variation)
+ S_SliceMs,
+ S_Bpm,
+ S_Bar, // 1-based bar
+ S_BeatInBar, // 1-based beat within the bar
+ S_SampleRate,
+ S_Cpu, // share of real time spent in process()
+ S_Latency, // samples (0)
+ S_Forced, // 1 = Repeat holds the burst
+ S_Gain, // the current repeat's gain (decay × volume), linear
+ S_PitchSt, // the current repeat's pitch, semitones
+ S_FilterHz, // the current repeat's filter centre, Hz
+ S_FilterOct, // the current repeat's filter width, octaves
+ S_Triggers, // bursts since the last reset
+ S_Playing,
+ S_TsNum,
+ S_BarBeats, // beats per bar
+ S_Cells, // kCells
+ S_WaveN, // kWave
+ S_Skipped, // intervals Chance skipped since the last reset
+ kTele = 32
+ };
+ static constexpr int kCells = 64;
+ static constexpr int kWave = 128;
+ static constexpr int kCellAt = kTele; // level dB · kind · gain
+ static constexpr int kWaveAt = kTele + 3 * kCells; // input peak (linear)
+ static constexpr int kScope = kWaveAt + kWave;
+
+ enum { A_Reset = 0, A_Trigger = 1 };
BeatRepeat() {
p_[Interval].store(0.6f); // 1 Bar (index 3 of 6)
@@ -44,115 +127,237 @@ public:
p_[Volume].store(0.5f); // 0 dB
p_[Decay].store(0.0f);
p_[FilterOn].store(0.0f);
- p_[FilterFreq].store(0.5f);
- p_[FilterWidth].store(0.5f);
+ p_[FilterFreq].store(0.5f); // 949 Hz
+ p_[FilterWidth].store(0.5f);// 2 oct
p_[Mode].store(0.5f); // Insert (index 1 of 3)
p_[Mix].store(1.0f); // full wet
- p_[Latch].store(0.0f); // manual repeat off
+ p_[Repeat].store(0.0f);
+ p_[Latch].store(0.0f);
+ p_[Triplet].store(0.0f);
+ p_[FilterType].store(0.5f); // BP — the original filter
+ p_[FilterNarrow].store(0.0f);
+ setSampleRate(44100.0, 0);
}
- static constexpr int kSlots = 64; // timeline resolution for the UI
-
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
sr_ = sr > 0 ? sr : 44100.0;
- for (int c = 0; c < 2; ++c) { for (int i = 0; i < kBuf; ++i) ring_[c][i] = 0.0f; svfIc1_[c] = svfIc2_[c] = 0.0; }
- for (int i = 0; i < kSlots; ++i) slots_[i] = 0.0f;
- wp_ = 0; repeating_ = false; prevIdx_ = -1e18; rng_ = 0x2F6E10A3u;
+ size_t need = 1;
+ while ((double)need < sr_ * 6.0) need <<= 1; // ≥ 6 s: a half-note slice at 30 BPM
+ for (auto& r : ring_) r.assign(need, 0.0f);
+ mask_ = (int)need - 1;
+ srA_.store((float)sr_, std::memory_order_relaxed);
+ resetState();
}
void setTransport(double beatStart, double spb, bool playing) override {
- beatStart_ = beatStart; spb_ = spb > 0 ? spb : 1.0; playing_ = playing;
+ beatStart_ = beatStart; spb_ = spb > 0 ? spb : spb_; playing_ = playing;
+ }
+ void setTransportInfo(const TransportInfo& ti) override {
+ if (ti.tsNum > 0) tsNum_ = ti.tsNum;
+ if (ti.tsDenom > 0) tsDen_ = ti.tsDenom;
}
- // Interval phase in [0,1) — the timeline playhead.
+ // Interval phase in [0,1) — kept for older viewers of the timeline playhead.
float gainReductionDb() const override { return phasePub_.load(std::memory_order_relaxed); }
- // Timeline: per-slot repeat-gain envelope over one interval window (0 = dry/well,
- // 1 = captured slice, 0<g<1 = a repeat generation fading with Decay).
- int32_t scopeRead(float* out, int32_t maxSamples) const override {
- if (!out || maxSamples <= 0) return 0;
- const int n = std::min(maxSamples, kSlots);
- for (int k = 0; k < n; ++k) out[k] = slots_[k];
- return n;
+ void deviceAction(int32_t id, int32_t /*iarg*/, float) override {
+ if (id == A_Reset) resetReq_.store(true, std::memory_order_relaxed);
+ else if (id == A_Trigger) triggerReq_.store(true, std::memory_order_relaxed);
}
void process(float* buf, int32_t frames) override {
- const double intervalBeats = kInterval[idx(Interval, 6)];
- const double gridBeats = kGrid[idx(Grid, 6)];
- const double offsetBeats = (double)get(Offset) * intervalBeats;
+ const auto t0 = std::chrono::steady_clock::now();
+ if (resetReq_.exchange(false, std::memory_order_relaxed)) {
+ repeating_ = false; forced_ = false; xf_ = 0.0f; triggers_ = 0; skipped_ = 0;
+ for (auto& c : cells_) std::fill(c.begin(), c.end(), 0.0f);
+ for (auto& v : cells_[0]) v = -120.0f;
+ std::fill(wave_.begin(), wave_.end(), 0.0f);
+ inEnv_ = repEnv_ = outEnv_ = 0.0f;
+ svf_[0] = svf_[1] = {};
+ }
+
+ const double barBeats = (double)tsNum_ * 4.0 / (double)tsDen_;
+ const double intervalBeats = intervalBeatsFor(barBeats);
+ const double offsetBeats = offsetSteps() / 16.0 * intervalBeats;
+ const double winBeats = intervalBeats * 2.0;
const float chance = std::clamp(get(Chance), 0.0f, 1.0f);
- const float gateFrac = std::clamp(get(Gate), 0.0f, 1.0f);
- const float variation= std::clamp(get(Variation), 0.0f, 1.0f);
- const double basePitch= ((double)get(Pitch) - 0.5) * 24.0; // ±12 st
- const double pDecay = (double)get(PitchDecay) * 6.0; // st dropped per cycle
+ const int mode = idx(Mode, 3); // 0 Mix, 1 Insert, 2 Gate
+ const float mixDW = std::clamp(get(Mix), 0.0f, 1.0f);
+ const bool forceOn = get(Repeat) >= 0.5f;
const float volLin = std::pow(10.0f, ((float)get(Volume) - 0.5f) * 24.0f / 20.0f);
- const double decayMul = 1.0 - (double)get(Decay) * 0.55; // per-cycle amplitude
- const bool filterOn = get(FilterOn) >= 0.5f;
- const int mode = idx(Mode, 3); // 0 Mix, 1 Insert, 2 Gate
- const float mixDW = std::clamp(get(Mix), 0.0f, 1.0f); // effect dry/wet
- const bool latch = get(Latch) >= 0.5f; // force repeats now
- // Band filter coefficients (control-rate).
- const double fc = expMap(get(FilterFreq), 50.0, 18000.0);
- const double q = 0.5 + (double)get(FilterWidth) * 8.0;
- const double g = std::tan(kPi * std::min(fc, sr_ * 0.49) / sr_);
- const double k = 1.0 / q;
- const double a1 = 1.0 / (1.0 + g * (g + k));
+ const float mRel = coef(80.0f);
+ const float xfStep = (float)(1.0 / std::max(1.0, 0.003 * sr_)); // 3 ms dry ↔ repeat
+ const double fade = std::max(8.0, 0.0015 * sr_); // slice-edge declick
+
+ // Manual trigger (device action) — fires on the next sample like an interval would.
+ bool trigNow = triggerReq_.exchange(false, std::memory_order_relaxed);
for (int32_t i = 0; i < frames; ++i) {
const float dryL = buf[i * 2], dryR = buf[i * 2 + 1];
- ring_[0][wp_] = dryL; ring_[1][wp_] = dryR;
+ ring_[0][(size_t)wp_] = dryL; ring_[1][(size_t)wp_] = dryR;
const double beat = beatStart_ + (double)i / spb_;
const double rel = (beat - offsetBeats) / intervalBeats;
- double phase = rel - std::floor(rel); // 0..1 within interval
+ const double phase = rel - std::floor(rel);
- // Interval boundary → roll Chance → (re)trigger a burst.
+ // Interval boundary → roll Chance → a new burst (unless Repeat holds one).
if (playing_) {
const double idxNow = std::floor(rel);
- if (prevIdx_ > -1e17 && idxNow > prevIdx_ && chance > 0.0f) {
- if (whiteUni() < chance) startBurst(intervalBeats, gridBeats, gateFrac, variation, basePitch);
+ if (prevIdx_ > -1e17 && idxNow > prevIdx_ && !forceOn) {
+ if (chance > 0.0f && uni() < chance) startBurst(intervalBeats, false);
+ else ++skipped_;
}
prevIdx_ = idxNow;
- } else if (!latch) { repeating_ = false; prevIdx_ = -1e18; }
+ } else {
+ prevIdx_ = -1e18;
+ if (repeating_ && !forced_) repeating_ = false; // stopping the transport ends a synced burst
+ }
+ if (trigNow) { startBurst(intervalBeats, false); trigNow = false; }
- // Manual latch / Repeat-hold: force a burst now and keep re-triggering.
- if (latch && !repeating_) startBurst(intervalBeats, gridBeats, gateFrac, variation, basePitch);
+ // Repeat: hold the current burst (or start one) for as long as it is on.
+ if (forceOn) { if (!repeating_) startBurst(intervalBeats, true); forced_ = true; }
+ else if (forced_) { forced_ = false; repeating_ = false; }
- float wetL = dryL, wetR = dryR;
+ float wetL = 0.0f, wetR = 0.0f;
+ bool inRepeat = false;
if (repeating_) {
- const double pos = captureBase_ + repeatPhase_;
- wetL = readFrac(0, pos); wetR = readFrac(1, pos);
- if (filterOn) { wetL = svf(0, wetL, g, a1, k); wetR = svf(1, wetR, g, a1, k); }
- wetL *= (float)cycleGain_ * volLin; wetR *= (float)cycleGain_ * volLin;
-
- const double rate = std::pow(2.0, cyclePitch_ / 12.0);
- repeatPhase_ += rate;
- if (repeatPhase_ >= sliceLen_) { // slice wrapped → next repeat cycle
- repeatPhase_ -= sliceLen_;
- ++repeatCount_;
- cycleGain_ *= decayMul;
- cyclePitch_ -= pDecay;
+ if (capturing_) {
+ if (++capElapsed_ >= (int64_t)sliceLen_) { capturing_ = false; beginPass(2); }
+ } else {
+ inRepeat = true;
+ const double pos = captureBase_ + repeatPhase_;
+ float rl = readFrac(0, pos), rr = readFrac(1, pos);
+ if (filterOn_) { rl = svfRun(0, rl); rr = svfRun(1, rr); }
+ const double edge = std::min({ 1.0, repeatPhase_ / fade, (sliceLen_ - repeatPhase_) / fade });
+ const float g = (float)(passGain_ * std::max(0.0, edge)) * volLin;
+ wetL = rl * g; wetR = rr * g;
+ repeatPhase_ += passRate_;
+ if (repeatPhase_ >= sliceLen_) { repeatPhase_ -= sliceLen_; beginPass(pass_ + 1); }
}
- if (++burstElapsed_ >= gateSamples_) repeating_ = false;
+ if (!forced_ && ++burstElapsed_ >= (int64_t)gateSamples_) repeating_ = false;
}
+ // Dry ↔ repeat crossfade (Insert / Gate replace the dry while a repeat plays).
+ const float xt = inRepeat ? 1.0f : 0.0f;
+ xf_ = xt > xf_ ? std::min(xt, xf_ + xfStep) : std::max(xt, xf_ - xfStep);
+
float outL, outR;
- if (mode == 2) { outL = repeating_ ? wetL : 0.0f; outR = repeating_ ? wetR : 0.0f; } // Gate
- else if (mode == 1) { outL = repeating_ ? wetL : dryL; outR = repeating_ ? wetR : dryR; } // Insert
- else { const bool add = repeating_ && repeatCount_ >= 1; // Mix
- outL = dryL + (add ? wetL : 0.0f); outR = dryR + (add ? wetR : 0.0f); }
- buf[i * 2] = dryL * (1.0f - mixDW) + outL * mixDW;
- buf[i * 2 + 1] = dryR * (1.0f - mixDW) + outR * mixDW;
-
- // Timeline: record the repeat-gain envelope at the current playhead slot.
- if (playing_) {
- int slot = (int)(phase * kSlots);
- if (slot < 0) slot = 0; else if (slot >= kSlots) slot = kSlots - 1;
- slots_[slot] = repeating_ ? (float)cycleGain_ : 0.0f;
+ if (mode == 0) { outL = dryL + wetL; outR = dryR + wetR; } // Mix
+ else if (mode == 1) { outL = dryL * (1.0f - xf_) + wetL; outR = dryR * (1.0f - xf_) + wetR; } // Insert
+ else { // Gate
+ const float g = (repeating_ && capturing_) ? 1.0f : 0.0f;
+ gateDry_ = g > gateDry_ ? std::min(g, gateDry_ + xfStep) : std::max(g, gateDry_ - xfStep);
+ outL = dryL * gateDry_ + wetL; outR = dryR * gateDry_ + wetR;
+ }
+ const float yl = dryL * (1.0f - mixDW) + outL * mixDW;
+ const float yr = dryR * (1.0f - mixDW) + outR * mixDW;
+ buf[i * 2] = yl; buf[i * 2 + 1] = yr;
+
+ // Meters.
+ const float ain = std::max(std::fabs(dryL), std::fabs(dryR));
+ const float arep = std::max(std::fabs(wetL), std::fabs(wetR));
+ const float aout = std::max(std::fabs(yl), std::fabs(yr));
+ inEnv_ = ain > inEnv_ ? ain : ain + mRel * (inEnv_ - ain);
+ repEnv_ = arep > repEnv_ ? arep : arep + mRel * (repEnv_ - arep);
+ outEnv_ = aout > outEnv_ ? aout : aout + mRel * (outEnv_ - aout);
+
+ // Timeline (2 intervals) and the interval's waveform, while the transport runs.
+ if (playing_ && beat >= 0.0) {
+ const double wp = std::fmod(beat, winBeats) / winBeats;
+ const int c = std::clamp((int)(wp * kCells), 0, kCells - 1);
+ if (c != cell_) { cell_ = c; cellPeak_ = 0.0f; }
+ cellPeak_ = std::max(cellPeak_, ain);
+ cells_[0][(size_t)c] = db(cellPeak_);
+ const int kind = !repeating_ ? 0 : capturing_ ? 1 : 2;
+ if (kind >= cells_[1][(size_t)c] || c != lastKindCell_) cells_[1][(size_t)c] = (float)kind;
+ cells_[2][(size_t)c] = kind == 2 ? (float)passGain_ : kind == 1 ? 1.0f : 0.0f;
+ lastKindCell_ = c;
+ winPhase_ = (float)wp;
+
+ const double ip = std::fmod(beat, intervalBeats) / intervalBeats;
+ const int w = std::clamp((int)(ip * kWave), 0, kWave - 1);
+ if (w != waveCol_) { waveCol_ = w; wave_[(size_t)w] = 0.0f; }
+ wave_[(size_t)w] = std::max(wave_[(size_t)w], ain);
+ bar_ = (float)(std::floor(beat / barBeats) + 1.0);
+ beatInBar_ = (float)(std::fmod(beat, barBeats) + 1.0);
}
- wp_ = (wp_ + 1) & (kBuf - 1);
+ wp_ = (wp_ + 1) & mask_;
phasePub_.store((float)phase, std::memory_order_relaxed);
}
+
+ // Publish.
+ inDb_.store(db(inEnv_), std::memory_order_relaxed);
+ repDb_.store(db(repEnv_), std::memory_order_relaxed);
+ outDb_.store(db(outEnv_), std::memory_order_relaxed);
+ stateA_.store(!repeating_ ? 0.0f : capturing_ ? 1.0f : 2.0f, std::memory_order_relaxed);
+ passA_.store(repeating_ ? (float)pass_ : 0.0f, std::memory_order_relaxed);
+ passesA_.store(forced_ ? 0.0f : (float)passes_, std::memory_order_relaxed);
+ winPhaseA_.store(winPhase_, std::memory_order_relaxed);
+ winBeatsA_.store((float)winBeats, std::memory_order_relaxed);
+ intervalA_.store((float)intervalBeats, std::memory_order_relaxed);
+ sliceBeatsA_.store((float)sliceBeats_, std::memory_order_relaxed);
+ bpmA_.store((float)(60.0 * sr_ / std::max(1.0, spb_)), std::memory_order_relaxed);
+ barA_.store(bar_, std::memory_order_relaxed);
+ beatA_.store(beatInBar_, std::memory_order_relaxed);
+ forcedA_.store(forced_ ? 1.0f : 0.0f, std::memory_order_relaxed);
+ gainA_.store(repeating_ && !capturing_ ? (float)passGain_ * volLin : 0.0f, std::memory_order_relaxed);
+ pitchA_.store((float)passPitch_, std::memory_order_relaxed);
+ fHzA_.store((float)passHz_, std::memory_order_relaxed);
+ fOctA_.store((float)passOct_, std::memory_order_relaxed);
+ trigA_.store((float)triggers_, std::memory_order_relaxed);
+ skipA_.store((float)skipped_, std::memory_order_relaxed);
+ playA_.store(playing_ ? 1.0f : 0.0f, std::memory_order_relaxed);
+ tsA_.store((float)tsNum_, std::memory_order_relaxed);
+ barBeatsA_.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);
+ }
+ }
+
+ // Telemetry block, then the timeline cells and the interval waveform. Writes as much of
+ // that layout as fits in maxSamples. Lock-free; torn reads are fine.
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ float t[kTele] = {};
+ t[S_InDb] = inDb_.load(std::memory_order_relaxed);
+ t[S_RepDb] = repDb_.load(std::memory_order_relaxed);
+ t[S_OutDb] = outDb_.load(std::memory_order_relaxed);
+ t[S_State] = stateA_.load(std::memory_order_relaxed);
+ t[S_Pass] = passA_.load(std::memory_order_relaxed);
+ t[S_Passes] = passesA_.load(std::memory_order_relaxed);
+ t[S_Phase] = phasePub_.load(std::memory_order_relaxed);
+ t[S_WinPhase] = winPhaseA_.load(std::memory_order_relaxed);
+ t[S_WinBeats] = winBeatsA_.load(std::memory_order_relaxed);
+ t[S_IntervalBeats] = intervalA_.load(std::memory_order_relaxed);
+ t[S_SliceBeats] = sliceBeatsA_.load(std::memory_order_relaxed);
+ t[S_Bpm] = bpmA_.load(std::memory_order_relaxed);
+ t[S_SliceMs] = t[S_SliceBeats] * 60000.0f / std::max(1.0f, t[S_Bpm]);
+ t[S_Bar] = barA_.load(std::memory_order_relaxed);
+ t[S_BeatInBar] = beatA_.load(std::memory_order_relaxed);
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_Latency] = 0.0f;
+ t[S_Forced] = forcedA_.load(std::memory_order_relaxed);
+ t[S_Gain] = gainA_.load(std::memory_order_relaxed);
+ t[S_PitchSt] = pitchA_.load(std::memory_order_relaxed);
+ t[S_FilterHz] = fHzA_.load(std::memory_order_relaxed);
+ t[S_FilterOct] = fOctA_.load(std::memory_order_relaxed);
+ t[S_Triggers] = trigA_.load(std::memory_order_relaxed);
+ t[S_Playing] = playA_.load(std::memory_order_relaxed);
+ t[S_TsNum] = tsA_.load(std::memory_order_relaxed);
+ t[S_BarBeats] = barBeatsA_.load(std::memory_order_relaxed);
+ t[S_Cells] = (float)kCells;
+ t[S_WaveN] = (float)kWave;
+ t[S_Skipped] = skipA_.load(std::memory_order_relaxed);
+
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ for (int s = 0; s < 3; ++s)
+ for (int k = 0; k < kCells && n < maxSamples; ++k) out[n++] = cells_[(size_t)s][(size_t)k];
+ for (int k = 0; k < kWave && n < maxSamples; ++k) out[n++] = wave_[(size_t)k];
+ return n;
}
const char* displayName() const override { return "Nota Beat Repeat"; }
@@ -160,14 +365,10 @@ public:
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
- switch (i) {
- case Interval: return "Interval"; case Offset: return "Offset"; case Grid: return "Grid";
- case Variation: return "Variation"; case Chance: return "Chance"; case Gate: return "Gate";
- case Pitch: return "Pitch"; case PitchDecay: return "Pitch Decay"; case Volume: return "Volume";
- case Decay: return "Decay"; case FilterOn: return "Filter On"; case FilterFreq: return "Filter Freq";
- case FilterWidth: return "Filter Width"; case Mode: return "Mode"; case Mix: return "Mix";
- case Latch: return "Latch"; default: return "";
- }
+ static const char* nm[kNumParams] = { "Interval", "Offset", "Grid", "Variation", "Chance", "Gate", "Pitch",
+ "Pitch Decay", "Volume", "Decay", "Filter On", "Filter Freq", "Filter Width",
+ "Mode", "Mix", "Repeat", "Latch", "Triplet", "Filter Type", "Filter Narrow" };
+ return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
float paramMin(int32_t /*i*/) const override { return 0.0f; }
float paramMax(int32_t /*i*/) const override { return 1.0f; }
@@ -178,66 +379,209 @@ public:
if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
}
+ // 0 — a one-line status; 1 — the live reading; 2 — a guide to the parameter values.
+ std::string deviceText(int32_t id) const override {
+ char b[900];
+ static const char* modes[3] = { "Mix", "Insert", "Gate" };
+ static const char* ivl[6] = { "1/8", "1/4", "1/2", "1 bar", "2 bars", "4 bars" };
+ static const char* types[3] = { "LP", "BP", "HP" };
+ if (id == 0) {
+ std::string s = modes[idx(Mode, 3)];
+ std::snprintf(b, sizeof b, " - every %s - grid %s - offset %d/16 - gate %d/16 - chance %.0f %%",
+ ivl[idx(Interval, 6)], gridName().c_str(), offsetSteps(), gateSteps(), get(Chance) * 100.0f);
+ s += b;
+ if (varSteps() > 0) { std::snprintf(b, sizeof b, " - variation +/-%d steps", varSteps()); s += b; }
+ std::snprintf(b, sizeof b, " - pitch %+.0f st", ((double)get(Pitch) - 0.5) * 24.0); s += b;
+ if (get(PitchDecay) > 0.001f) { std::snprintf(b, sizeof b, " (-%.1f st per repeat)", get(PitchDecay) * 6.0f); s += b; }
+ std::snprintf(b, sizeof b, " - decay %.0f %% - volume %+.1f dB", get(Decay) * 100.0f, (get(Volume) - 0.5f) * 24.0f); s += b;
+ if (get(FilterOn) >= 0.5f) {
+ std::snprintf(b, sizeof b, " - %s filter %s, %.1f oct%s", types[idx(FilterType, 3)], hzText(filterHz()).c_str(),
+ filterOct(), get(FilterNarrow) >= 0.5f ? ", narrowing" : "");
+ s += b;
+ }
+ std::snprintf(b, sizeof b, " - mix %.0f %%", get(Mix) * 100.0f); s += b;
+ if (get(Repeat) >= 0.5f) s += " - REPEAT held";
+ if (get(Latch) >= 0.5f) s += " - latch";
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ const int st = std::clamp((int)std::lround(sc[S_State]), 0, 2);
+ static const char* states[3] = { "idle", "capturing", "repeating" };
+ std::string passes = sc[S_Passes] > 0.5f ? std::to_string((int)sc[S_Passes]) : std::string("held");
+ std::snprintf(b, sizeof b,
+ "%s - pass %d of %s - slice %.0f ms (%.3g beats) - repeat gain %.2f - pitch %+.1f st - filter %s %.1f oct - "
+ "in %.1f dB - repeat %.1f dB - out %.1f dB - bar %.0f beat %.2f - %.0f bursts, %.0f skipped since reset - %s",
+ states[st], (int)sc[S_Pass], passes.c_str(), sc[S_SliceMs], sc[S_SliceBeats], sc[S_Gain], sc[S_PitchSt],
+ hzText(sc[S_FilterHz]).c_str(), sc[S_FilterOct], sc[S_InDb], sc[S_RepDb], sc[S_OutDb], sc[S_Bar],
+ sc[S_BeatInBar], sc[S_Triggers], sc[S_Skipped], sc[S_Playing] > 0.5f ? "playing" : "stopped");
+ return b;
+ }
+ if (id == 2) {
+ return "All params 0..1. Interval: round(5v) -> 1/8, 1/4, 1/2 note, 1, 2, 4 bars (0.6 = 1 bar; bars follow the time "
+ "signature). Offset: round(16v)/16 of the interval (where it fires). Grid: round(5v) -> 1/4, 1/8, 1/16, 1/32 "
+ "(0.4 = 1/16; 0.8 / 1.0 = legacy 1/8T / 1/16T), Triplet >= 0.5 makes it triplets. Variation: the grid moves "
+ "up to round(6v) doubling / halving steps per trigger. Chance: probability an interval fires. Gate: "
+ "round(16v)/16 of the interval (the burst's length; at least one slice). Pitch: (v-0.5)*24 st on the repeats. "
+ "Pitch Decay: 6v st lower per repeat. Volume: (v-0.5)*24 dB on the repeats. Decay: each repeat x(1-0.55v). "
+ "Filter On: the repeats go through the filter. Filter Type: 0 LP, 0.5 BP, 1 HP. Filter Freq: 50*360^v Hz "
+ "(0.5 = 949 Hz). Filter Width: 0.5+3v octaves (0.5 = 2 oct). Filter Narrow: each repeat narrows the band "
+ "x0.75 and moves it with the pitch. Mode: 0 Mix (repeats over the dry), 0.5 Insert (repeats replace the "
+ "dry), 1 Gate (only the burst sounds). Mix: dry/wet. Repeat: >= 0.5 repeats the current slice until "
+ "released. Latch: the card's Repeat button latches. Toggles: >= 0.5 = on.";
+ }
+ return {};
+ }
+
private:
static constexpr double kPi = 3.14159265358979323846;
- static constexpr int kBuf = 1 << 17; // ~3 s at 44.1k — holds a grid slice at slow tempi
- // Interval / Grid tables in beats (assumes 4/4; 1 Bar = 4 beats).
- static constexpr double kInterval[6] = { 0.5, 1.0, 2.0, 4.0, 8.0, 16.0 };
- static constexpr double kGrid[6] = { 1.0, 0.5, 0.25, 0.125, 1.0 / 3.0, 1.0 / 6.0 };
+ static constexpr double kGridStraight[4] = { 1.0, 0.5, 0.25, 0.125 };
float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
int idx(int p, int n) const { return std::clamp((int)std::lround(get(p) * (n - 1)), 0, n - 1); }
+ int offsetSteps() const { return std::clamp((int)std::lround(get(Offset) * 16.0f), 0, 16) % 16; }
+ int gateSteps() const { return std::clamp((int)std::lround(get(Gate) * 16.0f), 0, 16); }
+ int varSteps() const { return std::clamp((int)std::lround(get(Variation) * 6.0f), 0, 6); }
+ double intervalBeatsFor(double barBeats) const {
+ const double t[6] = { 0.5, 1.0, 2.0, barBeats, 2.0 * barBeats, 4.0 * barBeats };
+ return t[idx(Interval, 6)];
+ }
+ // Grid 0..3 straight, 4/5 = the legacy 1/8T, 1/16T; Triplet turns any straight grid to triplets.
+ double gridBeats() const {
+ const int g = idx(Grid, 6);
+ if (g >= 4) return kGridStraight[g - 3] * 2.0 / 3.0;
+ return kGridStraight[g] * (get(Triplet) >= 0.5f ? 2.0 / 3.0 : 1.0);
+ }
+ std::string gridName() const {
+ static const char* s[4] = { "1/4", "1/8", "1/16", "1/32" };
+ const int g = idx(Grid, 6);
+ const bool trip = g >= 4 || get(Triplet) >= 0.5f;
+ return std::string(s[g >= 4 ? g - 3 : g]) + (trip ? "T" : "");
+ }
+ double filterHz() const { return expMap(get(FilterFreq), 50.0, 18000.0); }
+ double filterOct() const { return 0.5 + (double)get(FilterWidth) * 3.0; }
static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
- float whiteUni() { rng_ = rng_ * 1664525u + 1013904223u; return (float)((rng_ >> 8) & 0xFFFFFF) / 16777216.0f; }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ float coef(float ms) const { return (float)std::exp(-1.0 / (std::max(0.01f, ms) * 0.001 * sr_)); }
+ float uni() { rng_ = rng_ * 1664525u + 1013904223u; return (float)((rng_ >> 8) & 0xFFFFFF) / 16777216.0f; }
+ static std::string hzText(double hz) {
+ char b[32];
+ if (hz >= 1000.0) std::snprintf(b, sizeof b, "%.1f kHz", hz / 1000.0); else std::snprintf(b, sizeof b, "%.0f Hz", hz);
+ return b;
+ }
- void startBurst(double intervalBeats, double gridBeats, float gateFrac, float variation, double basePitch) {
- double gb = gridBeats;
- if (variation > 0.0f && whiteUni() < variation) { // randomize the grid a step
- const double mul = whiteUni() < 0.5f ? 0.5 : 2.0;
- gb = std::clamp(gb * mul, kGrid[3], kGrid[0]);
+ // A new burst: the capture pass (the slice plays through as it is) and then the repeats.
+ void startBurst(double intervalBeats, bool forced) {
+ double gb = gridBeats();
+ if (const int r = varSteps(); r > 0) {
+ const int k = std::clamp((int)std::floor(uni() * (2 * r + 1)), 0, 2 * r) - r;
+ gb = std::clamp(gb * std::pow(2.0, (double)-k), 1.0 / 16.0, 2.0);
}
- sliceLen_ = std::max(4.0, gb * spb_);
- gateSamples_ = std::max(sliceLen_, (double)gateFrac * intervalBeats * spb_);
+ sliceBeats_ = gb;
+ sliceLen_ = std::max(16.0, gb * spb_);
+ sliceLen_ = std::min(sliceLen_, (double)mask_ - 4.0);
+ const double gate = (double)gateSteps() / 16.0 * intervalBeats * spb_;
+ gateSamples_ = std::max(sliceLen_, gate);
+ passes_ = std::max(1, (int)std::lround(gateSamples_ / sliceLen_));
captureBase_ = wp_;
- repeatPhase_ = 0.0; burstElapsed_ = 0; repeatCount_ = 0;
- cycleGain_ = 1.0; cyclePitch_ = basePitch;
- repeating_ = true;
+ capElapsed_ = 0; burstElapsed_ = 0; repeatPhase_ = 0.0;
+ capturing_ = true; repeating_ = true; forced_ = forced;
+ pass_ = 1; passGain_ = 1.0; passPitch_ = ((double)get(Pitch) - 0.5) * 24.0; passRate_ = 1.0;
+ passHz_ = filterHz(); passOct_ = filterOct();
+ ++triggers_;
+ }
+
+ // Pass p >= 2 is repeat p−1: its gain, pitch and filter.
+ void beginPass(int p) {
+ pass_ = p;
+ const int r = std::max(0, p - 2); // repeats before this one
+ const double base = ((double)get(Pitch) - 0.5) * 24.0;
+ passPitch_ = base - (double)get(PitchDecay) * 6.0 * r;
+ passRate_ = std::pow(2.0, passPitch_ / 12.0);
+ passGain_ = std::pow(1.0 - (double)get(Decay) * 0.55, (double)(p - 1));
+ filterOn_ = get(FilterOn) >= 0.5f;
+ const bool narrow = get(FilterNarrow) >= 0.5f;
+ passOct_ = filterOct() * (narrow ? std::pow(0.75, (double)r) : 1.0);
+ passOct_ = std::max(0.2, passOct_);
+ passHz_ = filterHz() * (narrow ? std::pow(2.0, (passPitch_ - base) / 12.0) : 1.0);
+ passHz_ = std::clamp(passHz_, 20.0, 20000.0);
+ // TPT SVF coefficients for this pass (Q from the bandwidth in octaves).
+ const double n2 = std::pow(2.0, passOct_);
+ double q = std::sqrt(n2) / (n2 - 1.0);
+ const int type = idx(FilterType, 3);
+ if (type != 1) q = std::max(0.5, q);
+ fG_ = std::tan(kPi * std::min(passHz_, sr_ * 0.45) / sr_);
+ fK_ = 1.0 / q;
+ fA1_ = 1.0 / (1.0 + fG_ * (fG_ + fK_));
+ fType_ = type;
}
inline float readFrac(int c, double pos) const {
- double rp = pos;
- while (rp < 0.0) rp += kBuf;
- const int i0 = (int)rp & (kBuf - 1);
- const int i1 = (i0 + 1) & (kBuf - 1);
+ double rp = std::fmod(pos, (double)(mask_ + 1));
+ if (rp < 0.0) rp += (double)(mask_ + 1);
+ const int i0 = (int)rp & mask_;
+ const int i1 = (i0 + 1) & mask_;
const double fr = rp - std::floor(rp);
- return (float)(ring_[c][i0] * (1.0 - fr) + ring_[c][i1] * fr);
+ return (float)(ring_[c][(size_t)i0] * (1.0 - fr) + ring_[c][(size_t)i1] * fr);
}
- // TPT state-variable band-pass (one per channel).
- inline float svf(int c, float in, double g, double a1, double k) {
- const double v3 = in - svfIc2_[c];
- const double v1 = a1 * svfIc1_[c] + a1 * g * v3;
- const double v2 = svfIc2_[c] + g * v1;
- svfIc1_[c] = 2.0 * v1 - svfIc1_[c];
- svfIc2_[c] = 2.0 * v2 - svfIc2_[c];
- return (float)(k * v1); // band-pass, scaled so peak ≈ unity
+ // TPT state-variable filter: LP / BP (peak ≈ unity) / HP.
+ struct SvfSt { double ic1 = 0.0, ic2 = 0.0; };
+ inline float svfRun(int c, float in) {
+ SvfSt& s = svf_[c];
+ const double v3 = in - s.ic2;
+ const double v1 = fA1_ * s.ic1 + fA1_ * fG_ * v3;
+ const double v2 = s.ic2 + fG_ * v1;
+ s.ic1 = 2.0 * v1 - s.ic1;
+ s.ic2 = 2.0 * v2 - s.ic2;
+ if (fType_ == 0) return (float)v2;
+ if (fType_ == 2) return (float)(in - fK_ * v1 - v2);
+ return (float)(fK_ * v1);
+ }
+
+ void resetState() {
+ for (auto& r : ring_) std::fill(r.begin(), r.end(), 0.0f);
+ wp_ = 0; repeating_ = capturing_ = forced_ = false; prevIdx_ = -1e18; rng_ = 0x2F6E10A3u;
+ svf_[0] = svf_[1] = {};
+ xf_ = gateDry_ = 0.0f;
+ inEnv_ = repEnv_ = outEnv_ = 0.0f;
+ for (auto& c : cells_) std::fill(c.begin(), c.end(), 0.0f);
+ for (auto& v : cells_[0]) v = -120.0f;
+ std::fill(wave_.begin(), wave_.end(), 0.0f);
+ cell_ = waveCol_ = lastKindCell_ = -1; cellPeak_ = 0.0f;
}
double sr_ = 44100.0;
std::atomic<float> p_[kNumParams] = {};
- float ring_[2][kBuf] = {};
- float slots_[kSlots] = {}; // published timeline envelope (audio writes, UI reads)
- double svfIc1_[2] = {}, svfIc2_[2] = {};
- int wp_ = 0;
+ std::vector<float> ring_[2];
+ int mask_ = 0, wp_ = 0;
+ SvfSt svf_[2];
+ double fG_ = 0.1, fK_ = 1.0, fA1_ = 1.0; int fType_ = 1; bool filterOn_ = false;
// Transport (set each block).
- double beatStart_ = 0.0, spb_ = 1.0; bool playing_ = false;
+ double beatStart_ = 0.0, spb_ = 22050.0; bool playing_ = false;
+ int tsNum_ = 4, tsDen_ = 4;
// Burst state.
- bool repeating_ = false;
+ bool repeating_ = false, capturing_ = false, forced_ = false;
double prevIdx_ = -1e18;
- double captureBase_ = 0.0, repeatPhase_ = 0.0, sliceLen_ = 0.0, gateSamples_ = 0.0;
- double cycleGain_ = 1.0, cyclePitch_ = 0.0;
- int burstElapsed_ = 0, repeatCount_ = 0;
+ double captureBase_ = 0.0, repeatPhase_ = 0.0, sliceLen_ = 0.0, gateSamples_ = 0.0, sliceBeats_ = 0.25;
+ int64_t capElapsed_ = 0, burstElapsed_ = 0;
+ int pass_ = 0, passes_ = 0;
+ double passGain_ = 1.0, passPitch_ = 0.0, passRate_ = 1.0, passHz_ = 949.0, passOct_ = 2.0;
+ float xf_ = 0.0f, gateDry_ = 0.0f;
uint32_t rng_ = 0x2F6E10A3u;
+ int64_t triggers_ = 0, skipped_ = 0;
+ // Meters / telemetry (audio writes, UI reads).
+ float inEnv_ = 0.0f, repEnv_ = 0.0f, outEnv_ = 0.0f;
+ std::vector<float> cells_[3] = { std::vector<float>(kCells, -120.0f), std::vector<float>(kCells, 0.0f), std::vector<float>(kCells, 0.0f) };
+ std::vector<float> wave_ = std::vector<float>(kWave, 0.0f);
+ int cell_ = -1, waveCol_ = -1, lastKindCell_ = -1; float cellPeak_ = 0.0f, winPhase_ = 0.0f, bar_ = 1.0f, beatInBar_ = 1.0f;
+ double cpuS_ = 0.0;
+ std::atomic<bool> resetReq_{false}, triggerReq_{false};
std::atomic<float> phasePub_{0.0f};
+ std::atomic<float> inDb_{-120.0f}, repDb_{-120.0f}, outDb_{-120.0f}, stateA_{0.0f}, passA_{0.0f}, passesA_{0.0f},
+ winPhaseA_{0.0f}, winBeatsA_{8.0f}, intervalA_{4.0f}, sliceBeatsA_{0.25f}, bpmA_{120.0f}, barA_{1.0f}, beatA_{1.0f},
+ srA_{44100.0f}, cpuA_{0.0f}, forcedA_{0.0f}, gainA_{0.0f}, pitchA_{0.0f}, fHzA_{949.0f}, fOctA_{2.0f},
+ trigA_{0.0f}, skipA_{0.0f}, playA_{0.0f}, tsA_{4.0f}, barBeatsA_{4.0f};
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 79ce665d..2d17368f 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -8080,18 +8080,24 @@ Console.WriteLine("-- Nota Beat Repeat (effect kind 11) --");
{
using var breng = new NotaEngine();
int brt = breng.AddAudioTrack();
- breng.AddAudioClip(brt, wav, 0.0); // 440 Hz sine
+ breng.AddAudioClip(brt, wav, 0.0); // 440 Hz sine, 1 s
breng.SetBpm(120);
+ breng.SetTimeSignature(4, 4);
+ float[] Render(int frames) { var b = new float[frames * 2]; breng.Seek(0); breng.Play(); breng.RenderOffline(b, frames); breng.StopTransport(); return b; }
// Dry reference (no device yet).
- var dry = new float[44100 * 2];
- breng.Seek(0); breng.Play(); breng.RenderOffline(dry, 44100); breng.StopTransport();
+ var dry = Render(44100);
int brdi = breng.AddBuiltinDevice(brt, 11);
Check(brdi >= 0, "add Nota Beat Repeat device");
Check(breng.DeviceName(brt, brdi) == "Nota Beat Repeat", $"device is Nota Beat Repeat (got '{breng.DeviceName(brt, brdi)}')");
Check(breng.TrackDeviceBuiltinKind(brt, brdi) == 11, "device reports builtin kind 11");
int brpc = breng.DeviceParamCount(brt, brdi);
- Check(brpc == 16, $"Nota Beat Repeat exposes 16 params ({brpc})");
+ Check(brpc == 20, $"Nota Beat Repeat exposes 20 params ({brpc})");
+ Check(breng.DeviceParamName(brt, brdi, 15) == "Repeat" && breng.DeviceParamName(brt, brdi, 16) == "Latch" && breng.DeviceParamName(brt, brdi, 17) == "Triplet"
+ && breng.DeviceParamName(brt, brdi, 18) == "Filter Type" && breng.DeviceParamName(brt, brdi, 19) == "Filter Narrow",
+ "appended params: Repeat (was Latch), Latch, Triplet, Filter Type, Filter Narrow");
+ Check(Math.Abs(breng.DeviceParamDefault(brt, brdi, 18) - 0.5f) < 1e-3f && breng.DeviceParamDefault(brt, brdi, 17) == 0f && breng.DeviceParamDefault(brt, brdi, 19) == 0f,
+ "appended params default to the old sound (band-pass, straight grid, no narrowing)");
breng.DeviceSetParam(brt, brdi, 5, 0.7f); // Gate
Check(Math.Abs(breng.DeviceGetParam(brt, brdi, 5) - 0.7f) < 1e-3f, "device param set/get round-trips");
@@ -8103,23 +8109,173 @@ Console.WriteLine("-- Nota Beat Repeat (effect kind 11) --");
breng.DeviceSetParam(brt, brdi, 5, 1.0f); // Gate full
breng.DeviceSetParam(brt, brdi, 6, 1.0f); // Pitch +12
breng.DeviceSetParam(brt, brdi, 13, 1.0f); // Mode = Gate
- var wet = new float[44100 * 2];
- breng.Seek(0); breng.Play(); breng.RenderOffline(wet, 44100); breng.StopTransport();
+ var wet = Render(44100);
double diff = 0; bool finite = true;
for (int s = 0; s < 44100 * 2; s++) { diff += Math.Abs(dry[s] - wet[s]); if (!float.IsFinite(wet[s]) || Math.Abs(wet[s]) > 8f) finite = false; }
Check(diff > 10.0 && finite, $"synced beat repeats alter the audio (sum|delta| {diff:0})");
float phase = breng.DeviceGainReduction(brt, brdi);
Check(phase >= 0f && phase < 2f, $"publishes interval phase for the viz ({phase:0.00})");
- var brslots = new float[64];
- int brn = breng.DeviceScope(brt, brdi, brslots, brslots.Length);
- bool slotsOk = brn == 64; for (int s = 0; s < brn; s++) if (!float.IsFinite(brslots[s]) || brslots[s] < 0f || brslots[s] > 1f) slotsOk = false;
- Check(slotsOk, $"publishes 64-slot timeline envelope for the viz (n={brn})");
- breng.DeviceSetParam(brt, brdi, 14, 0.5f); // Mix
- breng.DeviceSetParam(brt, brdi, 15, 1.0f); // Latch
- Check(Math.Abs(breng.DeviceGetParam(brt, brdi, 14) - 0.5f) < 1e-3f && Math.Abs(breng.DeviceGetParam(brt, brdi, 15) - 1.0f) < 1e-3f, "Mix/Latch params round-trip");
+ // Telemetry layout: 32 live values, 3 × 64 timeline cells, a 128-column interval waveform.
+ const int brTele = 32, brCells = 64, brWave = 128, brScope = brTele + 3 * brCells + brWave;
+ var brsc = new float[brScope];
+ int brn = breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ bool scOk = brn == brScope;
+ for (int s = 0; s < brn; s++) if (!float.IsFinite(brsc[s])) scOk = false;
+ int repCells = 0, capCells = 0;
+ for (int c = 0; c < brCells; c++) { int k = (int)Math.Round(brsc[brTele + brCells + c]); if (k == 2) repCells++; if (k == 1) capCells++; if (k < 0 || k > 2) scOk = false; }
+ double waveMax = 0; for (int c = 0; c < brWave; c++) waveMax = Math.Max(waveMax, brsc[brTele + 3 * brCells + c]);
+ Check(scOk && repCells > 0 && capCells > 0 && waveMax > 0.05, $"telemetry: {brn} values, timeline shows capture ({capCells}) and repeats ({repCells}), waveform peak {waveMax:0.00}");
+ double sr = brsc[15] > 1000 ? brsc[15] : 44100;
+ Check(Math.Abs(brsc[9] - 0.5f) < 1e-3f && Math.Abs(brsc[10] - 0.25f) < 1e-3f && Math.Abs(brsc[12] - 120f) < 0.5f && Math.Abs(brsc[26] - 4f) < 1e-3f,
+ $"telemetry reports interval {brsc[9]} beats, slice {brsc[10]} beats, {brsc[12]:0.#} BPM, {brsc[26]} beats a bar");
+
+ // The capture pass plays the input through untouched, even with the pitch up (it used to read
+ // ahead of the write head); the next pass repeats that slice.
+ breng.DeviceSetParam(brt, brdi, 13, 0.5f); // Insert
+ breng.DeviceSetParam(brt, brdi, 6, 1.0f); // Pitch +12 on the repeats
+ var ins = Render(44100);
+ int spb = (int)Math.Round(sr * 0.5), trig = spb / 2, slice = spb / 4; // Interval 1/8 = half a beat; Grid 1/16 = a quarter beat
+ double capErr = 0; for (int i = trig + 16; i < trig + slice - 16; i++) capErr = Math.Max(capErr, Math.Abs(ins[i * 2] - dry[i * 2]));
+ Check(capErr < 1e-4, $"capture pass is the dry input with Pitch +12 (max |delta| {capErr:0.000000})");
+ breng.DeviceSetParam(brt, brdi, 6, 0.5f); // Pitch 0 → the repeat is a copy of the slice
+ ins = Render(44100);
+ double repErr = 0; int fade = (int)(sr * 0.004) + 4; // the 3 ms dry → repeat crossfade
+ for (int i = trig + slice + fade; i < trig + 2 * slice - fade; i++) repErr = Math.Max(repErr, Math.Abs(ins[i * 2] - dry[(i - slice) * 2]));
+ Check(repErr < 1e-3, $"first repeat replays the captured slice (max |delta| {repErr:0.00000})");
+
+ // Chance 0 in Gate mode: nothing fires, nothing sounds.
+ breng.DeviceSetParam(brt, brdi, 4, 0f);
+ breng.DeviceSetParam(brt, brdi, 13, 1f);
+ var silent = Render(22050);
+ Check(Rms(silent, 22050) < 1e-4f, $"Gate mode with Chance 0 is silent (rms {Rms(silent, 22050):0.000000})");
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(brsc[29] >= 1, $"skipped intervals are counted ({brsc[29]:0})");
+
+ // Repeat holds a burst (no end, whatever the gate) while on, and stops when released.
+ breng.DeviceSetParam(brt, brdi, 15, 1f);
+ breng.DeviceSetParam(brt, brdi, 5, 0f); // Gate 0 would end a normal burst after one slice
+ var held = Render(22050);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(brsc[3] > 1.5f && brsc[18] > 0.5f && brsc[5] == 0f && brsc[4] >= 3 && Rms(held, 22050) > 0.01f,
+ $"Repeat holds the burst (state {brsc[3]}, pass {brsc[4]}, passes {brsc[5]}, rms {Rms(held, 22050):0.000})");
+ breng.DeviceSetParam(brt, brdi, 15, 0f);
+ Render(4096);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(brsc[3] < 0.5f && brsc[18] < 0.5f, $"releasing Repeat ends the burst (state {brsc[3]})");
+
+ // Triplet grid, the legacy 1/8T value, and bars that follow the time signature.
+ breng.DeviceSetParam(brt, brdi, 4, 1f);
+ breng.DeviceSetParam(brt, brdi, 13, 0.5f);
+ breng.DeviceSetParam(brt, brdi, 17, 1f); // Triplet on 1/16
+ Render(22050);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(Math.Abs(brsc[10] - 1f / 6f) < 1e-3f, $"Triplet turns 1/16 into 1/16T ({brsc[10]:0.0000} beats)");
+ breng.DeviceSetParam(brt, brdi, 17, 0f);
+ breng.DeviceSetParam(brt, brdi, 2, 0.8f); // legacy 1/8T
+ Render(22050);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(Math.Abs(brsc[10] - 1f / 3f) < 1e-3f, $"legacy Grid 1/8T still means a third of a beat ({brsc[10]:0.0000})");
+ breng.DeviceSetParam(brt, brdi, 2, 0.4f);
+ breng.SetTimeSignature(3, 4);
+ breng.DeviceSetParam(brt, brdi, 0, 0.6f); // 1 bar
+ Render(4096);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(Math.Abs(brsc[9] - 3f) < 1e-3f && Math.Abs(brsc[8] - 6f) < 1e-3f, $"1 bar in 3/4 is 3 beats, the timeline two bars ({brsc[9]}, {brsc[8]})");
+ breng.SetTimeSignature(4, 4);
+
+ // Variation: the slice lands on a doubling / halving of the grid.
+ breng.DeviceSetParam(brt, brdi, 0, 0f);
+ breng.DeviceSetParam(brt, brdi, 3, 0.5f); // ±3 steps
+ bool varOk = true; var seen = new HashSet<float>();
+ for (int r = 0; r < 6; r++)
+ {
+ Render(22050);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ double k = Math.Log2(brsc[10] / 0.25);
+ if (Math.Abs(k - Math.Round(k)) > 1e-3 || Math.Abs(k) > 3.001) varOk = false;
+ seen.Add(brsc[10]);
+ }
+ Check(varOk, $"Variation keeps the slice on the grid ladder ({string.Join(", ", seen)})");
+ breng.DeviceSetParam(brt, brdi, 3, 0f);
+
+ // Filter types on the repeats: all finite; a high-pass at 8 kHz takes the 440 Hz repeats down.
+ float RepRms()
+ {
+ breng.DeviceSetParam(brt, brdi, 13, 1f); // Gate: only the burst sounds
+ var b = Render(44100);
+ breng.DeviceSetParam(brt, brdi, 13, 0.5f);
+ foreach (var v in b) if (!float.IsFinite(v)) return float.NaN;
+ return Rms(b, 44100);
+ }
+ breng.DeviceSetParam(brt, brdi, 5, 1f); // Gate: the whole interval → capture + a repeat
+ float rNone = RepRms();
+ breng.DeviceSetParam(brt, brdi, 10, 1f);
+ bool typesFinite = true; float rHp = 0;
+ foreach (float t in new[] { 0f, 0.5f, 1f })
+ {
+ breng.DeviceSetParam(brt, brdi, 18, t);
+ breng.DeviceSetParam(brt, brdi, 11, t >= 1f ? 0.862f : 0.5f);
+ breng.DeviceSetParam(brt, brdi, 19, 1f);
+ float r = RepRms();
+ if (!float.IsFinite(r)) typesFinite = false;
+ if (t >= 1f) rHp = r;
+ }
+ Check(typesFinite && rHp < rNone * 0.8f, $"LP / BP / HP repeat filters render finite; HP 8 kHz lowers the burst (rms {rHp:0.000} vs {rNone:0.000})");
+ breng.DeviceSetParam(brt, brdi, 10, 0f);
+ breng.DeviceSetParam(brt, brdi, 19, 0f);
+ breng.DeviceSetParam(brt, brdi, 18, 0.5f);
+
+ // Device actions: 1 fires a repeat now (Chance 0), 0 resets the counters.
+ breng.DeviceSetParam(brt, brdi, 4, 0f);
+ breng.DeviceSetParam(brt, brdi, 0, 1f); // 4 bars: no interval inside the render
+ breng.DeviceAction(brt, brdi, 1, 0, 0);
+ Render(2048);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(brsc[23] >= 1 && brsc[3] > 0.5f, $"device_action 1 fires a repeat (bursts {brsc[23]}, state {brsc[3]})");
+ breng.DeviceAction(brt, brdi, 0, 0, 0);
+ Render(512);
+ breng.DeviceScope(brt, brdi, brsc, brsc.Length);
+ Check(brsc[23] == 0 && brsc[29] == 0, $"device_action 0 resets the counters ({brsc[23]}, {brsc[29]})");
+
+ // Texts.
+ string t0 = breng.DeviceText(brt, brdi, 0), t1 = breng.DeviceText(brt, brdi, 1), t2 = breng.DeviceText(brt, brdi, 2);
+ Check(t0.StartsWith("Insert") && t0.Contains("every 4 bars") && t0.Contains("grid 1/16") && t1.Contains("pass") && t2.Contains("Filter Width"),
+ $"device texts: status '{t0[..Math.Min(60, t0.Length)]}…', live, guide");
+
+ // MCP reading.
+ breng.DeviceSetParam(brt, brdi, 4, 1f);
+ breng.DeviceSetParam(brt, brdi, 0, 0.2f);
+ Render(44100);
+ var brtools = new Nota.Mcp.Tools.DeviceTools(breng, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ var brr = brtools.ReadBeatRepeat(brt, brdi).Result;
+ Check(brr.Mode == "Insert" && brr.Timeline.Length == 32 && brr.SampleRate > 1000 && Math.Abs(brr.IntervalBeats - 1) < 1e-3 && brr.Bursts > 0
+ && brr.Timeline.Any(s => s.Kind == "repeat") && brr.Summary.Length > 0 && brr.Live.Length > 0,
+ $"MCP read_beat_repeat reports mode, interval, bursts and the timeline ({brr.Mode}, {brr.IntervalBeats} beats, {brr.Bursts} bursts)");
+
+ // Every factory preset names only real params and renders finite.
+ var brcat = new FactoryPresetCatalog();
+ int brPresets = 0; bool brNamesOk = true, brPresetsFinite = true;
+ var brNames = new HashSet<string>();
+ for (int p = 0; p < brpc; p++) brNames.Add(breng.DeviceParamName(brt, brdi, p));
+ foreach (var info in brcat.All())
+ {
+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 11) continue;
+ var doc = brcat.Document(info.Id);
+ if (doc is null) continue;
+ brPresets++;
+ foreach (var k in doc.NamedParams!.Keys) if (!brNames.Contains(k)) { brNamesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }
+ brcat.ApplyInPlace(breng, info.Id, brt, brdi);
+ var pb = Render(22050);
+ foreach (var v in pb) if (!float.IsFinite(v) || Math.Abs(v) > 4f) { brPresetsFinite = false; Console.WriteLine($" preset {info.DisplayName} not finite"); break; }
+ }
+ Check(brPresets >= 25 && brNamesOk && brPresetsFinite, $"{brPresets} Beat Repeat factory presets, all params known, all render finite");
+
+ breng.DeviceSetParam(brt, brdi, 5, 1.0f);
+ breng.DeviceSetParam(brt, brdi, 17, 1.0f);
int brcopy = breng.DuplicateTrack(brt);
- Check(brcopy > 0 && Math.Abs(breng.DeviceGetParam(brcopy, brdi, 5) - 1.0f) < 1e-3f, "duplicate track clones Beat Repeat params");
+ Check(brcopy > 0 && Math.Abs(breng.DeviceGetParam(brcopy, brdi, 5) - 1.0f) < 1e-3f && breng.DeviceGetParam(brcopy, brdi, 17) > 0.5f,
+ "duplicate track clones Beat Repeat params (appended ones too)");
}
// ===================== built-in Volt project round-trip ===================