Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Instruments and FXs previews
Egor Khindikaynen419e38542370
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 910db418..12ad565a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,16 @@ created, and the build-and-publish run starts.Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.### Added+- Preview presets before loading them. The browser's player now also sits under the+ Instruments, Audio Effects, MIDI Effects and Presets tabs: select a preset (or a built-in+ device, to hear its default sound) and it plays. Instruments play a phrase that suits+ them — a chord for a pad, a riff for a bass, a line for a lead, a groove for Nota Rhythm.+ MIDI effects play a short phrase through a simple keys sound. Audio effects process a+ demo: drums (Beat), chords (Keys) or a full loop, chosen to suit the effect. Pick another+ with the source button, including the sample you last selected in Files. Sounds are+ prepared in the background and remembered, and the next preset is prepared ahead, so+ ↑ ↓ through a folder plays each one at once. Click **SPEC** in the waveform to see a live+ spectrum instead. Racks, drum kits and plug-in presets can't be previewed yet.- A new sample player at the bottom of the browser's Files tab. It shows the file's realwaveform: click it to play from that point, hover to see the time. It also has Play / Stop,a time readout, Loop, Auto (a file plays as soon as you select it) and a preview volumediff --git a/FEATURES.md b/FEATURES.mdindex 3fb34d14..ece225a8 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -640,6 +640,19 @@ and user presets, automation, persistence and cloning.search box counts the matches.- **Preview** a sample from the browser, and **drag and drop** onto a track, into the grid,or into a rack chain.+- **Preset preview**: the same player sits under the Instruments, Audio Effects, MIDI+ Effects and Presets tabs and plays the selected factory preset, saved preset or built-in+ device (its default sound). The preset is rendered offline on a standalone chain (not a+ track) in a few milliseconds and cached, and the row below is rendered ahead, so ↑ ↓+ through a folder plays each sound at once. Instruments play a phrase that suits them —+ a chord for pads, a riff for basses, a line for leads, an arpeggio for plucks and bells, a+ groove for Nota Rhythm, a held chord for Pendulum / Consort. MIDI effects play a phrase+ that shows what they do into a plain keys patch. Audio effects process a demo — **Beat**,+ **Keys** or **Loop** (drums, keys and bass), picked per device (dynamics get the beat,+ reverbs and delays the keys, EQ and drive the loop) — or the **sample** last selected in+ Files; the source chip changes it. **WAVE / SPEC** in the well switches to a live spectrum+ of what is playing. Racks, drum kits and plug-in presets aren't previewed (the well says+ why).- Dropping an instrument onto an existing track **replaces the instrument** in place(clips, devices and volume are kept); dropping onto empty space creates a new track.Racks are not replaced in place.diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.csindex a72cbf56..9202ad24 100644--- a/src/managed/Nota.App/App.axaml.cs+++ b/src/managed/Nota.App/App.axaml.cs@@ -39,6 +39,7 @@ public partial class App : Avalonia.Applicationservices.AddSingleton<IProjectStore, ProjectStore>();services.AddSingleton<IPresetStore, PresetStore>();services.AddSingleton<IFactoryPresets, FactoryPresetCatalog>();+ services.AddSingleton<IPresetAudition, PresetAudition>();services.AddSingleton<IDrumKits, DrumKitService>();services.AddSingleton<IBrowserLibrary, BrowserLibraryService>();services.AddSingleton<IAudioDeviceService, AudioDeviceService>();diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.csindex 94b19fa7..bad985a7 100644--- a/src/managed/Nota.App/BrowserView.cs+++ b/src/managed/Nota.App/BrowserView.cs@@ -8,11 +8,10 @@// drops to tertiary ink so names scan on their distinctive word, and the device// type sits at the right edge as a quiet tag. A search box filters the active list// live, a ⋮ button holds the view options, chips filter by favorite/tag, a status-// line counts what is on screen, and a pinned preview footer auditions the selected-// sample (Files tab, see PreviewPlayer). Double-clicking an item raises ItemActivated.-// Brushes bind via-// GetResourceObservable (the control is built during MainWindow's XAML load, before-// it is attached). Rows are drag sources (M7-5).+// line counts what is on screen, and a pinned preview footer auditions the selection — a+// sample, a preset or a built-in device (list tabs, see PreviewPlayer). Double-clicking an+// item raises ItemActivated. Brushes bind via GetResourceObservable (the control is built+// during MainWindow's XAML load, before it is attached). Rows are drag sources (M7-5).using System;using System.Collections.ObjectModel;@@ -150,7 +149,8 @@ public sealed class BrowserView : UserControl}private const int TabCount = 7; // Instr / FX / MIDI / Files / Preset / Proj / Map- private const int FilesTab = 3; // the only tab with a sample auditioner+ private const int FilesTab = 3; // samples: the player auditions the file+ private const int PresetsTab = 4; // Instr / FX / MIDI / Files / Presets carry the playerprivate const int MapTab = 6; // MIDI-learn mappings — hosts a MidiMapView, not a listprivate const double RowH = 26; // single-line index row (almanac list row: 26–28, one line)private const double GroupRowH = 22;@@ -189,7 +189,7 @@ public sealed class BrowserView : UserControlprivate readonly Border _emptyWrap;// Pinned preview footer + the status line under it.- private readonly PreviewPlayer _previewFooter; // sample auditioner — Files tab only+ private readonly PreviewPlayer _previewFooter; // sample / preset auditioner — list tabsprivate readonly Border _statusBar;private readonly TextBlock _statusText;@@ -321,6 +321,7 @@ public sealed class BrowserView : UserControl_chipsHost = new Border { Margin = new Thickness(8, 0, 8, 7), Child = _chipsPanel };_previewFooter = new PreviewPlayer();+ _previewFooter.SetContext(files: _active == FilesTab);// Status line: what the active tab is showing, counted._statusText = new TextBlock { FontSize = 9, VerticalAlignment = VerticalAlignment.Center };@@ -599,8 +600,12 @@ public sealed class BrowserView : UserControl_content.Content = isMap ? (Control?)_midiMap : _pages[index];_searchWrap.IsVisible = !isMap;_optionsBtn.IsVisible = !isMap;- // The sample auditioner only makes sense for the Files tab.- _previewFooter.IsVisible = index == FilesTab;+ // The auditioner follows the list tabs: samples in Files, presets and built-in devices+ // in Instr / FX / MIDI / Presets. It picks up the new tab's selection.+ bool auditions = index <= PresetsTab;+ _previewFooter.IsVisible = auditions;+ _previewFooter.SetContext(files: index == FilesTab);+ if (auditions) SyncPreview(_pages[index]);// Favorite/tag filter chips apply only to the device tabs._chipsHost.IsVisible = index is 0 or 1 or 2;_statusBar.IsVisible = !isMap;@@ -952,12 +957,27 @@ public sealed class BrowserView : UserControl/// the key isn't the browser's (another tab, nothing to play) so it falls to the transport.</summary>public bool TryTogglePreview(object? source){- if (_active != FilesTab || !_previewFooter.HasSample) return false;+ if (_active > PresetsTab || !_previewFooter.HasSample) return false;for (var c = source as StyledElement; c is not null; c = c.Parent)- if (c == _pages[FilesTab] || c == _previewFooter) { _previewFooter.Toggle(); return true; }+ if (c == _pages[_active] || c == _previewFooter) { _previewFooter.Toggle(); return true; }return false;}+ // Hands the player a list's selection and the row below it (which the player pre-renders,+ // so arrowing down plays at once).+ private void SyncPreview(ListBox list)+ {+ var item = list.SelectedItem as BrowserItem;+ BrowserItem? next = null;+ if (item is not null && list.ItemsSource is System.Collections.IList rows)+ {+ int i = rows.IndexOf(item);+ for (int j = i + 1; i >= 0 && j < rows.Count; j++)+ if (rows[j] is BrowserItem { IsGroup: false } r && r.Kind != BrowserItemKind.Folder) { next = r; break; }+ }+ _previewFooter.SetItem(item, next);+ }+private ListBox NewList(IDataTemplate itemTemplate) => new(){Classes = { "browser" },@@ -972,13 +992,13 @@ public sealed class BrowserView : UserControlif (list.SelectedItem is not BrowserItem { IsGroup: false } item) return;// Folders (sample dirs, preset categories) are navigation: double-click opens them.if (item.Kind == BrowserItemKind.Folder) _vm?.ToggleExpand(item);- else ItemActivated?.Invoke(item);+ else { _previewFooter.StopAudition(); ItemActivated?.Invoke(item); }};list.SelectionChanged += (_, _) =>{// Section headers are chrome: never let one become the selection.if (list.SelectedItem is BrowserItem { IsGroup: true }) { list.SelectedItem = null; return; }- if (list == _pages[FilesTab]) _previewFooter.SetItem(list.SelectedItem as BrowserItem);+ if (_active <= PresetsTab && list == _pages[_active]) SyncPreview(list);};// Drag source (M7-5): start a copy-drag when the pointer leaves the row.// Must use handledEventsToo — ListBoxItem marks PointerPressed as Handled fordiff --git a/src/managed/Nota.App/Controls/Fft.cs b/src/managed/Nota.App/Controls/Fft.csnew file mode 100644index 00000000..17f5f3a1--- /dev/null+++ b/src/managed/Nota.App/Controls/Fft.cs@@ -0,0 +1,46 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System;++namespace Nota.App;++/// <summary>In-place iterative radix-2 Cooley–Tukey FFT (length a power of two).</summary>+internal static class Fft+{+ public static void Transform(double[] re, double[] im)+ {+ int n = re.Length;+ for (int i = 1, j = 0; i < n; i++)+ {+ int bit = n >> 1;+ for (; (j & bit) != 0; bit >>= 1) j ^= bit;+ j ^= bit;+ if (i < j)+ {+ (re[i], re[j]) = (re[j], re[i]);+ (im[i], im[j]) = (im[j], im[i]);+ }+ }+ for (int len = 2; len <= n; len <<= 1)+ {+ double ang = -2 * Math.PI / len, wr = Math.Cos(ang), wi = Math.Sin(ang);+ for (int i = 0; i < n; i += len)+ {+ double cr = 1, ci = 0;+ for (int k = 0; k < len / 2; k++)+ {+ int a = i + k, b = i + k + len / 2;+ double tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;+ re[b] = re[a] - tr;+ im[b] = im[a] - ti;+ re[a] += tr;+ im[a] += ti;+ double ncr = cr * wr - ci * wi;+ ci = cr * wi + ci * wr;+ cr = ncr;+ }+ }+ }+ }+}diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex a9207772..b2a9dd6a 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -280,7 +280,7 @@ public partial class MainWindow : WindowTimeline.ShowSections = vm.Settings.Current.ArrangementShowSections;Browser.SetViewModel(vm.Browser);Browser.ItemActivated += OnBrowserItemActivated;- Browser.Preview.Attach(vm.Engine, vm.Settings);+ Browser.Preview.Attach(vm.Engine, vm.Settings, App.Services.GetRequiredService<IPresetAudition>());Browser.Preview.StatusChanged += msg => { if (_vm is not null) _vm.StatusText = msg; };Browser.RevealRequested += OnBrowserReveal;Browser.DeleteProjectRequested += OnBrowserDeleteProject;diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex c3d4d61f..ec1ab31d 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -696,11 +696,12 @@ public sealed class PreferencesWindow : NotaWindow("Z / X", "Shift octave down / up"),("C / V", "Lower / raise velocity"),}),- ("BROWSER · FILES", new[]+ ("BROWSER · PREVIEW", new[]{- ("↑ ↓", "Move through the files · with Auto on, each one plays as it is selected"),- ("Space", "Play / stop the selected sample (while the Files list has focus)"),+ ("↑ ↓", "Move through samples, presets and devices · with Auto on, each one plays as it is selected"),+ ("Space", "Play / stop the selected sample, preset or device (while a browser list has focus)"),("Click waveform", "Play from that point"),+ ("Click WAVE / SPEC", "Switch the well between the waveform and a live spectrum"),("Double-click volume", "Reset the preview volume to 0\u2009dB"),}),("GAMEPAD (MACOS)", new[]diff --git a/src/managed/Nota.App/PreviewPlayer.cs b/src/managed/Nota.App/PreviewPlayer.csindex 4b3450ae..3f249b5f 100644--- a/src/managed/Nota.App/PreviewPlayer.cs+++ b/src/managed/Nota.App/PreviewPlayer.cs@@ -1,18 +1,25 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// The sample auditioner pinned under the browser's Files tab ("Nota Preview Player",-// strip 1a): the file's name and format, its real waveform in a well (click = seek,-// hover = time tag, a brass playhead while it plays), then Play/Stop, the time readout,-// Loop, Auto (selecting a file plays it) and a preview-volume fader (double-click =-// 0 dB). The waveform is decoded off the UI thread through the engine's background-// import; playback is the engine's audition voice, polled for its playhead while live.-// Auto / Loop / volume persist in Settings. In a narrow browser the strip sheds by need-// (see Adapt): Auto drops its label, the total time goes (the meta line carries it), the-// fader folds into a speaker that pops it up, then Loop, then the time readout.+// The auditioner pinned under the browser ("Nota Preview Player", strip 1a). It plays the+// selected sample (Files) or the selected preset / built-in device (Instr, FX, MIDI, Presets):+// the name and format, the real waveform in a well (click = seek, hover = time tag, a brass+// playhead while it plays) or — WAVE / SPEC in the well's corner — a live spectrum of what+// the preview voice is playing, then Play/Stop, the time readout, the effect source (FX+// presets only), Loop, Auto (selecting plays it) and a preview-volume fader (double-click =+// 0 dB). A sample's waveform is decoded off the UI thread through the engine's background+// import. A preset is rendered OFFLINE: IPresetAudition plans a phrase that suits it, a+// worker builds and renders a standalone rig (see IAuditionRig), and the engine keeps the+// result in its audition cache; the row below the selection is then pre-rendered, so+// arrowing down a list plays at once. Playback is the engine's audition voice, polled for+// its playhead while live. Auto / Loop / volume / source / view persist in Settings. In a+// narrow browser the strip sheds by need (see Adapt): Auto drops its label, the total time+// goes (the meta line carries it), the fader folds into a speaker that pops it up, then+// Loop, then the time readout.using System;using System.Collections.Generic;+using System.Linq;using File = System.IO.File;using BinaryReader = System.IO.BinaryReader;using System.Threading;@@ -40,27 +47,37 @@ public sealed class PreviewPlayer : UserControlprivate readonly TextBlock _name, _meta, _timeNow, _timeTotal;private readonly PreviewWaveform _wave;- private readonly Border _playBtn, _loopBtn, _autoBtn;+ private readonly Border _playBtn, _loopBtn, _autoBtn, _sourceBtn;private readonly Path _playGlyph, _stopGlyph, _loopIcon, _volWaves;private readonly Ellipse _autoDot;- private readonly TextBlock _autoText;+ private readonly TextBlock _autoText, _sourceText;private readonly PreviewVolume _volume, _volumePop;private readonly Border _volIconBtn;private readonly StackPanel _time;private readonly Flyout _volFlyout;private string[] _metaParts = Array.Empty<string>();private bool _volCompact;- private readonly DispatcherTimer _poll;+ private readonly DispatcherTimer _poll, _renderHint;private IAudioEngine? _engine;private ISettingsService? _settings;- private BrowserItem? _item;- private double _duration; // seconds; 0 until the header is read- private double _pos; // seconds into the file- private bool _playing, _loop, _auto = true;+ private IPresetAudition? _audition;+ private BrowserItem? _item; // the sample, or the preset / device row+ private AuditionPlan? _plan; // set when _item is a preset / device that can render+ private BrowserItem? _next; // the row below the selection: pre-rendered+ private string? _samplePath; // the Files tab's last sample — an effect's Sample source+ private string _fxTrack = AuditionTrackIds.Auto;+ private double _duration; // seconds; 0 until the header is read / the render lands+ private double _pos; // seconds into the file+ private bool _playing, _loop, _spectrum;+ // Auto has two settings: Files (samples, on by default) and the device tabs (presets, off+ // by default). The chip shows the one of the tab the browser is on.+ private bool _autoFiles = true, _autoPresets, _filesContext = true;+ private bool _auto => _filesContext ? _autoFiles : _autoPresets;private int _loadGen;- // Decoded overviews by path, so arrowing back through a folder doesn't re-decode.+ // Decoded overviews by path (samples) or audition key (presets), so arrowing back through+ // a list doesn't re-decode or re-render.private readonly Dictionary<string, FileInfoCache> _cache = new(StringComparer.Ordinal);private readonly Queue<string> _cacheOrder = new();private const int CacheMax = 64;@@ -69,6 +86,20 @@ public sealed class PreviewPlayer : UserControl// Meta is the format line split in parts, most important first (length, rate, depth, channels).private sealed record FileInfoCache(double Duration, string[] Meta, float[]? Peaks);+ // The one render in flight (the selection's, or a prefetch of the row below it).+ private sealed class RenderJob(AuditionPlan plan, bool prefetch)+ {+ public AuditionPlan Plan { get; } = plan;+ public bool Prefetch { get; set; } = prefetch;+ private IAuditionRig? _rig;+ private volatile bool _cancelled;+ public bool Cancelled => _cancelled;+ public void Attach(IAuditionRig rig) { lock (this) { _rig = rig; if (_cancelled) rig.Cancel(); } }+ public void Cancel() { lock (this) { _cancelled = true; _rig?.Cancel(); } }+ }+ private RenderJob? _job;+ private string? _playWhenReady; // audition key to start once its render lands+/// <summary>Audition failed or started — for the status line.</summary>public event Action<string>? StatusChanged;@@ -91,9 +122,10 @@ public sealed class PreviewPlayer : UserControlGrid.SetColumn(_meta, 1);head.Children.Add(_meta);- // Row 2: the waveform well.+ // Row 2: the waveform / spectrum well._wave = new PreviewWaveform { Height = 46 };_wave.SeekRequested += f => { if (_item is not null && _duration > 0) Play(f * _duration); };+ _wave.ViewToggled += () => SetSpectrum(!_spectrum, persist: true);// Row 3: transport._playGlyph = new Path@@ -120,6 +152,30 @@ public sealed class PreviewPlayer : UserControlVerticalAlignment = VerticalAlignment.Center, Children = { _timeNow, _timeTotal },};+ // Effect presets: what they are heard through (Beat / Keys / Loop / the Files sample).+ _sourceText = new TextBlock+ {+ FontSize = 10, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextSecondary,+ VerticalAlignment = VerticalAlignment.Center,+ };+ var caret = new Path+ {+ Data = Geometry.Parse("M0 0 L6 0 L3 3.5 Z"), Width = 6, Height = 4, Fill = NotaPalette.TextTertiary,+ VerticalAlignment = VerticalAlignment.Center,+ };+ _sourceBtn = Chip(new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center,+ Children = { _sourceText, caret },+ }, double.NaN, 22, 4);+ _sourceBtn.Padding = new Thickness(7, 0);+ _sourceBtn.BorderBrush = NotaPalette.BorderDefault;+ _sourceBtn.Margin = new Thickness(0, 0, 6, 0);+ _sourceBtn.IsVisible = false;+ _sourceBtn.PointerPressed += (_, e) => { if (IsLeft(e)) { ShowSourceMenu(); e.Handled = true; } };+ // The wheel steps through the tracks without opening the menu (quick A / B).+ _sourceBtn.PointerWheelChanged += (_, e) => { StepTrack(e.Delta.Y < 0 ? 1 : -1); e.Handled = true; };+_loopIcon = IconPath(IconLoop);_loopBtn = Chip(Icon12(_loopIcon), 22, 22, 4);ToolTip.SetTip(_loopBtn, "Loop");@@ -170,12 +226,14 @@ public sealed class PreviewPlayer : UserControlDockPanel.SetDock(vol, Dock.Right);DockPanel.SetDock(_autoBtn, Dock.Right);DockPanel.SetDock(_loopBtn, Dock.Right);+ DockPanel.SetDock(_sourceBtn, Dock.Right);_autoBtn.Margin = new Thickness(6, 0);controls.Children.Add(_playBtn);controls.Children.Add(time);controls.Children.Add(vol);controls.Children.Add(_autoBtn);controls.Children.Add(_loopBtn);+ controls.Children.Add(_sourceBtn);Content = new Border{@@ -190,6 +248,13 @@ public sealed class PreviewPlayer : UserControl_poll = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(30) };_poll.Tick += (_, _) => Poll();+ // A slow render (a long tail, a generative synth) says so; a quick one never flashes it.+ _renderHint = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(150) };+ _renderHint.Tick += (_, _) =>+ {+ _renderHint.Stop();+ if (_plan is not null && _job is { Prefetch: false } && _job.Plan.Key == _plan.Key) _wave.Hint = "rendering…";+ };SetLoop(false, persist: false);SetAuto(true, persist: false);@@ -199,47 +264,118 @@ public sealed class PreviewPlayer : UserControlprivate readonly StackPanel _volumeBox;- /// <summary>Wire the engine (playback, decode) and the settings (Auto / Loop / volume).</summary>- public void Attach(IAudioEngine engine, ISettingsService settings)+ /// <summary>Wire the engine (playback, decode, render), the settings (Auto / Loop / volume /+ /// source / view) and the preset planner.</summary>+ public void Attach(IAudioEngine engine, ISettingsService settings, IPresetAudition audition){_engine = engine;_settings = settings;- SetAuto(settings.Current.BrowserPreviewAuto, persist: false);+ _audition = audition;+ _autoFiles = settings.Current.BrowserPreviewAuto;+ _autoPresets = settings.Current.BrowserPresetPreviewAuto;+ SetAuto(_auto, persist: false);SetLoop(settings.Current.BrowserPreviewLoop, persist: false);ApplyVolume(Math.Clamp(settings.Current.BrowserPreviewVolume, 0, 1), persist: false);+ var track = settings.Current.BrowserPreviewFxTrack;+ _fxTrack = track == AuditionTrackIds.Sample || audition.Tracks.Any(t => t.Id == track) ? track : AuditionTrackIds.Auto;+ SetSpectrum(settings.Current.BrowserPreviewSpectrum, persist: false);}- /// <summary>The browser selection moved. A sample loads its waveform (and plays, with Auto- /// on); anything else empties the player and stops what it was playing.</summary>- public void SetItem(BrowserItem? item)+ /// <summary>The browser selection moved. A sample loads its waveform, a preset or built-in+ /// device renders its audition (and plays, with Auto on); anything else empties the player+ /// and stops what it was playing. <paramref name="next"/> is the row below, pre-rendered.</summary>+ public void SetItem(BrowserItem? item, BrowserItem? next = null){- var sample = item is { Kind: BrowserItemKind.Sample } && !string.IsNullOrEmpty(item.Path) ? item : null;- if (sample is not null && _item is not null && sample.Path == _item.Path) return;+ _next = next;+ var subject = SubjectOf(item);+ bool sample = item is { Kind: BrowserItemKind.Sample } && !string.IsNullOrEmpty(item.Path);+ if (!sample && subject is null) item = null;+ if (item is not null && _item is not null && item.Kind == _item.Kind && item.Path == _item.Path+ && item.BuiltinKind == _item.BuiltinKind) { Prefetch(); return; }+bool wasPlaying = _playing;- _item = sample;+ _item = item;+ _plan = null;_pos = 0;_duration = 0;_metaParts = Array.Empty<string>();_wave.SetPeaks(null);- if (sample is null)+ _wave.Hint = null;+ _wave.ClearSpectrum();+ _playWhenReady = null;+ if (item is null){+ _wave.Hint = null;if (wasPlaying) Stop();Refresh();return;}- LoadInfo(sample.Path);- if (_auto) Play(0);- else { if (wasPlaying) Stop(); Refresh(); }+ if (sample)+ {+ _samplePath = item.Path;+ LoadInfo(item.Path);+ if (_autoFiles) Play(0);+ else { if (wasPlaying) Stop(); Refresh(); }+ return;+ }+ Replan(play: _autoPresets, wasPlaying);}- /// <summary>Space in the Files list: play the selected sample, or stop it.</summary>+ /// <summary>Space in a browser list: play the selection, or stop it.</summary>public void Toggle(){if (_playing) Stop();else Play(0);}- public bool HasSample => _item is not null;+ /// <summary>True when there is something to play (a sample or a renderable preset).</summary>+ public bool HasSample => _item is not null && (_plan is not null || _item.Kind == BrowserItemKind.Sample);++ /// <summary>Stops a preset audition (the row was just loaded onto a track).</summary>+ public void StopAudition()+ {+ if (_plan is not null && _playing) Stop();+ _playWhenReady = null;+ }++ private static AuditionSubject? SubjectOf(BrowserItem? item) => item switch+ {+ { IsGroup: true } => null,+ { Kind: BrowserItemKind.Preset } => new AuditionSubject(AuditionSubjectKind.Preset, item.BuiltinKind, item.Path, item.Name),+ { Kind: BrowserItemKind.BuiltinInstrument } => new AuditionSubject(AuditionSubjectKind.Instrument, item.BuiltinKind, "", item.Name),+ { Kind: BrowserItemKind.BuiltinEffect } => new AuditionSubject(AuditionSubjectKind.AudioEffect, item.BuiltinKind, "", item.Name),+ { Kind: BrowserItemKind.BuiltinMidiEffect } => new AuditionSubject(AuditionSubjectKind.MidiEffect, item.BuiltinKind, "", item.Name),+ _ => null,+ };++ // (Re)plans the preset / device row under the current source and renders or replays it.+ private void Replan(bool play, bool wasPlaying)+ {+ if (_item is null || _audition is null || SubjectOf(_item) is not { } subject) return;+ _plan = _audition.Plan(subject, _fxTrack, _samplePath, out var reason);+ if (_plan is null)+ {+ if (wasPlaying) Stop();+ if (_job is { } j) { j.Cancel(); _job = null; }+ _wave.Hint = reason;+ Refresh();+ return;+ }+ if (_cache.TryGetValue(_plan.Key, out var hit)) ShowInfo(hit);+ else _metaParts = AuditionMeta(_plan, 0);+ bool cached = _engine?.IsAuditionCached(_plan.Key) == true;+ if (cached && hit is not null)+ {+ if (play) Play(0);+ else { if (wasPlaying) Stop(); Refresh(); }+ Prefetch();+ return;+ }+ if (wasPlaying) Stop(); // the old sound must not run on under the new name+ StartRender(_plan, prefetch: false);+ if (play) _playWhenReady = _plan.Key;+ Refresh();+ }// --- playback -------------------------------------------------------------@@ -250,7 +386,20 @@ public sealed class PreviewPlayer : UserControl{_engine.SetPreviewLoop(_loop);_engine.SetPreviewGain((float)(_volume.Value * _volume.Value));- _engine.PreviewFileAt(_item.Path, Math.Max(0, from));+ if (_plan is { } plan)+ {+ if (!_engine.PreviewAuditionAt(plan.Key, Math.Max(0, from)))+ {+ // Not rendered yet (or dropped from the engine's cache): play when it lands.+ _playWhenReady = plan.Key;+ if (_job?.Plan.Key != plan.Key) StartRender(plan, prefetch: false);+ else _job.Prefetch = false;+ if (_playing) Stop();+ Refresh();+ return;+ }+ }+ else _engine.PreviewFileAt(_item.Path, Math.Max(0, from));_playing = true;_pos = from;_poll.Start();@@ -270,6 +419,7 @@ public sealed class PreviewPlayer : UserControl_playing = false;_pos = 0;_poll.Stop();+ _wave.ClearSpectrum();Refresh();}@@ -282,8 +432,13 @@ public sealed class PreviewPlayer : UserControl_playing = false;_pos = 0;_poll.Stop();+ _wave.ClearSpectrum();+ }+ else+ {+ _pos = _engine.PreviewPosition;+ if (_spectrum) _wave.FeedSpectrum(_engine, _engine.SampleRate);}- else _pos = _engine.PreviewPosition;Refresh();}@@ -299,12 +454,34 @@ public sealed class PreviewPlayer : UserControlprivate void SetAuto(bool on, bool persist){- _auto = on;+ if (_filesContext) _autoFiles = on; else _autoPresets = on;_autoBtn.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;_autoBtn.BorderBrush = on ? NotaPalette.AccentEdge : NotaPalette.BorderDefault;_autoDot.Fill = on ? NotaPalette.Accent : NotaPalette.BorderStrong;_autoText.Foreground = on ? NotaPalette.AccentHover : NotaPalette.TextMuted;- if (persist && _settings is not null) { _settings.Current.BrowserPreviewAuto = on; _settings.Save(); }+ ToolTip.SetTip(_autoBtn, _filesContext ? "Auto-audition: play a sample on select" : "Auto-audition: play a preset or device on select");+ if (persist && _settings is not null)+ {+ if (_filesContext) _settings.Current.BrowserPreviewAuto = on;+ else _settings.Current.BrowserPresetPreviewAuto = on;+ _settings.Save();+ }+ }++ /// <summary>The browser switched tabs: Files (samples) or a device / preset tab — each+ /// keeps its own Auto.</summary>+ public void SetContext(bool files)+ {+ if (_filesContext == files) return;+ _filesContext = files;+ SetAuto(_auto, persist: false);+ }++ private void SetSpectrum(bool on, bool persist)+ {+ _spectrum = on;+ _wave.Spectrum = on;+ if (persist && _settings is not null) { _settings.Current.BrowserPreviewSpectrum = on; _settings.Save(); }}// v is the fader position; the gain is v² (so the travel reads roughly in dB).@@ -321,9 +498,78 @@ public sealed class PreviewPlayer : UserControlif (persist && _settings is not null) { _settings.Current.BrowserPreviewVolume = v; _settings.Save(); }}+ // --- effect source ------------------------------------------------------------++ // The track list the chip offers: every demo track, then the Files sample when there is one.+ private List<(string Id, string Name)> TrackChoices()+ {+ var l = new List<(string, string)>();+ if (_audition is not null) foreach (var t in _audition.Tracks) l.Add((t.Id, t.Name));+ if (_samplePath is not null) l.Add((AuditionTrackIds.Sample, System.IO.Path.GetFileNameWithoutExtension(_samplePath)));+ return l;+ }++ private void ShowSourceMenu()+ {+ if (_plan is not { IsEffect: true } || _audition is null) return;+ var flyout = new MenuFlyout { Placement = PlacementMode.TopEdgeAlignedRight };+ int kind = _item?.BuiltinKind ?? -1;+ string autoName = kind >= 0 ? _audition.Tracks.FirstOrDefault(t => t.Id == _audition.AutoTrack(kind))?.Name ?? "" : "";+ void Add(string label, string id, string? tip = null, bool enabled = true)+ {+ var mi = new MenuItem+ {+ Header = label, ToggleType = MenuItemToggleType.CheckBox, IsChecked = _fxTrack == id, IsEnabled = enabled,+ };+ if (tip is not null) ToolTip.SetTip(mi, tip);+ mi.Click += (_, _) => SetTrack(id);+ flyout.Items.Add(mi);+ }+ Add(autoName.Length > 0 ? $"Auto ({autoName})" : "Auto", AuditionTrackIds.Auto, "Picked for this effect: drums for dynamics, keys for time and modulation, a full mix for tone");+ string group = "";+ foreach (var t in _audition.Tracks)+ {+ if (t.Group != group)+ {+ flyout.Items.Add(new Separator());+ flyout.Items.Add(new MenuItem { Header = t.Group.ToUpperInvariant(), IsEnabled = false, FontSize = 9 });+ group = t.Group;+ }+ Add(t.Name, t.Id, t.Blurb);+ }+ flyout.Items.Add(new Separator());+ Add(_samplePath is null ? "Sample — pick one in Files" : $"Sample — {System.IO.Path.GetFileNameWithoutExtension(_samplePath)}",+ AuditionTrackIds.Sample, enabled: _samplePath is not null);+ flyout.ShowAt(_sourceBtn);+ }++ // Wheel over the chip: the next / previous track (from Auto, starting at what it resolved to).+ private void StepTrack(int dir)+ {+ if (_plan is not { IsEffect: true } plan) return;+ var list = TrackChoices();+ if (list.Count == 0) return;+ int i = list.FindIndex(c => c.Id == plan.TrackId);+ SetTrack(list[((i < 0 ? 0 : i + dir) % list.Count + list.Count) % list.Count].Id);+ }++ private void SetTrack(string id)+ {+ _fxTrack = id;+ if (_settings is not null) { _settings.Current.BrowserPreviewFxTrack = id; _settings.Save(); }+ if (_plan is not { IsEffect: true }) return;+ bool wasPlaying = _playing;+ _pos = 0;+ _duration = 0;+ _wave.SetPeaks(null);+ _wave.ClearSpectrum();+ // Changing the track is asking to hear it: play even with Auto off.+ Replan(play: true, wasPlaying);+ }+private void Refresh(){- bool has = _item is not null;+ bool has = HasSample;_name.Text = _item?.Name ?? "—";_playGlyph.IsVisible = !_playing;_stopGlyph.IsVisible = _playing;@@ -337,6 +583,12 @@ public sealed class PreviewPlayer : UserControl_timeNow.Foreground = _playing ? NotaPalette.TextPrimary : NotaPalette.TextMuted;_timeTotal.Text = "/ " + Fmt(_duration);_wave.SetState(_duration, _pos, _playing);+ _sourceBtn.IsVisible = _plan is { IsEffect: true };+ if (_plan is { IsEffect: true } plan)+ {+ _sourceText.Text = plan.TrackId == AuditionTrackIds.Sample ? "Sample" : plan.TrackName;+ ToolTip.SetTip(_sourceBtn, $"Heard through {plan.TrackName}{(_fxTrack == AuditionTrackIds.Auto ? " (auto for this effect)" : "")} — click to pick a track, scroll to step through them");+ }Adapt();}@@ -346,7 +598,7 @@ public sealed class PreviewPlayer : UserControl// meta shortens ("0.50 s · 44.1k · 16-bit · M" → "0.50 s · 44.1k" → "0.50 s" → gone).// Controls, cheapest loss first: Auto's label (the lit dot still reads), the total time// (the meta line has it), the fader (folds into the speaker, which pops it up), Loop, then- // the time readout. Play, Auto and the speaker always stay.+ // the time readout. Play, Auto, the speaker and an effect's source always stay.private void Adapt(){double avail = Bounds.Width - 20; // the strip's padding@@ -371,12 +623,13 @@ public sealed class PreviewPlayer : UserControldouble total = 3 + TextW(_timeTotal.Text ?? "", NotaFonts.Mono, 10);double autoFull = 2 + 7 + 6 + 5 + TextW("Auto", NotaFonts.SansSemiBold, 10) + 7, autoDot = 22;double volFull = 12 + 5 + 46, volIcon = 22, loop = 22 + gap;+ double source = _sourceBtn.IsVisible ? 2 + 14 + 5 + 6 + TextW(_sourceText.Text ?? "", NotaFonts.SansSemiBold, 10) + gap : 0;int level = 0;for (; level < 5; level++){double left = 28 + gap + now + (level < 2 ? total : 0);- double right = (level < 4 ? loop : 0) + gap + (level < 1 ? autoFull : autoDot) + gap + (level < 3 ? volFull : volIcon);+ double right = source + (level < 4 ? loop : 0) + gap + (level < 1 ? autoFull : autoDot) + gap + (level < 3 ? volFull : volIcon);if (left + minMiddle + right <= avail) break;}_autoText.IsVisible = level < 1;@@ -404,6 +657,98 @@ public sealed class PreviewPlayer : UserControlreturn whole >= 60 ? $"{whole / 60}:{whole % 60:00}.{cs:00}" : $"{whole:00}.{cs:00}";}+ // --- preset audition: rendered off the UI thread ---------------------------------++ // The meta line of an audition: "pad chord · 6.20 s · Nota Volt" (an effect names its+ // source on the chip instead, so it leads with the length).+ private static string[] AuditionMeta(AuditionPlan plan, double seconds)+ {+ var parts = new List<string>();+ if (!plan.IsEffect && plan.Phrase.Length > 0) parts.Add(plan.Phrase);+ if (seconds > 0) parts.Add(NotaNum.Unit(Math.Floor(seconds * 100) / 100, "0.00", "s"));+ if (plan.Device.Length > 0) parts.Add(plan.Device);+ return parts.ToArray();+ }++ private void StartRender(AuditionPlan plan, bool prefetch)+ {+ var engine = _engine;+ if (engine is null) return;+ if (_job is { } running)+ {+ if (running.Plan.Key == plan.Key) { if (!prefetch) running.Prefetch = false; return; }+ running.Cancel(); // the selection moved on+ }+ var job = new RenderJob(plan, prefetch);+ _job = job;+ if (!prefetch) _renderHint.Start();+ Task.Run(() =>+ {+ IAuditionRig? rig = null;+ try+ {+ rig = engine.CreateAuditionRig();+ job.Attach(rig);+ if (job.Cancelled || !plan.Build(rig)) { rig.Dispose(); rig = null; }+ else if (rig.Render(plan.Notes, plan.Bpm, plan.PhraseBeats, plan.TailSeconds, plan.Rolling) <= 0) { rig.Dispose(); rig = null; }+ }+ catch { rig?.Dispose(); rig = null; }+ float[]? peaks = null;+ double seconds = 0;+ if (rig is not null)+ {+ var minMax = new float[PeakPoints * 2];+ int n = rig.ReadPeaks(minMax, PeakPoints);+ peaks = ToAmplitudes(minMax, n);+ seconds = rig.Seconds;+ }+ Dispatcher.UIThread.Post(() => RenderDone(job, rig, peaks, seconds));+ });+ }++ private void RenderDone(RenderJob job, IAuditionRig? rig, float[]? peaks, double seconds)+ {+ if (_job == job) { _job = null; _renderHint.Stop(); }+ var plan = job.Plan;+ bool current = _plan?.Key == plan.Key;+ if (rig is null)+ {+ if (!job.Cancelled && current)+ {+ _wave.Hint = "no sound to preview";+ _playWhenReady = null;+ StatusChanged?.Invoke($"Preview failed: {_item?.Name}");+ Refresh();+ }+ if (!current || job.Cancelled) Prefetch();+ return;+ }+ try { _engine?.StoreAudition(rig, plan.Key); }+ catch { }+ finally { rig.Dispose(); }+ var info = new FileInfoCache(seconds, AuditionMeta(plan, seconds), peaks);+ Remember(plan.Key, info);+ if (current)+ {+ _wave.Hint = null;+ ShowInfo(info);+ if (_playWhenReady == plan.Key) { _playWhenReady = null; Play(0); }+ }+ Prefetch();+ }++ // Renders the row below the selection ahead of time, so arrowing down plays at once.+ // Only when idle; a new selection cancels it (or adopts it, if it is that row).+ private void Prefetch()+ {+ if (_job is not null || _audition is null || _engine is null) return;+ if (SubjectOf(_next) is not { } s) return;+ var plan = _audition.Plan(s, _fxTrack, _samplePath, out _);+ if (plan is null || plan.Key == _plan?.Key) return;+ if (_cache.ContainsKey(plan.Key) && _engine.IsAuditionCached(plan.Key)) return;+ StartRender(plan, prefetch: true);+ }+// --- waveform + format, decoded off the UI thread ---------------------------private void LoadInfo(string path)@@ -454,7 +799,7 @@ public sealed class PreviewPlayer : UserControlDispatcher.UIThread.Post(() =>{if (final) Remember(path, info);- if (gen == _loadGen && _item?.Path == path) ShowInfo(info);+ if (gen == _loadGen && _plan is null && _item?.Path == path) ShowInfo(info);});}@@ -564,22 +909,37 @@ public sealed class PreviewPlayer : UserControl};}-/// <summary>The player's waveform well: peak bars (played part in brass), a hover line with-/// its time, and the playhead. A click asks to seek to that fraction of the file.</summary>+/// <summary>The player's well. WAVE: peak bars (played part in brass), a hover line with its+/// time, and the playhead. SPEC: a live spectrum of what the preview voice is playing (one+/// brass line, 30 Hz – 20 kHz, this frame only — no ballistics) over decade lines, with the+/// progress as a thin brass rule along the bottom. The WAVE / SPEC caps in the top-right+/// corner switch views; anywhere else a click asks to seek to that fraction. A hint line+/// (why there is nothing to play, "rendering…") sits centred when the well is empty.</summary>public sealed class PreviewWaveform : Control{private const double InsetX = 4, InsetY = 3;+ private const int FftN = 2048;+ private const double FLo = 30, FHi = 20000, DbFloor = -72;private float[]? _peaks;private double _duration, _pos;- private bool _playing;+ private bool _playing, _spectrum, _hasSpec;private double? _hover; // 0..1+ private string? _hint;+ private Rect _toggleRect;++ private readonly float[] _scope = new float[FftN];+ private readonly double[] _re = new double[FftN], _im = new double[FftN], _hann = new double[FftN];+ private readonly double[] _db = new double[FftN / 2];+ private double _sr = 48000;public event Action<double>? SeekRequested;+ public event Action? ViewToggled;public PreviewWaveform(){Cursor = new Cursor(StandardCursorType.Hand);ClipToBounds = true;+ for (int i = 0; i < FftN; i++) _hann[i] = 0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (FftN - 1));}public void SetPeaks(float[]? peaks) { _peaks = peaks; InvalidateVisual(); }@@ -590,20 +950,53 @@ public sealed class PreviewWaveform : ControlInvalidateVisual();}+ /// <summary>Centred note for an empty well (null = none).</summary>+ public string? Hint+ {+ get => _hint;+ set { _hint = value; InvalidateVisual(); }+ }++ public bool Spectrum+ {+ get => _spectrum;+ set { _spectrum = value; InvalidateVisual(); }+ }++ /// <summary>Analyses the preview voice's latest output (called on the player's poll tick).</summary>+ public void FeedSpectrum(IAudioEngine engine, double sampleRate)+ {+ int n = engine.ReadPreviewScope(_scope);+ if (n < FftN) { ClearSpectrum(); return; }+ for (int i = 0; i < FftN; i++) { _re[i] = _scope[i] * _hann[i]; _im[i] = 0; }+ Fft.Transform(_re, _im);+ _sr = sampleRate > 0 ? sampleRate : 48000;+ double refMag = FftN / 4.0;+ for (int k = 1; k < FftN / 2; k++)+ _db[k] = 20 * Math.Log10(Math.Sqrt(_re[k] * _re[k] + _im[k] * _im[k]) / refMag + 1e-9);+ _hasSpec = true;+ InvalidateVisual();+ }++ public void ClearSpectrum() { _hasSpec = false; InvalidateVisual(); }+private double Frac(Point p) => Math.Clamp((p.X - InsetX) / Math.Max(1, Bounds.Width - 2 * InsetX), 0, 1);protected override void OnPointerPressed(PointerPressedEventArgs e){base.OnPointerPressed(e);if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;- SeekRequested?.Invoke(Frac(e.GetPosition(this)));+ var p = e.GetPosition(this);+ if (_toggleRect.Contains(p)) ViewToggled?.Invoke();+ else SeekRequested?.Invoke(Frac(p));e.Handled = true;}protected override void OnPointerMoved(PointerEventArgs e){base.OnPointerMoved(e);- _hover = _duration > 0 ? Frac(e.GetPosition(this)) : null;+ var p = e.GetPosition(this);+ _hover = _duration > 0 && !_toggleRect.Contains(p) ? Frac(p) : null;InvalidateVisual();}@@ -619,33 +1012,77 @@ public sealed class PreviewWaveform : Controldouble w = Bounds.Width, h = Bounds.Height;if (w <= 0 || h <= 0) return;- var well = new Rect(0.5, 0.5, w - 1, h - 1);- ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.GraphBorder, 1), well, 4, 4);- ctx.FillRectangle(NotaPalette.GridBeat, new Rect(1, Math.Floor(h / 2), w - 2, 1));+ var well = new Rect(0, 0, w, h);+ NotaGraph.Window(ctx, well);double innerW = w - 2 * InsetX, innerH = h - 2 * InsetY, mid = h / 2;double p = _duration > 0 ? Math.Clamp(_pos / _duration, 0, 1) : 0;bool started = _playing || _pos > 0;+ string? hint = _hint;- if (_peaks is { Length: > 0 } peaks && innerW > 8)+ if (_spectrum){- // ~3.8px a bar with a 1px gap, as in the mockup (72 bars across its 274px well).- int n = Math.Max(8, (int)((innerW + 1) / 3.8));- double bw = (innerW - (n - 1)) / n;- for (int b = 0; b < n; b++)+ // Decade lines at 100 Hz, 1 kHz, 10 kHz, each labelled at the bottom.+ foreach (var (hz, label) in new[] { (100.0, "100"), (1000.0, "1k"), (10000.0, "10k") }){- int s0 = b * peaks.Length / n, s1 = Math.Max(s0 + 1, (b + 1) * peaks.Length / n);- float m = 0;- for (int i = s0; i < s1 && i < peaks.Length; i++) m = Math.Max(m, peaks[i]);- double amp = Math.Max(0.04, Math.Pow(Math.Min(1, m), 0.55));- double x = (b + 0.5) / n;- IBrush c = started && x <= p ? NotaPalette.Accent- : _hover is { } hv && x <= hv && x > p ? NotaPalette.AccentMute- : _playing ? NotaPalette.AccentEdge- : NotaPalette.AccentMute;- double bh = innerH * amp;- ctx.FillRectangle(c, new Rect(InsetX + b * (bw + 1), mid - bh / 2, bw, bh), 1);+ double x = Math.Round(InsetX + innerW * Math.Log(hz / FLo) / Math.Log(FHi / FLo)) + 0.5;+ ctx.DrawLine(NotaGraph.GridPen, new Point(x, 1), new Point(x, h - 1));+ var t = NotaGraph.AxisText(label);+ ctx.DrawText(t, new Point(x + 2, h - t.Height - 1));}+ if (_hasSpec && innerW > 8)+ {+ var geo = new StreamGeometry();+ using (var g = geo.Open())+ {+ double binHz = _sr / FftN;+ int cols = Math.Max(2, (int)(innerW / 2));+ for (int c = 0; c <= cols; c++)+ {+ double t0 = (double)c / cols, t1 = (double)(c + 1) / cols;+ double f0 = FLo * Math.Pow(FHi / FLo, t0), f1 = FLo * Math.Pow(FHi / FLo, t1);+ // The loudest bin under the column (low columns span < 1 bin: interpolate).+ int k0 = Math.Clamp((int)(f0 / binHz), 1, FftN / 2 - 2), k1 = Math.Clamp((int)(f1 / binHz), k0, FftN / 2 - 1);+ double db;+ if (k1 <= k0) { double fk = f0 / binHz - k0; db = _db[k0] + (_db[k0 + 1] - _db[k0]) * Math.Clamp(fk, 0, 1); }+ else { db = DbFloor; for (int k = k0; k <= k1; k++) db = Math.Max(db, _db[k]); }+ double y = InsetY + innerH * Math.Clamp(db / DbFloor, 0, 1);+ var pt = new Point(InsetX + innerW * t0, y);+ if (c == 0) g.BeginFigure(pt, false); else g.LineTo(pt);+ }+ g.EndFigure(false);+ }+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, geo);+ }+ else hint ??= _peaks is null ? null : "play to see the spectrum";+ if (started && _duration > 0)+ ctx.FillRectangle(NotaPalette.Accent, new Rect(InsetX, h - 3, innerW * p, 1.5));+ }+ else+ {+ ctx.FillRectangle(NotaPalette.GridBeat, new Rect(1, Math.Floor(h / 2), w - 2, 1));+ if (_peaks is { Length: > 0 } peaks && innerW > 8)+ {+ // ~3.8px a bar with a 1px gap, as in the mockup (72 bars across its 274px well).+ int n = Math.Max(8, (int)((innerW + 1) / 3.8));+ double bw = (innerW - (n - 1)) / n;+ for (int b = 0; b < n; b++)+ {+ int s0 = b * peaks.Length / n, s1 = Math.Max(s0 + 1, (b + 1) * peaks.Length / n);+ float m = 0;+ for (int i = s0; i < s1 && i < peaks.Length; i++) m = Math.Max(m, peaks[i]);+ double amp = Math.Max(0.04, Math.Pow(Math.Min(1, m), 0.55));+ double x = (b + 0.5) / n;+ IBrush c = started && x <= p ? NotaPalette.Accent+ : _hover is { } hv && x <= hv && x > p ? NotaPalette.AccentMute+ : _playing ? NotaPalette.AccentEdge+ : NotaPalette.AccentMute;+ double bh = innerH * amp;+ ctx.FillRectangle(c, new Rect(InsetX + b * (bw + 1), mid - bh / 2, bw, bh), 1);+ }+ }+ if (started && _duration > 0)+ ctx.FillRectangle(NotaPalette.AccentBright, new Rect(InsetX + innerW * p - 0.75, 0, 1.5, h));}if (_hover is { } f)@@ -660,8 +1097,24 @@ public sealed class PreviewWaveform : Controlctx.DrawText(ft, new Point(tx + 4, InsetY + 1));}- if (started && _duration > 0)- ctx.FillRectangle(NotaPalette.AccentBright, new Rect(InsetX + innerW * p - 0.75, 0, 1.5, h));+ if (!string.IsNullOrEmpty(hint) && (_peaks is null || _spectrum))+ {+ var ht = new FormattedText(hint, NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.Mono, 9, NotaPalette.TextTertiary)+ {+ MaxTextWidth = Math.Max(20, w - 16), MaxLineCount = 2, TextAlignment = TextAlignment.Center,+ Trimming = TextTrimming.CharacterEllipsis,+ };+ ctx.DrawText(ht, new Point((w - ht.MaxTextWidth) / 2, (h - ht.Height) / 2));+ }++ // WAVE · SPEC, the active one in brass, top-right.+ var wave = NotaGraph.AxisText("WAVE", _spectrum ? NotaPalette.TextTertiary : NotaPalette.Accent, 7);+ var spec = NotaGraph.AxisText("SPEC", _spectrum ? NotaPalette.Accent : NotaPalette.TextTertiary, 7);+ double lw = wave.Width + 5 + spec.Width, lx = w - lw - 5, ly = 3;+ _toggleRect = new Rect(lx - 4, 0, lw + 9, ly + wave.Height + 3);+ ctx.FillRectangle(NotaPalette.BgSunken, new Rect(lx - 2, ly - 1, lw + 4, wave.Height + 2), 2);+ ctx.DrawText(wave, new Point(lx, ly));+ ctx.DrawText(spec, new Point(lx + wave.Width + 5, ly));}private static string Fmt(double s)diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 17cf2cf8..28a4eaf3 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -779,6 +779,19 @@ public interface IAudioEngine : IDisposable/// <summary>Audition playhead, seconds into the file.</summary>double PreviewPosition { get; }bool PreviewSelfTest();+ /// <summary>The last <paramref name="output"/>.Length (≤ 4096) mono samples the preview+ /// voice played, oldest first. Returns the count written.</summary>+ int ReadPreviewScope(float[] output);++ // --- Preset audition ------------------------------------------------------+ /// <summary>A fresh offline audition chain at the engine's sample rate (see+ /// <see cref="IAuditionRig"/>). Safe to call from any thread.</summary>+ IAuditionRig CreateAuditionRig();+ /// <summary>UI thread: keeps a rendered rig's audio under <paramref name="key"/> (small LRU).</summary>+ void StoreAudition(IAuditionRig rig, string key);+ bool IsAuditionCached(string key);+ /// <summary>Plays the cached audition from <paramref name="startSeconds"/>; false = not cached.</summary>+ bool PreviewAuditionAt(string key, double startSeconds);// --- xrun / dropout telemetry (M7-8) -----------------------------------int XrunCount { get; }diff --git a/src/managed/Nota.Application/Engine/IAuditionRig.cs b/src/managed/Nota.Application/Engine/IAuditionRig.csnew file mode 100644index 00000000..6b9db4b3--- /dev/null+++ b/src/managed/Nota.Application/Engine/IAuditionRig.cs@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application;++/// <summary>One note of an audition phrase, in beats.</summary>+public readonly record struct AuditionNote(double StartBeat, double LengthBeats, int Pitch, float Velocity);++/// <summary>A standalone chain — MIDI effects → built-in instrument → audio effects — that+/// renders a phrase offline (see <see cref="IAudioEngine.CreateAuditionRig"/>). It touches no+/// engine state, so build and render it on a worker thread; <see cref="Cancel"/> may be called+/// from any thread. Hand the result to <see cref="IAudioEngine.StoreAudition"/> on the UI+/// thread, then dispose it.</summary>+public interface IAuditionRig : IDisposable+{+ /// <summary>Built-in instrument kind (no racks). False if the kind can't be built.</summary>+ bool SetInstrument(int kind);+ /// <summary>Normalized instrument value by plugin-param id; false if there's no such id.</summary>+ bool InstrumentParam(string id, float value);+ /// <summary>Appends a built-in audio effect; its index, or -1.</summary>+ int AddDevice(int kind);+ bool DeviceParam(int index, string name, float value);+ /// <summary>Appends a built-in MIDI effect; its index, or -1.</summary>+ int AddMidiEffect(int kind);+ bool MidiParam(int index, string name, float value);+ /// <summary>The Sampler's sample; null = a procedural keys tone at C4.</summary>+ bool SetSamplerSample(string? path);+ /// <summary>Effect source: the first <paramref name="maxSeconds"/> of an audio file.</summary>+ bool SetSourceFile(string path, double maxSeconds);+ /// <summary>A fresh rig at the same rate, to render one part of a demo track.</summary>+ IAuditionRig CreatePart();+ /// <summary>Effect source: mixes a rendered part rig in (a demo track is built part by part).</summary>+ bool AddSourceFrom(IAuditionRig part, float gain);+ /// <summary>Takes a demo track rendered earlier this session (any rig); false = not cached.</summary>+ bool UseCachedSource(string key);+ /// <summary>Normalizes the mixed source to <paramref name="targetPeak"/> and keeps it under <paramref name="key"/>.</summary>+ bool CacheSource(string key, float targetPeak);++ /// <summary>Kits: a pad instrument (Drum Rack style) in place of a built-in instrument.</summary>+ bool UseKit();+ /// <summary>A one-shot pad on <paramref name="note"/>: gain, pan −1..1, choke group (0 = none).+ /// Returns the pad index, or -1 (the file can't be read).</summary>+ int KitAddPad(int note, string path, float gain, float pan, int choke);+ int KitPadAddDevice(int pad, int kind);+ bool KitPadDeviceParam(int pad, int device, string name, float value);++ /// <summary>Renders the phrase and its tail. Returns the frames rendered, or -1 when+ /// cancelled / there is nothing to play. <paramref name="rolling"/>: the instrument sees a+ /// running transport (arp / sequencer synths).</summary>+ long Render(IReadOnlyList<AuditionNote> notes, double bpm, double phraseBeats, double maxTailSeconds, bool rolling);+ void Cancel();+ /// <summary>(min, max) pairs over the rendered audio; returns the bucket count.</summary>+ int ReadPeaks(float[] outMinMax, int maxPoints);+ double Seconds { get; }+}diff --git a/src/managed/Nota.Application/Ports/IPresetAudition.cs b/src/managed/Nota.Application/Ports/IPresetAudition.csnew file mode 100644index 00000000..8481becc--- /dev/null+++ b/src/managed/Nota.Application/Ports/IPresetAudition.cs@@ -0,0 +1,56 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application;++/// <summary>What a browser row auditions: a preset (factory "factory:…" id, a saved .notapreset+/// path, a "kit:" / "rhythmkit:" drum kit) or a bare built-in device (its default sound).</summary>+public enum AuditionSubjectKind { Preset, Instrument, AudioEffect, MidiEffect }++public readonly record struct AuditionSubject(AuditionSubjectKind Kind, int BuiltinKind, string Path, string Name);++/// <summary>A demo track an audio effect is heard through: a single part (drums, keys, bass)+/// or a short genre loop. <see cref="Group"/> sections the player's menu.</summary>+public sealed record AuditionTrack(string Id, string Name, string Group, string Blurb);++/// <summary>The two track ids that aren't demo tracks.</summary>+public static class AuditionTrackIds+{+ /// <summary>Pick per effect: dynamics hear the drums, time / modulation the keys, tone+ /// shaping a full mix.</summary>+ public const string Auto = "auto";+ /// <summary>The sample last selected in the Files tab.</summary>+ public const string Sample = "sample";+}++/// <summary>A resolved audition: the cache key, what the player shows, and how to build and+/// render the rig. <see cref="Build"/> and the render run on a worker thread.</summary>+public sealed record AuditionPlan(+ string Key,+ string Device, // "Nota Volt"+ string Phrase, // "pad chord", "groove · Kompakt"+ bool IsEffect, // an audio effect: the player offers the track choice+ string TrackId, // resolved (never Auto) for effects, "" otherwise+ string TrackName, // "House", or the sample's file name+ Func<IAuditionRig, bool> Build,+ IReadOnlyList<AuditionNote> Notes,+ double Bpm,+ double PhraseBeats,+ double TailSeconds,+ bool Rolling);++/// <summary>Turns browser rows into offline auditions (see <see cref="IAuditionRig"/>).</summary>+public interface IPresetAudition+{+ /// <summary>The demo tracks, in menu order (parts first, then genres).</summary>+ IReadOnlyList<AuditionTrack> Tracks { get; }++ /// <summary>The plan for <paramref name="subject"/>, or null with a short user-facing+ /// reason (plug-in presets and racks have nothing to render here). <paramref name="trackId"/>+ /// is a <see cref="Tracks"/> id, <see cref="AuditionTrackIds.Auto"/> or+ /// <see cref="AuditionTrackIds.Sample"/> (<paramref name="samplePath"/>: the Files tab's sample).</summary>+ AuditionPlan? Plan(AuditionSubject subject, string trackId, string? samplePath, out string reason);++ /// <summary>The track Auto resolves to for an audio effect kind.</summary>+ string AutoTrack(int effectKind);+}diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.csindex 0f0b368c..b394b7bc 100644--- a/src/managed/Nota.Application/Settings.cs+++ b/src/managed/Nota.Application/Settings.cs@@ -62,6 +62,14 @@ public sealed class Settingspublic bool BrowserPreviewLoop { get; set; }/// <summary>Files tab player: fader position 0..1 (gain = v², so 0.7 ≈ −6 dB, 1 = 0 dB).</summary>public double BrowserPreviewVolume { get; set; } = 0.7;+ /// <summary>Browser player: the demo track effect presets are heard through — a track id+ /// ("drums", "house" …), "auto" (chosen per effect) or "sample" (the Files tab's sample).</summary>+ public string BrowserPreviewFxTrack { get; set; } = "auto";+ /// <summary>Browser player on the Instr / FX / MIDI / Presets tabs: selecting a preset or+ /// device plays it. Off by default (Files has its own, BrowserPreviewAuto).</summary>+ public bool BrowserPresetPreviewAuto { get; set; }+ /// <summary>Browser player: the well shows the live spectrum instead of the waveform.</summary>+ public bool BrowserPreviewSpectrum { get; set; }// --- arrangement view options (View menu) --------------------------------/// <summary>How many clips print their name on the lane: 0 every clip, 1 the head of eachdiff --git a/src/managed/Nota.Infrastructure/Audition/PresetAudition.Kits.cs b/src/managed/Nota.Infrastructure/Audition/PresetAudition.Kits.csnew file mode 100644index 00000000..da73dba7--- /dev/null+++ b/src/managed/Nota.Infrastructure/Audition/PresetAudition.Kits.cs@@ -0,0 +1,99 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Drum kits in the audition rig: a kit plays on the rig's pad instrument with each pad's+// gain, pan, choke group and effects — what loading it onto a Drum Rack does (a Nota Rhythm+// gets the kit's pad for each of its eight voices, as DrumKitService.FillRhythm picks them).+// Macros stay at rest. The groove is written on the shared 16-pad map (36 kick … 51 cowbell)+// and played at a tempo that suits the kit's style.++using System.Collections.Generic;+using System.IO;+using Nota.Application;+using Nota.Infrastructure.Kits;++namespace Nota.Infrastructure;++public sealed partial class PresetAudition+{+ // Kit pad notes (every factory kit uses the same map).+ private const int Kick = 36, Rim = 37, Snare = 38, Clap = 39, Snare2 = 40, TomLo = 41, HatC = 42, TomMid = 43,+ HatP = 44, TomHi = 45, HatO = 46, PercLo = 47, PercMid = 48, Crash = 49, PercHi = 50, Bell = 51;++ /// <summary>Sets the rig up as the kit. <paramref name="rhythm"/>: only the eight pads a+ /// Nota Rhythm takes, on its voices' notes.</summary>+ private static bool SetupKit(IAuditionRig rig, KitDefinition kit, bool rhythm)+ {+ KitLibrary.Ensure(kit); // first use renders the kit's one-shots+ if (!rig.UseKit()) return false;+ var pads = new List<(int Note, KitPad Pad)>();+ if (rhythm)+ {+ var voices = DrumKitService.RhythmVoicePads(kit);+ for (int v = 0; v < voices.Length; v++)+ if (voices[v] is { } p) pads.Add((RhythmModel.MidiNotes[v], p));+ }+ else foreach (var p in kit.Pads) pads.Add((p.Note, p));++ int loaded = 0;+ foreach (var (note, pad) in pads)+ {+ var path = KitLibrary.PathOf(kit, pad);+ if (!File.Exists(path)) continue;+ int pi = rig.KitAddPad(note, path, pad.Gain, pad.Pan, pad.Choke);+ if (pi < 0) continue;+ loaded++;+ foreach (var fx in KitFx.For(kit, pad))+ {+ int di = rig.KitPadAddDevice(pi, fx.Kind);+ if (di < 0) continue;+ foreach (var (name, value) in fx.Params) rig.KitPadDeviceParam(pi, di, name, value);+ }+ }+ return loaded > 0;+ }++ // Tempo from the kit's style line: a breakbeat kit wants pace, boom bap wants to lean back.+ private static double KitBpm(KitDefinition kit)+ {+ string b = kit.Blurb.ToLowerInvariant();+ bool Has(params string[] w) { foreach (var x in w) if (b.Contains(x)) return true; return false; }+ if (Has("jungle", "breakbeat")) return 160;+ if (Has("techno", "industrial", "hyperpop", "edm")) return 128;+ if (Has("house", "garage", "disco", "afro", "electro")) return 122;+ if (Has("boom bap", "vinyl", "dub", "reggae", "808", "sub-forward")) return 88;+ if (Has("jazz", "ambient", "cinematic", "orchestral")) return 84;+ return 104;+ }++ // Two bars: a groove with a crash on the one, a 16th-note hat run with the kit's swing on+ // the off-16ths, some percussion in bar 2 and a tom fill into the end. Notes a kit lacks+ // simply don't sound.+ private static AuditionNote[] KitGroove(float swing)+ {+ var n = new List<AuditionNote>();+ double Sw(double b) => Math.Abs(b * 4 - Math.Round(b * 4)) < 1e-6 && ((int)Math.Round(b * 4)) % 2 == 1 ? b + swing * 0.125 : b;+ void Hit(double b, int note, float v) => n.Add(N(Sw(b), 0.2, note, v));+ foreach (double b in new[] { 0, 1.75, 2.5, 4, 4.75, 6.5 }) Hit(b, Kick, 0.95f);+ foreach (double b in new[] { 1.0, 3.0, 5.0 }) Hit(b, Snare, 0.9f);+ Hit(7, Clap, 0.85f); Hit(7, Snare, 0.75f);+ Hit(3.75, Snare, 0.3f); // ghost+ Hit(0, Crash, 0.7f);+ for (int i = 0; i < 16; i++) // bar 1: eighths, open on the "and" of 4+ if (i % 2 == 0) Hit(i * 0.25, i == 14 ? HatO : HatC, i % 4 == 0 ? 0.7f : 0.5f);+ for (int i = 16; i < 28; i++) // bar 2: sixteenths (swing shows)+ Hit(i * 0.25, HatC, i % 4 == 0 ? 0.7f : i % 2 == 0 ? 0.5f : 0.32f);+ Hit(4.75, PercMid, 0.6f); Hit(5.5, PercHi, 0.55f); Hit(5.75, PercLo, 0.6f); Hit(6.25, Bell, 0.5f); Hit(2.25, Rim, 0.45f);+ Hit(7.25, TomHi, 0.8f); Hit(7.5, TomMid, 0.8f); Hit(7.75, TomLo, 0.85f);+ return n.ToArray();+ }++ private AuditionPlan? KitPlan(string keyBase, string kitId, bool rhythm, out string reason)+ {+ reason = "";+ var kit = KitCatalog.ById(kitId);+ if (kit is null) { reason = "Kit not found."; return null; }+ return new AuditionPlan(keyBase, rhythm ? "Nota Rhythm" : "Nota Drum Rack", $"groove · {kit.Name}", false, "", "",+ rig => SetupKit(rig, kit, rhythm), KitGroove(kit.Swing), KitBpm(kit), 8, 2.5, false);+ }+}diff --git a/src/managed/Nota.Infrastructure/Audition/PresetAudition.Tracks.cs b/src/managed/Nota.Infrastructure/Audition/PresetAudition.Tracks.csnew file mode 100644index 00000000..74c899c8--- /dev/null+++ b/src/managed/Nota.Infrastructure/Audition/PresetAudition.Tracks.cs@@ -0,0 +1,237 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The demo tracks an audio-effect preset is heard through: three single parts (drums, keys,+// bass) and short genre loops, each composed here from Nota's own factory sounds — a kit for+// the drums, factory presets for the rest. A track renders part by part into the rig's source+// on first use and is then kept, normalized to one peak level so an effect compares fairly+// across tracks, for the rest of the session (see IAuditionRig.CacheSource).++using System.Collections.Generic;+using Nota.Application;+using Nota.Infrastructure.Kits;++namespace Nota.Infrastructure;++public sealed partial class PresetAudition+{+ private const float SourcePeak = 0.6f; // ≈ −4.4 dBFS: headroom for effects that add gain++ // A part: a factory preset id ("bass/Finger Bass") or a kit ("kit:volta"), and its notes.+ private sealed record DemoPart(string Sound, float Gain, AuditionNote[] Notes);+ private sealed record DemoTrack(AuditionTrack Info, double Bpm, double Beats, DemoPart[] Parts);++ private const string Parts = "Parts", Genres = "Genres";++ private static readonly DemoTrack[] DemoTracks =+ {+ new(new("drums", "Drums", Parts, "an analog kit, groove and fill"), 110, 8, new[]+ {+ new DemoPart("kit:volta", 1f, KitGroove(0)),+ }),+ new(new("keys", "Keys", Parts, "electric piano chords and a melody"), 110, 8, new[]+ {+ new DemoPart("operator/E-Piano", 1f, Cat(+ Chord(0, 1.4, 0.75f, 48, 60, 64, 67, 71), new[] { N(1.5, 0.45, 76, 0.7f), N(2, 0.45, 74, 0.65f), N(2.5, 0.9, 72, 0.7f) },+ Chord(4, 1.4, 0.75f, 45, 57, 60, 64, 67), new[] { N(5.5, 0.45, 72, 0.7f), N(6, 0.45, 71, 0.65f) },+ Chord(6.5, 1.2, 0.8f, 43, 55, 59, 62, 65))),+ }),+ new(new("bass", "Bass", Parts, "a finger-bass line"), 110, 8, new[]+ {+ new DemoPart("bass/Finger Bass", 1f, new[]+ {+ N(0, 0.9, 36, 0.9f), N(1, 0.4, 36, 0.7f), N(1.5, 0.45, 48, 0.8f), N(2, 0.9, 43, 0.85f), N(3, 0.45, 41, 0.7f), N(3.5, 0.45, 40, 0.75f),+ N(4, 0.9, 33, 0.9f), N(5, 0.4, 33, 0.7f), N(5.5, 0.45, 45, 0.8f), N(6, 0.9, 41, 0.85f), N(7, 0.45, 43, 0.75f), N(7.5, 0.45, 35, 0.7f),+ }),+ }),++ // Pop — C G Am F, acoustic kit, finger bass, poly keys.+ new(new("pop", "Pop", Genres, "acoustic kit, bass and keys · 110 BPM"), 110, 8, new[]+ {+ new DemoPart("kit:atelier", 0.9f, Cat(+ Hits(Kick, 0.95f, 0, 1.5, 2, 4, 5.5, 6), Hits(Snare, 0.85f, 1, 3, 5, 7), Hits(Crash, 0.6f, 0),+ Every(HatC, 0.5, 0, 8, 0.6f, 0.45f))),+ new DemoPart("bass/Finger Bass", 0.8f, Cat(Pulse(0.5, 0.4, 0.8f, (0, 36), (2, 31), (4, 33), (6, 29)))),+ new DemoPart("pentad/Poly Keys", 0.55f, Cat(+ Chord(0, 1.9, 0.6f, 60, 64, 67), Chord(2, 1.9, 0.6f, 59, 62, 67), Chord(4, 1.9, 0.6f, 57, 60, 64), Chord(6, 1.9, 0.6f, 57, 60, 65))),+ }),++ // House — four on the floor, offbeat hats and bass, organ stabs.+ new(new("house", "House", Genres, "four-on-the-floor, organ stabs · 124 BPM"), 124, 8, new[]+ {+ new DemoPart("kit:kompakt", 0.9f, Cat(+ Hits(Kick, 0.95f, 0, 1, 2, 3, 4, 5, 6, 7), Hits(Clap, 0.8f, 1, 3, 5, 7),+ Every(HatO, 1, 0.5, 8, 0.55f, 0.55f), Every(HatP, 0.5, 0.25, 8, 0.3f, 0.3f))),+ new DemoPart("bass/Stab Bass", 0.75f, Cat(Pulse(1, 0.35, 0.85f, (0.5, 33), (4.5, 38)))),+ new DemoPart("operator/Drawbar Organ", 0.5f, Cat(+ Chord(0.75, 0.3, 0.7f, 57, 60, 64, 67), Chord(1.5, 0.3, 0.6f, 57, 60, 64, 67), Chord(2.75, 0.3, 0.7f, 57, 60, 64, 67),+ Chord(4.75, 0.3, 0.7f, 57, 60, 62, 65), Chord(5.5, 0.3, 0.6f, 57, 60, 62, 65), Chord(6.75, 0.6, 0.7f, 57, 60, 62, 65))),+ }),++ // Techno — driven kick, sixteenth hats, an acid line with slides.+ new(new("techno", "Techno", Genres, "warehouse kick and an acid line · 130 BPM"), 130, 8, new[]+ {+ new DemoPart("kit:bunker", 0.9f, Cat(+ Hits(Kick, 1f, 0, 1, 2, 3, 4, 5, 6, 7), Hits(Clap, 0.75f, 1, 3, 5, 7),+ Every(HatC, 0.25, 0, 8, 0.55f, 0.3f), Every(HatO, 1, 0.5, 8, 0.45f, 0.45f))),+ new DemoPart("bass/Acid 303", 0.7f, Acid()),+ }),++ // Hip-hop — boom bap with the kit's swing, Wurly chords and a bass line.+ new(new("hiphop", "Hip-Hop", Genres, "boom bap, swung, Wurly chords · 90 BPM"), 90, 8, new[]+ {+ new DemoPart("kit:crate", 0.95f, Cat(+ Hits(Kick, 0.95f, 0, 0.75, 2.5, 4, 4.75, 6.5, 7.25), Hits(Snare, 0.9f, 1, 3, 5, 7),+ Every(HatC, 0.5, 0, 8, 0.55f, 0.4f))),+ new DemoPart("operator/Wurly", 0.55f, Cat(Chord(0, 3.8, 0.6f, 50, 53, 57, 60, 64), Chord(4, 3.8, 0.6f, 43, 53, 57, 59, 64))),+ new DemoPart("bass/Finger Bass", 0.8f, new[]+ {+ N(0, 1.4, 38, 0.9f), N(2.5, 0.7, 38, 0.8f), N(3.25, 0.6, 41, 0.75f), N(4, 1.9, 31, 0.9f), N(6.5, 0.6, 31, 0.8f), N(7.25, 0.6, 33, 0.75f),+ }),+ }),++ // Trap — half-time, rolling hats, a gliding 808 and FM bells.+ new(new("trap", "Trap", Genres, "half-time, hat rolls, 808 and bells · 140 BPM"), 140, 8, new[]+ {+ new DemoPart("kit:neon", 0.9f, Cat(+ Hits(Kick, 0.95f, 0, 2.5, 4, 6.75), Hits(Clap, 0.9f, 2, 6),+ Every(HatC, 0.5, 0, 3, 0.55f, 0.4f), Every(HatC, 0.25, 3, 4, 0.5f, 0.35f), Every(HatC, 0.5, 4, 7, 0.55f, 0.4f),+ Every(HatC, 1.0 / 6, 7, 7.5, 0.5f, 0.4f), Hits(HatO, 0.5f, 7.5))),+ new DemoPart("bass/808 Sub", 0.85f, new[] { N(0, 1.4, 29, 0.95f), N(2.5, 0.9, 29, 0.85f), N(3.5, 0.45, 32, 0.8f), N(4, 2.2, 25, 0.95f), N(6.5, 1.2, 27, 0.85f) }),+ new DemoPart("operator/FM Bell", 0.4f, Seq(0.8f, 0.5, 0.6f, 77, 80, 84, 80, 77, 80, 85, 84, 77, 80, 84, 80, 75, 77, 80, 72)),+ }),++ // Drum & bass — two-step breaks, a reese bass and a pad, four bars.+ new(new("dnb", "Drum & Bass", Genres, "two-step breaks, reese and pad · 172 BPM"), 172, 16, new[]+ {+ new DemoPart("kit:breakline", 0.9f, Cat(+ Bars(4, Hits(Kick, 0.95f, 0, 2.5), Hits(Snare, 0.9f, 1, 3), Hits(Snare, 0.3f, 3.75), Every(HatC, 0.5, 0, 4, 0.5f, 0.35f)),+ Hits(Crash, 0.6f, 0), Hits(TomHi, 0.7f, 15.25), Hits(TomLo, 0.75f, 15.5))),+ new DemoPart("bass/Reese Bass", 0.7f, new[] { N(0, 3.9, 33, 0.9f), N(4, 3.9, 29, 0.9f), N(8, 3.9, 36, 0.9f), N(12, 3.5, 31, 0.9f) }),+ new DemoPart("aurora/Glacier Pad", 0.4f, Cat(+ Chord(0, 3.9, 0.5f, 57, 60, 64), Chord(4, 3.9, 0.5f, 53, 57, 60), Chord(8, 3.9, 0.5f, 55, 60, 64), Chord(12, 3.9, 0.5f, 55, 59, 62))),+ }),++ // Synthwave — gated 80s kit, octave bass, strings and a sync lead.+ new(new("synthwave", "Synthwave", Genres, "gated 80s kit, octave bass, sync lead · 100 BPM"), 100, 8, new[]+ {+ new DemoPart("kit:linnwood", 0.85f, Cat(+ Hits(Kick, 0.95f, 0, 1, 2, 3, 4, 5, 6, 7), Hits(Snare, 0.9f, 1, 3, 5, 7), Every(HatC, 0.5, 0, 8, 0.5f, 0.4f))),+ new DemoPart("monolith/Fat Bass", 0.7f, Octaves(0.5, (0, 33), (2, 29), (4, 36), (6, 31))),+ new DemoPart("pentad/Analog Strings", 0.4f, Cat(+ Chord(0, 1.9, 0.55f, 57, 60, 64), Chord(2, 1.9, 0.55f, 53, 57, 60), Chord(4, 1.9, 0.55f, 55, 60, 64), Chord(6, 1.9, 0.55f, 55, 59, 62))),+ new DemoPart("pentad/Sync Lead", 0.45f, new[] { N(4, 0.7, 76, 0.75f), N(4.75, 0.25, 74, 0.7f), N(5, 0.95, 72, 0.75f), N(6, 0.45, 71, 0.7f), N(6.5, 1.4, 72, 0.8f) }),+ }),++ // Ambient — slow pad chords and sparse vibraphone, no drums.+ new(new("ambient", "Ambient", Genres, "pad and vibraphone, no drums · 80 BPM"), 80, 8, new[]+ {+ new DemoPart("aurora/Glacier Pad", 0.6f, Cat(Chord(0, 3.9, 0.55f, 48, 55, 64, 71), Chord(4, 3.9, 0.55f, 45, 52, 60, 67, 71))),+ new DemoPart("physical/Vibraphone", 0.55f, new[]+ {+ N(0.5, 0.9, 76, 0.6f), N(1.5, 1.2, 79, 0.55f), N(3, 1, 74, 0.6f), N(4.5, 0.9, 72, 0.6f), N(5.5, 1.2, 71, 0.55f), N(7, 1, 67, 0.6f),+ }),+ }),+ };++ public IReadOnlyList<AuditionTrack> Tracks { get; } = Array.ConvertAll(DemoTracks, t => t.Info);++ private static DemoTrack? TrackById(string id) => Array.Find(DemoTracks, t => t.Info.Id == id);++ public string AutoTrack(int effectKind) => effectKind switch+ {+ // Dynamics and rhythm effects want transients.+ 1 or 11 or 19 or 21 => "drums",+ // Time, modulation and pitch effects want sustained, spaced notes (tails heard alone).+ 2 or 3 or 9 or 10 or 15 or 20 or 23 or 24 or 25 => "keys",+ // Tone shaping (EQ, drive, filters, limiting, level) wants a full mix.+ _ => "pop",+ };++ /// <summary>Makes the track the rig's source: from the session cache, else rendered part+ /// by part (worker thread) and cached.</summary>+ private bool UseTrack(IAuditionRig rig, DemoTrack t)+ {+ string key = "track:" + t.Info.Id;+ if (rig.UseCachedSource(key)) return true;+ int mixed = 0;+ foreach (var part in t.Parts)+ {+ using var pr = rig.CreatePart();+ if (!SetupPart(pr, part.Sound)) continue;+ if (pr.Render(part.Notes, t.Bpm, t.Beats, 1.5, false) <= 0) continue;+ if (rig.AddSourceFrom(pr, part.Gain)) mixed++;+ }+ return mixed > 0 && rig.CacheSource(key, SourcePeak);+ }++ private bool SetupPart(IAuditionRig rig, string sound)+ {+ if (sound.StartsWith("kit:", StringComparison.Ordinal))+ return KitCatalog.ById(sound[4..]) is { } kit && SetupKit(rig, kit, rhythm: false);+ var doc = _factory.Document(sound);+ if (doc is null || !rig.SetInstrument(doc.BuiltinKind)) return false;+ foreach (var (id, v) in doc.NamedParams ?? new Dictionary<string, float>())+ if (!InstrumentView.IsViewParam(id)) rig.InstrumentParam(id, v);+ return true;+ }++ // --- note builders ------------------------------------------------------------------++ private static IEnumerable<AuditionNote> Hits(int note, float vel, params double[] beats)+ {+ foreach (var b in beats) yield return N(b, 0.2, note, vel);+ }++ // A hit every `step` beats over [from, to); on-beat hits at `onVel`, the rest at `offVel`.+ private static IEnumerable<AuditionNote> Every(int note, double step, double from, double to, float onVel, float offVel)+ {+ for (double b = from; b < to - 1e-9; b += step)+ yield return N(b, Math.Min(0.2, step * 0.8), note, Math.Abs(b - Math.Round(b)) < 1e-6 ? onVel : offVel);+ }++ // The same one-bar pattern repeated for `bars` bars.+ private static IEnumerable<AuditionNote> Bars(int bars, params IEnumerable<AuditionNote>[] bar)+ {+ var one = Cat(bar);+ for (int k = 0; k < bars; k++)+ foreach (var x in one) yield return x with { StartBeat = x.StartBeat + 4 * k };+ }++ // Repeated root notes every `step` beats from each (beat, pitch) until the next.+ private static IEnumerable<AuditionNote> Pulse(double step, double len, float vel, params (double At, int Pitch)[] roots)+ {+ for (int i = 0; i < roots.Length; i++)+ {+ double end = i + 1 < roots.Length ? roots[i + 1].At : 8;+ for (double b = roots[i].At; b < end - 1e-9; b += step) yield return N(b, len, roots[i].Pitch, vel);+ }+ }++ // Eighth-note octave bass (root, octave up, …) from each (beat, root) to the next.+ private static AuditionNote[] Octaves(double step, params (double At, int Pitch)[] roots)+ {+ var n = new List<AuditionNote>();+ for (int i = 0; i < roots.Length; i++)+ {+ double end = i + 1 < roots.Length ? roots[i + 1].At : 8;+ int k = 0;+ for (double b = roots[i].At; b < end - 1e-9; b += step, k++)+ n.Add(N(b, step * 0.8, roots[i].Pitch + (k % 2 == 1 ? 12 : 0), k % 2 == 0 ? 0.85f : 0.7f));+ }+ return n.ToArray();+ }++ // Sixteenths over A, with accents, octave jumps and overlapping (sliding) notes — twice.+ private static AuditionNote[] Acid()+ {+ int[] p = { 33, 33, 45, 33, 36, 33, 43, 33, 33, 45, 33, 40, 33, 31, 33, 45 };+ bool[] accent = { true, false, false, false, true, false, true, false, false, true, false, false, true, false, false, true };+ bool[] slide = { false, false, true, false, false, false, false, true, false, false, false, true, false, false, true, false };+ var n = new List<AuditionNote>();+ for (int rep = 0; rep < 2; rep++)+ for (int i = 0; i < 16; i++)+ n.Add(N(rep * 4 + i * 0.25, slide[i] ? 0.3 : 0.18, p[i], accent[i] ? 0.95f : 0.6f));+ return n.ToArray();+ }+}diff --git a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs b/src/managed/Nota.Infrastructure/Audition/PresetAudition.csnew file mode 100644index 00000000..3c9b45fa--- /dev/null+++ b/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs@@ -0,0 +1,328 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Browser preset audition: resolves a row (factory preset, saved .notapreset, drum kit, bare+// built-in device) into an offline render plan — the chain to build on an IAuditionRig and the+// phrase to play through it. Instruments get a phrase that suits the sound (a pad holds a+// chord, a bass plays a riff), picked from the preset's category and the device; kits (Drum+// Rack, Nota Rhythm) play a groove on their own pads (PresetAudition.Kits.cs); MIDI effects+// play a phrase that shows what they do into a plain keys patch; audio effects process a demo+// track — a part or a genre loop (PresetAudition.Tracks.cs), chosen per device unless the+// user picks — or the sample selected in the Files tab.++using System.Collections.Generic;+using System.IO;+using Nota.Application;++namespace Nota.Infrastructure;++public sealed partial class PresetAudition : IPresetAudition+{+ private const double Bpm = 120;+ private readonly FactoryPresetCatalog _factory;++ // Saved presets are re-read only when the file changes.+ private readonly Dictionary<string, (DateTime Stamp, PresetDocument Doc)> _userDocs = new(StringComparer.Ordinal);++ private readonly string _defaultKit;++ public PresetAudition(IFactoryPresets factory, IDrumKits? kits = null)+ {+ _factory = factory as FactoryPresetCatalog+ ?? throw new ArgumentException("Preset audition needs the built-in factory catalog.", nameof(factory));+ _defaultKit = kits?.DefaultRhythmKit ?? "kompakt";+ }++ public AuditionPlan? Plan(AuditionSubject s, string trackId, string? samplePath, out string reason)+ {+ reason = "";+ PresetDocument? doc;+ string category = "", keyBase;+ switch (s.Kind)+ {+ case AuditionSubjectKind.Preset when s.Path.StartsWith("factory:", StringComparison.Ordinal):+ {+ string id = s.Path["factory:".Length..];+ doc = _factory.Document(id);+ category = _factory.Info(id)?.Category ?? "";+ keyBase = s.Path;+ break;+ }+ case AuditionSubjectKind.Preset when s.Path.EndsWith(PresetService.Extension, StringComparison.OrdinalIgnoreCase):+ {+ doc = LoadUser(s.Path, out var stamp);+ keyBase = $"{s.Path}@{stamp.Ticks}";+ break;+ }+ case AuditionSubjectKind.Preset when s.Path.StartsWith("kit:", StringComparison.Ordinal):+ return KitPlan(s.Path, s.Path[4..], rhythm: false, out reason);+ case AuditionSubjectKind.Preset when s.Path.StartsWith("rhythmkit:", StringComparison.Ordinal):+ return KitPlan(s.Path, s.Path[10..], rhythm: true, out reason);+ case AuditionSubjectKind.Preset:+ reason = "Preset not found.";+ return null;+ // A fresh Drum Rack / Nota Rhythm is heard with the kit a new Rhythm starts with.+ case AuditionSubjectKind.Instrument when s.BuiltinKind is 4 or 12:+ return KitPlan($"device:inst:{s.BuiltinKind}:{_defaultKit}", _defaultKit, rhythm: s.BuiltinKind == 12, out reason);+ case AuditionSubjectKind.Instrument:+ doc = new PresetDocument { Type = "builtin-instrument", BuiltinKind = s.BuiltinKind };+ keyBase = $"device:inst:{s.BuiltinKind}";+ break;+ case AuditionSubjectKind.AudioEffect:+ doc = new PresetDocument { Type = "builtin-effect", BuiltinKind = s.BuiltinKind };+ keyBase = $"device:fx:{s.BuiltinKind}";+ break;+ case AuditionSubjectKind.MidiEffect:+ doc = new PresetDocument { Type = "builtin-midi-effect", BuiltinKind = s.BuiltinKind };+ keyBase = $"device:midi:{s.BuiltinKind}";+ break;+ default:+ return null;+ }+ if (doc is null) { reason = "Preset not found."; return null; }++ var named = doc.NamedParams ?? new Dictionary<string, float>();+ switch (doc.Type)+ {+ case "builtin-instrument":+ {+ int kind = doc.BuiltinKind;+ if (kind is 3 or 4) { reason = "Racks play what their chains hold — nothing to preview on its own."; return null; }+ var phrase = PhraseFor(kind, category, s.Name);+ return new AuditionPlan(keyBase, DeviceName(doc, kind, instrument: true), phrase.Label, false, "", "",+ rig =>+ {+ if (!rig.SetInstrument(kind)) return false;+ foreach (var (id, v) in named)+ if (!InstrumentView.IsViewParam(id)) rig.InstrumentParam(id, v);+ return true;+ },+ phrase.Notes, Bpm, phrase.Beats, phrase.Tail, phrase.Rolling);+ }+ case "builtin-midi-effect":+ {+ int kind = doc.BuiltinKind;+ var phrase = MidiPhrase(kind);+ return new AuditionPlan(keyBase, DeviceName(doc, kind, midi: true), phrase.Label, false, "", "",+ rig =>+ {+ if (!rig.SetInstrument(0)) return false;+ foreach (var (id, v) in MidiHostPatch) rig.InstrumentParam(id, v);+ int mi = rig.AddMidiEffect(kind);+ if (mi < 0) return false;+ foreach (var (name, v) in named) if (name != "View") rig.MidiParam(mi, name, v);+ return true;+ },+ phrase.Notes, Bpm, phrase.Beats, phrase.Tail, true);+ }+ case "builtin-effect":+ {+ int kind = doc.BuiltinKind;+ if (kind == 5) { reason = "The Effect Rack plays what its chains hold — nothing to preview on its own."; return null; }+ string id = trackId == AuditionTrackIds.Auto ? AutoTrack(kind) : trackId;+ if (id == AuditionTrackIds.Sample && string.IsNullOrEmpty(samplePath)) id = AutoTrack(kind);+ var track = id == AuditionTrackIds.Sample ? null : TrackById(id) ?? TrackById(AutoTrack(kind))!;+ string key = track is null ? $"{keyBase}|sample:{samplePath}" : $"{keyBase}|{track.Info.Id}";+ string name = track?.Info.Name ?? Path.GetFileNameWithoutExtension(samplePath)!;+ return new AuditionPlan(key, DeviceName(doc, kind), $"through {name}", true, track?.Info.Id ?? AuditionTrackIds.Sample, name,+ rig =>+ {+ bool ok = track is null ? rig.SetSourceFile(samplePath!, 8) : UseTrack(rig, track);+ if (!ok) return false;+ int di = rig.AddDevice(kind);+ if (di < 0) return false;+ foreach (var (pn, v) in named) rig.DeviceParam(di, pn, v);+ // EQ-3 presets from before Range was added were made in the Classic law.+ if (kind == 16 && doc.NamedParams is { Count: > 0 } && !named.ContainsKey("Range")) rig.DeviceParam(di, "Range", 0);+ return true;+ },+ Array.Empty<AuditionNote>(), track?.Bpm ?? Bpm, 0, 4.0, true);+ }+ default:+ reason = "Plug-in presets can't be previewed — load the plug-in to hear them.";+ return null;+ }+ }++ private PresetDocument? LoadUser(string path, out DateTime stamp)+ {+ stamp = DateTime.MinValue;+ try+ {+ stamp = File.GetLastWriteTimeUtc(path);+ if (_userDocs.TryGetValue(path, out var hit) && hit.Stamp == stamp) return hit.Doc;+ var doc = PresetService.Load(path);+ _userDocs[path] = (stamp, doc);+ return doc;+ }+ catch { return null; }+ }++ // --- device names ------------------------------------------------------------++ private static readonly Dictionary<int, string> InstrumentNames = new()+ {+ [0] = "Nota Synth", [1] = "Nota Sampler", [2] = "Nota Physical", [5] = "Nota Aurora", [6] = "Nota Volt",+ [7] = "Nota Bass", [8] = "Nota Pendulum", [9] = "Nota Operator", [10] = "Nota Grain", [11] = "Nota Flux",+ [12] = "Nota Rhythm", [13] = "Nota Monolith", [14] = "Nota Pentad", [15] = "Nota Consort",+ };+ private static readonly Dictionary<int, string> MidiNames = new()+ {+ [0] = "Nota Arp", [1] = "Nota Chord", [2] = "Nota Scale", [3] = "Nota Length", [4] = "Nota Velocity", [5] = "Nota Random",+ };+ private static readonly Dictionary<int, string> EffectNames = new()+ {+ [0] = "Nota EQ-8", [1] = "Nota Compressor", [2] = "Nota Reverb", [3] = "Nota Delay", [4] = "Nota Utility",+ [6] = "Nota Valve", [7] = "Nota Auto Filter", [8] = "Nota Vintage", [9] = "Nota Orbit", [10] = "Nota Auto Shift",+ [11] = "Nota Beat Repeat", [12] = "Nota Crush", [13] = "Nota Dynamic EQ-8", [14] = "Nota Ceiling",+ [15] = "Nota Strata", [16] = "Nota EQ-3", [17] = "Nota Forge", [18] = "Nota Level", [19] = "Nota Shutter",+ [20] = "Nota Chamber", [21] = "Nota Prism", [22] = "Nota Lens", [23] = "Nota Flanger", [24] = "Nota Phaser",+ [25] = "Nota Chorus",+ };++ private static string DeviceName(PresetDocument doc, int kind, bool instrument = false, bool midi = false)+ {+ if (!string.IsNullOrEmpty(doc.DeviceName)) return doc.DeviceName;+ var map = instrument ? InstrumentNames : midi ? MidiNames : EffectNames;+ return map.TryGetValue(kind, out var n) ? n : "";+ }++ // --- phrases -------------------------------------------------------------------+ // Two bars at 120 BPM unless a sound needs longer (a slow pad). Pitches are MIDI notes.++ private sealed record Phrase(string Label, AuditionNote[] Notes, double Beats, double Tail, bool Rolling = false);++ private static AuditionNote N(double at, double len, int pitch, float vel = 0.75f) => new(at, len, pitch, vel);++ private static IEnumerable<AuditionNote> Chord(double at, double len, float vel, params int[] pitches)+ {+ foreach (int p in pitches) yield return N(at, len, p, vel);+ }++ private static AuditionNote[] Cat(params IEnumerable<AuditionNote>[] parts)+ {+ var l = new List<AuditionNote>();+ foreach (var p in parts) l.AddRange(p);+ return l.ToArray();+ }++ // Cmaj9 → Am9, voiced wide, held long enough for a slow attack to bloom.+ private static readonly Phrase Pad = new("pad chord", Cat(+ Chord(0, 3.8, 0.7f, 48, 55, 64, 71, 74),+ Chord(4, 3.8, 0.7f, 45, 52, 60, 67, 71)), 8, 4.5);++ // A syncopated riff with an octave jump and two overlapping (glide / legato) moves.+ private static readonly Phrase BassRiff = new("bass riff", new[]+ {+ N(0, 0.45, 36, 0.95f), N(0.75, 0.25, 36, 0.7f), N(1, 0.45, 48, 0.85f), N(1.5, 0.5, 46, 0.75f),+ N(2, 0.7, 43, 0.9f), N(2.75, 0.5, 41, 0.75f), N(3.5, 0.5, 39, 0.8f),+ N(4, 0.45, 36, 0.95f), N(4.75, 0.25, 36, 0.7f), N(5, 0.45, 48, 0.85f), N(5.5, 0.6, 43, 0.75f),+ N(6, 0.95, 44, 0.9f), N(6.9, 0.6, 43, 0.8f), N(7.5, 0.45, 36, 0.85f),+ }, 8, 1.5);++ // A melody with a legato run (overlaps) and a long last note for vibrato / filter motion.+ private static readonly Phrase Lead = new("lead line", new[]+ {+ N(0, 0.5, 60), N(0.5, 0.5, 63), N(1, 1.0, 67, 0.85f), N(2, 0.3, 70), N(2.25, 0.3, 72), N(2.5, 0.3, 70),+ N(2.75, 1.25, 67, 0.8f), N(4, 0.5, 65), N(4.5, 0.55, 67), N(5, 0.55, 70), N(5.5, 2.3, 72, 0.9f),+ }, 8, 2.0);++ // Chords with a melody on top, then a stab — shows attack, body and release.+ private static readonly Phrase Keys = new("keys", Cat(+ Chord(0, 1.4, 0.75f, 48, 60, 64, 67, 71), new[] { N(1.5, 0.45, 76, 0.7f), N(2, 0.45, 74, 0.65f), N(2.5, 0.9, 72, 0.7f) },+ Chord(4, 1.4, 0.75f, 45, 57, 60, 64, 67), new[] { N(5.5, 0.45, 72, 0.7f), N(6, 0.45, 71, 0.65f) },+ Chord(6.5, 1.2, 0.8f, 43, 55, 59, 62, 65)), 8, 2.5);++ // Rising and falling arpeggio in the upper register, finishing on a chord.+ private static readonly Phrase Pluck = new("arpeggio", Cat(+ new[]+ {+ N(0, 0.45, 60), N(0.5, 0.45, 64), N(1, 0.45, 67), N(1.5, 0.45, 72), N(2, 0.45, 76, 0.85f), N(2.5, 0.45, 72),+ N(3, 0.45, 67), N(3.5, 0.45, 64), N(4, 0.45, 57), N(4.5, 0.45, 60), N(5, 0.45, 64), N(5.5, 0.45, 69, 0.85f),+ },+ Chord(6, 1.5, 0.8f, 60, 64, 67, 72)), 8, 3.0);++ // A slow, low drone with a fifth and a late ninth — lets textures and sweeps evolve.+ private static readonly Phrase Texture = new("texture", Cat(+ Chord(0, 6.5, 0.7f, 36, 43, 55), new[] { N(3, 3.5, 62, 0.55f) }), 8, 4.5);++ // A held chord for arp / sequencer synths: they make the rhythm themselves.+ private static readonly Phrase Held = new("held chord", Cat(Chord(0, 7.5, 0.8f, 48, 55, 60, 63, 67)), 8, 3.0, Rolling: true);++ // GM drum map (Nota Rhythm): kick 36, snare 38, clap 39, rim 37, hats 42 / 46, toms 45 / 41.+ private static readonly Phrase Groove = new("groove", Cat(+ new[] { N(0, 0.25, 36, 1f), N(1.75, 0.25, 36, 0.8f), N(2, 0.25, 36, 0.95f), N(4, 0.25, 36, 1f), N(5.75, 0.25, 36, 0.8f), N(6, 0.25, 36, 0.95f) },+ new[] { N(1, 0.25, 38, 0.9f), N(3, 0.25, 38, 0.9f), N(5, 0.25, 38, 0.9f), N(7, 0.25, 39, 0.9f), N(3.75, 0.25, 37, 0.6f) },+ new[] { N(6.5, 0.25, 45, 0.8f), N(6.75, 0.25, 41, 0.8f), N(7.5, 0.25, 46, 0.7f) },+ Hats()), 8, 1.5);++ private static IEnumerable<AuditionNote> Hats()+ {+ for (int i = 0; i < 12; i++) yield return N(i * 0.5, 0.25, i == 7 ? 46 : 42, i % 2 == 0 ? 0.75f : 0.5f);+ }++ private static Phrase PhraseFor(int kind, string category, string name)+ {+ if (kind == 12) return Groove;+ if (kind is 8 or 15) return Held; // Pendulum, Consort: generative, rolling+ string c = (category + " " + name).ToLowerInvariant();+ bool Has(params string[] words) { foreach (var w in words) if (c.Contains(w)) return true; return false; }+ if (Has("sequence", "arp", "generative")) return Held;+ if (Has("bass", "sub", "acid", "growl", "wobble", "808")) return BassRiff;+ if (Has("pad", "ambient", "ensemble", "string", "choir", "bowed", "waterfall", "swell")) return Pad;+ if (Has("texture", "drone", "sweep", " fx", "motion", "noise")) return Texture;+ if (Has("lead", "brass", "solo", "whistle")) return Lead;+ if (Has("bell", "mallet", "pluck", "harp", "music box", "percussion", "perc", "marimba", "vibra")) return Pluck;+ if (Has("keys", "piano", "organ", "electric", "rhodes")) return Keys;+ return kind switch+ {+ 7 => BassRiff, // Nota Bass+ 13 => Lead, // Nota Monolith (mono)+ 2 => Pluck, // Nota Physical (struck bodies)+ 10 => Texture, // Nota Grain+ _ => Keys,+ };+ }++ // --- MIDI effects ------------------------------------------------------------------+ // Played into a plain Nota Synth keys patch — short enough that note length and velocity read.++ private static readonly (string Id, float Value)[] MidiHostPatch =+ {+ ("wave", 0.667f), ("attack", 0f), ("decay", 0.55f), ("sustain", 0.5f), ("release", 0.35f),+ ("cutoff", 0.7f), ("resonance", 0.1f), ("filenv", 0.4f), ("velamp", 0.8f), ("gain", 0.8f),+ };++ private static Phrase MidiPhrase(int kind) => kind switch+ {+ 0 => new("held chord", Cat(Chord(0, 3.9, 0.8f, 48, 55, 60, 64), Chord(4, 3.9, 0.8f, 45, 52, 57, 60)), 8, 2.0),+ 1 => new("melody", Seq(0.9f, 1.0, 0.8f, 60, 62, 64, 65, 67, 69, 71, 72), 8, 2.0),+ 2 => new("chromatic run", Seq(0.45f, 0.5, 0.75f, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 71, 69, 67), 8, 1.5),+ 3 => new("mixed lengths", new[]+ {+ N(0, 0.2, 60), N(0.5, 0.2, 64), N(1, 1.5, 67), N(3, 0.1, 72), N(3.25, 0.1, 72), N(3.5, 0.4, 71),+ N(4, 2.0, 69), N(6, 0.25, 67), N(6.5, 0.25, 64), N(7, 0.9, 60),+ }, 8, 1.5),+ 4 => new("velocity ramp", VelocityRamp(), 8, 1.5),+ _ => new("repeating line", Seq(0.45f, 0.5, 0.75f, 60, 64, 67, 72, 67, 64, 60, 64, 67, 72, 67, 64, 60, 67, 72, 76), 8, 1.5),+ };++ private static AuditionNote[] Seq(float len, double step, float vel, params int[] pitches)+ {+ var n = new AuditionNote[pitches.Length];+ for (int i = 0; i < n.Length; i++) n[i] = N(i * step, len * step, pitches[i], vel);+ return n;+ }++ private static AuditionNote[] VelocityRamp()+ {+ var n = new List<AuditionNote>();+ int[] line = { 60, 64, 67, 64 };+ for (int i = 0; i < 16; i++)+ {+ float v = 0.15f + 0.85f * (i < 8 ? i / 7f : (15 - i) / 7f);+ n.Add(N(i * 0.5, 0.4, line[i % 4], v));+ }+ return n.ToArray();+ }+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.csnew file mode 100644index 00000000..598b313e--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs@@ -0,0 +1,96 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Runtime.InteropServices;++namespace Nota.Infrastructure;++/// <summary>Preset audition (a standalone chain rendered offline, played on the preview voice).</summary>+/// <remarks>Part of <see cref="NotaEngine"/>'s P/Invoke surface; see nota_engine.h.</remarks>+internal static partial class NativeMethods+{+ [StructLayout(LayoutKind.Sequential)]+ internal struct NotaAuditionNote+ {+ public double StartBeat;+ public double LengthBeats;+ public int Pitch;+ public float Velocity;+ }++ [LibraryImport(Lib, EntryPoint = "nota_audition_create")]+ internal static partial IntPtr AuditionCreate(double sampleRate);++ [LibraryImport(Lib, EntryPoint = "nota_audition_destroy")]+ internal static partial void AuditionDestroy(IntPtr rig);++ [LibraryImport(Lib, EntryPoint = "nota_audition_set_instrument")]+ internal static partial int AuditionSetInstrument(IntPtr rig, int kind);++ [LibraryImport(Lib, EntryPoint = "nota_audition_instrument_param", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionInstrumentParam(IntPtr rig, string id, float value);++ [LibraryImport(Lib, EntryPoint = "nota_audition_add_device")]+ internal static partial int AuditionAddDevice(IntPtr rig, int kind);++ [LibraryImport(Lib, EntryPoint = "nota_audition_device_param", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionDeviceParam(IntPtr rig, int index, string name, float value);++ [LibraryImport(Lib, EntryPoint = "nota_audition_add_midi_effect")]+ internal static partial int AuditionAddMidiEffect(IntPtr rig, int kind);++ [LibraryImport(Lib, EntryPoint = "nota_audition_midi_param", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionMidiParam(IntPtr rig, int index, string name, float value);++ [LibraryImport(Lib, EntryPoint = "nota_audition_set_sampler_sample", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionSetSamplerSample(IntPtr rig, string? path);++ [LibraryImport(Lib, EntryPoint = "nota_audition_add_source_from")]+ internal static partial int AuditionAddSourceFrom(IntPtr rig, IntPtr part, float gain);++ [LibraryImport(Lib, EntryPoint = "nota_audition_use_cached_source", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionUseCachedSource(IntPtr rig, string key);++ [LibraryImport(Lib, EntryPoint = "nota_audition_cache_source", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionCacheSource(IntPtr rig, string key, float targetPeak);++ [LibraryImport(Lib, EntryPoint = "nota_audition_use_kit")]+ internal static partial int AuditionUseKit(IntPtr rig);++ [LibraryImport(Lib, EntryPoint = "nota_audition_kit_add_pad", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionKitAddPad(IntPtr rig, int note, string path, float gain, float pan, int choke);++ [LibraryImport(Lib, EntryPoint = "nota_audition_kit_pad_add_device")]+ internal static partial int AuditionKitPadAddDevice(IntPtr rig, int pad, int kind);++ [LibraryImport(Lib, EntryPoint = "nota_audition_kit_pad_device_param", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionKitPadDeviceParam(IntPtr rig, int pad, int device, string name, float value);++ [LibraryImport(Lib, EntryPoint = "nota_audition_set_source_file", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionSetSourceFile(IntPtr rig, string path, double maxSeconds);++ [LibraryImport(Lib, EntryPoint = "nota_audition_render")]+ internal static partial long AuditionRender(IntPtr rig, [In] NotaAuditionNote[] notes, int count,+ double bpm, double phraseBeats, double maxTailSeconds, int flags);++ [LibraryImport(Lib, EntryPoint = "nota_audition_cancel")]+ internal static partial void AuditionCancel(IntPtr rig);++ [LibraryImport(Lib, EntryPoint = "nota_audition_peaks")]+ internal static partial int AuditionPeaks(IntPtr rig, [Out] float[] outMinMax, int maxPoints);++ [LibraryImport(Lib, EntryPoint = "nota_audition_seconds")]+ internal static partial double AuditionSeconds(IntPtr rig);++ [LibraryImport(Lib, EntryPoint = "nota_engine_audition_store", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial NotaResult AuditionStore(IntPtr engine, IntPtr rig, string key);++ [LibraryImport(Lib, EntryPoint = "nota_engine_audition_cached", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuditionCached(IntPtr engine, string key);++ [LibraryImport(Lib, EntryPoint = "nota_engine_preview_cached_at", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int PreviewCachedAt(IntPtr engine, string key, double startSeconds);++ [LibraryImport(Lib, EntryPoint = "nota_engine_preview_scope")]+ internal static partial int PreviewScope(IntPtr engine, [Out] float[] output, int n);+}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.csnew file mode 100644index 00000000..a0e4938e--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs@@ -0,0 +1,97 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Infrastructure;++public sealed partial class NotaEngine+{+ // --- Preset audition -----------------------------------------------------++ /// <summary>A standalone offline chain at the engine's rate (any thread; no engine state).</summary>+ public IAuditionRig CreateAuditionRig()+ {+ ThrowIfDisposed();+ double sr = NativeMethods.SampleRate(_handle);+ sr = sr > 0 ? sr : 48000;+ return new AuditionRig(NativeMethods.AuditionCreate(sr), sr);+ }++ public void StoreAudition(IAuditionRig rig, string key)+ {+ ThrowIfDisposed();+ if (rig is not AuditionRig r) throw new ArgumentException("Not a NotaEngine audition.", nameof(rig));+ NativeMethods.AuditionStore(_handle, r.Handle, key);+ }++ public bool IsAuditionCached(string key)+ { ThrowIfDisposed(); return NativeMethods.AuditionCached(_handle, key) != 0; }++ public bool PreviewAuditionAt(string key, double startSeconds)+ { ThrowIfDisposed(); return NativeMethods.PreviewCachedAt(_handle, key, startSeconds) != 0; }++ private sealed class AuditionRig : IAuditionRig+ {+ private IntPtr _h;+ private readonly double _sr;+ public AuditionRig(IntPtr h, double sr) { _h = h; _sr = sr; }++ public IAuditionRig CreatePart() => new AuditionRig(NativeMethods.AuditionCreate(_sr), _sr);++ internal IntPtr Handle => _h != IntPtr.Zero ? _h : throw new ObjectDisposedException(nameof(AuditionRig));++ public bool SetInstrument(int kind) => NativeMethods.AuditionSetInstrument(Handle, kind) != 0;+ public bool InstrumentParam(string id, float value) => NativeMethods.AuditionInstrumentParam(Handle, id, value) != 0;+ public int AddDevice(int kind) => NativeMethods.AuditionAddDevice(Handle, kind);+ public bool DeviceParam(int index, string name, float value) => NativeMethods.AuditionDeviceParam(Handle, index, name, value) != 0;+ public int AddMidiEffect(int kind) => NativeMethods.AuditionAddMidiEffect(Handle, kind);+ public bool MidiParam(int index, string name, float value) => NativeMethods.AuditionMidiParam(Handle, index, name, value) != 0;+ public bool SetSamplerSample(string? path) => NativeMethods.AuditionSetSamplerSample(Handle, path) != 0;+ public bool AddSourceFrom(IAuditionRig part, float gain)+ => part is AuditionRig p && NativeMethods.AuditionAddSourceFrom(Handle, p.Handle, gain) != 0;+ public bool UseCachedSource(string key) => NativeMethods.AuditionUseCachedSource(Handle, key) != 0;+ public bool CacheSource(string key, float targetPeak) => NativeMethods.AuditionCacheSource(Handle, key, targetPeak) != 0;+ public bool UseKit() => NativeMethods.AuditionUseKit(Handle) != 0;+ public int KitAddPad(int note, string path, float gain, float pan, int choke)+ => NativeMethods.AuditionKitAddPad(Handle, note, path, gain, pan, choke);+ public int KitPadAddDevice(int pad, int kind) => NativeMethods.AuditionKitPadAddDevice(Handle, pad, kind);+ public bool KitPadDeviceParam(int pad, int device, string name, float value)+ => NativeMethods.AuditionKitPadDeviceParam(Handle, pad, device, name, value) != 0;+ public bool SetSourceFile(string path, double maxSeconds) => NativeMethods.AuditionSetSourceFile(Handle, path, maxSeconds) != 0;++ public long Render(IReadOnlyList<AuditionNote> notes, double bpm, double phraseBeats, double maxTailSeconds, bool rolling)+ {+ var arr = new NativeMethods.NotaAuditionNote[notes.Count];+ for (int i = 0; i < arr.Length; i++)+ arr[i] = new NativeMethods.NotaAuditionNote+ {+ StartBeat = notes[i].StartBeat, LengthBeats = notes[i].LengthBeats,+ Pitch = notes[i].Pitch, Velocity = notes[i].Velocity,+ };+ return NativeMethods.AuditionRender(Handle, arr, arr.Length, bpm, phraseBeats, maxTailSeconds, rolling ? 1 : 0);+ }++ // Cancel comes from another thread while Render runs; the lock keeps it off a rig+ // that Dispose is freeing at the same moment.+ private readonly object _gate = new();++ public void Cancel()+ {+ lock (_gate) if (_h != IntPtr.Zero) NativeMethods.AuditionCancel(_h);+ }++ public int ReadPeaks(float[] outMinMax, int maxPoints)+ => NativeMethods.AuditionPeaks(Handle, outMinMax, Math.Min(maxPoints, outMinMax.Length / 2));++ public double Seconds => NativeMethods.AuditionSeconds(Handle);++ public void Dispose()+ {+ lock (_gate)+ {+ if (_h == IntPtr.Zero) return;+ NativeMethods.AuditionDestroy(_h);+ _h = IntPtr.Zero;+ }+ }+ }+}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex d50c16c6..eaab3492 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -186,6 +186,9 @@ public sealed partial class NotaEngine : IAudioEnginepublic double PreviewPosition{ get { ThrowIfDisposed(); return NativeMethods.PreviewPosition(_handle); } }+ public int ReadPreviewScope(float[] output)+ { ThrowIfDisposed(); return NativeMethods.PreviewScope(_handle, output, Math.Min(output.Length, 4096)); }+/// <summary>Stops the current audition.</summary>public void StopPreview(){ ThrowIfDisposed(); Check(NativeMethods.StopPreview(_handle)); }diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex fdb31bfe..4a1d10d6 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -19,6 +19,7 @@ public sealed class FactoryPresetCatalog : IFactoryPresets// Built-in effect kinds: EQ 0, Compressor 1, Reverb 2, Delay 3, Utility 4.private readonly List<(FactoryPresetInfo Info, PresetDocument Doc)> _all = new();private readonly Dictionary<string, PresetDocument> _byId = new();+ private readonly Dictionary<string, FactoryPresetInfo> _infoById = new();// The browser folder the following presets go into (see Section). Starts empty for// each device, so a device's Init sits loose above its folders.@@ -2424,6 +2425,9 @@ public sealed class FactoryPresetCatalog : IFactoryPresets/// <summary>The preset's document (named params), or null — for validation and tests.</summary>public PresetDocument? Document(string id) => _byId.TryGetValue(id, out var doc) ? doc : null;+ /// <summary>The preset's browser description (device, category), or null.</summary>+ public FactoryPresetInfo? Info(string id) => _infoById.TryGetValue(id, out var info) ? info : null;+public string Apply(IAudioEngine engine, string id, int targetTrackId)=> _byId.TryGetValue(id, out var doc)? PresetService.Apply(doc, engine, targetTrackId)@@ -2677,7 +2681,9 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsvar map = new Dictionary<string, float>(ps.Length);foreach (var (key, value) in ps) map[key] = value;var doc = new PresetDocument { DisplayName = name, Type = type, BuiltinKind = kind, NamedParams = map };- _all.Add((new FactoryPresetInfo(id, name, isInstrument, kind, isMidi, _section), doc));+ var info = new FactoryPresetInfo(id, name, isInstrument, kind, isMidi, _section);+ _all.Add((info, doc));_byId[id] = doc;+ _infoById[id] = info;}}diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex 3fa1de99..b9c9d0e9 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -65,6 +65,8 @@ set(NOTA_ENGINE_SOURCESsrc/AudioFile.cppsrc/AudioImport.cppsrc/nota_engine_import.cpp+ src/nota_engine_audition.cpp+ src/Audition.cppsrc/AudioBackendFactory.cpp # platform-selected backend construction)diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex fb283b00..db92aa4c 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -165,6 +165,69 @@ NOTA_API NotaResult nota_engine_set_preview_loop(NotaEngine* engine, int32_t on)NOTA_API NotaResult nota_engine_set_preview_gain(NotaEngine* engine, float gain);/* Playhead of the audition in seconds into the file (last rendered block). */NOTA_API double nota_engine_preview_position(const NotaEngine* engine);+/* The last n (≤ 4096) mono samples the preview voice played, oldest first — for a live+ * spectrum / scope under the browser player. Returns the count written. */+NOTA_API int32_t nota_engine_preview_scope(const NotaEngine* engine, float* out, int32_t n);++/* ---- Preset audition --------------------------------------------------------+ * A standalone chain (MIDI effects -> built-in instrument -> audio effects) that renders a+ * phrase offline into a buffer: not a track, never in the graph, so it is built, rendered+ * and destroyed on any worker thread. An effect-only rig plays a source (a demo loop or a+ * file) through its devices. The finished buffer is stored in the engine's audition cache+ * under a key (message thread) and played on the preview voice with preview_cached_at, so+ * loop / gain / position / scope work as for a sample.+ * create -> set_instrument / add_device / add_midi_effect (+ params) -> render+ * -> peaks -> nota_engine_audition_store (UI thread) -> destroy. */+typedef struct NotaAudition NotaAudition;+typedef struct NotaAuditionNote {+ double start_beat;+ double length_beats;+ int32_t pitch; /* 0..127 */+ float velocity; /* 0..1 */+} NotaAuditionNote;+#define NOTA_AUDITION_ROLLING 1 /* the instrument sees a rolling transport (generative synths) */+NOTA_API NotaAudition* nota_audition_create(double sample_rate);+NOTA_API void nota_audition_destroy(NotaAudition* rig);+/* 1 = ok. Instrument kinds as nota_engine_set_track_builtin_instrument (no racks). */+NOTA_API int32_t nota_audition_set_instrument(NotaAudition* rig, int32_t kind);+/* Normalized value by plugin-param id; 1 = the id exists. */+NOTA_API int32_t nota_audition_instrument_param(NotaAudition* rig, const char* id, float value);+/* Appends a built-in audio effect / MIDI effect; returns its index or -1. */+NOTA_API int32_t nota_audition_add_device(NotaAudition* rig, int32_t kind);+NOTA_API int32_t nota_audition_device_param(NotaAudition* rig, int32_t index, const char* name, float value);+NOTA_API int32_t nota_audition_add_midi_effect(NotaAudition* rig, int32_t kind);+NOTA_API int32_t nota_audition_midi_param(NotaAudition* rig, int32_t index, const char* name, float value);+/* The Sampler's sample (NULL / "" = a procedural keys tone at C4). */+NOTA_API int32_t nota_audition_set_sampler_sample(NotaAudition* rig, const char* path_utf8);+/* Effect source: a file (its first max_seconds), or a demo track mixed from part rigs that+ * were rendered first (add_source_from). cache_source normalizes the mix to target_peak and+ * keeps it process-wide under key; use_cached_source takes it back (0 = not cached). */+NOTA_API int32_t nota_audition_set_source_file(NotaAudition* rig, const char* path_utf8, double max_seconds);+NOTA_API int32_t nota_audition_add_source_from(NotaAudition* rig, const NotaAudition* part, float gain);+NOTA_API int32_t nota_audition_use_cached_source(NotaAudition* rig, const char* key);+NOTA_API int32_t nota_audition_cache_source(NotaAudition* rig, const char* key, float target_peak);+/* Kits (Drum Rack / Nota Rhythm): a pad instrument instead of a built-in one. A pad plays a+ * one-shot file on its note with gain, pan (-1..1) and a choke group (0 = none), through its+ * own effects. Returns the pad / device index or -1. */+NOTA_API int32_t nota_audition_use_kit(NotaAudition* rig);+NOTA_API int32_t nota_audition_kit_add_pad(NotaAudition* rig, int32_t note, const char* path_utf8,+ float gain, float pan, int32_t choke);+NOTA_API int32_t nota_audition_kit_pad_add_device(NotaAudition* rig, int32_t pad, int32_t kind);+NOTA_API int32_t nota_audition_kit_pad_device_param(NotaAudition* rig, int32_t pad, int32_t device,+ const char* name, float value);+/* Renders the notes (beats at bpm) for phrase_beats, then the tail until it falls silent or+ * max_tail_seconds pass. Returns frames rendered, or -1 (cancelled / nothing to play). */+NOTA_API int64_t nota_audition_render(NotaAudition* rig, const NotaAuditionNote* notes, int32_t count,+ double bpm, double phrase_beats, double max_tail_seconds, int32_t flags);+/* Any thread: makes a running render return -1 within one block. */+NOTA_API void nota_audition_cancel(NotaAudition* rig);+NOTA_API int32_t nota_audition_peaks(const NotaAudition* rig, float* out_min_max, int32_t max_points);+NOTA_API double nota_audition_seconds(const NotaAudition* rig);+/* Message thread: keep the rendered buffer under `key` (a small LRU). */+NOTA_API NotaResult nota_engine_audition_store(NotaEngine* engine, const NotaAudition* rig, const char* key);+NOTA_API int32_t nota_engine_audition_cached(const NotaEngine* engine, const char* key);+/* Plays the cached audition from start_seconds; 0 = not cached. */+NOTA_API int32_t nota_engine_preview_cached_at(NotaEngine* engine, const char* key, double start_seconds);/* ---- xrun / dropout telemetry (M7-8) -------------------------------------* Running count of audio-device overloads/dropouts since launch. The UI pollsdiff --git a/src/native/nota.engine/src/Audition.cpp b/src/native/nota.engine/src/Audition.cppnew file mode 100644index 00000000..bec30fed--- /dev/null+++ b/src/native/nota.engine/src/Audition.cpp@@ -0,0 +1,478 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Preset audition rig — see Audition.h.++#include "Audition.h"++#include <algorithm>+#include <cmath>+#include <cstring>+#include <map>+#include <mutex>+#include <utility>++#include "AudioFile.h"+#include "Device.h"+#include "DeviceFactory.h"+#include "Instrument.h"+#include "MidiDevice.h"+#include "Sampler.h"+#include "TransportInfo.h"++namespace nota {++namespace {++constexpr int32_t kBlock = 256;+constexpr int32_t kMaxEvents = 1024;+constexpr double kPi = 3.141592653589793;++// Note-offs before note-ons at a tie, so a same-pitch retrigger releases first.+bool evLess(const MidiEv& a, const MidiEv& b) { return a.off < b.off || (a.off == b.off && !a.on && b.on); }++// A struck, decaying harmonic tone at C4 — what the Sampler plays when no sample is given.+std::shared_ptr<SampleBuffer> keysTone(double sr) {+ auto s = std::make_shared<SampleBuffer>();+ const int64_t n = static_cast<int64_t>(2.2 * sr);+ s->channels = 1; s->frames = n; s->sourceSampleRate = sr; s->samples.resize(static_cast<size_t>(n));+ const double f0 = 261.6255653;+ for (int64_t i = 0; i < n; ++i) {+ const double t = static_cast<double>(i) / sr;+ double v = 0.0;+ for (int k = 1; k <= 8; ++k) // brighter partials die faster+ v += std::sin(2.0 * kPi * f0 * k * (1.0 + 0.0004 * k * k) * t) * std::exp(-t * (1.2 + 0.9 * k)) / k;+ const double attack = std::min(1.0, t / 0.004);+ s->samples[static_cast<size_t>(i)] = static_cast<float>(v * 0.42 * attack);+ }+ s->buildPeakTable();+ return s;+}++// Any buffer → stereo at `sr` (linear interpolation), at most maxFrames long.+std::shared_ptr<SampleBuffer> toStereoAt(const SampleBuffer& src, double sr, int64_t maxFrames) {+ auto s = std::make_shared<SampleBuffer>();+ const double ratio = src.sourceSampleRate > 0 ? src.sourceSampleRate / sr : 1.0;+ const int64_t n = std::min<int64_t>(maxFrames, static_cast<int64_t>(src.frames / ratio));+ s->channels = 2; s->frames = std::max<int64_t>(0, n); s->sourceSampleRate = sr;+ s->samples.resize(static_cast<size_t>(s->frames * 2));+ for (int64_t i = 0; i < s->frames; ++i) {+ const double p = i * ratio;+ const int64_t i0 = static_cast<int64_t>(p);+ const float fr = static_cast<float>(p - i0);+ float l0, r0, l1, r1;+ src.readStereo(i0, l0, r0);+ src.readStereo(i0 + 1, l1, r1);+ s->samples[static_cast<size_t>(i * 2)] = l0 + (l1 - l0) * fr;+ s->samples[static_cast<size_t>(i * 2 + 1)] = r0 + (r1 - r0) * fr;+ }+ return s;+}++} // namespace++AuditionRig::AuditionRig(double sampleRate) : sr_(sampleRate > 0 ? sampleRate : 48000.0) {}+AuditionRig::~AuditionRig() = default;++bool AuditionRig::setInstrument(int32_t kind) {+ kit_ = nullptr;+ inst_ = makeBuiltinInstrument(kind);+ if (!inst_) return false;+ inst_->setSampleRate(sr_);+ if (kind == 1) setSamplerSample({}); // an empty Sampler would be silent+ return true;+}++bool AuditionRig::instrumentParam(const std::string& id, float value) {+ if (!inst_) return false;+ const int32_t i = inst_->pluginParamIndexOfId(id);+ if (i < 0) return false;+ inst_->pluginParamSet(i, value);+ return true;+}++int32_t AuditionRig::addDevice(int32_t kind) {+ auto d = makeBuiltinDevice(kind);+ if (!d) return -1;+ d->setSampleRate(sr_, kBlock);+ devices_.push_back(std::move(d));+ return static_cast<int32_t>(devices_.size()) - 1;+}++bool AuditionRig::deviceParam(int32_t index, const std::string& name, float value) {+ if (index < 0 || index >= static_cast<int32_t>(devices_.size())) return false;+ Device& d = *devices_[static_cast<size_t>(index)];+ for (int32_t p = 0, n = d.paramCount(); p < n; ++p)+ if (name == d.paramName(p)) { d.setParam(p, value); return true; }+ return false;+}++int32_t AuditionRig::addMidiEffect(int32_t kind) {+ auto m = makeMidiDevice(kind);+ if (!m) return -1;+ m->setSampleRate(sr_, kBlock);+ midi_.push_back(std::move(m));+ return static_cast<int32_t>(midi_.size()) - 1;+}++bool AuditionRig::midiParam(int32_t index, const std::string& name, float value) {+ if (index < 0 || index >= static_cast<int32_t>(midi_.size())) return false;+ MidiDevice& m = *midi_[static_cast<size_t>(index)];+ for (int32_t p = 0, n = m.paramCount(); p < n; ++p)+ if (name == m.paramName(p)) { m.setParam(p, value); return true; }+ return false;+}++bool AuditionRig::setSamplerSample(const std::string& path) {+ auto* sampler = dynamic_cast<Sampler*>(inst_.get());+ if (!sampler) return false;+ std::shared_ptr<SampleBuffer> buf = path.empty() ? nullptr : decodeAudioFile(path);+ if (buf && !buf->empty()) {+ buf->buildPeakTable();+ sampler->setSample(buf, 60, false);+ return true;+ }+ sampler->setSample(keysTone(sr_), 60, false);+ return path.empty();+}++bool AuditionRig::setSourceFile(const std::string& path, double maxSeconds) {+ auto buf = decodeAudioFile(path);+ if (!buf || buf->empty()) return false;+ source_ = toStereoAt(*buf, sr_, static_cast<int64_t>(std::max(0.5, maxSeconds) * sr_));+ return source_->frames > 0;+}++int64_t AuditionRig::render(const AuditionNote* notes, int32_t count, double bpm, double phraseBeats,+ double maxTailSeconds, int32_t flags) {+ if (!inst_ && !source_) return -1;+ if (bpm <= 0) bpm = 120.0;+ const double spb = sr_ * 60.0 / bpm;+ const bool rolling = (flags & kRolling) != 0;++ // The note list as absolute sample positions; offs before ons at a tie.+ struct At { int64_t frame; MidiEv ev; };+ std::vector<At> timeline;+ if (inst_ && notes)+ for (int32_t i = 0; i < count; ++i) {+ const AuditionNote& n = notes[i];+ if (n.pitch < 0 || n.pitch > 127 || n.lengthBeats <= 0) continue;+ const int64_t on = static_cast<int64_t>(std::llround(n.startBeat * spb));+ const int64_t off = std::max(on + 1, static_cast<int64_t>(std::llround((n.startBeat + n.lengthBeats) * spb)));+ timeline.push_back({on, {0, true, n.pitch, std::clamp(n.velocity, 0.0f, 1.0f), static_cast<float>(n.lengthBeats)}});+ timeline.push_back({off, {0, false, n.pitch, 0.0f}});+ }+ std::stable_sort(timeline.begin(), timeline.end(), [](const At& a, const At& b) {+ return a.frame < b.frame || (a.frame == b.frame && !a.ev.on && b.ev.on);+ });++ int64_t phraseFrames = static_cast<int64_t>(std::ceil(std::max(0.0, phraseBeats) * spb));+ if (source_) phraseFrames = std::max(phraseFrames, source_->frames);+ const int64_t maxFrames = phraseFrames + static_cast<int64_t>(std::max(0.0, maxTailSeconds) * sr_);+ if (maxFrames <= 0) return -1;++ std::vector<float> out;+ out.reserve(static_cast<size_t>(maxFrames * 2));+ float buf[kBlock * 2];+ MidiEv evA[kMaxEvents], evB[kMaxEvents];+ size_t next = 0;+ int64_t quiet = 0, lastLoud = 0;+ const int64_t quietNeeded = static_cast<int64_t>(0.25 * sr_);+ bool endedQuiet = false;++ TransportInfo ti;+ ti.bpm = bpm;+ ti.isPlaying = true;++ for (int64_t pos = 0; pos < maxFrames; pos += kBlock) {+ if (cancelled_.load(std::memory_order_relaxed)) return -1;+ const int32_t n = static_cast<int32_t>(std::min<int64_t>(kBlock, maxFrames - pos));+ const double beat = pos / spb;+ std::memset(buf, 0, sizeof(float) * static_cast<size_t>(n) * 2);++ if (inst_) {+ int nEv = 0;+ while (next < timeline.size() && timeline[next].frame < pos + n) {+ if (nEv < kMaxEvents) {+ evA[nEv] = timeline[next].ev;+ evA[nEv].off = static_cast<int32_t>(std::max<int64_t>(0, timeline[next].frame - pos));+ ++nEv;+ }+ ++next;+ }+ MidiEv* a = evA;+ MidiEv* b = evB;+ for (auto& m : midi_) {+ int outN = 0;+ m->process(a, nEv, b, outN, kMaxEvents, n, beat, spb, true);+ std::swap(a, b);+ nEv = outN;+ }+ std::sort(a, a + nEv, evLess);++ ti.ppqPosition = beat;+ ti.timeInSeconds = pos / sr_;+ ti.timeInSamples = pos;+ ti.isPlaying = rolling;+ inst_->setTransport(beat, spb, rolling);+ inst_->setTransportInfo(ti);+ int32_t cursor = 0;+ for (int k = 0; k < nEv; ++k) {+ const int32_t segEnd = std::clamp(a[k].off, 0, n);+ if (segEnd > cursor) { inst_->render(&buf[cursor * 2], segEnd - cursor); cursor = segEnd; }+ if (a[k].on) inst_->noteOn(a[k].pitch, a[k].vel);+ else inst_->noteOff(a[k].pitch);+ }+ if (cursor < n) inst_->render(&buf[cursor * 2], n - cursor);+ }++ if (source_)+ for (int32_t i = 0; i < n; ++i) {+ float l, r;+ source_->readStereo(pos + i, l, r);+ buf[i * 2] += l; buf[i * 2 + 1] += r;+ }++ ti.ppqPosition = beat;+ ti.timeInSeconds = pos / sr_;+ ti.timeInSamples = pos;+ ti.isPlaying = true;+ for (auto& d : devices_) {+ d->setTransport(beat, spb, true);+ d->setTransportInfo(ti);+ d->process(buf, n);+ }++ float peak = 0.0f;+ for (int32_t i = 0; i < n * 2; ++i) {+ if (!std::isfinite(buf[i])) buf[i] = 0.0f;+ peak = std::max(peak, std::fabs(buf[i]));+ }+ out.insert(out.end(), buf, buf + n * 2);++ // Past the phrase, stop once the tail has been below −80 dB for a quarter second.+ if (peak > 1e-4f) { quiet = 0; lastLoud = pos + n; }+ else quiet += n;+ if (pos + n >= phraseFrames && quiet >= quietNeeded) { endedQuiet = true; break; }+ }++ int64_t frames = static_cast<int64_t>(out.size() / 2);+ if (endedQuiet) frames = std::min(frames, lastLoud + static_cast<int64_t>(0.05 * sr_));+ if (frames <= 0) return -1;+ out.resize(static_cast<size_t>(frames * 2));+ if (!endedQuiet) { // cut by the tail budget: fade the last 300 ms+ const int64_t fade = std::min<int64_t>(frames, static_cast<int64_t>(0.3 * sr_));+ for (int64_t i = 0; i < fade; ++i) {+ const float g = static_cast<float>(i) / static_cast<float>(fade);+ const size_t k = static_cast<size_t>((frames - 1 - i) * 2);+ out[k] *= g; out[k + 1] *= g;+ }+ }+ // Never hand the preview voice a clipping buffer: a hot preset is brought back to −0.2 dB.+ float peak = 0.0f;+ for (float v : out) peak = std::max(peak, std::fabs(v));+ if (peak > 0.977f) { const float g = 0.977f / peak; for (float& v : out) v *= g; }++ auto res = std::make_shared<SampleBuffer>();+ res->channels = 2;+ res->frames = frames;+ res->sourceSampleRate = sr_;+ res->samples = std::move(out);+ res->buildPeakTable();+ result_ = std::move(res);+ return frames;+}++int32_t AuditionRig::peaks(float* out, int32_t maxPoints) const {+ if (!out || maxPoints <= 0 || !result_ || result_->frames <= 0) return 0;+ const SampleBuffer& b = *result_;+ const int32_t buckets = static_cast<int32_t>(std::min<int64_t>(maxPoints, b.frames));+ for (int32_t i = 0; i < buckets; ++i) {+ const int64_t f0 = b.frames * i / buckets, f1 = b.frames * (i + 1) / buckets;+ // Both channels, not the mid: a side-only or polarity-flipped signal must still show.+ float mn = 0.0f, mx = 0.0f;+ for (int64_t f = f0; f < std::max(f0 + 1, f1) && f < b.frames; ++f) {+ const float l = b.samples[static_cast<size_t>(f * 2)], r = b.samples[static_cast<size_t>(f * 2 + 1)];+ mn = std::min(mn, std::min(l, r));+ mx = std::max(mx, std::max(l, r));+ }+ out[i * 2] = mn; out[i * 2 + 1] = mx;+ }+ return buckets;+}++// --- demo-track sources ---------------------------------------------------------------++namespace {+std::mutex gSourceMu;+std::map<std::pair<std::string, int64_t>, std::shared_ptr<const SampleBuffer>> gSources; // (key, rate)+constexpr size_t kSourceCacheMax = 24;+}++bool AuditionRig::addSourceFrom(const AuditionRig& part, float gain) {+ const auto& r = part.result_;+ if (!r || r->empty() || r->channels != 2) return false;+ if (!mixing_) {+ mixing_ = std::make_shared<SampleBuffer>();+ mixing_->channels = 2;+ mixing_->sourceSampleRate = sr_;+ }+ if (r->frames > mixing_->frames) {+ mixing_->frames = r->frames;+ mixing_->samples.resize(static_cast<size_t>(r->frames * 2), 0.0f);+ }+ for (size_t i = 0; i < r->samples.size(); ++i) mixing_->samples[i] += r->samples[i] * gain;+ source_ = mixing_;+ return true;+}++bool AuditionRig::useCachedSource(const std::string& key) {+ std::lock_guard<std::mutex> lock(gSourceMu);+ auto it = gSources.find({key, static_cast<int64_t>(sr_)});+ if (it == gSources.end()) return false;+ source_ = it->second;+ mixing_.reset();+ return true;+}++bool AuditionRig::cacheSource(const std::string& key, float targetPeak) {+ if (!mixing_ || mixing_->empty()) return false;+ // One level for every track, so an effect is compared on equal terms across genres.+ float peak = 0.0f;+ for (float v : mixing_->samples) peak = std::max(peak, std::fabs(v));+ if (peak > 1e-6f && targetPeak > 0.0f) {+ const float g = targetPeak / peak;+ for (float& v : mixing_->samples) v *= g;+ }+ std::shared_ptr<const SampleBuffer> done = std::move(mixing_);+ source_ = done;+ std::lock_guard<std::mutex> lock(gSourceMu);+ if (gSources.size() >= kSourceCacheMax) gSources.erase(gSources.begin());+ gSources[{key, static_cast<int64_t>(sr_)}] = done;+ return true;+}++// --- kits -----------------------------------------------------------------------------+// One-shot pads, the way a Drum Rack plays a kit: each pad restarts on its note, a pad in a+// choke group cuts the others in it (a 5 ms fade, no click), and each pad runs its own effect+// chain before its gain and pan. An idle pad's chain keeps running until its tail dies out.++class AuditionKit final : public Instrument {+public:+ explicit AuditionKit(double sr) : sr_(sr) { scratch_.resize(kBlock * 2); }++ struct Pad {+ int32_t note = 36;+ std::shared_ptr<SampleBuffer> buf;+ float gl = 1.0f, gr = 1.0f;+ int32_t choke = 0;+ std::vector<std::shared_ptr<Device>> fx;+ double pos = -1.0; // source frames; < 0 = silent+ float vel = 0.0f;+ float fade = 1.0f, fadeStep = 0.0f; // choke fade-out+ int64_t quiet = 0; // frames the pad (and its tail) has been silent+ };++ int32_t addPad(int32_t note, std::shared_ptr<SampleBuffer> buf, float gain, float pan, int32_t choke) {+ Pad p;+ p.note = note; p.buf = std::move(buf); p.choke = choke;+ pan = std::clamp(pan, -1.0f, 1.0f);+ p.gl = gain * std::min(1.0f, 1.0f - pan);+ p.gr = gain * std::min(1.0f, 1.0f + pan);+ p.quiet = kIdle;+ pads_.push_back(std::move(p));+ return static_cast<int32_t>(pads_.size()) - 1;+ }+ Pad* pad(int32_t i) { return i >= 0 && i < static_cast<int32_t>(pads_.size()) ? &pads_[static_cast<size_t>(i)] : nullptr; }++ void setSampleRate(double sr) override { sr_ = sr; }+ void noteOn(int32_t pitch, float velocity) override {+ for (auto& p : pads_) {+ if (p.note != pitch) continue;+ if (p.choke > 0)+ for (auto& o : pads_)+ if (&o != &p && o.choke == p.choke && o.pos >= 0.0) o.fadeStep = 1.0f / static_cast<float>(0.005 * sr_);+ p.pos = 0.0; p.vel = velocity; p.fade = 1.0f; p.fadeStep = 0.0f; p.quiet = 0;+ }+ }+ void noteOff(int32_t) override {}+ void allNotesOff() override { for (auto& p : pads_) p.pos = -1.0; }++ void render(float* out, int32_t frames) override {+ for (auto& p : pads_) {+ if (p.pos < 0.0 && p.quiet >= kIdle) continue;+ std::fill(scratch_.begin(), scratch_.begin() + frames * 2, 0.0f);+ bool sounding = false;+ if (p.pos >= 0.0 && p.buf) {+ const SampleBuffer& b = *p.buf;+ const double ratio = b.sourceSampleRate > 0 ? b.sourceSampleRate / sr_ : 1.0;+ for (int32_t i = 0; i < frames; ++i) {+ const int64_t i0 = static_cast<int64_t>(p.pos);+ if (i0 >= b.frames || p.fade <= 0.0f) { p.pos = -1.0; break; }+ const float fr = static_cast<float>(p.pos - i0);+ float l0, r0, l1, r1;+ b.readStereo(i0, l0, r0);+ b.readStereo(i0 + 1, l1, r1);+ const float g = p.vel * p.fade;+ scratch_[static_cast<size_t>(i * 2)] = (l0 + (l1 - l0) * fr) * g;+ scratch_[static_cast<size_t>(i * 2 + 1)] = (r0 + (r1 - r0) * fr) * g;+ p.fade -= p.fadeStep;+ p.pos += ratio;+ }+ sounding = true;+ }+ for (auto& d : p.fx) d->process(scratch_.data(), frames);+ float peak = 0.0f;+ for (int32_t i = 0; i < frames; ++i) {+ const float l = scratch_[static_cast<size_t>(i * 2)] * p.gl, r = scratch_[static_cast<size_t>(i * 2 + 1)] * p.gr;+ out[i * 2] += l; out[i * 2 + 1] += r;+ peak = std::max(peak, std::max(std::fabs(l), std::fabs(r)));+ }+ p.quiet = (sounding || peak > 1e-5f) ? 0 : p.quiet + frames;+ }+ }++ int32_t kind() const override { return 4; }+ const char* displayName() const override { return "Kit"; }++private:+ static constexpr int64_t kIdle = 48000; // ~1 s of silence ends a pad's tail+ double sr_;+ std::vector<Pad> pads_;+ std::vector<float> scratch_;+};++bool AuditionRig::useKit() {+ auto k = std::make_shared<AuditionKit>(sr_);+ kit_ = k.get();+ inst_ = std::move(k);+ return true;+}++int32_t AuditionRig::kitAddPad(int32_t note, const std::string& path, float gain, float pan, int32_t choke) {+ if (!kit_) return -1;+ auto buf = decodeAudioFile(path);+ if (!buf || buf->empty()) return -1;+ return kit_->addPad(note, std::move(buf), gain, pan, choke);+}++int32_t AuditionRig::kitPadAddDevice(int32_t pad, int32_t kind) {+ auto* p = kit_ ? kit_->pad(pad) : nullptr;+ if (!p) return -1;+ auto d = makeBuiltinDevice(kind);+ if (!d) return -1;+ d->setSampleRate(sr_, kBlock);+ p->fx.push_back(std::move(d));+ return static_cast<int32_t>(p->fx.size()) - 1;+}++bool AuditionRig::kitPadDeviceParam(int32_t pad, int32_t device, const std::string& name, float value) {+ auto* p = kit_ ? kit_->pad(pad) : nullptr;+ if (!p || device < 0 || device >= static_cast<int32_t>(p->fx.size())) return false;+ Device& d = *p->fx[static_cast<size_t>(device)];+ for (int32_t i = 0, n = d.paramCount(); i < n; ++i)+ if (name == d.paramName(i)) { d.setParam(i, value); return true; }+ return false;+}++} // namespace notadiff --git a/src/native/nota.engine/src/Audition.h b/src/native/nota.engine/src/Audition.hnew file mode 100644index 00000000..b933c941--- /dev/null+++ b/src/native/nota.engine/src/Audition.h@@ -0,0 +1,97 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Preset audition: a standalone chain — MIDI effects → instrument → audio effects — built+// fresh from built-in kinds, that renders a short phrase OFFLINE into a buffer. It is not a+// track and never enters the graph, so it can be built, rendered and thrown away on any+// worker thread while the audio thread plays the project; the finished buffer is handed to+// the engine's preview voice (see Engine::auditionStore / previewCached), which gives the+// browser player its waveform, seek, loop and level for free.+//+// An effect preset has no instrument: a source buffer is fed through its devices instead —+// a file, or a demo track the managed side composes from parts (each part a rig of its own,+// mixed in with addSourceFrom and kept by key with cacheSource, so a track is rendered once+// per session). A kit (Drum Rack / Nota Rhythm) plays on useKit's pad instrument: one-shot+// pads with gain, pan, choke groups and their own effect chains. Rendering runs in 256-frame+// blocks with a cancel flag checked between them, so a stale audition (the selection moved+// on) stops within a block. After the phrase the rig keeps rendering until the tail+// (release, reverb, delay) falls below −80 dB or the tail budget runs out (then it fades).++#pragma once++#include <atomic>+#include <cstdint>+#include <memory>+#include <string>+#include <vector>++#include "SampleBuffer.h"++namespace nota {++class Device;+class Instrument;+class MidiDevice;+class AuditionKit;++struct AuditionNote {+ double startBeat;+ double lengthBeats;+ int32_t pitch;+ float velocity; // 0..1+};++class AuditionRig {+public:+ // Render flags.+ static constexpr int32_t kRolling = 1; // instruments see a rolling transport (generative synths)++ explicit AuditionRig(double sampleRate);+ ~AuditionRig();++ bool setInstrument(int32_t kind);+ bool instrumentParam(const std::string& id, float value); // normalized, by plugin-param id+ int32_t addDevice(int32_t kind);+ bool deviceParam(int32_t index, const std::string& name, float value);+ int32_t addMidiEffect(int32_t kind);+ bool midiParam(int32_t index, const std::string& name, float value);+ // The Sampler's sample: a file, or (empty path) a procedural keys tone rooted at C4.+ bool setSamplerSample(const std::string& path);+ bool setSourceFile(const std::string& path, double maxSeconds);+ // Mixes another rig's rendered result into this rig's source (a demo track's part).+ bool addSourceFrom(const AuditionRig& part, float gain);+ // Demo tracks, rendered once: cacheSource normalizes the mixed source to targetPeak and+ // keeps it (process-wide, any thread) under key; useCachedSource takes it back.+ bool useCachedSource(const std::string& key);+ bool cacheSource(const std::string& key, float targetPeak);++ // Kits: a pad instrument in place of a built-in one. Pan −1..1, choke 0 = none.+ bool useKit();+ int32_t kitAddPad(int32_t note, const std::string& path, float gain, float pan, int32_t choke);+ int32_t kitPadAddDevice(int32_t pad, int32_t kind);+ bool kitPadDeviceParam(int32_t pad, int32_t device, const std::string& name, float value);++ // Renders the phrase (plus its tail) into the result buffer. Returns the frame count,+ // or -1 when cancelled / nothing to render. Call once per rig.+ int64_t render(const AuditionNote* notes, int32_t count, double bpm, double phraseBeats,+ double maxTailSeconds, int32_t flags);+ void cancel() { cancelled_.store(true, std::memory_order_relaxed); }++ // (min, max) pairs over both channels of the result; returns the bucket count.+ int32_t peaks(float* outMinMax, int32_t maxPoints) const;+ double seconds() const { return result_ && sr_ > 0 ? result_->frames / sr_ : 0.0; }+ std::shared_ptr<SampleBuffer> result() const { return result_; }++private:+ double sr_;+ std::shared_ptr<Instrument> inst_;+ std::vector<std::shared_ptr<Device>> devices_;+ std::vector<std::shared_ptr<MidiDevice>> midi_;+ std::shared_ptr<const SampleBuffer> source_; // stereo at sr_+ std::shared_ptr<SampleBuffer> mixing_; // source_ while parts are mixed in+ std::shared_ptr<SampleBuffer> result_;+ AuditionKit* kit_ = nullptr; // inst_ when useKit()+ std::atomic<bool> cancelled_{false};+};++} // namespace notadiff --git a/src/native/nota.engine/src/DeviceFactory.h b/src/native/nota.engine/src/DeviceFactory.hnew file mode 100644index 00000000..59c04bd2--- /dev/null+++ b/src/native/nota.engine/src/DeviceFactory.h@@ -0,0 +1,23 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Fresh built-in instances by kind (defined in Engine_Devices.cpp): the engine uses them to+// add / swap / clone devices and read factory defaults; the preset audition rig builds its+// standalone chain from them. nullptr = racks, plug-ins or an unknown kind.++#pragma once++#include <cstdint>+#include <memory>++namespace nota {++class Device;+class Instrument;+class MidiDevice;++std::shared_ptr<Device> makeBuiltinDevice(int32_t kind); // audio effects (builtinKind)+std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind); // instruments (kind), not racks+std::shared_ptr<MidiDevice> makeMidiDevice(int32_t kind); // MIDI effects (midiKind)++} // namespace notadiff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cppindex a49df63e..3e847c45 100644--- a/src/native/nota.engine/src/Engine.cpp+++ b/src/native/nota.engine/src/Engine.cpp@@ -192,10 +192,8 @@ bool Engine::previewFile(const std::string& path, double startSeconds) {if (!buf || buf->empty()) return false;// Retire the previous buffer so the audio thread can finish any block that// still holds its raw pointer, then publish the new one.- if (previewHold_) previewRetired_.push_back(std::move(previewHold_));- previewHold_ = buf;+ publishPreview(buf);previewPath_ = path;- previewLive_.store(buf.get(), std::memory_order_release);}const double start = startSeconds > 0.0 ? startSeconds : 0.0;previewStartSec_.store(start, std::memory_order_relaxed);@@ -207,15 +205,84 @@ bool Engine::previewFile(const std::string& path, double startSeconds) {void Engine::stopPreview() {previewActive_.store(false, std::memory_order_release);+ reapPreview();+}++void Engine::publishPreview(std::shared_ptr<SampleBuffer> buf) {+ auto old = std::move(previewHold_);+ previewHold_ = std::move(buf);+ previewLive_.store(previewHold_.get(), std::memory_order_release);+ // Stamped after the swap: a render that starts from here on reads the new buffer.+ if (old) previewRetired_.emplace_back(previewEpoch_.load(std::memory_order_acquire), std::move(old));+ reapPreview();+}++void Engine::reapPreview() {+ const uint64_t now = previewEpoch_.load(std::memory_order_acquire);+ previewRetired_.erase(std::remove_if(previewRetired_.begin(), previewRetired_.end(),+ [now](const auto& r) { return now >= r.first + 2; }),+ previewRetired_.end());+}++// --- preset audition cache ---------------------------------------------------------++namespace {+constexpr size_t kAuditionCacheMax = 32;+constexpr int64_t kAuditionCacheBytes = 96ll << 20;+}++void Engine::auditionStore(const std::string& key, std::shared_ptr<SampleBuffer> buf) {+ if (key.empty() || !buf || buf->empty()) return;+ auditionCache_.remove_if([&](const auto& e) { return e.first == key; });+ auditionCache_.emplace_front(key, std::move(buf));+ // Trim the least recent past the count / memory budget. The buffer the preview voice+ // holds stays alive through previewHold_ even when it drops out of the cache.+ int64_t bytes = 0;+ size_t kept = 0;+ for (auto it = auditionCache_.begin(); it != auditionCache_.end();) {+ bytes += static_cast<int64_t>(it->second->samples.size() * sizeof(float));+ if (++kept > kAuditionCacheMax || (kept > 1 && bytes > kAuditionCacheBytes)) it = auditionCache_.erase(it);+ else ++it;+ }+}++bool Engine::auditionCached(const std::string& key) const {+ for (const auto& e : auditionCache_) if (e.first == key) return true;+ return false;+}++bool Engine::previewCached(const std::string& key, double startSeconds) {+ auto it = std::find_if(auditionCache_.begin(), auditionCache_.end(), [&](const auto& e) { return e.first == key; });+ if (it == auditionCache_.end()) return false;+ auditionCache_.splice(auditionCache_.begin(), auditionCache_, it); // most recent+ const auto& buf = auditionCache_.front().second;+ if (previewHold_ != buf) publishPreview(buf);+ previewPath_ = key; // a file preview of any real path decodes afresh+ const double start = startSeconds > 0.0 ? startSeconds : 0.0;+ previewStartSec_.store(start, std::memory_order_relaxed);+ previewPosSec_.store(start, std::memory_order_relaxed);+ previewRestart_.store(true, std::memory_order_release);+ previewActive_.store(true, std::memory_order_release);+ return true;+}++int32_t Engine::previewScope(float* out, int32_t n) const {+ if (!out || n <= 0) return 0;+ n = std::min(n, kPreviewScope);+ const int64_t w = previewScopeW_.load(std::memory_order_acquire);+ for (int32_t i = 0; i < n; ++i)+ out[i] = previewScope_[(w - n + i) & (kPreviewScope - 1)].load(std::memory_order_relaxed);+ return n;}// Audio thread: mix the audition voice into `out` at its natural pitch.void Engine::renderPreview(float* out, int32_t numFrames) {- if (!previewActive_.load(std::memory_order_acquire)) {- // Safe point to release retired buffers (audio thread not reading them).- if (!previewRetired_.empty()) previewRetired_.clear();- return;- }+ // Every call, however it returns, ends one render epoch (see publishPreview).+ struct EpochTick {+ std::atomic<uint64_t>& e;+ ~EpochTick() { e.fetch_add(1, std::memory_order_release); }+ } tick{previewEpoch_};+ if (!previewActive_.load(std::memory_order_acquire)) return;SampleBuffer* sb = previewLive_.load(std::memory_order_acquire);if (!sb || sb->empty()) { previewActive_.store(false, std::memory_order_release); return; }const float target = previewGain_.load(std::memory_order_relaxed);@@ -228,6 +295,8 @@ void Engine::renderPreview(float* out, int32_t numFrames) {const double ratio = sr > 0 ? sb->sourceSampleRate / sr : 1.0; // source frames per device frameconst bool loop = previewLoop_.load(std::memory_order_relaxed);const float g0 = previewGainCur_, dg = numFrames > 0 ? (target - g0) / numFrames : 0.0f;+ const int64_t scopeW = previewScopeW_.load(std::memory_order_relaxed);+ int64_t scopeN = 0;for (int32_t i = 0; i < numFrames; ++i) {if (loop && previewPos_ >= sb->frames) previewPos_ -= sb->frames;const int64_t i0 = static_cast<int64_t>(previewPos_);@@ -238,10 +307,15 @@ void Engine::renderPreview(float* out, int32_t numFrames) {// Looping, the last frame interpolates into the first instead of into silence.sb->readStereo(loop && i0 + 1 >= sb->frames ? 0 : i0 + 1, l1, r1);const float g = g0 + dg * i;- out[i * 2] += g * static_cast<float>(l0 + (l1 - l0) * frac);- out[i * 2 + 1] += g * static_cast<float>(r0 + (r1 - r0) * frac);+ const float l = g * static_cast<float>(l0 + (l1 - l0) * frac);+ const float r = g * static_cast<float>(r0 + (r1 - r0) * frac);+ out[i * 2] += l;+ out[i * 2 + 1] += r;+ previewScope_[(scopeW + i) & (kPreviewScope - 1)].store(0.5f * (l + r), std::memory_order_relaxed);+ ++scopeN;previewPos_ += ratio;}+ previewScopeW_.store(scopeW + scopeN, std::memory_order_release);previewGainCur_ = target;previewPosSec_.store(sb->sourceSampleRate > 0 ? previewPos_ / sb->sourceSampleRate : 0.0,std::memory_order_relaxed);@@ -260,10 +334,8 @@ bool Engine::previewSelfTest() {buf->sourceSampleRate = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;buf->frames = static_cast<int64_t>(buf->sourceSampleRate * 0.1);buf->samples.assign(buf->frames * 2, 0.25f);- if (previewHold_) previewRetired_.push_back(std::move(previewHold_));- previewHold_ = buf;+ publishPreview(buf);previewPath_.clear();- previewLive_.store(buf.get(), std::memory_order_release);previewStartSec_.store(0.0, std::memory_order_relaxed);previewRestart_.store(true, std::memory_order_release);previewActive_.store(true, std::memory_order_release);diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex a6121356..d42b0013 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -26,6 +26,7 @@#include <array>#include <atomic>#include <functional>+#include <list>#include <memory>#include <string>#include <vector>@@ -115,6 +116,14 @@ public:double previewPosition() const { return previewPosSec_.load(std::memory_order_relaxed); }bool isPreviewActive() const { return previewActive_.load(std::memory_order_relaxed); }bool previewSelfTest(); // feed a synthetic buffer, render offline, no device+ // Preset audition: rendered buffers (see Audition.h) kept by key in a small LRU, so+ // stepping back through a list replays without a re-render. Message thread.+ void auditionStore(const std::string& key, std::shared_ptr<SampleBuffer> buf);+ bool auditionCached(const std::string& key) const;+ bool previewCached(const std::string& key, double startSeconds); // false = not cached+ // The last `n` (≤ kPreviewScope) mono samples the preview voice played, oldest first.+ int32_t previewScope(float* out, int32_t n) const;+ static constexpr int32_t kPreviewScope = 4096;// --- xrun / dropout telemetry (M7-8) ---// The backend's overload listener bumps this off the RT thread; the UI polls@@ -1070,9 +1079,15 @@ private:// Audio preview / audition (M7-4a): the message thread publishes a decoded// buffer via previewLive_ (raw ptr), keeping it alive in previewHold_ and// retiring the old one — same lifetime dance as the graph snapshots, so the- // audio thread never reads a freed buffer.+ // audio thread never reads a freed buffer. The retired list is message-thread+ // only: each entry carries the audio thread's render epoch at retirement and is+ // freed once two more renders have finished (none can still hold its pointer),+ // so the audio thread neither touches the list nor frees memory.+ void publishPreview(std::shared_ptr<SampleBuffer> buf);+ void reapPreview();std::shared_ptr<SampleBuffer> previewHold_;- std::vector<std::shared_ptr<SampleBuffer>> previewRetired_;+ std::vector<std::pair<uint64_t, std::shared_ptr<SampleBuffer>>> previewRetired_;+ std::atomic<uint64_t> previewEpoch_{0}; // audio thread: +1 per renderPreview callstd::atomic<SampleBuffer*> previewLive_{nullptr};std::atomic<bool> previewActive_{false};std::atomic<bool> previewRestart_{false};@@ -1083,6 +1098,9 @@ private:std::string previewPath_; // message thread: the file previewHold_ decodesdouble previewPos_ = 0.0; // audio-thread only, source framesfloat previewGainCur_ = 1.0f; // audio-thread only+ std::atomic<float> previewScope_[kPreviewScope] = {}; // mono ring, audio thread writes+ std::atomic<int64_t> previewScopeW_{0}; // samples written so far+ std::list<std::pair<std::string, std::shared_ptr<SampleBuffer>>> auditionCache_; // MRU first// Undo/redo snapshot stacks (M6-6). Hold retained Graph snapshots; entries// are cheap (metadata only — sample buffers are shared via shared_ptr).diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cppindex 440c3a51..cd5c02f4 100644--- a/src/native/nota.engine/src/Engine_Devices.cpp+++ b/src/native/nota.engine/src/Engine_Devices.cpp@@ -4,6 +4,7 @@// Engine — hosted plugins & device chain (M3): load instrument/effect, device CRUD/params/bypass/editor/state, clone helpers, kind/id introspection, PDC latency.#include "Engine.h"+#include "DeviceFactory.h"#include "Amp.h"#include "AutoFilter.h"#include "AudioFile.h"@@ -575,7 +576,7 @@ Device* Engine::deviceAt(int32_t trackId, int32_t deviceIndex) const {}// Fresh built-in instances, used to read a parameter's factory default value.-static std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {+std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {switch (kind) {case 0: return std::make_shared<Eq>();case 1: return std::make_shared<Compressor>();@@ -605,7 +606,7 @@ static std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {default: return nullptr; // Rack / plugin: no simple per-param default}}-static std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind) {+std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind) {switch (kind) {case 0: return std::make_shared<Synth>();case 1: return std::make_shared<Sampler>(); // empty; a sample is loaded later@@ -641,7 +642,7 @@ bool Engine::setTrackBuiltinInstrument(int32_t trackId, int32_t kind) {}// --- MIDI effects (before the instrument) ----------------------------------static std::shared_ptr<MidiDevice> makeMidiDevice(int32_t kind) {+std::shared_ptr<MidiDevice> makeMidiDevice(int32_t kind) {switch (kind) {case 0: return std::make_shared<Arpeggiator>();case 1: return std::make_shared<MidiChord>();diff --git a/src/native/nota.engine/src/nota_engine_audition.cpp b/src/native/nota.engine/src/nota_engine_audition.cppnew file mode 100644index 00000000..934dc694--- /dev/null+++ b/src/native/nota.engine/src/nota_engine_audition.cpp@@ -0,0 +1,89 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// C ABI — preset audition (an offline-rendered standalone chain, see Audition.h).++#include "nota_engine_internal.h"+#include "Audition.h"++#include <string>++#define RIG(r) reinterpret_cast<nota::AuditionRig*>(r)+#define CRIG(r) reinterpret_cast<const nota::AuditionRig*>(r)++static_assert(sizeof(NotaAuditionNote) == sizeof(nota::AuditionNote), "NotaAuditionNote layout");++extern "C" {++NotaAudition* nota_audition_create(double sample_rate) {+ return reinterpret_cast<NotaAudition*>(new nota::AuditionRig(sample_rate));+}+void nota_audition_destroy(NotaAudition* rig) { delete RIG(rig); }++int32_t nota_audition_set_instrument(NotaAudition* rig, int32_t kind) {+ return rig && RIG(rig)->setInstrument(kind) ? 1 : 0;+}+int32_t nota_audition_instrument_param(NotaAudition* rig, const char* id, float value) {+ return rig && id && RIG(rig)->instrumentParam(id, value) ? 1 : 0;+}+int32_t nota_audition_add_device(NotaAudition* rig, int32_t kind) { return rig ? RIG(rig)->addDevice(kind) : -1; }+int32_t nota_audition_device_param(NotaAudition* rig, int32_t index, const char* name, float value) {+ return rig && name && RIG(rig)->deviceParam(index, name, value) ? 1 : 0;+}+int32_t nota_audition_add_midi_effect(NotaAudition* rig, int32_t kind) { return rig ? RIG(rig)->addMidiEffect(kind) : -1; }+int32_t nota_audition_midi_param(NotaAudition* rig, int32_t index, const char* name, float value) {+ return rig && name && RIG(rig)->midiParam(index, name, value) ? 1 : 0;+}+int32_t nota_audition_set_sampler_sample(NotaAudition* rig, const char* path) {+ return rig && RIG(rig)->setSamplerSample(path ? std::string(path) : std::string()) ? 1 : 0;+}+int32_t nota_audition_add_source_from(NotaAudition* rig, const NotaAudition* part, float gain) {+ return rig && part && RIG(rig)->addSourceFrom(*CRIG(part), gain) ? 1 : 0;+}+int32_t nota_audition_use_cached_source(NotaAudition* rig, const char* key) {+ return rig && key && RIG(rig)->useCachedSource(key) ? 1 : 0;+}+int32_t nota_audition_cache_source(NotaAudition* rig, const char* key, float target_peak) {+ return rig && key && RIG(rig)->cacheSource(key, target_peak) ? 1 : 0;+}+int32_t nota_audition_use_kit(NotaAudition* rig) { return rig && RIG(rig)->useKit() ? 1 : 0; }+int32_t nota_audition_kit_add_pad(NotaAudition* rig, int32_t note, const char* path, float gain, float pan, int32_t choke) {+ return rig && path ? RIG(rig)->kitAddPad(note, path, gain, pan, choke) : -1;+}+int32_t nota_audition_kit_pad_add_device(NotaAudition* rig, int32_t pad, int32_t kind) {+ return rig ? RIG(rig)->kitPadAddDevice(pad, kind) : -1;+}+int32_t nota_audition_kit_pad_device_param(NotaAudition* rig, int32_t pad, int32_t device, const char* name, float value) {+ return rig && name && RIG(rig)->kitPadDeviceParam(pad, device, name, value) ? 1 : 0;+}+int32_t nota_audition_set_source_file(NotaAudition* rig, const char* path, double max_seconds) {+ return rig && path && RIG(rig)->setSourceFile(path, max_seconds) ? 1 : 0;+}+int64_t nota_audition_render(NotaAudition* rig, const NotaAuditionNote* notes, int32_t count,+ double bpm, double phrase_beats, double max_tail_seconds, int32_t flags) {+ if (!rig) return -1;+ return RIG(rig)->render(reinterpret_cast<const nota::AuditionNote*>(notes), count, bpm, phrase_beats,+ max_tail_seconds, flags);+}+void nota_audition_cancel(NotaAudition* rig) { if (rig) RIG(rig)->cancel(); }+int32_t nota_audition_peaks(const NotaAudition* rig, float* out, int32_t max_points) {+ return rig ? CRIG(rig)->peaks(out, max_points) : 0;+}+double nota_audition_seconds(const NotaAudition* rig) { return rig ? CRIG(rig)->seconds() : 0.0; }++NotaResult nota_engine_audition_store(NotaEngine* e, const NotaAudition* rig, const char* key) {+ if (!e || !rig || !key || !CRIG(rig)->result()) return NOTA_ERR_INVALID_ARG;+ ENG(e)->auditionStore(key, CRIG(rig)->result());+ return NOTA_OK;+}+int32_t nota_engine_audition_cached(const NotaEngine* e, const char* key) {+ return e && key && CENG(e)->auditionCached(key) ? 1 : 0;+}+int32_t nota_engine_preview_cached_at(NotaEngine* e, const char* key, double start_seconds) {+ return e && key && ENG(e)->previewCached(key, start_seconds) ? 1 : 0;+}+int32_t nota_engine_preview_scope(const NotaEngine* e, float* out, int32_t n) {+ return e ? CENG(e)->previewScope(out, n) : 0;+}++} // extern "C"diff --git a/tests/Nota.SmokeTest/AuditionTests.cs b/tests/Nota.SmokeTest/AuditionTests.csnew file mode 100644index 00000000..9d323502--- /dev/null+++ b/tests/Nota.SmokeTest/AuditionTests.cs@@ -0,0 +1,161 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Browser preset audition: every factory preset (and every bare built-in device) renders an+// audible, finite phrase offline; renders cancel; the engine caches and replays them.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --audition`.++using System.Diagnostics;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class AuditionTests+{+ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ using var engine = new NotaEngine();+ var factory = new FactoryPresetCatalog();+ var audition = new PresetAudition(factory, new DrumKitService());++ // (plan, frames, rms, peak, ms) per subject.+ (AuditionPlan? Plan, long Frames, double Rms, float Peak, double Ms, string Why) Render(AuditionSubject s,+ string src = AuditionTrackIds.Auto, string? sample = null)+ {+ var plan = audition.Plan(s, src, sample, out var why);+ if (plan is null) return (null, 0, 0, 0, 0, why);+ var sw = Stopwatch.StartNew();+ using var rig = engine.CreateAuditionRig();+ if (!plan.Build(rig)) return (plan, 0, 0, 0, 0, "build failed");+ long frames = rig.Render(plan.Notes, plan.Bpm, plan.PhraseBeats, plan.TailSeconds, plan.Rolling);+ double ms = sw.Elapsed.TotalMilliseconds;+ var peaks = new float[1024];+ int n = rig.ReadPeaks(peaks, 512);+ double sum = 0; float peak = 0;+ bool finite = true;+ for (int i = 0; i < n * 2; i++)+ {+ if (!float.IsFinite(peaks[i])) finite = false;+ sum += peaks[i] * (double)peaks[i];+ peak = Math.Max(peak, Math.Abs(peaks[i]));+ }+ return (plan, frames, finite ? Math.Sqrt(sum / Math.Max(1, n * 2)) : double.NaN, peak, ms, "");+ }++ // Every factory preset renders something audible and finite, within a sane time.+ var silent = new List<string>();+ var slow = new List<string>();+ int count = 0;+ double total = 0, worst = 0;+ string worstId = "";+ // Silent by design: a mute, and freezes that hold an empty buffer (they sound once fed).+ var silentByDesign = new HashSet<string> { "util/Mute", "reverb/Stone Hold", "delay/Tape Hold" };+ foreach (var fp in factory.All())+ {+ if (silentByDesign.Contains(fp.Id)) continue;+ var r = Render(new AuditionSubject(AuditionSubjectKind.Preset, fp.BuiltinKind, "factory:" + fp.Id, fp.DisplayName));+ count++;+ if (r.Plan is null || r.Frames <= 0 || !double.IsFinite(r.Rms) || r.Peak < 0.003f)+ silent.Add($"{fp.Id} ({(r.Plan is null ? r.Why : $"peak {r.Peak:0.0000}")})");+ total += r.Ms;+ if (r.Ms > worst) { worst = r.Ms; worstId = fp.Id; }+ if (r.Ms > 1500) slow.Add($"{fp.Id} {r.Ms:0} ms");+ }+ yield return (silent.Count == 0,+ $"all {count} factory presets audition audibly ({silent.Count} silent: {string.Join(", ", silent.Take(8))})");+ yield return (slow.Count == 0,+ $"renders stay quick: avg {total / Math.Max(1, count):0} ms, worst {worst:0} ms ({worstId}){(slow.Count > 0 ? " · slow: " + string.Join(", ", slow.Take(5)) : "")}");++ // Bare devices audition their default sound; racks say why they can't.+ var devSilent = new List<string>();+ foreach (int k in new[] { 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 })+ {+ var r = Render(new AuditionSubject(AuditionSubjectKind.Instrument, k, "", ""));+ if (r.Frames <= 0 || r.Peak < 0.003f) devSilent.Add($"inst {k}");+ }+ for (int k = 0; k <= 25; k++)+ {+ if (k == 5) continue;+ var r = Render(new AuditionSubject(AuditionSubjectKind.AudioEffect, k, "", ""));+ if (r.Frames <= 0 || r.Peak < 0.003f) devSilent.Add($"fx {k}");+ }+ for (int k = 0; k <= 5; k++)+ {+ var r = Render(new AuditionSubject(AuditionSubjectKind.MidiEffect, k, "", ""));+ if (r.Frames <= 0 || r.Peak < 0.003f) devSilent.Add($"midi {k}");+ }+ yield return (devSilent.Count == 0, $"every built-in device auditions its default sound ({string.Join(", ", devSilent)})");+ var rack = audition.Plan(new AuditionSubject(AuditionSubjectKind.Instrument, 3, "", ""), AuditionTrackIds.Auto, null, out var rackWhy);+ yield return (rack is null && rackWhy.Length > 0, "the Instrument Rack declines with a reason");++ // Every factory kit plays its groove, as a Drum Rack and as a Nota Rhythm's voices.+ var kitSilent = new List<string>();+ double kitWorst = 0;+ foreach (var kit in Nota.Infrastructure.Kits.KitCatalog.All)+ foreach (var prefix in new[] { "kit:", "rhythmkit:" })+ {+ var r = Render(new AuditionSubject(AuditionSubjectKind.Preset, -1, prefix + kit.Id, kit.Name));+ kitWorst = Math.Max(kitWorst, r.Ms);+ if (r.Plan is null || r.Frames <= 0 || r.Peak < 0.01f) kitSilent.Add($"{prefix}{kit.Id} ({r.Why}{r.Peak:0.000})");+ }+ yield return (kitSilent.Count == 0,+ $"all {Nota.Infrastructure.Kits.KitCatalog.All.Count} kits audition as Drum Rack and Rhythm (worst {kitWorst:0} ms; silent: {string.Join(", ", kitSilent.Take(6))})");++ // Effect tracks: Auto picks per device; every track renders; the key tells them apart.+ var comp = audition.Plan(new AuditionSubject(AuditionSubjectKind.AudioEffect, 1, "", ""), AuditionTrackIds.Auto, null, out _);+ var verb = audition.Plan(new AuditionSubject(AuditionSubjectKind.AudioEffect, 2, "", ""), AuditionTrackIds.Auto, null, out _);+ var eq = audition.Plan(new AuditionSubject(AuditionSubjectKind.AudioEffect, 0, "", ""), AuditionTrackIds.Auto, null, out _);+ yield return (comp?.TrackId == "drums" && verb?.TrackId == "keys" && eq?.TrackId == "pop" && comp.IsEffect,+ "auto track: a compressor hears the drums, a reverb the keys, an EQ the pop mix");+ var keys = new HashSet<string>();+ var bad = new List<string>();+ foreach (var t in audition.Tracks)+ {+ var sw = Stopwatch.StartNew();+ var r = Render(new AuditionSubject(AuditionSubjectKind.AudioEffect, 2, "", ""), t.Id);+ if (r.Frames <= 0 || r.Peak < 0.05f || r.Plan!.TrackId != t.Id) bad.Add($"{t.Id} ({r.Peak:0.000})");+ keys.Add(r.Plan!.Key);+ Console.WriteLine($" track {t.Id,-10} {r.Frames / 48000.0:0.0} s, first render {sw.Elapsed.TotalMilliseconds:0} ms");+ }+ var noSample = audition.Plan(new AuditionSubject(AuditionSubjectKind.AudioEffect, 2, "", ""), AuditionTrackIds.Sample, null, out _);+ yield return (bad.Count == 0 && keys.Count == audition.Tracks.Count && noSample?.TrackId == "keys",+ $"all {audition.Tracks.Count} demo tracks render under their own key; Sample without a sample falls back to Auto ({string.Join(", ", bad)})");+ {+ var sw = Stopwatch.StartNew();+ var r = Render(new AuditionSubject(AuditionSubjectKind.AudioEffect, 1, "", ""), "house");+ yield return (r.Frames > 0 && sw.Elapsed.TotalMilliseconds < 300,+ $"a demo track renders once and is reused (house again: {sw.Elapsed.TotalMilliseconds:0} ms)");+ }++ // A render cancels from another thread within a block.+ {+ var plan = audition.Plan(new AuditionSubject(AuditionSubjectKind.Preset, 20, "factory:chamber/" + factory.All().First(p => p.Id.StartsWith("chamber/")).DisplayName, ""),+ "pop", null, out _)!;+ using var rig = engine.CreateAuditionRig();+ plan.Build(rig);+ var t = Task.Run(() => rig.Render(plan.Notes, plan.Bpm, plan.PhraseBeats, 60, plan.Rolling));+ Thread.Sleep(2);+ rig.Cancel();+ bool done = t.Wait(2000);+ yield return (done && t.Result == -1, $"cancel stops a running render ({(done ? t.Result : "hung")})");+ }++ // The engine caches a rendered audition and plays it back by key.+ {+ var plan = audition.Plan(new AuditionSubject(AuditionSubjectKind.Preset, 0, "factory:synth/Warm Pad", "Warm Pad"),+ AuditionTrackIds.Auto, null, out _)!;+ using var rig = engine.CreateAuditionRig();+ plan.Build(rig);+ rig.Render(plan.Notes, plan.Bpm, plan.PhraseBeats, plan.TailSeconds, plan.Rolling);+ bool before = engine.IsAuditionCached(plan.Key);+ engine.StoreAudition(rig, plan.Key);+ bool after = engine.IsAuditionCached(plan.Key);+ bool plays = engine.PreviewAuditionAt(plan.Key, 0.5) && engine.IsPreviewActive;+ bool missing = !engine.PreviewAuditionAt("factory:nope", 0);+ engine.StopPreview();+ yield return (!before && after && plays && missing && plan.Phrase == "pad chord",+ "a stored audition replays by key (a pad plays its pad chord); an unknown key reports a miss");+ }+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 263c535f..a0098430 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -100,6 +100,15 @@ if (args.Length >= 1 && args[0] == "--audiocheck")return f == 0 ? 0 : 1;}+// Browser preset audition alone (fast iteration): `--audition`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--audition")+{+ Console.WriteLine("-- browser: preset audition --");+ foreach (var (ok, label) in AuditionTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "AUDITION PASSED" : $"AUDITION FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}+// Opt-in hosted-plugin check (M3-3): `--hostcheck <path-to-nota-scanworker>`.// Loads a hosted AU instrument and effect and confirms audio flows through them.if (args.Length >= 2 && args[0] == "--hostcheck")@@ -13431,5 +13440,9 @@ Console.WriteLine("-- background audio import --");Check(!bvm.Effects.Any(i => i.Depth > 0), "clearing the search collapses back to devices");}+// --- browser: preset audition (offline-rendered, cached, played on the preview voice) ---+Console.WriteLine("-- browser: preset audition --");+foreach (var (ok, label) in AuditionTests.Run()) Check(ok, label);+Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");return failures == 0 ? 0 : 1;