Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
Redesign of Auto Shift
Egor Khindikaynenbb61953dcfe6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27fa9cbd..8cacf585 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,43 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.level, the effective attack and release, look-ahead latency and how often it kicked in.### Changed+- **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+ **Trace**, **Scale** and **MIDI** tabs, a **Shift** / **Detect** panel and a status strip:+ - **Trace** — the sung pitch and the corrected one over the last two seconds on the+ scale's note lanes, the target lit; key, scale, Auto / Manual / MIDI and Learn above it;+ Amount, Speed, Range and the new **Human**, which keeps vibrato and drift around the+ corrected note instead of flattening them.+ - **Scale** — how long each note was sung (the last ~16 bars) under the scale's notes, and+ twelve note buttons: click one to add or take it out, which makes a **Custom** scale. The+ scale list adds Harmonic and Melodic Minor, Dorian, Phrygian, Lydian, Mixolydian, Blues and+ Whole Tone. **Learn** listens, then sets the key and scale that fit what was sung; **Auto**+ follows it as you go (both match Krumhansl key profiles, with the runner-up shown).+ - **MIDI** — pick an instrument track and the voice is pulled to its notes: the last held+ note or the held notes as a scale, Latch between notes, Oct lock, and **Pitch bend from+ MIDI** with Glide and Bend (steps within the bend range glide, wider leaps jump). The+ guide track can stay muted.+ - **Shift** — Shift, the new **Fine** (±100 ¢), the new **Formant** shift and Mix, the note+ being sung with its frequency and clarity, **Preserve formants**. **Detect** — a voice-type+ source list, the detection range (Low / High), Sensitivity, the Learn result and **Skip+ sibilants** (s, sh and breaths pass unshifted instead of turning metallic).+ - The shifter is new: pitch-synchronous grains taken a whole period apart, so with Preserve+ formants the vowel stays where it was while the pitch moves (a +12 st shift no longer+ sounds like a chipmunk), Formant moves the vowel on its own, the shifted voice keeps its+ level, and with nothing to correct the sound passes through unchanged. The pitch tracker runs on an FFT and only looks inside+ the detection range, so low voices are found and CPU stays low.+ - **34 factory presets**, up from six — correction styles (hard tune, robot, natural, pop,+ R&B, ballad, rap, choir, auto key), scales (blues, dorian, pentatonic …), voice types,+ creative shifts (octaves, chipmunk, monster, gender up / down, doubler, fifth harmony) and+ MIDI targets (harmony lock, melody replace). The 26 new parameters are appended and default+ to the old behaviour, so older projects open unchanged; every one of them automates (the+ scale notes, the detector and the MIDI target are grouped in the lane menu), MIDI-learns,+ saves in a preset and is reachable over MCP. `get_device_text` returns the status line,+ the live reading and a guide to the parameter values, `device_action` 0 resets the+ analysis and 1 runs Learn, `set_device_sidechain` picks the MIDI source, and the new+ `read_auto_shift` returns the pitch, target, correction, scale, sung notes, key guesses,+ the MIDI note and the last two seconds of pitch.- **Nota Shutter shows the gate working, and gains a shape, trigger mode and a real keyswitch.** The card moves onto the 700 × 260 frame of Utility, Valve and Vintage — a STATEcolumn (the input, or the key when a sidechain drives it, with the threshold tick, and the@@ -245,6 +282,15 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.returns the compressor's status line.### Fixed+- **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+ combed; both are aligned now. Follow scale device wrote the Nota Scale's root into the key as+ a raw number, so it landed on B for any root but C — it now copies the key and the scale. The Speed+ readout showed 1–250 ms while the engine used 2–300 ms.+- **Device commands inside a rack.** A card in a rack chain (Reset on Shutter, Learn on Auto+ Shift) sent its command to the track's own device at the same position instead; it now does+ nothing there.- **Nota Shutter's detector and Duck.** The detector's follower let go of the key within asample instead of over 3 ms, so the gate leaned on Hold to stay open on low notes; it nowfollows the key as intended, and the level meters decay smoothly. In Duck, Attack now setsdiff --git a/FEATURES.md b/FEATURES.mdindex 9fd33995..42ccd77f 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -373,9 +373,14 @@ and user presets, automation, persistence and cloning.response over the spectrum, modulation range) / Envelope (cutoff over time) / LFO (motionover two bars) and Mod / Output, with a SHAPE column and a status strip. 30 factorypresets. MCP: `read_filter_motion`.-- **Nota Auto Shift** (7) — real-time vocal pitch correction: pitch detection, Key +- Scale, Follow scale device, correction amount and speed, Range (guards against octave- jumps), Formant, Mix; a PITCH TRACE visualiser.+- **Nota Auto Shift** (10) — real-time vocal pitch correction: an FFT NSDF pitch tracker+ with a detection range (voice-type presets), sensitivity and sibilant detection; Key ++ Scale (5 scales, 8 modes, a Custom 12-note set), Auto key and one-shot Learn (Krumhansl+ key profiles over the sung-note histogram), Follow scale device, or a MIDI target from+ another track's notes (Note / Scale, Latch, Oct lock, Glide within a bend range); Amount,+ Speed, Range, Human (keeps vibrato); a PSOLA shifter with Shift, Fine, Preserve formants+ and Formant shift, Skip sibilants, Mix, latency compensated. Trace / Scale / MIDI graphs, a+ PITCH column, Shift / Detect panel; 34 factory presets; MCP `read_auto_shift`.- **Nota Vintage** (8) — degradation and saturation: 6 era characters(Vinyl/Cassette/Reel/VHS/Tube/Analog, with the voicing switchable off), drive, tone with aWarm / Flat / Dark model and low / high shelves, wow (free or tempo-synced) and flutter withdiff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.csindex 2c9722d4..33a0aab3 100644--- a/src/managed/Nota.App/ArrangementView.Automation.cs+++ b/src/managed/Nota.App/ArrangementView.Automation.cs@@ -391,10 +391,11 @@ public sealed partial class ArrangementView// view ("Spectrum", "Scope", "Waterfall", "Cursor"), the Compressor its key// ("SC HP", "SC Gain" …), the Auto Filter its sources ("Env", "LFO", "Mod"), Nota// Vintage its tone and wow ("Tone Low", "Wow Rate" …), Nota Valve its mic ("Mic Distance" …),- // Nota Utility its mono, phase and true-peak params ("Mono Freq", "Invert L", "TP Ceiling" …) and- // Nota Shutter its detector ("Det HP", "Det LP", "Det Filter"):+ // 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" …):// 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 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 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/AutoShiftViews.cs b/src/managed/Nota.App/Controls/AutoShiftViews.csnew file mode 100644index 00000000..5dcfd99f--- /dev/null+++ b/src/managed/Nota.App/Controls/AutoShiftViews.cs@@ -0,0 +1,275 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Auto Shift (device kind 10) card windows, all read from the engine's telemetry+// (AutoShift.h scopeRead), so the picture is what the corrector does:+// · AsPill — the PITCH column: IN (where the voice sits in the detection range, brass,+// rising from the bottom) or CORR (the correction now, teal, bipolar about the centre).+// · AsTraceView — the Trace and MIDI tabs: the detected pitch (teal dots) and the output+// (brass line) over the last ~2 s on note lanes of the active scale, the target lane lit;+// in MIDI mode the source's notes are drawn as blocks on their lanes.+// · AsHistView — the Scale tab: how long each pitch class was sung (decaying over ~16+// bars), in-scale columns brass, sung out-of-scale ones teal. Clicking a column toggles+// that note in the scale.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;++namespace Nota.App;++internal sealed class AsPill : Control+{+ private double _v = double.NaN;+ /// <summary>Bipolar: the fill hangs from the centre (the correction); else it rises from the bottom.</summary>+ public bool Bipolar { get; init; }+ public IBrush Ink { get; init; } = NotaPalette.Accent;++ public AsPill() { Width = 16; }++ /// <summary>0..1 (bipolar: −1..1), NaN = nothing to show.</summary>+ public void Set(double v)+ {+ if (!double.IsNaN(v)) v = Bipolar ? Math.Clamp(v, -1, 1) : Math.Clamp(v, 0, 1);+ if (v.Equals(_v) || (!double.IsNaN(v) && !double.IsNaN(_v) && Math.Abs(v - _v) < 1e-3)) return;+ _v = v; InvalidateVisual();+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 4 || h < 8) return;+ var rect = new Rect(0.5, 0.5, w - 1, h - 1);+ double r = Math.Min(8, w / 2);+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), rect, r, r);+ using (ctx.PushClip(new RoundedRect(rect, r)))+ {+ var wash = NotaPalette.Wash((SolidColorBrush)Ink, 0x4C);+ if (Bipolar)+ {+ double mid = h / 2;+ ctx.FillRectangle(NotaPalette.BorderStrong, new Rect(2, mid - 0.5, w - 4, 1));+ if (double.IsNaN(_v)) return;+ double y = mid - _v * (h / 2 - 2);+ ctx.FillRectangle(wash, new Rect(0, Math.Min(mid, y), w, Math.Abs(y - mid)));+ ctx.FillRectangle(Ink, new Rect(1.5, Math.Clamp(y - 1, 0, h - 2), w - 3, 2));+ }+ else+ {+ if (double.IsNaN(_v)) return;+ double y = (1 - _v) * h;+ ctx.FillRectangle(wash, new Rect(0, y, w, h - y));+ ctx.FillRectangle(Ink, new Rect(1.5, Math.Clamp(y - 1, 0, h - 2), w - 3, 2));+ }+ }+ }+}++internal sealed class AsTraceView : Control+{+ private static readonly string[] Names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ private float[] _det = Array.Empty<float>(), _out = Array.Empty<float>(), _midi = Array.Empty<float>();+ private int _n;+ private int _mask = 0x0AB5;+ private double _target, _center = 60;+ private bool _midiMode;+ private string _window = "2 s";++ public AsTraceView() { ClipToBounds = true; MinHeight = 40; }++ /// <summary>Histories (MIDI note numbers, 0 = none) from <paramref name="src"/>, the active+ /// pitch-class mask (absolute), the target note now (0 = none), MIDI mode, the window text.</summary>+ public void Set(float[] src, int detAt, int outAt, int midiAt, int n, int mask, double target, bool midiMode, string window)+ {+ if (_det.Length != n) { _det = new float[n]; _out = new float[n]; _midi = new float[n]; }+ if (n > 0 && midiAt + n <= src.Length)+ {+ Array.Copy(src, detAt, _det, 0, n); Array.Copy(src, outAt, _out, 0, n); Array.Copy(src, midiAt, _midi, 0, n);+ }+ _n = n; _mask = mask; _target = target; _midiMode = midiMode; _window = window;+ // The lanes follow the latest pitch (target, else output, else MIDI) smoothly.+ double follow = target > 0 ? target : 0;+ for (int k = n - 1; k >= 0 && follow <= 0; k--) { if (_out[k] > 0) follow = _out[k]; else if (_midi[k] > 0) follow = _midi[k]; }+ if (follow > 0) _center += (follow - _center) * (Math.Abs(follow - _center) > 7 ? 1 : 0.2);+ InvalidateVisual();+ }++ // Seven lanes: the scale notes around the centre (chromatic when the scale is too thin).+ private int[] Lanes()+ {+ int mask = BitCount(_mask) >= 5 ? _mask : 0x0FFF;+ int c = (int)Math.Round(_center);+ var below = new List<int>(); var above = new List<int>();+ int anchor = c;+ for (int d = 0; d < 12; d++) { if (In(mask, c - d)) { anchor = c - d; break; } if (In(mask, c + d)) { anchor = c + d; break; } }+ for (int m = anchor - 1; below.Count < 3 && m > anchor - 24; m--) if (In(mask, m)) below.Add(m);+ for (int m = anchor + 1; above.Count < 3 && m < anchor + 24; m++) if (In(mask, m)) above.Add(m);+ var lanes = new List<int>();+ for (int i = above.Count - 1; i >= 0; i--) lanes.Add(above[i]);+ lanes.Add(anchor);+ lanes.AddRange(below);+ return lanes.ToArray(); // top → bottom+ }+ private static bool In(int mask, int m) => (mask >> (((m % 12) + 12) % 12) & 1) != 0;+ private static int BitCount(int m) { int c = 0; for (; m != 0; m &= m - 1) c++; return c; }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ var frame = new Rect(0, 0, w, h);+ NotaGraph.Window(ctx, frame);+ var lanes = Lanes();+ int nl = lanes.Length;+ double laneH = (h - 2) / nl;+ double LaneY(int i) => 1 + (i + 0.5) * laneH;+ // Pitch → y, piecewise linear between the lanes (so every lane is the same height).+ double Y(double m)+ {+ if (m >= lanes[0]) return LaneY(0) - (m - lanes[0]) * laneH / 2;+ for (int i = 0; i < nl - 1; i++)+ if (m >= lanes[i + 1]) { double t = (lanes[i] - m) / Math.Max(1e-6, lanes[i] - lanes[i + 1]); return LaneY(i) + t * laneH; }+ return LaneY(nl - 1) + (lanes[nl - 1] - m) * laneH / 2;+ }++ int tgtNote = _target > 0 ? (int)Math.Round(_target) : int.MinValue;+ for (int i = 0; i < nl; i++)+ {+ var band = new Rect(0, 1 + i * laneH, w, laneH);+ if (lanes[i] == tgtNote) ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Accent, 0x14), band);+ else if (i % 2 == 0) ctx.FillRectangle(NotaPalette.Wash(NotaPalette.BorderDefault, 0x30), band);+ }+ for (int i = 1; i < 4; i++) ctx.DrawLine(NotaGraph.GridPen, new Point(w * i / 4, 0), new Point(w * i / 4, h));+ if (tgtNote != int.MinValue)+ {+ int ti = Array.IndexOf(lanes, tgtNote);+ if (ti >= 0) ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Accent, 0x40), 1), new Point(0, LaneY(ti)), new Point(w, LaneY(ti)));+ }++ double gx = 20, gw = w - gx - 4;+ double X(int k) => gx + (_n <= 1 ? 0 : (double)k / (_n - 1) * gw);++ // MIDI blocks: runs of one target note.+ if (_midiMode && _n > 1)+ {+ int k = 0;+ while (k < _n)+ {+ if (_midi[k] <= 0) { k++; continue; }+ int note = (int)Math.Round(_midi[k]), s = k;+ while (k < _n && _midi[k] > 0 && (int)Math.Round(_midi[k]) == note) k++;+ double y = Y(note), bh = Math.Max(4, laneH * 0.7);+ bool now = k >= _n;+ var r = new Rect(X(s), y - bh / 2, Math.Max(2, X(k - 1) - X(s)), bh);+ ctx.DrawRectangle(NotaPalette.Wash(NotaPalette.Accent, now ? (byte)0x4C : (byte)0x2E),+ new Pen(now ? NotaPalette.AccentBright : NotaPalette.Accent, now ? 1.2 : 1), new RoundedRect(r, 2));+ }+ }++ // Detected: teal dots.+ var dot = NotaPalette.Wash(NotaPalette.Teal, 0xB0);+ for (int k = 0; k < _n; k += 2)+ if (_det[k] > 0) ctx.DrawEllipse(dot, null, new Point(X(k), Y(_det[k])), 0.9, 0.9);++ // Output: brass line, broken where unvoiced.+ StreamGeometry? geo = null; StreamGeometryContext? gc = null;+ Point last = default; bool any = false;+ void Flush() { if (gc != null) { gc.Dispose(); ctx.DrawGeometry(null, NotaGraph.PrimaryPen, geo!); gc = null; geo = null; } }+ for (int k = 0; k < _n; k++)+ {+ if (_out[k] <= 0) { Flush(); continue; }+ var p = new Point(X(k), Y(_out[k]));+ if (gc == null) { geo = new StreamGeometry(); gc = geo.Open(); gc.BeginFigure(p, false); }+ else gc.LineTo(p);+ last = p; any = k == _n - 1;+ }+ Flush();+ if (any) ctx.DrawEllipse(NotaPalette.Accent, new Pen(NotaGraph.Ground, 1), last, 2.6, 2.6);++ // Lane labels, the target lit.+ for (int i = 0; i < nl; i++)+ {+ int m = lanes[i];+ var ft = NotaGraph.AxisText(Names[((m % 12) + 12) % 12] + (m / 12 - 1), m == tgtNote ? NotaPalette.AccentBright : null, 6);+ ctx.DrawText(ft, new Point(4, LaneY(i) - ft.Height / 2));+ }+ if (_midiMode) NotaGraph.Legend(ctx, w - 5, 2, ("MIDI", NotaPalette.AccentBright, NotaGraph.Mark.Area), ("input", NotaPalette.TealBright, NotaGraph.Mark.Dashed));+ else NotaGraph.Legend(ctx, w - 5, 2, ("input", NotaPalette.TealBright, NotaGraph.Mark.Dashed), ("corrected", NotaPalette.AccentBright, NotaGraph.Mark.Line));+ var t0 = NotaGraph.AxisText("−" + _window, null, 6);+ ctx.DrawText(t0, new Point(gx, h - t0.Height - 1));+ var t1 = NotaGraph.AxisText("now", null, 6);+ ctx.DrawText(t1, new Point(w - 5 - t1.Width, h - t1.Height - 1));+ }+}++internal sealed class AsHistView : Control+{+ private static readonly string[] Names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ private readonly float[] _h = new float[12];+ private int _mask, _key;+ private string _outName = "";+ private int _hover = -1;++ /// <summary>A pitch class was clicked (toggle it in the scale).</summary>+ public event Action<int>? NoteClicked;++ public AsHistView() { ClipToBounds = true; MinHeight = 30; Cursor = new Cursor(StandardCursorType.Hand); }++ public void Set(float[] src, int at, int mask, int key)+ {+ if (at + 12 <= src.Length) Array.Copy(src, at, _h, 0, 12);+ _mask = mask; _key = key;+ // The most-sung note outside the scale, for the legend.+ int best = -1; float bv = 0.08f;+ for (int i = 0; i < 12; i++) if ((mask >> i & 1) == 0 && _h[i] > bv) { bv = _h[i]; best = i; }+ _outName = best >= 0 ? ", " + Names[best] : "";+ InvalidateVisual();+ }++ private int Col(Point p)+ {+ double gw = (Bounds.Width - 12) / 12;+ int i = (int)Math.Floor((p.X - 6) / gw);+ return i is >= 0 and < 12 ? i : -1;+ }+ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ int i = Col(e.GetPosition(this));+ if (i >= 0) { NoteClicked?.Invoke(i); e.Handled = true; }+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ int i = Col(e.GetPosition(this));+ if (i != _hover) { _hover = i; InvalidateVisual(); }+ }+ protected override void OnPointerExited(PointerEventArgs e) { base.OnPointerExited(e); _hover = -1; InvalidateVisual(); }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ var frame = new Rect(0, 0, w, h);+ NotaGraph.Window(ctx, frame);+ double top = 15, bot = h - 4, gw = (w - 12) / 12, gap = 4;+ for (int i = 0; i < 12; i++)+ {+ bool inScale = (_mask >> i & 1) != 0;+ double v = Math.Clamp(_h[i], 0, 1);+ double bh = Math.Max(1.5, v * (bot - top));+ IBrush fill = inScale ? (i == _key ? NotaPalette.Accent : NotaPalette.Wash(NotaPalette.Accent, 0x8C))+ : v > 0.08 ? NotaPalette.Wash(NotaPalette.Teal, 0x99) : NotaPalette.BorderDefault;+ var r = new Rect(6 + i * gw + gap / 2, bot - bh, gw - gap, bh);+ if (i == _hover) ctx.FillRectangle(NotaPalette.Wash(NotaPalette.BorderStrong, 0x30), new Rect(6 + i * gw + 1, top - 2, gw - 2, bot - top + 2));+ ctx.DrawRectangle(fill, null, new RoundedRect(r, 2, 2, 0, 0));+ }+ var title = new FormattedText("SUNG NOTES", System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.SansBold, 7, NotaGraph.TitleInk);+ ctx.DrawText(title, new Point(5, 3));+ NotaGraph.Legend(ctx, w - 5, 2, ("in scale", NotaPalette.AccentBright, NotaGraph.Mark.Area), ("out of scale" + _outName, NotaPalette.TealBright, NotaGraph.Mark.Area));+ }+}diff --git a/src/managed/Nota.App/Controls/AutoShiftViz.cs b/src/managed/Nota.App/Controls/AutoShiftViz.csdeleted file mode 100644index 84ca0d27..00000000--- a/src/managed/Nota.App/Controls/AutoShiftViz.cs+++ /dev/null@@ -1,125 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.-//-// Nota Auto Shift pitch trace (mockup 3i): draws the device's two published histories —-// the detected pitch as a teal dotted cloud and the corrected output as a solid brass-// line — over labelled note lanes for a one-octave window that follows the corrected-// pitch, with the current target lane lit. A tuner needs to show both signals, so you-// can see how much correction the device is applying over the last few seconds.--using System;-using System.Globalization;-using Avalonia;-using Avalonia.Controls;-using Avalonia.Media;--namespace Nota.App;--internal sealed class AutoShiftViz : Control-{- private static readonly IBrush Sunken = NotaPalette.BgSunken;- private static readonly IBrush BorderDef = NotaPalette.GraphBorder;- private static readonly IBrush Brass = NotaPalette.Accent;- private static readonly IBrush Teal = NotaPalette.Teal;- private static readonly IBrush TealDim = NotaPalette.Wash(NotaPalette.Teal, 0x8C);- private static readonly IBrush Muted = NotaPalette.TextTertiary;- private static readonly IBrush Faint = NotaPalette.TextAxis;- private static readonly IBrush LaneLine = NotaPalette.Wash(NotaPalette.BorderStrong, 0x2A);- private static readonly IBrush WhiteLane = NotaPalette.Wash(NotaPalette.BorderStrong, 0x44);- private static readonly IBrush TargetLine = NotaPalette.Wash(NotaPalette.AccentBright, 0x55);- private static readonly IBrush TargetLabel = NotaPalette.AccentBright;- private static readonly Typeface Mono = NotaFonts.Mono;- private static readonly Typeface Bold = NotaFonts.SansBold;- private static readonly string[] Names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };- private static bool IsWhite(int pc) => pc is 0 or 2 or 4 or 5 or 7 or 9 or 11;-- private float[] _det = Array.Empty<float>(), _corr = Array.Empty<float>();- private int _n;- private double _center = 60; // smoothed window centre (MIDI)-- public AutoShiftViz() { MinWidth = 160; MinHeight = 80; }-- // det/corr are normalized MIDI (v*127), interleaved histories from the device.- public void SetTraces(float[] det, float[] corr, int n)- {- _det = det; _corr = corr; _n = n;- // Follow the latest voiced corrected note so the octave window scrolls smoothly.- for (int k = n - 1; k >= 0; k--)- if (corr.Length > k && corr[k] > 1e-4f) { _center += (corr[k] * 127.0 - _center) * 0.15; break; }- InvalidateVisual();- }-- 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 + 1, plotTop = pad + 14, plotBot = h - pad - 11;- double gutter = 22, x0 = pad + gutter, x1 = w - pad;-- // Header + legend.- g.DrawText(new FormattedText("PITCH TRACE", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Bold, 8, Muted), new Point(pad, headY));- NotaGraph.Legend(g, x1, headY, ("detected", Teal, NotaGraph.Mark.Dashed), ("corrected", Brass, NotaGraph.Mark.Line));-- // One-octave window centred on the (smoothed) corrected pitch.- int lowMidi = (int)Math.Round(_center) - 6;- double span = 12.0, ph = plotBot - plotTop;- double Y(double midi) => plotBot - Math.Clamp((midi - lowMidi) / span, 0, 1) * ph;-- // Note lanes: white notes labelled, target lane lit.- int targetNote = int.MinValue;- for (int k = _n - 1; k >= 0; k--) if (_corr.Length > k && _corr[k] > 1e-4f) { targetNote = (int)Math.Round(_corr[k] * 127.0); break; }- for (int m = lowMidi; m <= lowMidi + 12; m++)- {- int pc = ((m % 12) + 12) % 12;- double y = Y(m);- bool white = IsWhite(pc);- g.DrawLine(new Pen(white ? WhiteLane : LaneLine, 1), new Point(x0, y), new Point(x1, y));- if (white)- {- var lbl = new FormattedText(Names[pc] + (m / 12 - 1), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, m == targetNote ? TargetLabel : Faint);- g.DrawText(lbl, new Point(pad - 1, y - lbl.Height / 2));- }- }- if (targetNote != int.MinValue)- {- double ty = Y(targetNote);- g.DrawLine(new Pen(TargetLine, 1), new Point(x0, ty), new Point(x1, ty));- }-- // Traces. Detected = teal dots (raw), corrected = brass line + dots.- int n = Math.Min(_n, Math.Min(_det.Length, _corr.Length));- double X(int k) => x0 + (n <= 1 ? 0 : (double)k / (n - 1) * (x1 - x0));- for (int k = 0; k < n; k++)- {- float dv = _det[k];- if (dv > 1e-4f) g.DrawEllipse(TealDim, null, new Point(X(k), Y(dv * 127.0)), 1.4, 1.4);- }- var pen = new Pen(Brass, NotaGraph.PrimaryWidth, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round);- StreamGeometry? geo = null; StreamGeometryContext? gc = null; bool open = false;- void Flush() { if (gc != null) { gc.Dispose(); g.DrawGeometry(null, pen, geo!); gc = null; geo = null; } open = false; }- for (int k = 0; k < n; k++)- {- float cv = _corr[k];- if (cv <= 1e-4f) { Flush(); continue; }- var p = new Point(X(k), Y(cv * 127.0));- if (!open) { geo = new StreamGeometry(); gc = geo.Open(); gc.BeginFigure(p, false); open = true; }- else gc!.LineTo(p);- if (k == n - 1) g.DrawEllipse(Brass, null, p, 2.4, 2.4);- }- Flush();-- // Time axis.- g.DrawText(new FormattedText("−2\u2009s", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Faint), new Point(x0, plotBot + 2));- if (targetNote != int.MinValue)- {- int pc = ((targetNote % 12) + 12) % 12;- var tt = new FormattedText(Names[pc] + (targetNote / 12 - 1) + " target", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, TargetLabel);- g.DrawText(tt, new Point((x0 + x1) / 2 - tt.Width / 2, plotBot + 2));- }- var now = new FormattedText("now", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Faint);- g.DrawText(now, new Point(x1 - now.Width, plotBot + 2));- }-}diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.csindex e498260f..b0d8a009 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.cs@@ -1,17 +1,23 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — built-in Nota Auto Shift (device kind 10) body, mockup 3i: a full-// 700×260 shell with a LIVE strip (detected note + cents meter + key source), a KEY grid-// + SCALE list + Follow-scale-device rail, the two-trace PITCH TRACE plot, and a-// CORRECT (teal) / SHIFT (brass) parameter rail. Auto key / Learn key / Follow are driven-// here from the device's published pitch history + the track's Nota Scale MIDI effect;-// the DSP just snaps to the current Key + Scale, so everything persists/automates.+// Detail · Devices — built-in Nota Auto Shift body (pitch correction, device kind 10), a build+// of the "Nota Auto Shift" mockup (700 × 260) on the Shutter / Utility / Valve frame: an+// always-visible PITCH column (where the voice sits · the correction now), a centre panel+// with Trace / Scale / MIDI tabs — the detected and corrected pitch on the scale's note+// lanes, the sung-note histogram under the scale's notes (click to edit, Learn), the MIDI+// target from another track's notes — a right panel with Shift / Detect tabs, and a status+// strip. The pictures come from the engine (AutoShift.h scopeRead). Every control is a+// device param, so automation / MIDI learn / presets / A-B / persistence come for free;+// Learn and Reset are device actions, the MIDI source rides on the sidechain source, and+// Follow (copy a Nota Scale's key and scale) is driven from here.+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).using System;-using System.Globalization;+using System.Collections.Generic;using Avalonia;using Avalonia.Controls;+using Avalonia.Controls.Primitives;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;@@ -22,240 +28,793 @@ namespace Nota.App;internal sealed class AutoShiftDeviceBody : IDeviceBody{- // Param indices — must match AutoShift.h.- private const int Key = 0, Scale = 1, Amount = 2, Speed = 3, Shift = 4, Mix = 5, Range = 6, Formant = 7, KeySrc = 8, Follow = 9;+ // ── Parameter indices (must match AutoShift.h) ───────────────────────────+ private const int Key = 0, Scale = 1, Amount = 2, Speed = 3, Shift = 4, Mix = 5, Range = 6, Formant = 7, KeySrc = 8, Follow = 9,+ Human = 10, Fine = 11, FormantShift = 12, DetLow = 13, DetHigh = 14, DetSens = 15, SkipSib = 16, Custom = 17, NoteC = 18,+ MidiMode = 30, MidiLatch = 31, MidiOct = 32, MidiGlide = 33, MidiBendRange = 34, MidiBend = 35;+ // Scope layout (AutoShift::S_* / kTele / kHist).+ private const int S_DetMidi = 0, S_TargetMidi = 1, S_OutMidi = 2, S_CorrCents = 3, S_Conf = 4, S_Hz = 5, S_Voiced = 6, S_Sibilant = 7,+ S_SampleRate = 8, S_Cpu = 9, S_Latency = 10, S_MidiNote = 11, S_MidiVel = 12, S_MidiHeld = 13, S_MidiLive = 14, S_Learning = 15,+ S_LearnKey = 16, S_LearnScale = 17, S_LearnMatch = 18, S_Learn2Key = 19, S_Learn2Scale = 20, S_Learn2Match = 21, S_InScale = 22,+ S_AnalysisSec = 23, S_WindowSec = 24, S_HistN = 25, S_Mask = 26, S_Key = 27, S_Ratio = 28, S_InDb = 29, S_Bars = 30,+ kTele = 32, kHist = 384;+ private const int PcAt = kTele, H_Det = kTele + 12, H_Out = H_Det + kHist, H_Midi = H_Out + kHist, kScope = H_Midi + kHist;+ private const int A_ResetAnalysis = 0, A_Learn = 1;+private static readonly string[] Keys = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };private static readonly string[] Scales = { "Chromatic", "Major", "Minor", "Penta Maj", "Penta Min" };- private static readonly int[] Masks = { 0x0FFF, 0x0AB5, 0x05AD, 0x0295, 0x04A9 };-- 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 Bd2 = NotaPalette.GraphBorder;- 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 Red = NotaPalette.Accent; // a state, not an alert: red is kept for recording and overload- private static readonly IBrush Hue = NotaPalette.BorderStrong;- private static readonly IBrush Ink = NotaPalette.TextOnAccent;+ private static readonly int[] Masks = { 0x0FFF, 0x0AB5, 0x05AD, 0x0295, 0x04A9 }; // relative to the key+ // More modes: picked from the scale list, they become a Custom scale on the key.+ private static readonly (string Name, int Mask)[] Modes =+ {+ ("Harmonic Minor", 0x09AD), ("Melodic Minor", 0x0AAD), ("Dorian", 0x06AD), ("Phrygian", 0x05AB),+ ("Lydian", 0x0AD5), ("Mixolydian", 0x06B5), ("Blues", 0x04E9), ("Whole Tone", 0x0555),+ };+ // Detection presets (Det Low / Det High as MIDI notes).+ private static readonly (string Name, int Lo, int Hi)[] Voices =+ {+ ("Voice · all", 36, 84), ("Voice · soprano", 57, 88), ("Voice · alto", 52, 84), ("Voice · tenor", 45, 76),+ ("Voice · baritone", 40, 69), ("Voice · bass", 36, 64), ("Instrument", 28, 96),+ };public double Width => 700;-- public string? Subtitle => "PITCH"; // the processing type, shown as the header badgepublic bool FullBleed => true;+ public string? Subtitle => "PITCH";public Control Build(DeviceCardContext ctx, int index){var engine = ctx.Engine;int track = ctx.TrackId, di = index;float P(int p) => engine.DeviceGetParam(track, di, p);- void SetP(int p, float v) => engine.DeviceSetParam(track, di, p, v);void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");- static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));- 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 NoteName(int m) => Keys[((m % 12) + 12) % 12] + (m / 12 - 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;+ bool Blink() => Environment.TickCount64 % 1200 < 820;+ // ---- units ----------------------------------------------------------------+ static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));+ static string Note(int m) => Keys[((m % 12) + 12) % 12] + (m / 12 - 1);+ static string CentsF(double c) => NotaNum.F($"{c:+0;−0;0} ¢");+ static string MsF(double ms) => ms >= 100 ? NotaNum.F($"{ms:0} ms") : ms >= 10 ? NotaNum.F($"{ms:0} ms") : NotaNum.F($"{ms:0.#} ms");int KeyOf() => Math.Clamp((int)Math.Round(P(Key) * 11), 0, 11);- int ScaleOf() => Math.Clamp((int)Math.Round(P(Scale) * 4), 0, 4);- int SnapMidi(double m, int key, int mask)+ int ScaleOf() => Sel(Scale, 5);+ int Src() => P(KeySrc) < 0.25f ? 0 : P(KeySrc) < 0.75f ? 1 : 2;+ bool MidiOn() => Src() == 2;+ int CustomMask() { int m = 0; for (int i = 0; i < 12; i++) if (On(NoteC + i)) m |= 1 << i; return m; }+ static int Rot(int m, int k) { k = ((k % 12) + 12) % 12; return ((m << k) | (m >> (12 - k))) & 0x0FFF; }+ int ActiveMask() => On(Custom) ? CustomMask() : Rot(Masks[ScaleOf()], KeyOf());+ string ScaleName(){- int b = (int)Math.Round(m);- for (int d = 0; d <= 6; d++)- foreach (int s in d == 0 ? new[] { 0 } : new[] { d, -d })- { int note = b + s, pc = ((note - key) % 12 + 12) % 12; if ((mask >> pc & 1) != 0) return note; }- return b;+ if (!On(Custom)) return Scales[ScaleOf()];+ int m = CustomMask(), k = KeyOf();+ for (int i = 0; i < Masks.Length; i++) if (Rot(Masks[i], k) == m) return Scales[i];+ foreach (var md in Modes) if (Rot(md.Mask, k) == m) return md.Name;+ return "Custom";+ }+ string KeyScale() => $"{Keys[KeyOf()]} {ScaleName()}";+ double SpeedMs() => Exp(P(Speed), 2, 300);+ double RangeSt() => 1 + P(Range) * 11;+ double ShiftSt() => (P(Shift) - 0.5) * 24;+ double FineCt() => (P(Fine) - 0.5) * 200;+ double FormPct() => (P(FormantShift) - 0.5) * 200;+ double GlideMs() => Exp(P(MidiGlide), 5, 800);+ double BendSt() => P(MidiBendRange) * 6;+ int LowNote() => 24 + (int)Math.Round(P(DetLow) * 72);+ int HighNote() => 24 + (int)Math.Round(P(DetHigh) * 72);+ string VoiceName()+ {+ foreach (var v in Voices) if (v.Lo == LowNote() && v.Hi == HighNote()) return v.Name;+ return "Custom";}+ string ShiftF(double v) => NotaNum.F($"{(v - 0.5) * 24:+0;−0;0} st");+ string FineF(double v) => CentsF((v - 0.5) * 200);+ string FormF(double v) => NotaNum.F($"{(v - 0.5) * 200:+0;−0;0} %");+ string PctF(double v) => NotaNum.F($"{v * 100:0} %");+ string NoteF(double v) => Note(24 + (int)Math.Round(v * 72));- // ---- pitch trace + live telemetry ----- var viz = new AutoShiftViz { VerticalAlignment = VerticalAlignment.Stretch };- var scope = new float[1024];- var det = new float[512];- var corr = new float[512];-- var noteBig = new TextBlock { Text = "—", FontSize = 15, FontWeight = FontWeight.Bold, Foreground = AmberLit, VerticalAlignment = VerticalAlignment.Bottom };- var centsTb = Mono("", Sub); centsTb.VerticalAlignment = VerticalAlignment.Bottom;- var corrTb = new TextBlock { Text = "", FontSize = 8, Foreground = MutedB, VerticalAlignment = VerticalAlignment.Center };- var keyScaleTb = Mono("C Major", Txt);-- // bipolar cents meter (fixed 96×8)- var mCenter = new Border { Width = 1, Background = Hue, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch };- var mBand = new Border { Background = NotaPalette.Wash(NotaPalette.Accent, 0x59), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch };- var mMark = new Border { Width = 2, Background = Red, CornerRadius = NotaRadius.Bar, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch, Margin = new Thickness(0, 1) };- var centsMeter = new Panel { Width = 96, Height = 8, Children = { new Border { Background = Inset, CornerRadius = NotaRadius.Control }, mCenter, mBand, mMark } };- void SetMeter(double cents)- {- cents = Math.Clamp(cents, -50, 50);- double mx = 48 + cents / 50.0 * 48.0, lo = Math.Min(48, mx);- mBand.Margin = new Thickness(lo, 0, 0, 0); mBand.Width = Math.Max(1, Math.Abs(mx - 48));- mMark.Margin = new Thickness(Math.Clamp(mx - 1, 0, 94), 1, 0, 1);+ // Key-source MIDI track: the sidechain source slot.+ int MidiSrc() => engine.DeviceSidechainSource(track, di);+ string TrackName(int id)+ {+ for (int i = 0; i < engine.TrackCount; i++)+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)+ { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }+ return "—";}+ string MidiSrcName() => MidiSrc() >= 0 ? TrackName(MidiSrc()) : "none";- int AutoKey(int mask)+ // Key change: a Custom scale moves with its tonic.+ void SetKey(int k){- var ch = new double[12]; int voiced = 0;- for (int k = 0; k < det.Length; k++) { float v = det[k]; if (v > 1e-4f) { ch[((int)Math.Round(v * 127) % 12 + 12) % 12] += 1; voiced++; } }- if (voiced < 12) return -1;- int best = 0; double bestE = -1;- for (int key = 0; key < 12; key++) { double e = 0; for (int pc = 0; pc < 12; pc++) if ((mask >> (((pc - key) % 12 + 12) % 12) & 1) != 0) e += ch[pc]; if (e > bestE) { bestE = e; best = key; } }- return best;+ int old = KeyOf();+ if (On(Custom) && k != old)+ {+ int m = Rot(CustomMask(), k - old);+ for (int i = 0; i < 12; i++) if (On(NoteC + i) != ((m >> i & 1) != 0)) SetP(NoteC + i, (m >> i & 1) != 0 ? 1f : 0f);+ }+ SetP(Key, k / 11f);+ if (Src() == 0) SetP(KeySrc, 0.5f); // picking a key by hand leaves Auto}- int FindScaleDevice()+ void SetScale(int s) { SetP(Scale, s / 4f); if (On(Custom)) SetP(Custom, 0f); }+ void SetCustom(int mask){- int n = engine.TrackMidiEffectCount(track);- for (int i = 0; i < n; i++) if (engine.MidiEffectName(track, i) == "Nota Scale") return i;- return -1;+ for (int i = 0; i < 12; i++) { bool on = (mask >> i & 1) != 0; if (On(NoteC + i) != on) SetP(NoteC + i, on ? 1f : 0f); }+ if (!On(Custom)) SetP(Custom, 1f);}-- void Tick()+ void ToggleNote(int pc){- int cnt = engine.DeviceScope(track, di, scope, scope.Length);- int pairs = cnt / 2;- for (int k = 0; k < pairs; k++) { det[k] = scope[2 * k]; corr[k] = scope[2 * k + 1]; }- viz.SetTraces(det, corr, pairs);-- // Auto key / Follow drive Key from the audio / a Nota Scale device.- int src = Math.Clamp((int)Math.Round(P(KeySrc) * 2), 0, 2);- bool follow = P(Follow) >= 0.5f;- if (follow) { int sd = FindScaleDevice(); if (sd >= 0) { float root = engine.MidiEffectGetParam(track, sd, 0); if (Math.Abs(root - P(Key)) > 1e-3) SetP(Key, root); } }- else if (src == 0) { int ak = AutoKey(Masks[ScaleOf()]); if (ak >= 0 && ak != KeyOf()) SetP(Key, ak / 11f); }+ int m = ActiveMask() ^ (1 << pc);+ if (m == 0) return; // keep at least one note+ SetCustom(m);+ RefreshAll();+ }+ void Learn()+ {+ engine.DeviceAction(track, di, A_Learn, Sc(S_Learning) > 0.5 ? 0 : 1, 0);+ ctx.NotifyChanged();+ }- // LIVE readout from the instantaneous detected pitch.- double detNorm = engine.DeviceGainReduction(track, di);- if (detNorm > 1e-4)+ // Follow: copy the key and scale of a Nota Scale — on this track, on the MIDI source, or anywhere.+ (int track, int idx) FindScaleDevice()+ {+ (int, int) On(int t)+ {+ int n = engine.TrackMidiEffectCount(t);+ for (int i = 0; i < n; i++) if (engine.MidiEffectName(t, i) == "Nota Scale") return (t, i);+ return (-1, -1);+ }+ var r = On(track);+ if (r.Item1 < 0 && MidiSrc() >= 0) r = On(MidiSrc());+ for (int i = 0; i < engine.TrackCount && r.Item1 < 0; i++)+ if (engine.TryGetTrackInfo(i, out var ti)) r = On(ti.Id);+ return r;+ }+ long followAt = 0;+ void FollowTick()+ {+ if (!On(Follow) || Environment.TickCount64 - followAt < 250) return;+ followAt = Environment.TickCount64;+ var (ft, fi) = FindScaleDevice();+ if (ft < 0) return;+ int root = Math.Clamp((int)Math.Round(engine.MidiEffectGetParam(ft, fi, 0)), 0, 11);+ int sc = Math.Clamp((int)Math.Round(engine.MidiEffectGetParam(ft, fi, 1)), 0, 10);+ int[] preset = { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };+ int rel = 0;+ if (sc < 10) rel = preset[sc];+ else for (int i = 0; i < 12; i++) if (engine.MidiEffectGetParam(ft, fi, 3 + i) >= 0.5f) rel |= 1 << i;+ if (rel == 0) return;+ int abs = Rot(rel, root);+ if (KeyOf() != root) Raw(Key, root / 11.0);+ int named = Array.FindIndex(Masks, m => Rot(m, root) == abs);+ if (named >= 0) { if (ScaleOf() != named) Raw(Scale, named / 4.0); if (On(Custom)) Raw(Custom, 0); }+ else if (ActiveMask() != abs || !On(Custom)){- double dm = detNorm * 127.0;- int snapped = SnapMidi(dm, KeyOf(), Masks[ScaleOf()]);- double cents = (dm - snapped) * 100.0;- noteBig.Text = NoteName(snapped); noteBig.Foreground = AmberLit;- centsTb.Text = $"{cents:+0;−0;0}\u2009¢";- corrTb.Text = $"→ corrected to {NoteName(snapped)}";- SetMeter(cents);+ for (int i = 0; i < 12; i++) Raw(NoteC + i, (abs >> i & 1) != 0 ? 1 : 0);+ Raw(Custom, 1);}- else { noteBig.Text = "—"; noteBig.Foreground = MutedB; centsTb.Text = ""; corrTb.Text = ""; SetMeter(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 LearnBind(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));- keyScaleTb.Text = $"{Keys[KeyOf()]} {Scales[ScaleOf()]}";+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).+ Control K(int p, string name, Func<double, string> fmt, IBrush? arc = null, string? tip = null)+ {+ var val = Mono(fmt(P(p)), 7, TextPrimary);+ var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = Def(p), Width = 34, Height = 34 };+ knob.ValueChanged += v => { Raw(p, v); val.Text = fmt(P(p)); RefreshAll(); };+ knob.GestureBegin += () => Begin(p);+ knob.GestureEnd += () => End(p);+ LearnBind(knob, p);+ if (tip is not null) ToolTip.SetTip(knob, tip);+ readouts.Add(() => { if (knob.Dragging) return; double c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; val.Text = fmt(P(p)); });+ return KnobCell(name, knob, val, 44);}- ctx.AddDeviceRefresher(Tick);- // ---- horizontal slider (label · track · value) ----- Control Slider(string label, int p, Func<double, string> fmt, IBrush fill, bool bipolar = false)+ // On/off switch bound to a param (>= 0.5 = on).+ Control Toggle(int p, string label, string tip){- var row = DeviceCardKit.SliderRow(label, () => P(p), n => SetP(p, (float)n), () => fmt(P(p)), out var sync,- begin: () => Begin(p), end: () => End(p), bipolar: bipolar, labelWidth: 46, valueWidth: 34);- ctx.AddDeviceRefresher(sync);- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), label);- return row;+ var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); RefreshAll(); }, out var sync);+ readouts.Add(sync);+ LearnBind(wrap, p);+ ToolTip.SetTip(wrap, tip);+ return wrap;}- // ---- segmented / toggle helpers ----- Control Seg(string[] names, IBrush?[] accents, Func<int> get, Action<int> set)+ // Segmented pill over a normalized discrete param.+ Control Seg(int p, string[] names, string tip, Action<int>? pick = null, Func<int>? current = null){- // Role chromas stay inside the graphs; a chosen segment is brass.- var seg = DeviceCardKit.Segments(names, get, set, out var sync);- ctx.AddDeviceRefresher(sync);+ int n = names.Length;+ var seg = Segments(names, current ?? (() => Sel(p, n)), iv => { if (pick is not null) pick(iv); else SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); RefreshAll(); }, out var sync, padX: 5);+ readouts.Add(sync);+ LearnBind(seg, p);+ ToolTip.SetTip(seg, tip);return seg;}- Control PillToggle(string label, int p, IBrush accent)+ Control SourceSeg() => Seg(KeySrc, new[] { "Auto", "Manual", "MIDI" },+ "Key source — Auto follows the key you sing, Manual uses the key and scale you set, MIDI takes the target from another track's notes (MIDI tab)",+ iv => SetP(KeySrc, iv / 2f), Src);++ // 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, Func<bool>? blink = null){- var b = Switch(label, () => P(p) >= 0.5f, () => SetP(p, P(p) >= 0.5f ? 0f : 1f), out var sync);- ctx.AddDeviceRefresher(sync);- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));+ var dot = new Border { Width = 5, Height = 5, CornerRadius = NotaRadius.Pill, Background = Brass, VerticalAlignment = VerticalAlignment.Center, IsVisible = false };+ var tb = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };+ var b = new Border+ {+ Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand),+ VerticalAlignment = VerticalAlignment.Center, Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, HorizontalAlignment = HorizontalAlignment.Center, Children = { dot, 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();+ bool bl = blink?.Invoke() ?? false;+ dot.IsVisible = bl;+ dot.Opacity = bl && !Blink() ? 0.3 : 1;+ }+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); RefreshAll(); e.Handled = true; };+ ToolTip.SetTip(b, tip);+ if (p >= 0) LearnBind(b, p);+ readouts.Add(Hi); Hi();return b;}- Control RailBtn(string label, Action onClick)+ Border ToggleLatch(int p, string text, string tip) => Latch(p, () => On(p), () => SetP(p, On(p) ? 0f : 1f), () => text, tip);+ Border LearnLatch() => Latch(-1, () => Sc(S_Learning) > 0.5, Learn, () => "Learn",+ "Learn — listen to what is sung, then click again to set the key and scale that fit it best", blink: () => Sc(S_Learning) > 0.5);++ // A dropdown box: [text ▾], opens a menu of items.+ Border Drop(Func<string> text, Func<bool> lit, Action<MenuFlyout> fill, string tip, double minW = 0, bool stretch = false, int learnP = -1){- var b = new Border { BorderBrush = Hue, BorderThickness = new Thickness(1), Background = CardBg, CornerRadius = NotaRadius.Badge, Padding = new Thickness(0, 2), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = label, FontSize = 9, Foreground = Sub, HorizontalAlignment = HorizontalAlignment.Center } };- b.PointerPressed += (_, e) => { e.Handled = true; onClick(); };- return b;+ var name = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var chev = new Glyph(GlyphKind.ChevronDown, 7) { Margin = new Thickness(6, 0, 0, 0) };+ var box = new Border+ {+ Height = 16, MinWidth = minW, Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,+ Child = new DockPanel { Children = { Docked(chev, Dock.Right), name } },+ };+ if (stretch) box.HorizontalAlignment = HorizontalAlignment.Stretch;+ readouts.Add(() =>+ {+ bool on = lit();+ name.Text = text();+ name.Foreground = on ? AccentBright : TextPrimary;+ name.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ box.BorderBrush = on ? Brass : BorderDef;+ chev.Foreground = on ? NotaPalette.AccentDim : TextTertiary;+ });+ ToolTip.SetTip(box, tip);+ if (learnP >= 0) LearnBind(box, learnP);+ box.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;+ var fly = new MenuFlyout();+ fill(fly);+ fly.ShowAt(box);+ e.Handled = true;+ };+ return box;+ }+ static MenuItem Item(string label, bool cur, Action pick)+ {+ var mi = new MenuItem { Header = label };+ if (cur) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };+ mi.Click += (_, _) => pick();+ return mi;+ }+ Control KeyDrop(bool lit) => Drop(() => Keys[KeyOf()], () => lit, fly =>+ {+ for (int k = 0; k < 12; k++) { int kv = k; fly.Items.Add(Item(Keys[k], KeyOf() == k, () => { SetKey(kv); RefreshAll(); })); }+ }, "Key — the tonic; the scale's notes are counted from it", 0, false, Key);+ Control ScaleDrop() => Drop(ScaleName, () => false, fly =>+ {+ for (int s = 0; s < Scales.Length; s++) { int sv = s; fly.Items.Add(Item(Scales[s], !On(Custom) && ScaleOf() == s, () => { SetScale(sv); RefreshAll(); })); }+ fly.Items.Add(new Separator());+ foreach (var md in Modes)+ {+ var m = md;+ fly.Items.Add(Item(m.Name, On(Custom) && CustomMask() == Rot(m.Mask, KeyOf()), () => { SetCustom(Rot(m.Mask, KeyOf())); RefreshAll(); }));+ }+ fly.Items.Add(new Separator());+ fly.Items.Add(Item("Custom — edit on the Scale tab", On(Custom), () => { SetCustom(ActiveMask()); RefreshAll(); }));+ }, "Scale — the notes the voice is pulled to", 62, false, Scale);++ // The MIDI source: [name ▾] lists the instrument tracks. Picking one switches Key Source to MIDI.+ Control FromDrop() => Drop(MidiSrcName, () => MidiSrc() >= 0 && MidiOn(), fly =>+ {+ fly.Items.Add(Item("None", MidiSrc() < 0, () => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); RefreshAll(); }));+ for (int i = 0; i < engine.TrackCount; i++)+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track && ti.IsInstrument)+ {+ int id = ti.Id;+ fly.Items.Add(Item(TrackName(id), MidiSrc() == id, () =>+ {+ engine.SetDeviceSidechainSource(track, di, id);+ if (!MidiOn()) SetP(KeySrc, 1f);+ ctx.NotifyChanged(); RefreshAll();+ }));+ }+ }, "From — the instrument track whose notes set the target (its MIDI clips and effects, even when muted)", 74, false, KeySrc);++ Control VoiceDrop() => Drop(VoiceName, () => false, fly =>+ {+ foreach (var v in Voices)+ {+ var vv = v;+ fly.Items.Add(Item(NotaNum.F($"{vv.Name} ({Note(vv.Lo)}…{Note(vv.Hi)})"), LowNote() == vv.Lo && HighNote() == vv.Hi, () =>+ { SetP(DetLow, (vv.Lo - 24) / 72f); SetP(DetHigh, (vv.Hi - 24) / 72f); RefreshAll(); }));+ }+ }, "Source — sets the detection range for a voice type or an instrument", 0, true);++ // Slider row: caps label · track · mono value.+ Control SliderRow(string label, int p, Func<double, string> fmt, bool bipolar = false, bool modulation = false, IBrush? valueInk = 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), bipolar: bipolar, valueWidth: 34, modulation: modulation);+ readouts.Add(sync);+ LearnBind(bar, p);+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("44,*"), VerticalAlignment = VerticalAlignment.Center };+ g.Children.Add(Caps(label));+ g.Children.Add(Col(bar, 1));+ return g;+ }++ 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;+ }+ TextBlock RightInfo(Func<string> text)+ {+ var t = Mono("", 7, AccentBright);+ readouts.Add(() => t.Text = text());+ return t;}+ Control KnobRow(Control[] knobs, Func<string> info1, Func<string> info2)+ {+ var i1 = Mono("", 7, TextTertiary); i1.HorizontalAlignment = HorizontalAlignment.Right;+ var i2 = Mono("", 7, TextTertiary); i2.HorizontalAlignment = HorizontalAlignment.Right;+ i1.TextTrimming = i2.TextTrimming = TextTrimming.CharacterEllipsis;+ readouts.Add(() => { i1.Text = info1(); i2.Text = info2(); });+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 52, ColumnSpacing = 6 };+ g.Children.Add(Row(4, knobs));+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { i1, i2 } }, 1));+ return g;+ }+ static Control TabBody(Control head, Control window, Control bottom) => new DockPanel+ {+ LastChildFill = true, Margin = new Thickness(8, 5, 8, 0),+ Children = { Docked(head, Dock.Top), Docked(bottom, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 0), Child = window } },+ };++ // Live readings shared by the tabs.+ bool Voiced() => Sc(S_Voiced) > 0.5;+ int DetNote() => (int)Math.Round(Sc(S_DetMidi));+ double DetCents() => (Sc(S_DetMidi) - DetNote()) * 100;+ int TargetNote() => Sc(S_TargetMidi) > 0.5 ? (int)Math.Round(Sc(S_TargetMidi)) : -1;+ string InputText() => Voiced() ? NotaNum.F($"{Note(DetNote())} {CentsF(DetCents())}") : Sc(S_Sibilant) > 0.5 ? "sibilant" : "—";+ string TargetText() => TargetNote() >= 0 ? Note(TargetNote()) : "—";++ // ======================================================================+ // LEFT — PITCH column (where the voice sits · the correction now)+ // ======================================================================+ var pitchTitle = Caps("PITCH"); pitchTitle.HorizontalAlignment = HorizontalAlignment.Center;+ var inPill = new AsPill { Ink = Brass, VerticalAlignment = VerticalAlignment.Stretch };+ var corrPill = new AsPill { Ink = Teal, Bipolar = true, VerticalAlignment = VerticalAlignment.Stretch };+ var inLbl = Caps("IN"); inLbl.HorizontalAlignment = HorizontalAlignment.Center;+ var corrLbl = Caps("CORR"); corrLbl.HorizontalAlignment = HorizontalAlignment.Center;+ ToolTip.SetTip(inPill, "The detected pitch, low to high across the detection range (Detect tab)");+ ToolTip.SetTip(corrPill, "The correction now — up or down from the centre, full height = 2 semitones");+ var pitchNote = Mono("—", 9, AccentBright); pitchNote.HorizontalAlignment = HorizontalAlignment.Center; pitchNote.FontWeight = FontWeight.Medium;+ var pitchCents = Mono("", 7, TextPrimary); pitchCents.HorizontalAlignment = HorizontalAlignment.Center;+ readouts.Add(() =>+ {+ bool v = Voiced();+ double lo = LowNote(), hi = Math.Max(lo + 1, HighNote());+ inPill.Set(v ? (Sc(S_DetMidi) - lo) / (hi - lo) : double.NaN);+ corrPill.Set(v ? Sc(S_CorrCents) / 200.0 : double.NaN);+ pitchNote.Text = v ? (TargetNote() >= 0 ? Note(TargetNote()) : Note(DetNote())) : "—";+ pitchNote.Foreground = v ? AccentBright : TextTertiary;+ pitchCents.Text = v ? CentsF(Sc(S_CorrCents)) : "";+ pitchTitle.Foreground = v && (MidiOn() || Math.Abs(Sc(S_CorrCents)) > 1) ? AccentBright : TextTertiary;+ });+ Control PillCol(AsPill 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(corrPill, corrLbl), 1));+ var pitchCol = 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(pitchTitle, Dock.Top), Docked(pitchCents, Dock.Bottom), Docked(pitchNote, Dock.Bottom), pills } },+ };+ DockPanel.SetDock(pitchCol, Dock.Left);- // ---- KEY grid (6×2) + SCALE list ----- Control KeyGrid()+ // ======================================================================+ // CENTRE — Trace+ // ======================================================================+ AsTraceView? trace = null;+ Control TraceTab(){- var grid = new Grid { ColumnSpacing = 3, RowSpacing = 3 };- for (int c = 0; c < 6; 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[12]; var texts = new TextBlock[12];- void Sync() { int cur = KeyOf(); for (int i = 0; i < 12; i++) { bool on = i == cur; cells[i].Background = on ? Amber : Inset; cells[i].BorderBrush = on ? Amber : Bd; texts[i].Foreground = on ? Ink : Sub; } }+ trace = new AsTraceView();+ ToolTip.SetTip(trace, "The detected pitch (teal dots) and the corrected output (brass) over the last two seconds, on the scale's note lanes; the target lane is lit");+ var head = HeadRow(Row(6, Caps("KEY"), KeyDrop(false), ScaleDrop(), SourceSeg(), LearnLatch()), RightInfo(() => TargetNote() >= 0 ? "target " + TargetText() : ""));+ var knobs = KnobRow(new[]+ {+ K(Amount, "AMOUNT", PctF, tip: "Amount — how far the voice is pulled to the target note"),+ K(Speed, "SPEED", v => MsF(Exp(v, 2, 300)), tip: "Speed — how fast the retune glides (2 ms = hard tune)"),+ K(Range, "RANGE", v => NotaNum.F($"±{1 + v * 11:0} st"), tip: "Range — the largest correction; a note further off than this is only pulled this far"),+ K(Human, "HUMAN", PctF, Teal, "Human — keeps vibrato and slow drift around the corrected note (0 = flat)"),+ },+ () => Voiced() ? NotaNum.F($"input {InputText()} → target {TargetText()}") : "no pitch",+ () => (P(Amount) >= 0.95f && SpeedMs() < 12 ? "hard correction" : P(Amount) < 0.4f ? "light correction" : "natural correction")+ + (P(Human) < 0.05f ? " · vibrato cut" : NotaNum.F($" · vibrato kept {P(Human) * 100:0} %")));+ return TabBody(head, trace, knobs);+ }++ // ======================================================================+ // CENTRE — Scale+ // ======================================================================+ AsHistView? histView = null;+ Control ScaleTab()+ {+ histView = new AsHistView();+ histView.NoteClicked += ToggleNote;+ ToolTip.SetTip(histView, "How long each note was sung (the last ~16 bars) over the scale's notes — brass in the scale, teal outside it. Click a column to add or remove its note");+ LearnBind(histView, Custom);+ var scaleSeg = Seg(Scale, new[] { "Chrom", "Major", "Minor", "Pent", "Custom" },+ "Scale — Chromatic, Major, Minor, Pentatonic (major or minor — click again to swap) or Custom (the notes below)",+ iv =>+ {+ if (iv == 4) SetCustom(ActiveMask());+ else if (iv == 3) SetScale(!On(Custom) && ScaleOf() == 3 ? 4 : !On(Custom) && ScaleOf() == 4 ? 3 : ScaleOf() == 2 ? 4 : 3);+ else SetScale(iv);+ },+ () => On(Custom) ? 4 : ScaleOf() >= 3 ? 3 : ScaleOf());+ var head = HeadRow(Row(6, Caps("KEY"), KeyDrop(true), scaleSeg, LearnLatch()),+ RightInfo(() => Sc(S_AnalysisSec) > 0.3 ? NotaNum.F($"match {Sc(S_InScale) * 100:0} %") : ""));++ // Note chips: tonic filled, in-scale outlined, sung out-of-scale dashed teal.+ var chipGrid = new Grid { ColumnSpacing = 4, Margin = new Thickness(6, 0) };+ var chips = new Border[12]; var chipTx = new TextBlock[12];for (int i = 0; i < 12; i++){- int iv = i;- var t = Mono(Keys[i], Sub); t.HorizontalAlignment = HorizontalAlignment.Center;- var c = new Border { Height = 17, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Cursor = new Cursor(StandardCursorType.Hand), Child = t };- c.PointerPressed += (_, e) => { e.Handled = true; SetP(Key, iv / 11f); if (P(Follow) < 0.5f && Math.Round(P(KeySrc) * 2) == 0) SetP(KeySrc, 0.5f); Sync(); };- cells[i] = c; texts[i] = t; Grid.SetColumn(c, i % 6); Grid.SetRow(c, i / 6); grid.Children.Add(c);+ int pc = i;+ chipGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));+ var tb = new TextBlock { Text = Keys[i], FontSize = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Height = 22, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; ToggleNote(pc); e.Handled = true; };+ LearnBind(b, NoteC + i);+ ToolTip.SetTip(b, NotaNum.F($"{Keys[i]} — click to add it to the scale or take it out (makes the scale Custom)"));+ chips[i] = b; chipTx[i] = tb;+ chipGrid.Children.Add(Col(b, i));}- Sync(); ctx.AddDeviceRefresher(Sync);- return grid;+ readouts.Add(() =>+ {+ int mask = ActiveMask(), key = KeyOf();+ for (int i = 0; i < 12; i++)+ {+ bool inS = (mask >> i & 1) != 0, tonic = inS && i == key;+ bool sung = !inS && Sc(PcAt + i) > 0.08;+ chips[i].Background = tonic ? Brass : inS ? NotaPalette.AccentSubtle : Sunken;+ chips[i].BorderBrush = inS ? Brass : sung ? Teal : BorderDef;+ chipTx[i].Foreground = tonic ? OnAccent : inS ? AccentBright : sung ? NotaPalette.TealBright : TextDisabled;+ chipTx[i].FontWeight = tonic ? FontWeight.Bold : inS ? FontWeight.SemiBold : FontWeight.Normal;+ }+ });+ var capL = Mono("", 7, TextTertiary); var capR = Mono("", 7, TextTertiary);+ readouts.Add(() =>+ {+ capL.Text = NotaNum.F($"tonic {Keys[KeyOf()]} · click a note to add or remove it");+ int mask = ActiveMask(), best = -1; double bv = 0.08;+ for (int i = 0; i < 12; i++) if ((mask >> i & 1) == 0 && Sc(PcAt + i) > bv) { bv = Sc(PcAt + i); best = i; }+ if (best < 0) { capR.Text = ""; return; }+ int to = -1;+ for (int d = 1; d <= 6 && to < 0; d++) { if ((mask >> ((best + d) % 12) & 1) != 0) to = (best + d) % 12; else if ((mask >> ((best - d + 12) % 12) & 1) != 0) to = (best - d + 12) % 12; }+ capR.Text = to >= 0 ? NotaNum.F($"{Keys[best]} pulls to {Keys[to]}") : "";+ });+ var caption = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(6, 0) };+ caption.Children.Add(capL); caption.Children.Add(Col(capR, 1));+ var bottom = new StackPanel { Height = 52, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { new Border { Height = 5 }, chipGrid, caption } };+ return TabBody(head, histView, bottom);}- Control ScaleList()++ // ======================================================================+ // CENTRE — MIDI+ // ======================================================================+ AsTraceView? midiView = null;+ Control MidiTab(){- var col = new StackPanel { Spacing = 2 };- var cells = new Border[Scales.Length]; var texts = new TextBlock[Scales.Length];- void Sync() { int cur = ScaleOf(); for (int i = 0; i < Scales.Length; i++) { bool on = i == cur; cells[i].Background = on ? NotaPalette.Wash(NotaPalette.Accent, 0x30) : Inset; texts[i].Foreground = on ? AmberLit : Sub; texts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal; } }- for (int i = 0; i < Scales.Length; i++)+ midiView = new AsTraceView();+ ToolTip.SetTip(midiView, "The source track's notes (brass blocks) and the voice (teal) over the last two seconds — with Key Source MIDI the voice is pulled to the notes");+ var head = HeadRow(Row(6, Caps("FROM"), FromDrop(),+ Seg(MidiMode, new[] { "Note", "Scale" }, "Note — the voice goes to the last held note; Scale — the held notes form the scale"),+ ToggleLatch(MidiLatch, "Latch", "Latch — keep the last target between notes (off = no correction while no note is held)"),+ ToggleLatch(MidiOct, "Oct lock", "Oct lock — the note's own octave (off = whichever octave of it is nearest the voice)")),+ RightInfo(() => MidiOn() ? NotaNum.F($"{Sc(S_MidiHeld):0} {(Math.Round(Sc(S_MidiHeld)) == 1 ? "note" : "notes")}") : "Key Source is not MIDI"));+ var knobs = KnobRow(new[]{- int iv = i;- var t = new TextBlock { Text = Scales[i], FontSize = 9, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center };- var c = new Border { Height = 16, CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = t };- c.PointerPressed += (_, e) => { e.Handled = true; SetP(Scale, iv / (float)(Scales.Length - 1)); Sync(); };- cells[i] = c; texts[i] = t; col.Children.Add(c);+ K(Amount, "AMOUNT", PctF, tip: "Amount — how far the voice is pulled to the note"),+ K(MidiGlide, "GLIDE", v => MsF(Exp(v, 5, 800)), tip: "Glide — how long the target bends from one note to the next (Pitch bend from MIDI)"),+ K(Speed, "SPEED", v => MsF(Exp(v, 2, 300)), tip: "Speed — how fast the voice follows the target"),+ K(MidiBendRange, "BEND", v => NotaNum.F($"±{v * 6:0.#} st"), Teal, "Bend — the widest move between notes that bends over Glide; wider leaps jump"),+ },+ () => !MidiOn() ? "set Key Source to MIDI to follow the notes"+ : Sc(S_MidiNote) < 0 ? (MidiSrc() < 0 ? "pick a track in FROM" : "no note held")+ : Voiced() ? NotaNum.F($"input {InputText()} → clip note {TargetText()}") : NotaNum.F($"clip note {Note((int)Sc(S_MidiNote))}"),+ () => On(MidiLatch) ? "latch holds the target between notes" : "no correction between notes");+ return TabBody(head, midiView, knobs);+ }++ // ======================================================================+ // RIGHT — Shift / Detect+ // ======================================================================+ static Control LabelRow(string label, Control c, double labW = 44)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(NotaNum.F($"{labW},*")) };+ g.Children.Add(new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center });+ g.Children.Add(Col(c, 1));+ return g;+ }+ static Control Spread(params Control[] rows)+ {+ var defs = new List<string>();+ for (int i = 0; i < rows.Length; i++) { if (i > 0) defs.Add("*"); defs.Add("Auto"); }+ var g = new Grid { RowDefinitions = new RowDefinitions(string.Join(",", defs)) };+ for (int i = 0; i < rows.Length; i++) g.Children.Add(GRow(rows[i], i * 2));+ return new Border { Padding = new Thickness(8, 6), Child = g };+ }+ // A reading box: caps title · dot + line · second line.+ Control InfoBox(Func<(string title, bool hot, IBrush dot, bool blink, string l1, string l2)> read, string tip)+ {+ var t = Caps("");+ 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(() =>+ {+ var r = read();+ t.Text = r.title; l1.Text = r.l1; l2.Text = r.l2;+ t.Foreground = r.hot ? AccentBright : TextTertiary;+ l1.Foreground = r.hot ? AccentBright : TextPrimary;+ b.BorderBrush = r.hot ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;+ dot.Background = r.dot;+ dot.Opacity = r.blink && !Blink() ? 0.3 : 1;+ });+ ToolTip.SetTip(b, tip);+ return b;+ }++ Control ShiftTab()+ {+ var noteBox = InfoBox(() =>+ {+ if (MidiOn())+ {+ int mn = (int)Sc(S_MidiNote);+ bool live = mn >= 0;+ return ("MIDI TARGET", true, live ? Brass : BorderStrong, live && Sc(S_MidiHeld) > 0,+ live ? NotaNum.F($"{Note(mn)} · vel {Sc(S_MidiVel):0}") : MidiSrc() < 0 ? "no source" : "no note",+ live && Voiced() ? NotaNum.F($"leads {CentsF(Sc(S_CorrCents))} · glide {MsF(GlideMs())}") : NotaNum.F($"from {MidiSrcName()}"));+ }+ bool v = Voiced();+ return ("NOTE", false, v ? Success : BorderStrong, false,+ v ? NotaNum.F($"{Note(DetNote())} · {Sc(S_Hz):0.0} Hz") : Sc(S_Sibilant) > 0.5 ? (On(SkipSib) ? "sibilant · passed" : "sibilant") : "no pitch",+ v ? NotaNum.F($"correction {CentsF(Sc(S_CorrCents))} · conf {Sc(S_Conf) * 100:0} %") : NotaNum.F($"in {Sc(S_InDb):0} dB"));+ }, "What the detector hears now and the correction applied — or, with Key Source MIDI, the note the voice is pulled to");+ var follow = Toggle(Follow, "Follow Scale device", "Follow — copy the key and scale of a Nota Scale MIDI effect (this track, the MIDI source, or the first one found)");+ var bend = Toggle(MidiBend, "Pitch bend from MIDI", "Pitch bend from MIDI — moves between notes bend over Glide when they are within Bend; off = the target steps");+ readouts.Add(() => { follow.IsVisible = !MidiOn(); bend.IsVisible = MidiOn(); });+ return Spread(+ SliderRow("SHIFT", Shift, ShiftF, bipolar: true),+ SliderRow("FINE", Fine, FineF, bipolar: true),+ SliderRow("FORMANT", FormantShift, FormF, bipolar: true, modulation: true),+ new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = SliderRow("MIX", Mix, PctF) },+ noteBox,+ new StackPanel { Spacing = 5, Children = {+ Toggle(Formant, "Preserve formants", "Preserve formants — the vowel colour stays put while the pitch moves (off = it moves with the pitch, like a tape speed-up)"),+ new Panel { Children = { follow, bend } } } });+ }++ Control DetectTab()+ {+ var learnBox = InfoBox(() =>+ {+ bool learning = Sc(S_Learning) > 0.5;+ if (Sc(S_LearnKey) < 0)+ return ("LEARN", learning, learning ? Brass : BorderStrong, learning, learning ? "listening…" : "—", "sing a few bars");+ string Ks(int k, double s) => $"{Keys[Math.Clamp(k, 0, 11)]} {(s > 1.5 ? "Minor" : "Major")}";+ return ("LEARN", learning, learning ? Brass : Success, learning,+ NotaNum.F($"{Ks((int)Sc(S_LearnKey), Sc(S_LearnScale))} · {Sc(S_LearnMatch) * 100:0} %"),+ NotaNum.F($"next {Ks((int)Sc(S_Learn2Key), Sc(S_Learn2Scale))} · {Sc(S_Learn2Match) * 100:0} %"));+ }, "The key that fits what was sung (Krumhansl profiles over the last ~16 bars), and the runner-up. Learn sets it; Auto follows it");+ return Spread(+ LabelRow("SOURCE", VoiceDrop()),+ SliderRow("LOW", DetLow, NoteF, modulation: true),+ SliderRow("HIGH", DetHigh, NoteF, modulation: true),+ new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = SliderRow("SENS", DetSens, PctF) },+ learnBox,+ new StackPanel { Spacing = 5, Children = {+ Toggle(Follow, "Follow Scale device", "Follow — copy the key and scale of a Nota Scale MIDI effect"),+ Toggle(SkipSib, "Skip sibilants", "Skip sibilants — s, sh, t and breath pass unshifted, so they don't turn metallic") } });+ }++ // ======================================================================+ // Tab frames+ // ======================================================================+ int centreTab = MidiOn() ? 2 : 0;+ var centreHost = new ContentControl();+ var rightHost = new ContentControl();+ var centreBodies = new Control?[3];+ var rightBodies = new Control?[2];+ var extras = Mono("", 7, TextTertiary);+ var extrasHost = new Border { Background = Brushes.Transparent, Child = extras, VerticalAlignment = VerticalAlignment.Center };+ readouts.Add(() =>+ {+ extras.Text = centreTab switch+ {+ 1 => NotaNum.F($"analysis {Sc(S_Bars):0} bars · {BitCount(ActiveMask())} of 12"),+ 2 => "in: " + MidiSrcName(),+ _ => NotaNum.F($"window {(Sc(S_WindowSec) > 0 ? Sc(S_WindowSec) : 2):0.#} s · {KeyScale()}"),+ };+ });+ static int BitCount(int m) { int c = 0; for (; m != 0; m &= m - 1) c++; return c; }+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => ScaleTab(), 2 => MidiTab(), _ => TraceTab() };+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? DetectTab() : ShiftTab();++ var centre = TabFrame(new[] { "Trace", "Scale", "MIDI" }, centreHost, CentreBody, false, centreTab, t => { centreTab = t; Refresh(); }, extrasHost);+ var rightFrame = TabFrame(new[] { "Shift", "Detect" }, rightHost, RightBody, true, 0, _ => 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>();+ string src = Src() switch { 0 => "auto", 2 => "MIDI", _ => "manual" };+ switch (centreTab)+ {+ case 1:+ parts.Add(KeyScale());+ parts.Add(Sc(S_Learning) > 0.5 ? "learning" : src);+ parts.Add(NotaNum.F($"{BitCount(ActiveMask())} notes"));+ parts.Add(NotaNum.F($"{VoiceName().ToLowerInvariant()} {Note(LowNote())}…{Note(HighNote())}"));+ parts.Add(NotaNum.F($"sens {P(DetSens) * 100:0} %"));+ if (On(SkipSib)) parts.Add("skip sibilants");+ break;+ case 2:+ parts.Add("MIDI");+ parts.Add(MidiSrcName());+ parts.Add(On(MidiMode) ? "scale" : "note");+ if (On(MidiLatch)) parts.Add("latch");+ if (On(MidiOct)) parts.Add("oct lock");+ parts.Add(NotaNum.F($"amount {P(Amount) * 100:0} %"));+ parts.Add(On(MidiBend) ? NotaNum.F($"glide {MsF(GlideMs())} within ±{BendSt():0.#} st") : "steps");+ if (Math.Abs(FormPct()) >= 0.5) parts.Add(NotaNum.F($"formant {FormPct():+0;−0} %"));+ if (!MidiOn()) parts.Add("key source is " + src);+ break;+ default:+ parts.Add(KeyScale());+ parts.Add(src);+ parts.Add(NotaNum.F($"amount {P(Amount) * 100:0} %"));+ parts.Add("speed " + MsF(SpeedMs()));+ parts.Add(NotaNum.F($"range ±{RangeSt():0} st"));+ if (P(Human) >= 0.01f) parts.Add(NotaNum.F($"human {P(Human) * 100:0} %"));+ parts.Add(NotaNum.F($"shift {ShiftSt():+0;−0;0}") + (Math.Abs(FineCt()) >= 0.5 ? NotaNum.F($" {FineCt():+0;−0} ¢") : ""));+ parts.Add(NotaNum.F($"mix {P(Mix) * 100:0} %"));+ break;}- Sync(); ctx.AddDeviceRefresher(Sync);- return col;+ if (On(Follow) && centreTab != 2) parts.Add("follows Nota Scale");+ return string.Join(" · ", parts);}+ readouts.Add(() =>+ {+ statusLeft.Text = StatusText();+ double sr = Sc(S_SampleRate);+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · latency {Sc(S_Latency):0} smp · CPU {Sc(S_Cpu) * 100:0.0} %") : "";+ });+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };+ statusGrid.Children.Add(statusLeft);+ statusGrid.Children.Add(Col(statusRight, 1));+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };+ DockPanel.SetDock(status, Dock.Bottom);- // ============ LIVE strip ============- var detGroup = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { noteBig, centsTb } };- var keySrcSeg = Seg(new[] { "Auto", "Manual", "MIDI in" }, new IBrush?[] { Amber, Amber, TealB }, () => Math.Clamp((int)Math.Round(P(KeySrc) * 2), 0, 2), i => SetP(KeySrc, i / 2f));- MidiLearn.Bind(keySrcSeg, MidiTarget.DeviceParam(track, di, KeySrc), engine.DeviceParamName(track, di, KeySrc));- var liveRight = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right, Children = { Cap("KEY"), keyScaleTb, keySrcSeg } };- var liveLeft = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { detGroup, centsMeter, corrTb } };- 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 } } };-- // ============ key + scale rail (176) ============- var follow = PillToggle("FOLLOW SCALE DEVICE", Follow, TealB);- DockPanel.SetDock(follow, Dock.Bottom);- var keyScaleInner = new DockPanel { LastChildFill = true, Children = { follow,- new StackPanel { Spacing = 5, Children = { Cap("KEY"), KeyGrid(), Cap("SCALE"), ScaleList() } } } };- var keyScalePanel = new Border { Width = 176, Background = Rail, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(8, 6), Child = keyScaleInner };-- // ============ CORRECT / SHIFT rail (182) ============- string Pct(double v) => $"{v * 100:0}\u2009%";- var learnBypass = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4, [DockPanel.DockProperty] = Dock.Bottom, Children = {- RailBtn("Learn key", () => { int ak = AutoKey(Masks[ScaleOf()]); if (ak >= 0) { SetP(Key, ak / 11f); SetP(KeySrc, 0.5f); } }),- } };- var bypassBtn = RailBtn("Bypass", () => { bool b = engine.DeviceBypassed(track, di); engine.SetDeviceBypassed(track, di, !b); ctx.RequestRebuild(); });- Grid.SetColumn(bypassBtn, 1); learnBypass.Children.Add(bypassBtn);- var railTop = new StackPanel { Spacing = 4, Children = {- Cap("CORRECT", TealB),- Slider("Amount", Amount, Pct, TealB),- Slider("Speed", Speed, v => $"{Exp(v, 1, 250):0}\u2009ms", TealB),- Slider("Range", Range, v => $"±{1 + v * 11:0}\u2009st", TealB),- new Border { Height = 1, Background = CardBg, Margin = new Thickness(0, 2) },- Cap("SHIFT"),- Slider("Shift", Shift, v => $"{(v - 0.5) * 24:+0;−0;0}\u2009st", Amber, bipolar: true),- Slider("Formant", Formant, Pct, Amber),- Slider("Mix", Mix, Pct, Amber),- } };- var rail = new Border { Width = 182, Background = Rail, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6),- Child = new DockPanel { LastChildFill = true, Children = { learnBypass, railTop } } };-- // ============ pitch trace (fill) ============- var tracePanel = new Border { Padding = new Thickness(8, 6), Child = viz };-- DockPanel.SetDock(keyScalePanel, Dock.Left); DockPanel.SetDock(rail, Dock.Right);- var body = new DockPanel { LastChildFill = true, Children = { keyScalePanel, rail, tracePanel } };- DockPanel.SetDock(liveStrip, Dock.Top);- Tick();- return new DockPanel { LastChildFill = true, Children = { liveStrip, body } };+ // ---- assemble ---------------------------------------------------------------+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { pitchCol, right, centreBox } };+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };++ void Refresh()+ {+ FollowTick();+ scN = engine.DeviceScope(track, di, scope, kScope);+ int n = scN >= kScope ? Math.Clamp((int)Sc(S_HistN), 0, kHist) : 0;+ string win = NotaNum.F($"{(Sc(S_WindowSec) > 0 ? Sc(S_WindowSec) : 2):0.#} s");+ if (centreTab == 0 && trace is not null) trace.Set(scope, H_Det, H_Out, H_Midi, n, ActiveMask(), Sc(S_TargetMidi), false, win);+ if (centreTab == 1 && histView is not null) histView.Set(scope, PcAt, ActiveMask(), KeyOf());+ if (centreTab == 2 && midiView is not null) midiView.Set(scope, H_Det, H_Out, H_Midi, n, ActiveMask(), Sc(S_TargetMidi), true, win);+ 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, int initial, Action<int>? changed, Control? extrasCtl)+ {+ int sel = initial;+ var btns = new Border[tabs.Length];+ void Hi()+ {+ for (int i = 0; i < tabs.Length; i++)+ {+ bool on = i == sel;+ btns[i].Background = on ? Card2 : Brushes.Transparent;+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;+ var tb = (TextBlock)btns[i].Child!;+ tb.Foreground = on ? AccentBright : TextTertiary;+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ }+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };+ for (int i = 0; i < tabs.Length; i++)+ {+ int iv = i;+ var b = new Border+ {+ Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },+ };+ b.PointerPressed += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };+ btns[i] = b;+ bar.Children.Add(b);+ }+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Dock.Right); barDock.Children.Add(ex); }+ if (!centered) DockPanel.SetDock(bar, Dock.Left);+ barDock.Children.Add(bar);+ var barBorder = new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };+ DockPanel.SetDock(barBorder, Dock.Top);+ Hi();+ host.Content = body(sel);+ return new DockPanel { LastChildFill = true, Children = { barBorder, host } };+ }}}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex e7ab0f1a..944c0898 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -1674,6 +1674,7 @@ internal class RackChainDeviceEngineProxy : System.Reflection.DispatchProxy// track's top-level device at the same index.case nameof(Nota.Application.IAudioEngine.DeviceScope): return 0;case nameof(Nota.Application.IAudioEngine.DeviceLayerWave): return 0;+ case nameof(Nota.Application.IAudioEngine.DeviceAction): return null; // same: it would command the top-level devicecase nameof(Nota.Application.IAudioEngine.DeviceAcceptsSidechain): return false;case nameof(Nota.Application.IAudioEngine.DeviceSidechainSource): return -1;case nameof(Nota.Application.IAudioEngine.DeviceSidechainGain): return 0f;diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex 58bba18c..cdf360b3 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -1470,14 +1470,61 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsFx("autopan", 9, "Random Space", ("Rate", 0.62f), ("Amount", 0.75f), ("Waveform", 1f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 0.85f));Fx("autopan", 9, "Hard Square", ("Rate", 0.66f), ("Amount", 0.85f), ("Waveform", 0f), ("Shape", 0.9f), ("Phase", 0.5f), ("Mix", 1f));- // ---- Nota Auto Shift (kind 10) — all params normalized 0..1. Key 0 C..1 B;- // Scale 0 Chromatic/.25 Major/.5 Minor/.75 Pent Maj/1 Pent Min; Shift 0.5 = 0 st.- Fx("autoshift", 10, "Hard Tune", ("Key", 0f), ("Scale", 0.25f), ("Amount", 1.0f), ("Speed", 0.0f), ("Shift", 0.5f), ("Mix", 1f));- Fx("autoshift", 10, "Natural Vocal", ("Key", 0f), ("Scale", 0.25f), ("Amount", 0.7f), ("Speed", 0.45f), ("Shift", 0.5f), ("Mix", 1f));- Fx("autoshift", 10, "Minor Key", ("Key", 0.818f), ("Scale", 0.5f), ("Amount", 0.9f), ("Speed", 0.2f), ("Shift", 0.5f), ("Mix", 1f));- Fx("autoshift", 10, "Chromatic Fix", ("Key", 0f), ("Scale", 0f), ("Amount", 0.8f), ("Speed", 0.25f), ("Shift", 0.5f), ("Mix", 1f));- Fx("autoshift", 10, "Octave Up", ("Key", 0f), ("Scale", 0.25f), ("Amount", 0.6f), ("Speed", 0.3f), ("Shift", 1.0f), ("Mix", 0.5f));- Fx("autoshift", 10, "Pentatonic Pop", ("Key", 0.583f), ("Scale", 0.75f), ("Amount", 1.0f), ("Speed", 0.1f), ("Shift", 0.5f), ("Mix", 1f));+ // ---- Nota Auto Shift (kind 10) — pitch correction, all params normalized 0..1 (unnamed ones+ // reset to their defaults). Key round(11v) (0 C, .182 D, .364 E, .455 F, .636 G, .818 A);+ // Scale 0 Chromatic/.25 Major/.5 Minor/.75 Penta Maj/1 Penta Min; Custom Scale 1 = the+ // Note C..B toggles are the scale; Speed 2*150^v ms (0 = 2, .1 = 3.3, .2 = 5.4, .3 = 9,+ // .4 = 15, .5 = 25, .6 = 40, .7 = 67); Range 1 + 11v st (.182 = ±3, .364 = ±5, 1 = ±12);+ // Shift (v−.5)·24 st (.208 = −7, .333 = −4, .667 = +4, .792 = +7, 0/1 = ∓12); Fine (v−.5)·200 ¢;+ // Formant 1 = formants preserved (0 = they move with the pitch); Formant Shift (v−.5)·200 %+ // (±100 % = one octave); Det Low / High MIDI 24 + 72v (.167 C2, .222 E2, .292 A2, .333 C3,+ // .389 E3, .458 A3, .556 E4, .625 A4, .722 E5, .833 C6, .889 E6, 1 C7); Key Source 0 Auto /+ // .5 Manual / 1 MIDI (route the MIDI track as the sidechain source); MIDI Mode 0 Note / 1 Scale;+ // MIDI Glide 5*160^v ms (.273 = 20, .49 = 60, .626 = 120); MIDI Bend Range 6v st.+ Fx("autoshift", 10, "Init", ("Key", 0f));+ // Correction+ Fx("autoshift", 10, "Hard Tune", ("Scale", 0.25f), ("Amount", 1f), ("Speed", 0f), ("Formant", 1f));+ Fx("autoshift", 10, "Robot Voice", ("Scale", 0f), ("Amount", 1f), ("Speed", 0f), ("Range", 1f), ("Formant", 1f));+ Fx("autoshift", 10, "Natural Vocal", ("Scale", 0.25f), ("Amount", 0.7f), ("Speed", 0.5f), ("Human", 0.5f), ("Formant", 1f));+ Fx("autoshift", 10, "Transparent Touch", ("Scale", 0.25f), ("Amount", 0.5f), ("Speed", 0.7f), ("Human", 0.8f), ("Range", 0.182f), ("Formant", 1f));+ Fx("autoshift", 10, "Pop Lead", ("Scale", 0.25f), ("Amount", 0.9f), ("Speed", 0.3f), ("Human", 0.25f), ("Formant", 1f), ("Skip Sibilants", 1f));+ Fx("autoshift", 10, "R&B Runs", ("Key", 0.818f), ("Scale", 0.5f), ("Amount", 0.85f), ("Speed", 0.2f), ("Human", 0.35f), ("Range", 0.182f), ("Formant", 1f));+ Fx("autoshift", 10, "Ballad", ("Scale", 0.25f), ("Amount", 0.7f), ("Speed", 0.6f), ("Human", 0.7f), ("Formant", 1f));+ Fx("autoshift", 10, "Rap Hook", ("Key", 0.818f), ("Scale", 0.5f), ("Amount", 1f), ("Speed", 0.1f), ("Human", 0.1f), ("Formant", 1f), ("Skip Sibilants", 1f));+ Fx("autoshift", 10, "Choir Tighten", ("Scale", 0.25f), ("Amount", 0.6f), ("Speed", 0.55f), ("Human", 0.6f), ("Formant", 1f), ("Det Low", 0.333f));+ Fx("autoshift", 10, "Auto Key", ("Key Source", 0f), ("Scale", 0.25f), ("Amount", 0.9f), ("Speed", 0.25f), ("Human", 0.3f), ("Formant", 1f));+ // Scales+ Fx("autoshift", 10, "Chromatic Fix", ("Scale", 0f), ("Amount", 0.8f), ("Speed", 0.25f));+ Fx("autoshift", 10, "Minor Key", ("Key", 0.818f), ("Scale", 0.5f), ("Amount", 0.9f), ("Speed", 0.2f));+ Fx("autoshift", 10, "Pentatonic Pop", ("Key", 0.583f), ("Scale", 0.75f), ("Amount", 1f), ("Speed", 0.1f));+ Fx("autoshift", 10, "Blues in A", ("Key", 0.818f), ("Custom Scale", 1f), ("Note C", 1f), ("Note C#", 0f), ("Note D", 1f), ("Note D#", 1f),+ ("Note E", 1f), ("Note F", 0f), ("Note F#", 0f), ("Note G", 1f), ("Note G#", 0f), ("Note A", 1f), ("Note A#", 0f), ("Note B", 0f),+ ("Amount", 0.85f), ("Speed", 0.3f), ("Human", 0.4f), ("Formant", 1f));+ Fx("autoshift", 10, "Dorian Groove", ("Key", 0.182f), ("Custom Scale", 1f), ("Note C", 1f), ("Note C#", 0f), ("Note D", 1f), ("Note D#", 0f),+ ("Note E", 1f), ("Note F", 1f), ("Note F#", 0f), ("Note G", 1f), ("Note G#", 0f), ("Note A", 1f), ("Note A#", 0f), ("Note B", 1f),+ ("Amount", 0.9f), ("Speed", 0.2f), ("Formant", 1f));+ // Voice types (detection range)+ Fx("autoshift", 10, "Soprano", ("Scale", 0.25f), ("Amount", 0.8f), ("Speed", 0.35f), ("Human", 0.4f), ("Formant", 1f), ("Det Low", 0.458f), ("Det High", 0.889f));+ Fx("autoshift", 10, "Alto", ("Scale", 0.25f), ("Amount", 0.8f), ("Speed", 0.35f), ("Human", 0.4f), ("Formant", 1f), ("Det Low", 0.389f), ("Det High", 0.833f));+ Fx("autoshift", 10, "Tenor", ("Scale", 0.25f), ("Amount", 0.8f), ("Speed", 0.35f), ("Human", 0.4f), ("Formant", 1f), ("Det Low", 0.292f), ("Det High", 0.722f));+ Fx("autoshift", 10, "Bass Voice", ("Scale", 0.25f), ("Amount", 0.8f), ("Speed", 0.4f), ("Human", 0.4f), ("Formant", 1f), ("Det Low", 0.167f), ("Det High", 0.556f));+ Fx("autoshift", 10, "Lead Instrument", ("Scale", 0f), ("Amount", 0.8f), ("Speed", 0.3f), ("Formant", 1f), ("Det Low", 0.056f), ("Det High", 1f), ("Det Sens", 0.6f));+ // Creative+ Fx("autoshift", 10, "Octave Up", ("Scale", 0.25f), ("Amount", 0.6f), ("Speed", 0.3f), ("Shift", 1f), ("Mix", 0.5f));+ Fx("autoshift", 10, "Octave Down", ("Amount", 0f), ("Shift", 0f), ("Formant", 1f));+ Fx("autoshift", 10, "Chipmunk", ("Amount", 0f), ("Shift", 0.792f));+ Fx("autoshift", 10, "Monster", ("Amount", 0f), ("Shift", 0.208f), ("Formant Shift", 0.3f));+ Fx("autoshift", 10, "Gender Up", ("Amount", 0f), ("Shift", 0.667f), ("Formant", 1f), ("Formant Shift", 0.64f));+ Fx("autoshift", 10, "Gender Down", ("Amount", 0f), ("Shift", 0.333f), ("Formant", 1f), ("Formant Shift", 0.36f));+ Fx("autoshift", 10, "Formant Up", ("Amount", 0f), ("Formant", 1f), ("Formant Shift", 0.7f));+ Fx("autoshift", 10, "Detune Double", ("Amount", 0f), ("Fine", 0.45f), ("Formant", 1f), ("Mix", 0.5f));+ Fx("autoshift", 10, "Fifth Harmony", ("Scale", 0.25f), ("Amount", 0.8f), ("Speed", 0.3f), ("Shift", 0.792f), ("Formant", 1f), ("Mix", 0.5f));+ // MIDI target — pick the guide track in the MIDI tab (FROM)+ Fx("autoshift", 10, "Harmony Lock", ("Key Source", 1f), ("MIDI Mode", 0f), ("MIDI Latch", 1f), ("Amount", 0.85f), ("Speed", 0.2f), ("MIDI Glide", 0.49f),+ ("MIDI Bend", 1f), ("MIDI Bend Range", 0.333f), ("Formant", 1f), ("Formant Shift", 0.62f));+ Fx("autoshift", 10, "MIDI Hard Tune", ("Key Source", 1f), ("Amount", 1f), ("Speed", 0f), ("MIDI Bend", 0f), ("Formant", 1f));+ 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.diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.csindex 930be03d..5935cc4a 100644--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs@@ -67,21 +67,21 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));- [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. 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.")]+ [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.")]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). 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. Devices without a command ignore the call.")]public Task DeviceAction(int trackId, int deviceIndex, [Description("Command id — see the device's list in this description")] int id,int intArg = 0, float floatArg = 0) => Mutate(() => E.DeviceAction(trackId, deviceIndex, id, intArg, floatArg));public sealed record Sidechain(bool Accepts, int SourceTrackId, bool TapPre, float GainDb, float Mix);- [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, Nota Shutter and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1).")]+ [McpServerTool(Name = "get_device_sidechain"), Description("Read a device's sidechain routing: whether it can take a key at all (the Compressor, Ceiling, Nota Shutter, Nota Auto Shift — its MIDI source — and plugins with a sidechain bus), the source track id (-1 = the device keys off its own track), whether the source is tapped pre-FX (true) or post-fader (false), the detector gain in dB and the effect's sidechain dry/wet mix (0..1).")]public Task<Sidechain> GetDeviceSidechain(int trackId, int deviceIndex) => Read(() => new Sidechain(E.DeviceAcceptsSidechain(trackId, deviceIndex), E.DeviceSidechainSource(trackId, deviceIndex),E.DeviceSidechainTapPre(trackId, deviceIndex), E.DeviceSidechainGain(trackId, deviceIndex), E.DeviceSidechainMix(trackId, deviceIndex)));- [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). Nota Shutter (kind 19) gates or ducks against a key the same way (Flip = 1 for Duck; Det HP / Det LP shape the key; External Key on, its default). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain.")]+ [McpServerTool(Name = "set_device_sidechain"), Description("Route a sidechain key into a device — e.g. duck a bass or pad under the kick with a Compressor (kind 1): pass the kick track as sourceTrackId, then shape the key with the Compressor's params (SC HP / SC LP / SC Q / SC Gain / Hold; External Key must be on, which is its default). Nota Shutter (kind 19) gates or ducks against a key the same way (Flip = 1 for Duck; Det HP / Det LP shape the key; External Key on, its default). Nota Auto Shift (kind 10) takes an instrument track here as its MIDI source: with Key Source = 1 (MIDI) the voice is pulled to that track's notes (its clips after its MIDI effects, even while muted). sourceTrackId -1 clears the source (the device keys off its own track). Optional: tapPre (true = the source before its effects and fader, false = after), gainDb (extra detector gain, ±24 dB). Leave an optional argument out to keep its current value. No effect on devices that take no sidechain.")]public Task SetDeviceSidechain(int trackId, int deviceIndex, [Description("Key source track id, or -1 for none")] int sourceTrackId,bool? tapPre = null, float? gainDb = null) => Mutate(() =>{@@ -324,6 +324,62 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, IR1(V(15)), R1(V(16)), R1(V(17)), Math.Round(V(7), 2), win, (int)V(8), (int)V(9), (int)V(12), pts.ToArray(), V(10));});+ public sealed record PitchPoint(double Ms, double DetectedMidi, double OutputMidi, double MidiTarget);+ public sealed record KeyGuess(string Key, string Scale, double Match);+ public sealed record AutoShiftReading(string Summary, string Live, string KeySource, bool Voiced, bool Sibilant,+ double DetectedMidi, string DetectedNote, double DetectedCents, double Hz, double Clarity, double TargetMidi, string TargetNote,+ double CorrectionCents, double Ratio, double InputDb, string Scale, string[] ScaleNotes, double InScale, double[] SungPitchClasses,+ double AnalysedSeconds, KeyGuess? Best, KeyGuess? RunnerUp, bool Learning, int MidiSourceTrackId, bool MidiLive, int MidiNote,+ int MidiVelocity, int MidiHeld, int LatencySamples, double WindowSeconds, PitchPoint[] History, double SampleRate);++ [McpServerTool(Name = "read_auto_shift"), Description(+ "Read what a Nota Auto Shift (built-in effect kind 10 — vocal pitch correction) is doing right now: the key source "+ + "(Auto / Manual / MIDI), whether the input is voiced or a sibilant, the detected pitch (fractional MIDI, note name, cents, Hz, "+ + "clarity 0..1), the target note, the correction being applied (cents) and the pitch ratio incl. Shift / Fine, the input level, "+ + "the active scale and its notes (absolute), the share of what was sung that lies in it, the sung pitch-class histogram (C..B, "+ + "max 1, the last ~16 bars) with the seconds it holds, the best and runner-up key (Krumhansl profile match 0..1), whether Learn "+ + "is running, the MIDI source track and the note it holds (Key Source MIDI), the latency, and the last ~2 s of pitch in 16 steps "+ + "(ms before now, detected, output and MIDI-target MIDI note numbers; 0 = none). Pitch moves only while audio plays through the "+ + "track. Use get_device_text id 2 for what each parameter value means, device_action 1 to Learn the key, set_device_sidechain "+ + "to pick the MIDI source.")]+ public Task<AutoShiftReading> ReadAutoShift(int trackId, int deviceIndex) => Read(() =>+ {+ const int tele = 32, hist = 384;+ string[] keys = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ string[] scales = { "Chromatic", "Major", "Minor", "Penta Maj", "Penta Min" };+ var sc = new float[tele + 12 + 3 * hist];+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);+ float V(int i) => n > i ? sc[i] : 0f;+ static double R1(double v) => Math.Round(v, 1);+ string NoteName(double m) => m > 0.5 ? keys[((int)Math.Round(m) % 12 + 12) % 12] + ((int)Math.Round(m) / 12 - 1) : "";+ float P(int i) => E.DeviceGetParam(trackId, deviceIndex, i);+ float ks = P(8);+ string src = ks < 0.25f ? "Auto" : ks < 0.75f ? "Manual" : "MIDI";+ int mask = (int)V(26);+ var notes = new List<string>();+ for (int i = 0; i < 12; i++) if ((mask >> i & 1) != 0) notes.Add(keys[i]);+ string scaleName = P(17) >= 0.5f ? "Custom" : scales[Math.Clamp((int)Math.Round(P(1) * 4), 0, 4)];+ string scale = src == "MIDI" ? "MIDI" : keys[Math.Clamp((int)Math.Round(P(0) * 11), 0, 11)] + " " + scaleName;+ var pcs = new double[12];+ for (int i = 0; i < 12; i++) pcs[i] = Math.Round(V(tele + i), 3);+ KeyGuess? Guess(int k, int s, int m) => V(k) >= 0 && n > k ? new KeyGuess(keys[Math.Clamp((int)V(k), 0, 11)], V(s) > 1.5f ? "Minor" : "Major", Math.Round(V(m), 2)) : null;+ double win = V(24) > 0 ? V(24) : 2;+ var pts = new List<PitchPoint>();+ if (n >= sc.Length)+ for (int k = 0; k < 16; k++)+ {+ int a = k * hist / 16, b = (k + 1) * hist / 16;+ double Avg(int at) { double s = 0; int c = 0; for (int i = a; i < b; i++) if (sc[at + i] > 0) { s += sc[at + i]; c++; } return c > 0 ? R1(s / c) : 0; }+ pts.Add(new PitchPoint(Math.Round((1 - (double)b / hist) * win * 1000), Avg(tele + 12), Avg(tele + 12 + hist), Avg(tele + 12 + 2 * hist)));+ }+ double det = V(0);+ return new AutoShiftReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1), src,+ V(6) > 0.5f, V(7) > 0.5f, Math.Round(det, 2), NoteName(det), det > 0.5 ? Math.Round((det - Math.Round(det)) * 100) : 0, R1(V(5)), Math.Round(V(4), 2),+ Math.Round(V(1), 2), NoteName(V(1)), Math.Round(V(3)), Math.Round(V(28), 4), R1(V(29)), scale, notes.ToArray(), Math.Round(V(22), 2), pcs,+ R1(V(23)), Guess(16, 17, 18), Guess(19, 20, 21), V(15) > 0.5f, E.DeviceSidechainSource(trackId, deviceIndex), V(14) > 0.5f, (int)V(11),+ (int)V(12), (int)V(13), (int)V(10), R1(win), pts.ToArray(), V(8));+ });+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/AutoShift.h b/src/native/nota.engine/src/AutoShift.hindex c55607d3..f41d35b7 100644--- a/src/native/nota.engine/src/AutoShift.h+++ b/src/native/nota.engine/src/AutoShift.h@@ -1,126 +1,262 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Built-in Nota Auto Shift (device kind 10) — a real-time vocal pitch-correction-// insert in the spirit of classic pitch-correction units. Three stages:-// 1. DETECT — an NSDF pitch tracker (McLeod-style: normalized square-difference,-// first peak above 90% of the global max) on the mono sum, run at a-// control-rate hop, with sub-sample parabolic peak refinement. NSDF +-// first-peak picking avoids the octave errors that plague plain-// autocorrelation; the detected note is lightly smoothed.-// 2. SNAP — the (smoothed) pitch is pulled toward the nearest note of the chosen-// Key + Scale by Amount, glided in at the Speed, plus a manual Shift.-// 3. SHIFT — a single-read-pointer granular pitch shifter that crossfades only when-// the read pointer wraps, so it is transparent (no comb) at unity and-// click-free across the whole correction range — no bypass discontinuity.+// Built-in Nota Auto Shift (device kind 10) — a real-time vocal pitch corrector. Stages:+// 1. DETECT — an NSDF pitch tracker (McLeod: normalized square difference, first peak+// above 90% of the global max, parabolic refinement) over the mono sum, run+// every hop. The autocorrelation goes through an FFT, so the window can grow+// to cover low voices; the lag search is limited to the Det Low … Det High+// note range and Det Sens sets the voicing threshold. Unvoiced frames with a+// high zero-crossing rate are flagged as sibilants.+// 2. TARGET — the smoothed pitch (Human blends in a slow note centre, so vibrato is kept+// around the corrected note) is pulled toward the nearest note of the key's+// scale, a Custom 12-note set, or — Key Source MIDI — the notes another+// track is playing (routed through the sidechain source: Note / Scale mode,+// Latch, Oct Lock, Glide within the MIDI Bend range). Amount, Range, Shift+// and Fine finish the target; Speed glides the retune.+// 3. SHIFT — a pitch-synchronous overlap-add (TD-PSOLA) shifter: two-period Hann grains+// taken a whole period apart and laid out at the new period. Each grain is+// resampled by the formant factor, so Formant (preserve 0..1) keeps the+// vocal tract where it was and Formant Shift moves it on its own. At unity+// grains land where they were taken → transparent. Skip Sibilants passes+// sibilants unshifted. The shifted path follows the dry level (a slow level+// match, ±6 dB). The dry path is delayed by the same fixed latency (reported+// for PDC), so Mix never combs.+// Learn: a decaying, duration-weighted histogram of the sung pitch classes (about 16 bars)+// is matched against Krumhansl key profiles; Key Source Auto follows the best key, and+// deviceAction 1 runs a one-shot Learn that commits it.//-// The detected pitch is published two ways for the UI: an instantaneous smoothed value-// via gainReductionDb() (the needle) and a scrolling history ring via scopeRead() (the-// pitch ribbon). Header-only, allocation-free, JUCE-free. Params normalized 0..1 →-// persist / clone / automation flow generically through the base Device.+// scopeRead layout: kTele telemetry floats (S_*), then the 12-bin pitch-class histogram+// (max = 1), then three kHist histories (oldest first): detected pitch, output pitch and+// the MIDI target (MIDI note numbers, 0 = none). gainReductionDb() keeps publishing the+// detected pitch / 127 (the original LIVE feed).+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.+// deviceAction: 0 = reset the analysis (histogram + history), 1 = Learn (iarg 1 start,+// 0 stop and commit, 2 cancel).+// Header-only, allocation-free after setSampleRate. Params normalized 0..1 → persist /+// clone / automation flow generically through the base Device. APPEND ONLY.#pragma once#include "Device.h"+#include "MidiDevice.h"#include <algorithm>+#include <array>#include <atomic>+#include <chrono>#include <cmath>#include <cstdint>+#include <cstdio>+#include <string>namespace nota {class AutoShift : public Device {public:- // Param layout — order is the persisted/automation layout. APPEND ONLY.- // Range clamps the retune so detection octave-errors can't jump; Formant applies a- // shift-linked spectral tilt (formant compensation). KeySource/Follow are UI mode- // flags (the card drives Key/Scale for Auto / Follow-scale-device); the DSP just- // snaps to the current Key + Scale. v2 blob appends 4 floats.- enum { Key = 0, Scale, Amount, Speed, Shift, Mix, Range, Formant, KeySource, Follow, kNumParams };+ // Param layout — order is the persisted/automation layout. APPEND ONLY. 0..9 are the+ // original params (Formant = how much of the formant envelope is preserved 0..1).+ enum {+ Key = 0, Scale, Amount, Speed, Shift, Mix, Range, Formant, KeySource, Follow,+ Human, Fine, FormantShift, DetLow, DetHigh, DetSens, SkipSibilants, CustomScale,+ NoteC, NoteCs, NoteD, NoteDs, NoteE, NoteF, NoteFs, NoteG, NoteGs, NoteA, NoteAs, NoteB,+ MidiMode, MidiLatch, MidiOctLock, MidiGlide, MidiBendRange, MidiBend,+ kNumParams+ };++ // Telemetry block (scopeRead, first kTele floats).+ enum {+ S_DetMidi = 0, // smoothed detected pitch (MIDI, fractional), 0 = unvoiced+ S_TargetMidi, // target note (MIDI, may glide), 0 = none+ S_OutMidi, // output pitch now (detected + the applied shift), 0 = unvoiced+ S_CorrCents, // correction being applied now, cents (excl. Shift / Fine)+ S_Conf, // detector clarity 0..1+ S_Hz, // detected frequency+ S_Voiced, // 1 = pitched+ S_Sibilant, // 1 = an unvoiced, noisy frame (sibilant)+ S_SampleRate,+ S_Cpu, // share of real time spent in process()+ S_Latency, // samples+ S_MidiNote, // MIDI target note (before octave / glide), -1 = none+ S_MidiVel, // its velocity 0..127+ S_MidiHeld, // notes held on the source now+ S_MidiLive, // 1 = a MIDI source fed this device in the last block+ S_Learning, // 1 = a one-shot Learn is running+ S_LearnKey, // best key 0..11 (-1 = not enough singing yet)+ S_LearnScale, // its scale: 1 Major, 2 Minor+ S_LearnMatch, // its profile correlation 0..1+ S_Learn2Key, // runner-up+ S_Learn2Scale,+ S_Learn2Match,+ S_InScale, // share of the sung notes that lie in the active scale 0..1+ S_AnalysisSec, // seconds of voiced singing the histogram holds (effective)+ S_WindowSec, // history span, seconds+ S_HistN, // points per history+ S_Mask, // active 12-bit pitch-class mask (absolute, C = bit 0)+ S_Key, // active key 0..11+ S_Ratio, // pitch ratio now+ S_InDb, // input level (detector window RMS), dBFS+ S_Bars, // analysis length, bars+ S_MidiMask, // pitch classes held on the MIDI source (absolute)+ kTele = 32+ };+ static constexpr int kHist = 384;+ static constexpr int kScope = kTele + 12 + 3 * kHist;+ enum { A_ResetAnalysis = 0, A_Learn = 1 };AutoShift() {- p_[Key].store(0.0f); // C- p_[Scale].store(0.25f); // Major (0..4 in .25 steps)- p_[Amount].store(1.0f); // full correction- p_[Speed].store(0.15f); // fairly fast retune- p_[Shift].store(0.5f); // no manual transpose+ p_[Key].store(0.0f); // C+ p_[Scale].store(0.25f); // Major (0..4 in .25 steps)+ p_[Amount].store(1.0f); // full correction+ p_[Speed].store(0.15f); // fairly fast retune+ p_[Shift].store(0.5f); // no manual transposep_[Mix].store(1.0f);- p_[Range].store(0.3636f); // ±5 st correction range (1 + v*11)- p_[Formant].store(0.0f); // no formant compensation- p_[KeySource].store(0.5f); // Manual (0 Auto / 0.5 Manual / 1 MIDI)- p_[Follow].store(0.0f); // don't follow a scale device+ p_[Range].store(0.3636f); // ±5 st correction range (1 + v*11)+ p_[Formant].store(0.0f); // formants move with the pitch (the original shifter)+ p_[KeySource].store(0.5f); // Manual (0 Auto / 0.5 Manual / 1 MIDI)+ p_[Follow].store(0.0f); // don't follow a scale device+ p_[Human].store(0.0f); // hard correction+ p_[Fine].store(0.5f); // 0 cents+ p_[FormantShift].store(0.5f); // no formant shift+ p_[DetLow].store(12.0f / 72.0f); // C2 (24 + 72v)+ p_[DetHigh].store(60.0f / 72.0f); // C6+ p_[DetSens].store(0.7f); // voicing threshold 0.5 (the original)+ p_[SkipSibilants].store(0.0f);+ p_[CustomScale].store(0.0f);+ for (int i = 0; i < 12; ++i) p_[NoteC + i].store((kScaleMask[1] >> i) & 1 ? 1.0f : 0.0f); // C major+ p_[MidiMode].store(0.0f); // Note+ p_[MidiLatch].store(1.0f);+ p_[MidiOctLock].store(0.0f);+ p_[MidiGlide].store(0.49f); // ~60 ms+ p_[MidiBendRange].store(1.0f / 3.0f); // ±2 st (6v)+ p_[MidiBend].store(1.0f);+ setSampleRate(44100.0, 0);}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;- for (int i = 0; i < kBuf; ++i) det_[i] = 0.0f;- for (int i = 0; i < kHist; ++i) { histDet_[i] = 0.0f; histCorr_[i] = 0.0f; }- rw_ = 0; hop_ = 0; histW_ = 0;- d_ = kFade + kGrain * 0.5; fadeD_ = 0.0; fadeCnt_ = 0;- curRatio_ = 1.0; targetRatio_ = 1.0; smMidi_ = 60.0; havePitch_ = false;- lpF_[0] = lpF_[1] = 0.0;- lpCoef_ = 1.0 - std::exp(-2.0 * kPi * 900.0 / sr_); // formant-tilt split ≈ 900 Hz- minLag_ = std::max(2, (int)(sr_ / 1000.0));- maxLag_ = std::min(kWin - 2, (int)(sr_ / 70.0));+ lat_ = std::clamp((int)std::lround(sr_ * 0.016), 64, kBuf / 4);+ hop_ = sr_ >= 88200.0 ? 512 : 256;+ baseWin_ = sr_ >= 88200.0 ? 2048 : 1024;+ for (int k = 0; k < kFftMax / 2; ++k) {+ twC_[(size_t)k] = (float)std::cos(-2.0 * kPi * k / kFftMax);+ twS_[(size_t)k] = (float)std::sin(-2.0 * kPi * k / kFftMax);+ }+ lvlA_ = 1.0 - std::exp(-1.0 / (0.08 * sr_));+ lvlB_ = 1.0 - std::exp(-1.0 / (0.05 * sr_));+ srA_.store((float)sr_, std::memory_order_relaxed);+ resetState();+ }++ int32_t latencySamples() const override { return lat_; }++ // The MIDI source rides on the sidechain source slot: pick an instrument track and the+ // engine hands this device that track's notes each block (setMidiKey).+ int32_t sidechainSourceTrackId() const override { return srcTrack_.load(std::memory_order_relaxed); }+ void setSidechainSourceTrackId(int32_t id) override { srcTrack_.store(id, std::memory_order_relaxed); }+ void setSidechain(const float*, int32_t) override {}+ bool acceptsSidechain() const override { return true; }+ bool wantsMidiKey() const override { return true; }+ void setMidiKey(const MidiEv* evs, int32_t n) override { midiEvs_ = evs; midiN_ = n; midiFed_ = true; }++ void setTransportInfo(const TransportInfo& ti) override {+ if (ti.bpm > 1.0) bpm_ = ti.bpm;+ if (ti.tsNum > 0) tsNum_ = ti.tsNum;}- // Instantaneous smoothed detected pitch (MIDI/127), 0 = unvoiced — the LIVE readout.+ // Instantaneous smoothed detected pitch (MIDI/127), 0 = unvoiced — the original LIVE feed.float gainReductionDb() const override { return pitchPub_.load(std::memory_order_relaxed); }- // Scrolling pitch history, oldest→newest, interleaved [detected/127, corrected/127]- // (0 = unvoiced) — the two-trace pitch plot.- int32_t scopeRead(float* out, int32_t maxSamples) const override {- if (!out || maxSamples <= 0) return 0;- const int pairs = std::min(maxSamples / 2, kHist);- const int w = histW_.load(std::memory_order_relaxed);- const int start = (w - pairs) & (kHist - 1);- for (int k = 0; k < pairs; ++k) {- const int idx = (start + k) & (kHist - 1);- out[2 * k] = histDet_[idx];- out[2 * k + 1] = histCorr_[idx];- }- return pairs * 2;+ void deviceAction(int32_t id, int32_t iarg, float) override {+ if (id == A_ResetAnalysis) resetReq_.store(true, std::memory_order_relaxed);+ else if (id == A_Learn) learnReq_.store(iarg == 1 ? 1 : iarg == 2 ? 3 : 2, std::memory_order_relaxed); // 1 start, 2 commit, 3 cancel}void process(float* buf, int32_t frames) override {- const int key = std::clamp((int)std::lround(get(Key) * 11.0f), 0, 11);- const uint16_t mask = kScaleMask[std::clamp((int)std::lround(get(Scale) * 4.0f), 0, 4)];- const float amount = std::clamp(get(Amount), 0.0f, 1.0f);- const double shiftSt = ((double)get(Shift) - 0.5) * 24.0; // ±12 st- const float mix = std::clamp(get(Mix), 0.0f, 1.0f);- const double rangeSt = 1.0 + (double)std::clamp(get(Range), 0.0f, 1.0f) * 11.0; // 1..12 st- const float formant = std::clamp(get(Formant), 0.0f, 1.0f);- const double tau = expMap(get(Speed), 0.002, 0.30); // retune glide time (s)+ const auto t0 = std::chrono::steady_clock::now();+ if (resetReq_.exchange(false, std::memory_order_relaxed)) resetAnalysis();+ switch (learnReq_.exchange(0, std::memory_order_relaxed)) {+ case 1: resetAnalysis(); learning_ = true; break;+ case 2: if (learning_) commitLearn(); learning_ = false; break;+ case 3: learning_ = false; break;+ default: break;+ }+ takeMidi();++ const float mix = std::clamp(get(Mix), 0.0f, 1.0f);+ const double tau = expMap(get(Speed), 0.002, 0.30); // retune glide (s)const double smooth = 1.0 - std::exp(-1.0 / (tau * sr_));+ const double pres = std::clamp((double)get(Formant), 0.0, 1.0);+ const double fsh = std::pow(2.0, ((double)get(FormantShift) - 0.5) * 2.0); // ±1 octavefor (int32_t i = 0; i < frames; ++i) {- const float dryL = buf[i * 2], dryR = buf[i * 2 + 1];- det_[rw_] = 0.5f * (dryL + dryR);- ring_[0][rw_] = dryL; ring_[1][rw_] = dryR;-- if (++hop_ >= kHop) { hop_ = 0; detect(key, mask, amount, shiftSt, rangeSt); }-- curRatio_ += (targetRatio_ - curRatio_) * smooth; // glide- grainStep(curRatio_);- float wetL = grainOut(0), wetR = grainOut(1);-- // Formant compensation: a shift-linked spectral tilt. Shifting up brightens the- // formants; boosting lows / cutting highs by the same octave count pushes them- // back toward the original envelope (and the inverse when shifting down).- if (formant > 0.001f) {- const double tilt = std::clamp((double)formant * std::log2(std::max(1e-6, curRatio_)) * 0.6, -0.85, 0.85);- lpF_[0] += lpCoef_ * (wetL - lpF_[0]); const float loL = (float)lpF_[0], hiL = wetL - loL;- lpF_[1] += lpCoef_ * (wetR - lpF_[1]); const float loR = (float)lpF_[1], hiR = wetR - loR;- wetL = (float)(loL * (1.0 + tilt) + hiL * (1.0 - tilt));- wetR = (float)(loR * (1.0 + tilt) + hiR * (1.0 - tilt));+ const float inL = buf[i * 2], inR = buf[i * 2 + 1];+ const int w = (int)(n_ & kMask);+ ring_[0][(size_t)w] = inL; ring_[1][(size_t)w] = inR;+ det_[(size_t)w] = 0.5f * (inL + inR);+ ++n_;+ if (++hopCnt_ >= hop_) { hopCnt_ = 0; detect(); }++ const int64_t to = n_ - 1 - lat_; // the sample leaving now (input time)+ const Rec& rc = recAt(to);+ curSemi_ += (rc.semi - curSemi_) * smooth;++ // Lay out every grain whose first sample is due.+ for (int guard = 0; guard < 8; ++guard) {+ const double r = rc.sib ? 1.0 : std::pow(2.0, curSemi_ / 12.0);+ const double fr = rc.sib ? 1.0 : std::clamp(std::pow(r, 1.0 - pres) * fsh, 0.5, 2.0);+ pg_ = std::clamp(rc.period, pg_ * 0.97, pg_ * 1.03);+ const double halfOut = pg_ / fr;+ if (ns_ < (double)to - halfOut) ns_ = (double)to + halfOut * 0.5; // lost sync (start / reset)+ if (ns_ - halfOut > (double)to + 1.0) break;+ grain(ns_, pg_, r, fr, rc.sib, to);+ ns_ += pg_ / r;}- rw_ = (rw_ + 1) & (kBuf - 1);+ const int o = (int)(to & kMask);+ float wetL = acc_[0][(size_t)o], wetR = acc_[1][(size_t)o];+ acc_[0][(size_t)o] = 0.0f; acc_[1][(size_t)o] = 0.0f;+ const float dryL = to >= 0 ? ring_[0][(size_t)o] : 0.0f, dryR = to >= 0 ? ring_[1][(size_t)o] : 0.0f;+ // Level match: re-spaced grains add up louder or softer than the source depending on+ // the ratio and the waveform, so the shifted path follows the (aligned) dry level —+ // slowly (~80 ms), within ±6 dB, held through silence. At unity it stays at 1.+ eDry_ += ((double)dryL * dryL + (double)dryR * dryR - eDry_) * lvlA_;+ eWet_ += ((double)wetL * wetL + (double)wetR * wetR - eWet_) * lvlA_;+ if (eDry_ > 1e-9) gAuto_ += (std::clamp(std::sqrt(eDry_ / std::max(eWet_, 1e-12)), 0.5, 2.0) - gAuto_) * lvlB_;+ wetL *= (float)gAuto_; wetR *= (float)gAuto_;buf[i * 2] = dryL * (1.0f - mix) + wetL * mix;buf[i * 2 + 1] = dryR * (1.0f - mix) + wetR * mix;}+ ratioA_.store((float)std::pow(2.0, curSemi_ / 12.0), std::memory_order_relaxed);+ midiEvs_ = nullptr; midiN_ = 0;+ midiLiveA_.store(midiFed_ ? 1.0f : 0.0f, std::memory_order_relaxed);+ midiFed_ = false;+ 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, the pitch-class histogram, then the three histories (oldest first).+ int32_t scopeRead(float* out, int32_t maxSamples) const override {+ if (!out || maxSamples <= 0) return 0;+ float t[kTele] = {};+ for (int k = 0; k < kTele; ++k) t[k] = tele_[(size_t)k].load(std::memory_order_relaxed);+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);+ t[S_Latency] = (float)lat_;+ t[S_MidiLive] = midiLiveA_.load(std::memory_order_relaxed);+ t[S_Ratio] = ratioA_.load(std::memory_order_relaxed);+ t[S_HistN] = (float)kHist;+ t[S_WindowSec] = (float)(kHist * hop_ / sr_);+ int32_t n = 0;+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];+ for (int k = 0; k < 12 && n < maxSamples; ++k) out[n++] = pcPub_[(size_t)k].load(std::memory_order_relaxed);+ const int hw = histW_.load(std::memory_order_acquire);+ for (int s = 0; s < 3; ++s)+ for (int k = 0; k < kHist && n < maxSamples; ++k) out[n++] = hist_[(size_t)s][(size_t)((hw + k) % kHist)];+ return n;}const char* displayName() const override { return "Nota Auto Shift"; }@@ -128,12 +264,12 @@ public:int32_t paramCount() const override { return kNumParams; }const char* paramName(int32_t i) const override {- switch (i) {- case Key: return "Key"; case Scale: return "Scale"; case Amount: return "Amount";- case Speed: return "Speed"; case Shift: return "Shift"; case Mix: return "Mix";- case Range: return "Range"; case Formant: return "Formant"; case KeySource: return "Key Source";- case Follow: return "Follow Scale"; default: return "";- }+ static const char* nm[kNumParams] = {+ "Key", "Scale", "Amount", "Speed", "Shift", "Mix", "Range", "Formant", "Key Source", "Follow Scale",+ "Human", "Fine", "Formant Shift", "Det Low", "Det High", "Det Sens", "Skip Sibilants", "Custom Scale",+ "Note C", "Note C#", "Note D", "Note D#", "Note E", "Note F", "Note F#", "Note G", "Note G#", "Note A", "Note A#", "Note B",+ "MIDI Mode", "MIDI Latch", "MIDI Oct Lock", "MIDI Glide", "MIDI Bend Range", "MIDI Bend" };+ 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; }@@ -144,132 +280,528 @@ public:if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);}+ std::string deviceText(int32_t id) const override {+ static const char* keys[12] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ static const char* scales[5] = { "Chromatic", "Major", "Minor", "Penta Maj", "Penta Min" };+ static const char* srcs[3] = { "auto", "manual", "MIDI" };+ char b[768];+ float t[kTele];+ scopeRead(t, kTele);+ if (id == 0) {+ const int src = keySrc();+ std::string s;+ if (src == 2) {+ std::snprintf(b, sizeof b, "MIDI target - %s%s%s - glide %.0f ms%s",+ get(MidiMode) >= 0.5f ? "scale" : "note", get(MidiLatch) >= 0.5f ? " - latch" : "",+ get(MidiOctLock) >= 0.5f ? " - oct lock" : "", expMap(get(MidiGlide), 5.0, 800.0),+ get(MidiBend) >= 0.5f ? (" - bends within " + stText(get(MidiBendRange) * 6.0)).c_str() : " - steps");+ s = b;+ s += sidechainSourceTrackId() >= 0 ? " - source routed" : " - no MIDI source";+ } else {+ s = std::string(keys[keyIdx()]) + " " + (get(CustomScale) >= 0.5f ? "Custom" : scales[scaleIdx()]) + " - " + srcs[src];+ }+ std::snprintf(b, sizeof b, " - amount %.0f %% - speed %.0f ms - range ±%.0f st - human %.0f %%",+ get(Amount) * 100.0f, expMap(get(Speed), 2.0, 300.0), 1.0 + get(Range) * 11.0, get(Human) * 100.0f);+ s += b;+ std::snprintf(b, sizeof b, " - shift %+.0f st %+.0f ct - formant %s, shift %+.0f %% - mix %.0f %%",+ ((double)get(Shift) - 0.5) * 24.0, ((double)get(Fine) - 0.5) * 200.0,+ get(Formant) >= 0.5f ? "preserved" : "moves", ((double)get(FormantShift) - 0.5) * 200.0, get(Mix) * 100.0f);+ s += b;+ std::snprintf(b, sizeof b, " - detect %s..%s sens %.0f %%", noteText(detLowMidi()).c_str(), noteText(detHighMidi()).c_str(), get(DetSens) * 100.0f);+ s += b;+ if (get(SkipSibilants) >= 0.5f) s += " - skip sibilants";+ if (get(Follow) >= 0.5f) s += " - follows a Nota Scale";+ return s;+ }+ if (id == 1) {+ std::string s;+ if (t[S_Voiced] > 0.5f) {+ std::snprintf(b, sizeof b, "voiced - %s %+.0f ct (%.1f Hz, clarity %.0f %%)", noteText((int)std::lround(t[S_DetMidi])).c_str(),+ (t[S_DetMidi] - std::round(t[S_DetMidi])) * 100.0f, t[S_Hz], t[S_Conf] * 100.0f);+ s = b;+ if (t[S_TargetMidi] > 0.5f) {+ std::snprintf(b, sizeof b, " - target %s - correcting %+.0f ct", noteText((int)std::lround(t[S_TargetMidi])).c_str(), t[S_CorrCents]);+ s += b;+ } else s += " - no target";+ } else s = t[S_Sibilant] > 0.5f ? "sibilant" : "unvoiced";+ std::snprintf(b, sizeof b, " - ratio %.3f - in %.1f dB", t[S_Ratio], t[S_InDb]);+ s += b;+ if (t[S_MidiLive] > 0.5f || keySrc() == 2) {+ if (t[S_MidiNote] >= 0.0f) std::snprintf(b, sizeof b, " - MIDI %s vel %.0f (%.0f held)", noteText((int)t[S_MidiNote]).c_str(), t[S_MidiVel], t[S_MidiHeld]);+ else std::snprintf(b, sizeof b, " - MIDI none held");+ s += b;+ }+ std::snprintf(b, sizeof b, " - %.0f %% in scale over %.1f s", t[S_InScale] * 100.0f, t[S_AnalysisSec]);+ s += b;+ if (t[S_LearnKey] >= 0.0f) {+ std::snprintf(b, sizeof b, " - best %s %s %.0f %%, next %s %s %.0f %%", keys[(int)t[S_LearnKey] % 12], t[S_LearnScale] > 1.5f ? "Minor" : "Major",+ t[S_LearnMatch] * 100.0f, keys[(int)t[S_Learn2Key] % 12], t[S_Learn2Scale] > 1.5f ? "Minor" : "Major", t[S_Learn2Match] * 100.0f);+ s += b;+ }+ if (t[S_Learning] > 0.5f) s += " - LEARNING";+ std::snprintf(b, sizeof b, " - latency %d smp", lat_);+ s += b;+ return s;+ }+ if (id == 2) {+ return "All params 0..1. Key: round(v*11) = C..B. Scale: 0 Chromatic, .25 Major, .5 Minor, .75 Penta Maj, 1 Penta Min. "+ "Custom Scale on: the Note C..Note B toggles (absolute pitch classes) are the scale. Amount 0..100 %. "+ "Speed 2*150^v ms retune glide (0 = hard tune). Range: 1 + 11v semitones, the largest correction. "+ "Human: keeps vibrato and drift around the corrected note (0 = flat). Shift: (v-0.5)*24 st. Fine: (v-0.5)*200 cents. "+ "Formant: how much of the formant envelope is preserved while shifting (1 = natural). Formant Shift: (v-0.5)*200 %, "+ "±100 % = one octave. Mix 0..100 %. Key Source: 0 Auto (follows the sung key), 0.5 Manual, 1 MIDI (the notes of "+ "the track routed as the sidechain source are the target). Follow Scale: the card copies a Nota Scale's key and scale. "+ "Det Low / Det High: detection range, MIDI 24 + 72v (C1..C7). Det Sens: voicing sensitivity. Skip Sibilants: "+ "unvoiced noisy frames pass unshifted. MIDI Mode: 0 Note (the last held note), 1 Scale (held notes form the scale). "+ "MIDI Latch: keep the target between notes. MIDI Oct Lock: the note's own octave (off = the octave nearest the voice). "+ "MIDI Glide: 5*160^v ms. MIDI Bend: moves between notes glide when within MIDI Bend Range (6v st); wider leaps jump. "+ "Toggles: >= 0.5 = on.";+ }+ return {};+ }+private:static constexpr double kPi = 3.14159265358979323846;- static constexpr double kHalfPi = 1.5707963267948966;- static constexpr int kBuf = 4096; // audio ring (power of two)- static constexpr int kWin = 1024; // analysis window- static constexpr int kHop = 256; // detection hop- static constexpr int kGrain = 1024; // granular grain length- static constexpr int kFade = 256; // granular crossfade length- static constexpr int kHist = 512; // pitch-history ring (~3 s) for the UI plot- // Scale masks (bit i set = semitone i above the key is in-scale):- // Chromatic / Major / Minor / Pentatonic Major / Pentatonic Minor.+ static constexpr int kBuf = 16384; // audio / output ring (power of two)+ static constexpr int64_t kMask = kBuf - 1;+ static constexpr int kWinMax = 4096; // largest analysis window+ static constexpr int kFftMax = 2 * kWinMax;+ static constexpr int kRec = 64; // per-hop decisions, timestamped+ // Chromatic / Major / Minor / Pentatonic Major / Pentatonic Minor (bit i = i semitones above the key).static constexpr uint16_t kScaleMask[5] = { 0x0FFF, 0x0AB5, 0x05AD, 0x0295, 0x04A9 };+ // Krumhansl–Kessler key profiles.+ static constexpr double kMajProf[12] = { 6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88 };+ static constexpr double kMinProf[12] = { 6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17 };++ struct Rec { int64_t at = 0; double semi = 0.0; double period = 200.0; bool sib = false; };float get(int i) const { return p_[i].load(std::memory_order_relaxed); }static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }+ int keyIdx() const { return std::clamp((int)std::lround(get(Key) * 11.0f), 0, 11); }+ int scaleIdx() const { return std::clamp((int)std::lround(get(Scale) * 4.0f), 0, 4); }+ int keySrc() const { const float v = get(KeySource); return v < 0.25f ? 0 : v < 0.75f ? 1 : 2; }+ int detLowMidi() const { return 24 + (int)std::lround(get(DetLow) * 72.0f); }+ int detHighMidi() const { return 24 + (int)std::lround(get(DetHigh) * 72.0f); }+ static uint16_t rot(uint16_t m, int key) { key = ((key % 12) + 12) % 12; return (uint16_t)(((m << key) | (m >> (12 - key))) & 0x0FFF); }+ uint16_t scaleMask() const {+ if (get(CustomScale) >= 0.5f) {+ uint16_t m = 0;+ for (int i = 0; i < 12; ++i) if (get(NoteC + i) >= 0.5f) m |= (uint16_t)(1u << i);+ return m;+ }+ return rot(kScaleMask[scaleIdx()], keyIdx());+ }+ static std::string noteText(int m) {+ static const char* nn[12] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ return std::string(nn[((m % 12) + 12) % 12]) + std::to_string(m / 12 - 1);+ }+ static std::string stText(double st) { char b[24]; std::snprintf(b, sizeof b, "%.1f st", st); return b; }- // Nearest in-scale note to a continuous MIDI pitch (prefers the closer side).- static double snapMidi(double m, int key, uint16_t mask) {+ // Nearest note whose pitch class is in `mask` (absolute); ties go to the closer side.+ static double snapMask(double m, uint16_t mask) {+ if (!mask) return -1.0;const int base = (int)std::lround(m);- for (int d = 0; d <= 6; ++d)- for (int s = (d == 0 ? 0 : d), step = 0; step < (d == 0 ? 1 : 2); ++step, s = -d) {- const int note = base + s;- const int pc = ((note - key) % 12 + 12) % 12;- if (mask & (uint16_t)(1u << pc)) return (double)note;+ int best = base; double bd = 1e9;+ for (int d = -6; d <= 6; ++d) {+ const int note = base + d;+ if (!(mask & (uint16_t)(1u << (((note % 12) + 12) % 12)))) continue;+ const double dist = std::fabs(note - m);+ if (dist < bd) { bd = dist; best = note; }+ }+ return bd < 1e8 ? (double)best : -1.0;+ }++ void resetAnalysis() {+ pcw_.fill(0.0); totalW_ = 0.0; hopsSinceKey_ = 0;+ for (auto& h : hist_) h.fill(0.0f);+ for (auto& p : pcPub_) p.store(0.0f, std::memory_order_relaxed);+ tele_[S_LearnKey].store(-1.0f, std::memory_order_relaxed);+ tele_[S_Learn2Key].store(-1.0f, std::memory_order_relaxed);+ tele_[S_AnalysisSec].store(0.0f, std::memory_order_relaxed);+ }++ void resetState() {+ for (auto& r : ring_) r.fill(0.0f);+ for (auto& a : acc_) a.fill(0.0f);+ det_.fill(0.0f);+ n_ = 0; hopCnt_ = 0;+ const double pu = sr_ * 0.005;+ for (auto& r : rec_) r = Rec{ 0, 0.0, pu, false };+ recW_ = 0;+ pg_ = pu; ns_ = 0.0; la_ = 0.0; lastP_ = 0.0; curSemi_ = 0.0;+ eDry_ = eWet_ = 0.0; gAuto_ = 1.0;+ sm_ = center_ = 60.0; have_ = false; midiT_ = -1.0;+ held_.fill(0); order_.fill(-1); orderN_ = 0; lastNote_ = -1; lastVel_ = 0; latchMask_ = 0;+ histW_.store(0, std::memory_order_relaxed);+ for (auto& t : tele_) t.store(0.0f, std::memory_order_relaxed);+ tele_[S_MidiNote].store(-1.0f, std::memory_order_relaxed);+ tele_[S_InDb].store(-120.0f, std::memory_order_relaxed);+ tele_[S_Bars].store(16.0f, std::memory_order_relaxed);+ resetAnalysis();+ learning_ = false;+ pitchPub_.store(0.0f, std::memory_order_relaxed);+ }++ // The decision in force for input time `t`: the latest record stamped at or before it.+ const Rec& recAt(int64_t t) const {+ for (int k = 0; k < kRec; ++k) {+ const Rec& r = rec_[(size_t)((recW_ - 1 - k + kRec) % kRec)];+ if (r.at <= t) return r;+ }+ return rec_[(size_t)(recW_ % kRec)];+ }++ // --- MIDI target ------------------------------------------------------------+ void takeMidi() {+ if (!midiEvs_) return;+ for (int32_t k = 0; k < midiN_; ++k) {+ const MidiEv& e = midiEvs_[k];+ if (e.pitch < 0 || e.pitch > 127) continue;+ if (e.on && e.vel > 0.0f) {+ held_[(size_t)e.pitch] = (uint8_t)std::clamp((int)std::lround(e.vel * 127.0f), 1, 127);+ dropOrder(e.pitch);+ if (orderN_ < (int)order_.size()) order_[(size_t)orderN_++] = e.pitch;+ lastNote_ = e.pitch; lastVel_ = held_[(size_t)e.pitch];+ } else {+ held_[(size_t)e.pitch] = 0;+ dropOrder(e.pitch);}- return m;+ }+ uint16_t m = 0;+ for (int k = 0; k < orderN_; ++k) m |= (uint16_t)(1u << (order_[(size_t)k] % 12));+ if (m) latchMask_ = m;+ }+ void dropOrder(int p) {+ int w = 0;+ for (int k = 0; k < orderN_; ++k) if (order_[(size_t)k] != p) order_[(size_t)w++] = order_[(size_t)k];+ orderN_ = w;}- // NSDF pitch tracker over the most recent window; updates targetRatio_ + UI feeds.- void detect(int key, uint16_t mask, float amount, double shiftSt, double rangeSt) {- for (int i = 0; i < kWin; ++i) win_[i] = det_[(rw_ - kWin + i) & (kBuf - 1)];- double pe[kWin + 1]; pe[0] = 0.0;- for (int i = 0; i < kWin; ++i) pe[i + 1] = pe[i] + (double)win_[i] * win_[i];-- double globalMax = 0.0;- for (int lag = minLag_; lag <= maxLag_; ++lag) {- double r = 0.0;- for (int i = 0; i < kWin - lag; ++i) r += (double)win_[i] * win_[i + lag];- const double m = pe[kWin - lag] + (pe[kWin] - pe[lag]); // Σx[i]² + Σx[i+lag]²- const double nsdf = m > 1e-9 ? 2.0 * r / m : 0.0;- nsdf_[lag] = (float)nsdf;- if (nsdf > globalMax) globalMax = nsdf;+ // --- FFT (radix-2, in place) ----------------------------------------------------+ void fft(int n, bool inverse) {+ for (int i = 1, j = 0; i < n; ++i) {+ int bit = n >> 1;+ for (; j & bit; bit >>= 1) j ^= bit;+ j ^= bit;+ if (i < j) { std::swap(re_[(size_t)i], re_[(size_t)j]); std::swap(im_[(size_t)i], im_[(size_t)j]); }+ }+ for (int len = 2; len <= n; len <<= 1) {+ const int step = kFftMax / len;+ for (int i = 0; i < n; i += len)+ for (int k = 0; k < len / 2; ++k) {+ const float wr = twC_[(size_t)(k * step)], wi = inverse ? -twS_[(size_t)(k * step)] : twS_[(size_t)(k * step)];+ const size_t a = (size_t)(i + k), b2 = (size_t)(i + k + len / 2);+ const float xr = re_[b2] * wr - im_[b2] * wi, xi = re_[b2] * wi + im_[b2] * wr;+ re_[b2] = re_[a] - xr; im_[b2] = im_[a] - xi;+ re_[a] += xr; im_[a] += xi;+ }}+ }- // First local maximum above 90% of the global peak → the true period (avoids- // choosing a stronger sub-octave peak at 2× the lag).- int bestLag = 0;- if (globalMax > 0.0) {- const double thr = 0.90 * globalMax;- for (int lag = minLag_ + 1; lag < maxLag_; ++lag)- if (nsdf_[lag] > thr && nsdf_[lag] >= nsdf_[lag - 1] && nsdf_[lag] >= nsdf_[lag + 1]) { bestLag = lag; break; }+ // --- detection + target (every hop) -----------------------------------------------+ void detect() {+ const double hopSec = hop_ / sr_;+ const int lo = std::min(detLowMidi(), detHighMidi() - 1), hi = std::max(detHighMidi(), lo + 1);+ const double fLo = 440.0 * std::pow(2.0, (lo - 69) / 12.0), fHi = 440.0 * std::pow(2.0, (hi - 69) / 12.0);+ const int maxLag = std::clamp((int)std::ceil(sr_ / fLo) + 1, 8, kWinMax / 2 - 2);+ const int minLag = std::clamp((int)std::floor(sr_ / fHi) - 1, 2, maxLag - 4);+ int win = baseWin_;+ while (win < 2 * maxLag && win < kWinMax) win <<= 1;+ const int nfft = 2 * win;++ double e = 0.0; int zc = 0; float prev = 0.0f;+ for (int i = 0; i < win; ++i) {+ const float x = det_[(size_t)((n_ - win + i) & kMask)];+ re_[(size_t)i] = x; im_[(size_t)i] = 0.0f;+ e += (double)x * x;+ if (i > 0 && ((x >= 0.0f) != (prev >= 0.0f))) ++zc;+ prev = x;}+ for (int i = win; i < nfft; ++i) { re_[(size_t)i] = 0.0f; im_[(size_t)i] = 0.0f; }+ const double rms = std::sqrt(e / win);+ const float inDb = rms > 1e-6 ? (float)(20.0 * std::log10(rms)) : -120.0f;+ const double zcrHz = zc * 0.5 * sr_ / win;+ const bool loud = inDb > -60.0f;- if (globalMax > 0.5 && bestLag > 0) {+ double globalMax = 0.0; int bestLag = 0; double clarity = 0.0;+ if (loud) {+ fft(nfft, false);+ for (int i = 0; i < nfft; ++i) { re_[(size_t)i] = re_[(size_t)i] * re_[(size_t)i] + im_[(size_t)i] * im_[(size_t)i]; im_[(size_t)i] = 0.0f; }+ fft(nfft, true);+ // prefix energy for the NSDF normaliser+ pe_[0] = 0.0;+ for (int i = 0; i < win; ++i) { const double x = det_[(size_t)((n_ - win + i) & kMask)]; pe_[(size_t)i + 1] = pe_[(size_t)i] + x * x; }+ for (int lag = std::max(1, minLag - 1); lag <= maxLag + 1 && lag < win; ++lag) {+ const double r = re_[(size_t)lag] / nfft;+ const double m = pe_[(size_t)(win - lag)] + (pe_[(size_t)win] - pe_[(size_t)lag]);+ const double v = m > 1e-9 ? 2.0 * r / m : 0.0;+ nsdf_[(size_t)lag] = (float)v;+ if (lag >= minLag && lag <= maxLag && v > globalMax) globalMax = v;+ }+ if (globalMax > 0.0) {+ const double thr = 0.90 * globalMax;+ for (int lag = minLag; lag <= maxLag; ++lag)+ if (nsdf_[(size_t)lag] > thr && nsdf_[(size_t)lag] >= nsdf_[(size_t)lag - 1] && nsdf_[(size_t)lag] >= nsdf_[(size_t)lag + 1]) { bestLag = lag; break; }+ }+ clarity = bestLag > 0 ? nsdf_[(size_t)bestLag] : 0.0;+ }+ const double vThr = std::clamp(0.95 - 0.64 * (double)get(DetSens), 0.3, 0.95);+ const bool voiced = loud && bestLag > 0 && globalMax > vThr;+ const bool sib = loud && !voiced && zcrHz > 2500.0;++ // Target.+ const int src = keySrc();+ uint16_t mask = scaleMask();+ double tgt = -1.0, detMidi = 0.0, hz = 0.0, period = sr_ * 0.005;+ const double shiftSt = ((double)get(Shift) - 0.5) * 24.0 + ((double)get(Fine) - 0.5) * 2.0;+ double semi = shiftSt, corrApplied = 0.0;+ int midiNote = -1;+ if (src == 2) {+ const bool latch = get(MidiLatch) >= 0.5f;+ midiNote = orderN_ > 0 ? order_[(size_t)orderN_ - 1] : latch ? lastNote_ : -1;+ mask = orderN_ > 0 ? heldMask() : latch ? latchMask_ : 0;+ }+ if (voiced) {double lagF = bestLag;- const double nm1 = nsdf_[bestLag - 1], n0 = nsdf_[bestLag], np1 = nsdf_[bestLag + 1];- const double denom = nm1 - 2 * n0 + np1;- if (std::fabs(denom) > 1e-9) lagF += 0.5 * (nm1 - np1) / denom;- const double f0 = sr_ / std::max(1.0, lagF);- double detMidi = std::clamp(69.0 + 12.0 * std::log2(f0 / 440.0), 24.0, 108.0);- if (!havePitch_) { smMidi_ = detMidi; havePitch_ = true; }- else smMidi_ += (detMidi - smMidi_) * 0.5; // light smoothing → less warble-- const double snapped = snapMidi(smMidi_, key, mask);- double corr = amount * (snapped - smMidi_);- corr = std::clamp(corr, -rangeSt, rangeSt); // correction range guard- targetRatio_ = std::pow(2.0, (corr + shiftSt) / 12.0);- pushHist((float)(smMidi_ / 127.0), (float)((smMidi_ + corr) / 127.0));+ const double nm1 = nsdf_[(size_t)bestLag - 1], n0 = nsdf_[(size_t)bestLag], np1 = nsdf_[(size_t)bestLag + 1];+ const double den = nm1 - 2 * n0 + np1;+ if (std::fabs(den) > 1e-9) lagF += 0.5 * (nm1 - np1) / den;+ hz = sr_ / std::max(1.0, lagF);+ period = std::clamp(lagF, 16.0, (double)kBuf / 8.0);+ detMidi = std::clamp(69.0 + 12.0 * std::log2(hz / 440.0), 12.0, 120.0);+ const double kc = 1.0 - std::exp(-hopSec / 0.12);+ if (!have_) { sm_ = center_ = detMidi; have_ = true; }+ else { sm_ += (detMidi - sm_) * 0.5; center_ += (sm_ - center_) * kc; }+ const double h = std::clamp((double)get(Human), 0.0, 1.0);+ const double ref = sm_ * (1.0 - h) + center_ * h; // Human: correct the note centre, keep the wobble++ if (src == 2) {+ double t = -1.0;+ if (get(MidiMode) >= 0.5f) t = snapMask(ref, mask);+ else if (midiNote >= 0) t = get(MidiOctLock) >= 0.5f ? midiNote : midiNote + 12.0 * std::round((ref - midiNote) / 12.0);+ if (t < 0.0) midiT_ = -1.0;+ else {+ const bool bend = get(MidiBend) >= 0.5f;+ const double br = get(MidiBendRange) * 6.0 + 0.01;+ if (midiT_ < 0.0 || !bend || std::fabs(t - midiT_) > br) midiT_ = t;+ else midiT_ += (t - midiT_) * (1.0 - std::exp(-hopSec / (expMap(get(MidiGlide), 5.0, 800.0) * 0.001)));+ }+ tgt = midiT_;+ } else tgt = snapMask(ref, mask);++ if (tgt >= 0.0) {+ const double rangeSt = 1.0 + (double)std::clamp(get(Range), 0.0f, 1.0f) * 11.0;+ corrApplied = std::clamp((double)get(Amount) * (tgt - ref), -rangeSt, rangeSt);+ }+ semi = corrApplied + shiftSt;++ // Key analysis: duration-weighted pitch classes, decaying over ~16 bars of singing.+ const double barSec = 60.0 / std::max(20.0, bpm_) * std::max(1, tsNum_);+ const double decay = std::exp(-hopSec / (16.0 * barSec));+ for (auto& w : pcw_) w *= decay;+ totalW_ = totalW_ * decay + hopSec * clarity;+ pcw_[(size_t)(((int)std::lround(sm_) % 12 + 12) % 12)] += hopSec * clarity;} else {- targetRatio_ = std::pow(2.0, shiftSt / 12.0); // unvoiced → manual shift only- havePitch_ = false;- pushHist(0.0f, 0.0f);+ have_ = false;+ if (src == 2 && get(MidiLatch) < 0.5f && orderN_ == 0) midiT_ = -1.0;+ if (sib && get(SkipSibilants) >= 0.5f) semi = 0.0;}+ const bool sibSkip = sib && get(SkipSibilants) >= 0.5f;++ // Timestamp the decision at the window's centre: the shifter applies it to that audio.+ Rec& r = rec_[(size_t)(recW_ % kRec)];+ r.at = n_ - win / 2; r.semi = semi; r.period = period; r.sib = sibSkip;+ ++recW_;++ // Key analysis → Learn / Auto.+ if (++hopsSinceKey_ >= 8) { hopsSinceKey_ = 0; analyseKey(src); }++ // Telemetry + history.+ const double outMidi = voiced ? sm_ + 12.0 * std::log2(std::max(1e-6, std::pow(2.0, curSemi_ / 12.0))) : 0.0;+ tele_[S_DetMidi].store(voiced ? (float)sm_ : 0.0f, std::memory_order_relaxed);+ tele_[S_TargetMidi].store(voiced && tgt >= 0.0 ? (float)tgt : 0.0f, std::memory_order_relaxed);+ tele_[S_OutMidi].store((float)outMidi, std::memory_order_relaxed);+ tele_[S_CorrCents].store((float)(corrApplied * 100.0), std::memory_order_relaxed);+ tele_[S_Conf].store((float)clarity, std::memory_order_relaxed);+ tele_[S_Hz].store((float)hz, std::memory_order_relaxed);+ tele_[S_Voiced].store(voiced ? 1.0f : 0.0f, std::memory_order_relaxed);+ tele_[S_Sibilant].store(sib ? 1.0f : 0.0f, std::memory_order_relaxed);+ tele_[S_MidiNote].store((float)midiNote, std::memory_order_relaxed);+ tele_[S_MidiVel].store(midiNote >= 0 ? (float)(held_[(size_t)midiNote] ? held_[(size_t)midiNote] : lastVel_) : 0.0f, std::memory_order_relaxed);+ tele_[S_MidiHeld].store((float)orderN_, std::memory_order_relaxed);+ tele_[S_MidiMask].store((float)(orderN_ > 0 ? heldMask() : latchMask_), std::memory_order_relaxed);+ tele_[S_Learning].store(learning_ ? 1.0f : 0.0f, std::memory_order_relaxed);+ tele_[S_Mask].store((float)mask, std::memory_order_relaxed);+ tele_[S_Key].store((float)keyIdx(), std::memory_order_relaxed);+ tele_[S_InDb].store(inDb, std::memory_order_relaxed);+ pitchPub_.store(voiced ? (float)(sm_ / 127.0) : 0.0f, std::memory_order_relaxed);+ const int hw = histW_.load(std::memory_order_relaxed);+ hist_[0][(size_t)hw] = voiced ? (float)sm_ : 0.0f;+ hist_[1][(size_t)hw] = (float)outMidi;+ hist_[2][(size_t)hw] = src == 2 && midiT_ >= 0.0 ? (float)midiT_ : 0.0f;+ histW_.store((hw + 1) % kHist, std::memory_order_release);}- void pushHist(float det, float corr) {- pitchPub_.store(det, std::memory_order_relaxed);- const int w = histW_.load(std::memory_order_relaxed);- histDet_[w & (kHist - 1)] = det;- histCorr_[w & (kHist - 1)] = corr;- histW_.store((w + 1) & (kHist - 1), std::memory_order_relaxed);+ uint16_t heldMask() const {+ uint16_t m = 0;+ for (int k = 0; k < orderN_; ++k) m |= (uint16_t)(1u << (order_[(size_t)k] % 12));+ return m;}- // --- single-read-pointer granular pitch shifter -------------------------- // d_ is the read delay behind the write head. It drifts at (1 - ratio) per sample;- // when it leaves the [kFade, kFade+kGrain] band the pointer jumps by one grain and- // an equal-power crossfade to the jumped position hides the seam. At ratio == 1 the- // delay is constant → no jumps → bit-transparent (aside from a fixed latency).- void grainStep(double ratio) {- d_ += (1.0 - ratio);- if (fadeCnt_ > 0) { fadeD_ += (1.0 - ratio); --fadeCnt_; }- else if (d_ < (double)kFade) { fadeD_ = d_; d_ += kGrain; fadeCnt_ = kFade; }- else if (d_ > (double)(kFade + kGrain)) { fadeD_ = d_; d_ -= kGrain; fadeCnt_ = kFade; }+ static double profileCorr(const std::array<double, 12>& h, const double* prof, int key) {+ double mh = 0, mp = 0;+ for (int i = 0; i < 12; ++i) { mh += h[(size_t)i]; mp += prof[i]; }+ mh /= 12; mp /= 12;+ double num = 0, dh = 0, dp = 0;+ for (int pc = 0; pc < 12; ++pc) {+ const double a = h[(size_t)pc] - mh, b = prof[((pc - key) % 12 + 12) % 12] - mp;+ num += a * b; dh += a * a; dp += b * b;+ }+ return dh > 1e-12 && dp > 1e-12 ? num / std::sqrt(dh * dp) : 0.0;+ }++ void analyseKey(int src) {+ double mx = 0.0;+ for (double w : pcw_) mx = std::max(mx, w);+ for (int i = 0; i < 12; ++i) pcPub_[(size_t)i].store(mx > 0 ? (float)(pcw_[(size_t)i] / mx) : 0.0f, std::memory_order_relaxed);+ tele_[S_AnalysisSec].store((float)totalW_, std::memory_order_relaxed);+ const uint16_t mask = scaleMask();+ double in = 0.0, all = 0.0;+ for (int i = 0; i < 12; ++i) { all += pcw_[(size_t)i]; if (mask & (1u << i)) in += pcw_[(size_t)i]; }+ tele_[S_InScale].store(all > 0 ? (float)(in / all) : 0.0f, std::memory_order_relaxed);+ if (totalW_ < 0.4 || mx <= 0.0) {+ tele_[S_LearnKey].store(-1.0f, std::memory_order_relaxed);+ tele_[S_Learn2Key].store(-1.0f, std::memory_order_relaxed);+ return;+ }+ int bk = 0, bs = 1, k2 = 0, s2 = 2; double bc = -2, c2 = -2;+ for (int s = 1; s <= 2; ++s)+ for (int k = 0; k < 12; ++k) {+ const double c = profileCorr(pcw_, s == 1 ? kMajProf : kMinProf, k);+ if (c > bc) { c2 = bc; k2 = bk; s2 = bs; bc = c; bk = k; bs = s; }+ else if (c > c2) { c2 = c; k2 = k; s2 = s; }+ }+ best_ = { bk, bs, bc };+ tele_[S_LearnKey].store((float)bk, std::memory_order_relaxed);+ tele_[S_LearnScale].store((float)bs, std::memory_order_relaxed);+ tele_[S_LearnMatch].store((float)std::max(0.0, bc), std::memory_order_relaxed);+ tele_[S_Learn2Key].store((float)k2, std::memory_order_relaxed);+ tele_[S_Learn2Scale].store((float)s2, std::memory_order_relaxed);+ tele_[S_Learn2Match].store((float)std::max(0.0, c2), std::memory_order_relaxed);++ // Auto: follow the sung key once there's enough of it (hysteresis against flapping).+ if (src != 0 || learning_ || get(CustomScale) >= 0.5f || totalW_ < 3.0) return;+ const int sc = scaleIdx();+ if (sc == 1 || sc == 2) {+ const double cur = profileCorr(pcw_, sc == 1 ? kMajProf : kMinProf, keyIdx());+ if ((bk != keyIdx() || bs != sc) && bc > cur + 0.03) {+ p_[Key].store(bk / 11.0f, std::memory_order_relaxed);+ p_[Scale].store(bs == 1 ? 0.25f : 0.5f, std::memory_order_relaxed);+ }+ } else if (sc != 0) {+ int best = keyIdx(); double be = -1;+ for (int k = 0; k < 12; ++k) {+ const uint16_t m = rot(kScaleMask[sc], k);+ double e = 0; for (int i = 0; i < 12; ++i) if (m & (1u << i)) e += pcw_[(size_t)i];+ if (e > be + 1e-9) { be = e; best = k; }+ }+ if (best != keyIdx()) p_[Key].store(best / 11.0f, std::memory_order_relaxed);+ }}- float grainOut(int c) {- const float main = readFrac(c, d_);- if (fadeCnt_ <= 0) return main;- const double m = (double)(kFade - fadeCnt_) / (double)kFade; // 0 → 1 (old → new)- const float alt = readFrac(c, fadeD_);- return alt * (float)std::cos(m * kHalfPi) + main * (float)std::sin(m * kHalfPi);++ void commitLearn() {+ analyseKey(-1);+ if (totalW_ < 0.4 || best_.key < 0) return;+ p_[Key].store(best_.key / 11.0f, std::memory_order_relaxed);+ p_[Scale].store(best_.scale == 1 ? 0.25f : 0.5f, std::memory_order_relaxed);+ p_[CustomScale].store(0.0f, std::memory_order_relaxed);+ if (keySrc() == 0) p_[KeySource].store(0.5f, std::memory_order_relaxed);}- inline float readFrac(int c, double delay) const {- if (delay < 1.0) delay = 1.0;- double rp = (double)rw_ - delay;- while (rp < 0.0) rp += kBuf;- const int i0 = (int)rp & (kBuf - 1);- const int i1 = (i0 + 1) & (kBuf - 1);- const double fr = rp - std::floor(rp);- return (float)(ring_[c][i0] * (1.0 - fr) + ring_[c][i1] * fr);++ // --- TD-PSOLA grain ------------------------------------------------------------------+ // Synthesis mark s (input time), period P, pitch ratio r, formant factor fr. The analysis+ // mark is the one a whole number of periods from the last, nearest s, whose grain is+ // fully written; `snap` takes it at s (sibilants).+ void grain(double s, double P, double r, double fr, bool snap, int64_t to) {+ (void)r;+ const double halfIn = P, halfOut = P / fr;+ // A whole number of periods (the last grain's, so a gliding period stays exact at unity)+ // on from the last mark. Near unity a leftover offset from an earlier shift relaxes by+ // ≤ 0.3 % of a period per grain (a few cents at most), so an in-tune voice ends up+ // taken exactly where it lands. Sibilants have no period to keep: take them in place.+ const double step = lastP_ > 0.0 ? lastP_ : P;+ double m = std::round((s - la_) / step);+ if (m < 0.0 || m > 64.0) { la_ = s; m = 0.0; }+ double A = la_ + m * step;+ if (snap) A = s;+ else if (std::fabs(r - 1.0) < 0.003) A += std::clamp(s - A, -0.003 * P, 0.003 * P);+ const double newest = (double)(n_ - 2);+ for (int g = 0; g < 16 && A + halfIn > newest; ++g) A -= step;+ const double oldest = (double)(n_ - kBuf + 4);+ if (A - halfIn < oldest) A = oldest + halfIn;+ la_ = A; lastP_ = P;+ int64_t k0 = (int64_t)std::ceil(s - halfOut), k1 = (int64_t)std::floor(s + halfOut);+ if (k0 < to) k0 = to;+ if (k1 > to + kBuf / 2) k1 = to + kBuf / 2;+ const double invH = 1.0 / halfOut;+ for (int64_t k = k0; k <= k1; ++k) {+ const double u = (double)k - s;+ const float w = (float)(0.5 + 0.5 * std::cos(kPi * u * invH));+ const double x = A + u * fr;+ const int64_t xi = (int64_t)std::floor(x);+ const float fx = (float)(x - (double)xi);+ const size_t i0 = (size_t)(xi & kMask), i1 = (size_t)((xi + 1) & kMask), o = (size_t)(k & kMask);+ acc_[0][o] += w * (ring_[0][i0] + (ring_[0][i1] - ring_[0][i0]) * fx);+ acc_[1][o] += w * (ring_[1][i0] + (ring_[1][i1] - ring_[1][i0]) * fx);+ }}double sr_ = 44100.0;+ int lat_ = 706, hop_ = 256, baseWin_ = 1024;std::atomic<float> p_[kNumParams] = {};- float ring_[2][kBuf] = {};- float det_[kBuf] = {};- float win_[kWin] = {};- float nsdf_[kWin] = {};- float histDet_[kHist] = {};- float histCorr_[kHist] = {};+ std::array<std::array<float, kBuf>, 2> ring_{};+ std::array<std::array<float, kBuf>, 2> acc_{};+ std::array<float, kBuf> det_{};+ std::array<float, kFftMax> re_{}, im_{};+ std::array<float, kFftMax / 2> twC_{}, twS_{};+ std::array<double, kWinMax + 1> pe_{};+ std::array<float, kWinMax> nsdf_{};+ std::array<Rec, kRec> rec_{};+ int64_t recW_ = 0;+ int64_t n_ = 0;+ int hopCnt_ = 0;+ double pg_ = 220.0, ns_ = 0.0, la_ = 0.0, lastP_ = 0.0, curSemi_ = 0.0;+ double eDry_ = 0.0, eWet_ = 0.0, gAuto_ = 1.0, lvlA_ = 0.0003, lvlB_ = 0.0005; // level match+ double sm_ = 60.0, center_ = 60.0, midiT_ = -1.0;+ bool have_ = false;++ // MIDI source+ std::atomic<int32_t> srcTrack_{-1};+ const MidiEv* midiEvs_ = nullptr;+ int32_t midiN_ = 0;+ bool midiFed_ = false;+ std::array<uint8_t, 128> held_{};+ std::array<int, 16> order_{};+ int orderN_ = 0, lastNote_ = -1, lastVel_ = 0;+ uint16_t latchMask_ = 0;++ // key analysis+ std::array<double, 12> pcw_{};+ double totalW_ = 0.0;+ int hopsSinceKey_ = 0;+ struct Best { int key = -1, scale = 1; double corr = 0.0; } best_;+ bool learning_ = false;+ double bpm_ = 120.0; int tsNum_ = 4;++ // UI feeds+ std::array<std::atomic<float>, kTele> tele_{};+ std::array<std::atomic<float>, 12> pcPub_{};+ std::array<std::array<float, kHist>, 3> hist_{};std::atomic<int> histW_{0};- int rw_ = 0, hop_ = 0, minLag_ = 44, maxLag_ = 630;- double d_ = 0.0, fadeD_ = 0.0; int fadeCnt_ = 0;- double curRatio_ = 1.0, targetRatio_ = 1.0, smMidi_ = 60.0;- bool havePitch_ = false;- double lpF_[2] = {0.0, 0.0}, lpCoef_ = 0.1; // formant-tilt one-pole state- std::atomic<float> pitchPub_{0.0f};+ std::atomic<float> pitchPub_{0.0f}, srA_{44100.0f}, cpuA_{0.0f}, ratioA_{1.0f}, midiLiveA_{0.0f};+ std::atomic<bool> resetReq_{false};+ std::atomic<int> learnReq_{0};+ double cpuS_ = 0.0;};} // namespace notadiff --git a/src/native/nota.engine/src/Device.h b/src/native/nota.engine/src/Device.hindex c79c591a..d5fe0bc5 100644--- a/src/native/nota.engine/src/Device.h+++ b/src/native/nota.engine/src/Device.h@@ -20,6 +20,8 @@namespace nota {+struct MidiEv;+class Device {public:virtual ~Device() = default;@@ -131,6 +133,12 @@ public:// bus (Phase C). The UI only offers a source picker when this is true.virtual bool acceptsSidechain() const { return false; }+ // MIDI key: a device that follows another track's notes (Nota Auto Shift's MIDI target)+ // returns true; the engine then hands it the sidechain source track's post-FX note+ // events for the block (offsets within the block) right before process(). Audio thread.+ virtual bool wantsMidiKey() const { return false; }+ virtual void setMidiKey(const MidiEv* /*evs*/, int32_t /*n*/) {}+// Sidechain shaping (Phase D). Stored on the base so they// persist/query generically; each dynamics device reads them in process():// - gain: dB applied to the sidechain detector signal (raises how hard thediff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex 6dece2b8..34e33113 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -824,6 +824,8 @@ private:double blockStart, double spb, bool playing, bool arrangementActive);// Pre-pass: fill blockMidi_/blockMidiN_ for every non-session instrument track.void computeBlockMidi(Graph* g, int32_t frames, double blockStart, double spb, bool playing, bool arrangementActive);+ // Hand a MIDI-keyed device its source track's notes for this block (from blockMidi_).+ void feedMidiKey(Graph* g, Device& d, int32_t srcTrackId);void renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double spb);int applyMidiEffects(Track& t, MidiEv* evs, int n, MidiEv* scratch,int32_t frames, double beatStart, double spb, bool playing);diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cppindex 2f7d3797..89a95262 100644--- a/src/native/nota.engine/src/Engine_Render.cpp+++ b/src/native/nota.engine/src/Engine_Render.cpp@@ -395,6 +395,15 @@ void Engine::computeBlockMidi(Graph* g, int32_t frames, double blockStart, doubl}}+// A device that takes a MIDI key (Nota Auto Shift's MIDI target) gets its source track's+// post-FX notes for this block, from the pre-pass (blockMidi_). Audio thread.+void Engine::feedMidiKey(Graph* g, Device& d, int32_t srcTrackId) {+ if (!g) return;+ const size_t nt = std::min(g->tracks.size(), blockMidiN_.size());+ for (size_t j = 0; j < nt; ++j)+ if (g->tracks[j] && g->tracks[j]->id() == srcTrackId) { d.setMidiKey(blockMidi_[j].data(), blockMidiN_[j]); return; }+}+// Renders the instrument's dry stereo (pre-fader) into `dst` (zeroed here) from this block's// precomputed MIDI: the track's own post-FX output plus the post-FX output of any track routing// its MIDI here (so a source's arp/MIDI-FX drive this instrument too). Fader/pan and the device@@ -948,6 +957,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, bconst float* sc = s < 0 ? nullptr: (d->sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());d->setSidechain(sc, frames);+ if (d->wantsMidiKey()) feedMidiKey(g, *d, src);}if (spb > 0.0) d->setTransport(blockStart / spb, spb, playing); // tempo-synced devicesd->setTransportInfo(ti); // hosted-plugin sync@@ -1031,6 +1041,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, bconst float* sc = s < 0 ? nullptr: (d->sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());d->setSidechain(sc, frames);+ if (d->wantsMidiKey()) feedMidiKey(g, *d, src);}if (spb > 0.0) d->setTransport(blockStart / spb, spb, playing);d->setTransportInfo(ti);@@ -1097,6 +1108,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, bconst float* sc = s < 0 ? nullptr: (d->sidechainTapPre() ? routeBusPre_[s].data() : routeBus_[s].data());d->setSidechain(sc, frames);+ if (d->wantsMidiKey()) feedMidiKey(g, *d, src);}if (spb > 0.0) d->setTransport(blockStart / spb, spb, playing);d->setTransportInfo(ti); // hosted-plugin syncdiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 8660f9a1..79ce665d 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -7813,6 +7813,11 @@ Console.WriteLine("-- Nota Orbit (effect kind 9) --");// ===================== Nota Auto Shift (effect kind 10) ===================Console.WriteLine("-- Nota Auto Shift (effect kind 10) --");{+ // Params (AutoShift.h): 0 Key, 1 Scale, 2 Amount, 3 Speed, 4 Shift, 5 Mix, 6 Range, 7 Formant,+ // 8 Key Source, 9 Follow, 10 Human, 11 Fine, 12 Formant Shift, 13 Det Low, 14 Det High,+ // 15 Det Sens, 16 Skip Sibilants, 17 Custom Scale, 18..29 Note C..B, 30 MIDI Mode, 31 MIDI Latch,+ // 32 MIDI Oct Lock, 33 MIDI Glide, 34 MIDI Bend Range, 35 MIDI Bend.+ const int kTele = 32, kHistN = 384, kScopeN = kTele + 12 + 3 * kHistN;using var aseng = new NotaEngine();int ast = aseng.AddAudioTrack();aseng.AddAudioClip(ast, wav, 0.0); // 1 s sine @ 440 Hz = A4 (MIDI 69)@@ -7821,8 +7826,15 @@ Console.WriteLine("-- Nota Auto Shift (effect kind 10) --");Check(aseng.DeviceName(ast, asdi) == "Nota Auto Shift", $"device is Nota Auto Shift (got '{aseng.DeviceName(ast, asdi)}')");Check(aseng.TrackDeviceBuiltinKind(ast, asdi) == 10, "device reports builtin kind 10");int aspc = aseng.DeviceParamCount(ast, asdi);- Check(aspc == 10, $"Nota Auto Shift exposes 10 params ({aspc})");- Check(aseng.DeviceParamName(ast, asdi, 6) == "Range" && aseng.DeviceParamName(ast, asdi, 7) == "Formant", "new params: Range + Formant");+ Check(aspc == 36, $"Nota Auto Shift exposes 36 params ({aspc})");+ Check(aseng.DeviceParamName(ast, asdi, 6) == "Range" && aseng.DeviceParamName(ast, asdi, 7) == "Formant"+ && aseng.DeviceParamName(ast, asdi, 9) == "Follow Scale", "original params keep their names and places");+ Check(aseng.DeviceParamName(ast, asdi, 10) == "Human" && aseng.DeviceParamName(ast, asdi, 12) == "Formant Shift"+ && aseng.DeviceParamName(ast, asdi, 18) == "Note C" && aseng.DeviceParamName(ast, asdi, 29) == "Note B"+ && aseng.DeviceParamName(ast, asdi, 35) == "MIDI Bend", "appended params: Human … Note C..B … MIDI Bend");+ Check(Math.Abs(aseng.DeviceParamDefault(ast, asdi, 7)) < 1e-6f && Math.Abs(aseng.DeviceParamDefault(ast, asdi, 10)) < 1e-6f+ && Math.Abs(aseng.DeviceParamDefault(ast, asdi, 11) - 0.5f) < 1e-6f && Math.Abs(aseng.DeviceParamDefault(ast, asdi, 17)) < 1e-6f,+ "new params default to the old behaviour (formants move, human 0, fine 0, no custom scale)");aseng.DeviceSetParam(ast, asdi, 2, 0.8f); // Amountaseng.DeviceSetParam(ast, asdi, 6, 0.7f); // Rangeaseng.DeviceSetParam(ast, asdi, 7, 0.6f); // Formant@@ -7835,12 +7847,13 @@ Console.WriteLine("-- Nota Auto Shift (effect kind 10) --");Check(Rms(asbuf, 8192) > 1e-4f, $"Auto Shift passes audio (rms {Rms(asbuf, 8192):0.000})");float detMidi = aseng.DeviceGainReduction(ast, asdi) * 127f;Check(Math.Abs(detMidi - 69f) < 1.5f, $"detects the 440 Hz sine as A4 (~69, got {detMidi:0.0})");- // Interleaved [detected, corrected] scope: even = detected A4, odd = corrected (in scale).- var asscope = new float[1024];+ var asscope = new float[kScopeN];int asn = aseng.DeviceScope(ast, asdi, asscope, asscope.Length);- Check(asn >= 2 && (asn % 2) == 0, $"pitch scope returns interleaved pairs ({asn})");- bool anyDet = false; for (int s = 0; s < asn; s += 2) if (asscope[s] > 1e-4f) { anyDet = true; break; }- Check(anyDet, "scope carries the detected-pitch trace");+ Check(asn == kScopeN, $"scope returns telemetry + histogram + three histories ({asn})");+ bool anyDet = false; for (int s = kTele + 12; s < kTele + 12 + kHistN; s++) if (Math.Abs(asscope[s] - 69f) < 1f) { anyDet = true; break; }+ Check(anyDet, "the detected-pitch history carries A4");+ Check(asscope[8] > 40000 && asscope[10] > 100 && asscope[10] < 2000, $"telemetry: sample rate {asscope[8]:0} · latency {asscope[10]:0} smp");+ Check(aseng.TrackLatencySamples(ast) == (int)asscope[10], $"latency reported for PDC ({aseng.TrackLatencySamples(ast)} smp)");// Manual Shift +12 st (ratio 2) audibly transposes → output differs from no-shift.aseng.DeviceSetParam(ast, asdi, 2, 0f); // Amount 0 (isolate manual shift)@@ -7856,6 +7869,210 @@ Console.WriteLine("-- Nota Auto Shift (effect kind 10) --");int ascopy = aseng.DuplicateTrack(ast);Check(ascopy > 0 && Math.Abs(aseng.DeviceGetParam(ascopy, asdi, 2) - 0f) < 1e-3f, "duplicate track clones Auto Shift params");+ Check(aseng.DeviceText(ast, asdi, 0).Length > 20 && aseng.DeviceText(ast, asdi, 1).Length > 10 && aseng.DeviceText(ast, asdi, 2).Contains("Det Low"),+ "device text: status, live reading, parameter guide");+}++// Nota Auto Shift on a voice-like tone: correction, transparency, formants, custom scale, MIDI target.+{+ const int sr = 44100, kScopeV = 32 + 12 + 3 * 384;+ // Pitch of a mono segment by NSDF (first peak above 90 % of the max), in Hz.+ static double PitchHz(float[] st, int from, int len, int srate)+ {+ var x = new double[len];+ for (int i = 0; i < len; i++) x[i] = st[(from + i) * 2];+ int minLag = srate / 1200, maxLag = srate / 60;+ var n = new double[maxLag + 2];+ double best = 0;+ for (int lag = minLag - 1; lag <= maxLag + 1; lag++)+ {+ double r = 0, m = 0;+ for (int i = 0; i + lag < len; i++) { r += x[i] * x[i + lag]; m += x[i] * x[i] + x[i + lag] * x[i + lag]; }+ n[lag] = m > 1e-12 ? 2 * r / m : 0;+ if (lag >= minLag && lag <= maxLag) best = Math.Max(best, n[lag]);+ }+ for (int lag = minLag; lag <= maxLag; lag++)+ if (n[lag] > 0.9 * best && n[lag] >= n[lag - 1] && n[lag] >= n[lag + 1])+ {+ double den = n[lag - 1] - 2 * n[lag] + n[lag + 1];+ double lf = lag + (Math.Abs(den) > 1e-12 ? 0.5 * (n[lag - 1] - n[lag + 1]) / den : 0);+ return srate / lf;+ }+ return 0;+ }+ // Spectral centroid (Hz) of a Hann-windowed mono segment.+ static double Centroid(float[] st, int from, int len, int srate)+ {+ double num = 0, den = 0;+ for (int k = 1; k < len / 2; k += 2)+ {+ double re = 0, im = 0, w = 2 * Math.PI * k / len;+ for (int i = 0; i < len; i++)+ {+ double v = st[(from + i) * 2] * (0.5 - 0.5 * Math.Cos(2 * Math.PI * i / len));+ re += v * Math.Cos(w * i); im -= v * Math.Sin(w * i);+ }+ double mag = Math.Sqrt(re * re + im * im);+ num += mag * k * srate / (double)len; den += mag;+ }+ return den > 0 ? num / den : 0;+ }+ static double Cents(double a, double b) => 1200 * Math.Log2(a / b);++ // A vowel-like source: A3 + 40 cents with harmonics shaped by /a/ formants (700 / 1200 / 2600 Hz).+ double f0 = 220.0 * Math.Pow(2, 0.4 / 12);+ static double Formants(double f) => 1.0 / (1 + Math.Pow((f - 700) / 110, 2)) + 0.6 / (1 + Math.Pow((f - 1200) / 130, 2)) + 0.25 / (1 + Math.Pow((f - 2600) / 180, 2)) + 0.02;+ string vox = Path.Combine(Path.GetTempPath(), "nota_smoke_autoshift_vox.wav");+ Nota.SmokeTest.WavWriter.WriteStereo(vox, 2.5, sr, i =>+ {+ double t = i / (double)sr, s = 0;+ for (int h = 1; h * f0 < 8000; h++) s += Formants(h * f0) * Math.Sin(2 * Math.PI * h * f0 * t) / Math.Sqrt(h);+ return (s * 0.25, s * 0.25);+ });+ using var ve = new NotaEngine();+ ve.SetBpm(120);+ int vt = ve.AddAudioTrack();+ ve.AddAudioClip(vt, vox, 0.0);+ int vd = ve.AddBuiltinDevice(vt, 10);+ void VP(int p, float v) => ve.DeviceSetParam(vt, vd, p, v);+ float[] Render(int frames) { var b = new float[frames * 2]; ve.Seek(0); ve.Play(); ve.RenderOffline(b, frames); ve.StopTransport(); return b; }+ const int N = sr * 2, At = sr, Len = 8192;+ VP(5, 0f); // Mix 0 = the (latency-aligned) dry path+ double inHz = PitchHz(Render(N), At, Len, sr);+ Check(Math.Abs(Cents(inHz, f0)) < 5, $"dry path keeps the input pitch ({inHz:0.0} Hz vs {f0:0.0})");+ VP(5, 1f);++ // C major, Amount 100 %, fastest Speed → A3 (220 Hz).+ VP(0, 0f); VP(1, 0.25f); VP(2, 1f); VP(3, 0f);+ var tuned = Render(N);+ double tunedHz = PitchHz(tuned, At, Len, sr);+ Check(Math.Abs(Cents(tunedHz, 220.0)) < 8, $"corrects A3 +40 ¢ to A3 ({tunedHz:0.0} Hz, {Cents(tunedHz, 220.0):+0;-0} ¢)");+ var tsc = new float[kScopeV]; ve.DeviceScope(vt, vd, tsc, tsc.Length);+ Check(Math.Abs(tsc[1] - 57f) < 0.01f && Math.Abs(tsc[3] + 40f) < 6f, $"telemetry: target A3 (57, got {tsc[1]:0.0}), correction ≈ −40 ¢ (got {tsc[3]:0})");+ bool finiteV = true; foreach (var s in tuned) if (!float.IsFinite(s) || Math.Abs(s) > 4f) { finiteV = false; break; }+ Check(finiteV, "corrected output stays finite and bounded");++ // Amount 0 + Shift 0 is transparent: the wet path matches the (equally delayed) dry path.+ VP(2, 0f);+ var wet0 = Render(N);+ VP(5, 0f);+ var dry0 = Render(N);+ VP(5, 1f);+ double err = 0, refE = 0;+ for (int i = At * 2; i < (At + Len) * 2; i++) { err += (wet0[i] - dry0[i]) * (double)(wet0[i] - dry0[i]); refE += dry0[i] * (double)dry0[i]; }+ double relErr = Math.Sqrt(err / Math.Max(1e-12, refE));+ Check(relErr < 0.12, $"no correction, no shift → transparent against the delayed dry (rel. error {relErr:0.000})");++ // +12 st: formants move with the pitch (Formant 0) or stay (Formant 1).+ double c0 = Centroid(dry0, At, 4096, sr);+ VP(4, 1f);+ VP(7, 0f); var upMove = Render(N);+ VP(7, 1f); var upKeep = Render(N);+ double upHz = PitchHz(upKeep, At, Len, sr), cMove = Centroid(upMove, At, 4096, sr), cKeep = Centroid(upKeep, At, 4096, sr);+ Check(Math.Abs(Cents(upHz, 2 * f0)) < 15, $"Shift +12 st with formants preserved doubles the pitch ({upHz:0.0} Hz vs {2 * f0:0.0})");+ Check(cMove / c0 > 1.45 && cKeep / c0 < 1.3, $"formants: moved ×{cMove / c0:0.00}, preserved ×{cKeep / c0:0.00} (centroid {c0:0} Hz)");+ static double SegDb(float[] b, int from, int len) { double e = 0; for (int i = from * 2; i < (from + len) * 2; i++) e += b[i] * (double)b[i]; return 10 * Math.Log10(e / (len * 2) + 1e-20); }+ VP(4, 0f); var downKeep = Render(N); VP(4, 1f); // −12 st, formants preserved+ double dDry = SegDb(dry0, At, Len), dTuned = SegDb(tuned, At, Len) - dDry, dKeep = SegDb(upKeep, At, Len) - dDry,+ dMove = SegDb(upMove, At, Len) - dDry, dDown = SegDb(downKeep, At, Len) - dDry;+ Check(Math.Abs(dTuned) < 1.5 && Math.Abs(dKeep) < 1.5 && Math.Abs(dMove) < 1.5 && Math.Abs(dDown) < 1.5,+ $"level holds: tuned {dTuned:0.0} dB, +12 st preserved {dKeep:0.0} / moved {dMove:0.0} dB, −12 st {dDown:0.0} dB");+ VP(12, 0.75f); var fUp = Render(N); // Formant Shift +50 % with the pitch unchanged+ VP(4, 0.5f); var fOnly = Render(N);+ double cF = Centroid(fOnly, At, 4096, sr), fHz = PitchHz(fOnly, At, Len, sr);+ Check(cF / c0 > 1.15 && Math.Abs(Cents(fHz, f0)) < 15, $"Formant Shift moves the formants (×{cF / c0:0.00}) and keeps the pitch ({fHz:0.0} Hz)");+ VP(12, 0.5f); VP(7, 0f);++ // Custom scale: only G# → pulls A3 +40 ¢ down to G#3.+ VP(2, 1f); VP(17, 1f);+ for (int n = 0; n < 12; n++) VP(18 + n, n == 8 ? 1f : 0f);+ var gs = Render(N);+ double gsHz = PitchHz(gs, At, Len, sr);+ Check(Math.Abs(Cents(gsHz, 207.652)) < 10, $"custom scale {{G#}} → G#3 ({gsHz:0.0} Hz)");+ VP(17, 0f);++ // Fine −40 ¢ on top of a hard tune to A lands 40 ¢ flat.+ VP(11, 0.3f);+ var fine = Render(N);+ double fineHz = PitchHz(fine, At, Len, sr);+ Check(Math.Abs(Cents(fineHz, 220.0) + 40) < 10, $"Fine −40 ¢ ({Cents(fineHz, 220.0):+0;-0} ¢ from A3)");+ VP(11, 0.5f);++ // MIDI target: an instrument track holding E3 drives the target (Oct Lock, Range 12 st).+ int mt = ve.AddInstrumentTrack();+ int mc = ve.AddMidiClip(mt, 0.0, 8.0);+ ve.SetClipNotes(mt, mc, new[] { new NotaNote(52, 0.0, 7.5, 0.8f) });+ ve.SetTrackMute(mt, true);+ ve.SetDeviceSidechainSource(vt, vd, mt);+ VP(8, 1f); VP(30, 0f); VP(32, 1f); VP(6, 1f);+ var midiOut = Render(N);+ double mHz = PitchHz(midiOut, At, Len, sr);+ var msc = new float[kScopeV]; ve.DeviceScope(vt, vd, msc, msc.Length);+ Check(Math.Abs(msc[11] - 52f) < 0.01f && msc[14] > 0.5f, $"MIDI source feeds the device (note {msc[11]:0}, live {msc[14]:0})");+ Check(Math.Abs(Cents(mHz, 164.814)) < 12, $"MIDI target E3 pulls the voice to E3 ({mHz:0.0} Hz)");+ VP(32, 0f); // octave nearest the voice → E4 is 7 st up vs E3 5.4 st down → E3 either way; check no crash+ VP(8, 0.5f); VP(6, 0.3636f);++ // Skip Sibilants: noise with Shift +12 passes unshifted when on.+ string noise = Path.Combine(Path.GetTempPath(), "nota_smoke_autoshift_noise.wav");+ var rng = new Random(7);+ Nota.SmokeTest.WavWriter.WriteStereo(noise, 2.5, sr, i => { double hp = rng.NextDouble() * 2 - 1; return (hp * 0.2, hp * 0.2); });+ int nt2 = ve.AddAudioTrack();+ ve.SetTrackMute(vt, true);+ ve.AddAudioClip(nt2, noise, 0.0);+ int nd = ve.AddBuiltinDevice(nt2, 10);+ ve.DeviceSetParam(nt2, nd, 4, 1f); // +12 st+ ve.DeviceSetParam(nt2, nd, 5, 0f); var nDry = Render(N);+ ve.DeviceSetParam(nt2, nd, 5, 1f);+ ve.DeviceSetParam(nt2, nd, 16, 1f); var nSkip = Render(N);+ ve.DeviceSetParam(nt2, nd, 16, 0f); var nShift = Render(N);+ double eSkip = 0, eShift = 0, eRef = 0;+ for (int i = At * 2; i < (At + Len) * 2; i++)+ { eSkip += Math.Pow(nSkip[i] - nDry[i], 2); eShift += Math.Pow(nShift[i] - nDry[i], 2); eRef += nDry[i] * (double)nDry[i]; }+ Check(Math.Sqrt(eSkip / eRef) < 0.2 && Math.Sqrt(eShift / eRef) > 0.5,+ $"Skip Sibilants passes noise unshifted (rel. err {Math.Sqrt(eSkip / eRef):0.00} vs shifted {Math.Sqrt(eShift / eRef):0.00})");++ // Learn: start, sing, commit → a key and Major/Minor, Key Source Manual.+ ve.SetTrackMute(vt, false); ve.SetTrackMute(nt2, true);+ ve.DeviceSetParam(vt, vd, 8, 0f); // Auto+ ve.DeviceAction(vt, vd, 1, 1, 0);+ Render(N);+ var lsc = new float[kScopeV]; ve.DeviceScope(vt, vd, lsc, lsc.Length);+ Check(lsc[15] > 0.5f && lsc[16] >= 0 && lsc[23] > 0.5f, $"Learn runs and ranks keys (best {lsc[16]:0}, {lsc[23]:0.0} s analysed)");+ ve.DeviceAction(vt, vd, 1, 0, 0);+ Render(1024);+ float sAfter = ve.DeviceGetParam(vt, vd, 1), srcAfter = ve.DeviceGetParam(vt, vd, 8);+ Check((Math.Abs(sAfter - 0.25f) < 1e-3f || Math.Abs(sAfter - 0.5f) < 1e-3f) && Math.Abs(srcAfter - 0.5f) < 1e-3f,+ $"Learn commits a Major/Minor key and switches to Manual (scale {sAfter:0.00}, source {srcAfter:0.00})");+ int keyAfter = (int)Math.Round(ve.DeviceGetParam(vt, vd, 0) * 11);+ Check(new[] { 9, 2, 4, 5, 0 }.Contains(keyAfter), $"learned key holds the sung A ({keyAfter})");++ // MCP: the corrector's reading.+ var vtools = new Nota.Mcp.Tools.DeviceTools(ve, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());+ ve.DeviceSetParam(vt, vd, 2, 1f);+ Render(N);+ var rd = vtools.ReadAutoShift(vt, vd).Result;+ Check(rd.Voiced && rd.DetectedNote == "A3" && Math.Abs(rd.DetectedCents - 40) < 6 && rd.TargetNote == "A3" && rd.ScaleNotes.Length == 7+ && rd.History.Length == 16 && rd.SampleRate > 1000 && rd.LatencySamples > 0 && rd.Best is not null && rd.SungPitchClasses[9] > 0.99,+ $"MCP read_auto_shift reports pitch, target, scale, key guess and history ({rd.DetectedNote} {rd.DetectedCents:+0} ¢ → {rd.TargetNote}, {rd.Scale}, best {rd.Best?.Key} {rd.Best?.Scale})");++ // Every factory preset names only real params and renders finite.+ var cat = new FactoryPresetCatalog();+ int asPresets = 0; bool namesOk = true, presetsFinite = true;+ var names = new HashSet<string>();+ for (int p = 0; p < ve.DeviceParamCount(vt, vd); p++) names.Add(ve.DeviceParamName(vt, vd, p));+ foreach (var info in cat.All())+ {+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 10) continue;+ var doc = cat.Document(info.Id);+ if (doc is null) continue;+ asPresets++;+ foreach (var k in doc.NamedParams!.Keys) if (!names.Contains(k)) { namesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }+ cat.ApplyInPlace(ve, info.Id, vt, vd);+ var pb = Render(8192);+ foreach (var v in pb) if (!float.IsFinite(v) || Math.Abs(v) > 4f) { presetsFinite = false; Console.WriteLine($" preset {info.DisplayName} not finite"); break; }+ }+ Check(asPresets >= 25 && namesOk && presetsFinite, $"{asPresets} Auto Shift factory presets, all params known, all render finite");}// ===================== Nota Beat Repeat (effect kind 11) ==================