Skip to content

armgit / nota

Public Imported from GitHub
0

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

Redesign of Sampler

Egor Khindikaynen6028e7c7415e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7902a7af..a0864ce8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,39 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Nota Sampler's editor is now the almanac's card, with the new mockup's features.** The card
+ moves onto the 700 × 260 frame the other instruments use: a **Sample** / **Pitch** / **Env** /
+ **Filter** tab panel with a one-line reading beside the tabs, a fixed 186 px rail and a
+ status strip:
+ - **Sample** — the waveform with Start / End and the loop (drag them, double-click resets),
+ the crossfade zone drawn in, Loop Off / Fwd / Ping / Rev, Crossfade, a new **Gain** (±24 dB
+ before the envelope), **Snap to zero** and a new **Trim silence** (Start and End to where
+ the sound begins and fades out).
+ - **Pitch** — a keyboard C2 … C6 that follows the root: click a key to make it the root; the
+ key that plays the sample at its own pitch is outlined and the note sounding now is teal.
+ Transpose, Detune, a new pitch **Keytrack** (100 % chromatic … 0 % every key plays the
+ root), the root stepper and **Detect from file name** ("Piano_C4.wav" → C4).
+ - **Env** — the amp envelope as a graph you drag (attack, decay + sustain, release), with
+ the loudest voice riding it in teal; A / D / S / R and a Vel → Vol switch.
+ - **Filter** — the filter's real response (the engine's SVF) — drag for cutoff and
+ resonance, the cutoff the voice actually hears shown in teal; Type, Cutoff, Reso,
+ Keytrack and a new **Env → Cutoff** with its depth (±6 octaves).
+ - **Rail** — Poly 16 / Mono / Choke, Volume, Pan, a new **Glide** (a slide from the last note;
+ in Mono it is legato — no retrigger, and a released key slides back to the one still
+ held), a new **Output** level, Vel → Vol and the output meter.
+ The same editor opens for a Sampler inside a Drum Rack pad or an Instrument Rack chain.
+- **Nota Sampler ships 30 factory presets** — plucks and keys, looped pads, bass with glide,
+ choked drum hits, lo-fi and telephone colours, envelope sweeps. A preset shapes the sound
+ and leaves the loaded sample and its Start / End / loop points alone (unless it names them),
+ and the Sampler can now be saved as a user preset too.
+- **MCP: `read_sampler` and `set_sampler`.** Read a Sampler track — a summary, a guide to every
+ parameter, the sample (file name, length), the root its file name suggests, where the sound
+ starts and fades out, every setting in real units and the live voice (play position,
+ envelope stage, note, the cutoff it hears) — and shape it in seconds, dB, semitones, Hz and
+ words ("Ping", "LP", "Mono", root "A3"), including Trim silence, Snap to zero and Detect
+ root. `add_sampler_track` / `load_sampler_sample` take `detectRoot`; `get_sampler_info`
+ returns the file name.
+
- **Nota Pendulum's editor is now the almanac's card, and it shows the balls the engine is
actually swinging.** The card moves onto the 700 × 260 frame the other instruments use — a
**Balls** / **Voice** tab panel with a one-line reading beside the tabs, a fixed 186 px ball
@@ -156,6 +189,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Sampler's automation menu is grouped.** Its parameters list under **Sample**, **Loop**,
+ **Pitch**, **Env**, **Filter**, **Voice** and **Out** (e.g. Filter › Cutoff, Loop ›
+ Crossfade); the ids are unchanged, so existing lanes and projects keep working. The six new
+ parameters are appended and default to the old sound.
- **Nota Pendulum's automation menu is grouped.** Its parameters list under **Balls**,
**Motion**, **Voice**, **Spread** and **Scale** (e.g. Motion › Rate, Spread › Humanize); the
ids are unchanged, so existing lanes and projects keep working.
@@ -681,6 +718,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
returns the compressor's status line.
### Fixed
+- **A Sampler's loop could change kind on its own.** Reloading a sample turned a ping-pong
+ loop into a forward one and a forward loop into a one-shot, and a sampler created with the
+ loop flag (e.g. from a kit) played ping-pong instead of forward. The loop kind now survives.
+- **A Sampler preset from the browser made a Synth track.** It now makes a Sampler.
- **Nota Dynamic EQ-8's key track did nothing.** The device never stored the sidechain source
it was given, so a chosen key track was forgotten at once and every band kept listening to
its own track. The key is now kept, saved with the project and heard by the bands set to
diff --git a/FEATURES.md b/FEATURES.md
index 18aee7dd..b2537e65 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -257,9 +257,12 @@ and user presets, automation, persistence and cloning.
stack with stereo spread; ADSR; a filter with type Off/LP/HP/BP, resonance and an
Env → Cutoff amount; voice modes Poly 16 / Mono / Legato with glide, pan and Vel→Vol.
Osc · Env · Filter tabs with draggable envelope and filter graphs. 25 factory presets.
-- **Nota Sampler** — sampler (one-shot and loop), voice modes Poly 16 / Mono / Choke, loop
- crossfade, reverse loop, filter key-tracking, Vel→Vol; Sample · Pitch · Env · Filter
- tabs; an editable waveform.
+- **Nota Sampler** — sampler (one-shot and loop: Off / Fwd / Ping / Rev), voice modes
+ Poly 16 / Mono / Choke, Glide (legato in Mono), loop crossfade, sample Gain, pitch
+ Keytrack, filter key-tracking and Env → Cutoff, Vel→Vol, Output; Sample · Pitch · Env ·
+ Filter tabs over an editable waveform, a clickable keyboard for the root, a draggable
+ envelope and a draggable filter response, with Snap to zero, Trim silence and Detect
+ from file name; 30 factory presets; MCP `read_sampler` / `set_sampler`.
- **Nota Grain** — granular sampler: a read Position that Scans through the file, Freezes
or follows the keyboard, grains of a chosen size, density and window shape (Hann /
Gauss / Tukey / Tri) sprayed around it, coarse/fine pitch, per-grain position, pitch and
@@ -690,8 +693,9 @@ Coverage:
instrument, parameters, mix (gain/pan/mute/solo), key and velocity zones, trigger note,
8 macros and their mappings, rack volume and glide; for the Drum Rack, per-pad
choke/tune/decay and kit swing/humanize.
-- **Samples**: create a Sampler or Grain with a file, load a sample onto a track or into a
- rack chain, and read sample info.
+- **Samples**: create a Sampler or Grain with a file (optionally taking the root from the file
+ name), load a sample onto a track or into a rack chain, read sample info, and read / shape a
+ Sampler in real units (`read_sampler`, `set_sampler`).
- **Mixer**: sends to returns, the return list, track and master meters, record source.
- **Plugins**: list the AU/VST3 catalogue, look up by id, add as an instrument or insert
effect, open and close the editor, read and write parameters and state.
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/SamplerInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/SamplerInstrumentCard.cs
index 9f6e13ea..3cc9c5d9 100644
--- a/src/managed/Nota.App/DeviceCards/Instruments/SamplerInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/Instruments/SamplerInstrumentCard.cs
@@ -1,14 +1,28 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — the track's built-in Nota Sampler card (instrument kind 1), rebuilt
-// to mockup 2o (700×260 on the shared shell). A LIVE strip (Vol / Pan / Cutoff + Voice
-// mode) over a body of tab rail (Sample · Pitch · Env · Filter) | tab content. The Sample
-// tab is the editable waveform (start/end/loop handles, loop modes + crossfade, Snap
-// zero) with an amp-envelope rail; Pitch / Env / Filter group the rest. Zones (multi-
-// sample mapping) is intentionally out of scope — this is the single-sample engine.
-// The editor body (BuildEditor) is reused for the track Sampler and rack-chain Samplers
-// (Drum Rack pads / Instrument Rack chains) via ISamplerAccess.
+// Detail · Devices — the Nota Sampler editor (instrument kind 1), on the 700 × 260 frame
+// the almanac draws for it (header 24 · body · status 18):
+//
+// Centre a tab panel — Sample · Pitch · Env · Filter — each a window over a 66 px
+// row of controls, with the tab's reading beside the tabs:
+// Sample — the waveform with Start / End, the loop and its crossfade
+// (drag them); Loop Off / Fwd / Ping / Rev, Crossfade, Gain, Snap
+// to zero and Trim silence.
+// Pitch — the keyboard (click a key for the root, the key that plays the
+// sample at its own pitch outlined); Transpose, Detune, Keytrack,
+// the root stepper and Detect from file name.
+// Env — the amp envelope (drag its nodes), A / D / S / R and Vel → Vol.
+// Filter — the SVF's real response (drag: cutoff × resonance); Type,
+// Cutoff, Reso, Keytrack and Env → Cutoff with its depth.
+// Rail 186 always there: the voice mode (Poly 16 / Mono / Choke), Volume, Pan,
+// Glide, the Output level, Vel → Vol and the output meter.
+//
+// Brass is the parameter itself; teal is detune and modulation (keytrack, velocity, the
+// envelope's reach) and what the engine is doing now (the voice on the envelope, the
+// cutoff it hears). Every control is a plugin param → automation / persist / clone, and
+// the card follows automation live. The editor (BuildEditor) also serves a rack chain's
+// Sampler (Drum Rack pads / Instrument Rack chains) through ISamplerAccess.
using System;
using System.Collections.Generic;
@@ -28,397 +42,557 @@ internal sealed class SamplerInstrumentCard : IInstrumentCard
public string Subtitle => "BUILT-IN";
public double CardWidth => 700;
- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;
- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
- private static readonly IBrush Border2 = NotaPalette.BorderDefault;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush FieldBorder = NotaPalette.GraphBorder;
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush TealC = NotaPalette.Teal;
- private static readonly IBrush TxtC = NotaPalette.TextPrimary;
- private static readonly IBrush MutedC = NotaPalette.TextTertiary;
- private static readonly IBrush GreenC = NotaPalette.Success;
- private static readonly IBrush RedC = NotaPalette.TextSecondary; // a state, not an alert: red is kept for recording and overload
- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);
- private static readonly IBrush RowLit = NotaPalette.SurfaceRaised;
- private static readonly IBrush TealSubtle = NotaPalette.Wash(NotaPalette.Teal, 0x24);
-
- private static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ private const double RailW = 186, TabH = 20, RowH = 66, StatusH = 18;
+ private static readonly string[] TabNames = { "Sample", "Pitch", "Env", "Filter" };
+ private static readonly string[] TabHints = { "start · end · loop · crossfade", "root · transpose · detune · keytrack", "a · d · s · r · vel", "type · cutoff · reso · keytrack" };
public Control Build(DeviceCardContext ctx)
- {
- ctx.SetInstLiveViz(null); // no live graphs — the waveform ticks via the refreshers
- return BuildEditor(ctx.Engine, new TrackSamplerAccess(ctx.Engine, ctx.TrackId), ctx.AddDeviceRefresher);
- }
+ => BuildEditor(ctx.Engine, new TrackSamplerAccess(ctx.Engine, ctx.TrackId), ctx.AddDeviceRefresher, ctx.SetInstLiveViz);
- // The whole editor, reusable for the track Sampler (TrackSamplerAccess) and a rack
- // chain's Sampler (ChainSamplerAccess, in Drum Rack pads / Instrument Rack chains).
- internal static Control BuildEditor(IAudioEngine engine, ISamplerAccess acc, Action<Action> registerTick)
+ // The whole editor, for the track Sampler (TrackSamplerAccess) and a rack chain's
+ // Sampler (ChainSamplerAccess). `registerTick` runs at 60 Hz; `setLiveViz` (track
+ // only) hands the card's refresh to the automation live-follow.
+ internal static Control BuildEditor(IAudioEngine engine, ISamplerAccess acc, Action<Action> registerTick, Action<Action?>? setLiveViz = null)
{
int pc = acc.ParamCount();
var idx = new Dictionary<string, int>();
for (int i = 0; i < pc; i++) idx[acc.ParamId(i)] = i;
- float G(string id) => idx.TryGetValue(id, out var i) ? acc.ParamGet(i) : 0f;
- int GI(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);
- void SetId(string id, double v) { if (idx.TryGetValue(id, out var i)) acc.ParamSet(i, (float)v); }
+ int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;
+ float G(string id) => I(id) is var i and >= 0 ? acc.ParamGet(i) : 0f;
+ void SetP(string id, double v) { if (I(id) is var i and >= 0) acc.ParamSet(i, (float)Math.Clamp(v, 0, 1)); }
+ void Begin(string id) { if (I(id) >= 0) acc.BeginGesture(id); }
+ void End(string id) { if (I(id) >= 0) acc.EndGesture(id); }
+ void Write(string id, double v) { Begin(id); SetP(id, v); End(id); }
+ float Def(string id) => I(id) is var i and >= 0 ? acc.ParamDefault(i) : 0f;
+ int Sel(string id, int n) => SamplerModel.Index(G(id), n);
+ int LoopSel() => SamplerModel.LoopIndex(G("loopmode"), G("reverse"));
var readouts = new List<Action>();
-
- bool hasSample = acc.Info(out long sampleId, out int root) && sampleId != 0;
- if (!hasSample)
- {
- // Empty state: one line in Ink 5, centred, no illustration (almanac § States).
- var prompt = new TextBlock { Text = "Drop a sample here", FontSize = 9, Foreground = NotaPalette.TextTertiary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
- ToolTip.SetTip(prompt, "Drag from the Files tab or the browser");
- return new Border { Background = NotaPalette.BgApp, Child = prompt };
- }
-
- // Sample data: peaks for the waveform + raw mono for zero-crossing snapping.
- float[] raw = Array.Empty<float>(); int ch = 1; long frames = 0; double durSec = 0; double sr = 48000;
- if (engine.TryGetSampleInfo(sampleId, out var sinfo))
+ int tab = 0;
+ Action refresh = () => { };
+ void Refresh() => refresh();
+
+ // ---- the sample ---------------------------------------------------------------
+ bool hasSample = acc.Info(out long sampleId, out int rootv) && sampleId != 0;
+ float[] raw = Array.Empty<float>(); int ch = 1; long frames = 0; double sr = 0, durSec = 0;
+ if (hasSample && engine.TryGetSampleInfo(sampleId, out var sinfo))
{
raw = engine.ReadSample(sampleId); ch = Math.Max(1, sinfo.Channels); frames = sinfo.Frames; sr = sinfo.SampleRate;
durSec = sr > 0 ? frames / sr : 0;
}
- float Mono(long f) { if (f < 0 || f >= frames) return 0; float s = 0; for (int c = 0; c < ch; c++) s += raw[f * ch + c]; return s / ch; }
+ hasSample = hasSample && frames > 1;
+ string sampleName = hasSample ? engine.SampleName(sampleId) : "";
+ var snap = new SamplerModel.Snapshot();
+ var scope = new float[SamplerModel.ScopeLength];
- // ---- waveform + markers + live playhead ----
- var wave = new SamplerWaveform { Height = 84 };
- wave.SetPeaks(BuildPeaks(raw, ch, frames, 600));
- if (durSec > 0) wave.SetDuration(durSec);
- void SyncWave() => wave.SetMarkers(G("start"), G("end"), G("loopstart"), G("loopend"), (int)Math.Round(G("loopmode") * 2));
- wave.StartChanged += f => { SetId("start", f); SyncWave(); };
- wave.EndChanged += f => { SetId("end", f); SyncWave(); };
- wave.LoopStartChanged += f => { SetId("loopstart", f); SyncWave(); };
- wave.LoopEndChanged += f => { SetId("loopend", f); SyncWave(); };
- wave.GestureBegin = () => acc.BeginGesture("start");
- SyncWave();
+ static TextBlock Cap(string t, IBrush? c = null) => new()
+ {
+ Text = t, FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold,
+ LetterSpacing = NotaType.KnobLabelTracking, Foreground = c ?? TextTertiary,
+ VerticalAlignment = VerticalAlignment.Center,
+ };
+ static TextBlock Mono(string t, IBrush? c = null, double fs = 7) => new()
+ {
+ Text = t, FontSize = fs, Foreground = c ?? TextSecondary,
+ VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily,
+ };
- bool IsZeroCross(long c) => c >= 1 && c < frames && ((Mono(c - 1) <= 0 && Mono(c) >= 0) || (Mono(c - 1) >= 0 && Mono(c) <= 0));
- long SnapZero(double p)
+ // ---- shared builders ----------------------------------------------------------
+ Control PKnob(string id, string label, Func<float, string> fmt, double size = NotaSize.KnobSecondary, double cellW = 54,
+ IBrush? arc = null, bool emphasised = false, string? tip = null)
{
- long target = (long)Math.Round(Math.Clamp(p, 0, 1) * (frames - 1));
- if (frames < 2) return target;
- for (long d = 0; d < frames; d++)
+ int pi = I(id);
+ if (pi < 0) return new Panel();
+ var value = new TextBlock { Text = fmt(G(id)), Foreground = TextPrimary };
+ var knob = new Knob(G(id), 1.0) { Accent = true, ArcColor = arc, Default = acc.ParamDefault(pi), Width = size, Height = size };
+ knob.ValueChanged += v => { acc.ParamSet(pi, (float)v); value.Text = fmt((float)v); Refresh(); };
+ knob.GestureBegin += () => Begin(id);
+ knob.GestureEnd += () => End(id);
+ readouts.Add(() =>
{
- if (IsZeroCross(target - d)) return target - d;
- if (IsZeroCross(target + d)) return target + d;
- }
- return target;
+ if (knob.Dragging) return;
+ float v = G(id);
+ if (Math.Abs(v - knob.Value) > 1e-4) knob.Value = v;
+ value.Text = fmt(v);
+ });
+ acc.Learn(knob, pi);
+ var cell = KnobCell(label, knob, value, cellW, emphasised, emphasised ? AccentBright : null);
+ cell.VerticalAlignment = VerticalAlignment.Center;
+ if (tip is not null) ToolTip.SetTip(cell, tip);
+ return cell;
}
- // ---- shared builders ----
- Control Cap(string t, IBrush? c = null) => new TextBlock { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, VerticalAlignment = VerticalAlignment.Center };
- TextBlock MonoTx(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; }
-
- Control Seg(string id, string[] names, double fs = 9, double padX = 6)
+ Border Chips(string[] names, Func<int> cur, Action<int> pick, double padX = 6, double fontSize = 7, string? learnId = null)
{
- int n = names.Length;
- var seg = DeviceCardKit.Segments(names, () => GI(id, n), iv => { SetId(id, n > 1 ? iv / (double)(n - 1) : 0); RefreshAll(); }, out var sync);
+ var seg = Segments(names, cur, iv => { pick(iv); Refresh(); }, out var sync, padX: padX, fontSize: fontSize);
readouts.Add(sync);
+ if (learnId is not null && I(learnId) is var li and >= 0) acc.Learn(seg, li);
return seg;
}
+ Border ParamChips(string id, string[] names, double padX = 6, double fontSize = 7)
+ => Chips(names, () => Sel(id, names.Length), iv => Write(id, iv / (double)(names.Length - 1)), padX, fontSize, id);
- // Loop segmented (Off/Fwd/Ping/Rev) — maps to loopmode + reverse (append-safe).
- Control LoopSeg()
+ Grid Slider(string label, string id, Func<string> text, bool bipolar = false, bool modulation = false, string? tip = null)
{
- var names = new[] { "Off", "Fwd", "Ping", "Rev" }; var arr = new Border[4];
- int Cur() { int lm = (int)Math.Round(G("loopmode") * 2); bool rev = G("reverse") > 0.5f; return lm == 2 ? 2 : lm == 1 ? (rev ? 3 : 1) : 0; }
- void Set(int i) { SetId("loopmode", i == 2 ? 1.0 : i == 0 ? 0.0 : 0.5); SetId("reverse", i == 3 ? 1 : 0); }
- void Hi() { int cur = Cur(); for (int i = 0; i < 4; i++) { bool on = i == cur; arr[i].Background = on ? NotaPalette.Accent : Brushes.Transparent; arr[i].BorderBrush = on ? NotaPalette.Accent : Brushes.Transparent; ((TextBlock)arr[i].Child!).Foreground = on ? NotaPalette.TextOnAccent : MutedC; } }
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };
- for (int i = 0; i < 4; i++) { int iv = i; var c = new Border { CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(7, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = 9, Foreground = MutedC } }; c.PointerPressed += (_, _) => { Set(iv); SyncWave(); RefreshAll(); }; arr[i] = c; row.Children.Add(c); }
- readouts.Add(Hi);
- return new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = row };
+ int pi = I(id);
+ var row = SliderRow(label, () => G(id), v => { SetP(id, v); Refresh(); }, text, out var sync,
+ begin: pi >= 0 ? () => Begin(id) : null,
+ end: pi >= 0 ? () => End(id) : null,
+ reset: pi >= 0 ? () => { Write(id, Def(id)); Refresh(); } : null,
+ bipolar: bipolar, labelWidth: 42, valueWidth: 36, modulation: modulation);
+ row.ColumnSpacing = 6;
+ readouts.Add(sync);
+ if (pi >= 0) acc.Learn(row, pi);
+ if (tip is not null) ToolTip.SetTip(row, tip);
+ return row;
}
- Control OutToggle(string id, string label, bool teal = false)
+ // A raised text button; a latching one turns brass-washed while on.
+ Border Button(string text, Action click, string tip, Func<bool>? on = null, Func<bool>? enabled = null, string? learnId = null)
{
- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(7, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold } };
- void Hi() { bool on = G(id) > 0.5f; b.Background = on ? (teal ? TealSubtle : AmberSubtle) : Brushes.Transparent; b.BorderBrush = on ? (teal ? TealC : Amber) : Border2; ((TextBlock)b.Child!).Foreground = on ? (teal ? TealC : AmberLit) : MutedC; }
- b.PointerPressed += (_, _) => { SetId(id, G(id) > 0.5f ? 0 : 1); RefreshAll(); };
- readouts.Add(Hi);
+ var tb = new TextBlock { Text = text, FontSize = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ var b = new Border
+ {
+ Height = 17, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(8, 0),
+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb, VerticalAlignment = VerticalAlignment.Center,
+ };
+ ToolTip.SetTip(b, tip);
+ void Paint()
+ {
+ bool lit = on?.Invoke() ?? false, ok = enabled?.Invoke() ?? true;
+ b.Background = lit ? NotaPalette.AccentSubtle : NotaPalette.SurfaceRaised;
+ b.BorderBrush = lit ? NotaPalette.BorderBrass : BorderDef;
+ tb.Foreground = !ok ? TextTertiary : lit ? AccentBright : NotaPalette.TextStrong;
+ b.Cursor = ok ? new Cursor(StandardCursorType.Hand) : Cursor.Default;
+ }
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed || !(enabled?.Invoke() ?? true)) return;
+ click(); Paint(); Refresh(); e.Handled = true;
+ };
+ readouts.Add(Paint);
+ Paint();
+ if (learnId is not null && I(learnId) is var li and >= 0) acc.Learn(b, li);
return b;
}
- Control ActionBtn(string label, Action click)
+ static Grid Row(double spacing, params (Control C, string W)[] cols)
{
- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), BorderBrush = NotaPalette.BorderStrong, Background = RowLit, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 9, Foreground = NotaPalette.TextSecondary } };
- b.PointerPressed += (_, _) => click();
- return b;
+ var g = new Grid { ColumnSpacing = spacing, VerticalAlignment = VerticalAlignment.Stretch };
+ for (int i = 0; i < cols.Length; i++)
+ {
+ g.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Parse(cols[i].W)));
+ cols[i].C.VerticalAlignment = VerticalAlignment.Center;
+ Grid.SetColumn(cols[i].C, i); g.Children.Add(cols[i].C);
+ }
+ return g;
}
-
- Control KUnit(string id, string name, Func<double, string> fmt, bool mod = false, double size = 36, double cellW = 58)
+ static StackPanel Labeled(string cap, Control c) => new()
{
- if (!idx.TryGetValue(id, out var i)) return new Panel();
- var value = MonoTx(fmt(G(id)), TxtC, 9); value.HorizontalAlignment = HorizontalAlignment.Center;
- var knob = new Knob(G(id), 1.0) { Accent = true, ArcColor = mod ? Teal : null, Default = acc.ParamDefault(i), Width = size, Height = size };
- knob.ValueChanged += v => { acc.ParamSet(i, (float)v); value.Text = fmt(v); RefreshAll(); };
- knob.GestureBegin += () => acc.BeginGesture(id);
- knob.GestureEnd += () => acc.EndGesture(id);
- readouts.Add(() => { if (!knob.Dragging) { double v = G(id); if (Math.Abs(v - knob.Value) > 1e-3) knob.Value = v; value.Text = fmt(v); } });
- return KnobCell(name, knob, value, cellW);
- }
-
- Control HSlider(string id, string label, Func<double, string> fmt, bool bipolar = false, double lw = 44, double vw = 52)
+ Spacing = 4, VerticalAlignment = VerticalAlignment.Center,
+ Children = { Cap(cap), c },
+ };
+ // Dims a subtree when `inactive` flips (it stays editable) — only on change.
+ void DimWhen(Control c, Func<bool> inactive)
{
- if (!idx.TryGetValue(id, out var pi)) return new Panel();
- var row = DeviceCardKit.SliderRow(label, () => G(id), n => acc.ParamSet(pi, (float)n), () => fmt(G(id)), out var sync,
- begin: () => { acc.BeginGesture(id); RefreshAll(); }, end: () => acc.EndGesture(id),
- bipolar: bipolar, labelWidth: lw, valueWidth: vw);
- readouts.Add(sync);
- return row;
+ bool? was = null;
+ readouts.Add(() => { bool now = inactive(); if (was != now) { Inactive.Set(c, now, interactive: true); was = now; } });
}
- int rootv = root;
- Control RootStepper()
+ // ---- words --------------------------------------------------------------------
+ string St(float v) => NotaNum.Unit(SamplerModel.TransposeSt(v), "+0;−0;0", "st");
+ string Cents(float v) => NotaNum.Unit(SamplerModel.DetuneCents(v), "+0;−0;0", "c");
+ string DbLin(float v) => NotaNum.Db(SamplerModel.VolumeDb(v), floor: -80);
+ string PanText(float v) { double p = SamplerModel.PanSigned(v); return Math.Abs(p) < 0.015 ? "C" : (p < 0 ? "L" : "R") + NotaNum.Str(Math.Abs(p) * 100, "0"); }
+ string GlideText(float v) { double s = SamplerModel.GlideSec(v); return s <= 0 ? NotaNum.Unit(0, "0", "ms") : NotaNum.Time(s); }
+ string Oct(float v) => NotaNum.Unit(SamplerModel.EnvOctaves(v), "+0.0;−0.0;0.0", "oct");
+ string WindowText() => $"{NotaNum.Str(G("start") * durSec, "0.00")} → {NotaNum.Unit(G("end") * durSec, "0.00", "s")}";
+ string LoopWord()
{
- var lbl = MonoTx(NoteName(rootv), TxtC, 10); lbl.Width = 26; lbl.TextAlignment = TextAlignment.Center;
- Border Btn(string t, int d) { var b = new Border { Width = 16, Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = NotaPalette.BorderStrong, Background = RowLit, Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = t, FontSize = 9, Foreground = NotaPalette.TextSecondary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center } }; b.PointerPressed += (_, _) => { rootv = Math.Clamp(rootv + d, 0, 127); acc.SetRoot(rootv); lbl.Text = NoteName(rootv); RefreshAll(); }; return b; }
- return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { Btn("−", -1), lbl, Btn("+", +1) } };
+ int l = LoopSel();
+ return l switch
+ {
+ 0 => "no loop",
+ _ => $"{SamplerModel.LoopNames[l].ToLowerInvariant()} {NotaNum.Str(G("loopstart") * durSec, "0.00")} – {NotaNum.Unit(G("loopend") * durSec, "0.00", "s")}",
+ };
}
- // ---- formatters (real units) ----
- string Db(double v) => v <= 0.0011 ? "−∞\u2009dB" : $"{20 * Math.Log10(v):+0.0;−0.0;0.0}\u2009dB";
- string Pan(double v) { double p = (v - 0.5) * 2; return Math.Abs(p) < 0.03 ? "C" : p < 0 ? $"L{Math.Abs(p) * 100:0}" : $"R{p * 100:0}"; }
- string Hz(double v) { double fc = Exp(v, 20, 20000); return fc >= 1000 ? $"{fc / 1000:0.0}\u2009k" : $"{fc:0}\u2009Hz"; }
- string St(double v) => $"{(v - 0.5) * 48:+0;−0;0}\u2009st";
- string Cent(double v) => $"{(v - 0.5) * 100:+0;−0;0}\u2009c";
- string Ms(double v, double lo, double hi) { double s = Exp(v, lo, hi); return s < 1 ? $"{s * 1000:0}\u2009ms" : $"{s:0.00}\u2009s"; }
- string SusDb(double v) => v <= 0.0011 ? "−∞" : $"{20 * Math.Log10(v):0.0}\u2009dB";
- string Pct(double v) => $"{v * 100:0}\u2009%";
-
- // ================= LIVE strip =================
- var voiceSeg = Seg("voicemode", new[] { "Poly 16", "Mono", "Choke" }, 9, 7);
- var live = new Border { Height = 34, Background = HdrBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new DockPanel { LastChildFill = false, Margin = new Thickness(9, 0), Children = {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center, Children = {
- Cap("LIVE", MutedC),
- HSlider("volume", "VOLUME", Db, lw: 26, vw: 52),
- HSlider("pan", "PAN", Pan, bipolar: true, lw: 26, vw: 26),
- HSlider("cutoff", "CUTOFF", Hz, lw: 40, vw: 52) } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right, Children = {
- Cap("VOICES"), voiceSeg } } } } };
-
- // ================= tab rail =================
- var tabNames = new[] { "Sample", "Pitch", "Env", "Filter" };
- var tabBtns = new Border[tabNames.Length];
- var bodyContent = new ContentControl { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch };
- Control[] pages = new Control[tabNames.Length];
- void SelectTab(int t)
+ // ================= Sample tab =================
+ var wave = new SamplerWaveView();
+ wave.SetEmpty("Drop a sample here");
+ if (hasSample) wave.SetPeaks(SamplerModel.Peaks(raw, ch, 1200), durSec);
+ ToolTip.SetTip(wave, hasSample ? "Drag Start / End (and the loop markers when looping) · double-click a marker to reset it" : "Drag a sample from the Files tab or the browser");
+ wave.DragBegin += hnd => Begin(SamplerWaveView.HandleId(hnd));
+ wave.DragEnd += hnd => End(SamplerWaveView.HandleId(hnd));
+ wave.Moved += (hnd, f) => { SetP(SamplerWaveView.HandleId(hnd), f); Refresh(); };
+ wave.ResetHandle += hnd => { var id = SamplerWaveView.HandleId(hnd); Write(id, Def(id)); Refresh(); };
+ readouts.Add(() => wave.Set(G("start"), G("end"), G("loopstart"), G("loopend"), LoopSel(), SamplerModel.CrossfadeSec(G("loopxfade")),
+ hasSample ? $"{NotaNum.Str(sr / 1000, "0.#")} k · {NotaNum.Unit(durSec, "0.00", "s")} · root {SamplerModel.NoteName(rootv)}" : "",
+ hasSample ? LoopWord() : ""));
+
+ var loopSeg = Chips(SamplerModel.LoopNames, LoopSel, iv =>
+ {
+ var (lm, rev) = SamplerModel.LoopValues(iv);
+ Write("loopmode", lm); Write("reverse", rev);
+ }, padX: 7, learnId: "loopmode");
+ ToolTip.SetTip(loopSeg, "Off plays once · Fwd loops · Ping bounces · Rev loops backwards");
+ var xfadeKnob = PKnob("loopxfade", "CROSSFADE", v => NotaNum.Time(SamplerModel.CrossfadeSec(v)), tip: "Blends the loop's end into its start (forward loops)");
+ DimWhen(xfadeKnob, () => LoopSel() != 1);
+ var gainKnob = PKnob("gain", "GAIN", v => NotaNum.Db(SamplerModel.GainDb(v), signed: true), tip: "The sample's level before the envelope");
+ void SnapAll()
{
- bodyContent.Content = pages[t];
- for (int i = 0; i < tabBtns.Length; i++) { bool on = i == t; tabBtns[i].Background = on ? RowLit : Brushes.Transparent; tabBtns[i].BorderBrush = on ? Amber : Brushes.Transparent; ((TextBlock)tabBtns[i].Child!).Foreground = on ? TxtC : MutedC; }
+ foreach (var id in new[] { "start", "end", "loopstart", "loopend" }) Write(id, SamplerModel.SnapZero(raw, ch, frames, G(id)));
}
- var railCol = new StackPanel { Spacing = 2 };
- for (int i = 0; i < tabNames.Length; i++) { int ti = i; var b = new Border { Height = 20, CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 0), BorderThickness = new Thickness(2, 0, 0, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = tabNames[i], FontSize = 9, FontWeight = FontWeight.Medium, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center } }; b.PointerPressed += (_, _) => SelectTab(ti); tabBtns[i] = b; railCol.Children.Add(b); }
- var tabRail = new Border { Width = 70, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(5), Child = railCol };
-
- // ================= Sample tab =================
- var loopReadout = MonoTx("", AmberLit, 8);
- DockPanel.SetDock(loopReadout, Dock.Right);
- var fileHdr = new DockPanel { LastChildFill = false, Height = 12, Children = {
- MonoTx(sinfoLabel(sr, durSec, rootv), MutedC, 8), loopReadout } };
- readouts.Add(() => loopReadout.Text = LoopReadout(G("loopstart"), G("loopend"), durSec, (int)Math.Round(G("loopmode") * 2)));
- var startFoot = MonoTx("start 0.00", GreenC, 8);
- var endFoot = MonoTx("end 0.00", RedC, 8); endFoot.HorizontalAlignment = HorizontalAlignment.Right;
- readouts.Add(() => { startFoot.Text = $"start {G("start") * durSec:0.00}"; endFoot.Text = $"end {G("end") * durSec:0.00}"; });
- var waveFoot = new DockPanel { LastChildFill = false, Height = 11, Children = { startFoot, endFoot } };
- DockPanel.SetDock(endFoot, Dock.Right);
- var waveIsland = new Border { Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 4), Child =
- new DockPanel { LastChildFill = true, Children = { WithDock(fileHdr, Dock.Top), WithDock(waveFoot, Dock.Bottom), wave } } };
- var loopRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Height = 40, Children = {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("LOOP"), LoopSeg() } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Width = 150, Children = { Cap("CROSSFADE"), HSlider("loopxfade", "", v => $"{v * 200:0}\u2009ms", lw: 0, vw: 46) } },
- ActionSnap() } };
- Control ActionSnap()
+ void Trim()
{
- var b = ActionBtn("Snap zero", () => { foreach (var id in new[] { "start", "end", "loopstart", "loopend" }) SetId(id, SnapZero(G(id)) / (double)Math.Max(1, frames - 1)); SyncWave(); RefreshAll(); });
- ((Border)b).HorizontalAlignment = HorizontalAlignment.Right;
- return new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Children = { b } };
+ if (SamplerModel.TrimSilence(raw, ch, frames) is not { } t) return;
+ Write("start", t.Start); Write("end", t.End);
+ if (G("loopstart") < t.Start) Write("loopstart", t.Start);
+ if (G("loopend") > t.End) Write("loopend", t.End);
}
- var sampleCenter = new DockPanel { LastChildFill = true, Margin = new Thickness(8, 7), Children = { WithDock(loopRow, Dock.Bottom), waveIsland } };
- var ampRail = BuildAmpRail(G, OutToggle, readouts, Ms, SusDb);
- DockPanel.SetDock(ampRail, Dock.Right);
- pages[0] = new DockPanel { LastChildFill = true, Children = { ampRail, sampleCenter } };
+ var snapBtn = Button("Snap to zero", SnapAll, "Move Start, End and the loop to the nearest zero crossing — no clicks", enabled: () => hasSample);
+ var trimBtn = Button("Trim silence", Trim, "Move Start and End to where the sound begins and fades out (−48\u2009dB)", enabled: () => hasSample);
+ snapBtn.HorizontalAlignment = HorizontalAlignment.Stretch; trimBtn.HorizontalAlignment = HorizontalAlignment.Stretch;
+ var sampleBtns = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { snapBtn, trimBtn } };
+ var sampleRow = Row(14, (Labeled("LOOP", loopSeg), "Auto"), (xfadeKnob, "Auto"), (gainKnob, "Auto"), (new Panel(), "*"), (sampleBtns, "Auto"));
// ================= Pitch tab =================
- var keys = new SamplerKeys();
- readouts.Add(() => keys.Set(rootv, (G("transpose") - 0.5) * 48));
- var pitchKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = {
- KUnit("transpose", "TRANSPOSE", St), KUnit("detune", "DETUNE", Cent, mod: true) } };
- var rootRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("ROOT"), RootStepper() } };
- pages[1] = new DockPanel { LastChildFill = true, Margin = new Thickness(10, 8), Children = {
- WithDock(new Border { Height = 40, Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(4), Child = keys, Margin = new Thickness(0, 6, 0, 0) }, Dock.Bottom),
- WithDock(rootRow, Dock.Bottom),
- pitchKnobs } };
+ var keys = new SamplerKeysView();
+ ToolTip.SetTip(keys, "Click a key to make it the root — the key that plays the sample as recorded");
+ keys.RootPicked += k => { rootv = k; acc.SetRoot(k); Refresh(); };
+ int NaturalKey()
+ {
+ // The key that plays the sample at its own pitch: root − (transpose + detune) / keytrack.
+ double tr = G("pitchtrack");
+ if (tr < 0.01) return -1;
+ double off = SamplerModel.TransposeSt(G("transpose")) + SamplerModel.DetuneCents(G("detune")) / 100.0;
+ return (int)Math.Round(rootv - off / tr);
+ }
+ readouts.Add(() => keys.Set(rootv, NaturalKey(), snap.Live ? snap.Note : -1, G("pitchtrack"), "the key sets the playback speed"));
+ var rootText = Mono(SamplerModel.NoteName(rootv), TextPrimary, 9);
+ rootText.HorizontalAlignment = HorizontalAlignment.Center;
+ readouts.Add(() => rootText.Text = SamplerModel.NoteName(rootv));
+ Border StepBtn(GlyphKind g, int d, string tip)
+ {
+ var b = new Border
+ {
+ Width = 16, Height = 17, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1),
+ BorderBrush = BorderDef, Background = NotaPalette.SurfaceRaised, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new Glyph(g, 7) { Foreground = NotaPalette.TextStrong, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },
+ };
+ ToolTip.SetTip(b, tip);
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ rootv = Math.Clamp(rootv + d, 0, 127); acc.SetRoot(rootv); Refresh(); e.Handled = true;
+ };
+ return b;
+ }
+ var rootBox = new Border
+ {
+ Height = 17, MinWidth = 40, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderDef,
+ Background = NotaPalette.BgSunken, Child = rootText,
+ };
+ rootBox.PointerWheelChanged += (_, e) => { rootv = Math.Clamp(rootv + (e.Delta.Y > 0 ? 1 : -1), 0, 127); acc.SetRoot(rootv); Refresh(); e.Handled = true; };
+ ToolTip.SetTip(rootBox, "The root note — scroll to step it");
+ var rootStepper = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { StepBtn(GlyphKind.Minus, -1, "Root a semitone down"), rootBox, StepBtn(GlyphKind.Plus, +1, "Root a semitone up") } };
+ int detected = SamplerModel.DetectRoot(sampleName);
+ var detectBtn = Button("Detect from file name", () => { if (detected >= 0) { rootv = detected; acc.SetRoot(detected); } },
+ detected >= 0 ? $"\"{sampleName}\" names {SamplerModel.NoteName(detected)} — make it the root"
+ : sampleName.Length > 0 ? $"\"{sampleName}\" names no note (e.g. C4, F#3, Eb2)" : "The sample's file name isn't known",
+ on: () => detected >= 0 && detected == rootv, enabled: () => detected >= 0);
+ var pitchRow = Row(16,
+ (PKnob("transpose", "TRANSPOSE", St, tip: "Shift every note, ±24 semitones"), "Auto"),
+ (PKnob("detune", "DETUNE", Cents, arc: Teal, tip: "Fine tune, ±50 cents"), "Auto"),
+ (PKnob("pitchtrack", "KEYTRACK", v => NotaNum.Pct(v), tip: "How far the key moves the pitch — 100\u2009% chromatic, 0\u2009% every key plays the root"), "Auto"),
+ (Labeled("ROOT", rootStepper), "Auto"),
+ (new Panel(), "*"),
+ (detectBtn, "Auto"));
// ================= Env tab =================
- var envBig = new SamplerEnv { Height = 96 };
- readouts.Add(() => envBig.Set(G("attack"), G("decay"), G("sustain"), G("release")));
- var envKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, HorizontalAlignment = HorizontalAlignment.Center, Children = {
- KUnit("attack", "ATTACK", v => Ms(v, 0.0005, 4.0)), KUnit("decay", "DECAY", v => Ms(v, 0.002, 6.0)),
- KUnit("sustain", "SUSTAIN", SusDb), KUnit("release", "RELEASE", v => Ms(v, 0.002, 6.0)) } };
- pages[2] = new DockPanel { LastChildFill = true, Margin = new Thickness(10, 8), Children = {
- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 6, 0, 0), [DockPanel.DockProperty] = Dock.Bottom, Children = { envKnobs, OutToggle("velamount", "VEL→VOL", teal: true) } }, Dock.Bottom),
- new Border { Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(6), Child = envBig } } };
+ var env = new SamplerEnvView();
+ ToolTip.SetTip(env, "Drag the nodes: attack, decay and sustain (up / down), release · Shift for fine steps · double-click resets");
+ env.DragBegin += Begin;
+ env.DragEnd += End;
+ env.Changed += (id, v) => { SetP(id, v); Refresh(); };
+ env.Reset += id => { Write(id, Def(id)); Refresh(); };
+ string EnvTl() => $"{NotaNum.Time(SamplerModel.AttackSec(G("attack")))} · {NotaNum.Time(SamplerModel.DecaySec(G("decay")))} · {DbLin(G("sustain"))} · {NotaNum.Time(SamplerModel.ReleaseSec(G("release")))}";
+ readouts.Add(() => env.Set(G("attack"), G("decay"), G("sustain"), G("release"), snap, EnvTl(),
+ hasSample ? NotaNum.Unit((G("end") - G("start")) * durSec, "0.00", "s") : ""));
+ float lastVel = G("velamount") > 0.005f ? G("velamount") : 1f;
+ var velSwitch = Switch("", () => G("velamount") > 0.005f, () =>
+ {
+ if (G("velamount") > 0.005f) { lastVel = G("velamount"); Write("velamount", 0); }
+ else Write("velamount", lastVel);
+ Refresh();
+ }, out var velSync);
+ readouts.Add(velSync);
+ if (I("velamount") is var vli and >= 0) acc.Learn(velSwitch, vli);
+ var velWord = Mono("", TextSecondary, 8);
+ readouts.Add(() => velWord.Text = G("velamount") > 0.005f ? NotaNum.Pct(G("velamount")) : "off");
+ var velBlock = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { Cap("VEL → VOL"), velSwitch, velWord } };
+ ToolTip.SetTip(velBlock, "Velocity sets the level — the amount is the rail's VEL → VOL");
+ var envRow = Row(16,
+ (PKnob("attack", "ATTACK", v => NotaNum.Time(SamplerModel.AttackSec(v))), "Auto"),
+ (PKnob("decay", "DECAY", v => NotaNum.Time(SamplerModel.DecaySec(v))), "Auto"),
+ (PKnob("sustain", "SUSTAIN", DbLin, NotaSize.KnobMain, 58), "Auto"),
+ (PKnob("release", "RELEASE", v => NotaNum.Time(SamplerModel.ReleaseSec(v))), "Auto"),
+ (new Panel(), "*"),
+ (velBlock, "Auto"));
// ================= Filter tab =================
- var filtViz = new SamplerFilter { Height = 92 };
- readouts.Add(() => filtViz.Set(GI("filtertype", 4), G("cutoff"), G("resonance")));
- var filtKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, HorizontalAlignment = HorizontalAlignment.Center, Children = {
- KUnit("cutoff", "CUTOFF", Hz), KUnit("resonance", "RESO", Pct), KUnit("keytrack", "KEYTRACK", Pct, mod: true) } };
- pages[3] = new DockPanel { LastChildFill = true, Margin = new Thickness(10, 8), Children = {
- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, HorizontalAlignment = HorizontalAlignment.Center, Children = { Cap("TYPE"), Seg("filtertype", new[] { "Off", "LP", "HP", "BP" }, 9, 8) } }, Dock.Top),
- WithDock(filtKnobs, Dock.Bottom),
- new Border { Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(6), Margin = new Thickness(0, 5), Child = filtViz } } };
-
- // ================= assemble =================
- DockPanel.SetDock(tabRail, Dock.Left);
- var body = new DockPanel { LastChildFill = true, Children = { tabRail, bodyContent } };
- DockPanel.SetDock(live, Dock.Top);
- var root2 = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };
-
- void RefreshAll() { foreach (var a in readouts) a(); }
- registerTick(() => { wave.SetPlayhead(acc.PlayPosition()); RefreshAll(); });
- SelectTab(0);
- RefreshAll();
- return root2;
- }
-
- // Amp-envelope rail (Sample tab): teal label + mini curve + A/D/S/R readouts + Vel→Vol.
- private static Control BuildAmpRail(Func<string, float> G, Func<string, string, bool, Control> OutToggle, List<Action> readouts,
- Func<double, double, double, string> Ms, Func<double, string> SusDb)
- {
- var env = new SamplerEnv { Height = 42 };
- readouts.Add(() => env.Set(G("attack"), G("decay"), G("sustain"), G("release")));
- Control Row(string label, Func<double> get, Func<double, string> fmt)
+ var filt = new SamplerFilterView();
+ ToolTip.SetTip(filt, "Drag: left / right for the cutoff, up / down for the resonance · Shift for fine steps · double-click resets");
+ filt.DragBegin += () => { Begin("cutoff"); Begin("resonance"); };
+ filt.DragEnd += () => { End("cutoff"); End("resonance"); };
+ filt.Changed += (id, v) => { SetP(id, v); Refresh(); };
+ filt.Reset += () => { Write("cutoff", Def("cutoff")); Write("resonance", Def("resonance")); Refresh(); };
+ string FiltTl()
{
- var v = new TextBlock { FontSize = 9, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right };
- v.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- readouts.Add(() => v.Text = fmt(get()));
- return new DockPanel { LastChildFill = false, Children = { new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center }, v } };
+ int t = Sel("filtertype", 4);
+ if (t == 0) return "off · the sample passes untouched";
+ return $"{SamplerModel.FilterNames[t]} 12\u2009dB/oct · {NotaNum.Hz(SamplerModel.CutoffHz(G("cutoff")))} · reso {NotaNum.Pct(G("resonance"))}";
}
- return new Border { Width = 104, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child =
- new DockPanel { LastChildFill = false, Children = {
- WithDock(new StackPanel { Spacing = 5, Children = {
- new TextBlock { Text = "AMP ENV", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TealC },
- new Border { Height = 42, Background = Inset, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(2), Child = env },
- Row("ATTACK", () => G("attack"), v => Ms(v, 0.0005, 4.0)),
- Row("DECAY", () => G("decay"), v => Ms(v, 0.002, 6.0)),
- Row("SUSTAIN", () => G("sustain"), SusDb),
- Row("RELEASE", () => G("release"), v => Ms(v, 0.002, 6.0)) } }, Dock.Top),
- WithDock(OutToggle("velamount", "VEL → VOL", true), Dock.Bottom) } } };
- }
-
- private static Control WithDock(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
-
- private static string sinfoLabel(double sr, double dur, int root) => $"{sr / 1000:0.#} k · {dur:0.00}\u2009s · root {NoteName(root)}";
-
- private static string LoopReadout(double ls, double le, double dur, int mode) => mode <= 0 ? "no loop" : $"loop {ls * dur:0.00} – {le * dur:0.00}\u2009s";
-
- // Downsample interleaved float samples to min/max pairs per bucket (mono sum).
- private static float[] BuildPeaks(float[] samples, int channels, long frames, int buckets)
- {
- var peaks = new float[buckets * 2];
- if (samples.Length == 0 || channels <= 0) return peaks;
- long fr = samples.Length / channels;
- for (int b = 0; b < buckets; b++)
+ readouts.Add(() => filt.Set(Sel("filtertype", 4), G("cutoff"), G("resonance"), snap.Live ? snap.CutoffHz : -1, FiltTl()));
+ var typeSeg = ParamChips("filtertype", SamplerModel.FilterNames, padX: 7);
+ ToolTip.SetTip(typeSeg, "Off · low-pass · high-pass · band-pass (12\u2009dB/oct)");
+ var cutKnob = PKnob("cutoff", "CUTOFF", v => NotaNum.Hz(SamplerModel.CutoffHz(v)), NotaSize.KnobMain, 58, emphasised: true);
+ var resoKnob = PKnob("resonance", "RESO", v => NotaNum.Pct(v));
+ var ktKnob = PKnob("keytrack", "KEYTRACK", v => NotaNum.Pct(v), arc: Teal, tip: "The cutoff follows the key, 0 … 100\u2009%");
+ var envBtn = Button("Env → Cutoff", () => Write("envcutoff", G("envcutoff") >= 0.5f ? 0 : 1),
+ "Let the amp envelope open (or close) the filter — the depth is ENV", on: () => G("envcutoff") >= 0.5f, learnId: "envcutoff");
+ var envAmt = PKnob("envamount", "ENV", Oct, arc: Teal, tip: "How far the envelope moves the cutoff, ±6 octaves");
+ var filterBody = new[] { cutKnob, resoKnob, ktKnob };
+ foreach (var c in filterBody) DimWhen(c, () => Sel("filtertype", 4) == 0);
+ DimWhen(envAmt, () => Sel("filtertype", 4) == 0 || G("envcutoff") < 0.5f);
+ var filterRow = Row(14, (Labeled("TYPE", typeSeg), "Auto"), (cutKnob, "Auto"), (resoKnob, "Auto"), (ktKnob, "Auto"),
+ (new Panel(), "*"), (envBtn, "Auto"), (envAmt, "Auto"));
+
+ // ---- the tab panel ------------------------------------------------------------
+ var views = new Control[] { wave, keys, env, filt };
+ var rows = new Control[] { sampleRow, pitchRow, envRow, filterRow };
+ var pages = new Control[views.Length];
+ for (int i = 0; i < views.Length; i++)
{
- long a = b * fr / buckets, e = (b + 1) * fr / buckets;
- if (e <= a) e = Math.Min(fr, a + 1);
- float mn = 1f, mx = -1f;
- for (long f = a; f < e; f++) { float s = 0; for (int c = 0; c < channels; c++) s += samples[f * channels + c]; s /= channels; if (s < mn) mn = s; if (s > mx) mx = s; }
- if (mn > mx) { mn = mx = 0; }
- peaks[b * 2] = mn; peaks[b * 2 + 1] = mx;
+ var rowHost = new Border
+ {
+ Height = RowH, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0),
+ Padding = new Thickness(0, 3, 0, 0), Child = rows[i],
+ };
+ var page = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 5, Margin = new Thickness(7, 5, 7, 0) };
+ page.Children.Add(views[i]);
+ Grid.SetRow(rowHost, 1); page.Children.Add(rowHost);
+ pages[i] = page;
}
- return peaks;
- }
-}
-
-// ---- amp-envelope schematic (ADSR from normalized param values) ----
-internal sealed class SamplerEnv : Control
-{
- private static readonly IBrush Teal = NotaPalette.Teal;
- private static readonly IBrush TealFill = NotaPalette.Wash(NotaPalette.Teal, 0x1F);
- private double _a, _d, _s = 1, _r;
- public void Set(double a, double d, double s, double r) { _a = a; _d = d; _s = s; _r = r; InvalidateVisual(); }
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height; if (w <= 2 || h <= 2) return;
- double pad = 2, x0 = pad, x1 = w - pad, top = pad, bot = h - pad;
- double aw = (0.05 + 0.30 * _a) * (x1 - x0), dw = (0.05 + 0.30 * _d) * (x1 - x0), rw = (0.05 + 0.30 * _r) * (x1 - x0);
- double sy = top + (1 - _s) * (bot - top);
- double pA = x0 + aw, pD = pA + dw, pR = x1 - rw;
- if (pR < pD) pR = pD;
- var pts = new[] { new Point(x0, bot), new Point(pA, top), new Point(pD, sy), new Point(pR, sy), new Point(x1, bot) };
- var fill = new StreamGeometry();
- using (var g = fill.Open()) { g.BeginFigure(new Point(x0, bot), true); foreach (var p in pts) g.LineTo(p); g.EndFigure(true); }
- ctx.DrawGeometry(TealFill, null, fill);
- var pen = new Pen(Teal, 1.5, lineJoin: PenLineJoin.Round);
- for (int i = 1; i < pts.Length; i++) ctx.DrawLine(pen, pts[i - 1], pts[i]);
- }
-}
-
-// ---- filter magnitude response schematic ----
-internal sealed class SamplerFilter : Control
-{
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush Fill = NotaPalette.Wash(NotaPalette.Accent, 0x1C);
- private static readonly IBrush Grid = NotaPalette.Wash(NotaPalette.BorderStrong, 0x40);
- private int _type; private double _cut = 1, _reso;
- public void Set(int type, double cut, double reso) { _type = type; _cut = cut; _reso = reso; InvalidateVisual(); }
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height; if (w <= 2 || h <= 2) return;
- for (int i = 1; i < 4; i++) { double gx = i / 4.0 * w; ctx.DrawLine(new Pen(Grid, 1), new Point(gx, 0), new Point(gx, h)); }
- double cx = Math.Clamp(_cut, 0.02, 0.98) * w, mid = h * 0.55, peak = mid - (h * 0.42) * (0.3 + _reso);
- var pts = new List<Point>();
- for (int i = 0; i <= 60; i++)
+ var tabCells = new Border[TabNames.Length];
+ var tabTexts = new TextBlock[TabNames.Length];
+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };
+ Action showTab = () => { };
+ for (int i = 0; i < TabNames.Length; i++)
+ {
+ int iv = i;
+ var tb = new TextBlock { Text = TabNames[i], FontSize = NotaType.DeviceSection, VerticalAlignment = VerticalAlignment.Center };
+ var cell = new Border { Padding = new Thickness(7, 0), BorderThickness = new Thickness(0, 0, 0, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
+ cell.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(cell).Properties.IsLeftButtonPressed) return;
+ tab = iv; showTab(); e.Handled = true;
+ };
+ tabCells[i] = cell; tabTexts[i] = tb; tabRow.Children.Add(cell);
+ }
+ var hint = Mono("", TextTertiary);
+ hint.HorizontalAlignment = HorizontalAlignment.Right; hint.Margin = new Thickness(0, 0, 8, 0);
+ var tabStrip = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ tabStrip.Children.Add(tabRow);
+ Grid.SetColumn(hint, 1); tabStrip.Children.Add(hint);
+ var tabHost = new Panel();
+ foreach (var p in pages) tabHost.Children.Add(p);
+ var tabGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ tabGrid.Children.Add(HeaderStrip(tabStrip));
+ Grid.SetRow(tabHost, 1); tabGrid.Children.Add(tabHost);
+ var tabPanel = SectionBox(tabGrid);
+
+ // ---- the rail · voices and output -----------------------------------------------
+ var voiceSeg = ParamChips("voicemode", SamplerModel.VoiceNames, padX: 5);
+ ToolTip.SetTip(voiceSeg, "Poly: 16 voices · Mono: one at a time (legato with Glide) · Choke: a new note cuts the ringing ones");
+ var railHead = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*"), Margin = new Thickness(8, 0) };
+ var railCap = Cap("VOICES"); railCap.LetterSpacing = NotaType.SectionLabelTracking;
+ railHead.Children.Add(railCap);
+ voiceSeg.HorizontalAlignment = HorizontalAlignment.Right; voiceSeg.VerticalAlignment = VerticalAlignment.Center;
+ Grid.SetColumn(voiceSeg, 1); railHead.Children.Add(voiceSeg);
+
+ var sliders = new StackPanel
+ {
+ Spacing = 6,
+ Children =
+ {
+ Slider("VOLUME", "volume", () => DbLin(G("volume")), tip: "The voices' level"),
+ Slider("PAN", "pan", () => PanText(G("pan")), bipolar: true),
+ Slider("GLIDE", "glide", () => GlideText(G("glide")), tip: "Slide from the last note — in Mono, legato: no retrigger"),
+ },
+ };
+ var outKnob = PKnob("output", "OUTPUT", v => NotaNum.Pct(v), NotaSize.KnobMain, 50, tip: "The level after everything");
+ var velKnob = PKnob("velamount", "VEL → VOL", v => NotaNum.Pct(v), cellW: 50, arc: Teal, tip: "How much velocity sets the level");
+
+ Control meterBlock;
+ if (acc.TryMeter(out _))
+ {
+ var meter = new MeterBar { VerticalAlignment = VerticalAlignment.Stretch, Width = MeterScale.StereoWidth };
+ registerTick(() => { if (acc.TryMeter(out var m)) meter.Push(m); });
+ var meterScale = new Grid { VerticalAlignment = VerticalAlignment.Stretch, RowDefinitions = new RowDefinitions(string.Join(",", ScaleRows(0, -12, -48))) };
+ for (int i = 0; i < 3; i++)
+ {
+ var c = Mono(i == 0 ? "0" : i == 1 ? "−12" : "−48", NotaPalette.TextAxis, NotaType.Axis);
+ Grid.SetRow(c, i * 2 + 1); meterScale.Children.Add(c);
+ }
+ var mg = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 4, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 2, 0, 2) };
+ mg.Children.Add(meter);
+ Grid.SetColumn(meterScale, 1); mg.Children.Add(meterScale);
+ meterBlock = mg;
+ }
+ else meterBlock = new Panel();
+ var outRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 4 };
+ outRow.Children.Add(outKnob);
+ Grid.SetColumn(velKnob, 1); outRow.Children.Add(velKnob);
+ Grid.SetColumn(meterBlock, 2); outRow.Children.Add(meterBlock);
+ var outHost = new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = outRow };
+
+ var railBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 6, Margin = new Thickness(8, 6, 8, 5) };
+ railBody.Children.Add(sliders);
+ Grid.SetRow(outHost, 1); railBody.Children.Add(outHost);
+ var railGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ railGrid.Children.Add(HeaderStrip(railHead));
+ Grid.SetRow(railBody, 1); railGrid.Children.Add(railBody);
+ var rail = SectionBox(railGrid);
+ rail.Width = RailW;
+
+ // ---- the status line ----------------------------------------------------------
+ var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = Mono("", TextSecondary, 8);
+ string EnvWord()
+ {
+ double a = SamplerModel.AttackSec(G("attack")), s = G("sustain"), rel = SamplerModel.ReleaseSec(G("release"));
+ if (s < 0.05) return "a pluck — it decays to silence while held";
+ if (a < 0.01 && s > 0.89 && rel < 0.05) return "almost a gate — the sample is heard whole";
+ if (a > 0.3) return "a slow swell";
+ if (rel > 1.0) return "a long tail after release";
+ return "held at the sustain level";
+ }
+ string Summary()
+ {
+ if (!hasSample) return "No sample · drop one from the Files tab or the browser";
+ switch (tab)
+ {
+ case 0:
+ {
+ string name = sampleName.Length > 0 ? sampleName + " · " : "";
+ int l = LoopSel();
+ string loop = l == 0 ? "loop off, crossfade not applied"
+ : l == 1 ? $"{LoopWord()} · crossfade {NotaNum.Time(SamplerModel.CrossfadeSec(G("loopxfade")))}"
+ : $"{LoopWord()} · no crossfade";
+ string gain = Math.Abs(SamplerModel.GainDb(G("gain"))) > 0.05 ? $" · gain {NotaNum.Db(SamplerModel.GainDb(G("gain")), signed: true)}" : "";
+ return $"{name}{WindowText()} · {loop}{gain}";
+ }
+ case 1:
+ {
+ int nat = NaturalKey();
+ string tail = nat == rootv ? "the sample plays at its own pitch on the root"
+ : nat < 0 ? "every key plays the same pitch"
+ : $"{SamplerModel.NoteName(nat)} plays the sample at its own pitch";
+ return $"Root {SamplerModel.NoteName(rootv)} · transpose {St(G("transpose"))} · detune {Cents(G("detune"))} · keytrack {NotaNum.Pct(G("pitchtrack"))} — {tail}";
+ }
+ case 2:
+ return $"Env {EnvTl()} — {EnvWord()}"
+ + (G("velamount") > 0.005f ? $" · velocity {NotaNum.Pct(G("velamount"))}" : " · velocity off");
+ default:
+ {
+ int t = Sel("filtertype", 4);
+ if (t == 0) return "Filter off — the sample passes untouched";
+ string kt = G("keytrack") > 0.005f ? $"keytrack {NotaNum.Pct(G("keytrack"))}" : "keytrack off";
+ string ev = G("envcutoff") >= 0.5f ? $" · env {Oct(G("envamount"))}" : "";
+ string live = snap.Live && snap.CutoffHz > 0 ? $" · now {NotaNum.Hz(snap.CutoffHz)}" : "";
+ return $"Filter {SamplerModel.FilterNames[t]} · cutoff {NotaNum.Hz(SamplerModel.CutoffHz(G("cutoff")))} · reso {NotaNum.Pct(G("resonance"))} · {kt}{ev}{live}";
+ }
+ }
+ }
+ var statusBar = new Grid { Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };
+ statusBar.Children.Add(status);
+ Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);
+ var statusHost = new Border
+ {
+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0),
+ Background = NotaPalette.SurfaceAbyss, Padding = new Thickness(8, 0), Child = statusBar,
+ };
+
+ // ---- assembly -----------------------------------------------------------------
+ var body = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = NotaSpace.DeviceGap, Margin = new Thickness(NotaSpace.DeviceGap) };
+ body.Children.Add(tabPanel);
+ Grid.SetColumn(rail, 1); body.Children.Add(rail);
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };
+
+ showTab = () =>
{
- double x = (double)i / 60; double px = x * w; double mag;
- double d = (x - _cut) * 6.0;
- switch (_type)
+ for (int i = 0; i < TabNames.Length; i++)
{
- case 1: mag = x <= _cut ? 1.0 : 1.0 / (1.0 + d * d); break; // LP
- case 2: mag = x >= _cut ? 1.0 : 1.0 / (1.0 + d * d); break; // HP
- case 3: mag = 1.0 / (1.0 + d * d * 2.0); break; // BP
- default: mag = 1.0; break; // Off (flat)
+ bool on = i == tab;
+ tabCells[i].Background = on ? NotaPalette.SurfaceRaised : Brushes.Transparent;
+ tabCells[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ tabTexts[i].Foreground = on ? AccentBright : TextTertiary;
+ tabTexts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ pages[i].IsVisible = on;
}
- double reBump = (_type > 0 && Math.Abs(px - cx) < w * 0.06) ? _reso * 0.5 : 0;
- double y = mid - (mag + reBump) * (mid - (h * 0.12));
- pts.Add(new Point(px, Math.Clamp(y, 2, h - 2)));
+ hint.Text = TabHints[tab];
+ Refresh();
+ };
+ refresh = () =>
+ {
+ foreach (var r in readouts) r();
+ status.Text = Summary();
+ };
+ void Live()
+ {
+ int n = acc.Scope(scope);
+ SamplerModel.Parse(scope.AsSpan(0, Math.Max(0, n)), snap);
+ if (acc.Info(out long sid, out int r) && sid == sampleId) rootv = r; // the root may move from MCP / undo
+ wave.SetPlayhead(snap.Live ? snap.PlayPos : acc.PlayPosition());
+ int voices = snap.Live ? snap.Voices : 0;
+ double esr = engine.SampleRate > 0 ? engine.SampleRate : 48000;
+ meta.Text = hasSample
+ ? $"{NotaNum.Unit(esr / 1000, "0.#", "kHz")} · {NotaNum.Unit(durSec, "0.00", "s")} sample · {voices}/{SamplerModel.Voices} voices · CPU {NotaNum.Unit(engine.CpuLoad * 100, "0.0", "%")}"
+ : $"{NotaNum.Unit(esr / 1000, "0.#", "kHz")} · CPU {NotaNum.Unit(engine.CpuLoad * 100, "0.0", "%")}";
+ Refresh();
}
- var fill = new StreamGeometry();
- using (var g = fill.Open()) { g.BeginFigure(new Point(0, h), true); foreach (var p in pts) g.LineTo(p); g.LineTo(new Point(w, h)); g.EndFigure(true); }
- ctx.DrawGeometry(Fill, null, fill);
- var pen = new Pen(Amber, 1.5, lineJoin: PenLineJoin.Round);
- for (int i = 1; i < pts.Count; i++) ctx.DrawLine(pen, pts[i - 1], pts[i]);
- if (_type > 0) ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x66), 1) { DashStyle = DashStyle.Dash }, new Point(cx, 0), new Point(cx, h));
+ registerTick(Live);
+ setLiveViz?.Invoke(Refresh);
+ showTab();
+ Live();
+ return root;
}
-}
-// ---- mini keyboard marking the sampler's root (+ transposed pitch) ----
-internal sealed class SamplerKeys : Control
-{
- private static readonly IBrush White = NotaPalette.MiniKeyWhite;
- private static readonly IBrush Black = NotaPalette.MiniKeyBlack;
- private static readonly IBrush RootB = NotaPalette.Accent;
- private static readonly IBrush TransB = NotaPalette.Wash(NotaPalette.Teal, 0x88);
- private int _root = 60; private double _transpose;
- public void Set(int root, double transpose) { _root = root; _transpose = transpose; InvalidateVisual(); }
- public override void Render(DrawingContext ctx)
+ // A section: card ground, hairline, radius 6 — the almanac's section box.
+ private static Border SectionBox(Control child) => new()
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = child,
+ };
+
+ // A section's own header strip: a hairline under it, nothing else.
+ private static Border HeaderStrip(Control child) => new()
+ {
+ BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = child,
+ };
+
+ private static IEnumerable<string> ScaleRows(params double[] dbs)
{
- double w = Bounds.Width, h = Bounds.Height; if (w <= 2 || h <= 2) return;
- int lo = _root - 12, hi = _root + 12; int n = hi - lo + 1; double kw = w / n;
- int played = (int)Math.Round(_root + _transpose);
- for (int i = 0; i < n; i++)
+ double prev = 0;
+ foreach (var db in dbs)
{
- int note = lo + i; int pc = ((note % 12) + 12) % 12;
- bool blackKey = pc is 1 or 3 or 6 or 8 or 10;
- IBrush b = note == _root ? RootB : note == played ? TransB : blackKey ? Black : White;
- ctx.FillRectangle(b, new Rect(i * kw + 0.5, 2, kw - 1, h - 4));
+ double fromTop = 1.0 - MeterScale.NormDb(db);
+ yield return Math.Max(0, fromTop - prev).ToString("0.000", NotaNum.Culture) + "*";
+ yield return "Auto";
+ prev = fromTop;
}
+ yield return Math.Max(0, 1.0 - prev).ToString("0.000", NotaNum.Culture) + "*";
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Sampler/ISamplerAccess.cs b/src/managed/Nota.App/DeviceCards/Sampler/ISamplerAccess.cs
index e3b69d03..ffc69a3b 100644
--- a/src/managed/Nota.App/DeviceCards/Sampler/ISamplerAccess.cs
+++ b/src/managed/Nota.App/DeviceCards/Sampler/ISamplerAccess.cs
@@ -25,6 +25,13 @@ internal interface ISamplerAccess
void BeginGesture(string id);
void EndGesture(string id);
bool Automatable { get; } // true → wire automation write + live-follow (track only)
+ string ParamName(int i);
+ /// <summary>The engine's telemetry (SamplerModel scope); 0 floats when there is none (a rack chain).</summary>
+ int Scope(float[] buf);
+ /// <summary>The output meter under the rail — the track's own meter; false in a chain.</summary>
+ bool TryMeter(out NotaMeter meter);
+ /// <summary>MIDI Learn / CV for a control bound to param i (track only).</summary>
+ void Learn(Avalonia.Controls.Control c, int i);
}
internal sealed class TrackSamplerAccess(IAudioEngine engine, int trackId) : ISamplerAccess
@@ -45,6 +52,10 @@ internal sealed class TrackSamplerAccess(IAudioEngine engine, int trackId) : ISa
public void BeginGesture(string id) => engine.BeginAutomationWrite(trackId, AutomationTarget.PluginParam, -1, -1, id);
public void EndGesture(string id) => engine.EndAutomationWrite(trackId, AutomationTarget.PluginParam, -1, -1, id);
public bool Automatable => true;
+ public string ParamName(int i) => engine.PluginParamName(trackId, -1, i);
+ public int Scope(float[] buf) => engine.InstrumentScope(trackId, buf);
+ public bool TryMeter(out NotaMeter meter) => engine.TryGetTrackMeter(trackId, out meter);
+ public void Learn(Avalonia.Controls.Control c, int i) => MidiLearn.Bind(c, MidiTarget.PluginParam(trackId, -1, i), ParamName(i));
}
internal sealed class ChainSamplerAccess(IAudioEngine engine, int trackId, int chain) : ISamplerAccess
@@ -65,4 +76,8 @@ internal sealed class ChainSamplerAccess(IAudioEngine engine, int trackId, int c
public void BeginGesture(string id) { } // chain instrument params follow macros, not direct automation
public void EndGesture(string id) { }
public bool Automatable => false;
+ public string ParamName(int i) => engine.RackChainInstrumentParamName(trackId, chain, i);
+ public int Scope(float[] buf) => 0;
+ public bool TryMeter(out NotaMeter meter) { meter = default; return false; }
+ public void Learn(Avalonia.Controls.Control c, int i) { }
}
diff --git a/src/managed/Nota.App/DeviceCards/Sampler/SamplerViews.cs b/src/managed/Nota.App/DeviceCards/Sampler/SamplerViews.cs
new file mode 100644
index 00000000..45a037f2
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Sampler/SamplerViews.cs
@@ -0,0 +1,538 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Sampler's windows — one per tab, each a control, not a picture:
+//
+// SamplerWaveView the sample: brass peaks (the lower half a deeper brass), the played
+// window washed, Start / End as bright brass lines, the loop and its
+// crossfade when looping, the live playhead. Drag a line to move it.
+// SamplerKeysView the keyboard C2 … C6 (it follows the root): the root key in brass,
+// the key that plays the sample at its own pitch outlined, the note
+// sounding now in teal. Click a key to make it the root.
+// SamplerEnvView the amp envelope: drag Attack / Decay (and Sustain vertically) /
+// Release; the loudest voice rides it as a teal node.
+// SamplerFilterView the filter's real response (the engine's SVF): drag for cutoff (x)
+// and resonance (y); the cutoff the loudest voice hears after key
+// tracking and the envelope shows as a teal line.
+//
+// All in the NotaGraph window (well, hairline, radius 4, corner labels in mono 7).
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal static class SamplerInk
+{
+ public static FormattedText Mono(string t, IBrush ink, double size = 7)
+ => new(t, NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);
+
+ public static void Corner(DrawingContext ctx, Rect r, NotaGraph.Corner c, string text, IBrush ink)
+ {
+ if (text.Length == 0) return;
+ var ft = Mono(text, ink);
+ const double padX = 6, padY = 3;
+ double x = c is NotaGraph.Corner.TopLeft or NotaGraph.Corner.BottomLeft ? r.X + padX : r.Right - padX - ft.Width;
+ double y = c is NotaGraph.Corner.TopLeft or NotaGraph.Corner.TopRight ? r.Y + padY : r.Bottom - padY - ft.Height + 1;
+ ctx.DrawText(ft, new Point(x, y));
+ }
+}
+
+// ---- the sample -------------------------------------------------------------------------
+internal sealed class SamplerWaveView : Control
+{
+ private float[] _peaks = Array.Empty<float>();
+ private double _start, _end = 1, _ls, _le = 1, _xf, _dur, _play = -1;
+ private int _loop; // 0 Off, 1 Fwd, 2 Ping, 3 Rev
+ private int _drag = -1;
+ private string _info = "", _loopText = "", _empty = "";
+
+ /// <summary>A handle moved: 0 start, 1 end, 2 loop start, 3 loop end → the new position.</summary>
+ public event Action<int, double>? Moved;
+ public event Action<int>? DragBegin, DragEnd, ResetHandle;
+
+ private static readonly string[] Ids = { "start", "end", "loopstart", "loopend" };
+ public static string HandleId(int h) => Ids[h];
+
+ public SamplerWaveView() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.SizeWestEast); }
+
+ public void SetPeaks(float[] p, double durationSec) { _peaks = p; _dur = durationSec; InvalidateVisual(); }
+ public void SetEmpty(string text) { _empty = text; InvalidateVisual(); }
+ public void SetPlayhead(double frac) { if (Math.Abs(frac - _play) > 1e-4) { _play = frac; InvalidateVisual(); } }
+ public void Set(double s, double e, double ls, double le, int loop, double xfadeSec, string info, string loopText)
+ {
+ _start = s; _end = e; _ls = ls; _le = le; _loop = loop; _xf = xfadeSec; _info = info; _loopText = loopText;
+ InvalidateVisual();
+ }
+
+ private double[] Handles() => _loop > 0 ? new[] { _start, _end, _ls, _le } : new[] { _start, _end };
+
+ private int Hit(double xFrac, double w)
+ {
+ var hs = Handles();
+ int best = -1; double bestD = 7 / Math.Max(1, w); // 7 px grab radius
+ for (int i = 0; i < hs.Length; i++) { double d = Math.Abs(xFrac - hs[i]); if (d < bestD) { bestD = d; best = i; } }
+ return best;
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ double w = Bounds.Width;
+ if (w <= 0 || _peaks.Length == 0 || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ double x = e.GetPosition(this).X / w;
+ int h = Hit(x, w);
+ if (h < 0) return;
+ if (e.ClickCount == 2) { ResetHandle?.Invoke(h); e.Handled = true; return; }
+ _drag = h;
+ DragBegin?.Invoke(h);
+ e.Pointer.Capture(this);
+ e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ if (_drag < 0 || Bounds.Width <= 0) return;
+ double f = Math.Clamp(e.GetPosition(this).X / Bounds.Width, 0, 1);
+ f = _drag switch
+ {
+ 0 => Math.Min(f, _end - 0.001),
+ 1 => Math.Max(f, _start + 0.001),
+ 2 => Math.Clamp(Math.Min(f, _le - 0.001), _start, _end),
+ _ => Math.Clamp(Math.Max(f, _ls + 0.001), _start, _end),
+ };
+ Moved?.Invoke(_drag, f);
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_drag < 0) return;
+ int h = _drag; _drag = -1;
+ e.Pointer.Capture(null);
+ DragEnd?.Invoke(h);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, r);
+ if (_peaks.Length == 0)
+ {
+ var ft = SamplerInk.Mono(_empty, NotaPalette.TextTertiary, 9);
+ ctx.DrawText(ft, new Point((w - ft.Width) / 2, (h - ft.Height) / 2));
+ return;
+ }
+ double top = 2, bot = h - 2, cy = (top + bot) / 2, amp = (bot - top) / 2 - 1;
+
+ // The played window, washed; outside it the peaks go quiet.
+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Accent, 0x14), new Rect(_start * w, 0, (_end - _start) * w, h));
+ var grid = NotaGraph.GridPen;
+ ctx.DrawLine(grid, new Point(0, cy), new Point(w, cy));
+ for (int i = 1; i < 4; i++) ctx.DrawLine(grid, new Point(w * i / 4, 0), new Point(w * i / 4, h));
+
+ // Loop + its crossfade zone (the engine crossfades a forward loop only) — a deeper wash between the markers.
+ if (_loop > 0)
+ {
+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Accent, 0x1C), new Rect(_ls * w, 0, Math.Max(1, (_le - _ls) * w), h));
+ if (_loop == 1 && _xf > 0 && _dur > 0)
+ {
+ double xw = Math.Min(_xf / _dur, (_le - _ls) / 2) * w;
+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Accent, 0x30), new Rect(_le * w - xw, 0, xw, h));
+ }
+ }
+
+ int n = _peaks.Length / 2;
+ var upIn = new Pen(NotaPalette.Accent, 1.2); var downIn = new Pen(NotaPalette.AccentDim, 1.2);
+ var outPen = new Pen(NotaPalette.Wash(NotaPalette.Accent, 0x40), 1);
+ int step = Math.Max(1, (int)Math.Floor(n / Math.Max(1.0, w / 1.5)));
+ for (int i = 0; i < n; i += step)
+ {
+ double f = (double)i / n, x = f * w;
+ float mn = 0, mx = 0;
+ for (int j = i; j < Math.Min(n, i + step); j++) { mn = Math.Min(mn, _peaks[j * 2]); mx = Math.Max(mx, _peaks[j * 2 + 1]); }
+ bool inWin = f >= _start && f <= _end;
+ ctx.DrawLine(inWin ? upIn : outPen, new Point(x, cy), new Point(x, cy - mx * amp));
+ ctx.DrawLine(inWin ? downIn : outPen, new Point(x, cy), new Point(x, cy - mn * amp));
+ }
+
+ if (_loop > 0)
+ {
+ var lp = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0xB0), 1, new DashStyle(new double[] { 3, 2 }, 0));
+ ctx.DrawLine(lp, new Point(_ls * w, 0), new Point(_ls * w, h));
+ ctx.DrawLine(lp, new Point(_le * w, 0), new Point(_le * w, h));
+ }
+ var edge = new Pen(NotaPalette.AccentBright, 1.5);
+ ctx.DrawLine(edge, new Point(_start * w, 0), new Point(_start * w, h));
+ ctx.DrawLine(edge, new Point(_end * w, 0), new Point(_end * w, h));
+ if (_play >= 0 && _play <= 1) ctx.DrawLine(new Pen(NotaPalette.TextPrimary, 1), new Point(_play * w, 0), new Point(_play * w, h));
+
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopLeft, _info, NotaPalette.TextTertiary);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopRight, _loopText, _loop > 0 ? NotaPalette.AccentBright : NotaPalette.TextTertiary);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.BottomLeft, "start " + NotaNum.Str(_start * _dur, "0.00"), NotaPalette.AccentBright);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.BottomRight, "end " + NotaNum.Str(_end * _dur, "0.00"), NotaPalette.AccentBright);
+ }
+}
+
+// ---- the keyboard -----------------------------------------------------------------------
+internal sealed class SamplerKeysView : Control
+{
+ private int _root = 60, _lo = 36, _natural = 60;
+ private double _playing = -1, _track = 1;
+ private string _hint = "";
+
+ public event Action<int>? RootPicked;
+
+ public SamplerKeysView() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); }
+
+ /// <param name="natural">The key that plays the sample at its own pitch (−1 none).</param>
+ public void Set(int root, int natural, double playingNote, double keytrack, string hint)
+ {
+ _root = root; _natural = natural; _playing = playingNote; _track = keytrack; _hint = hint;
+ // Four octaves from a C, C2 … C6 by default, shifted so the root stays in view.
+ int lo = 36;
+ while (_root < lo + 3 && lo > 0) lo -= 12;
+ while (_root > lo + 45 && lo < 79) lo += 12;
+ _lo = lo;
+ InvalidateVisual();
+ }
+
+ private const double LabelH = 14;
+ private int Keys => 49;
+
+ private int KeyAt(Point p)
+ {
+ double pad = 4, kw = (Bounds.Width - pad * 2) / Keys;
+ if (kw <= 0) return -1;
+ int i = (int)Math.Floor((p.X - pad) / kw);
+ return i < 0 || i >= Keys ? -1 : Math.Clamp(_lo + i, 0, 127);
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ int k = KeyAt(e.GetPosition(this));
+ if (k < 0) return;
+ RootPicked?.Invoke(k);
+ e.Handled = true;
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, r);
+ double pad = 4, kw = (w - pad * 2) / Keys, top = LabelH + 4, bot = h - pad;
+ double keyH = Math.Max(8, bot - top);
+ int playing = _playing >= 0 ? (int)Math.Round(_playing) : -1;
+ var hair = new Pen(NotaPalette.GraphBorder, 1);
+ for (int i = 0; i < Keys; i++)
+ {
+ int note = _lo + i;
+ int pc = ((note % 12) + 12) % 12;
+ bool black = pc is 1 or 3 or 6 or 8 or 10;
+ double kh = black ? keyH * 0.62 : keyH;
+ var rect = new Rect(pad + i * kw + 1, bot - kh, Math.Max(1, kw - 2), kh); // resting on the bottom edge
+ IBrush fill = note == _root ? NotaPalette.Accent
+ : note == playing ? NotaPalette.Teal
+ : black ? NotaPalette.SurfaceAbyss : NotaPalette.SurfaceRaised;
+ ctx.DrawRectangle(fill, note == _root ? null : hair, new RoundedRect(rect, 0, 0, 2, 2));
+ if (note == _natural && note != _root)
+ ctx.DrawRectangle(null, new Pen(NotaPalette.AccentBright, 1), new RoundedRect(rect.Deflate(0.5), 0, 0, 2, 2));
+ if (pc == 0 && note != _root)
+ {
+ var c = SamplerInk.Mono(SamplerModel.NoteName(note), NotaPalette.TextAxis);
+ if (!black && kh > c.Height + 4) ctx.DrawText(c, new Point(rect.X + (rect.Width - c.Width) / 2, rect.Bottom - c.Height - 2));
+ }
+ if (note == _root)
+ {
+ var t = SamplerInk.Mono(SamplerModel.NoteName(note), NotaPalette.TextOnAccent);
+ ctx.DrawText(t, new Point(rect.X + (rect.Width - t.Width) / 2, rect.Bottom - t.Height - 2));
+ }
+ }
+ string range = $"range {SamplerModel.NoteName(_lo)} — {SamplerModel.NoteName(_lo + 48)} · root {SamplerModel.NoteName(_root)} · keytrack {NotaNum.Pct(_track)}";
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopLeft, range, NotaPalette.TextTertiary);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopRight, _hint, NotaPalette.TextAxis);
+ }
+}
+
+// ---- the amp envelope -------------------------------------------------------------------
+internal sealed class SamplerEnvView : Control
+{
+ private double _a, _d = 0.3, _s = 1, _r = 0.06;
+ private SamplerModel.Snapshot? _live;
+ private string _tl = "", _br = "";
+ private int _drag = -1; // 0 attack, 1 decay+sustain, 2 release
+ private Point _last;
+
+ /// <summary>A node moved: (param id, new normalized value).</summary>
+ public event Action<string, double>? Changed;
+ public event Action<string>? DragBegin, DragEnd, Reset;
+
+ public SamplerEnvView() { ClipToBounds = true; }
+
+ public void Set(double a, double d, double s, double r, SamplerModel.Snapshot? live, string tl, string br)
+ {
+ _a = a; _d = d; _s = s; _r = r; _live = live; _tl = tl; _br = br;
+ InvalidateVisual();
+ }
+
+ // Each timed segment takes 4 … 30 % of the width by its (normalized) value; the rest is
+ // the held note.
+ private const double SegMin = 0.04, SegSpan = 0.26, Pad = 4;
+ private (Point A, Point D, Point S, Point R, Point O) Nodes()
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ double x0 = Pad, x1 = w - Pad, span = x1 - x0, top = 14, bot = h - 12;
+ double aw = (SegMin + SegSpan * _a) * span, dw = (SegMin + SegSpan * _d) * span, rw = (SegMin + SegSpan * _r) * span;
+ double sy = top + (1 - _s) * (bot - top);
+ var o = new Point(x0, bot);
+ var a = new Point(x0 + aw, top);
+ var d = new Point(a.X + dw, sy);
+ var rEnd = new Point(Math.Max(d.X + 8, x1 - span * 0.06), bot);
+ var s = new Point(Math.Max(d.X, rEnd.X - rw), sy);
+ return (a, d, s, rEnd, o);
+ }
+
+ private static readonly string[] Ids = { "attack", "decay", "release" };
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ var p = e.GetPosition(this);
+ var n = Nodes();
+ var pts = new[] { n.A, n.D, n.R };
+ int best = -1; double bd = 10;
+ for (int i = 0; i < 3; i++) { double dd = Math.Abs(p.X - pts[i].X) + Math.Abs(p.Y - pts[i].Y) * 0.5; if (dd < bd) { bd = dd; best = i; } }
+ if (best < 0) return;
+ if (e.ClickCount == 2) { Reset?.Invoke(Ids[best]); if (best == 1) Reset?.Invoke("sustain"); e.Handled = true; return; }
+ _drag = best; _last = p;
+ DragBegin?.Invoke(Ids[best]);
+ if (best == 1) DragBegin?.Invoke("sustain");
+ e.Pointer.Capture(this);
+ e.Handled = true;
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ var p = e.GetPosition(this);
+ if (_drag < 0)
+ {
+ var n = Nodes();
+ bool near = new[] { n.A, n.D, n.R }.Any(q => Math.Abs(p.X - q.X) + Math.Abs(p.Y - q.Y) * 0.5 < 10);
+ Cursor = near ? new Cursor(StandardCursorType.SizeAll) : Cursor.Default;
+ return;
+ }
+ double span = Math.Max(1, Bounds.Width - Pad * 2) * SegSpan;
+ double dx = (p.X - _last.X) / span;
+ bool fine = e.KeyModifiers.HasFlag(KeyModifiers.Shift);
+ if (fine) dx *= 0.2;
+ switch (_drag)
+ {
+ case 0: _a = Math.Clamp(_a + dx, 0, 1); Changed?.Invoke("attack", _a); break;
+ case 1:
+ {
+ _d = Math.Clamp(_d + dx, 0, 1); Changed?.Invoke("decay", _d);
+ double top = 14, bot = Bounds.Height - 12;
+ double dy = (p.Y - _last.Y) / Math.Max(1, bot - top) * (fine ? 0.2 : 1);
+ _s = Math.Clamp(_s - dy, 0, 1); Changed?.Invoke("sustain", _s);
+ break;
+ }
+ default: _r = Math.Clamp(_r - dx, 0, 1); Changed?.Invoke("release", _r); break; // the release node moves left as it grows
+ }
+ _last = p;
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_drag < 0) return;
+ DragEnd?.Invoke(Ids[_drag]);
+ if (_drag == 1) DragEnd?.Invoke("sustain");
+ _drag = -1;
+ e.Pointer.Capture(null);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, r);
+ var grid = NotaGraph.GridPen;
+ for (int i = 1; i < 4; i++) ctx.DrawLine(grid, new Point(w * i / 4, 0), new Point(w * i / 4, h));
+ var n = Nodes();
+ ctx.DrawLine(grid, new Point(0, n.A.Y), new Point(w, n.A.Y));
+ ctx.DrawLine(grid, new Point(0, n.D.Y), new Point(w, n.D.Y));
+
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ g.BeginFigure(n.O, true);
+ g.LineTo(n.A); g.LineTo(n.D); g.LineTo(n.S); g.LineTo(n.R);
+ g.EndFigure(true);
+ }
+ ctx.DrawGeometry(NotaPalette.Wash(NotaPalette.Accent, 0x14), null, geo);
+ var line = new StreamGeometry();
+ using (var g = line.Open())
+ {
+ g.BeginFigure(n.O, false);
+ g.LineTo(n.A); g.LineTo(n.D); g.LineTo(n.S); g.LineTo(n.R);
+ g.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, line);
+ NotaGraph.Node(ctx, n.A, _drag == 0, NotaPalette.AccentBright);
+ NotaGraph.Node(ctx, n.D, _drag == 1, NotaPalette.AccentBright);
+ NotaGraph.Node(ctx, n.S, false, NotaPalette.AccentBright);
+ NotaGraph.Node(ctx, n.R, _drag == 2, NotaPalette.AccentBright);
+
+ // The loudest voice on the curve, in teal.
+ if (_live is { Live: true, Stage: >= 0 } lv)
+ {
+ double env = Math.Clamp(lv.Env, 0, 1), top = n.A.Y, bot = n.O.Y;
+ double y = bot - env * (bot - top);
+ double x = lv.Stage switch
+ {
+ 0 => n.O.X + (n.A.X - n.O.X) * env,
+ 1 => n.A.X + (n.D.X - n.A.X) * (1 - env) / Math.Max(1e-3, 1 - _s),
+ 2 => (n.D.X + n.S.X) / 2,
+ _ => n.S.X + (n.R.X - n.S.X) * (1 - env / Math.Max(1e-3, _s)),
+ };
+ x = Math.Clamp(x, n.O.X, n.R.X);
+ NotaGraph.Node(ctx, new Point(x, y), true, NotaPalette.Teal);
+ }
+
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopLeft, _tl, NotaPalette.TextTertiary);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopRight, "note held", NotaPalette.TextAxis);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.BottomLeft, "0", NotaPalette.TextAxis);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.BottomRight, _br, NotaPalette.TextAxis);
+ }
+}
+
+// ---- the filter -------------------------------------------------------------------------
+internal sealed class SamplerFilterView : Control
+{
+ private int _type;
+ private double _cut = 1, _reso, _liveHz = -1;
+ private string _tl = "";
+ private bool _drag;
+ private Point _last;
+
+ public event Action<string, double>? Changed;
+ public event Action? DragBegin, DragEnd, Reset;
+
+ private const double FLo = 30, FHi = 18000, DbTop = 18, DbBot = -42;
+
+ public SamplerFilterView() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.SizeAll); }
+
+ public void Set(int type, double cutNorm, double reso, double liveHz, string tl)
+ {
+ _type = type; _cut = cutNorm; _reso = reso; _liveHz = liveHz; _tl = tl;
+ InvalidateVisual();
+ }
+
+ private static double XOf(double hz, double w) => Math.Log(Math.Clamp(hz, FLo, FHi) / FLo) / Math.Log(FHi / FLo) * w;
+
+ // The engine's TPT SVF magnitude at f for cutoff fc (k = 2 − 1.9·reso).
+ private static double MagDb(int type, double f, double fc, double reso)
+ {
+ double k = 2.0 - 1.9 * reso, x = f / fc, re = 1 - x * x, im = k * x;
+ double den = Math.Sqrt(re * re + im * im);
+ double mag = type switch { 1 => 1 / den, 2 => x * x / den, 3 => x / den, _ => 1 };
+ return 20 * Math.Log10(Math.Max(mag, 1e-6));
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { Reset?.Invoke(); e.Handled = true; return; }
+ _drag = true; _last = e.GetPosition(this);
+ DragBegin?.Invoke();
+ e.Pointer.Capture(this);
+ e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ if (!_drag) return;
+ var p = e.GetPosition(this);
+ double k = e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? 0.2 : 1;
+ // x across the window spans 30 Hz … 18 kHz; the cutoff param spans 20 Hz … 20 kHz.
+ double octPerPx = Math.Log2(FHi / FLo) / Math.Max(1, Bounds.Width);
+ _cut = Math.Clamp(_cut + (p.X - _last.X) * octPerPx / Math.Log2(1000) * k, 0, 1);
+ _reso = Math.Clamp(_reso - (p.Y - _last.Y) / Math.Max(1, Bounds.Height) * k, 0, 1);
+ Changed?.Invoke("cutoff", _cut);
+ Changed?.Invoke("resonance", _reso);
+ _last = p;
+ InvalidateVisual();
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (!_drag) return;
+ _drag = false;
+ e.Pointer.Capture(null);
+ DragEnd?.Invoke();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, r);
+ double top = 12, bot = h - 12;
+ double Y(double db) => top + (DbTop - Math.Clamp(db, DbBot, DbTop)) / (DbTop - DbBot) * (bot - top);
+ var grid = NotaGraph.GridPen;
+ foreach (var hz in new[] { 100.0, 1000, 10000 }) { double x = XOf(hz, w); ctx.DrawLine(grid, new Point(x, 0), new Point(x, h)); }
+ ctx.DrawLine(grid, new Point(0, Y(0)), new Point(w, Y(0)));
+ ctx.DrawLine(grid, new Point(0, Y(-24)), new Point(w, Y(-24)));
+
+ double fc = SamplerModel.CutoffHz((float)_cut);
+ var pts = new List<Point>();
+ for (int i = 0; i <= 120; i++)
+ {
+ double x = i / 120.0 * w;
+ double f = FLo * Math.Pow(FHi / FLo, i / 120.0);
+ pts.Add(new Point(x, Y(MagDb(_type, f, fc, _reso))));
+ }
+ var fill = new StreamGeometry();
+ using (var g = fill.Open())
+ {
+ g.BeginFigure(new Point(0, bot), true);
+ foreach (var p in pts) g.LineTo(p);
+ g.LineTo(new Point(w, bot));
+ g.EndFigure(true);
+ }
+ var line = new StreamGeometry();
+ using (var g = line.Open())
+ {
+ g.BeginFigure(pts[0], false);
+ for (int i = 1; i < pts.Count; i++) g.LineTo(pts[i]);
+ g.EndFigure(false);
+ }
+ if (_type > 0) ctx.DrawGeometry(NotaPalette.Wash(NotaPalette.Accent, 0x14), null, fill);
+ ctx.DrawGeometry(null, _type > 0 ? NotaGraph.PrimaryPen : new Pen(NotaPalette.TextTertiary, 1.2), line);
+
+ if (_type > 0)
+ {
+ double cx = XOf(fc, w);
+ ctx.DrawLine(new Pen(NotaPalette.AccentDim, 1, new DashStyle(new double[] { 3, 3 }, 0)), new Point(cx, 0), new Point(cx, h));
+ NotaGraph.Node(ctx, new Point(cx, Y(MagDb(_type, fc, fc, _reso))), _drag, NotaPalette.AccentBright);
+ if (_liveHz > 0 && Math.Abs(Math.Log2(_liveHz / fc)) > 0.05)
+ {
+ double lx = XOf(_liveHz, w);
+ ctx.DrawLine(new Pen(NotaPalette.Teal, 1.2), new Point(lx, 0), new Point(lx, h));
+ }
+ }
+
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.TopLeft, _tl, NotaPalette.TextTertiary);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.BottomLeft, "30\u2009Hz", NotaPalette.TextAxis);
+ SamplerInk.Corner(ctx, r, NotaGraph.Corner.BottomRight, "18\u2009k", NotaPalette.TextAxis);
+ var k1 = SamplerInk.Mono("1\u2009k", NotaPalette.TextAxis);
+ ctx.DrawText(k1, new Point(XOf(1000, w) + 3, h - 3 - k1.Height + 1));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Sampler/SamplerWaveform.cs b/src/managed/Nota.App/DeviceCards/Sampler/SamplerWaveform.cs
deleted file mode 100644
index f85bfed9..00000000
--- a/src/managed/Nota.App/DeviceCards/Sampler/SamplerWaveform.cs
+++ /dev/null
@@ -1,128 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Detail · Devices — the Sampler's waveform view: draggable Start/End brackets +
-// Loop Start/End markers, a time grid, and a live playback cursor.
-
-using System;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Input;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class SamplerWaveform : Control
-{
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush Wave = NotaPalette.Accent;
- private static readonly IBrush WaveDim = NotaPalette.Wash(NotaPalette.Accent, 0x40);
- private static readonly IBrush Outside = NotaPalette.Wash(NotaPalette.BgSunken, 0x80);
- private static readonly IBrush LoopFill = NotaPalette.Wash(NotaPalette.Accent, 0x14); // brass wash
- // Trim boundaries: 1px brass lines (almanac § oscillogram); green and red are status only.
- private static readonly IPen StartPen = new Pen(NotaPalette.Accent, 1);
- private static readonly IPen EndPen = new Pen(NotaPalette.Accent, 1);
- private static readonly IPen LoopPen = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0xC8), 1.2);
- private static readonly IPen MidLine = new Pen(NotaPalette.GridBar, 1);
- private static readonly IPen GridPen = NotaGraph.GridPen;
- private static readonly IPen PlayPen = new Pen(NotaPalette.AccentBright, 1.4) { };
- private static readonly IBrush GridText = NotaPalette.TextTertiary;
- private static readonly Typeface Mono = NotaFonts.Mono;
-
- private float[] _peaks = Array.Empty<float>();
- private double _start, _end = 1, _ls, _le = 1;
- private int _loopMode;
- private int _drag = -1;
- private double _dur; // sample duration (seconds), for the time grid
- private double _play = -1; // live playback position (0..1), -1 = hidden
-
- public event Action<double>? StartChanged, EndChanged, LoopStartChanged, LoopEndChanged;
- public Action? GestureBegin;
-
- public SamplerWaveform() { MinHeight = 70; ClipToBounds = true; }
- public void SetPeaks(float[] p) { _peaks = p; InvalidateVisual(); }
- public void SetDuration(double seconds) { _dur = seconds; InvalidateVisual(); }
- public void SetPlayhead(double frac) { if (Math.Abs(frac - _play) > 1e-4) { _play = frac; InvalidateVisual(); } }
- public void SetMarkers(double s, double e, double ls, double le, int mode)
- { _start = s; _end = e; _ls = ls; _le = le; _loopMode = mode; InvalidateVisual(); }
-
- private double[] Handles() => _loopMode > 0 ? new[] { _start, _end, _ls, _le } : new[] { _start, _end };
-
- protected override void OnPointerPressed(PointerPressedEventArgs e)
- {
- double w = Bounds.Width; if (w <= 0) return;
- double x = e.GetPosition(this).X / w;
- var hs = Handles();
- int best = -1; double bestD = 0.04; // ~4% of width grab radius
- for (int i = 0; i < hs.Length; i++) { double d = Math.Abs(x - hs[i]); if (d < bestD) { bestD = d; best = i; } }
- _drag = best;
- if (_drag >= 0) { GestureBegin?.Invoke(); e.Pointer.Capture(this); Apply(x); e.Handled = true; }
- }
- protected override void OnPointerMoved(PointerEventArgs e)
- { if (_drag >= 0 && Bounds.Width > 0) Apply(Math.Clamp(e.GetPosition(this).X / Bounds.Width, 0, 1)); }
- protected override void OnPointerReleased(PointerReleasedEventArgs e) { _drag = -1; e.Pointer.Capture(null); }
-
- private void Apply(double f)
- {
- f = Math.Clamp(f, 0, 1);
- switch (_drag)
- {
- case 0: StartChanged?.Invoke(Math.Min(f, _end - 0.001)); break;
- case 1: EndChanged?.Invoke(Math.Max(f, _start + 0.001)); break;
- case 2: LoopStartChanged?.Invoke(Math.Min(f, _le - 0.001)); break;
- case 3: LoopEndChanged?.Invoke(Math.Max(f, _ls + 0.001)); break;
- }
- }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- double cy = h / 2;
-
- // Time grid (behind the waveform): vertical lines + labels at a nice step.
- if (_dur > 0)
- {
- double step = _dur <= 0.5 ? 0.05 : _dur <= 1.5 ? 0.1 : _dur <= 5 ? 0.5 : _dur <= 15 ? 1.0 : 5.0;
- for (double t = step; t < _dur; t += step)
- {
- double x = t / _dur * w;
- ctx.DrawLine(GridPen, new Point(x, 0), new Point(x, h));
- string lbl = _dur >= 1 ? $"{t:0.##}\u2009s" : $"{(int)Math.Round(t * 1000)}";
- ctx.DrawText(new FormattedText(lbl, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, GridText), new Point(x + 2, h - 11));
- }
- }
-
- int n = _peaks.Length / 2;
- if (n > 0)
- {
- for (int i = 0; i < n; i++)
- {
- double x = (double)i / n * w;
- double frac = (double)i / n;
- bool inWin = frac >= _start && frac <= _end;
- double y0 = cy - _peaks[i * 2 + 1] * (cy - 2);
- double y1 = cy - _peaks[i * 2] * (cy - 2);
- ctx.DrawLine(new Pen(inWin ? Wave : WaveDim, 1), new Point(x, y0), new Point(x, y1));
- }
- }
- ctx.DrawLine(MidLine, new Point(0, cy), new Point(w, cy));
-
- // Dim the region outside [start,end].
- if (_start > 0) ctx.FillRectangle(Outside, new Rect(0, 0, _start * w, h));
- if (_end < 1) ctx.FillRectangle(Outside, new Rect(_end * w, 0, (1 - _end) * w, h));
- // Loop region + markers.
- if (_loopMode > 0)
- {
- ctx.FillRectangle(LoopFill, new Rect(_ls * w, 0, Math.Max(1, (_le - _ls) * w), h));
- ctx.DrawLine(LoopPen, new Point(_ls * w, 0), new Point(_ls * w, h));
- ctx.DrawLine(LoopPen, new Point(_le * w, 0), new Point(_le * w, h));
- }
- // Start (green) / End (red) brackets.
- ctx.DrawLine(StartPen, new Point(_start * w, 0), new Point(_start * w, h));
- ctx.DrawLine(EndPen, new Point(_end * w, 0), new Point(_end * w, h));
- // Live playback cursor.
- if (_play >= 0 && _play <= 1) ctx.DrawLine(PlayPen, new Point(_play * w, 0), new Point(_play * w, h));
- }
-}
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index ee71acc4..fd5f848b 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -300,6 +300,12 @@ public interface IAudioEngine : IDisposable
bool SetTrackSamplerRoot(int trackId, int rootNote);
/// <summary>Live Sampler playback position (0..1 of the sample, -1 = silent) for the UI cursor.</summary>
float SamplerPlayPosition(int trackId);
+ /// <summary>The file name (no extension) a sample was loaded from, or "" when unknown —
+ /// the engine keeps only the audio, so the name is remembered here on load and carried
+ /// by the project (SamplerDto.Name). Used by the Sampler's "Detect from file name".</summary>
+ string SampleName(long sampleId);
+ /// <summary>Remember the source name of a sample (a project reload restores it).</summary>
+ void SetSampleName(long sampleId, string name);
int AddMidiClip(int trackId, double startBeat, double lengthBeats);
// --- Hosted plugins (M3-3) ---------------------------------------------
diff --git a/src/managed/Nota.Application/Instruments/SamplerModel.cs b/src/managed/Nota.Application/Instruments/SamplerModel.cs
new file mode 100644
index 00000000..6cdb327d
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/SamplerModel.cs
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Sampler (built-in instrument kind 1) — the engine's own value maps, in one place
+// for the editor card and the MCP server: what a normalized 0..1 parameter means (dB,
+// semitones, cents, envelope times, cutoff, glide), the Loop / Filter / Voice choices, the
+// sample tools (snap to a zero crossing, trim silence, the root note from a file name),
+// how the telemetry is laid out, a one-line summary of the patch and a guide to every
+// parameter. Mirrors Sampler.h.
+
+using System;
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Nota.Application;
+
+public static class SamplerModel
+{
+ public const int Kind = 1;
+ public const int Voices = 16;
+
+ // scopeRead layout (Sampler::kTele).
+ public const int ScopeLength = 8;
+
+ public static readonly string[] LoopNames = { "Off", "Fwd", "Ping", "Rev" };
+ public static readonly string[] FilterNames = { "Off", "LP", "HP", "BP" };
+ public static readonly string[] VoiceNames = { "Poly 16", "Mono", "Choke" };
+ public static readonly string[] StageNames = { "attack", "decay", "sustain", "release" };
+ private static readonly string[] NoteNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+
+ public static double ExpMap(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0.0, 1.0));
+ public static double ExpInv(double x, double lo, double hi) => Math.Clamp(Math.Log(Math.Clamp(x, lo, hi) / lo) / Math.Log(hi / lo), 0, 1);
+ public static int Index(float v, int n) => Math.Clamp((int)Math.Round(v * (n - 1)), 0, n - 1);
+
+ // ---- value maps ---------------------------------------------------------------------
+ public static double LinDb(double lin) => lin <= 1e-5 ? double.NegativeInfinity : 20 * Math.Log10(lin);
+ /// <summary>volume / output: a linear gain 0..1 (1 = 0 dB).</summary>
+ public static double VolumeDb(float v) => LinDb(v);
+ /// <summary>gain: the sample's gain before the envelope, ±24 dB (0.5 = 0 dB).</summary>
+ public static double GainDb(float v) => (Math.Clamp(v, 0f, 1f) - 0.5) * 48.0;
+ public static float GainNorm(double db) => (float)Math.Clamp(0.5 + db / 48.0, 0, 1);
+ public static double TransposeSt(float v) => (v - 0.5) * 48.0;
+ public static float TransposeNorm(double st) => (float)Math.Clamp(0.5 + st / 48.0, 0, 1);
+ public static double DetuneCents(float v) => (v - 0.5) * 100.0;
+ public static float DetuneNorm(double c) => (float)Math.Clamp(0.5 + c / 100.0, 0, 1);
+ public static double AttackSec(float v) => ExpMap(v, 0.0005, 4.0);
+ public static double DecaySec(float v) => ExpMap(v, 0.002, 6.0);
+ public static double ReleaseSec(float v) => ExpMap(v, 0.002, 6.0);
+ public static double CutoffHz(float v) => ExpMap(v, 20.0, 20000.0);
+ public static double CrossfadeSec(float v) => v * 0.2;
+ public static double GlideSec(float v) => v <= 0.001f ? 0 : 0.001 * Math.Pow(2000.0, Math.Clamp(v, 0f, 1f));
+ public static float GlideNorm(double sec) => sec <= 0.0005 ? 0f : (float)Math.Clamp(Math.Log(sec / 0.001) / Math.Log(2000.0), 0.002, 1);
+ public static double EnvOctaves(float v) => (Math.Clamp(v, 0f, 1f) - 0.5) * 12.0;
+ public static float EnvOctavesNorm(double oct) => (float)Math.Clamp(0.5 + oct / 12.0, 0, 1);
+ /// <summary>pan: 0 left … 0.5 centre … 1 right → −1..1.</summary>
+ public static double PanSigned(float v) => (v - 0.5) * 2.0;
+
+ /// <summary>The Loop choice from loopmode + reverse: Off, Fwd, Ping, Rev (a reversed forward loop).</summary>
+ public static int LoopIndex(float loopmode, float reverse)
+ {
+ int lm = Index(loopmode, 3);
+ return lm == 2 ? 2 : lm == 1 ? (reverse >= 0.5f ? 3 : 1) : 0;
+ }
+ /// <summary>loopmode + reverse for a Loop choice.</summary>
+ public static (float LoopMode, float Reverse) LoopValues(int choice) => choice switch
+ {
+ 1 => (0.5f, 0f), 2 => (1f, 0f), 3 => (0.5f, 1f), _ => (0f, 0f),
+ };
+
+ // ---- notes ----------------------------------------------------------------------------
+ public static string NoteName(int note) => note < 0 ? "—" : $"{NoteNames[((note % 12) + 12) % 12]}{note / 12 - 1}";
+
+ /// <summary>"C4", "F#3", "Eb2", "a-1" (C4 = 60) or a MIDI number "60" → the MIDI note, or −1.</summary>
+ public static int ParseNote(string? text)
+ {
+ if (string.IsNullOrWhiteSpace(text)) return -1;
+ var t = text.Trim();
+ if (int.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) return n is >= 0 and <= 127 ? n : -1;
+ var m = Regex.Match(t, @"^([A-Ga-g])([#♯b♭]?)(-?\d)$");
+ return m.Success ? NoteOf(m) : -1;
+ }
+
+ private static int NoteOf(Match m)
+ {
+ int pc = char.ToUpperInvariant(m.Groups[1].Value[0]) switch { 'C' => 0, 'D' => 2, 'E' => 4, 'F' => 5, 'G' => 7, 'A' => 9, _ => 11 };
+ string acc = m.Groups[2].Value;
+ if (acc is "#" or "♯") pc++;
+ else if (acc is "b" or "♭") pc--;
+ int oct = int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
+ int note = (oct + 1) * 12 + pc;
+ return note is >= 0 and <= 127 ? note : -1;
+ }
+
+ /// <summary>The root note a sample's file name names — "Piano_C4", "Str Eb3 soft",
+ /// "bass-F#1-rr2" (the last note-like token wins, C4 = 60). −1 when there is none.</summary>
+ public static int DetectRoot(string? fileName)
+ {
+ if (string.IsNullOrWhiteSpace(fileName)) return -1;
+ string name = System.IO.Path.GetFileNameWithoutExtension(fileName);
+ // A note letter not glued to a word before it, an optional accidental, an octave
+ // −1..9 not followed by another digit.
+ var ms = Regex.Matches(name, @"(?<![A-Za-z0-9])([A-Ga-g])([#♯b♭]?)(-?\d)(?!\d)");
+ for (int i = ms.Count - 1; i >= 0; i--)
+ {
+ int note = NoteOf(ms[i]);
+ if (note >= 0) return note;
+ }
+ return -1;
+ }
+
+ // ---- sample tools ---------------------------------------------------------------------
+ private static float Mono(float[] raw, int ch, long f)
+ {
+ float s = 0;
+ for (int c = 0; c < ch; c++) s += raw[f * ch + c];
+ return s / ch;
+ }
+
+ /// <summary>The zero crossing nearest a normalized position (0..1), normalized.</summary>
+ public static double SnapZero(float[] raw, int channels, long frames, double pos)
+ {
+ int ch = Math.Max(1, channels);
+ if (frames < 2 || raw.Length < frames * ch) return pos;
+ long target = (long)Math.Round(Math.Clamp(pos, 0, 1) * (frames - 1));
+ bool Cross(long c) => c >= 1 && c < frames
+ && ((Mono(raw, ch, c - 1) <= 0 && Mono(raw, ch, c) >= 0) || (Mono(raw, ch, c - 1) >= 0 && Mono(raw, ch, c) <= 0));
+ for (long d = 0; d < frames; d++)
+ {
+ if (Cross(target - d)) return (target - d) / (double)(frames - 1);
+ if (Cross(target + d)) return (target + d) / (double)(frames - 1);
+ }
+ return pos;
+ }
+
+ /// <summary>Where the sound starts and ends: the first and last frame louder than
+ /// <paramref name="thresholdDb"/> below the sample's peak (normalized), or null when the
+ /// sample is silent.</summary>
+ public static (double Start, double End)? TrimSilence(float[] raw, int channels, long frames, double thresholdDb = -48)
+ {
+ int ch = Math.Max(1, channels);
+ if (frames < 2 || raw.Length < frames * ch) return null;
+ float peak = 0;
+ for (long f = 0; f < frames; f++) peak = Math.Max(peak, Math.Abs(Mono(raw, ch, f)));
+ if (peak <= 1e-6f) return null;
+ float thr = peak * (float)Math.Pow(10, thresholdDb / 20.0);
+ long a = 0, b = frames - 1;
+ while (a < frames && Math.Abs(Mono(raw, ch, a)) < thr) a++;
+ while (b > a && Math.Abs(Mono(raw, ch, b)) < thr) b--;
+ if (a >= b) return null;
+ return (a / (double)(frames - 1), Math.Min(1.0, (b + 1) / (double)(frames - 1)));
+ }
+
+ /// <summary>Downsample interleaved samples to min/max pairs per bucket (mono sum).</summary>
+ public static float[] Peaks(float[] samples, int channels, int buckets)
+ {
+ var peaks = new float[buckets * 2];
+ if (samples.Length == 0 || channels <= 0) return peaks;
+ long fr = samples.Length / channels;
+ for (int b = 0; b < buckets; b++)
+ {
+ long a = b * fr / buckets, e = (b + 1) * fr / buckets;
+ if (e <= a) e = Math.Min(fr, a + 1);
+ float mn = 1f, mx = -1f;
+ for (long f = a; f < e; f++) { float s = Mono(samples, channels, f); if (s < mn) mn = s; if (s > mx) mx = s; }
+ if (mn > mx) { mn = mx = 0; }
+ peaks[b * 2] = mn; peaks[b * 2 + 1] = mx;
+ }
+ return peaks;
+ }
+
+ // ---- telemetry ------------------------------------------------------------------------
+
+ public sealed class Snapshot
+ {
+ public int Voices, Stage = -1, Held;
+ public double PlayPos = -1, Env, Note = -1, CutoffHz = -1, Peak;
+ public bool Live;
+ }
+
+ /// <summary>Parse the engine scope. <c>Live</c> is false when the scope is empty (a
+ /// Sampler inside a rack chain) — the caller then leans on the play position alone.</summary>
+ public static void Parse(ReadOnlySpan<float> s, Snapshot o)
+ {
+ o.Live = s.Length >= ScopeLength;
+ if (!o.Live) return;
+ o.Voices = (int)s[0]; o.PlayPos = s[1]; o.Env = s[2]; o.Stage = (int)s[3];
+ o.Note = s[4]; o.CutoffHz = s[5]; o.Peak = s[6]; o.Held = (int)s[7];
+ }
+
+ // ---- words ----------------------------------------------------------------------------
+
+ private static string S(double v, string f) => v.ToString(f, CultureInfo.InvariantCulture);
+ public static string Secs(double s) => s < 1 ? S(s * 1000, "0") + " ms" : S(s, "0.00") + " s";
+ public static string Db(double db) => double.IsNegativeInfinity(db) || db < -99 ? "-inf dB" : S(db, "+0.0;-0.0;0.0") + " dB";
+ public static string Hz(double hz) => hz < 999.5 ? S(hz, "0") + " Hz" : S(hz / 1000, hz < 9950 ? "0.0" : "0") + " kHz";
+ private static string Pct(double v) => S(v * 100, "0") + " %";
+
+ /// <summary>A one-line summary of the patch, from a param-id getter, the root and the sample's length.</summary>
+ public static string Summary(Func<string, float> g, int root, double durationSec, string sampleName = "")
+ {
+ var sb = new StringBuilder();
+ if (sampleName.Length > 0) sb.Append('"').Append(sampleName).Append("\" · ");
+ if (durationSec > 0)
+ sb.Append(S(g("start") * durationSec, "0.00")).Append(" → ").Append(S(g("end") * durationSec, "0.00")).Append(" s · ");
+ int loop = LoopIndex(g("loopmode"), g("reverse"));
+ sb.Append(loop == 0 ? (g("reverse") >= 0.5f ? "one-shot reversed" : "one-shot") : "loop " + LoopNames[loop].ToLowerInvariant());
+ if (loop > 0 && durationSec > 0)
+ sb.Append(' ').Append(S(g("loopstart") * durationSec, "0.00")).Append("–").Append(S(g("loopend") * durationSec, "0.00")).Append(" s, crossfade ").Append(Secs(CrossfadeSec(g("loopxfade"))));
+ if (Math.Abs(GainDb(g("gain"))) > 0.05) sb.Append(" · gain ").Append(Db(GainDb(g("gain"))));
+ sb.Append(" · root ").Append(NoteName(root));
+ double st = TransposeSt(g("transpose")), ct = DetuneCents(g("detune"));
+ if (Math.Abs(st) > 0.01) sb.Append(" · transpose ").Append(S(st, "+0;-0")).Append(" st");
+ if (Math.Abs(ct) > 0.5) sb.Append(" · detune ").Append(S(ct, "+0;-0")).Append(" c");
+ if (g("pitchtrack") < 0.995f) sb.Append(" · keytrack ").Append(Pct(g("pitchtrack")));
+ sb.Append(" · env ").Append(Secs(AttackSec(g("attack")))).Append(" / ").Append(Secs(DecaySec(g("decay"))))
+ .Append(" / ").Append(Db(VolumeDb(g("sustain")))).Append(" / ").Append(Secs(ReleaseSec(g("release"))));
+ int ft = Index(g("filtertype"), 4);
+ if (ft > 0)
+ {
+ sb.Append(" · filter ").Append(FilterNames[ft]).Append(' ').Append(Hz(CutoffHz(g("cutoff")))).Append(", reso ").Append(Pct(g("resonance")));
+ if (g("keytrack") > 0.005f) sb.Append(", keytrack ").Append(Pct(g("keytrack")));
+ if (g("envcutoff") >= 0.5f) sb.Append(", env ").Append(S(EnvOctaves(g("envamount")), "+0.0;-0.0")).Append(" oct");
+ }
+ sb.Append(" · ").Append(VoiceNames[Index(g("voicemode"), 3)].ToLowerInvariant());
+ if (GlideSec(g("glide")) > 0) sb.Append(", glide ").Append(Secs(GlideSec(g("glide"))));
+ sb.Append(" · vol ").Append(Db(VolumeDb(g("volume"))));
+ double pan = PanSigned(g("pan"));
+ if (Math.Abs(pan) > 0.015) sb.Append(" · pan ").Append(pan < 0 ? "L" : "R").Append(S(Math.Abs(pan) * 100, "0"));
+ if (g("output") < 0.995f) sb.Append(" · out ").Append(Pct(g("output")));
+ sb.Append(" · vel→vol ").Append(Pct(g("velamount")));
+ return sb.ToString();
+ }
+
+ /// <summary>What each 0..1 parameter value means, one line per group.</summary>
+ public const string Guide =
+ "All params are normalized 0..1 (set_instrument_param_by_id, or set_sampler in real units). The sampler plays one sample, pitched by "
+ + "the key relative to the root note.\n"
+ + "start / end: the played window, 0..1 of the sample. gain: sample gain ±24 dB, 0.5 = 0 dB. reverse: 1 plays backwards. "
+ + "loopmode: Off 0 · Forward 0.5 · Ping-pong 1 (Rev = forward with reverse 1); loopstart / loopend 0..1 of the sample (inside start..end); "
+ + "loopxfade: forward-loop crossfade 0..200 ms (v*200).\n"
+ + "transpose: ±24 st, 0.5 = 0 ((v-0.5)*48). detune: ±50 cents, 0.5 = 0. pitchtrack: how far the key moves the pitch — 1 chromatic, "
+ + "0 every key plays the root. Root note: set_sampler root (not a param).\n"
+ + "attack 0.5 ms … 4 s, decay 2 ms … 6 s, release 2 ms … 6 s (all exp: lo·(hi/lo)^v); sustain: linear level 0..1 (1 = 0 dB).\n"
+ + "filtertype: Off 0 · LP .333 · HP .667 · BP 1. cutoff 20 Hz … 20 kHz (exp). resonance 0..1. keytrack: cutoff follows the key 0..100 %. "
+ + "envcutoff: 1 lets the amp envelope move the cutoff by envamount: ±6 octaves, 0.5 = none ((v-0.5)*12).\n"
+ + "voicemode: Poly 16 0 · Mono .5 · Choke 1 (a new note cuts the others). glide: 0 off, else 1 ms … 2 s (exp) — a slide from the last "
+ + "note; in Mono, legato (no retrigger, a release slides back to the held key). velamount: velocity → volume 0..100 %.\n"
+ + "volume: voice level, linear (1 = 0 dB). pan: 0 left · 0.5 centre · 1 right. output: the level after everything, linear 0..1.";
+}
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs
index a2f025ed..e6bbb25a 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs
@@ -29,10 +29,20 @@ public sealed partial class NotaEngine
}
public int RackAddSamplerChain(int trackId, string path, int rootNote, bool loop)
- { ThrowIfDisposed(); return NativeMethods.RackAddSamplerChain(_handle, trackId, path, rootNote, loop ? 1 : 0); }
+ {
+ ThrowIfDisposed();
+ int c = NativeMethods.RackAddSamplerChain(_handle, trackId, path, rootNote, loop ? 1 : 0);
+ if (c >= 0 && RackChainSamplerInfo(trackId, c, out var si)) RememberSampleName(si.SampleId, path);
+ return c;
+ }
public bool RackSetChainSamplerSample(int trackId, int chain, string path, int rootNote)
- { ThrowIfDisposed(); return NativeMethods.RackSetChainSamplerSample(_handle, trackId, chain, path, rootNote) != 0; }
+ {
+ ThrowIfDisposed();
+ bool ok = NativeMethods.RackSetChainSamplerSample(_handle, trackId, chain, path, rootNote) != 0;
+ if (ok && RackChainSamplerInfo(trackId, chain, out var si)) RememberSampleName(si.SampleId, path);
+ return ok;
+ }
public void RackOpenChainInstrumentEditor(int trackId, int chain)
{ ThrowIfDisposed(); NativeMethods.RackOpenChainInstrumentEditor(_handle, trackId, chain); }
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index 37c6c138..ae446bc4 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -499,6 +499,7 @@ public sealed partial class NotaEngine
ThrowIfDisposed();
var id = NativeMethods.AddSamplerTrack(_handle, path, rootNote, loop ? 1 : 0);
if (id <= 0) throw new NotaEngineException($"Failed to load sampler from {path}.");
+ if (TryGetSamplerInfo(id, out var si)) RememberSampleName(si.SampleId, path);
return id;
}
@@ -513,7 +514,27 @@ public sealed partial class NotaEngine
/// <summary>Loads a sample file into an existing Sampler track, keeping its params. Returns success.</summary>
public bool SetTrackSamplerSample(int trackId, string path, int rootNote = 60)
- { ThrowIfDisposed(); return NativeMethods.SetTrackSamplerSample(_handle, trackId, path, rootNote) != 0; }
+ {
+ ThrowIfDisposed();
+ bool ok = NativeMethods.SetTrackSamplerSample(_handle, trackId, path, rootNote) != 0;
+ if (ok && TryGetSamplerInfo(trackId, out var si)) RememberSampleName(si.SampleId, path);
+ return ok;
+ }
+
+ // Source names of loaded samples (the native buffer keeps only the audio).
+ private readonly Dictionary<long, string> _sampleNames = new();
+
+ private void RememberSampleName(long sampleId, string path)
+ {
+ if (sampleId == 0) return;
+ lock (_sampleNames) _sampleNames[sampleId] = System.IO.Path.GetFileNameWithoutExtension(path);
+ }
+
+ public string SampleName(long sampleId)
+ { lock (_sampleNames) return _sampleNames.TryGetValue(sampleId, out var n) ? n : ""; }
+
+ public void SetSampleName(long sampleId, string name)
+ { if (sampleId != 0) lock (_sampleNames) _sampleNames[sampleId] = name ?? ""; }
public bool SetTrackSamplerRoot(int trackId, int rootNote)
{ ThrowIfDisposed(); return NativeMethods.SetTrackSamplerRoot(_handle, trackId, rootNote) != 0; }
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 0aa0e6fd..ddb34867 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -57,6 +57,51 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Inst("synth", 0, "Filter Sweep", ("wave", 0f), ("attack", 0.35f), ("decay", 0.70f), ("sustain", 0.75f), ("release", 0.70f), ("cutoff", 0.30f), ("resonance", 0.45f), ("filenv", 0.92f), ("unison", 0.333f), ("detune", 0.57f), ("gain", 0.74f));
Inst("synth", 0, "Band Motion", ("wave", 0.333f), ("pulsewidth", 0.44f), ("attack", 0.28f), ("decay", 0.62f), ("sustain", 0.70f), ("release", 0.62f), ("filtype", 1f), ("cutoff", 0.58f), ("resonance", 0.50f), ("filenv", 0.74f), ("unison", 0.333f), ("detune", 0.60f), ("spread", 0.65f), ("gain", 0.74f));
+ // ---- Nota Sampler (kind 1) — 30 sounds for whatever sample is loaded (a preset shapes the
+ // sound; Start / End and the loop points stay with the sample unless it names them).
+ // loopmode: Off 0 / Fwd .5 / Ping 1 (+ reverse 1 = Rev) · filtertype: Off 0 / LP .333 /
+ // HP .667 / BP 1 · voicemode: Poly 0 / Mono .5 / Choke 1. attack .5 ms·8000^v; decay /
+ // release 2 ms·3000^v (.3 ≈ 22 ms, .6 ≈ 240 ms, .8 ≈ 1.2 s); cutoff 20 Hz·1000^v
+ // (.6 ≈ 1.3 k, .8 ≈ 5 k); transpose ±24 st at .5 (.25 = −12, .75 = +12); gain ±24 dB
+ // at .5; glide 1 ms·2000^v (.6 ≈ 95 ms); envamount ±6 oct at .5 (.75 = +3 oct).
+ // Basics
+ Inst("sampler", 1, "Init");
+ Inst("sampler", 1, "One-Shot", ("release", 0.20f));
+ Inst("sampler", 1, "Gated Hold", ("loopmode", 0.5f), ("loopxfade", 0.25f), ("release", 0.02f), ("voicemode", 0.5f));
+ // Keys and plucks
+ Inst("sampler", 1, "Brass Pluck", ("decay", 0.55f), ("sustain", 0f), ("release", 0.45f), ("filtertype", 0.333f), ("cutoff", 0.72f), ("resonance", 0.18f), ("envcutoff", 1f), ("envamount", 0.75f));
+ Inst("sampler", 1, "Soft Keys", ("attack", 0.15f), ("decay", 0.70f), ("sustain", 0.45f), ("release", 0.60f), ("filtertype", 0.333f), ("cutoff", 0.70f), ("keytrack", 0.5f), ("velamount", 0.8f));
+ Inst("sampler", 1, "Music Box", ("transpose", 0.75f), ("decay", 0.72f), ("sustain", 0f), ("release", 0.55f), ("filtertype", 0.333f), ("cutoff", 0.85f));
+ Inst("sampler", 1, "Mallet", ("decay", 0.60f), ("sustain", 0f), ("release", 0.50f), ("filtertype", 0.333f), ("cutoff", 0.62f), ("resonance", 0.25f), ("envcutoff", 1f), ("envamount", 0.80f));
+ Inst("sampler", 1, "Harp Pluck", ("decay", 0.68f), ("sustain", 0f), ("release", 0.60f), ("filtertype", 0.333f), ("cutoff", 0.78f), ("keytrack", 0.6f));
+ Inst("sampler", 1, "Lo-Fi Keys", ("detune", 0.45f), ("attack", 0.20f), ("decay", 0.60f), ("sustain", 0.60f), ("release", 0.50f), ("filtertype", 0.333f), ("cutoff", 0.60f), ("resonance", 0.15f), ("gain", 0.55f), ("velamount", 0.6f));
+ // Pads and loops
+ Inst("sampler", 1, "Warm Pad", ("loopmode", 0.5f), ("loopxfade", 0.50f), ("attack", 0.70f), ("decay", 0.70f), ("sustain", 0.85f), ("release", 0.78f), ("filtertype", 0.333f), ("cutoff", 0.60f));
+ Inst("sampler", 1, "Glass Pad", ("loopmode", 0.5f), ("loopxfade", 0.60f), ("transpose", 0.75f), ("attack", 0.65f), ("sustain", 0.90f), ("release", 0.80f), ("filtertype", 0.667f), ("cutoff", 0.45f));
+ Inst("sampler", 1, "Ping-Pong Drone", ("loopmode", 1f), ("attack", 0.75f), ("sustain", 1f), ("release", 0.85f), ("filtertype", 0.333f), ("cutoff", 0.55f), ("resonance", 0.20f), ("detune", 0.56f));
+ Inst("sampler", 1, "Reverse Swell", ("loopmode", 0.5f), ("reverse", 1f), ("loopxfade", 0.40f), ("attack", 0.80f), ("sustain", 0.90f), ("release", 0.70f));
+ Inst("sampler", 1, "Tape Sustain", ("loopmode", 0.5f), ("loopxfade", 0.80f), ("attack", 0.30f), ("release", 0.60f), ("filtertype", 0.333f), ("cutoff", 0.66f), ("detune", 0.47f), ("gain", 0.55f));
+ Inst("sampler", 1, "Filter Keys", ("loopmode", 0.5f), ("loopxfade", 0.50f), ("pitchtrack", 0f), ("filtertype", 0.333f), ("cutoff", 0.45f), ("resonance", 0.60f), ("keytrack", 1f), ("attack", 0.30f), ("release", 0.55f));
+ // Bass
+ Inst("sampler", 1, "Mono Bass", ("voicemode", 0.5f), ("transpose", 0.25f), ("decay", 0.60f), ("sustain", 0.60f), ("release", 0.25f), ("filtertype", 0.333f), ("cutoff", 0.55f), ("resonance", 0.25f), ("envcutoff", 1f), ("envamount", 0.70f));
+ Inst("sampler", 1, "Slide Bass", ("voicemode", 0.5f), ("glide", 0.60f), ("transpose", 0.25f), ("sustain", 0.70f), ("release", 0.30f), ("filtertype", 0.333f), ("cutoff", 0.50f), ("resonance", 0.40f), ("envcutoff", 1f), ("envamount", 0.75f));
+ Inst("sampler", 1, "Sub Drop", ("voicemode", 0.5f), ("glide", 0.70f), ("transpose", 0.25f), ("release", 0.45f), ("filtertype", 0.333f), ("cutoff", 0.42f));
+ Inst("sampler", 1, "Acid Slice", ("voicemode", 0.5f), ("glide", 0.50f), ("decay", 0.50f), ("sustain", 0.20f), ("release", 0.30f), ("filtertype", 0.333f), ("cutoff", 0.38f), ("resonance", 0.70f), ("envcutoff", 1f), ("envamount", 0.85f));
+ // Drums and one-shots
+ Inst("sampler", 1, "Drum Hit", ("voicemode", 1f), ("pitchtrack", 0f), ("release", 0.20f));
+ Inst("sampler", 1, "Choke Hat", ("voicemode", 1f), ("pitchtrack", 0f), ("decay", 0.45f), ("sustain", 0f), ("release", 0.15f), ("filtertype", 0.667f), ("cutoff", 0.70f));
+ Inst("sampler", 1, "Tuned Perc", ("decay", 0.55f), ("sustain", 0f), ("release", 0.40f), ("filtertype", 1f), ("cutoff", 0.70f), ("resonance", 0.30f), ("keytrack", 1f));
+ Inst("sampler", 1, "Chop", ("voicemode", 1f), ("attack", 0.10f), ("release", 0.12f), ("velamount", 0.7f));
+ Inst("sampler", 1, "Soft Velocity", ("velamount", 0.4f), ("attack", 0.10f), ("release", 0.30f));
+ // Character
+ Inst("sampler", 1, "Telephone", ("filtertype", 1f), ("cutoff", 0.66f), ("resonance", 0.35f), ("gain", 0.60f));
+ Inst("sampler", 1, "Dark Room", ("filtertype", 0.333f), ("cutoff", 0.50f), ("resonance", 0.05f), ("keytrack", 0.3f), ("sustain", 0.80f), ("release", 0.70f));
+ Inst("sampler", 1, "Octave Up", ("transpose", 0.75f));
+ Inst("sampler", 1, "Half Speed", ("transpose", 0.25f), ("filtertype", 0.333f), ("cutoff", 0.80f));
+ // Motion
+ Inst("sampler", 1, "Envelope Sweep", ("attack", 0.75f), ("decay", 0.70f), ("sustain", 0.50f), ("release", 0.60f), ("filtertype", 0.333f), ("cutoff", 0.35f), ("resonance", 0.45f), ("envcutoff", 1f), ("envamount", 1f));
+ Inst("sampler", 1, "Legato Lead", ("voicemode", 0.5f), ("glide", 0.55f), ("attack", 0.30f), ("sustain", 0.90f), ("release", 0.50f), ("filtertype", 0.333f), ("cutoff", 0.75f), ("keytrack", 0.5f));
+
// ---- Nota Physical (kind 2) — 32 modal patches: mallets, bells, percussion, plucked
// and blown, textures. Type (r1type / r2type): Beam 0 / Marimba .2 / String .4 /
// Membrane .6 / Plate .8 / Pipe 1 · noisetype LP 0 / BP .5 / HP 1 · structure
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
index eea3f666..d5dddf73 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
@@ -34,11 +34,13 @@ public static class PresetService
return string.IsNullOrEmpty(doc.PluginId) ? null : doc;
}
// Built-in instrument: capture the normalized plugin-params by id. Skip kinds whose
- // state isn't fully recallable from params alone — Sampler (1) & Grain (10) need the
- // sample, Rhythm (12) its patterns/samples, and the Instrument/Drum racks (3/4) their
- // chains. Everything else (Synth, Physical, Aurora, Volt, Bass, Pendulum, Operator,
- // Flux, …) is a param-only synth and saves cleanly.
- if (ik is 1 or 3 or 4 or 10 or 12) return null;
+ // state isn't fully recallable from params alone — Grain (10) needs the sample,
+ // Rhythm (12) its patterns/samples, and the Instrument/Drum racks (3/4) their chains.
+ // The Sampler (1) saves its sound — envelope, filter, pitch, loop, voices — and
+ // applying it keeps whatever sample is loaded (like its factory presets). Everything
+ // else (Synth, Physical, Aurora, Volt, Bass, Pendulum, Operator, Flux, …) is a
+ // param-only synth and saves cleanly.
+ if (ik is 3 or 4 or 10 or 12) return null;
{
int pc = engine.PluginParamCount(trackId, -1);
if (pc <= 0) return null;
@@ -171,6 +173,7 @@ public static class PresetService
{
int t = doc.BuiltinKind switch
{
+ 1 => engine.AddSamplerInstrumentTrack(),
2 => engine.AddPhysicalSynthTrack(),
5 => engine.AddWavetableSynthTrack(),
6 => engine.AddVoltSynthTrack(),
@@ -230,11 +233,15 @@ public static class PresetService
case "builtin-instrument":
{
int pc = engine.PluginParamCount(trackId, -1);
+ // The Sampler's trim and loop points belong to the loaded sample, not the
+ // sound: a preset that doesn't name them leaves them where they are.
+ bool sampler = engine.TrackInstrumentKind(trackId) == 1;
for (int i = 0; i < pc; i++)
{
string id = engine.PluginParamId(trackId, -1, i);
- float v = doc.NamedParams is { Count: > 0 } && doc.NamedParams.TryGetValue(id, out var pv)
- ? pv : engine.InstrumentParamDefault(trackId, i);
+ bool named = doc.NamedParams is { Count: > 0 } && doc.NamedParams.ContainsKey(id);
+ if (!named && sampler && id is "start" or "end" or "loopstart" or "loopend") continue;
+ float v = named ? doc.NamedParams![id] : engine.InstrumentParamDefault(trackId, i);
engine.PluginParamSet(trackId, -1, i, v);
}
return "";
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index d7d7f43e..a368ac38 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -198,6 +198,9 @@ public sealed class SamplerDto
public string Sample { get; set; } = ""; // relative bundle path ("" = empty Sampler)
public int RootNote { get; set; } = 60;
public bool Loop { get; set; }
+ /// <summary>The file name the sample came from (no extension) — the bundle stores it as
+ /// sample-N.wav, so this keeps the Sampler's "Detect from file name" working after a reload.</summary>
+ public string Name { get; set; } = "";
/// <summary>Normalized plugin-param values (vol/pan/start/end/loop/ADSR/filter…). Empty = defaults.</summary>
public float[] Params { get; set; } = System.Array.Empty<float>();
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 5d030c43..4a4baa41 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -107,6 +107,7 @@ public sealed class ProjectService
sd.RootNote = si.RootNote;
sd.Loop = si.Loop != 0;
if (si.SampleId != 0) sd.Sample = RegisterSample(doc, engine, si.SampleId, warnings) ?? "";
+ if (si.SampleId != 0) sd.Name = engine.SampleName(si.SampleId);
}
int pc = engine.PluginParamCount(ti.Id, -1);
sd.Params = new float[pc];
@@ -493,6 +494,7 @@ public sealed class ProjectService
{
int pc = engine.PluginParamCount(id, -1);
for (int p = 0; p < sd.Params.Length && p < pc; p++) engine.PluginParamSet(id, -1, p, sd.Params[p]);
+ if (sd.Name.Length > 0 && engine.TryGetSamplerInfo(id, out var nsi)) engine.SetSampleName(nsi.SampleId, sd.Name);
}
}
else if (t.Instrument is { Kind: 10, Sampler: { } gd }) // Nota Grain: sample + params
diff --git a/src/managed/Nota.Mcp/Tools/SampleTools.cs b/src/managed/Nota.Mcp/Tools/SampleTools.cs
index aee30d52..48a330b0 100644
--- a/src/managed/Nota.Mcp/Tools/SampleTools.cs
+++ b/src/managed/Nota.Mcp/Tools/SampleTools.cs
@@ -3,7 +3,8 @@
//
// MCP tools — loading audio samples into sample-based instruments: the built-in Sampler (kind 1),
// the Grain granular synth (kind 10), and a Sampler inside a rack chain. rootNote is the MIDI note
-// at which the sample plays back at its original pitch (60 = middle C).
+// at which the sample plays back at its original pitch (60 = middle C). read_sampler / set_sampler
+// read and shape the Sampler in musical units (SamplerModel holds the engine's value maps).
using System.ComponentModel;
using ModelContextProtocol.Server;
@@ -15,33 +16,208 @@ namespace Nota.Mcp.Tools;
public sealed class SampleTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh)
: EngineTools(engine, dispatch, refresh)
{
- public sealed record SamplerInfo(bool HasSample, long SampleId, int RootNote, bool Loop, int Channels, long Frames, double SampleRate);
+ public sealed record SamplerInfo(bool HasSample, long SampleId, int RootNote, bool Loop, int Channels, long Frames, double SampleRate, string Name = "");
+
+ private static int RootFor(string path, int rootNote, bool detectRoot)
+ => detectRoot && SamplerModel.DetectRoot(path) is var d and >= 0 ? d : rootNote;
[McpServerTool(Name = "add_sampler_track"), Description(
- "Add a Sampler instrument track and load an audio file into it in one step. Returns the track id.")]
- public Task<int> AddSamplerTrack(string path, int rootNote = 60) => Mutate(() =>
+ "Add a Sampler instrument track and load an audio file into it in one step. Returns the track id. detectRoot = take the root "
+ + "from a note in the file name (\"Piano_C4.wav\" → C4), falling back to rootNote.")]
+ public Task<int> AddSamplerTrack(string path, int rootNote = 60, bool detectRoot = false) => Mutate(() =>
{
int id = E.AddSamplerInstrumentTrack();
- if (id > 0) E.SetTrackSamplerSample(id, path, rootNote);
+ if (id > 0) E.SetTrackSamplerSample(id, path, RootFor(path, rootNote, detectRoot));
return id;
});
- [McpServerTool(Name = "load_sampler_sample"), Description("Load an audio file into an existing Sampler track (kind 1).")]
- public Task<bool> LoadSamplerSample(int trackId, string path, int rootNote = 60)
- => Mutate(() => E.SetTrackSamplerSample(trackId, path, rootNote));
+ [McpServerTool(Name = "load_sampler_sample"), Description(
+ "Load an audio file into an existing Sampler track (kind 1), keeping its settings. detectRoot = take the root from a note in the "
+ + "file name, falling back to rootNote.")]
+ public Task<bool> LoadSamplerSample(int trackId, string path, int rootNote = 60, bool detectRoot = false)
+ => Mutate(() => E.SetTrackSamplerSample(trackId, path, RootFor(path, rootNote, detectRoot)));
[McpServerTool(Name = "set_sampler_root"), Description("Set the Sampler's root note (the MIDI note that plays the sample at its original pitch).")]
public Task<bool> SetSamplerRoot(int trackId, int rootNote) => Mutate(() => E.SetTrackSamplerRoot(trackId, rootNote));
- [McpServerTool(Name = "get_sampler_info"), Description("Read a Sampler track's loaded sample: root note, loop flag, channels, frame count, sample rate.")]
+ [McpServerTool(Name = "get_sampler_info"), Description("Read a Sampler track's loaded sample: root note, loop flag, channels, frame count, sample rate, file name.")]
public Task<SamplerInfo> GetSamplerInfo(int trackId) => Read(() =>
{
if (!E.TryGetSamplerInfo(trackId, out var si) || si.SampleId == 0)
return new SamplerInfo(false, 0, 0, false, 0, 0, 0);
E.TryGetSampleInfo(si.SampleId, out var s);
- return new SamplerInfo(true, si.SampleId, si.RootNote, si.Loop != 0, s.Channels, s.Frames, s.SampleRate);
+ return new SamplerInfo(true, si.SampleId, si.RootNote, si.Loop != 0, s.Channels, s.Frames, s.SampleRate, E.SampleName(si.SampleId));
+ });
+
+ public sealed record SamplerValues(
+ double StartSec, double EndSec, string Loop, double LoopStartSec, double LoopEndSec, double CrossfadeMs, double GainDb,
+ string Root, int RootMidi, double TransposeSt, double DetuneCents, double PitchKeytrackPercent,
+ double AttackMs, double DecayMs, double SustainDb, double ReleaseMs, double VelocityPercent,
+ string Filter, double CutoffHz, double ResonancePercent, double FilterKeytrackPercent, bool EnvToCutoff, double EnvOctaves,
+ string Voices, double GlideMs, double VolumeDb, double PanPercent, double OutputPercent);
+ public sealed record SamplerLive(int ActiveVoices, int MaxVoices, double PlayPosition, string Stage, double Envelope, string Note, double CutoffHz);
+ public sealed record SamplerReading(string Summary, string Guide, bool HasSample, string SampleName, double DurationSec, int Channels,
+ double SampleRate, string DetectedRoot, double SoundStartSec, double SoundEndSec, SamplerValues Values, SamplerLive Live);
+
+ [McpServerTool(Name = "read_sampler"), Description(
+ "Read a Nota Sampler track (built-in instrument kind 1 — one sample pitched by the key relative to a root note). Returns a "
+ + "one-line summary, a guide to what each 0..1 parameter value means (ids for set_instrument_param_by_id, or use set_sampler), "
+ + "the sample (file name, length, channels, rate), the root a note in the file name suggests (DetectedRoot, \"—\" none), where "
+ + "the sound starts and fades out (SoundStart/End, what trimSilence would set), every setting in real units (seconds, dB, "
+ + "semitones, cents, Hz, %) and the live state: sounding voices, the loudest voice's play position 0..1, envelope stage and "
+ + "level, note (fractional while gliding) and the cutoff it hears after key tracking and the envelope (-1 = filter off).")]
+ public Task<SamplerReading?> ReadSampler(int trackId) => Read<SamplerReading?>(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != SamplerModel.Kind) return null;
+ var g = Getter(trackId);
+ E.TryGetSamplerInfo(trackId, out var si);
+ bool has = si.SampleId != 0 && E.TryGetSampleInfo(si.SampleId, out _);
+ E.TryGetSampleInfo(si.SampleId, out var s);
+ double dur = has && s.SampleRate > 0 ? s.Frames / s.SampleRate : 0;
+ string name = has ? E.SampleName(si.SampleId) : "";
+ int det = SamplerModel.DetectRoot(name);
+ double soundA = 0, soundB = dur;
+ if (has && SamplerModel.TrimSilence(E.ReadSample(si.SampleId), s.Channels, s.Frames) is { } t) { soundA = t.Start * dur; soundB = t.End * dur; }
+ int root = has ? si.RootNote : 60;
+ var v = new SamplerValues(
+ R(g("start") * dur, 3), R(g("end") * dur, 3), SamplerModel.LoopNames[SamplerModel.LoopIndex(g("loopmode"), g("reverse"))],
+ R(g("loopstart") * dur, 3), R(g("loopend") * dur, 3), R(SamplerModel.CrossfadeSec(g("loopxfade")) * 1000, 1), R(SamplerModel.GainDb(g("gain")), 1),
+ SamplerModel.NoteName(root), root, R(SamplerModel.TransposeSt(g("transpose")), 2), R(SamplerModel.DetuneCents(g("detune")), 1), R(g("pitchtrack") * 100, 1),
+ R(SamplerModel.AttackSec(g("attack")) * 1000, 1), R(SamplerModel.DecaySec(g("decay")) * 1000, 1), R(Db(g("sustain")), 1),
+ R(SamplerModel.ReleaseSec(g("release")) * 1000, 1), R(g("velamount") * 100, 1),
+ SamplerModel.FilterNames[SamplerModel.Index(g("filtertype"), 4)], R(SamplerModel.CutoffHz(g("cutoff")), 0), R(g("resonance") * 100, 1),
+ R(g("keytrack") * 100, 1), g("envcutoff") >= 0.5f, R(SamplerModel.EnvOctaves(g("envamount")), 2),
+ SamplerModel.VoiceNames[SamplerModel.Index(g("voicemode"), 3)], R(SamplerModel.GlideSec(g("glide")) * 1000, 1),
+ R(Db(g("volume")), 1), R(SamplerModel.PanSigned(g("pan")) * 100, 0), R(g("output") * 100, 1));
+ var sc = new float[SamplerModel.ScopeLength];
+ int n = E.InstrumentScope(trackId, sc);
+ var snap = new SamplerModel.Snapshot();
+ SamplerModel.Parse(sc.AsSpan(0, Math.Max(0, n)), snap);
+ var live = new SamplerLive(snap.Voices, SamplerModel.Voices, R(snap.PlayPos, 3),
+ snap.Stage is >= 0 and < 4 ? SamplerModel.StageNames[snap.Stage] : "idle", R(snap.Env, 3),
+ snap.Note >= 0 ? SamplerModel.NoteName((int)Math.Round(snap.Note)) : "—", R(snap.CutoffHz, 0));
+ return new SamplerReading(SamplerModel.Summary(g, root, dur, name), SamplerModel.Guide, has, name, R(dur, 3), s.Channels, s.SampleRate,
+ det >= 0 ? SamplerModel.NoteName(det) : "—", R(soundA, 3), R(soundB, 3), v, live);
});
+ [McpServerTool(Name = "set_sampler"), Description(
+ "Shape a Nota Sampler track (kind 1) in real units; every argument is optional and only the given ones change. "
+ + "Sample: startSec / endSec (the played window), loop Off | Fwd | Ping | Rev, loopStartSec / loopEndSec, crossfadeMs 0..200 "
+ + "(forward loops), gainDb ±24, reverse. Tools: trimSilence (Start/End to where the sound begins and fades, -48 dB), snapToZero "
+ + "(Start/End/loop to the nearest zero crossings), detectRoot (root from a note in the file name). "
+ + "Pitch: root (\"C4\", \"F#3\", \"Eb2\" or a MIDI number; C4 = 60), transposeSt ±24, detuneCents ±50, pitchKeytrackPercent 0..100 "
+ + "(0 = every key plays the root). Env: attackMs 0.5..4000, decayMs 2..6000, sustainDb (0 = full, -inf allowed as -100), "
+ + "releaseMs 2..6000, velocityPercent 0..100 (velocity → volume). Filter: filter Off | LP | HP | BP, cutoffHz 20..20000, "
+ + "resonancePercent, filterKeytrackPercent, envToCutoff on/off, envOctaves ±6. Voices: voices Poly | Mono | Choke, glideMs 0..2000 "
+ + "(Mono + glide = legato), volumeDb (≤ 0), panPercent -100..100, outputPercent 0..100. Returns the new summary, or an error line "
+ + "naming what it could not use.")]
+ public Task<string> SetSampler(int trackId,
+ double? startSec = null, double? endSec = null, string? loop = null, double? loopStartSec = null, double? loopEndSec = null,
+ double? crossfadeMs = null, double? gainDb = null, bool? reverse = null, bool? trimSilence = null, bool? snapToZero = null, bool? detectRoot = null,
+ string? root = null, double? transposeSt = null, double? detuneCents = null, double? pitchKeytrackPercent = null,
+ double? attackMs = null, double? decayMs = null, double? sustainDb = null, double? releaseMs = null, double? velocityPercent = null,
+ string? filter = null, double? cutoffHz = null, double? resonancePercent = null, double? filterKeytrackPercent = null,
+ bool? envToCutoff = null, double? envOctaves = null,
+ string? voices = null, double? glideMs = null, double? volumeDb = null, double? panPercent = null, double? outputPercent = null) => Mutate(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != SamplerModel.Kind) return $"error: track {trackId} is not a Nota Sampler";
+ int pc = E.PluginParamCount(trackId, -1);
+ var ids = new Dictionary<string, int>();
+ for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;
+ float Get(string id) => ids.TryGetValue(id, out var i) ? E.PluginParamGet(trackId, -1, i) : 0f;
+ void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ static int Find(string[] names, string v) => Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase)
+ || n.StartsWith(v.Trim(), StringComparison.OrdinalIgnoreCase));
+ var errors = new List<string>();
+
+ E.TryGetSamplerInfo(trackId, out var si);
+ float[] raw = Array.Empty<float>(); int ch = 1; long frames = 0; double dur = 0;
+ if (si.SampleId != 0 && E.TryGetSampleInfo(si.SampleId, out var s) && s.SampleRate > 0)
+ { ch = s.Channels; frames = s.Frames; dur = s.Frames / s.SampleRate; }
+ bool needDur = startSec is not null || endSec is not null || loopStartSec is not null || loopEndSec is not null;
+ if (needDur && dur <= 0) errors.Add("positions (no sample loaded)");
+ else
+ {
+ if (startSec is { } a) Set("start", a / dur);
+ if (endSec is { } b) Set("end", b / dur);
+ if (loopStartSec is { } la) Set("loopstart", la / dur);
+ if (loopEndSec is { } lb) Set("loopend", lb / dur);
+ }
+ if (loop is not null)
+ {
+ string l = loop.Trim().ToLowerInvariant() switch { "forward" => "fwd", "pingpong" or "ping-pong" => "ping", "reverse" => "rev", "none" or "one-shot" => "off", var x => x };
+ int li = Find(SamplerModel.LoopNames, l);
+ if (li < 0) errors.Add($"loop '{loop}'");
+ else { var (lm, rv) = SamplerModel.LoopValues(li); Set("loopmode", lm); Set("reverse", rv); }
+ }
+ if (reverse is { } rev) Set("reverse", rev ? 1 : 0);
+ if (crossfadeMs is { } xf) Set("loopxfade", xf / 200.0);
+ if (gainDb is { } gd) Set("gain", SamplerModel.GainNorm(gd));
+ if (trimSilence == true || snapToZero == true)
+ {
+ if (frames < 2) errors.Add("trim / snap (no sample loaded)");
+ else
+ {
+ raw = E.ReadSample(si.SampleId);
+ if (trimSilence == true && SamplerModel.TrimSilence(raw, ch, frames) is { } t) { Set("start", t.Start); Set("end", t.End); }
+ if (snapToZero == true)
+ foreach (var id in new[] { "start", "end", "loopstart", "loopend" }) Set(id, SamplerModel.SnapZero(raw, ch, frames, Get(id)));
+ }
+ }
+ if (detectRoot == true)
+ {
+ int d = SamplerModel.DetectRoot(si.SampleId != 0 ? E.SampleName(si.SampleId) : "");
+ if (d < 0) errors.Add("detectRoot (the file name names no note)"); else E.SetTrackSamplerRoot(trackId, d);
+ }
+ if (root is not null)
+ {
+ int r = SamplerModel.ParseNote(root);
+ if (r < 0) errors.Add($"root '{root}'"); else E.SetTrackSamplerRoot(trackId, r);
+ }
+ if (transposeSt is { } st) Set("transpose", SamplerModel.TransposeNorm(st));
+ if (detuneCents is { } dc) Set("detune", SamplerModel.DetuneNorm(dc));
+ if (pitchKeytrackPercent is { } pk) Set("pitchtrack", pk / 100.0);
+ if (attackMs is { } at) Set("attack", SamplerModel.ExpInv(at / 1000, 0.0005, 4.0));
+ if (decayMs is { } dm) Set("decay", SamplerModel.ExpInv(dm / 1000, 0.002, 6.0));
+ if (sustainDb is { } sd) Set("sustain", sd <= -99 ? 0 : Math.Pow(10, Math.Min(0, sd) / 20));
+ if (releaseMs is { } rm) Set("release", SamplerModel.ExpInv(rm / 1000, 0.002, 6.0));
+ if (velocityPercent is { } vp) Set("velamount", vp / 100.0);
+ if (filter is not null)
+ {
+ int f = Find(SamplerModel.FilterNames, filter.Trim().ToLowerInvariant() switch { "lowpass" or "low-pass" => "LP", "highpass" or "high-pass" => "HP", "bandpass" or "band-pass" => "BP", var x => x });
+ if (f < 0) errors.Add($"filter '{filter}'"); else Set("filtertype", f / 3.0);
+ }
+ if (cutoffHz is { } hz) Set("cutoff", SamplerModel.ExpInv(hz, 20, 20000));
+ if (resonancePercent is { } rp) Set("resonance", rp / 100.0);
+ if (filterKeytrackPercent is { } fk) Set("keytrack", fk / 100.0);
+ if (envToCutoff is { } ec) Set("envcutoff", ec ? 1 : 0);
+ if (envOctaves is { } eo) { Set("envamount", SamplerModel.EnvOctavesNorm(eo)); if (envToCutoff is null) Set("envcutoff", 1); }
+ if (voices is not null)
+ {
+ int vi = Find(SamplerModel.VoiceNames, voices);
+ if (vi < 0) errors.Add($"voices '{voices}'"); else Set("voicemode", vi / 2.0);
+ }
+ if (glideMs is { } gm) Set("glide", SamplerModel.GlideNorm(gm / 1000));
+ if (volumeDb is { } vd) Set("volume", vd <= -99 ? 0 : Math.Pow(10, Math.Min(0, vd) / 20));
+ if (panPercent is { } pp) Set("pan", 0.5 + Math.Clamp(pp, -100, 100) / 200.0);
+ if (outputPercent is { } op) Set("output", op / 100.0);
+
+ E.TryGetSamplerInfo(trackId, out var si2);
+ string summary = SamplerModel.Summary(Getter(trackId), si2.RootNote, dur, si2.SampleId != 0 ? E.SampleName(si2.SampleId) : "");
+ return errors.Count == 0 ? summary : $"error: could not use {string.Join(", ", errors)} · {summary}";
+ });
+
+ private Func<string, float> Getter(int trackId)
+ {
+ int pc = E.PluginParamCount(trackId, -1);
+ var vals = new Dictionary<string, float>();
+ for (int i = 0; i < pc; i++) vals[E.PluginParamId(trackId, -1, i)] = E.PluginParamGet(trackId, -1, i);
+ return id => vals.TryGetValue(id, out var v) ? v : 0f;
+ }
+
+ private static double R(double v, int digits) => double.IsFinite(v) ? Math.Round(v, digits) : -100;
+ private static double Db(float lin) => lin <= 1e-5f ? -100 : 20 * Math.Log10(lin);
+
[McpServerTool(Name = "add_grain_track"), Description(
"Add a Grain (granular) instrument track and load an audio file to granulate. Returns the track id.")]
public Task<int> AddGrainTrack(string path, int rootNote = 60) => Mutate(() =>
diff --git a/src/native/nota.engine/src/Sampler.h b/src/native/nota.engine/src/Sampler.h
index e7a54a90..2038afd3 100644
--- a/src/native/nota.engine/src/Sampler.h
+++ b/src/native/nota.engine/src/Sampler.h
@@ -9,6 +9,13 @@
// the Instrument plugin-param interface (normalized 0..1) so they automate/persist like
// the Nota Synth. `setSample` + kind 1 stay unchanged for Drum/Instrument Rack
// compatibility; the defaults reproduce the old one-shot behavior. Params are APPEND-ONLY.
+//
+// The 2026-09 redesign appends: sample Gain (±24 dB before the envelope), Glide (a slide
+// from the last note; in Mono it is legato — the voice keeps playing and slides, and a
+// released note slides back to the one still held), pitch Keytrack (how far the key moves
+// the pitch: 100 % chromatic, 0 % every key plays the root), Env → Cutoff (on/off + a
+// bipolar ±6 octave depth from the amp envelope) and an Output level after the voices.
+// Telemetry (scopeRead) gives the editor the loudest voice's envelope and cutoff.
#pragma once
@@ -27,7 +34,8 @@ class Sampler final : public Instrument {
public:
enum Param { Volume = 0, Pan, Transpose, Detune, Start, End, Reverse, LoopMode,
LoopStart, LoopEnd, Attack, Decay, Sustain, Release, FilterType, Cutoff, Resonance,
- VoiceMode, LoopXfade, FilterKeyTrack, VelAmount, kNumParams };
+ VoiceMode, LoopXfade, FilterKeyTrack, VelAmount,
+ Gain, Glide, PitchTrack, EnvCutoff, EnvAmount, Output, kNumParams };
Sampler() {
pn_[Volume].store(1.0f); pn_[Pan].store(0.5f);
@@ -40,6 +48,28 @@ public:
pn_[FilterType].store(0.0f); pn_[Cutoff].store(1.0f); pn_[Resonance].store(0.0f);
pn_[VoiceMode].store(0.0f); pn_[LoopXfade].store(0.1f); pn_[FilterKeyTrack].store(0.0f);
pn_[VelAmount].store(1.0f);
+ pn_[Gain].store(0.5f); pn_[Glide].store(0.0f); pn_[PitchTrack].store(1.0f); // 0 dB · no glide · chromatic
+ pn_[EnvCutoff].store(0.0f); pn_[EnvAmount].store(0.75f); pn_[Output].store(1.0f); // env → cutoff off (+3 oct when on)
+ }
+
+ // ---- value maps (mirrored by SamplerModel.cs) -------------------------------------
+ static double gainDb(float v) { return (std::clamp(v, 0.0f, 1.0f) - 0.5) * 48.0; } // ±24 dB
+ static double glideSeconds(float v) { return v <= 0.001f ? 0.0 : 0.001 * std::pow(2000.0, std::clamp(v, 0.0f, 1.0f)); } // 1 ms … 2 s
+ static double envOctaves(float v) { return (std::clamp(v, 0.0f, 1.0f) - 0.5) * 12.0; } // ±6 oct
+
+ // ---- telemetry --------------------------------------------------------------------
+ // [0] sounding voices · [1] play position 0..1 of the loudest voice (−1 silent) ·
+ // [2] its envelope level 0..1 · [3] its stage (0 A · 1 D · 2 S · 3 R, −1 none) ·
+ // [4] its note (fractional while gliding, −1 none) · [5] its cutoff in Hz after key
+ // tracking and the envelope (−1 filter off / silent) · [6] output peak since the last
+ // read, linear · [7] notes held (Mono stack depth).
+ static constexpr int kTele = 8;
+ int32_t scopeRead(float* out, int32_t maxN) const override {
+ if (!out || maxN <= 0) return 0;
+ const int n = std::min<int>(maxN, kTele);
+ for (int i = 0; i < n; ++i) out[i] = tele_[i].load(std::memory_order_relaxed);
+ if (n > 6) tele_[6].store(0.0f, std::memory_order_relaxed); // peak-hold: a read clears it
+ return n;
}
int32_t kind() const override { return 1; }
@@ -49,11 +79,13 @@ public:
std::shared_ptr<SampleBuffer> sample() const { return sample_; }
int32_t rootNote() const { return rootNote_.load(std::memory_order_relaxed); }
void setRoot(int32_t r) { rootNote_.store(std::clamp(r, 0, 127), std::memory_order_relaxed); }
- bool loopEnabled() const { return pn_[LoopMode].load(std::memory_order_relaxed) > 0.5f; }
+ bool loopEnabled() const { return loopModeOf() > 0; }
void setSample(std::shared_ptr<SampleBuffer> s, int32_t rootNote, bool loop) {
sample_ = std::move(s);
rootNote_.store(std::clamp(rootNote, 0, 127), std::memory_order_relaxed);
- pn_[LoopMode].store(loop ? 1.0f : 0.0f, std::memory_order_relaxed); // Drum Rack loop flag → forward loop
+ // The loop flag only corrects a disagreeing mode: on → forward (0.5) unless already
+ // looping (ping-pong 1.0 stays), off → one-shot. A reload keeps the loop kind.
+ if (loop != loopEnabled()) pn_[LoopMode].store(loop ? 0.5f : 0.0f, std::memory_order_relaxed);
}
void setSampleRate(double sr) override { sampleRate_ = sr > 0 ? sr : 44100.0; }
@@ -70,13 +102,19 @@ public:
std::string pluginParamId(int32_t i) const override {
static const char* ids[] = { "volume", "pan", "transpose", "detune", "start", "end", "reverse", "loopmode",
"loopstart", "loopend", "attack", "decay", "sustain", "release", "filtertype", "cutoff", "resonance",
- "voicemode", "loopxfade", "keytrack", "velamount" };
+ "voicemode", "loopxfade", "keytrack", "velamount",
+ "gain", "glide", "pitchtrack", "envcutoff", "envamount", "output" };
return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};
}
std::string pluginParamName(int32_t i) const override {
- static const char* nm[] = { "Volume", "Pan", "Transpose", "Detune", "Start", "End", "Reverse", "Loop",
- "Loop Start", "Loop End", "Attack", "Decay", "Sustain", "Release", "Filter", "Cutoff", "Resonance",
- "Voices", "Loop Xfade", "Key Track", "Vel→Vol" };
+ // Display names group by their head in the automation menu (Sample › Start,
+ // Filter › Cutoff …); the ids are what persists, so names may change.
+ static const char* nm[] = { "Out Volume", "Out Pan", "Pitch Transpose", "Pitch Detune", "Sample Start", "Sample End",
+ "Sample Reverse", "Loop Mode", "Loop Start", "Loop End",
+ "Env Attack", "Env Decay", "Env Sustain", "Env Release",
+ "Filter Type", "Filter Cutoff", "Filter Resonance",
+ "Voice Mode", "Loop Crossfade", "Filter Keytrack", "Voice Velocity",
+ "Sample Gain", "Voice Glide", "Pitch Keytrack", "Filter Env On", "Filter Env Amount", "Out Level" };
return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};
}
float pluginParamGet(int32_t i) const override { return (i >= 0 && i < kNumParams) ? pn_[i].load(std::memory_order_relaxed) : 0.0f; }
@@ -97,24 +135,46 @@ public:
void noteOn(int32_t pitch, float velocity) override {
if (!sample_ || sample_->empty()) return;
const int vm = voiceModeOf();
- if (vm == 1) { for (auto& v : voices_) if (v.active && v.stage != Stage::Release) v.stage = Stage::Release; } // Mono: release others
- else if (vm == 2) { for (auto& v : voices_) v.active = false; } // Choke: hard cut
+ const bool glide = pn_[Glide].load(std::memory_order_relaxed) > 0.001f;
+ const double from = lastNote_ >= 0 ? static_cast<double>(lastNote_) : static_cast<double>(pitch);
+ lastNote_ = pitch;
+ if (vm == 1) {
+ pushHeld(pitch);
+ if (glide) { // legato: the sounding voice keeps its place and envelope and slides
+ for (auto& v : voices_)
+ if (v.active && v.stage != Stage::Release) { v.pitch = pitch; v.velocity = velocity; return; }
+ }
+ for (auto& v : voices_) if (v.active && v.stage != Stage::Release) v.stage = Stage::Release; // Mono: release others
+ } else if (vm == 2) {
+ for (auto& v : voices_) v.active = false; // Choke: hard cut
+ }
Voice* v = findFreeVoice();
const double startF = std::clamp(pn_[Start].load(std::memory_order_relaxed), 0.0f, 1.0f) * sample_->frames;
const double endF = std::clamp(pn_[End].load(std::memory_order_relaxed), 0.0f, 1.0f) * sample_->frames;
const bool rev = pn_[Reverse].load(std::memory_order_relaxed) > 0.5f;
v->active = true; v->stage = Stage::Attack; v->env = 0.0f;
v->pitch = pitch; v->velocity = velocity; v->dir = rev ? -1 : 1;
+ v->note = glide ? from : static_cast<double>(pitch);
v->pos = rev ? std::max(startF, endF - 1.0) : startF;
v->ic1L = v->ic2L = v->ic1R = v->ic2R = 0.0;
}
void noteOff(int32_t pitch) override {
+ if (voiceModeOf() == 1) {
+ const bool top = heldN_ > 0 && held_[heldN_ - 1] == pitch;
+ popHeld(pitch);
+ // Legato glide back to the note still held underneath.
+ if (top && heldN_ > 0 && pn_[Glide].load(std::memory_order_relaxed) > 0.001f) {
+ const int32_t back = held_[heldN_ - 1];
+ for (auto& v : voices_)
+ if (v.active && v.stage != Stage::Release && v.pitch == pitch) { v.pitch = back; lastNote_ = back; return; }
+ }
+ }
for (auto& v : voices_) if (v.active && v.pitch == pitch && v.stage != Stage::Release) v.stage = Stage::Release;
}
- void allNotesOff() override { for (auto& v : voices_) v.active = false; }
+ void allNotesOff() override { for (auto& v : voices_) v.active = false; heldN_ = 0; }
void render(float* out, int32_t frames) override {
- if (!sample_ || sample_->empty()) return;
+ if (!sample_ || sample_->empty()) { publishIdle(); return; }
const double N = static_cast<double>(sample_->frames);
double startF = std::clamp(pn_[Start].load(std::memory_order_relaxed), 0.0f, 1.0f) * N;
double endF = std::clamp(pn_[End].load(std::memory_order_relaxed), 0.0f, 1.0f) * N;
@@ -132,8 +192,11 @@ public:
const int32_t root = rootNote_.load(std::memory_order_relaxed);
const double pitchOff = (pn_[Transpose].load(std::memory_order_relaxed) - 0.5) * 48.0
+ (pn_[Detune].load(std::memory_order_relaxed) - 0.5) * 1.0; // ±50 cents
+ const double pTrack = pn_[PitchTrack].load(std::memory_order_relaxed);
const double srcRatio = sample_->sourceSampleRate / sampleRate_;
- const float gain = pn_[Volume].load(std::memory_order_relaxed);
+ const float gain = pn_[Volume].load(std::memory_order_relaxed)
+ * static_cast<float>(std::pow(10.0, gainDb(pn_[Gain].load(std::memory_order_relaxed)) / 20.0))
+ * pn_[Output].load(std::memory_order_relaxed);
const double pan = pn_[Pan].load(std::memory_order_relaxed) * 2.0 - 1.0;
const float gl = static_cast<float>(std::cos((pan + 1.0) * kPi / 4.0));
const float gr = static_cast<float>(std::sin((pan + 1.0) * kPi / 4.0));
@@ -144,23 +207,39 @@ public:
const float sustain = pn_[Sustain].load(std::memory_order_relaxed);
const float velAmt = pn_[VelAmount].load(std::memory_order_relaxed); // 1 = full velocity→volume, 0 = flat
- // Filter (TPT SVF). Cutoff can key-track the note relative to the root.
+ // Glide: a one-pole slide of the voice's note toward its key (time ≈ to 63 %).
+ const double glideSec = glideSeconds(pn_[Glide].load(std::memory_order_relaxed));
+ const double glideK = glideSec > 0.0 ? 1.0 - std::exp(-static_cast<double>(kCtl) / (glideSec * sampleRate_)) : 1.0;
+
+ // Filter (TPT SVF). Cutoff can key-track the note relative to the root and follow
+ // the amp envelope; coefficients refresh every kCtl samples.
const int fType = std::clamp(static_cast<int>(std::lround(pn_[FilterType].load(std::memory_order_relaxed) * 3.0f)), 0, 3);
const double baseCut = expMap(pn_[Cutoff].load(std::memory_order_relaxed), 20.0, 20000.0);
const double kTrack = pn_[FilterKeyTrack].load(std::memory_order_relaxed);
const double k = 2.0 - 1.9 * pn_[Resonance].load(std::memory_order_relaxed);
+ const bool envOn = pn_[EnvCutoff].load(std::memory_order_relaxed) > 0.5f;
+ const double envOct = envOn ? envOctaves(pn_[EnvAmount].load(std::memory_order_relaxed)) : 0.0;
int nActive = 0;
+ float peak = 0.0f;
for (auto& v : voices_) {
if (!v.active) continue;
++nActive;
- const double inc = std::pow(2.0, (v.pitch - root + pitchOff) / 12.0) * srcRatio;
- // Per-voice filter coefficients (key-tracking shifts cutoff by note).
- double fc = baseCut;
- if (fType > 0 && kTrack > 0.0) fc = baseCut * std::pow(2.0, kTrack * (v.pitch - root) / 12.0);
- const double g = std::tan(kPi * std::clamp(fc, 20.0, sampleRate_ * 0.49) / sampleRate_);
- const double a1 = 1.0 / (1.0 + g * (g + k)), a2 = g * a1, a3 = g * a2;
+ double inc = 0.0, a1 = 0.0, a2 = 0.0, a3 = 0.0;
for (int32_t i = 0; i < frames; ++i) {
+ if ((i % kCtl) == 0) { // control rate: glide, pitch, filter coefficients
+ v.note += (v.pitch - v.note) * glideK;
+ if (std::abs(v.pitch - v.note) < 1e-4) v.note = v.pitch;
+ inc = std::pow(2.0, ((v.note - root) * pTrack + pitchOff) / 12.0) * srcRatio;
+ if (fType > 0) {
+ double fc = baseCut;
+ if (kTrack > 0.0) fc *= std::pow(2.0, kTrack * (v.note - root) / 12.0);
+ if (envOn) fc *= std::pow(2.0, envOct * v.env);
+ v.cutoff = std::clamp(fc, 20.0, sampleRate_ * 0.49);
+ const double g = std::tan(kPi * v.cutoff / sampleRate_);
+ a1 = 1.0 / (1.0 + g * (g + k)); a2 = g * a1; a3 = g * a2;
+ }
+ }
// envelope
switch (v.stage) {
case Stage::Attack: v.env += atkRate; if (v.env >= 1.0f) { v.env = 1.0f; v.stage = Stage::Decay; } break;
@@ -198,11 +277,20 @@ public:
}
}
}
- // Publish the loudest active voice's position + the voice count for the UI.
- float bestEnv = -1.0f; double bestPos = 0.0; bool any = false;
- for (auto& v : voices_) if (v.active && v.env > bestEnv) { bestEnv = v.env; bestPos = v.pos; any = true; }
- playPos_.store(any ? static_cast<float>(bestPos / N) : -1.0f, std::memory_order_relaxed);
+ for (int32_t i = 0; i < frames * 2; ++i) peak = std::max(peak, std::abs(out[i]));
+ // Publish the loudest active voice + the voice count for the UI.
+ const Voice* best = nullptr;
+ for (auto& v : voices_) if (v.active && (!best || v.env > best->env)) best = &v;
+ playPos_.store(best ? static_cast<float>(best->pos / N) : -1.0f, std::memory_order_relaxed);
activeVoices_.store(nActive, std::memory_order_relaxed);
+ tele_[0].store(static_cast<float>(nActive), std::memory_order_relaxed);
+ tele_[1].store(best ? static_cast<float>(best->pos / N) : -1.0f, std::memory_order_relaxed);
+ tele_[2].store(best ? best->env : 0.0f, std::memory_order_relaxed);
+ tele_[3].store(best ? static_cast<float>(static_cast<int>(best->stage)) : -1.0f, std::memory_order_relaxed);
+ tele_[4].store(best ? static_cast<float>(best->note) : -1.0f, std::memory_order_relaxed);
+ tele_[5].store(best && fType > 0 ? static_cast<float>(best->cutoff) : -1.0f, std::memory_order_relaxed);
+ if (peak > tele_[6].load(std::memory_order_relaxed)) tele_[6].store(peak, std::memory_order_relaxed);
+ tele_[7].store(static_cast<float>(heldN_), std::memory_order_relaxed);
}
private:
@@ -211,7 +299,7 @@ private:
struct Voice {
bool active = false;
int32_t pitch = 0, dir = 1;
- double pos = 0.0;
+ double pos = 0.0, note = 0.0, cutoff = 20000.0;
float velocity = 0.0f, env = 0.0f;
double ic1L = 0, ic2L = 0, ic1R = 0, ic2R = 0;
Stage stage = Stage::Attack;
@@ -245,6 +333,30 @@ private:
return static_cast<float>(v1); // band-pass
}
+ void publishIdle() {
+ playPos_.store(-1.0f, std::memory_order_relaxed);
+ activeVoices_.store(0, std::memory_order_relaxed);
+ tele_[0].store(0.0f, std::memory_order_relaxed); tele_[1].store(-1.0f, std::memory_order_relaxed);
+ tele_[2].store(0.0f, std::memory_order_relaxed); tele_[3].store(-1.0f, std::memory_order_relaxed);
+ tele_[4].store(-1.0f, std::memory_order_relaxed); tele_[5].store(-1.0f, std::memory_order_relaxed);
+ }
+ // Mono note stack (most recent last) for legato glide back to a still-held key.
+ void pushHeld(int32_t p) {
+ popHeld(p);
+ if (heldN_ == kHeld) { std::memmove(held_, held_ + 1, sizeof(int32_t) * (kHeld - 1)); --heldN_; }
+ held_[heldN_++] = p;
+ }
+ void popHeld(int32_t p) {
+ for (int i = 0; i < heldN_; ++i)
+ if (held_[i] == p) { std::memmove(held_ + i, held_ + i + 1, sizeof(int32_t) * (heldN_ - i - 1)); --heldN_; return; }
+ }
+
+ static constexpr int kCtl = 16; // control-rate block (glide, pitch, filter coefficients)
+ static constexpr int kHeld = 16;
+ int32_t held_[kHeld] = {};
+ int heldN_ = 0;
+ int32_t lastNote_ = -1;
+ mutable std::atomic<float> tele_[kTele] = {};
static constexpr int kVoices = 16;
Voice voices_[kVoices];
std::shared_ptr<SampleBuffer> sample_;
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 3b123168..af20f1dd 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -3004,7 +3004,7 @@ Console.WriteLine("-- Sampler --");
Check(t > 0 && se.TrackInstrumentKind(t) == 1, "AddSamplerInstrumentTrack → kind 1");
Check(se.DeviceName(t, -1) == "Nota Sampler", $"instrument is Nota Sampler (got '{se.DeviceName(t, -1)}')");
int pc = se.PluginParamCount(t, -1);
- Check(pc == 21, $"Nota Sampler exposes 21 params (got {pc})");
+ Check(pc == 27, $"Nota Sampler exposes 27 params (got {pc})");
se.AddMidiClip(t, 0.0, 4.0);
se.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 3.0, 0.9f) });
@@ -3068,6 +3068,165 @@ Console.WriteLine("-- Sampler --");
se.Seek(0); se.Play(); se.RenderOffline(sb, 16384); se.StopTransport();
Check(Rms(sb, 16384) > 0.001f, "AddSamplerTrack (one-shot) still audible");
+ // ---- the 2026-09 redesign: gain, glide, pitch keytrack, env → cutoff, output, telemetry ----
+ {
+ using var ne = new NotaEngine();
+ ne.SetBpm(120); ne.SetTimeSignature(4, 4);
+ int st = ne.AddSamplerInstrumentTrack();
+ Check(ne.SetTrackSamplerSample(st, sampPath, 60), "redesign: load the sample");
+ Check(ne.SampleName(ne.TryGetSamplerInfo(st, out var nsi) ? nsi.SampleId : 0) == System.IO.Path.GetFileNameWithoutExtension(sampPath),
+ "the engine remembers the sample's file name");
+ int npc = ne.PluginParamCount(st, -1);
+ var ni = new System.Collections.Generic.Dictionary<string, int>();
+ for (int i = 0; i < npc; i++) ni[ne.PluginParamId(st, -1, i)] = i;
+ bool idsOk = new[] { "gain", "glide", "pitchtrack", "envcutoff", "envamount", "output" }.All(ni.ContainsKey);
+ Check(idsOk && ni["gain"] == 21 && ni["output"] == 26, "new params append after velamount (gain 21 … output 26)");
+ Check(Math.Abs(ne.InstrumentParamDefault(st, ni["gain"]) - 0.5f) < 1e-4 && ne.InstrumentParamDefault(st, ni["glide"]) == 0f
+ && ne.InstrumentParamDefault(st, ni["pitchtrack"]) == 1f && ne.InstrumentParamDefault(st, ni["envcutoff"]) == 0f
+ && ne.InstrumentParamDefault(st, ni["output"]) == 1f, "new params default to the old sound (0 dB, no glide, chromatic, env off, output 100 %)");
+ Check(ne.PluginParamName(st, -1, ni["cutoff"]) == "Filter Cutoff" && ne.PluginParamName(st, -1, ni["start"]) == "Sample Start",
+ $"sampler names group by head for the automation menu (cutoff → '{ne.PluginParamName(st, -1, ni["cutoff"])}')");
+ void P(string id, float v) => ne.PluginParamSet(st, -1, ni[id], v);
+ void Reset() { for (int i = 0; i < npc; i++) ne.PluginParamSet(st, -1, i, ne.InstrumentParamDefault(st, i)); }
+ float[] Render(NotaNote[] notes, int frames = 16384)
+ {
+ ne.SetClipNotes(st, 0, notes);
+ var b = new float[frames * 2];
+ ne.Seek(0); ne.Play(); ne.RenderOffline(b, frames); ne.StopTransport();
+ return b;
+ }
+ static double Diff(float[] a, float[] b) { double d = 0; for (int i = 0; i < a.Length; i++) { double x = a[i] - b[i]; d += x * x; } return Math.Sqrt(d / a.Length); }
+ ne.AddMidiClip(st, 0.0, 4.0);
+ var one = new[] { new NotaNote(60, 0.0, 3.0, 0.9f) };
+ float baseRms = Rms(Render(one), 16384);
+ P("gain", SamplerModel.GainNorm(-12));
+ float quiet = Rms(Render(one), 16384);
+ Check(quiet < baseRms * 0.35f && quiet > baseRms * 0.15f, $"Gain −12 dB lowers the level ×0.25 ({quiet:F4} vs {baseRms:F4})");
+ Reset(); P("output", 0f);
+ Check(Rms(Render(one), 16384) < 1e-6f, "Output 0 silences the sampler");
+ Reset();
+ // Pitch keytrack 0: every key plays the root's pitch.
+ P("pitchtrack", 0f);
+ var k60 = Render(one); var k72 = Render(new[] { new NotaNote(72, 0.0, 3.0, 0.9f) });
+ Check(Diff(k60, k72) < 1e-4, "Keytrack 0 %: C5 plays exactly like the root");
+ Reset();
+ Check(Diff(Render(one), Render(new[] { new NotaNote(72, 0.0, 3.0, 0.9f) })) > 1e-3, "Keytrack 100 %: C5 plays an octave up");
+ // Env → Cutoff: with a low LP the envelope opens the filter.
+ P("filtertype", 0.333f); P("cutoff", 0.3f);
+ var closed = Render(one);
+ P("envcutoff", 1f); P("envamount", 1f);
+ var opened = Render(one);
+ Check(Rms(opened, 16384) > Rms(closed, 16384) * 1.2f, $"Env → Cutoff opens a low-pass ({Rms(opened, 16384):F4} > {Rms(closed, 16384):F4})");
+ Reset();
+ // Glide (Mono, legato): overlapping notes slide instead of retriggering → a different render.
+ var legato = new[] { new NotaNote(60, 0.0, 1.0, 0.9f), new NotaNote(67, 0.5, 1.5, 0.9f) };
+ P("voicemode", 0.5f);
+ var hard = Render(legato);
+ P("glide", 0.6f);
+ var slid = Render(legato);
+ bool fin = slid.All(float.IsFinite);
+ Check(fin && Rms(slid, 16384) > 0.001f && Diff(hard, slid) > 1e-3, "Mono + Glide slides legato (audible, finite, differs from a retrigger)");
+ Reset();
+ // Telemetry: a looping held note reports a voice, its envelope and note.
+ P("loopmode", 0.5f); P("filtertype", 0.333f); P("cutoff", 0.7f);
+ ne.SetClipNotes(st, 0, new[] { new NotaNote(64, 0.0, 4.0, 0.9f) });
+ var tb = new float[512 * 2];
+ ne.Seek(0); ne.Play();
+ for (int k = 0; k < 20; k++) ne.RenderOffline(tb, 512);
+ var sc = new float[SamplerModel.ScopeLength];
+ int sn = ne.InstrumentScope(st, sc);
+ var snap = new SamplerModel.Snapshot();
+ SamplerModel.Parse(sc.AsSpan(0, Math.Max(0, sn)), snap);
+ ne.StopTransport();
+ Check(sn == SamplerModel.ScopeLength && snap.Live && snap.Voices == 1 && snap.Env > 0.5 && Math.Abs(snap.Note - 64) < 1e-3
+ && snap.Stage is 1 or 2 && snap.PlayPos is >= 0 and <= 1 && Math.Abs(snap.CutoffHz - SamplerModel.CutoffHz(0.7f)) < 1,
+ $"telemetry: 1 voice, env {snap.Env:F2}, stage {snap.Stage}, note {snap.Note:F2}, cutoff {snap.CutoffHz:F0} Hz (got {sn} floats)");
+ // A ping-pong loop survives a sample reload (the loop flag used to force forward / off).
+ P("loopmode", 1f);
+ ne.SetTrackSamplerSample(st, sampPath, 60);
+ Check(ne.PluginParamGet(st, -1, ni["loopmode"]) == 1f, "reloading the sample keeps a ping-pong loop");
+ P("loopmode", 0.5f);
+ ne.SetTrackSamplerSample(st, sampPath, 60);
+ Check(ne.PluginParamGet(st, -1, ni["loopmode"]) == 0.5f, "reloading the sample keeps a forward loop");
+ Reset();
+
+ // The name round-trips through a project (the bundle stores sample-N.wav).
+ var nw = new System.Collections.Generic.List<string>();
+ var ndoc = ProjectService.Capture(ne, new TransportState(120.0, 1.0, false, false), nw);
+ string nb = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "nota-sampname-" + System.Guid.NewGuid().ToString("N") + ".nota");
+ ProjectService.Save(ndoc, nb, ne);
+ using (var ne2 = new NotaEngine())
+ {
+ ProjectService.Apply(ProjectService.Load(nb), ne2, nb);
+ string got = "";
+ for (int i = 0; i < ne2.TrackCount; i++)
+ if (ne2.TryGetTrackInfo(i, out var ti2) && ti2.IsInstrument && ne2.TrackInstrumentKind(ti2.Id) == 1 && ne2.TryGetSamplerInfo(ti2.Id, out var s2))
+ got = ne2.SampleName(s2.SampleId);
+ Check(got == System.IO.Path.GetFileNameWithoutExtension(sampPath), $"the sample's file name survives a project reload (got '{got}')");
+ }
+ try { System.IO.Directory.Delete(nb, true); } catch { /* best-effort */ }
+
+ // Presets: ≥ 25 factory presets, every id real, each applies in place (keeping the
+ // trim) and plays the sample finite; the browser path builds a Sampler, not a Synth.
+ var ids = new HashSet<string>(ni.Keys);
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 1).ToList();
+ Check(mine.Count >= 25, $"Nota Sampler ships ≥ 25 factory presets (got {mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Sampler preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ var broken = new List<string>();
+ foreach (var p in mine)
+ {
+ P("start", 0.1f);
+ if (cat.ApplyInPlace(ne, p.Id, st, -1).Length != 0) { broken.Add($"{p.DisplayName} (apply)"); continue; }
+ if (Math.Abs(ne.PluginParamGet(st, -1, ni["start"]) - 0.1f) > 1e-4) broken.Add($"{p.DisplayName} (lost the trim)");
+ var pb = Render(new[] { new NotaNote(60, 0.0, 1.0, 0.9f), new NotaNote(64, 0.25, 1.0, 0.9f) });
+ float r = Rms(pb, 16384), pk = pb.Max(Math.Abs);
+ if (!pb.All(float.IsFinite) || r < 0.0005f || pk > 2f) broken.Add($"{p.DisplayName} ({r:F4}/{pk:F2})");
+ }
+ Check(broken.Count == 0, $"every Sampler preset keeps the trim and plays finite{(broken.Count > 0 ? " — " + string.Join(", ", broken) : "")}");
+ int before = ne.TrackCount;
+ Check(cat.Apply(ne, mine[3].Id, 0).Length == 0 && ne.TrackCount == before + 1, "a Sampler preset from the browser adds a track");
+ bool madeSampler = ne.TryGetTrackInfo(ne.TrackCount - 1, out var lti) && ne.TrackInstrumentKind(lti.Id) == 1;
+ Check(madeSampler, "… and that track is a Sampler (it used to fall back to a Synth)");
+ Check(PresetService.Capture(ne, st, -1, "Mine") is { Type: "builtin-instrument", BuiltinKind: 1 }, "a user preset can be saved from the Sampler");
+
+ // MCP: read_sampler / set_sampler.
+ var mcp = new Nota.Mcp.Tools.SampleTools(ne, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ Reset();
+ var rd = mcp.ReadSampler(st).Result;
+ Check(rd is not null && rd.HasSample && rd.Values.Root == "C4" && rd.Values.Loop == "Off" && Math.Abs(rd.DurationSec - 0.5) < 1e-3
+ && rd.Guide.Contains("pitchtrack") && rd.SampleName.Length > 0, $"read_sampler reads the sample and its settings ({rd?.Summary})");
+ Check(mcp.ReadSampler(ne.AddInstrumentTrack()).Result is null, "read_sampler returns null for another instrument");
+ string res = mcp.SetSampler(st, loop: "Ping", startSec: 0.05, gainDb: -6, root: "A3", attackMs: 20, filter: "LP", cutoffHz: 2000,
+ envOctaves: 2, voices: "Mono", glideMs: 80, panPercent: -50).Result;
+ var rd2 = mcp.ReadSampler(st).Result!;
+ Check(!res.StartsWith("error") && rd2.Values.Loop == "Ping" && Math.Abs(rd2.Values.StartSec - 0.05) < 0.002 && Math.Abs(rd2.Values.GainDb + 6) < 0.1
+ && rd2.Values.RootMidi == 57 && Math.Abs(rd2.Values.AttackMs - 20) < 0.5 && rd2.Values.Filter == "LP" && Math.Abs(rd2.Values.CutoffHz - 2000) < 2
+ && rd2.Values.EnvToCutoff && Math.Abs(rd2.Values.EnvOctaves - 2) < 0.01 && rd2.Values.Voices == "Mono" && Math.Abs(rd2.Values.GlideMs - 80) < 1
+ && Math.Abs(rd2.Values.PanPercent + 50) < 1, $"set_sampler shapes the Sampler in real units ({res})");
+ string trim = mcp.SetSampler(st, trimSilence: true, snapToZero: true).Result;
+ Check(!trim.StartsWith("error"), $"set_sampler trims silence and snaps to zero ({trim})");
+ string err = mcp.SetSampler(st, loop: "Sideways", root: "H9").Result;
+ Check(err.StartsWith("error") && err.Contains("Sideways") && err.Contains("H9"), $"set_sampler names the values it cannot use ({err})");
+ }
+
+ // SamplerModel: notes from file names, silence, zero crossings.
+ Check(SamplerModel.DetectRoot("Piano_C4.wav") == 60 && SamplerModel.DetectRoot("Str Eb3 soft") == 51 && SamplerModel.DetectRoot("bass-F#1-rr2") == 30
+ && SamplerModel.DetectRoot("a-1 test") == 9 && SamplerModel.DetectRoot("Break 2") == -1 && SamplerModel.DetectRoot("kick") == -1 && SamplerModel.DetectRoot("mix2") == -1,
+ "DetectRoot finds the note in a file name (C4 = 60) and nothing where there is none");
+ Check(SamplerModel.ParseNote("A4") == 69 && SamplerModel.ParseNote("60") == 60 && SamplerModel.ParseNote("Bb2") == 46 && SamplerModel.ParseNote("X3") == -1, "ParseNote reads names and MIDI numbers");
+ {
+ var sil = new float[1000];
+ for (int i = 200; i < 700; i++) sil[i] = (float)Math.Sin(i * 0.3);
+ var tr = SamplerModel.TrimSilence(sil, 1, 1000);
+ Check(tr is { } tt && Math.Abs(tt.Start * 999 - 201) < 3 && Math.Abs(tt.End * 999 - 700) < 3, $"TrimSilence finds where the sound starts and ends ({tr})");
+ double z = SamplerModel.SnapZero(sil, 1, 1000, 0.3);
+ long zf = (long)Math.Round(z * 999);
+ Check(Math.Sign(sil[zf - 1]) != Math.Sign(sil[zf]) || sil[zf] == 0 || sil[zf - 1] == 0, $"SnapZero lands on a zero crossing (frame {zf})");
+ Check(SamplerModel.LoopIndex(0.5f, 1f) == 3 && SamplerModel.LoopValues(3) == (0.5f, 1f) && SamplerModel.LoopIndex(1f, 0f) == 2, "Loop Rev = a forward loop played in reverse");
+ }
+
try { System.IO.File.Delete(sampPath); System.IO.Directory.Delete(bundle, true); } catch { /* best-effort */ }
}
@@ -7607,7 +7766,7 @@ Console.WriteLine("-- Drum Rack: engine + C ABI + persistence --");
// Rich Sampler editing per pad: chain param id/count/default + Sampler info/root all
// reachable so the full editor works inside a Drum Rack pad (not just the track).
- Check(re.RackChainInstrumentParamCount(t, p2) == 21, "sampler pad exposes 21 chain params");
+ Check(re.RackChainInstrumentParamCount(t, p2) == 27, "sampler pad exposes 27 chain params");
Check(re.RackChainInstrumentParamId(t, p2, 4) == "start", $"chain param id maps (got '{re.RackChainInstrumentParamId(t, p2, 4)}')");
Check(re.RackChainSamplerInfo(t, p2, out var cinfo) && cinfo.SampleId != 0 && cinfo.RootNote == 40, "chain sampler info (sample + root) readable");
// Load a (new) sample into an existing chain Sampler (the pop-out drop path).