Skip to content

armgit / nota

Public Imported from GitHub
0

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

(feat) Add Mosaic

Egor Khindikaynen9edd77b5138b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 40318f58..310a3bca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,17 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Nota Mosaic — a multisample instrument.** Many samples across the keyboard: zones by key and
+ velocity, layers with round-robin, release samples that sound when you let go of a key (quieter
+ after a long hold), the sustain pedal, up to 128 voices and MPE. The Zones tab draws the map —
+ drag a zone to move it, an edge to resize it, play the keyboard under it. Load an **SFZ**
+ instrument, or build one from a folder: **Create multisample** (right-click a folder in the
+ Files tab, or drop files on the card) reads the notes, velocity layers and round-robin steps
+ from the file names, checks the octave by ear and shows what needs a look before it saves the
+ presets. Every installed sample pack shows up as Mosaic presets under **Packs**, and 11 factory
+ presets play built-in multisamples (felt piano, mallets, nylon guitar and more). Samples are
+ referenced, not copied into the project; if a pack is missing on another computer, the card
+ offers to install it.
- **Tap tempo.** A **TAP** cell beside the BPM in the transport bar: tap the beat on it and the
project tempo follows from the second tap, averaged over the last eight. Four dots count the
beats as you tap. Change pace mid-series and it picks up the new tempo at once; pause for
diff --git a/FEATURES.md b/FEATURES.md
index ac898898..eda396e3 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -444,6 +444,27 @@ and user presets, automation, persistence and cloning.
preamp (drive, bass, treble), mono or stereo-pan tremolo (free or tempo-synced), phaser,
chorus, Suitcase / Combo / DI cabinet, volume and pan. Two sizes: L (Sound / FX tabs) and S
(model, pickup, four knobs). 40 factory presets; MCP `read_keys` / `set_keys`.
+- **Nota Mosaic** — multisample instrument: zones (a sample on a key × velocity rectangle with
+ its root, fine tune, gain, pan, start / end and loop) in groups with a shared gain / tune and
+ a round-robin (Sequential / Random / No repeat), key and velocity crossfades, exclusive groups
+ (choke by `off_by`), release samples on key-up or pedal-up that get quieter the longer the
+ key was held. Poly 16 / 32 / 64 / 128 (steals released, then the quietest, then the oldest
+ voices with an adjustable fade; up to 1–4 strikes per key), Mono with glide, Choke; sustain
+ pedal (CC64); MPE (bend with a set range, pressure → level, slide → cutoff); amp ADSR,
+ LP / HP / BP filter with keytrack and env → cutoff, a velocity curve. Card tabs Zones (drag
+ tiles and edges on the map, the keyboard plays, Attack / Release view), Sample, Groups,
+ Pitch, Env, Filter, and a Voices rail; S size shows a mini map. Samples load into RAM in the
+ background (notes silent until ready) and stay referenced, not copied — a project or preset
+ on a computer without the pack offers to install it or to locate the folder. **SFZ import**
+ (`#include` / `#define`, Windows paths, CC articulations picked from the tab strip, an import
+ report of what was ignored); **Create multisample** maps a folder by file names
+ (`trombone_gb4.wav`, `_f_`, `_rr2`, `_rel`), checks the octave convention by pitch detection
+ and lists gaps, duplicates and guessed notes (browser folder menu, or files dropped on the
+ card). Installed sample packs become presets under Nota Mosaic → Packs. 11 factory presets
+ on built-in multisamples (felt piano with release samples, mallets, nylon guitar, brass, pad,
+ music box) rendered on first use; MCP `read_mosaic`, `set_mosaic`, `set_mosaic_zone`,
+ `set_mosaic_group`, `import_sfz`, `create_multisample`, `list_mosaic_presets`,
+ `load_mosaic_preset`, `scan_sample_packs`.
### Audio effects
- **Nota EQ-8** (kind 0) — 8-band parametric: each band on / off, Low cut / Low shelf / Bell /
@@ -956,6 +977,8 @@ Coverage:
- **AI models**: `list_ai_models` (installed or not), `separate_stems` (a clip → a group of
Drums / Bass / Other / Vocals tracks), `convert_audio_to_midi` (melody or harmony with
basic-pitch → a new MIDI track). Installing models stays with the user.
+- **Nota Mosaic**: read and shape it, edit zones and groups, import SFZ, map a folder of
+ samples by name, list and load its factory and pack presets (see Nota Mosaic above).
- **Sample library**: `search_samples` (kind, BPM range, key, words in the path),
`get_sample_info`, `find_similar_samples`, `get_project_key` / `set_project_key`.
- **MIDI devices and MIDI Learn over MCP**: list connected MIDI inputs, toggle listening,
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.cs
index 5d54cbbe..bc322045 100644
--- a/src/managed/Nota.App/App.axaml.cs
+++ b/src/managed/Nota.App/App.axaml.cs
@@ -51,6 +51,7 @@ public partial class App : Avalonia.Application
services.AddSingleton<IFactoryPresets, FactoryPresetCatalog>();
services.AddSingleton<IPresetAudition, PresetAudition>();
services.AddSingleton<IDrumKits, DrumKitService>();
+ services.AddSingleton<IMosaicPacks, Nota.Infrastructure.Mosaic.MosaicPackLibrary>();
services.AddSingleton<IBrowserLibrary, BrowserLibraryService>();
services.AddSingleton<IAudioDeviceService, AudioDeviceService>();
services.AddSingleton<IMidiDeviceService, MidiDeviceService>();
@@ -91,6 +92,16 @@ public partial class App : Avalonia.Application
// paints so nothing flashes graphite on the way to paper.
NotaThemeService.Set(Services.GetRequiredService<ISettingsService>().Current.Theme);
+ // Nota Mosaic's samples resolve against the Samples and data folders; installed sample
+ // packs get their Mosaic presets in the background (once per pack version).
+ Nota.Infrastructure.Mosaic.MosaicRoots.Install(Services.GetRequiredService<ISettingsService>());
+ _ = System.Threading.Tasks.Task.Run(async () =>
+ {
+ await System.Threading.Tasks.Task.Delay(4000);
+ try { await Services.GetRequiredService<IMosaicPacks>().ScanAsync(); }
+ catch (Exception e) { log.Error("Couldn't make Mosaic presets for the sample packs", e); }
+ });
+
// Plugins installed from the registry (Preferences → Get Plug-ins) live in their own folder.
try { PluginScan.EnsureStoreScanPath(Services.GetRequiredService<IPluginCatalog>(), Services.GetRequiredService<IPluginStore>()); }
catch (Exception e) { log.Error("Couldn't register the Get Plug-ins folder", e); }
diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.cs
index 70c1822a..dfd111fe 100644
--- a/src/managed/Nota.App/BrowserView.cs
+++ b/src/managed/Nota.App/BrowserView.cs
@@ -230,6 +230,9 @@ public sealed class BrowserView : UserControl
public PreviewPlayer Preview => _previewFooter;
/// <summary>Reveal a sample / folder / project in the system file manager.</summary>
public event Action<BrowserItem>? RevealRequested;
+
+ /// <summary>Map a sample folder into Nota Mosaic presets (the auto-multisample preview).</summary>
+ public event Action<BrowserItem>? CreateMultisampleRequested;
/// <summary>Delete a project bundle (moves to Trash after confirmation).</summary>
public event Action<BrowserItem>? DeleteProjectRequested;
/// <summary>Open the tag editor. Item null = manage all tags; non-null = create a tag
@@ -1562,8 +1565,12 @@ public sealed class BrowserView : UserControl
}
case BrowserItemKind.Folder when _active == FilesTab: // real sample folders (preset folders are synthetic)
{
+ var multi = new MenuItem { Header = "Create multisample…" };
+ multi.Click += (_, _) => CreateMultisampleRequested?.Invoke(item);
+ ToolTip.SetTip(multi, "Map the folder's samples by their names into Nota Mosaic presets");
var reveal = new MenuItem { Header = "Reveal in Finder" };
reveal.Click += (_, _) => RevealRequested?.Invoke(item);
+ flyout.Items.Add(multi);
flyout.Items.Add(reveal);
return flyout;
}
diff --git a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs
index 0553f2a6..8652060d 100644
--- a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs
+++ b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs
@@ -29,6 +29,7 @@ internal sealed class InstrumentCardFactory
[14] = new PentadInstrumentCard(),
[15] = new ConsortInstrumentCard(),
[16] = new KeysInstrumentCard(),
+ [17] = new MosaicInstrumentCard(),
};
/// <summary>Resolve the editor for a built-in instrument kind. The Sampler (1) always
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/MosaicInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/MosaicInstrumentCard.cs
new file mode 100644
index 00000000..6ea9c0fe
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Instruments/MosaicInstrumentCard.cs
@@ -0,0 +1,1428 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — Nota Mosaic (instrument kind 17), a build of the "Nota Mosaic" mockup.
+// One device, two sizes (the shell's S / L toggle — the instrument's "view" param):
+//
+// • L 700 × 260. Centre: a tab panel —
+// Zones the zone map (keys × velocity, the keyboard under it, a brass tick under
+// every root), Attack / Release to show the release zones, and the selected
+// zone's row: root · layer · round-robin, keys, velocity, fine, gain, pan.
+// Drag a tile to move it, an edge to resize; the keyboard plays.
+// Sample the selected zone's sample: start / end / loop (drag), loop mode, crossfade,
+// gain, snap to zero, trim silence.
+// Groups the layers: zones, gain, tune, round-robin and its mode, exclusive groups;
+// release triggers with their level and the length → level curve, the
+// velocity curve. The rail edits the selected group.
+// Pitch the keyboard with the selected zone's root; transpose, detune, keytrack, the
+// zone's root and fine tune, the MPE bend range.
+// Env the amp envelope (drag it), A / D / S / R, velocity curve, MPE pressure.
+// Filter the filter response (drag it), type, cutoff, reso, keytrack, env → cutoff,
+// MPE slide.
+// Rail: VOICES — Poly N (its popover: polyphony, what the voices are doing, the stealing
+// order, strikes per key, old-voice fade) / Mono / Choke, volume, pan, glide, the pedal,
+// output, Vel → Vol and the meter. States take the rail over: the SFZ import report, the
+// memory while samples load, the source of a missing pack.
+// • S 260 × 260 — the name, the mini map, zones · layers and the RAM; a loading bar.
+//
+// Samples are referenced, never copied (see MosaicProgram). The program is edited here as a
+// MosaicProgram and committed whole (one undo step); a drag previews in the map and commits
+// on release. Brass is the parameter; teal is modulation depth (Vel → Vol, MPE).
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Shapes;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Nota.Application;
+using Avalonia.Platform.Storage;
+using Nota.Application.Mosaic;
+using Nota.Presentation;
+using Path = System.IO.Path;
+using static Nota.App.DeviceCardKit;
+
+namespace Nota.App;
+
+internal sealed class MosaicInstrumentCard : IInstrumentCard
+{
+ public bool BodyOnly => true;
+ public string Subtitle => "MULTISAMPLE";
+
+ public double WidthFor(IAudioEngine engine, int trackId) => InstrumentView.IsMini(engine, trackId) ? 260 : 700;
+
+ public Control? HeaderAccessory(DeviceCardContext ctx)
+ {
+ var e = ctx.Engine; int t = ctx.TrackId;
+ if (InstrumentView.Index(e, t) < 0) return null;
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
+ if (!InstrumentView.IsMini(e, t)) row.Children.Add(MidiCardHeader.LearnButton(ctx));
+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, () => InstrumentView.IsMini(e, t), m => InstrumentView.SetMini(e, t, m)));
+ return row;
+ }
+
+ // The header readout: what the program is and how much RAM it takes (S: the voices).
+ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)
+ {
+ int poly = 64;
+ int pc = engine.PluginParamCount(trackId, -1);
+ for (int i = 0; i < pc; i++) if (engine.PluginParamId(trackId, -1, i) == "polyphony") poly = MosaicModel.Poly(engine.PluginParamGet(trackId, -1, i));
+ if (InstrumentView.IsMini(engine, trackId)) return $"{Math.Max(0, active)}/{poly}";
+ if (!engine.TryGetMosaicStatus(trackId, out var st) || st.FilesTotal == 0) return $"{Math.Max(0, active)}/{poly}";
+ if (st.State == 1) return $"LOADING {(int)Math.Round(100.0 * st.DiskDone / Math.Max(1, st.DiskTotal))} %";
+ var ui = Ui(trackId);
+ string tag = ui.SourceTag;
+ return $"{tag} · {NotaNum.Bytes(st.RamBytes)}";
+ }
+
+ // ---- per-track UI state (survives a rebuild) --------------------------------------------
+ internal sealed class UiState
+ {
+ public int Tab, Zone = -1, Group;
+ public bool ReleaseView, ReportOpen;
+ public SfzImportReport? Report;
+ public bool ReportDismissed;
+ public string SourceTag = "FILES";
+ }
+ private static readonly Dictionary<int, UiState> States = new();
+ internal static UiState Ui(int track) => States.TryGetValue(track, out var s) ? s : States[track] = new UiState();
+ /// <summary>A fresh SFZ import on this track: the card shows its banner and report.</summary>
+ internal static void SetImportReport(int track, SfzImportReport report) { var u = Ui(track); u.Report = report; u.ReportDismissed = false; u.ReportOpen = true; }
+
+ /// <summary>Raised when the card asks for the multisample preview (files / a folder dropped on it).</summary>
+ internal static event Action<int, IReadOnlyList<string>>? CreateMultisampleRequested;
+ /// <summary>Raised when the card asks to install a registry sample pack (Settings → Downloads).</summary>
+ internal static event Action<string>? InstallPackRequested;
+
+ private const double RailW = 186, TabH = 20, StatusH = 18;
+ private static readonly string[] TabNames = { "Zones", "Sample", "Groups", "Pitch", "Env", "Filter" };
+
+ private static string SourceTagOf(MosaicProgram p) => p.SourceKind switch
+ {
+ "sfz" => p.PackId.Length > 0 ? "PACK" : "SFZ",
+ "folder" => p.PackId.Length > 0 ? "PACK" : "MULTI",
+ "factory" => "BUILT-IN",
+ "sample" => "ONE-SHOT",
+ _ => p.PackId.Length > 0 ? "PACK" : "MULTI",
+ };
+
+ public Control Build(DeviceCardContext ctx)
+ {
+ var engine = ctx.Engine;
+ int track = ctx.TrackId;
+ var ui = Ui(track);
+ int pc = engine.PluginParamCount(track, -1);
+ var idx = new Dictionary<string, int>();
+ for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;
+ int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;
+ float G(string id) => I(id) is var i and >= 0 ? engine.PluginParamGet(track, -1, i) : 0f;
+ void SetP(string id, double v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ void Begin(string id) { if (I(id) >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }
+ void End(string id) { if (I(id) >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }
+ void Write(string id, double v) { Begin(id); SetP(id, v); End(id); }
+ float Def(string id) => I(id) is var i and >= 0 ? engine.InstrumentParamDefault(track, i) : 0f;
+ int Sel(string id, int n) => MosaicModel.Index(G(id), n);
+
+ // ---- the program --------------------------------------------------------------------
+ var prog = MosaicProgram.Parse(engine.MosaicProgram(track));
+ engine.TryGetMosaicStatus(track, out var status);
+ int knownSerial = status.Serial;
+ ui.SourceTag = SourceTagOf(prog);
+ if (ui.Zone >= prog.Zones.Count) ui.Zone = -1;
+ if (ui.Zone < 0 && prog.Zones.Count > 0)
+ {
+ // The first attack zone around middle C.
+ int best = 0, bd = int.MaxValue;
+ for (int i = 0; i < prog.Zones.Count; i++)
+ {
+ var z = prog.Zones[i];
+ int d = (z.Release ? 1000 : 0) + Math.Abs(z.Root - 60) * 2 + (127 - z.VelHi) / 16;
+ if (d < bd) { bd = d; best = i; }
+ }
+ ui.Zone = best;
+ }
+ if (ui.Group >= prog.Groups.Count) ui.Group = 0;
+ bool hasRelease = prog.Zones.Any(z => z.Release);
+ if (!hasRelease) ui.ReleaseView = false;
+ MosaicZone? Zsel() => ui.Zone >= 0 && ui.Zone < prog.Zones.Count ? prog.Zones[ui.Zone] : null;
+
+ void Commit(bool rebuild = false)
+ {
+ engine.MosaicSetProgram(track, prog.Serialize());
+ if (engine.TryGetMosaicStatus(track, out var s2)) knownSerial = s2.Serial;
+ ctx.NotifyChanged();
+ if (rebuild) ctx.RequestRebuild();
+ }
+
+ var readouts = new List<Action>();
+ Action refresh = () => { };
+ void Refresh() => refresh();
+ var snap = new MosaicModel.Snapshot();
+ var scope = new float[MosaicModel.ScopeLength];
+ var samSnap = new SamplerModel.Snapshot();
+ bool mini = InstrumentView.IsMini(engine, track);
+
+ // Loading / missing.
+ bool Loading() => status.State == 1;
+ bool AllMissing() => status.State == 2 && status.FilesTotal > 0 && status.Missing == status.FilesTotal;
+ double LoadFrac() => status.DiskTotal > 0 ? Math.Clamp(status.DiskDone / (double)status.DiskTotal, 0, 1)
+ : status.FilesTotal > 0 ? status.FilesDone / (double)status.FilesTotal : 0;
+ long RamEstimate() => LoadFrac() > 0.02 ? (long)(status.RamBytes / LoadFrac()) : status.RamBytes;
+
+ static TextBlock Caps(string t, IBrush? c = null) => new()
+ {
+ Text = t.ToUpperInvariant(), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold,
+ LetterSpacing = NotaType.KnobLabelTracking, Foreground = c ?? TextTertiary, VerticalAlignment = VerticalAlignment.Center,
+ };
+ static TextBlock Mono(string t, IBrush? c = null, double fs = 8) => new()
+ {
+ Text = t, FontSize = fs, Foreground = c ?? TextSecondary, VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily,
+ };
+
+ // ---- shared builders ------------------------------------------------------------------
+ Control PKnob(string id, string label, Func<float, string> fmt, double size = NotaSize.KnobSecondary, double cellW = 52, IBrush? arc = null, string? tip = null)
+ {
+ int pi = I(id);
+ if (pi < 0) return new Panel();
+ var value = new TextBlock { Text = fmt(G(id)), Foreground = TextPrimary };
+ var knob = new Knob(G(id), 1.0) { Accent = true, ArcColor = arc, Default = Def(id), Width = size, Height = size };
+ knob.ValueChanged += v => { SetP(id, v); value.Text = fmt((float)v); Refresh(); };
+ knob.GestureBegin += () => Begin(id);
+ knob.GestureEnd += () => End(id);
+ readouts.Add(() =>
+ {
+ if (knob.Dragging) return;
+ float v = G(id);
+ if (Math.Abs(v - knob.Value) > 1e-4) knob.Value = v;
+ value.Text = fmt(v);
+ });
+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, pi), id);
+ var cell = KnobCell(label, knob, value, cellW);
+ cell.VerticalAlignment = VerticalAlignment.Center;
+ if (tip is not null) ToolTip.SetTip(cell, tip);
+ return cell;
+ }
+
+ // A knob over a zone / group value (program data): live in the map, committed on release.
+ Control VKnob(string label, Func<double> getNorm, Action<double> setNorm, Func<string> fmt, double def, IBrush? arc = null, string? tip = null, double size = NotaSize.KnobSecondary)
+ {
+ var value = new TextBlock { Text = fmt(), Foreground = TextPrimary };
+ var knob = new Knob(getNorm(), 1.0) { Accent = true, ArcColor = arc, Default = def, Width = size, Height = size };
+ knob.ValueChanged += v => { setNorm(v); value.Text = fmt(); Refresh(); };
+ knob.GestureEnd += () => Commit();
+ readouts.Add(() => { if (knob.Dragging) return; double v = getNorm(); if (Math.Abs(v - knob.Value) > 1e-4) knob.Value = v; value.Text = fmt(); });
+ var cell = KnobCell(label, knob, value, 52);
+ cell.VerticalAlignment = VerticalAlignment.Center;
+ if (tip is not null) ToolTip.SetTip(cell, tip);
+ return cell;
+ }
+
+ Border Chips(string id, string[] names, double padX = 6, double fontSize = 8)
+ {
+ int n = names.Length;
+ var seg = Segments(names, () => Sel(id, n), iv => { Write(id, iv / (double)(n - 1)); Refresh(); }, out var sync, padX: padX, fontSize: fontSize);
+ readouts.Add(sync);
+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), id);
+ return seg;
+ }
+
+ Grid Slider(string label, string id, Func<string> text, bool bipolar = false, bool modulation = false, string? tip = null)
+ {
+ int pi = I(id);
+ var row = SliderRow(label, () => G(id), v => { SetP(id, v); Refresh(); }, text, out var sync,
+ begin: pi >= 0 ? () => Begin(id) : null, end: pi >= 0 ? () => End(id) : null,
+ reset: pi >= 0 ? () => { Write(id, Def(id)); Refresh(); } : null,
+ bipolar: bipolar, labelWidth: 46, valueWidth: 40, modulation: modulation);
+ readouts.Add(sync);
+ if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), id);
+ if (tip is not null) ToolTip.SetTip(row, tip);
+ return row;
+ }
+
+ // A raised text button; a latching one turns brass-washed while on.
+ Border Button(string text, Action click, string tip, Func<bool>? on = null, Func<bool>? enabled = null, bool primary = false)
+ {
+ var tb = new TextBlock { Text = text, FontSize = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ var b = new Border
+ {
+ Height = 17, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(8, 0),
+ Child = tb, VerticalAlignment = VerticalAlignment.Center,
+ };
+ ToolTip.SetTip(b, tip);
+ void Paint()
+ {
+ bool lit = on?.Invoke() ?? false, ok = enabled?.Invoke() ?? true;
+ b.Background = primary && ok ? Brass : lit ? NotaPalette.AccentSubtle : NotaPalette.SurfaceRaised;
+ b.BorderBrush = primary && ok ? Brass : lit ? NotaPalette.BorderBrass : BorderDef;
+ tb.Foreground = !ok ? TextTertiary : primary ? OnAccent : lit ? AccentBright : NotaPalette.TextStrong;
+ tb.FontWeight = primary ? FontWeight.SemiBold : FontWeight.Normal;
+ b.Cursor = ok ? new Cursor(StandardCursorType.Hand) : Cursor.Default;
+ }
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed || !(enabled?.Invoke() ?? true)) return;
+ click(); Paint(); Refresh(); e.Handled = true;
+ };
+ readouts.Add(Paint);
+ Paint();
+ return b;
+ }
+
+ // A small number box: drag up / down (Shift fine), wheel, double-click resets.
+ Border NumBox(Func<string> text, Action<int> step, Action? reset = null, double width = 44, string? tip = null, Action? done = null)
+ {
+ var tb = Mono(text(), TextPrimary, 9);
+ tb.HorizontalAlignment = HorizontalAlignment.Center;
+ var b = new Border
+ {
+ Height = 17, MinWidth = width, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderDef,
+ Background = NotaPalette.BgSunken, Child = tb, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Padding = new Thickness(4, 0),
+ };
+ double y0 = 0, acc = 0; bool drag = false;
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2 && reset is not null) { reset(); done?.Invoke(); tb.Text = text(); Refresh(); e.Handled = true; return; }
+ drag = true; y0 = e.GetPosition(b).Y; acc = 0; e.Pointer.Capture(b); e.Handled = true;
+ };
+ b.PointerMoved += (_, e) =>
+ {
+ if (!drag) return;
+ double y = e.GetPosition(b).Y;
+ acc += (y0 - y) / (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? 12.0 : 4.0); y0 = y;
+ int n = (int)Math.Truncate(acc);
+ if (n != 0) { acc -= n; step(n); tb.Text = text(); Refresh(); }
+ };
+ b.PointerReleased += (_, e) => { if (!drag) return; drag = false; e.Pointer.Capture(null); done?.Invoke(); };
+ b.PointerWheelChanged += (_, e) => { step(e.Delta.Y > 0 ? 1 : -1); tb.Text = text(); done?.Invoke(); Refresh(); e.Handled = true; };
+ readouts.Add(() => { if (!drag) tb.Text = text(); });
+ if (tip is not null) ToolTip.SetTip(b, tip);
+ return b;
+ }
+ Control Field(string cap, Control c) => new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Children = { Caps(cap), c } };
+ Control ReadField(string cap, Func<string> text, IBrush? ink = null)
+ {
+ var t = Mono(text(), ink ?? TextPrimary, 9);
+ readouts.Add(() => t.Text = text());
+ return Field(cap, t);
+ }
+ static Grid Row(double spacing, params (Control C, string W)[] cols)
+ {
+ var g = new Grid { ColumnSpacing = spacing, VerticalAlignment = VerticalAlignment.Stretch };
+ for (int i = 0; i < cols.Length; i++)
+ {
+ g.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Parse(cols[i].W)));
+ cols[i].C.VerticalAlignment = VerticalAlignment.Center;
+ Grid.SetColumn(cols[i].C, i); g.Children.Add(cols[i].C);
+ }
+ return g;
+ }
+
+ // ---- words ------------------------------------------------------------------------------
+ string LayerOf(MosaicZone z)
+ {
+ string gname = z.Group >= 0 && z.Group < prog.Groups.Count ? prog.Groups[z.Group].Name : "";
+ int dot = gname.LastIndexOf('·');
+ return dot >= 0 ? gname[(dot + 1)..].Trim() : gname.Length > 0 ? gname : $"{z.VelLo}–{z.VelHi}";
+ }
+ int SeqLenOf(MosaicZone z) => z.Group >= 0 && z.Group < prog.Groups.Count ? prog.Groups[z.Group].SeqLen : 1;
+ string ZoneChip(MosaicZone z) => z.Release
+ ? $"{MosaicNames.NoteName(z.Root)} · release"
+ : $"{MosaicNames.NoteName(z.Root)} · {LayerOf(z)}{(SeqLenOf(z) > 1 ? $" · rr {z.Seq}/{SeqLenOf(z)}" : "")}";
+ string Keys(MosaicZone z) => z.KeyLo == z.KeyHi ? MosaicNames.NoteName(z.KeyLo) : $"{MosaicNames.NoteName(z.KeyLo)}–{MosaicNames.NoteName(z.KeyHi)}";
+ string Cents(double c) => NotaNum.Unit(c, "+0;−0;0", "c");
+ string DbS(double db) => NotaNum.Db(db, signed: true);
+ string PanS(double p) => Math.Abs(p) < 0.015 ? "C" : (p < 0 ? "L" : "R") + NotaNum.Str(Math.Abs(p) * 100, "0");
+ string DbLin(float v) => NotaNum.Db(MosaicModel.VolumeDb(v), floor: -80);
+ string St(float v) => NotaNum.Unit(MosaicModel.TransposeSt(v), "+0;−0;0", "st");
+ string GlideText(float v) { double s = MosaicModel.GlideSec(v); return s <= 0 ? NotaNum.Unit(0, "0", "ms") : NotaNum.Time(s); }
+
+ // ======================= the zone map (Zones tab, and S) =================================
+ var map = new MosaicZoneMap { Mini = mini, Interactive = !mini };
+ string EmptyText() => mini ? "Empty" : "Drop samples or a folder here · or pick a preset";
+ void SetMap() => map.Set(prog.Zones, ui.ReleaseView, ui.Zone, EmptyText());
+ SetMap();
+ map.Selected += i => { ui.Zone = i; if (i >= 0 && i < prog.Zones.Count) ui.Group = prog.Zones[i].Group; Refresh(); };
+ map.Edited += (i, klo, khi, vlo, vhi, done) =>
+ {
+ if (i < 0 || i >= prog.Zones.Count) return;
+ var z = prog.Zones[i];
+ // Every round-robin tile stacked with it moves along.
+ foreach (var o in prog.Zones)
+ if (o != z && o.Release == z.Release && o.Group == z.Group && o.KeyLo == z.KeyLo && o.KeyHi == z.KeyHi && o.VelLo == z.VelLo && o.VelHi == z.VelHi)
+ { o.KeyLo = klo; o.KeyHi = khi; o.VelLo = vlo; o.VelHi = vhi; }
+ z.KeyLo = klo; z.KeyHi = khi; z.VelLo = vlo; z.VelHi = vhi;
+ SetMap();
+ if (done) Commit();
+ Refresh();
+ };
+ map.KeyDown += k => engine.TrackNoteOn(track, k, 0.75f);
+ map.KeyUp += k => engine.TrackNoteOff(track, k);
+
+ // ---- status / meta ------------------------------------------------------------------------
+ var statusText = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = Mono("", TextSecondary, 8);
+ double esr = engine.SampleRate > 0 ? engine.SampleRate : 48000;
+ string Rate() => NotaNum.Unit(esr / 1000, "0.#", "kHz");
+ int Poly() => MosaicModel.Poly(G("polyphony"));
+
+ if (mini) return BuildMini();
+
+ // ======================= Zones tab =======================================================
+ var zoneChip = new Border
+ {
+ CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = NotaPalette.BorderBrass,
+ Background = NotaPalette.AccentSubtle, Padding = new Thickness(7, 2), VerticalAlignment = VerticalAlignment.Center,
+ Child = Mono("", AccentBright, 9),
+ };
+ readouts.Add(() => ((TextBlock)zoneChip.Child!).Text = Zsel() is { } z ? ZoneChip(z) : "no zone");
+ var zKeys = ReadField("Keys", () => Zsel() is { } z ? Keys(z) : "—");
+ var zVel = ReadField("Vel", () => Zsel() is { } z ? $"{z.VelLo}–{z.VelHi}" : "—");
+ var zXf = ReadField("Xf vel", () => Zsel() is { } z && z.XVelInHi > z.XVelInLo ? NotaNum.Str(z.XVelInHi - z.XVelInLo, "0") : "—");
+ var zFine = Field("Fine", NumBox(() => Zsel() is { } z ? Cents(z.Tune) : "—", d => { if (Zsel() is { } z) z.Tune = Math.Clamp(z.Tune + d, -100, 100); },
+ () => { if (Zsel() is { } z) z.Tune = 0; }, 40, "The zone's fine tune — drag, wheel, double-click resets", () => Commit()));
+ var zGain = Field("Gain", NumBox(() => Zsel() is { } z ? DbS(z.GainDb) : "—", d => { if (Zsel() is { } z) z.GainDb = Math.Clamp(Math.Round(z.GainDb * 10 + d) / 10.0, -48, 24); },
+ () => { if (Zsel() is { } z) z.GainDb = 0; }, 50, "The zone's level", () => Commit()));
+ var zPan = Field("Pan", NumBox(() => Zsel() is { } z ? PanS(z.Pan) : "—", d => { if (Zsel() is { } z) z.Pan = Math.Clamp(Math.Round(z.Pan * 100 + d) / 100.0, -1, 1); },
+ () => { if (Zsel() is { } z) z.Pan = 0; }, 32, "The zone's pan", () => Commit()));
+ int tab = ui.Tab;
+ Action showTab = () => { };
+ var openSample = Button("Open in Sample", () => { tab = 1; showTab(); }, "Edit this zone's start, end and loop", enabled: () => Zsel() is not null);
+ var zoneRow = Row(12, (zoneChip, "Auto"), (zKeys, "Auto"), (zVel, "Auto"), (zXf, "Auto"), (zFine, "Auto"), (zGain, "Auto"), (zPan, "Auto"), (new Panel(), "*"), (openSample, "Auto"));
+
+ // Loading: over the map, and the row says what still works.
+ var loadBar = new Border { Height = 3, CornerRadius = NotaRadius.Badge, Background = Brass, HorizontalAlignment = HorizontalAlignment.Left };
+ var loadTrack = new Border { Height = 3, CornerRadius = NotaRadius.Badge, Background = NotaPalette.BorderDefault, Child = loadBar };
+ var loadPct = Mono("", AccentBright, 9);
+ var loadLine = Mono("", TextSecondary, 8);
+ var loadHead = new DockPanel { Children = { loadPct } };
+ DockPanel.SetDock(loadPct, Dock.Right);
+ loadHead.Children.Add(new TextBlock { Text = "Loading samples", FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary });
+ var loadBox = new Border
+ {
+ Width = 250, Padding = new Thickness(10, 8), CornerRadius = NotaRadius.Tile, BorderThickness = new Thickness(1), BorderBrush = BorderDef,
+ Background = NotaPalette.SurfaceCard, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
+ Child = new StackPanel { Spacing = 5, Children = { loadHead, loadTrack, loadLine, new TextBlock { Text = "Notes are silent until loading finishes", FontSize = 7.5, Foreground = TextTertiary } } },
+ };
+ loadBox.BindResource(Border.BoxShadowProperty, "Shadow.Popover");
+ var loadScrim = new Border { Background = NotaPalette.Wash(NotaPalette.BgSunken, 0x99), IsHitTestVisible = false };
+ var loadLayer = new Panel { Children = { loadScrim, loadBox } };
+ loadTrack.SizeChanged += (_, _) => loadBar.Width = loadTrack.Bounds.Width * LoadFrac();
+ var loadRow = Row(10, (new TextBlock { Text = "Zones can already be selected and edited", FontSize = 8, Foreground = TextTertiary }, "*"),
+ (Button("Cancel", () => { prog = new MosaicProgram { Name = prog.Name }; Commit(rebuild: true); }, "Stop loading — the instrument empties (undo brings it back)"), "Auto"));
+
+ // SFZ import banner over the map.
+ var bannerText = Mono("", TextPrimary, 8);
+ var bannerDot = new Ellipse { Width = 6, Height = 6, Fill = NotaPalette.Success, VerticalAlignment = VerticalAlignment.Center };
+ var reportLink = new TextBlock { Text = "Report", FontSize = 8, Foreground = AccentBright, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };
+ var bannerClose = new Glyph(GlyphKind.Close, 7) { Foreground = TextTertiary, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };
+ Action rebuildRail = () => { };
+ reportLink.PointerPressed += (_, e) => { ui.ReportOpen = !ui.ReportOpen; rebuildRail(); e.Handled = true; };
+ var banner = new Border
+ {
+ Height = 18, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = NotaPalette.SuccessDim,
+ Background = NotaPalette.Wash(NotaPalette.Success, 0x14), Padding = new Thickness(6, 0), Margin = new Thickness(0, 0, 0, 3),
+ };
+ var bannerGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 6 };
+ bannerGrid.Children.Add(bannerDot);
+ Grid.SetColumn(bannerText, 1); bannerGrid.Children.Add(bannerText);
+ Grid.SetColumn(reportLink, 2); bannerGrid.Children.Add(reportLink);
+ Grid.SetColumn(bannerClose, 3); bannerGrid.Children.Add(bannerClose);
+ banner.Child = bannerGrid;
+ bannerClose.PointerPressed += (_, e) => { ui.ReportDismissed = true; ui.ReportOpen = false; banner.IsVisible = false; rebuildRail(); e.Handled = true; };
+ bool ShowBanner() => ui.Report is not null && !ui.ReportDismissed && prog.SourceKind == "sfz";
+ banner.IsVisible = ShowBanner();
+ if (ui.Report is { } rep0) bannerText.Text = rep0.Summary();
+
+ // A missing pack: the map gives way to what to do about it.
+ Control MissingPanel()
+ {
+ bool pack = prog.PackId.Length > 0;
+ string title = pack ? $"Pack “{(prog.PackName.Length > 0 ? prog.PackName : prog.PackId)}” is not installed" : "The samples aren't where the program says";
+ string body = pack
+ ? $"This preset uses {prog.Files.Count} samples from the pack. Zone settings are kept, no sound until installed."
+ : $"None of its {prog.Files.Count} samples were found. Zone settings are kept — point Mosaic at the folder that holds them.";
+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Center };
+ if (pack) buttons.Children.Add(Button("Install pack", () => InstallPackRequested?.Invoke(prog.PackId), "Settings → Downloads → Sample Packs", primary: true));
+ buttons.Children.Add(Button("Locate folder…", () => _ = LocateAsync(), "Pick the folder that holds the samples — Mosaic finds each file in it by its path or its name"));
+ return new Border
+ {
+ Background = NotaPalette.BgSunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(NotaRadius.ControlValue),
+ Child = new StackPanel
+ {
+ Spacing = 6, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, MaxWidth = 380,
+ Children =
+ {
+ new TextBlock { Text = title, FontSize = 11, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, TextAlignment = TextAlignment.Center },
+ new TextBlock { Text = body, FontSize = 8, Foreground = TextSecondary, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ Mono(pack ? $"{prog.PackId} · {prog.Zones.Count} zones" : MosaicPaths.FileName(prog.Files.FirstOrDefault() ?? ""), TextTertiary, 8),
+ buttons,
+ },
+ },
+ };
+ }
+
+ // Finds every sample under a folder the user picks: by its relative tail, else its name.
+ async System.Threading.Tasks.Task LocateAsync()
+ {
+ var top = TopLevel.GetTopLevel(map);
+ if (top is null) return;
+ var picked = await top.StorageProvider.OpenFolderPickerAsync(new Avalonia.Platform.Storage.FolderPickerOpenOptions { Title = "Locate the samples", AllowMultiple = false });
+ var dir = picked.FirstOrDefault()?.TryGetLocalPath();
+ if (dir is null) return;
+ var byName = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ try { foreach (var f in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)) byName.TryAdd(Path.GetFileName(f), f); } catch { }
+ int found = 0;
+ for (int i = 0; i < prog.Files.Count; i++)
+ {
+ string reference = prog.Files[i];
+ string rel = reference.Contains(':') && reference.IndexOf(':') >= 2 ? reference[(reference.IndexOf(':') + 1)..] : reference;
+ var parts = rel.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries);
+ string? hit = null;
+ for (int k = 0; k < parts.Length && hit is null; k++)
+ {
+ string cand = Path.Combine(dir, Path.Combine(parts[k..]));
+ if (File.Exists(cand)) hit = cand;
+ }
+ hit ??= byName.TryGetValue(Path.GetFileName(rel), out var n) ? n : null;
+ if (hit is not null) { prog.Files[i] = hit; found++; }
+ }
+ if (found > 0) Commit(rebuild: true);
+ }
+
+ var mapHost = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ mapHost.Children.Add(banner);
+ var mapCell = new Panel();
+ if (AllMissing() && prog.Zones.Count > 0) mapCell.Children.Add(MissingPanel());
+ else { mapCell.Children.Add(map); mapCell.Children.Add(loadLayer); }
+ Grid.SetRow(mapCell, 1); mapHost.Children.Add(mapCell);
+ var zoneRowHost = new Panel { Children = { zoneRow, loadRow } };
+
+ // ======================= Sample tab ======================================================
+ var wave = new SamplerWaveView();
+ wave.SetEmpty("Select a zone");
+ long waveSampleId = 0; int waveZone = -1; float[] raw = Array.Empty<float>(); int wch = 1; long wframes = 0; double wsr = 0;
+ void LoadWave()
+ {
+ long sid = ui.Zone >= 0 ? engine.MosaicZoneSampleId(track, ui.Zone) : 0;
+ if (sid == waveSampleId && ui.Zone == waveZone) return;
+ waveSampleId = sid; waveZone = ui.Zone;
+ raw = Array.Empty<float>(); wframes = 0;
+ if (sid != 0 && engine.TryGetSampleInfo(sid, out var si))
+ {
+ raw = engine.ReadSample(sid); wch = Math.Max(1, si.Channels); wframes = si.Frames; wsr = si.SampleRate;
+ wave.SetPeaks(SamplerModel.Peaks(raw, wch, 1200), wsr > 0 ? wframes / wsr : 0);
+ }
+ else wave.SetEmpty(Loading() ? "Loading…" : Zsel() is null ? "Select a zone" : "Sample not loaded");
+ }
+ double FrameNorm(double frames, double def) => wframes > 1 ? (frames < 0 ? def : Math.Clamp(frames / wframes, 0, 1)) : def;
+ double ToFrames(double norm) => Math.Round(Math.Clamp(norm, 0, 1) * wframes);
+ (double S, double E, double LS, double LE) ZoneWindow(MosaicZone z)
+ => (FrameNorm(z.Start, 0), FrameNorm(z.End, 1), FrameNorm(z.LoopStart, FrameNorm(z.Start, 0)), FrameNorm(z.LoopEnd, FrameNorm(z.End, 1)));
+ wave.Moved += (h, f) =>
+ {
+ if (Zsel() is not { } z || wframes <= 1) return;
+ switch (SamplerWaveView.HandleId(h))
+ {
+ case "start": z.Start = ToFrames(Math.Min(f, ZoneWindow(z).E - 0.001)); break;
+ case "end": z.End = ToFrames(Math.Max(f, ZoneWindow(z).S + 0.001)); break;
+ case "loopstart": z.LoopStart = ToFrames(f); break;
+ case "loopend": z.LoopEnd = ToFrames(f); break;
+ }
+ Refresh();
+ };
+ wave.DragEnd += _ => Commit();
+ wave.ResetHandle += h =>
+ {
+ if (Zsel() is not { } z) return;
+ switch (SamplerWaveView.HandleId(h)) { case "start": z.Start = 0; break; case "end": z.End = -1; break; case "loopstart": z.LoopStart = -1; break; case "loopend": z.LoopEnd = -1; break; }
+ Commit(); Refresh();
+ };
+ readouts.Add(() =>
+ {
+ LoadWave();
+ if (Zsel() is { } z)
+ {
+ var (s, e, ls, le) = ZoneWindow(z);
+ double dur = wsr > 0 ? wframes / wsr : 0;
+ wave.Set(s, e, ls, le, z.LoopMode, z.Crossfade,
+ wframes > 1 ? $"{prog.FileName(z.File)} · {NotaNum.Unit(wsr / 1000, "0.#", "k")} · {NotaNum.Unit(dur, "0.00", "s")} · root {MosaicNames.NoteName(z.Root)}" : prog.FileName(z.File),
+ z.LoopMode == 0 ? "no loop" : $"{MosaicModel.LoopNames[z.LoopMode].ToLowerInvariant()} {NotaNum.Str(ls * dur, "0.00")} – {NotaNum.Unit(le * dur, "0.00", "s")}");
+ }
+ });
+ var loopSeg = Segments(MosaicModel.LoopNames, () => Zsel()?.LoopMode ?? 0, iv => { if (Zsel() is { } z) { z.LoopMode = iv; Commit(); } Refresh(); }, out var loopSync, padX: 7, fontSize: 8);
+ readouts.Add(loopSync);
+ ToolTip.SetTip(loopSeg, "Off plays once · Fwd loops · Ping bounces — this zone only");
+ var xfKnob = VKnob("Crossfade", () => Math.Sqrt(Math.Clamp((Zsel()?.Crossfade ?? 0) / 0.5, 0, 1)), v => { if (Zsel() is { } z) z.Crossfade = v * v * 0.5; },
+ () => NotaNum.Time(Zsel()?.Crossfade ?? 0), 0, tip: "Blends the loop's end into its start (forward loops)");
+ var zGainKnob = VKnob("Gain", () => ((Zsel()?.GainDb ?? 0) + 24) / 48.0, v => { if (Zsel() is { } z) z.GainDb = Math.Round((v * 48 - 24) * 10) / 10; },
+ () => DbS(Zsel()?.GainDb ?? 0), 0.5, tip: "This zone's level");
+ void SnapAll()
+ {
+ if (Zsel() is not { } z || wframes <= 1) return;
+ var (s, e, ls, le) = ZoneWindow(z);
+ z.Start = ToFrames(SamplerModel.SnapZero(raw, wch, wframes, s));
+ if (z.End >= 0) z.End = ToFrames(SamplerModel.SnapZero(raw, wch, wframes, e));
+ if (z.LoopStart >= 0) z.LoopStart = ToFrames(SamplerModel.SnapZero(raw, wch, wframes, ls));
+ if (z.LoopEnd >= 0) z.LoopEnd = ToFrames(SamplerModel.SnapZero(raw, wch, wframes, le));
+ Commit();
+ }
+ void Trim()
+ {
+ if (Zsel() is not { } z || wframes <= 1 || SamplerModel.TrimSilence(raw, wch, wframes) is not { } t) return;
+ z.Start = ToFrames(t.Start); z.End = ToFrames(t.End);
+ Commit();
+ }
+ var snapBtn = Button("Snap to zero", SnapAll, "Move Start, End and the loop to the nearest zero crossing", enabled: () => wframes > 1);
+ var trimBtn = Button("Trim silence", Trim, "Move Start and End to where the sound begins and fades out (−48 dB)", enabled: () => wframes > 1);
+ snapBtn.HorizontalAlignment = HorizontalAlignment.Stretch; trimBtn.HorizontalAlignment = HorizontalAlignment.Stretch;
+ var sampleChip = Mono("", AccentBright, 9);
+ readouts.Add(() => sampleChip.Text = Zsel() is { } z ? ZoneChip(z) : "");
+ var sampleRow = Row(14, (Field("Zone", sampleChip), "Auto"), (Field("Loop", loopSeg), "Auto"), (xfKnob, "Auto"), (zGainKnob, "Auto"), (new Panel(), "*"),
+ (new StackPanel { Spacing = 3, Children = { snapBtn, trimBtn } }, "Auto"));
+
+ // ======================= Groups tab ======================================================
+ var groupList = new StackPanel { Spacing = 1 };
+ Action rebuildGroups = () => { };
+ string RrModeWord(int m) => MosaicProgram.RrNames[Math.Clamp(m, 0, 2)] is var w && m == 2 ? "Random no repeat" : MosaicProgram.RrNames[Math.Clamp(m, 0, 2)];
+ int ZonesIn(int g) => prog.Zones.Count(z => z.Group == g);
+ bool IsReleaseGroup(int g) => prog.Zones.Any(z => z.Group == g) && prog.Zones.Where(z => z.Group == g).All(z => z.Release);
+ string ExclOf(int g)
+ {
+ var zs = prog.Zones.Where(z => z.Group == g).ToList();
+ if (zs.Count == 0 || zs.All(z => z.Excl == 0 && z.OffBy == 0)) return "—";
+ var e = zs.First(z => z.Excl != 0 || z.OffBy != 0);
+ return $"{(e.Excl != 0 ? e.Excl.ToString(NotaNum.Culture) : "—")} / {(e.OffBy != 0 ? e.OffBy.ToString(NotaNum.Culture) : "—")}";
+ }
+ Grid GroupRowGrid() => new() { ColumnDefinitions = new ColumnDefinitions("*,44,52,40,22,112,36"), ColumnSpacing = 4, Height = 17 };
+ TextBlock Cell(Grid g, int col, string text, IBrush? ink = null, bool mono = true, TextAlignment align = TextAlignment.Right)
+ {
+ var tb = mono ? Mono(text, ink ?? TextPrimary, 8) : new TextBlock { Text = text, FontSize = 8, Foreground = ink ?? TextPrimary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ tb.TextAlignment = align;
+ Grid.SetColumn(tb, col); g.Children.Add(tb);
+ return tb;
+ }
+ var groupHead = GroupRowGrid();
+ foreach (var (c, t, a) in new[] { (0, "GROUP", TextAlignment.Left), (1, "ZONES", TextAlignment.Right), (2, "GAIN", TextAlignment.Right), (3, "TUNE", TextAlignment.Right), (4, "RR", TextAlignment.Right), (5, "RR MODE", TextAlignment.Left), (6, "EXCL", TextAlignment.Right) })
+ {
+ var cap = Caps(t); cap.TextAlignment = a; cap.HorizontalAlignment = a == TextAlignment.Left ? HorizontalAlignment.Left : HorizontalAlignment.Right;
+ Grid.SetColumn(cap, c); groupHead.Children.Add(cap);
+ }
+ rebuildGroups = () =>
+ {
+ groupList.Children.Clear();
+ for (int g = 0; g < prog.Groups.Count; g++)
+ {
+ int gi = g;
+ var gr = prog.Groups[g];
+ bool sel = g == ui.Group;
+ var row = GroupRowGrid();
+ var name = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center };
+ name.Children.Add(new TextBlock { Text = gr.Name.Length > 0 ? gr.Name : $"Group {g + 1}", FontSize = 8.5, FontWeight = sel ? FontWeight.SemiBold : FontWeight.Normal, Foreground = sel ? AccentBright : TextPrimary, VerticalAlignment = VerticalAlignment.Center });
+ if (IsReleaseGroup(g)) name.Children.Add(new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(3, 0), Child = Mono("TRIG REL", TextTertiary, 7) });
+ Grid.SetColumn(name, 0); row.Children.Add(name);
+ Cell(row, 1, ZonesIn(g).ToString(NotaNum.Culture));
+ Cell(row, 2, DbS(gr.GainDb));
+ Cell(row, 3, Cents(gr.Tune), Math.Abs(gr.Tune) > 0.01 ? NotaPalette.TealBright : NotaPalette.Teal);
+ Cell(row, 4, gr.SeqLen.ToString(NotaNum.Culture));
+ if (sel && gr.SeqLen > 1)
+ {
+ var seg = Segments(new[] { "Seq", "Rnd", "Rnd≠" }, () => gr.RrMode, iv => { gr.RrMode = iv; Commit(); rebuildGroups(); rebuildRail(); }, out _, padX: 4, fontSize: 7);
+ seg.HorizontalAlignment = HorizontalAlignment.Left;
+ Grid.SetColumn(seg, 5); row.Children.Add(seg);
+ }
+ else Cell(row, 5, gr.SeqLen > 1 ? RrModeWord(gr.RrMode) : "—", gr.SeqLen > 1 ? TextPrimary : TextTertiary, align: TextAlignment.Left);
+ Cell(row, 6, ExclOf(g), TextTertiary);
+ var host = new Border
+ {
+ Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand),
+ Background = sel ? NotaPalette.AccentSubtle : g % 2 == 0 ? NotaPalette.Wash(NotaPalette.SurfaceRaised, 0x80) : Brushes.Transparent,
+ BorderBrush = sel ? NotaPalette.BorderBrass : Brushes.Transparent, Child = row,
+ };
+ host.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(host).Properties.IsLeftButtonPressed) return;
+ ui.Group = gi; rebuildGroups(); rebuildRail(); Refresh(); e.Handled = true;
+ };
+ groupList.Children.Add(host);
+ }
+ };
+ rebuildGroups();
+ var groupScroll = new ScrollViewer { Content = groupList, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto };
+ var groupTable = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 2 };
+ groupHead.Margin = new Thickness(7, 0);
+ groupTable.Children.Add(groupHead);
+ Grid.SetRow(groupScroll, 1); groupTable.Children.Add(groupScroll);
+
+ // Release triggers · their level · length → level · the velocity curve · + Group.
+ var relSwitch = Switch("", () => G("relon") >= 0.5f, () => Write("relon", G("relon") >= 0.5f ? 0 : 1), out var relSync, liveLabel: () => G("relon") >= 0.5f ? "on" : "off");
+ readouts.Add(relSync);
+ if (I("relon") is var rli and >= 0) MidiLearn.Bind(relSwitch, MidiTarget.PluginParam(track, -1, rli), "Release Triggers");
+ var relVolKnob = PKnob("relvol", "Rel vol", v => NotaNum.Db(MosaicModel.RelVolDb(v), signed: true), NotaSize.KnobMain, 52, tip: "The release samples' level");
+ var lenCurve = new MosaicCurveView
+ {
+ Width = 120, Height = 34,
+ Curve = x => 0.85 * Math.Pow(10, MosaicModel.RelLenDb(G("rellen")) * Math.Min(1, x * 2) / 20.0),
+ Get = () => G("rellen"), SetValue = v => { SetP("rellen", v); Refresh(); }, Begin = () => Begin("rellen"), End = () => End("rellen"),
+ Default = Def("rellen"), UpIsMore = false, Node = 0.5,
+ };
+ ToolTip.SetTip(lenCurve, "How much quieter a release sample gets the longer the key was held — drag up / down");
+ var lenWord = Mono("", TextSecondary, 7.5);
+ readouts.Add(() => { lenWord.Text = $"{NotaNum.Db(MosaicModel.RelLenDb(G("rellen")), signed: true)} after 2 s hold"; lenCurve.InvalidateVisual(); });
+ var velCurve = new MosaicCurveView
+ {
+ Width = 64, Height = 34,
+ Curve = x => MosaicModel.VelCurveAt(x, G("velcurve")),
+ Get = () => G("velcurve"), SetValue = v => { SetP("velcurve", v); Refresh(); }, Begin = () => Begin("velcurve"), End = () => End("velcurve"),
+ Default = Def("velcurve"), UpIsMore = false,
+ };
+ ToolTip.SetTip(velCurve, "Velocity → level: drag up for soft (quiet notes louder), down for hard");
+ var velWord = Mono("", TextSecondary, 7.5);
+ string VelCurveWord() { int c = MosaicModel.VelCurve(G("velcurve")); return c == 0 ? "linear" : c < 0 ? $"soft +{-c}" : $"hard +{c}"; }
+ readouts.Add(() => { velWord.Text = VelCurveWord(); velCurve.InvalidateVisual(); });
+ var addGroup = Button("+ Group", () =>
+ {
+ prog.Groups.Add(new MosaicGroup { Name = $"Group {prog.Groups.Count + 1}" });
+ ui.Group = prog.Groups.Count - 1;
+ Commit(); rebuildGroups(); rebuildRail();
+ }, "A new, empty layer — move zones into it from the rail");
+ var groupBottom = Row(18,
+ (new StackPanel { Spacing = 4, Children = { Caps("Release triggers"), relSwitch } }, "Auto"),
+ (relVolKnob, "Auto"),
+ (new StackPanel { Spacing = 2, Children = { Caps("Length → level"), lenCurve, lenWord } }, "Auto"),
+ (new StackPanel { Spacing = 2, Children = { Caps("Vel curve"), velCurve, velWord } }, "Auto"),
+ (new Panel(), "*"), (addGroup, "Auto"));
+
+ // ======================= Pitch tab =======================================================
+ var keysView = new SamplerKeysView();
+ ToolTip.SetTip(keysView, "Click a key to make it the selected zone's root");
+ keysView.RootPicked += k => { if (Zsel() is { } z) { z.Root = k; Commit(); SetMap(); } Refresh(); };
+ readouts.Add(() => keysView.Set(Zsel()?.Root ?? 60, -1, snap.Live ? snap.Note : -1, G("pitchtrack"), Zsel() is { } z ? ZoneChip(z) : ""));
+ var rootBox = Field("Root", NumBox(() => Zsel() is { } z ? MosaicNames.NoteName(z.Root) : "—", d => { if (Zsel() is { } z) z.Root = Math.Clamp(z.Root + d, 0, 127); },
+ null, 40, "The zone's root — drag or scroll", () => { Commit(); SetMap(); }));
+ int Detected() => Zsel() is { } z ? SamplerModel.DetectRoot(prog.FileName(z.File)) : -1;
+ var detectBtn = Button("Detect from file name", () => { if (Zsel() is { } z && Detected() >= 0) { z.Root = Detected(); Commit(); SetMap(); } },
+ "Make the note in the zone's file name its root", on: () => Zsel() is { } z && Detected() == z.Root, enabled: () => Detected() >= 0);
+ var fineKnob = VKnob("Fine", () => ((Zsel()?.Tune ?? 0) + 100) / 200.0, v => { if (Zsel() is { } z) z.Tune = Math.Round(v * 200 - 100); }, () => Cents(Zsel()?.Tune ?? 0), 0.5, Teal, "The zone's fine tune, ±100 cents");
+ var pitchRow = Row(12,
+ (PKnob("transpose", "Transpose", St, tip: "Shift every note, ±24 semitones"), "Auto"),
+ (PKnob("detune", "Detune", v => Cents(MosaicModel.DetuneCents(v)), arc: Teal, tip: "Fine tune of the whole instrument, ±50 cents"), "Auto"),
+ (PKnob("pitchtrack", "Keytrack", v => NotaNum.Pct(v), tip: "How far the key moves the pitch — 100 % chromatic, 0 % every key plays the root"), "Auto"),
+ (rootBox, "Auto"), (fineKnob, "Auto"),
+ (PKnob("bendrange", "Bend", v => NotaNum.Unit(MosaicModel.BendSemis(v), "0", "st"), arc: Teal, tip: "The pitch wheel's range (MPE bends are per note)"), "Auto"),
+ (new Panel(), "*"), (detectBtn, "Auto"));
+
+ // ======================= Env tab =========================================================
+ var env = new SamplerEnvView();
+ ToolTip.SetTip(env, "Drag the nodes: attack, decay and sustain (up / down), release · Shift for fine steps · double-click resets");
+ env.DragBegin += Begin;
+ env.DragEnd += End;
+ env.Changed += (id, v) => { SetP(id, v); Refresh(); };
+ env.Reset += id => { Write(id, Def(id)); Refresh(); };
+ string EnvTl() => $"{NotaNum.Time(MosaicModel.AttackSec(G("attack")))} · {NotaNum.Time(MosaicModel.DecaySec(G("decay")))} · {DbLin(G("sustain"))} · {NotaNum.Time(MosaicModel.ReleaseSec(G("release")))}";
+ readouts.Add(() => env.Set(G("attack"), G("decay"), G("sustain"), G("release"), samSnap, EnvTl(), ""));
+ var envRow = Row(12,
+ (PKnob("attack", "Attack", v => NotaNum.Time(MosaicModel.AttackSec(v))), "Auto"),
+ (PKnob("decay", "Decay", v => NotaNum.Time(MosaicModel.DecaySec(v))), "Auto"),
+ (PKnob("sustain", "Sustain", DbLin, NotaSize.KnobMain, 56), "Auto"),
+ (PKnob("release", "Release", v => NotaNum.Time(MosaicModel.ReleaseSec(v))), "Auto"),
+ (new Panel(), "*"),
+ (PKnob("velcurve", "Vel curve", v => { int c = MosaicModel.VelCurve(v); return c == 0 ? "linear" : c < 0 ? $"soft {-c}" : $"hard {c}"; }, arc: Teal, tip: "Velocity → level curve"), "Auto"),
+ (PKnob("mpepressure", "Pressure", v => NotaNum.Pct(v), arc: Teal, tip: "MPE pressure (aftertouch) → level"), "Auto"));
+
+ // ======================= Filter tab ======================================================
+ var filt = new SamplerFilterView();
+ ToolTip.SetTip(filt, "Drag: left / right for the cutoff, up / down for the resonance · Shift for fine steps · double-click resets");
+ filt.DragBegin += () => { Begin("cutoff"); Begin("resonance"); };
+ filt.DragEnd += () => { End("cutoff"); End("resonance"); };
+ filt.Changed += (id, v) => { SetP(id, v); Refresh(); };
+ filt.Reset += () => { Write("cutoff", Def("cutoff")); Write("resonance", Def("resonance")); Refresh(); };
+ string FiltTl()
+ {
+ int t = Sel("filtertype", 4);
+ if (t == 0) return "off · the samples pass untouched";
+ return $"{MosaicModel.FilterNames[t]} 12 dB/oct · {NotaNum.Hz(MosaicModel.CutoffHz(G("cutoff")))} · reso {NotaNum.Pct(G("resonance"))}";
+ }
+ readouts.Add(() => filt.Set(Sel("filtertype", 4), G("cutoff"), G("resonance"), snap.Live ? snap.CutoffHz : -1, FiltTl()));
+ var envBtn = Button("Env → Cutoff", () => Write("envcutoff", G("envcutoff") >= 0.5f ? 0 : 1), "Let the amp envelope open (or close) the filter", on: () => G("envcutoff") >= 0.5f);
+ var filterRow = Row(10,
+ (Field("Type", Chips("filtertype", MosaicModel.FilterNames, padX: 6)), "Auto"),
+ (PKnob("cutoff", "Cutoff", v => NotaNum.Hz(MosaicModel.CutoffHz(v)), NotaSize.KnobMain, 56), "Auto"),
+ (PKnob("resonance", "Reso", v => NotaNum.Pct(v)), "Auto"),
+ (PKnob("keytrack", "Keytrack", v => NotaNum.Pct(v), arc: Teal, tip: "The cutoff follows the key"), "Auto"),
+ (new Panel(), "*"), (envBtn, "Auto"),
+ (PKnob("envamount", "Env", v => NotaNum.Unit(MosaicModel.EnvOctaves(v), "+0.0;−0.0;0.0", "oct"), arc: Teal), "Auto"),
+ (PKnob("mpeslide", "Slide", v => NotaNum.Pct(v), arc: Teal, tip: "MPE slide (CC74) → cutoff"), "Auto"));
+
+ // ======================= the tab panel ===================================================
+ const double RowH = 62;
+ Control Page(Control view, Control row, double rowH = RowH)
+ {
+ var rowHost = new Border { Height = rowH, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 3, 0, 0), Child = row };
+ var page = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 4, Margin = new Thickness(7, 5, 7, 4) };
+ page.Children.Add(view);
+ Grid.SetRow(rowHost, 1); page.Children.Add(rowHost);
+ return page;
+ }
+ var pages = new Control[]
+ {
+ Page(mapHost, zoneRowHost, 34),
+ Page(wave, sampleRow),
+ Page(groupTable, groupBottom, 66),
+ Page(keysView, pitchRow),
+ Page(env, envRow),
+ Page(filt, filterRow),
+ };
+ var tabCells = new Border[TabNames.Length];
+ var tabTexts = new TextBlock[TabNames.Length];
+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < TabNames.Length; i++)
+ {
+ int iv = i;
+ var tb = new TextBlock { Text = TabNames[i], FontSize = NotaType.DeviceSection, VerticalAlignment = VerticalAlignment.Center };
+ var cell = new Border { Padding = new Thickness(7, 0), BorderThickness = new Thickness(0, 0, 0, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
+ cell.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(cell).Properties.IsLeftButtonPressed) return;
+ tab = iv; showTab(); e.Handled = true;
+ };
+ tabCells[i] = cell; tabTexts[i] = tb; tabRow.Children.Add(cell);
+ }
+ // The strip's right side: Attack / Release + the count (Zones), the articulation (SFZ), a hint.
+ var arSeg = Segments(new[] { "Attack", "Release" }, () => ui.ReleaseView ? 1 : 0, iv => { ui.ReleaseView = iv == 1; SetMap(); Refresh(); }, out var arSync, padX: 5, fontSize: 7);
+ readouts.Add(arSync);
+ arSeg.IsVisible = hasRelease;
+ var countText = Mono("", TextTertiary, 7);
+ readouts.Add(() =>
+ {
+ int n = prog.Zones.Count(z => z.Release == ui.ReleaseView);
+ int rr = prog.MaxRoundRobin;
+ countText.Text = tab switch
+ {
+ 0 => $"{n} zones{(rr > 1 && !ui.ReleaseView ? $" · rr {rr}" : "")}",
+ 2 => "gain · tune · rr · exclusive",
+ 3 => "transpose · root · fine · bend",
+ 4 => "a · d · s · r · curve",
+ 5 => "type · cutoff · reso · keytrack",
+ _ => "start · end · loop",
+ };
+ });
+ var articulation = ArticulationPicker();
+ var stripRight = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 7, 0) };
+ if (articulation is not null) stripRight.Children.Add(articulation);
+ stripRight.Children.Add(arSeg);
+ stripRight.Children.Add(countText);
+ var tabStrip = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ tabStrip.Children.Add(tabRow);
+ Grid.SetColumn(stripRight, 1); tabStrip.Children.Add(stripRight);
+ var tabHost = new Panel();
+ foreach (var p in pages) tabHost.Children.Add(p);
+ var dropLayer = DropOverlay();
+ tabHost.Children.Add(dropLayer);
+ var tabGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ tabGrid.Children.Add(HeaderStrip(tabStrip));
+ Grid.SetRow(tabHost, 1); tabGrid.Children.Add(tabHost);
+ var tabPanel = SectionBox(tabGrid);
+
+ // SFZ: pick the articulation (a controller's value the zones were imported with).
+ Control? ArticulationPicker()
+ {
+ if (prog.SourceKind != "sfz" || prog.Ccs.Count == 0) return null;
+ string? sfzPath = App.Services?.GetService(typeof(IMosaicPacks)) is IMosaicPacks packs ? packs.Resolve(prog.SourceRef) : prog.SourceRef;
+ if (sfzPath is null || !File.Exists(sfzPath)) return null;
+ var ranges = SfzImporter.CcRanges(sfzPath);
+ var choices = new List<(int Cc, int Value, string Label)>();
+ foreach (var (cc, list) in ranges)
+ foreach (var (lo, hi, lab) in list) choices.Add((cc, lo, lab.Length > 0 ? lab : $"cc{cc} {lo}–{hi}"));
+ if (choices.Count < 2) return null;
+ int Current() => choices.FindIndex(c => prog.Ccs.TryGetValue(c.Cc, out var v) && ranges[c.Cc].Any(r => r.Lo == c.Value && v >= r.Lo && v <= r.Hi));
+ var artLabel = new TextBlock { FontSize = 8, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center };
+ var sub = Mono("", TextTertiary, 7);
+ void Paint() { int c = Current(); artLabel.Text = c >= 0 ? choices[c].Label : "—"; sub.Text = c >= 0 ? $"cc{choices[c].Cc}={choices[c].Value}" : ""; }
+ Paint();
+ var box = new Border
+ {
+ Height = 15, Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderDef,
+ Background = NotaPalette.BgSunken, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, Children = { artLabel, sub, new Glyph(GlyphKind.ChevronDown, 6) { Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center } } },
+ };
+ ToolTip.SetTip(box, "The articulation — the SFZ's controller value its zones were chosen by");
+ box.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;
+ var f = new MenuFlyout();
+ for (int i = 0; i < choices.Count; i++)
+ {
+ var c = choices[i];
+ var mi = new MenuItem { Header = $"{c.Label} · cc{c.Cc}={c.Value}", ToggleType = MenuItemToggleType.Radio, IsChecked = i == Current() };
+ mi.Click += (_, _) =>
+ {
+ var over = new Dictionary<int, int>(prog.Ccs) { [c.Cc] = c.Value };
+ var packs = App.Services?.GetService(typeof(IMosaicPacks)) as IMosaicPacks;
+ var res = SfzImporter.Import(sfzPath, over, packs is null ? null : packs.ToRef);
+ res.Program.Name = prog.Name; res.Program.SourceRef = prog.SourceRef; res.Program.PackId = prog.PackId; res.Program.PackName = prog.PackName;
+ prog = res.Program;
+ SetImportReport(track, res.Report);
+ Commit(rebuild: true);
+ };
+ f.Items.Add(mi);
+ }
+ f.ShowAt(box);
+ e.Handled = true;
+ };
+ return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Caps("Artic"), box } };
+ }
+
+ // ======================= the rail ========================================================
+ var railHost = new ContentControl();
+ var rail = SectionBox(railHost);
+ rail.Width = RailW;
+
+ Control RailHead(string title, Control? right = null, string? sub = null)
+ {
+ var head = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*"), Margin = new Thickness(8, 0) };
+ var cap = Caps(title); cap.LetterSpacing = NotaType.SectionLabelTracking;
+ head.Children.Add(cap);
+ Control? r = right ?? (sub is null ? null : Mono(sub, TextTertiary, 7));
+ if (r is not null) { r.HorizontalAlignment = HorizontalAlignment.Right; r.VerticalAlignment = VerticalAlignment.Center; Grid.SetColumn(r, 1); head.Children.Add(r); }
+ return HeaderStrip(head);
+ }
+ Control RailBody(Control head, Control body)
+ {
+ var g = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ g.Children.Add(head);
+ body.Margin = new Thickness(8, 6, 8, 5);
+ Grid.SetRow(body, 1); g.Children.Add(body);
+ return g;
+ }
+ Control KV(string k, Func<string> v, IBrush? ink = null)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 14 };
+ g.Children.Add(Mono(k, TextSecondary, 8));
+ var val = Mono(v(), ink ?? TextPrimary, 8);
+ readouts.Add(() => val.Text = v());
+ Grid.SetColumn(val, 1); g.Children.Add(val);
+ return g;
+ }
+ static Control Rule() => new Border { Height = 1, Background = NotaPalette.GraphBorder, Margin = new Thickness(0, 3) };
+
+ // The voice-mode strip: Poly N ▾ (its popover) · Mono · Choke.
+ Control VoiceSeg()
+ {
+ var cells = new Border[3]; var texts = new TextBlock[3];
+ Glyph? chevron = null;
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };
+ for (int i = 0; i < 3; i++)
+ {
+ int iv = i;
+ var tb = new TextBlock { FontSize = 7.5, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ Control content = tb;
+ if (i == 0) // Poly opens its popover: a chevron says so
+ {
+ var chev = new Glyph(GlyphKind.ChevronDown, 5) { VerticalAlignment = VerticalAlignment.Center };
+ chevron = chev;
+ content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Children = { tb, chev } };
+ }
+ var c = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(5, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = content };
+ c.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(c).Properties.IsLeftButtonPressed) return;
+ if (iv == 0 && Sel("voicemode", 3) == 0) PolyPopover().ShowAt(c);
+ else Write("voicemode", iv / 2.0);
+ Refresh(); e.Handled = true;
+ };
+ cells[i] = c; texts[i] = tb; row.Children.Add(c);
+ }
+ readouts.Add(() =>
+ {
+ int cur = Sel("voicemode", 3);
+ for (int i = 0; i < 3; i++)
+ {
+ bool on = i == cur;
+ cells[i].Background = on ? Brass : Brushes.Transparent;
+ texts[i].Foreground = on ? OnAccent : TextTertiary;
+ texts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ texts[i].Text = i == 0 ? $"Poly {Poly()}" : MosaicModel.VoiceNames[i];
+ }
+ if (chevron is not null) chevron.Foreground = cur == 0 ? OnAccent : TextTertiary;
+ });
+ if (I("voicemode") is var vmi and >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, vmi), "voicemode");
+ ToolTip.SetTip(row, "Poly: chords (click again for the voice settings) · Mono: one at a time, legato with Glide · Choke: a new note cuts the ringing ones");
+ var host = new Border
+ {
+ Background = NotaPalette.BgSunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control,
+ Padding = new Thickness(1), Child = row, VerticalAlignment = VerticalAlignment.Center,
+ };
+ return host;
+ }
+
+ // The Poly popover: polyphony, the voices now, the stealing order, per key, old fade.
+ Flyout PolyPopover()
+ {
+ var polySeg = Segments(MosaicModel.PolyCounts.Select(n => n.ToString(NotaNum.Culture)).ToArray(), () => Sel("polyphony", 4),
+ iv => { Write("polyphony", iv / 3.0); Refresh(); }, out var ps, fill: true, padX: 4, fontSize: 9);
+ var busyBar = new Border { Height = 3, Background = Brass, HorizontalAlignment = HorizontalAlignment.Left, CornerRadius = NotaRadius.Badge };
+ var busyTrack = new Border { Height = 3, Background = NotaPalette.BorderDefault, CornerRadius = NotaRadius.Badge, Child = busyBar };
+ var busyText = Mono("", TextSecondary, 8);
+ void PaintBusy()
+ {
+ ps();
+ busyBar.Width = busyTrack.Bounds.Width * Math.Clamp(snap.Voices / (double)Math.Max(1, Poly()), 0, 1);
+ busyText.Text = $"{snap.Held} busy · {snap.PedalHeld} on pedal · {snap.Release} release";
+ }
+ var order = new StackPanel { Spacing = 2 };
+ for (int i = 0; i < MosaicModel.StealOrder.Length; i++)
+ order.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { Mono((i + 1).ToString(NotaNum.Culture), AccentBright, 8), new TextBlock { Text = MosaicModel.StealOrder[i], FontSize = 8.5, Foreground = TextPrimary } } });
+ var perKey = NumBox(() => MosaicModel.PerKey(G("perkey")).ToString(NotaNum.Culture), d => SetP("perkey", (MosaicModel.PerKey(G("perkey")) - 1 + d) / 3.0),
+ () => SetP("perkey", Def("perkey")), 30, "How many strikes of one key may ring together");
+ var fade = NumBox(() => NotaNum.Unit(MosaicModel.OldFadeMs(G("oldfade")), "0", "ms"), d => SetP("oldfade", MosaicModel.OldFadeNorm(MosaicModel.OldFadeMs(G("oldfade")) + d)),
+ () => SetP("oldfade", Def("oldfade")), 44, "How fast a stolen or superseded voice fades");
+ var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ bottom.Children.Add(new StackPanel { Spacing = 3, Children = { Caps("Per key"), perKey } });
+ var fadeCol = new StackPanel { Spacing = 3, HorizontalAlignment = HorizontalAlignment.Right, Children = { Caps("Old voice fade"), fade } };
+ Grid.SetColumn(fadeCol, 1); bottom.Children.Add(fadeCol);
+ var panel = new StackPanel
+ {
+ Width = 196, Spacing = 6, Margin = new Thickness(4),
+ Children = { Caps("Polyphony"), polySeg, busyTrack, busyText, Rule(), Caps("Voice stealing · order"), order, Rule(), bottom },
+ };
+ var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(80) };
+ timer.Tick += (_, _) => PaintBusy();
+ var fly = new Flyout { Content = panel, Placement = PlacementMode.BottomEdgeAlignedRight };
+ fly.Opened += (_, _) => { PaintBusy(); timer.Start(); };
+ fly.Closed += (_, _) => timer.Stop();
+ return fly;
+ }
+
+ Control VoicesRail()
+ {
+ var sliders = new StackPanel
+ {
+ Spacing = 6,
+ Children =
+ {
+ Slider("Volume", "volume", () => DbLin(G("volume"))),
+ Slider("Pan", "pan", () => PanS(G("pan") * 2 - 1), bipolar: true),
+ Slider("Glide", "glide", () => GlideText(G("glide")), tip: "Slide from the last note — in Mono, legato"),
+ },
+ };
+ // The pedal: on / off (CC64 heard), lit while it is down.
+ var pedalDot = new Ellipse { Width = 6, Height = 6, VerticalAlignment = VerticalAlignment.Center };
+ var pedalTxt = Mono("CC64", TextTertiary, 8);
+ var pedalPill = new Border
+ {
+ CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(5, 1), Cursor = new Cursor(StandardCursorType.Hand),
+ Background = Brushes.Transparent, Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { pedalDot, pedalTxt } },
+ };
+ pedalPill.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(pedalPill).Properties.IsLeftButtonPressed) return; Write("pedal", G("pedal") >= 0.5f ? 0 : 1); Refresh(); e.Handled = true; };
+ if (I("pedal") is var pdi and >= 0) MidiLearn.Bind(pedalPill, MidiTarget.PluginParam(track, -1, pdi), "Voice Pedal");
+ ToolTip.SetTip(pedalPill, "The sustain pedal: a keyboard's CC64 holds released keys — click to stop listening to it");
+ var voicesTxt = Mono("", TextPrimary, 9);
+ readouts.Add(() =>
+ {
+ bool on = G("pedal") >= 0.5f, down = on && snap.Pedal;
+ pedalDot.Fill = down ? Success : on ? Brass : NotaPalette.BorderStrong;
+ pedalPill.BorderBrush = down ? Success : on ? NotaPalette.BorderBrass : BorderDef;
+ pedalTxt.Foreground = on ? TextPrimary : TextTertiary;
+ voicesTxt.Text = $"{snap.Voices} / {Poly()}";
+ });
+ var pedalRow = new Grid { ColumnDefinitions = new ColumnDefinitions("50,Auto,*"), ColumnSpacing = 4 };
+ var pl = new TextBlock { Text = "PEDAL", FontSize = NotaType.RowLabel, FontWeight = FontWeight.Bold, LetterSpacing = NotaType.RowLabelTracking, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ pedalRow.Children.Add(pl);
+ Grid.SetColumn(pedalPill, 1); pedalRow.Children.Add(pedalPill);
+ voicesTxt.HorizontalAlignment = HorizontalAlignment.Right;
+ Grid.SetColumn(voicesTxt, 2); pedalRow.Children.Add(voicesTxt);
+ sliders.Children.Add(pedalRow);
+
+ var outKnob = PKnob("output", "Output", v => NotaNum.Pct(v), NotaSize.KnobMain, 50, tip: "The level after everything");
+ var velKnob = PKnob("velamount", "Vel → Vol", v => NotaNum.Pct(v), cellW: 50, arc: Teal, tip: "How much velocity sets the level");
+ var meter = new MeterBar { VerticalAlignment = VerticalAlignment.Stretch, Width = MeterScale.StereoWidth };
+ ctx.AddDeviceRefresher(() => { if (engine.TryGetTrackMeter(track, out var m)) meter.Push(m); });
+ var outRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 4 };
+ outRow.Children.Add(outKnob);
+ Grid.SetColumn(velKnob, 1); outRow.Children.Add(velKnob);
+ meter.HorizontalAlignment = HorizontalAlignment.Right; meter.Margin = new Thickness(0, 2, 0, 2);
+ Grid.SetColumn(meter, 2); outRow.Children.Add(meter);
+ var outHost = new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = outRow };
+ var body = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 6 };
+ body.Children.Add(sliders);
+ Grid.SetRow(outHost, 1); body.Children.Add(outHost);
+ return RailBody(RailHead("Voices", VoiceSeg()), body);
+ }
+
+ Control GroupRail()
+ {
+ if (ui.Group < 0 || ui.Group >= prog.Groups.Count) return VoicesRail();
+ var gr = prog.Groups[ui.Group];
+ string title = $"Group · {(gr.Name.Length > 0 ? gr.Name : (ui.Group + 1).ToString(NotaNum.Culture))}";
+ Grid GSlider(string label, Func<double> get, Action<double> set, Func<string> text, bool bipolar, bool mod)
+ {
+ var row = SliderRow(label, get, v => { set(v); Refresh(); }, text, out var sync, end: () => { Commit(); rebuildGroups(); }, reset: () => { set(bipolar ? 0.5 : 24.0 / 36.0); Commit(); rebuildGroups(); },
+ bipolar: bipolar, labelWidth: 46, valueWidth: 40, modulation: mod);
+ readouts.Add(sync);
+ return row;
+ }
+ var gain = GSlider("Gain", () => (gr.GainDb + 24) / 36.0, v => gr.GainDb = Math.Round((v * 36 - 24) * 10) / 10, () => DbS(gr.GainDb), false, false);
+ var tune = GSlider("Tune", () => (gr.Tune + 100) / 200.0, v => gr.Tune = Math.Round(v * 200 - 100), () => Cents(gr.Tune), true, true);
+ var seq = NumBox(() => gr.SeqLen.ToString(NotaNum.Culture), d => gr.SeqLen = Math.Clamp(gr.SeqLen + d, 1, 16), () => gr.SeqLen = 1, 36,
+ "Round-robin steps: the group's zones take turns 1 … N (each zone's step is set by its file)", () => { Commit(); rebuildGroups(); });
+ var seqRow = new Grid { ColumnDefinitions = new ColumnDefinitions("50,Auto") };
+ seqRow.Children.Add(new TextBlock { Text = "SEQ LEN", FontSize = NotaType.RowLabel, FontWeight = FontWeight.Bold, LetterSpacing = NotaType.RowLabelTracking, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center });
+ Grid.SetColumn(seq, 1); seqRow.Children.Add(seq);
+ var rrSeg = Segments(new[] { "Sequential", "Random", "No repeat" }, () => gr.RrMode, iv => { gr.RrMode = iv; Commit(); rebuildGroups(); }, out var rrSync, fill: true, padX: 3, fontSize: 7.5);
+ readouts.Add(rrSync);
+ int ExclVal(bool off) { var z = prog.Zones.FirstOrDefault(z => z.Group == ui.Group); return z is null ? 0 : off ? z.OffBy : z.Excl; }
+ void SetExcl(bool off, int v) { foreach (var z in prog.Zones.Where(z => z.Group == ui.Group)) { if (off) z.OffBy = v; else z.Excl = v; } }
+ var exG = NumBox(() => ExclVal(false) is var v && v > 0 ? $"group {v}" : "group —", d => SetExcl(false, Math.Clamp(ExclVal(false) + d, 0, 64)), () => SetExcl(false, 0), 70,
+ "This group's exclusive number", () => { Commit(); rebuildGroups(); SetMap(); });
+ var exO = NumBox(() => ExclVal(true) is var v && v > 0 ? $"off_by {v}" : "off_by —", d => SetExcl(true, Math.Clamp(ExclVal(true) + d, 0, 64)), () => SetExcl(true, 0), 70,
+ "Voices of this group stop when a note of that exclusive group starts", () => { Commit(); rebuildGroups(); SetMap(); });
+ var exRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { exG, exO } };
+ var note = new TextBlock { Text = "Exclusive is for hi-hats and valves: a new note chokes the off_by group.", FontSize = 7.5, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap };
+ var body = new StackPanel
+ {
+ Spacing = 6,
+ Children = { gain, tune, seqRow, Caps("Round-robin"), rrSeg, Caps("Exclusive · group / off by"), exRow, note },
+ };
+ return RailBody(RailHead(title, sub: $"{ZonesIn(ui.Group)} zones"), body);
+ }
+
+ Control ReportRail()
+ {
+ var r = ui.Report!;
+ var list = new StackPanel { Spacing = 0, Margin = new Thickness(0, 0, 9, 0) };
+ list.Children.Add(KV("Regions", () => r.Regions.ToString(NotaNum.Culture)));
+ list.Children.Add(KV("Imported", () => r.Imported.ToString(NotaNum.Culture)));
+ list.Children.Add(KV("Groups", () => r.Groups.ToString(NotaNum.Culture)));
+ list.Children.Add(KV("#include", () => r.Includes.ToString(NotaNum.Culture)));
+ list.Children.Add(KV("CC sets", () => r.CcState.Count == 0 ? "—" : $"{r.CcState.Count} · via set_cc"));
+ list.Children.Add(KV("Paths ..\\ → /", () => r.PathsFixed.ToString(NotaNum.Culture)));
+ if (r.Missing > 0) list.Children.Add(KV("Missing", () => r.Missing.ToString(NotaNum.Culture), NotaPalette.DangerBright));
+ list.Children.Add(Rule());
+ list.Children.Add(Caps("Ignored"));
+ foreach (var (fam, n) in r.Ignored.OrderByDescending(kv => kv.Value).Take(7))
+ list.Children.Add(KV(fam, () => n.ToString(NotaNum.Culture), TextTertiary));
+ if (r.Ignored.Count == 0) list.Children.Add(Mono("nothing", TextTertiary, 8));
+ return RailBody(RailHead("Import", sub: $"{r.File} · {NotaNum.Unit(r.Seconds, "0.0", "s")}"), new ScrollViewer { Content = list, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
+ }
+
+ Control MemoryRail()
+ {
+ var body = new StackPanel
+ {
+ Spacing = 2,
+ Children =
+ {
+ Caps("Memory"),
+ KV("Loaded", () => NotaNum.Bytes(status.RamBytes)),
+ KV("Estimated", () => NotaNum.Bytes(RamEstimate())),
+ KV("Files", () => $"{status.FilesDone} / {status.FilesTotal}"),
+ KV("Missing", () => status.Missing.ToString(NotaNum.Culture), status.Missing > 0 ? NotaPalette.DangerBright : null),
+ Rule(),
+ KV("Total in RAM", () => NotaNum.Bytes(status.State == 2 ? status.RamBytes : RamEstimate())),
+ },
+ };
+ return RailBody(RailHead("Voices", VoiceSeg()), body);
+ }
+
+ Control SourceRail()
+ {
+ string reference = prog.Files.FirstOrDefault() ?? "";
+ string where = prog.PackId.Length > 0 ? $"pack://{prog.PackId}/{MosaicPaths.FileName(reference)}…" : reference;
+ var body = new StackPanel
+ {
+ Spacing = 4,
+ Children =
+ {
+ Caps("Source"),
+ new TextBlock { Text = where, FontSize = 8, Foreground = TextPrimary, FontFamily = NotaFonts.MonoFamily, TextWrapping = TextWrapping.Wrap },
+ new TextBlock { Text = "Samples are not copied into the project; the program keeps where they are.", FontSize = 7.5, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap },
+ },
+ };
+ return RailBody(RailHead("Voices", VoiceSeg()), body);
+ }
+
+ rebuildRail = () =>
+ {
+ Control c =
+ AllMissing() && prog.Zones.Count > 0 ? SourceRail()
+ : Loading() ? MemoryRail()
+ : ui.ReportOpen && ui.Report is not null && !ui.ReportDismissed ? ReportRail()
+ : tab == 2 ? GroupRail()
+ : VoicesRail();
+ railHost.Content = c;
+ Refresh();
+ };
+
+ // ======================= status ==========================================================
+ string Summary()
+ {
+ if (AllMissing() && prog.Zones.Count > 0) return "Samples unavailable · notes muted";
+ if (Loading()) return $"Loading · {NotaNum.Bytes(status.RamBytes)} / {NotaNum.Bytes(RamEstimate())} · notes muted";
+ if (prog.IsEmpty) return "Empty · drop samples or a folder, or pick a preset";
+ string name = prog.Name.Length > 0 ? prog.Name + " · " : "";
+ switch (tab)
+ {
+ case 0 when ui.ReleaseView:
+ {
+ int sounding = snap.Zones.Count(z => z.Zone >= 0 && z.Zone < prog.Zones.Count && prog.Zones[z.Zone].Release);
+ return $"Release · {sounding} sounding · {NotaNum.Db(MosaicModel.RelVolDb(G("relvol")), signed: true)} · {NotaNum.Db(MosaicModel.RelLenDb(G("rellen")), signed: true)} after 2 s hold";
+ }
+ case 0:
+ case 1:
+ case 3:
+ {
+ string pedal = snap.Pedal ? " · pedal down" : "";
+ string missing = status.Missing > 0 ? $" · {status.Missing} missing" : "";
+ return $"{name}{prog.Summary()}{pedal}{missing}";
+ }
+ case 2:
+ {
+ string rel = G("relon") >= 0.5f ? $"release {NotaNum.Db(MosaicModel.RelVolDb(G("relvol")), signed: true)}" : "release off";
+ var rrg = prog.Groups.FirstOrDefault(g => g.SeqLen > 1);
+ string rr = rrg is null ? "no round-robin" : $"rr {rrg.SeqLen} {MosaicProgram.RrNames[rrg.RrMode].ToLowerInvariant()}";
+ return $"{prog.Groups.Count} groups · {rr} · {rel}";
+ }
+ case 4: return $"Env {EnvTl()} · vel {NotaNum.Pct(G("velamount"))} · curve {VelCurveWord()}";
+ default:
+ {
+ int t = Sel("filtertype", 4);
+ if (t == 0) return "Filter off — the samples pass untouched";
+ return $"Filter {MosaicModel.FilterNames[t]} · cutoff {NotaNum.Hz(MosaicModel.CutoffHz(G("cutoff")))} · reso {NotaNum.Pct(G("resonance"))}";
+ }
+ }
+ }
+ var statusBar = new Grid { Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };
+ statusBar.Children.Add(statusText);
+ Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);
+ var statusHost = new Border
+ {
+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Background = NotaPalette.SurfaceAbyss,
+ Padding = new Thickness(8, 0), Child = statusBar,
+ };
+
+ // ======================= assembly ========================================================
+ var body = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = NotaSpace.DeviceGap, Margin = new Thickness(NotaSpace.DeviceGap) };
+ body.Children.Add(tabPanel);
+ Grid.SetColumn(rail, 1); body.Children.Add(rail);
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };
+ HookDrop(root, dropLayer);
+
+ bool lastLoading = Loading(), lastMissing = AllMissing();
+ showTab = () =>
+ {
+ ui.Tab = tab;
+ for (int i = 0; i < TabNames.Length; i++)
+ {
+ bool on = i == tab;
+ tabCells[i].Background = on ? NotaPalette.SurfaceRaised : Brushes.Transparent;
+ tabCells[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ tabTexts[i].Foreground = on ? AccentBright : TextTertiary;
+ tabTexts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ pages[i].IsVisible = on;
+ }
+ arSeg.IsVisible = hasRelease && tab == 0;
+ if (articulation is not null) articulation.IsVisible = tab == 0;
+ rebuildRail();
+ };
+ refresh = () =>
+ {
+ foreach (var r in readouts) r();
+ statusText.Text = Summary();
+ statusText.Foreground = AllMissing() && prog.Zones.Count > 0 ? NotaPalette.DangerBright : Loading() ? AccentBright : TextSecondary;
+ bool ld = Loading();
+ loadLayer.IsVisible = ld;
+ zoneRow.IsVisible = !ld; loadRow.IsVisible = ld;
+ if (ld)
+ {
+ double f = LoadFrac();
+ loadPct.Text = NotaNum.Pct(f);
+ loadLine.Text = $"{NotaNum.Bytes(status.RamBytes)} / {NotaNum.Bytes(RamEstimate())} · {status.FilesDone} / {status.FilesTotal} files";
+ loadBar.Width = loadTrack.Bounds.Width * f;
+ }
+ };
+ void Live()
+ {
+ engine.TryGetMosaicStatus(track, out status);
+ // Another program (undo, a preset, the MCP): start over from it.
+ if (status.Serial != knownSerial) { knownSerial = status.Serial; ctx.RequestRebuild(); return; }
+ int n = engine.InstrumentScope(track, scope);
+ MosaicModel.Parse(scope.AsSpan(0, Math.Max(0, n)), snap);
+ samSnap.Live = snap.Live; samSnap.Voices = snap.Voices; samSnap.Env = snap.Env; samSnap.Stage = snap.Stage;
+ samSnap.Note = snap.Note; samSnap.CutoffHz = snap.CutoffHz; samSnap.PlayPos = snap.Pos;
+ map.SetSounding(snap.Zones, snap.Keys);
+ if (tab == 1) wave.SetPlayhead(snap.Live && snap.Zone == ui.Zone ? snap.Pos : -1);
+ meta.Text = $"{Rate()} · {snap.Voices}/{Poly()} voices · CPU {NotaNum.Unit(engine.CpuLoad * 100, "0.0", "%")}";
+ bool ld = Loading(), miss = AllMissing();
+ if (ld != lastLoading || miss != lastMissing)
+ {
+ lastLoading = ld; lastMissing = miss;
+ if (miss != (mapCell.Children.Count == 1)) { ctx.RequestRebuild(); return; }
+ waveSampleId = -1;
+ rebuildRail();
+ }
+ Refresh();
+ }
+ ctx.AddDeviceRefresher(Live);
+ ctx.SetInstLiveViz(Refresh);
+ showTab();
+ Live();
+ return root;
+
+ // ======================= drop: files / a folder → a multisample ============================
+ Control DropOverlay()
+ {
+ var title = new TextBlock { FontSize = 12, FontWeight = FontWeight.SemiBold, Foreground = AccentBright, HorizontalAlignment = HorizontalAlignment.Center };
+ var line = new TextBlock { FontSize = 8.5, Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, TextAlignment = TextAlignment.Center };
+ var hint = new TextBlock { FontSize = 7.5, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center, Text = "Opens the mapping preview. A single file replaces the sample, as before." };
+ var dash = new Rectangle
+ {
+ Stroke = AccentBright, StrokeThickness = 1.2, StrokeDashArray = new Avalonia.Collections.AvaloniaList<double> { 4, 3 },
+ RadiusX = 6, RadiusY = 6, Fill = NotaPalette.Wash(NotaPalette.SurfaceCard, 0xE6),
+ };
+ var box = new Panel
+ {
+ Margin = new Thickness(5), IsVisible = false, IsHitTestVisible = false,
+ Children = { dash, new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { title, line, hint } } },
+ };
+ box.Tag = (Action<string, string>)((t, l) => { title.Text = t; line.Text = l; });
+ return box;
+ }
+
+ void HookDrop(Control target, Control overlay)
+ {
+ DragDrop.SetAllowDrop(target, true);
+ void Show(bool on, string t = "", string l = "")
+ {
+ overlay.IsVisible = on;
+ if (on && overlay.Tag is Action<string, string> set) set(t, l);
+ }
+ DragDrop.AddDragOverHandler(target, (_, e) =>
+ {
+ var item = BrowserView.CurrentDrag;
+ bool folder = item is { Kind: BrowserItemKind.Folder } && Directory.Exists(item.Path);
+ bool sample = item is { Kind: BrowserItemKind.Sample };
+ bool files = item is null && e.DataTransfer.Contains(DataFormat.File);
+ if (!folder && !sample && !files) return;
+ e.DragEffects = DragDropEffects.Copy;
+ e.Handled = true;
+ ctx.HideDropGlow();
+ if (sample) Show(true, "Release to load the sample", item!.Name);
+ else
+ {
+ var paths = folder ? new List<string> { item!.Path } : DroppedPaths(e);
+ var audio = ExpandAudio(paths);
+ if (audio.Count == 1) Show(true, "Release to load the sample", Path.GetFileName(audio[0]));
+ else
+ {
+ var stems = audio.Select(p => MultisampleMapper.ParseName(p).Stem).Distinct().ToList();
+ Show(true, "Release to build a multisample",
+ audio.Count == 0 ? "a folder of samples" : $"{audio.Count} files · {stems.Count} instrument{(stems.Count == 1 ? "" : "s")} found by name: {string.Join(", ", stems.Take(4))}");
+ }
+ }
+ });
+ DragDrop.AddDragLeaveHandler(target, (_, _) => Show(false));
+ DragDrop.AddDropHandler(target, (_, e) =>
+ {
+ Show(false);
+ var item = BrowserView.CurrentDrag;
+ List<string> paths;
+ if (item is { Kind: BrowserItemKind.Sample }) paths = new List<string> { item.Path };
+ else if (item is { Kind: BrowserItemKind.Folder } && Directory.Exists(item.Path)) paths = new List<string> { item.Path };
+ else if (item is null) paths = DroppedPaths(e);
+ else return;
+ var audio = ExpandAudio(paths);
+ if (audio.Count == 0) return;
+ e.Handled = true;
+ if (audio.Count == 1 && !paths.Any(Directory.Exists))
+ {
+ var packs = App.Services?.GetService(typeof(IMosaicPacks)) as IMosaicPacks;
+ int rootNote = SamplerModel.DetectRoot(audio[0]) is var d and >= 0 ? d : 60;
+ prog = MosaicProgram.Single(packs?.ToRef(audio[0]) ?? audio[0], rootNote, Path.GetFileNameWithoutExtension(audio[0]));
+ ui.Zone = 0; ui.Report = null;
+ Commit(rebuild: true);
+ return;
+ }
+ CreateMultisampleRequested?.Invoke(track, paths.Any(Directory.Exists) ? paths : audio);
+ });
+ }
+
+ // ======================= S ===============================================================
+ Control BuildMini()
+ {
+ var zonesTxt = Mono("", TextSecondary, 8);
+ var ramTxt = Mono("", TextSecondary, 8);
+ var miniBar = new Border { Height = 3, Background = Brass, HorizontalAlignment = HorizontalAlignment.Left, CornerRadius = NotaRadius.Badge };
+ var miniTrack = new Border { Height = 3, Background = NotaPalette.BorderDefault, CornerRadius = NotaRadius.Badge, Child = miniBar, Margin = new Thickness(0, 4, 0, 0) };
+ var inner = new Grid { RowDefinitions = new RowDefinitions("*,Auto,Auto"), RowSpacing = 4, Margin = new Thickness(6, 6, 6, 4) };
+ inner.Children.Add(map);
+ Grid.SetRow(miniTrack, 1); inner.Children.Add(miniTrack);
+ var foot = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ foot.Children.Add(zonesTxt);
+ Grid.SetColumn(ramTxt, 1); foot.Children.Add(ramTxt);
+ Grid.SetRow(foot, 2); inner.Children.Add(foot);
+ var island = SectionBox(inner);
+ island.Margin = new Thickness(NotaSpace.DeviceGap);
+ void MiniLive()
+ {
+ engine.TryGetMosaicStatus(track, out status);
+ if (status.Serial != knownSerial) { knownSerial = status.Serial; ctx.RequestRebuild(); return; }
+ int n = engine.InstrumentScope(track, scope);
+ MosaicModel.Parse(scope.AsSpan(0, Math.Max(0, n)), snap);
+ map.SetSounding(snap.Zones, snap.Keys);
+ bool ld = Loading();
+ miniTrack.IsVisible = ld;
+ miniBar.Width = miniTrack.Bounds.Width * LoadFrac();
+ zonesTxt.Text = ld ? $"Loading {NotaNum.Pct(LoadFrac())}" : prog.IsEmpty ? "Empty" : $"{prog.Zones.Count} zones · {prog.VelocityLayers} layer{(prog.VelocityLayers == 1 ? "" : "s")}";
+ zonesTxt.Foreground = ld ? AccentBright : AllMissing() && prog.Zones.Count > 0 ? NotaPalette.DangerBright : TextSecondary;
+ ramTxt.Text = ld ? $"{NotaNum.Bytes(status.RamBytes)} / {NotaNum.Bytes(RamEstimate())}" : NotaNum.Bytes(status.RamBytes);
+ }
+ ctx.AddDeviceRefresher(MiniLive);
+ MiniLive();
+ var dropMini = DropOverlay();
+ var host = new Panel { Children = { island, dropMini } };
+ HookDrop(host, dropMini);
+ return host;
+ }
+ }
+
+ private static List<string> DroppedPaths(DragEventArgs e)
+ {
+ var list = new List<string>();
+ if (!e.DataTransfer.Contains(DataFormat.File)) return list;
+ var files = e.DataTransfer.TryGetFiles();
+ if (files is null) return list;
+ foreach (var f in files) if (f.TryGetLocalPath() is { Length: > 0 } p) list.Add(p);
+ return list;
+ }
+
+ private static List<string> ExpandAudio(IEnumerable<string> paths)
+ {
+ var list = new List<string>();
+ foreach (var p in paths)
+ {
+ if (Directory.Exists(p))
+ {
+ try { list.AddRange(Directory.EnumerateFiles(p, "*", SearchOption.AllDirectories).Where(MultisampleMapper.IsAudio).Take(4000)); } catch { }
+ }
+ else if (MultisampleMapper.IsAudio(p)) list.Add(p);
+ }
+ return list;
+ }
+
+ private static Border SectionBox(Control child) => new()
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = child,
+ };
+
+ private static Border HeaderStrip(Control child) => new()
+ {
+ BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = child,
+ };
+}
diff --git a/src/managed/Nota.App/DeviceCards/Mosaic/MosaicViews.cs b/src/managed/Nota.App/DeviceCards/Mosaic/MosaicViews.cs
new file mode 100644
index 00000000..2ca6ef09
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Mosaic/MosaicViews.cs
@@ -0,0 +1,394 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic's windows:
+//
+// MosaicZoneMap the zone map — keys on X, velocity on Y, the keyboard under it with a
+// brass tick under every root. Zones are tiles; the selected one is
+// outlined in Brass Light with its root written in; zones sounding now
+// fill brass (muted brass while the pedal holds them, a deeper wash for
+// release samples and fades); an exclusive group is outlined. Click a
+// tile to select it (again: the next round-robin tile under it), drag it
+// to move, drag an edge to resize. The keyboard plays (press / release).
+// The mini (S) map is the same picture without axes or input.
+// MosaicCurveView a small curve window: the release level against hold time, or the
+// velocity curve. Drag up / down to change it; double-click resets.
+//
+// All in the NotaGraph window (well, hairline, radius 4, labels in mono 7).
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Nota.Application;
+using Nota.Application.Mosaic;
+
+namespace Nota.App;
+
+internal sealed class MosaicZoneMap : Control
+{
+ private IReadOnlyList<MosaicZone> _zones = Array.Empty<MosaicZone>();
+ private bool _release; // show the release zones (else the attack ones)
+ private int _sel = -1;
+ private readonly Dictionary<int, int> _sounding = new(); // zone → 0 held · 1 pedal · 2 release
+ private readonly HashSet<int> _keysDown = new();
+ private int _lo = 21, _hi = 108; // keys shown (inclusive)
+ private string _empty = "";
+
+ public bool Mini { get; init; }
+ public bool Interactive { get; init; } = true;
+ /// <summary>Notes to flag on the keyboard (a gap, say) in Danger.</summary>
+ public HashSet<int> Flagged { get; } = new();
+
+ /// <summary>A tile was picked (index into the zone list).</summary>
+ public event Action<int>? Selected;
+ /// <summary>A drag moved / resized a zone: index, key lo / hi, vel lo / hi, done (pointer up).</summary>
+ public event Action<int, int, int, int, int, bool>? Edited;
+ public event Action<int>? KeyDown, KeyUp;
+
+ private const double AxisW = 14, KeyH = 12, OctH = 9;
+
+ public MosaicZoneMap() { ClipToBounds = true; }
+
+ public void Set(IReadOnlyList<MosaicZone> zones, bool release, int selected, string empty = "")
+ {
+ _zones = zones; _release = release; _sel = selected; _empty = empty;
+ // Whole octaves around what the map holds (C to C), at least four.
+ int lo = 127, hi = 0;
+ foreach (var z in zones) { lo = Math.Min(lo, z.KeyLo); hi = Math.Max(hi, z.KeyHi); }
+ if (lo > hi) { lo = 36; hi = 84; }
+ lo -= lo % 12;
+ hi = Math.Min(127, hi + (12 - hi % 12) % 12);
+ while (hi - lo < 48 && (lo > 0 || hi < 127)) { if (lo >= 12) lo -= 12; if (hi - lo < 48) hi = Math.Min(127, hi + 12); }
+ _lo = lo; _hi = hi;
+ InvalidateVisual();
+ }
+
+ public void SetSounding(IEnumerable<MosaicModel.Sounding> s, IEnumerable<int> keys)
+ {
+ _sounding.Clear();
+ foreach (var x in s)
+ if (!_sounding.TryGetValue(x.Zone, out var cur) || x.State < cur) _sounding[x.Zone] = x.State;
+ _playing.Clear();
+ foreach (var k in keys) _playing.Add(k);
+ InvalidateVisual();
+ }
+ private readonly HashSet<int> _playing = new();
+
+ // ---- geometry ----------------------------------------------------------------------------
+ private Rect MapRect()
+ {
+ double ax = Mini ? 0 : AxisW;
+ double bottom = Mini ? KeyH * 0.75 : KeyH + OctH + 2;
+ return new Rect(ax, 0, Math.Max(1, Bounds.Width - ax), Math.Max(1, Bounds.Height - bottom));
+ }
+ private double KeyW(Rect m) => m.Width / Math.Max(1, _hi - _lo + 1);
+ private Rect ZoneRect(Rect m, MosaicZone z)
+ {
+ double kw = KeyW(m);
+ double x0 = m.X + (Math.Max(z.KeyLo, _lo) - _lo) * kw, x1 = m.X + (Math.Min(z.KeyHi, _hi) - _lo + 1) * kw;
+ double y0 = m.Y + (127 - z.VelHi) / 128.0 * m.Height, y1 = m.Y + (128 - z.VelLo) / 128.0 * m.Height;
+ return new Rect(x0, y0, Math.Max(1, x1 - x0), Math.Max(1, y1 - y0));
+ }
+ public int KeyAt(Point p)
+ {
+ var m = MapRect();
+ double kw = KeyW(m);
+ if (kw <= 0 || p.X < m.X) return -1;
+ return Math.Clamp(_lo + (int)Math.Floor((p.X - m.X) / kw), 0, 127);
+ }
+ private int VelAt(Point p, Rect m) => Math.Clamp(127 - (int)Math.Floor((p.Y - m.Y) / m.Height * 128), 0, 127);
+ private bool Shows(MosaicZone z) => z.Release == _release;
+
+ // ---- input -------------------------------------------------------------------------------
+ private enum Drag { None, Move, Left, Right, Top, Bottom }
+ private Drag _drag;
+ private int _dragZone = -1, _keyHeld = -1;
+ private Point _press;
+ private bool _moved;
+ private (int Klo, int Khi, int Vlo, int Vhi) _orig, _live;
+
+ private (int Zone, Drag Part) HitTest(Point p)
+ {
+ var m = MapRect();
+ int found = -1; Drag part = Drag.None;
+ // Prefer the selected zone (its edges), then the topmost tile under the pointer.
+ for (int pass = 0; pass < 2 && found < 0; pass++)
+ for (int i = _zones.Count - 1; i >= 0; i--)
+ {
+ if (!Shows(_zones[i]) || (pass == 0 && i != _sel)) continue;
+ var r = ZoneRect(m, _zones[i]);
+ if (!r.Inflate(2).Contains(p)) continue;
+ found = i;
+ const double e = 4;
+ if (Math.Abs(p.X - r.Left) <= e && r.Width > 10) part = Drag.Left;
+ else if (Math.Abs(p.X - r.Right) <= e && r.Width > 10) part = Drag.Right;
+ else if (Math.Abs(p.Y - r.Top) <= 3 && r.Height > 10) part = Drag.Top;
+ else if (Math.Abs(p.Y - r.Bottom) <= 3 && r.Height > 10) part = Drag.Bottom;
+ else part = Drag.Move;
+ break;
+ }
+ return (found, part);
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (!Interactive) return;
+ var p = e.GetPosition(this);
+ if (_drag == Drag.None)
+ {
+ var (z, part) = HitTest(p);
+ Cursor = z >= 0 && z == _sel ? part switch
+ {
+ Drag.Left or Drag.Right => new Cursor(StandardCursorType.SizeWestEast),
+ Drag.Top or Drag.Bottom => new Cursor(StandardCursorType.SizeNorthSouth),
+ _ => new Cursor(StandardCursorType.SizeAll),
+ } : z >= 0 || p.Y > MapRect().Bottom ? new Cursor(StandardCursorType.Hand) : Cursor.Default;
+ return;
+ }
+ if (_dragZone < 0) return;
+ if (!_moved && Math.Abs(p.X - _press.X) + Math.Abs(p.Y - _press.Y) < 3) return;
+ _moved = true;
+ var m = MapRect();
+ int dk = (int)Math.Round((p.X - _press.X) / KeyW(m));
+ int dv = (int)Math.Round(-(p.Y - _press.Y) / m.Height * 128);
+ var (klo, khi, vlo, vhi) = _orig;
+ switch (_drag)
+ {
+ case Drag.Move:
+ dk = Math.Clamp(dk, -klo, 127 - khi); dv = Math.Clamp(dv, -vlo, 127 - vhi);
+ klo += dk; khi += dk; vlo += dv; vhi += dv; break;
+ case Drag.Left: klo = Math.Clamp(klo + dk, 0, khi); break;
+ case Drag.Right: khi = Math.Clamp(khi + dk, klo, 127); break;
+ case Drag.Top: vhi = Math.Clamp(vhi + dv, vlo, 127); break;
+ case Drag.Bottom: vlo = Math.Clamp(vlo + dv, 0, vhi); break;
+ }
+ if ((klo, khi, vlo, vhi) != _live)
+ {
+ _live = (klo, khi, vlo, vhi);
+ Edited?.Invoke(_dragZone, klo, khi, vlo, vhi, false);
+ }
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!Interactive || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ var p = e.GetPosition(this);
+ var m = MapRect();
+ if (p.Y > m.Bottom) // the keyboard plays
+ {
+ int k = KeyAt(p);
+ if (k >= 0) { _keyHeld = k; _keysDown.Add(k); KeyDown?.Invoke(k); InvalidateVisual(); e.Pointer.Capture(this); e.Handled = true; }
+ return;
+ }
+ var (z, part) = HitTest(p);
+ if (z < 0) return;
+ // A second click on the selected tile picks the next one stacked under it (round-robin).
+ if (z == _sel && part == Drag.Move && e.ClickCount == 1)
+ {
+ var r = ZoneRect(m, _zones[z]);
+ var stack = new List<int>();
+ for (int i = 0; i < _zones.Count; i++) if (Shows(_zones[i]) && ZoneRect(m, _zones[i]) == r) stack.Add(i);
+ if (stack.Count > 1) { _cycleNext = stack[(stack.IndexOf(z) + 1) % stack.Count]; }
+ }
+ if (z != _sel) { _sel = z; Selected?.Invoke(z); }
+ _drag = part; _dragZone = z; _press = p; _moved = false;
+ var zz = _zones[z];
+ _orig = _live = (zz.KeyLo, zz.KeyHi, zz.VelLo, zz.VelHi);
+ e.Pointer.Capture(this);
+ e.Handled = true;
+ InvalidateVisual();
+ }
+ private int _cycleNext = -1;
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (_keyHeld >= 0) { KeyUp?.Invoke(_keyHeld); _keysDown.Remove(_keyHeld); _keyHeld = -1; InvalidateVisual(); }
+ if (_drag != Drag.None && _dragZone >= 0)
+ {
+ if (_moved) Edited?.Invoke(_dragZone, _live.Klo, _live.Khi, _live.Vlo, _live.Vhi, true);
+ else if (_cycleNext >= 0) { _sel = _cycleNext; Selected?.Invoke(_sel); }
+ }
+ _cycleNext = -1;
+ _drag = Drag.None; _dragZone = -1;
+ e.Pointer.Capture(null);
+ }
+
+ // ---- drawing -----------------------------------------------------------------------------
+ private static readonly IPen Hair = new Pen(NotaPalette.GraphBorder, 1);
+ private static readonly IPen SelPen = new Pen(NotaPalette.AccentBright, 1.5);
+ private static readonly IPen ExclPen = new Pen(NotaPalette.TextTertiary, 1);
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 2 || h <= 2) return;
+ var m = MapRect();
+ NotaGraph.Window(ctx, m);
+ var inner = m.Deflate(1);
+ double kw = KeyW(m);
+
+ // Octave rules (a C every 12 keys).
+ for (int k = _lo; k <= _hi; k++)
+ if (k % 12 == 0 && k > _lo)
+ {
+ double x = Math.Round(m.X + (k - _lo) * kw) + 0.5;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x, inner.Top), new Point(x, inner.Bottom));
+ }
+
+ // Tiles: plain ones first, the sounding over them, the selected last.
+ var drawn = new HashSet<Rect>();
+ var roots = new HashSet<int>();
+ for (int i = 0; i < _zones.Count; i++)
+ {
+ var z = _zones[i];
+ if (!Shows(z)) continue;
+ roots.Add(z.Root);
+ var r = ZoneRect(m, z).Deflate(0.5);
+ if (_sounding.ContainsKey(i) || i == _sel || !drawn.Add(r)) continue;
+ ctx.DrawRectangle(NotaPalette.SurfaceCard, Hair, new RoundedRect(r, 1));
+ if (z.Excl != 0 || z.OffBy != 0) ctx.DrawRectangle(null, ExclPen, new RoundedRect(r.Deflate(1.5), 1));
+ }
+ foreach (var (i, st) in _sounding)
+ {
+ if (i < 0 || i >= _zones.Count || !Shows(_zones[i])) continue;
+ var r = ZoneRect(m, _zones[i]).Deflate(0.5);
+ IBrush fill = st == 0 ? NotaPalette.Accent : st == 1 ? NotaPalette.AccentDim : NotaPalette.AccentMute;
+ ctx.DrawRectangle(fill, null, new RoundedRect(r, 1));
+ }
+ if (_sel >= 0 && _sel < _zones.Count && Shows(_zones[_sel]))
+ {
+ var z = _zones[_sel];
+ var r = ZoneRect(m, z).Deflate(0.75);
+ if (!_sounding.ContainsKey(_sel)) ctx.DrawRectangle(NotaPalette.AccentSubtle, null, new RoundedRect(r, 1));
+ ctx.DrawRectangle(null, SelPen, new RoundedRect(r, 1));
+ if (!Mini)
+ {
+ var t = SamplerInk.Mono(MosaicNames.NoteName(z.Root), _sounding.ContainsKey(_sel) ? NotaPalette.TextOnAccent : NotaPalette.AccentBright, 6.5);
+ if (t.Width + 2 < r.Width && t.Height + 2 < r.Height)
+ ctx.DrawText(t, new Point(r.X + (r.Width - t.Width) / 2, r.Y + (r.Height - t.Height) / 2));
+ }
+ }
+ if (_zones.Count == 0 && _empty.Length > 0)
+ {
+ var t = SamplerInk.Mono(_empty, NotaPalette.TextTertiary, 8);
+ ctx.DrawText(t, new Point(m.X + (m.Width - t.Width) / 2, m.Y + (m.Height - t.Height) / 2));
+ }
+
+ // Velocity axis.
+ if (!Mini)
+ foreach (var (v, s) in new[] { (127, "127"), (64, "64"), (1, "1") })
+ {
+ var t = SamplerInk.Mono(s, NotaPalette.TextAxis, 6);
+ double y = m.Y + (127 - v) / 128.0 * m.Height;
+ y = Math.Clamp(y, m.Y, m.Bottom - t.Height);
+ ctx.DrawText(t, new Point(AxisW - 2 - t.Width, y));
+ }
+
+ // The keyboard: white / black keys, sounding keys brass, a tick under every root.
+ double ky = m.Bottom + 1, kh = Mini ? KeyH * 0.75 - 2 : KeyH;
+ var held = new HashSet<int>(_keysDown);
+ held.UnionWith(_playing);
+ for (int k = _lo; k <= _hi; k++)
+ {
+ int pc = k % 12;
+ bool black = pc is 1 or 3 or 6 or 8 or 10;
+ var r = new Rect(m.X + (k - _lo) * kw + 0.5, ky, Math.Max(1, kw - 1), black ? kh * 0.62 : kh);
+ IBrush fill = held.Contains(k) ? NotaPalette.Accent : Flagged.Contains(k) ? NotaPalette.Danger
+ : black ? NotaPalette.KeyBlack : NotaPalette.MiniKeyWhite;
+ ctx.DrawRectangle(fill, null, r);
+ if (roots.Contains(k) && !Mini)
+ ctx.DrawRectangle(NotaPalette.Accent, null, new Rect(r.X + r.Width * 0.2, ky + kh + 1, Math.Max(1, r.Width * 0.6), 1.5));
+ }
+ if (!Mini)
+ for (int k = _lo; k <= _hi; k++)
+ if (k % 12 == 0)
+ {
+ var t = SamplerInk.Mono(MosaicNames.NoteName(k), NotaPalette.TextAxis, 6);
+ double x = m.X + (k - _lo) * kw;
+ if (x + t.Width <= m.Right + 1) ctx.DrawText(t, new Point(x, ky + kh + 2));
+ }
+ }
+}
+
+// ---- a small curve window (release level vs hold · velocity curve) ------------------------------
+internal sealed class MosaicCurveView : Control
+{
+ /// <summary>y (0..1, 1 = top) at x (0..1) for the current value.</summary>
+ public Func<double, double> Curve { get; set; } = x => x;
+ /// <summary>Normalized value the curve stands for; a vertical drag changes it.</summary>
+ public Func<float> Get { get; set; } = () => 0.5f;
+ public Action<float>? SetValue { get; set; }
+ public Action? Begin { get; set; }
+ public Action? End { get; set; }
+ public float Default { get; set; } = 0.5f;
+ /// <summary>A node to mark on the curve (x 0..1), or null.</summary>
+ public double? Node { get; set; }
+ /// <summary>Drag up raises the value (else lowers it).</summary>
+ public bool UpIsMore { get; set; } = true;
+
+ private bool _drag;
+ private double _y0;
+ private float _v0;
+
+ public MosaicCurveView() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.SizeNorthSouth); }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed || SetValue is null) return;
+ if (e.ClickCount == 2) { Begin?.Invoke(); SetValue(Default); End?.Invoke(); InvalidateVisual(); e.Handled = true; return; }
+ _drag = true; _y0 = e.GetPosition(this).Y; _v0 = Get();
+ Begin?.Invoke();
+ e.Pointer.Capture(this);
+ e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (!_drag || SetValue is null) return;
+ double dy = (_y0 - e.GetPosition(this).Y) / Math.Max(20, Bounds.Height * 2);
+ if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) dy *= 0.2;
+ SetValue((float)Math.Clamp(_v0 + (UpIsMore ? dy : -dy), 0, 1));
+ InvalidateVisual();
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_drag) return;
+ _drag = false; End?.Invoke();
+ e.Pointer.Capture(null);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 4 || h <= 4) return;
+ var r = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, r);
+ var inner = r.Deflate(5);
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ const int n = 40;
+ for (int i = 0; i <= n; i++)
+ {
+ double x = i / (double)n, y = Math.Clamp(Curve(x), 0, 1);
+ var p = new Point(inner.X + x * inner.Width, inner.Bottom - y * inner.Height);
+ if (i == 0) g.BeginFigure(p, false); else g.LineTo(p);
+ }
+ g.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, geo);
+ if (Node is { } nx)
+ {
+ double y = Math.Clamp(Curve(nx), 0, 1);
+ NotaGraph.Node(ctx, new Point(inner.X + nx * inner.Width, inner.Bottom - y * inner.Height), true);
+ }
+ }
+}
diff --git a/src/managed/Nota.App/DeviceChainView.Instruments.cs b/src/managed/Nota.App/DeviceChainView.Instruments.cs
index 5c4bc9c6..ad3b59a7 100644
--- a/src/managed/Nota.App/DeviceChainView.Instruments.cs
+++ b/src/managed/Nota.App/DeviceChainView.Instruments.cs
@@ -31,7 +31,8 @@ public sealed partial class DeviceChainView
Name: _engine.DeviceName(_trackId, -1), Subtitle: strategy.Subtitle, DeviceIndex: -1, Count: 1,
Bypassed: false, Bypassable: false, CanMove: false, CanDelete: false,
PresetKind: kind, IsInstrument: true, Width: width, Kind: ChainKind.Instrument,
- VoiceLabel: strategy.VoiceLabel, Presets: kind == Nota.Application.RhythmModel.Kind ? KitPresets() : null,
+ VoiceLabel: strategy.VoiceLabel,
+ Presets: kind == Nota.Application.RhythmModel.Kind ? KitPresets() : kind == Nota.Application.MosaicModel.Kind ? MosaicPresets() : null,
HeaderExtra: strategy.HeaderAccessory(ctx), Compact: width < 300);
return BuildCardShell(spec, body);
}
@@ -52,6 +53,35 @@ public sealed partial class DeviceChainView
});
}
+ // Nota Mosaic's presets: the factory multisamples, then every pack preset ("Pack / Name").
+ // The one the instrument holds is named by its program (a pack preset keeps its name).
+ private CardPresets MosaicPresets()
+ {
+ int t = _trackId;
+ var items = new System.Collections.Generic.List<(string, string)>();
+ foreach (var p in _factory.All())
+ if (p.IsInstrument && p.BuiltinKind == Nota.Application.MosaicModel.Kind) items.Add(("factory:" + p.Id, p.DisplayName));
+ if (_mosaic is not null)
+ foreach (var p in _mosaic.Presets()) items.Add((p.Path, $"{p.Folder} / {p.Name}"));
+ // A program that is no preset (an SFZ, dropped files) still names itself in the picker.
+ string held = Nota.Application.Mosaic.MosaicProgram.Parse(_engine.MosaicProgram(t)).Name;
+ if (held.Length > 0 && !items.Exists(i => i.Item2 == held || i.Item2.EndsWith(" / " + held, StringComparison.Ordinal)))
+ items.Insert(0, ("program:", held));
+ string Current()
+ {
+ string name = Nota.Application.Mosaic.MosaicProgram.Parse(_engine.MosaicProgram(t)).Name;
+ if (name.Length == 0) return "";
+ foreach (var (id, n) in items) if (n == name || n.EndsWith(" / " + name, StringComparison.Ordinal)) return id;
+ return "";
+ }
+ return new CardPresets(items, Current, id =>
+ {
+ if (id == "program:") return "";
+ if (id.StartsWith("factory:", StringComparison.Ordinal)) return _factory.ApplyInPlace(_engine, id["factory:".Length..], t, -1);
+ return _mosaic?.ApplyInPlace(_engine, id, t) ?? "Presets are unavailable.";
+ });
+ }
+
// The Drum Rack in the shared shell: its presets are the factory kits, which replace the
// rack's pads, and the badge counts the loaded pads.
private Control DrumRackCard()
diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.cs
index dc8148f7..56cfe1ce 100644
--- a/src/managed/Nota.App/DeviceChainView.cs
+++ b/src/managed/Nota.App/DeviceChainView.cs
@@ -44,6 +44,7 @@ public sealed partial class DeviceChainView : UserControl
private readonly IFactoryPresets _factory;
private readonly IPluginCatalog? _catalog; // maps a copied plugin's id → catalog index for paste
private readonly IDrumKits? _kits; // the Drum Rack card's preset list
+ private readonly IMosaicPacks? _mosaic; // Nota Mosaic's pack presets, beside its factory ones
private readonly DeviceCardFactory _cardFactory = new();
private readonly InstrumentCardFactory _instrumentFactory = new();
private readonly MidiDeviceCardFactory _midiFactory = new();
@@ -80,12 +81,13 @@ public sealed partial class DeviceChainView : UserControl
Margin = new Thickness(2),
};
- public DeviceChainView(IAudioEngine engine, IFactoryPresets factory, IPluginCatalog? catalog = null, IDrumKits? kits = null)
+ public DeviceChainView(IAudioEngine engine, IFactoryPresets factory, IPluginCatalog? catalog = null, IDrumKits? kits = null, IMosaicPacks? mosaic = null)
{
_engine = engine;
_factory = factory;
_catalog = catalog;
_kits = kits;
+ _mosaic = mosaic;
Focusable = true; // so Ctrl+C/X/V + Delete on a selected device reach OnKeyDown
var scroller = new ScrollViewer
{
diff --git a/src/managed/Nota.App/MainWindow.Mosaic.cs b/src/managed/Nota.App/MainWindow.Mosaic.cs
new file mode 100644
index 00000000..334f7c76
--- /dev/null
+++ b/src/managed/Nota.App/MainWindow.Mosaic.cs
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic around the window: the "Create multisample" preview (from a browser folder or
+// files dropped on a Mosaic card), the pack presets the library writes for installed sample
+// packs (the browser lists them under Nota Mosaic → Packs), and a missing pack's "Install".
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Avalonia.Threading;
+using Microsoft.Extensions.DependencyInjection;
+using Nota.Application;
+
+namespace Nota.App;
+
+public partial class MainWindow
+{
+ private void InitMosaic()
+ {
+ var packs = App.Services.GetService<IMosaicPacks>();
+ if (packs is not null)
+ packs.Changed += () => Dispatcher.UIThread.Post(() => _vm?.Browser.Rebuild(), DispatcherPriority.Background);
+ MosaicInstrumentCard.CreateMultisampleRequested += (track, paths) => OpenMosaicCreate(paths, track);
+ MosaicInstrumentCard.InstallPackRequested += _ => ShowPreferences(1); // Downloads → Sample Packs
+ }
+
+ /// <summary>Opens the mapping preview for files / folders. With a Mosaic <paramref name="trackId"/>
+ /// the first preset made also loads there; without one it lands on a new Mosaic track.</summary>
+ private async void OpenMosaicCreate(IReadOnlyList<string> paths, int trackId)
+ {
+ var packs = App.Services.GetService<IMosaicPacks>();
+ if (packs is null || _vm is null || paths.Count == 0) return;
+ var win = new MosaicCreateWindow(packs, paths);
+ await win.ShowDialog(this);
+ if (win.Created.Count == 0) return;
+ _vm.Browser.Rebuild();
+ var (_, prog) = win.Created[0];
+ var engine = _vm.Engine;
+ int t = trackId > 0 && engine.TrackInstrumentKind(trackId) == MosaicModel.Kind ? trackId : -1;
+ if (t < 0) { t = engine.AddMosaicTrack(); engine.AddMidiClip(t, 0.0, 4.0); }
+ engine.MosaicSetProgram(t, prog.Serialize());
+ Timeline.Refresh();
+ ShowDevices(t);
+ _vm.StatusText = win.Created.Count == 1 ? $"Created the preset {prog.Name}" : $"Created {win.Created.Count} presets · loaded {prog.Name}";
+ }
+}
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 33a28da8..a715511f 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -311,10 +311,12 @@ public partial class MainWindow : Window
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.CreateMultisampleRequested += item => OpenMosaicCreate(new[] { item.Path }, -1);
Browser.DeleteProjectRequested += OnBrowserDeleteProject;
Browser.EditTagsRequested += OnBrowserEditTags;
- _deviceChain = new DeviceChainView(vm.Engine, _factory, App.Services.GetService<IPluginCatalog>(), _kits);
+ _deviceChain = new DeviceChainView(vm.Engine, _factory, App.Services.GetService<IPluginCatalog>(), _kits, App.Services.GetService<IMosaicPacks>());
+ InitMosaic();
// A pad added / removed / renamed in the Drum Rack card changes the pattern grid's rows.
_deviceChain.Changed += () => { Timeline.Refresh(); _patternView?.Reload(); if (_modular?.IsVisible == true) _modular.Refresh(); };
_deviceChain.DevicesRemapped += Timeline.RemapAutoTargets;
diff --git a/src/managed/Nota.App/Mcp/McpAppServices.cs b/src/managed/Nota.App/Mcp/McpAppServices.cs
index 5aaab693..4f1dcf01 100644
--- a/src/managed/Nota.App/Mcp/McpAppServices.cs
+++ b/src/managed/Nota.App/Mcp/McpAppServices.cs
@@ -91,7 +91,7 @@ public sealed class McpService(
IPluginCatalog pluginCatalog, IFactoryPresets factoryPresets, IPresetStore presetStore, IPresetLibrary presetLibrary,
IAudioExporter exporter, IMidiDeviceService midiDevices, MidiLearnService midiLearn, IDrumKits drumKits,
ProjectVersionsBridge projectVersions, IProjectHistory projectHistory, IModelStore models, IClipAi clipAi,
- ISampleIndex sampleIndex, Nota.Presentation.TransportViewModel transport)
+ ISampleIndex sampleIndex, Nota.Presentation.TransportViewModel transport, IMosaicPacks mosaicPacks)
{
private readonly NotaMcpServer _server = new();
@@ -115,6 +115,7 @@ public sealed class McpService(
s.AddSingleton(models);
s.AddSingleton(clipAi);
s.AddSingleton(sampleIndex);
+ s.AddSingleton(mosaicPacks);
s.AddSingleton<IProjectKeyAccess>(new ProjectKeyAccess(transport));
}
diff --git a/src/managed/Nota.App/MosaicCreateWindow.cs b/src/managed/Nota.App/MosaicCreateWindow.cs
new file mode 100644
index 00000000..ec214fac
--- /dev/null
+++ b/src/managed/Nota.App/MosaicCreateWindow.cs
@@ -0,0 +1,365 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// "Create multisample" — the auto-mapping preview (mockup 2a). Files or a folder go through
+// MultisampleMapper: instruments by name stem on the left (each with its confidence), the
+// octave convention (C4 or C3 = 60, the pitch detector's verdict explained) and the mapping
+// options; on the right the chosen instrument's zone map with what needs a look — gaps where
+// neighbours stretched, duplicates, notes that came from analysis — and every file with the
+// note, layer, round-robin step and release mark it got. "Create N presets" saves one Nota
+// Mosaic preset per checked instrument under Nota Mosaic → Packs → <folder>.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Nota.Application;
+using Nota.Application.Mosaic;
+using static Nota.App.DeviceCardKit;
+using Path = System.IO.Path;
+
+namespace Nota.App;
+
+public sealed class MosaicCreateWindow : NotaWindow
+{
+ /// <summary>The presets written (path + program), in instrument order; empty when cancelled.</summary>
+ public IReadOnlyList<(string Path, MosaicProgram Program)> Created => _created;
+ private readonly List<(string, MosaicProgram)> _created = new();
+
+ private readonly IMosaicPacks _packs;
+ private readonly IReadOnlyList<string> _inputs;
+ private readonly string _folderName;
+ private readonly MultisampleOptions _opt = new();
+ private MultisampleProposal? _prop;
+ private int _sel;
+
+ private readonly StackPanel _instList = new() { Spacing = 3 };
+ private readonly ContentControl _octave = new();
+ private readonly ContentControl _mapping = new();
+ private readonly TextBlock _instTitle = new() { FontSize = 10, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center };
+ private readonly TextBlock _instSub = Mono("", TextTertiary, 8);
+ private readonly MosaicZoneMap _map = new() { Interactive = false };
+ private readonly WrapPanel _issues = new() { Orientation = Orientation.Horizontal };
+ private readonly StackPanel _rows = new();
+ private readonly TextBlock _headerInfo = Mono("", TextTertiary, 8);
+ private readonly TextBlock _where = new() { FontSize = 8.5, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
+ private readonly Button _create = new() { Classes = { "primary" } };
+
+ public MosaicCreateWindow(IMosaicPacks packs, IReadOnlyList<string> inputs, string? breadcrumb = null)
+ {
+ _packs = packs;
+ _inputs = inputs;
+ _folderName = inputs.Count == 1 && Directory.Exists(inputs[0]) ? Path.GetFileName(inputs[0].TrimEnd('/', '\\'))
+ : Path.GetFileName(Path.GetDirectoryName(inputs.FirstOrDefault() ?? "") ?? "Multisamples");
+ if (string.IsNullOrWhiteSpace(_folderName)) _folderName = "Multisamples";
+ Title = "Create multisample";
+ Width = 860; Height = 520; MinWidth = 760; MinHeight = 440;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner;
+ Background = NotaPalette.BgApp;
+
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 12, Margin = new Thickness(12, 8) };
+ head.Children.Add(new TextBlock { Text = "Create multisample", FontSize = 11, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center });
+ var crumb = Mono(breadcrumb ?? _folderName, TextTertiary, 8.5);
+ Grid.SetColumn(crumb, 1); head.Children.Add(crumb);
+ Grid.SetColumn(_headerInfo, 2); head.Children.Add(_headerInfo);
+
+ // Left: instruments · octave · mapping.
+ var left = new StackPanel
+ {
+ Spacing = 6, Width = 210,
+ Children =
+ {
+ Panel("Instruments", new ScrollViewer { Content = _instList, MaxHeight = 190, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled }, "by name stem"),
+ Panel("Octave", _octave),
+ Panel("Mapping", _mapping),
+ },
+ };
+
+ // Right: the chosen instrument.
+ var legend = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center,
+ Children = { LegendItem("stretched", NotaPalette.TextTertiary), LegendItem("next to gap", NotaPalette.Danger), LegendItem("low confidence", NotaPalette.Warning) },
+ };
+ var instHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), ColumnSpacing = 8, Margin = new Thickness(0, 0, 0, 4) };
+ instHead.Children.Add(_instTitle);
+ Grid.SetColumn(_instSub, 1); instHead.Children.Add(_instSub);
+ Grid.SetColumn(legend, 3); instHead.Children.Add(legend);
+ _map.Height = 150;
+ var tableHead = TableRow("FILE", "NOTE", "LAYER", "RR", "RELEASE", "CONF", "", TextTertiary, caps: true);
+ var table = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ table.Children.Add(tableHead);
+ var scroll = new ScrollViewer { Content = _rows };
+ Grid.SetRow(scroll, 1); table.Children.Add(scroll);
+ var right = new Grid { RowDefinitions = new RowDefinitions("Auto,Auto,Auto,*"), RowSpacing = 6 };
+ right.Children.Add(instHead);
+ Grid.SetRow(_map, 1); right.Children.Add(_map);
+ Grid.SetRow(_issues, 2); right.Children.Add(_issues);
+ Grid.SetRow(table, 3); right.Children.Add(table);
+ var rightBox = Box(right);
+
+ var mid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 8, Margin = new Thickness(12, 0, 12, 8) };
+ mid.Children.Add(new ScrollViewer { Content = left, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
+ Grid.SetColumn(rightBox, 1); mid.Children.Add(rightBox);
+
+ var cancel = new Button { Content = "Cancel", Classes = { "ghost" } };
+ cancel.Click += (_, _) => Close();
+ _create.Click += (_, _) => Create();
+ var foot = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), ColumnSpacing = 8, Margin = new Thickness(12, 0, 12, 10) };
+ foot.Children.Add(_where);
+ Grid.SetColumn(cancel, 1); foot.Children.Add(cancel);
+ Grid.SetColumn(_create, 2); foot.Children.Add(_create);
+
+ var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") };
+ root.Children.Add(head);
+ Grid.SetRow(mid, 1); root.Children.Add(mid);
+ Grid.SetRow(foot, 2); root.Children.Add(foot);
+ SetBody(root);
+
+ _instTitle.Text = "Reading the files…";
+ _create.IsEnabled = false;
+ _create.Content = "Create presets";
+ _where.Text = $"Presets will appear in Nota Mosaic → Packs → {_folderName}";
+ Opened += async (_, _) => await MapAsync();
+ }
+
+ // ---- mapping ---------------------------------------------------------------------------------
+ private async Task MapAsync()
+ {
+ var opt = _opt;
+ var inputs = _inputs;
+ var prop = await Task.Run(() =>
+ {
+ var files = new List<string>();
+ foreach (var p in inputs)
+ {
+ if (Directory.Exists(p))
+ {
+ try { files.AddRange(Directory.EnumerateFiles(p, "*", SearchOption.AllDirectories).Where(MultisampleMapper.IsAudio)); } catch { }
+ }
+ else if (MultisampleMapper.IsAudio(p)) files.Add(p);
+ }
+ files.Sort(StringComparer.OrdinalIgnoreCase);
+ return MultisampleMapper.MapFiles(files, opt, _packs.DetectNote);
+ });
+ _prop = prop;
+ if (_opt.OctaveShift is null) _opt.OctaveShift = prop.OctaveShift; // keep the verdict when options change
+ _sel = Math.Clamp(_sel, 0, Math.Max(0, prop.Instruments.Count - 1));
+ Paint();
+ }
+
+ private void Paint()
+ {
+ if (_prop is not { } prop) return;
+ int files = prop.Instruments.Sum(i => i.Files.Count);
+ _headerInfo.Text = $"{files} files · {NotaNum.Bytes(prop.Bytes)}";
+
+ // Instruments.
+ _instList.Children.Clear();
+ for (int i = 0; i < prop.Instruments.Count; i++)
+ {
+ int iv = i;
+ var inst = prop.Instruments[i];
+ bool sel = i == _sel;
+ var check = new CheckBox { IsChecked = inst.Selected, VerticalAlignment = VerticalAlignment.Center, MinWidth = 0 };
+ check.IsCheckedChanged += (_, _) => { inst.Selected = check.IsChecked == true; PaintFoot(); };
+ string layers = inst.Layers.Count > 1 ? string.Join("/", inst.Layers) : $"{inst.Layers.Count} layer";
+ var name = new TextBlock { Text = inst.Stem, FontSize = 9, FontWeight = sel ? FontWeight.SemiBold : FontWeight.Normal, Foreground = sel ? AccentBright : TextPrimary };
+ var sub = Mono($"{inst.Files.Count} files · {inst.Roots} roots · {layers}{(inst.MaxRr > 1 ? $" · rr {inst.MaxRr}" : "")}", TextTertiary, 7.5);
+ var conf = Mono(NotaNum.Unit(inst.Confidence, "0", "%"), inst.Confidence >= 85 ? TextPrimary : NotaPalette.Warning, 8.5);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6 };
+ g.Children.Add(check);
+ var txt = new StackPanel { Spacing = 1, Children = { name, sub } };
+ Grid.SetColumn(txt, 1); g.Children.Add(txt);
+ Grid.SetColumn(conf, 2); g.Children.Add(conf);
+ var b = new Border
+ {
+ Padding = new Thickness(6, 4), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand),
+ BorderBrush = sel ? NotaPalette.BorderBrass : Brushes.Transparent, Background = sel ? NotaPalette.AccentSubtle : Brushes.Transparent, Child = g,
+ };
+ b.PointerPressed += (_, e) => { if (e.Source is CheckBox) return; _sel = iv; Paint(); };
+ _instList.Children.Add(b);
+ }
+ if (prop.Instruments.Count == 0) _instList.Children.Add(new TextBlock { Text = "No audio files with a note in their name or a clear pitch.", FontSize = 8.5, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });
+
+ // Octave.
+ var oct = Segments(new[] { "C4 = 60", "C3 = 60" }, () => (_opt.OctaveShift ?? 0) == 12 ? 1 : 0, iv => { _opt.OctaveShift = iv == 1 ? 12 : 0; Remap(); }, out _, fill: true, fontSize: 8.5);
+ _octave.Content = new StackPanel
+ {
+ Spacing = 5,
+ Children =
+ {
+ oct,
+ new TextBlock { Text = prop.OctaveWhy.Length > 0 ? prop.OctaveWhy : "The names are taken as written (C4 = 60).", FontSize = 8, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap },
+ },
+ };
+
+ // Mapping.
+ var inst0 = prop.Instruments.Count > 0 ? prop.Instruments[Math.Clamp(_sel, 0, prop.Instruments.Count - 1)] : null;
+ var stretch = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 3,
+ Children = { Step("−", () => { _opt.EdgeStretch = Math.Max(0, _opt.EdgeStretch - 1); Remap(); }), Mono($"±{_opt.EdgeStretch} st", TextPrimary, 9), Step("+", () => { _opt.EdgeStretch = Math.Min(48, _opt.EdgeStretch + 1); Remap(); }) },
+ };
+ var layerText = inst0 is null || inst0.Layers.Count <= 1 ? "one layer"
+ : string.Join(" · ", inst0.Layers.Select(l => { var f = inst0.Used.First(x => !x.Release && x.Layer == l); return $"{l} {f.VelLo}–{f.VelHi}"; }));
+ int rel = inst0?.Used.Count(f => f.Release) ?? 0;
+ var rrSeg = Segments(new[] { "Seq", "Rnd", "No repeat" }, () => _opt.RrMode, iv => { _opt.RrMode = iv; }, out _, fill: true, fontSize: 8);
+ _mapping.Content = new StackPanel
+ {
+ Spacing = 5,
+ Children =
+ {
+ KV("Edge zone stretch", stretch),
+ new TextBlock { Text = "Velocity layers by dynamics", FontSize = 8.5, Foreground = TextSecondary },
+ Mono(layerText, TextPrimary, 8.5),
+ KV("Release samples → Release group", Mono(rel.ToString(NotaNum.Culture), TextPrimary, 9)),
+ KV("Round-robin", Mono(inst0?.MaxRr > 1 ? $"rr {inst0.MaxRr}" : "none", TextPrimary, 9)),
+ rrSeg,
+ },
+ };
+
+ PaintInstrument(inst0);
+ PaintFoot();
+ }
+
+ private void PaintInstrument(MappedInstrument? inst)
+ {
+ _rows.Children.Clear();
+ _issues.Children.Clear();
+ _map.Flagged.Clear();
+ if (inst is null) { _instTitle.Text = "—"; _instSub.Text = ""; _map.Set(Array.Empty<MosaicZone>(), false, -1, "nothing to map"); return; }
+ var prog = MultisampleMapper.Build(inst, _opt);
+ var (lo, hi) = inst.Span;
+ _instTitle.Text = inst.Stem;
+ _instSub.Text = $"{MosaicNames.NoteName(lo)} – {MosaicNames.NoteName(hi)} · {prog.Zones.Count} zones";
+ foreach (var g in inst.Gaps) _map.Flagged.Add(g);
+ _map.Set(prog.Zones, false, -1);
+
+ foreach (var g in inst.Gaps)
+ _issues.Children.Add(Chip($"Gap at {MosaicNames.NoteName(g)} — neighbours stretched", NotaPalette.Danger));
+ int dups = inst.Files.Count(f => f.Duplicate);
+ if (dups > 0) _issues.Children.Add(Chip($"{dups} duplicate{(dups == 1 ? "" : "s")}", NotaPalette.Danger));
+ int an = inst.Files.Count(f => f.NoteFrom == "analysis");
+ if (an > 0) _issues.Children.Add(Chip($"{an} note{(an == 1 ? "" : "s")} from sample analysis", NotaPalette.Warning));
+ int none = inst.Files.Count(f => f.Note < 0);
+ if (none > 0) _issues.Children.Add(Chip($"{none} without a note — left out", NotaPalette.TextTertiary));
+
+ foreach (var f in inst.Files.OrderBy(f => f.Duplicate).ThenBy(f => f.Note).ThenBy(f => f.Name, StringComparer.Ordinal))
+ {
+ string note = f.Note < 0 ? "—" : f.NoteFrom == "analysis" ? $"{f.NoteText} · analysis"
+ : f.NamedNote != f.Note ? $"{MosaicNames.NoteName(f.NamedNote)} → {f.NoteText}"
+ : f.NoteFrom == "midi" ? $"{f.NoteText} · MIDI" : f.NoteText;
+ string action = f.Duplicate ? "duplicate" : f.Note < 0 ? "skipped" : f.LayerGuessed ? "layer?" : "";
+ IBrush ink = f.Duplicate || f.Note < 0 ? TextTertiary : TextPrimary;
+ var row = TableRow(f.Name, note, f.Release ? "—" : f.Layer.Length > 0 ? f.Layer : "—", f.Rr > 0 ? f.Rr.ToString(NotaNum.Culture) : "—",
+ f.Release ? "rel" : "—", f.Confidence > 0 ? f.Confidence.ToString(NotaNum.Culture) : "—", action, ink, strike: f.Duplicate,
+ confInk: f.Confidence > 0 && f.Confidence < 80 ? NotaPalette.Warning : null, actionInk: f.Duplicate ? NotaPalette.DangerBright : NotaPalette.AccentBright);
+ if (f.Duplicate || f.NoteFrom == "analysis") row.Background = NotaPalette.Wash(NotaPalette.Danger, 0x14);
+ _rows.Children.Add(row);
+ }
+ }
+
+ private void PaintFoot()
+ {
+ int n = _prop?.Instruments.Count(i => i.Selected && i.Used.Any()) ?? 0;
+ _create.Content = n == 1 ? "Create 1 preset" : $"Create {n} presets";
+ _create.IsEnabled = n > 0;
+ }
+
+ private async void Remap()
+ {
+ _instTitle.Text = "Mapping…";
+ var keep = _prop?.Instruments.Where(i => !i.Selected).Select(i => i.Stem).ToHashSet() ?? new HashSet<string>();
+ await MapAsync();
+ if (_prop is not null) foreach (var i in _prop.Instruments) i.Selected = !keep.Contains(i.Stem);
+ Paint();
+ }
+
+ private void Create()
+ {
+ if (_prop is null) return;
+ var chosen = _prop.Instruments.Where(i => i.Selected && i.Used.Any()).ToList();
+ foreach (var inst in chosen)
+ {
+ string name = chosen.Count == 1 && _prop.Instruments.Count == 1 ? MultisampleMapper.Pretty(_folderName.Replace(' ', '_')) : MultisampleMapper.Pretty(inst.Stem);
+ var prog = MultisampleMapper.Build(inst, _opt, _packs.ToRef, name);
+ prog.SourceRef = _inputs.Count == 1 ? _packs.ToRef(_inputs[0]) : "";
+ string path = _packs.Save(prog, name, _folderName);
+ _created.Add((path, prog));
+ }
+ Close();
+ }
+
+ // ---- pieces ------------------------------------------------------------------------------------
+ private static TextBlock Mono(string t, IBrush ink, double fs) => new() { Text = t, FontSize = fs, Foreground = ink, FontFamily = NotaFonts.MonoFamily, VerticalAlignment = VerticalAlignment.Center };
+
+ private static Border Box(Control child) => new()
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ Padding = new Thickness(8), Child = child,
+ };
+
+ private static Border Panel(string title, Control body, string? note = null)
+ {
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(0, 0, 0, 5) };
+ head.Children.Add(new TextBlock { Text = title.ToUpperInvariant(), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold, LetterSpacing = NotaType.SectionLabelTracking, Foreground = TextTertiary });
+ if (note is not null) { var n = Mono(note, TextTertiary, 7.5); Grid.SetColumn(n, 1); head.Children.Add(n); }
+ return Box(new StackPanel { Children = { head, body } });
+ }
+
+ private static Control KV(string k, Control v)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ g.Children.Add(new TextBlock { Text = k, FontSize = 8.5, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center });
+ Grid.SetColumn(v, 1); g.Children.Add(v);
+ return g;
+ }
+
+ private static Control Step(string glyph, Action click)
+ {
+ var b = new Border
+ {
+ Width = 16, Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderDef, Background = NotaPalette.SurfaceRaised,
+ Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = glyph, FontSize = 9, Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },
+ };
+ b.PointerPressed += (_, e) => { if (e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) { click(); e.Handled = true; } };
+ return b;
+ }
+
+ private static Control Chip(string text, IBrush ink) => new Border
+ {
+ Margin = new Thickness(0, 0, 6, 4), Padding = new Thickness(7, 2), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = ink,
+ Background = NotaPalette.Wash(NotaPalette.SurfaceRaised, 0xCC), Child = new TextBlock { Text = text, FontSize = 8, Foreground = TextPrimary },
+ };
+
+ private static Control LegendItem(string text, IBrush ink) => new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 4,
+ Children = { new Border { Width = 8, Height = 8, BorderBrush = ink, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, VerticalAlignment = VerticalAlignment.Center }, Mono(text, TextTertiary, 7.5) },
+ };
+
+ private static Border TableRow(string file, string note, string layer, string rr, string rel, string conf, string action, IBrush ink,
+ bool caps = false, bool strike = false, IBrush? confInk = null, IBrush? actionInk = null)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,110,48,30,48,40,60"), ColumnSpacing = 6, Height = caps ? 16 : 18 };
+ string[] cells = { file, note, layer, rr, rel, conf, action };
+ for (int i = 0; i < cells.Length; i++)
+ {
+ var tb = caps
+ ? new TextBlock { Text = cells[i], FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold, LetterSpacing = NotaType.KnobLabelTracking, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center }
+ : Mono(cells[i], i == 5 && confInk is not null ? confInk : i == 6 ? actionInk ?? TextTertiary : ink, 8.5);
+ tb.TextTrimming = TextTrimming.CharacterEllipsis;
+ if (strike && i == 0) tb.TextDecorations = TextDecorations.Strikethrough;
+ if (i == 6) tb.HorizontalAlignment = HorizontalAlignment.Right;
+ Grid.SetColumn(tb, i); g.Children.Add(tb);
+ }
+ return new Border { Padding = new Thickness(6, 0), Child = g, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 0, 0, caps ? 1 : 0) };
+ }
+}
diff --git a/src/managed/Nota.App/NotaDocs.cs b/src/managed/Nota.App/NotaDocs.cs
index 76b5dd53..04a52e5e 100644
--- a/src/managed/Nota.App/NotaDocs.cs
+++ b/src/managed/Nota.App/NotaDocs.cs
@@ -23,7 +23,7 @@ internal static class NotaDocs
"racks/drum-rack", "instruments/aurora", "instruments/volt", "instruments/bass",
"instruments/pendulum", "instruments/operator", "instruments/grain", "instruments/flux",
"instruments/rhythm", "instruments/monolith", "instruments/pentad", "instruments/consort",
- "instruments/keys",
+ "instruments/keys", "instruments/mosaic",
};
private static readonly string[] AudioEffects =
{
diff --git a/src/managed/Nota.App/PreferencesWindow.Samples.cs b/src/managed/Nota.App/PreferencesWindow.Samples.cs
index 88a6066d..47645229 100644
--- a/src/managed/Nota.App/PreferencesWindow.Samples.cs
+++ b/src/managed/Nota.App/PreferencesWindow.Samples.cs
@@ -318,7 +318,9 @@ public sealed partial class PreferencesWindow
if (_samples.Installed.FirstOrDefault(i => i.Id == p.Id) is { } installed)
App.Services.GetRequiredService<ISampleIndex>().Prioritize(installed.Path);
main?.Browser.RebuildSamples();
- return Task.FromResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab, where it is being analysed for tempo and key.");
+ // Its instruments become Nota Mosaic presets (Packs → the pack) in the background.
+ _ = App.Services.GetService<IMosaicPacks>()?.ScanAsync();
+ return Task.FromResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab, where it is being analysed for tempo and key; its instruments appear under Nota Mosaic → Packs.");
});
}
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index 107e9d7b..a3ecc1d4 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -145,6 +145,23 @@ public struct NotaSamplerInfo
public int Loop; // 0/1
}
+/// <summary>Nota Mosaic's loading state. Matches native NotaMosaicStatus. State: 0 empty ·
+/// 1 loading · 2 ready; Disk* are the files' bytes on disk (progress), RamBytes the decoded
+/// samples' size; Missing = files that didn't decode.</summary>
+[StructLayout(LayoutKind.Sequential)]
+public struct NotaMosaicStatus
+{
+ public int State;
+ public int FilesDone;
+ public int FilesTotal;
+ public int Missing;
+ public int Zones;
+ public int Serial; // changes whenever another program is set
+ public long DiskDone;
+ public long DiskTotal;
+ public long RamBytes;
+}
+
/// <summary>Captured session audio take. Matches native NotaSessionAudioSlot (M7-6b).</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NotaSessionAudioSlot
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 2d49aede..95c676d5 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -376,6 +376,19 @@ public interface IAudioEngine : IDisposable
int AddConsortTrack();
/// <summary>Adds an instrument track with the built-in Nota Keys modelled electric piano (kind 16).</summary>
int AddKeysTrack();
+ /// <summary>Adds an instrument track with the built-in Nota Mosaic multisample instrument (kind 17),
+ /// empty until a program is set.</summary>
+ int AddMosaicTrack();
+ /// <summary>Sets a Nota Mosaic's program (MosaicProgram text) and starts loading its samples in
+ /// the background. <paramref name="undoable"/>: one undo step (sounding notes stop); false edits
+ /// the live instrument in place (a drag in progress). False when the track isn't a Mosaic.</summary>
+ bool MosaicSetProgram(int trackId, string text, bool undoable = true);
+ /// <summary>The Mosaic's program text ("" when none / not a Mosaic).</summary>
+ string MosaicProgram(int trackId);
+ /// <summary>The Mosaic's loading state; false when the track isn't a Mosaic.</summary>
+ bool TryGetMosaicStatus(int trackId, out NotaMosaicStatus status);
+ /// <summary>The sample id behind a zone (for TryGetSampleInfo / ReadSample), 0 = not loaded.</summary>
+ long MosaicZoneSampleId(int trackId, int zone);
/// <summary>UI editing channel for the track's instrument (e.g. Rhythm step patterns).</summary>
void InstrumentAction(int trackId, int id, int iarg, float farg);
/// <summary>Loads a sample file into a Nota Grain track (kind 10). True on success.</summary>
diff --git a/src/managed/Nota.Application/Engine/IAuditionRig.cs b/src/managed/Nota.Application/Engine/IAuditionRig.cs
index 4522aea0..0e3705bf 100644
--- a/src/managed/Nota.Application/Engine/IAuditionRig.cs
+++ b/src/managed/Nota.Application/Engine/IAuditionRig.cs
@@ -26,6 +26,8 @@ public interface IAuditionRig : IDisposable
/// <summary>The Sampler's or Nota Grain's sample, played at its own pitch on
/// <paramref name="rootNote"/>; null = the Sampler's procedural keys tone at C4.</summary>
bool SetSamplerSample(string? path, int rootNote = 60);
+ /// <summary>Nota Mosaic's program (MosaicProgram text); returns once its samples are loaded.</summary>
+ bool SetMosaicProgram(string text);
/// <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>
diff --git a/src/managed/Nota.Application/Instruments/Mosaic/MosaicProgram.cs b/src/managed/Nota.Application/Instruments/Mosaic/MosaicProgram.cs
new file mode 100644
index 00000000..46029ba2
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/Mosaic/MosaicProgram.cs
@@ -0,0 +1,291 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic's program: files, groups (layers) and zones — the map the instrument plays.
+// It travels as text (the engine parses the same grammar, see native Mosaic.h): one record
+// per line, "key=value" tokens, names and paths %-escaped. The text is what a project and a
+// preset store; samples are referenced, never copied: "samples:<rel>" resolves against the
+// user's Samples folder, "data:<rel>" against Nota's data folder, anything else is a path.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+
+namespace Nota.Application.Mosaic;
+
+/// <summary>A sample on a key × velocity rectangle. Frames are the sample's own (−1 = its edge).</summary>
+public sealed class MosaicZone
+{
+ public int File = -1, Group, Root = 60;
+ public int KeyLo, KeyHi = 127, VelLo, VelHi = 127;
+ public double Tune, GainDb, Pan; // cents · dB · −1..+1
+ public double Start, End = -1, LoopStart = -1, LoopEnd = -1;
+ public int LoopMode; // 0 off · 1 forward · 2 ping-pong
+ public double Crossfade; // loop crossfade, seconds
+ public int Seq = 1; // round-robin step (1-based)
+ public double RandLo, RandHi = 1; // SFZ lorand / hirand
+ public int XKeyInLo = -1, XKeyInHi = -1, XKeyOutLo = -1, XKeyOutHi = -1;
+ public int XVelInLo = -1, XVelInHi = -1, XVelOutLo = -1, XVelOutHi = -1;
+ public bool Release; // a release trigger
+ public int Excl, OffBy; // exclusive group · off by
+ public bool OffNormal; // off_mode normal (release) vs fast
+
+ public MosaicZone Clone() => (MosaicZone)MemberwiseClone();
+ public bool Covers(int key, int vel) => key >= KeyLo && key <= KeyHi && vel >= VelLo && vel <= VelHi;
+}
+
+/// <summary>A layer: shared gain / tune and a round-robin.</summary>
+public sealed class MosaicGroup
+{
+ public string Name = "";
+ public double GainDb, Tune;
+ public int RrMode; // 0 sequential · 1 random · 2 random without repeat
+ public int SeqLen = 1;
+ public MosaicGroup Clone() => (MosaicGroup)MemberwiseClone();
+}
+
+public sealed class MosaicProgram
+{
+ public const int Version = 1;
+ public static readonly string[] RrNames = { "Sequential", "Random", "No repeat" };
+
+ public string Name = "";
+ /// <summary>Where it came from: "sfz" · "folder" · "files" · "factory" · "sample" · "" (informational).</summary>
+ public string SourceKind = "";
+ public string SourceRef = "";
+ /// <summary>The registry pack the samples come from ("" = none) and its display name.</summary>
+ public string PackId = "", PackName = "";
+ /// <summary>SFZ articulation state (CC number → value) the zones were imported with.</summary>
+ public SortedDictionary<int, int> Ccs = new();
+ public List<string> Files = new();
+ public List<MosaicGroup> Groups = new();
+ public List<MosaicZone> Zones = new();
+
+ public bool IsEmpty => Zones.Count == 0;
+
+ public MosaicProgram Clone()
+ {
+ var p = (MosaicProgram)MemberwiseClone();
+ p.Ccs = new SortedDictionary<int, int>(Ccs);
+ p.Files = new List<string>(Files);
+ p.Groups = Groups.Select(g => g.Clone()).ToList();
+ p.Zones = Zones.Select(z => z.Clone()).ToList();
+ return p;
+ }
+
+ /// <summary>A program of one sample spanning the whole keyboard (a dropped file, a Sampler sound).</summary>
+ public static MosaicProgram Single(string fileRef, int root, string name, bool loop = false)
+ {
+ var p = new MosaicProgram { Name = name, SourceKind = "sample" };
+ p.Files.Add(fileRef);
+ p.Groups.Add(new MosaicGroup { Name = "Sample" });
+ p.Zones.Add(new MosaicZone { File = 0, Root = Math.Clamp(root, 0, 127), LoopMode = loop ? 1 : 0 });
+ return p;
+ }
+
+ // ---- reading ---------------------------------------------------------------------------
+ public IEnumerable<int> Roots => Zones.Where(z => !z.Release).Select(z => z.Root).Distinct().OrderBy(r => r);
+ public int VelocityLayers => Zones.Where(z => !z.Release).Select(z => (z.VelLo, z.VelHi)).Distinct().Count();
+ public int ReleaseZones => Zones.Count(z => z.Release);
+ public int MaxRoundRobin => Groups.Count == 0 ? 1 : Groups.Max(g => g.SeqLen);
+ public (int Lo, int Hi) KeySpan => Zones.Count == 0 ? (0, 127) : (Zones.Min(z => z.KeyLo), Zones.Max(z => z.KeyHi));
+ public string FileName(int file) => file >= 0 && file < Files.Count ? MosaicPaths.FileName(Files[file]) : "";
+
+ /// <summary>"30 roots × 4 velocity layers · release 30".</summary>
+ public string Summary()
+ {
+ if (IsEmpty) return "no zones";
+ int roots = Roots.Count(), layers = VelocityLayers, rel = ReleaseZones, rr = MaxRoundRobin;
+ var sb = new StringBuilder();
+ sb.Append(roots).Append(roots == 1 ? " root" : " roots");
+ if (layers > 1) sb.Append(" × ").Append(layers).Append(" velocity layers");
+ if (rr > 1) sb.Append(" · rr ").Append(rr);
+ if (rel > 0) sb.Append(" · release ").Append(rel);
+ return sb.ToString();
+ }
+
+ // ---- text --------------------------------------------------------------------------------
+ private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
+ private static string N(double v) => Math.Round(v, 6).ToString("0.######", Inv);
+
+ public string Serialize()
+ {
+ var sb = new StringBuilder();
+ sb.Append("mosaic ").Append(Version).Append('\n');
+ if (Name.Length > 0) sb.Append("name ").Append(Escape(Name)).Append('\n');
+ if (SourceKind.Length > 0) sb.Append("source ").Append(Escape(SourceKind)).Append(' ').Append(Escape(SourceRef)).Append('\n');
+ if (PackId.Length > 0) sb.Append("pack ").Append(Escape(PackId)).Append(' ').Append(Escape(PackName)).Append('\n');
+ if (Ccs.Count > 0) sb.Append("ccs ").Append(string.Join(' ', Ccs.Select(kv => $"{kv.Key}={kv.Value}"))).Append('\n');
+ foreach (var f in Files) sb.Append("file ").Append(Escape(f)).Append('\n');
+ foreach (var g in Groups)
+ sb.Append("group gain=").Append(N(g.GainDb)).Append(" tune=").Append(N(g.Tune))
+ .Append(" rr=").Append(g.RrMode).Append(" seq=").Append(g.SeqLen)
+ .Append(" name=").Append(Escape(g.Name)).Append('\n');
+ foreach (var z in Zones)
+ {
+ sb.Append("zone f=").Append(z.File).Append(" g=").Append(z.Group).Append(" root=").Append(z.Root)
+ .Append(" klo=").Append(z.KeyLo).Append(" khi=").Append(z.KeyHi)
+ .Append(" vlo=").Append(z.VelLo).Append(" vhi=").Append(z.VelHi);
+ if (z.Tune != 0) sb.Append(" tune=").Append(N(z.Tune));
+ if (z.GainDb != 0) sb.Append(" gain=").Append(N(z.GainDb));
+ if (z.Pan != 0) sb.Append(" pan=").Append(N(z.Pan));
+ if (z.Start > 0) sb.Append(" s=").Append(N(z.Start));
+ if (z.End >= 0) sb.Append(" e=").Append(N(z.End));
+ if (z.LoopMode != 0) sb.Append(" lm=").Append(z.LoopMode);
+ if (z.LoopStart >= 0) sb.Append(" ls=").Append(N(z.LoopStart));
+ if (z.LoopEnd >= 0) sb.Append(" le=").Append(N(z.LoopEnd));
+ if (z.Crossfade > 0) sb.Append(" xf=").Append(N(z.Crossfade));
+ if (z.Seq != 1) sb.Append(" seq=").Append(z.Seq);
+ if (z.RandLo > 0) sb.Append(" rlo=").Append(N(z.RandLo));
+ if (z.RandHi < 1) sb.Append(" rhi=").Append(N(z.RandHi));
+ void X(string k, int v) { if (v >= 0) sb.Append(' ').Append(k).Append('=').Append(v); }
+ X("xkil", z.XKeyInLo); X("xkih", z.XKeyInHi); X("xkol", z.XKeyOutLo); X("xkoh", z.XKeyOutHi);
+ X("xvil", z.XVelInLo); X("xvih", z.XVelInHi); X("xvol", z.XVelOutLo); X("xvoh", z.XVelOutHi);
+ if (z.Release) sb.Append(" trig=1");
+ if (z.Excl != 0) sb.Append(" excl=").Append(z.Excl);
+ if (z.OffBy != 0) sb.Append(" off=").Append(z.OffBy);
+ if (z.OffNormal) sb.Append(" om=1");
+ sb.Append('\n');
+ }
+ return sb.ToString();
+ }
+
+ public static MosaicProgram Parse(string? text)
+ {
+ var p = new MosaicProgram();
+ if (string.IsNullOrEmpty(text)) return p;
+ foreach (var raw in text.Split('\n'))
+ {
+ var line = raw.TrimEnd('\r');
+ var tok = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
+ if (tok.Length == 0) continue;
+ string? Kv(string key)
+ {
+ for (int t = 1; t < tok.Length; t++)
+ if (tok[t].Length > key.Length && tok[t].StartsWith(key, StringComparison.Ordinal) && tok[t][key.Length] == '=')
+ return tok[t][(key.Length + 1)..];
+ return null;
+ }
+ double D(string key, double def) => Kv(key) is { } s && double.TryParse(s, NumberStyles.Float, Inv, out var v) ? v : def;
+ int I(string key, int def) => (int)Math.Round(D(key, def));
+ switch (tok[0])
+ {
+ case "name" when tok.Length >= 2: p.Name = Unescape(tok[1]); break;
+ case "source" when tok.Length >= 2: p.SourceKind = Unescape(tok[1]); p.SourceRef = tok.Length >= 3 ? Unescape(tok[2]) : ""; break;
+ case "pack" when tok.Length >= 2: p.PackId = Unescape(tok[1]); p.PackName = tok.Length >= 3 ? Unescape(tok[2]) : ""; break;
+ case "ccs":
+ for (int t = 1; t < tok.Length; t++)
+ {
+ var kv = tok[t].Split('=');
+ if (kv.Length == 2 && int.TryParse(kv[0], NumberStyles.Integer, Inv, out int cc) && int.TryParse(kv[1], NumberStyles.Integer, Inv, out int val))
+ p.Ccs[cc] = val;
+ }
+ break;
+ case "file" when tok.Length >= 2: p.Files.Add(Unescape(tok[1])); break;
+ case "group":
+ p.Groups.Add(new MosaicGroup
+ {
+ Name = Kv("name") is { } n ? Unescape(n) : "",
+ GainDb = D("gain", 0), Tune = D("tune", 0),
+ RrMode = Math.Clamp(I("rr", 0), 0, 2), SeqLen = Math.Clamp(I("seq", 1), 1, 64),
+ });
+ break;
+ case "zone":
+ p.Zones.Add(new MosaicZone
+ {
+ File = I("f", -1), Group = I("g", 0), Root = Math.Clamp(I("root", 60), 0, 127),
+ KeyLo = Math.Clamp(I("klo", 0), 0, 127), KeyHi = Math.Clamp(I("khi", 127), 0, 127),
+ VelLo = Math.Clamp(I("vlo", 0), 0, 127), VelHi = Math.Clamp(I("vhi", 127), 0, 127),
+ Tune = D("tune", 0), GainDb = D("gain", 0), Pan = Math.Clamp(D("pan", 0), -1, 1),
+ Start = Math.Max(0, D("s", 0)), End = D("e", -1),
+ LoopMode = Math.Clamp(I("lm", 0), 0, 2), LoopStart = D("ls", -1), LoopEnd = D("le", -1),
+ Crossfade = Math.Clamp(D("xf", 0), 0, 2), Seq = Math.Max(1, I("seq", 1)),
+ RandLo = D("rlo", 0), RandHi = D("rhi", 1),
+ XKeyInLo = I("xkil", -1), XKeyInHi = I("xkih", -1), XKeyOutLo = I("xkol", -1), XKeyOutHi = I("xkoh", -1),
+ XVelInLo = I("xvil", -1), XVelInHi = I("xvih", -1), XVelOutLo = I("xvol", -1), XVelOutHi = I("xvoh", -1),
+ Release = D("trig", 0) >= 0.5, Excl = I("excl", 0), OffBy = I("off", 0), OffNormal = D("om", 0) >= 0.5,
+ });
+ break;
+ }
+ }
+ if (p.Groups.Count == 0) p.Groups.Add(new MosaicGroup { Name = "Group 1" });
+ p.Zones.RemoveAll(z => z.File < 0 || z.File >= p.Files.Count);
+ foreach (var z in p.Zones) z.Group = Math.Clamp(z.Group, 0, p.Groups.Count - 1);
+ return p;
+ }
+
+ /// <summary>%-escapes bytes at or below space, '%' and '=' (UTF-8 stays as it is).</summary>
+ public static string Escape(string s)
+ {
+ if (string.IsNullOrEmpty(s)) return "";
+ var sb = new StringBuilder(s.Length + 8);
+ foreach (char c in s)
+ {
+ if (c <= ' ' || c == '%' || c == '=') sb.Append('%').Append(((int)c).ToString("X2", Inv));
+ else sb.Append(c);
+ }
+ return sb.ToString();
+ }
+
+ public static string Unescape(string s)
+ {
+ if (s.IndexOf('%') < 0) return s;
+ var bytes = new List<byte>(s.Length);
+ var src = Encoding.UTF8.GetBytes(s);
+ for (int i = 0; i < src.Length; i++)
+ {
+ if (src[i] == '%' && i + 2 < src.Length && Hex(src[i + 1]) >= 0 && Hex(src[i + 2]) >= 0)
+ {
+ bytes.Add((byte)(Hex(src[i + 1]) * 16 + Hex(src[i + 2]))); i += 2;
+ }
+ else bytes.Add(src[i]);
+ }
+ return Encoding.UTF8.GetString(bytes.ToArray());
+ static int Hex(byte b) => b is >= (byte)'0' and <= (byte)'9' ? b - '0' : b is >= (byte)'a' and <= (byte)'f' ? b - 'a' + 10 : b is >= (byte)'A' and <= (byte)'F' ? b - 'A' + 10 : -1;
+ }
+}
+
+/// <summary>Sample references: "samples:<rel>" / "data:<rel>" against the host's roots, else a path.</summary>
+public static class MosaicPaths
+{
+ public const string SamplesRoot = "samples", DataRoot = "data";
+
+ /// <summary>A portable reference for an absolute path: relative to the Samples folder or
+ /// the data folder when inside one of them (forward slashes), else the path itself.</summary>
+ public static string ToRef(string path, string? samplesFolder, string? dataFolder)
+ {
+ string full;
+ try { full = System.IO.Path.GetFullPath(path); } catch { return path; }
+ foreach (var (name, root) in new[] { (SamplesRoot, samplesFolder), (DataRoot, dataFolder) })
+ {
+ if (string.IsNullOrEmpty(root)) continue;
+ string r;
+ try { r = System.IO.Path.GetFullPath(root).TrimEnd('/', '\\'); } catch { continue; }
+ if (full.Length > r.Length + 1 && full.StartsWith(r, StringComparison.OrdinalIgnoreCase) && (full[r.Length] == '/' || full[r.Length] == '\\'))
+ return name + ":" + full[(r.Length + 1)..].Replace('\\', '/');
+ }
+ return full;
+ }
+
+ /// <summary>The absolute path a reference names, given the roots (null when a root is unknown).</summary>
+ public static string? Resolve(string reference, string? samplesFolder, string? dataFolder)
+ {
+ int colon = reference.IndexOf(':');
+ if (colon >= 2 && !reference.StartsWith('/'))
+ {
+ string name = reference[..colon];
+ string? root = name == SamplesRoot ? samplesFolder : name == DataRoot ? dataFolder : null;
+ if (name is SamplesRoot or DataRoot)
+ return string.IsNullOrEmpty(root) ? null : System.IO.Path.Combine(root, reference[(colon + 1)..].Replace('/', System.IO.Path.DirectorySeparatorChar));
+ }
+ return reference;
+ }
+
+ public static string FileName(string reference)
+ {
+ int cut = Math.Max(reference.LastIndexOf('/'), Math.Max(reference.LastIndexOf('\\'), reference.IndexOf(':') >= 2 ? reference.IndexOf(':') : -1));
+ return cut >= 0 ? reference[(cut + 1)..] : reference;
+ }
+}
diff --git a/src/managed/Nota.Application/Instruments/Mosaic/MultisampleMapper.cs b/src/managed/Nota.Application/Instruments/Mosaic/MultisampleMapper.cs
new file mode 100644
index 00000000..42361ffe
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/Mosaic/MultisampleMapper.cs
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Auto-multisample: a folder of "trombone_gb4.wav", "trombone_f_c3_rr2.wav",
+// "trombone_a2_rel.wav" … becomes Nota Mosaic programs, one per instrument.
+//
+// 1. Each file name splits into tokens: the note (gb4, c#3, db2, cs4, a MIDI number
+// "_060" / "n60"), a velocity layer (pp … fff, v1 … vN, vel3, soft / med / hard), a
+// round-robin step (rr2, seq2), a release mark (rel, release). The rest is the
+// instrument's stem — "trombone" and "trombone_mute" are two instruments. Words that
+// only mark a take ("take3", "copy", "final") don't make a stem of their own.
+// 2. A file whose name names no note gets one from pitch detection (lower confidence).
+// 3. Octave numbering differs between makers (C3 or C4 = 60). The pitch detector checks a
+// few named files; a steady ±12 shifts the whole set.
+// 4. Layers split velocity 1 … 127 evenly in dynamic order; each root covers the keys up
+// to half-way to its neighbours, the outermost stretch ±N semitones (12 by default).
+// 5. Problems are listed, not hidden: duplicates (same note, layer and step), gaps (where
+// neighbours had to stretch far), notes that only came from analysis.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+namespace Nota.Application.Mosaic;
+
+/// <summary>What the mapper made of one file.</summary>
+public sealed class MappedFile
+{
+ public string Path = "", Name = "", Stem = "";
+ public int Note = -1; // after the octave shift
+ public int NamedNote = -1; // as the name spelled it (before the shift)
+ public string NoteFrom = ""; // "name" · "midi" · "analysis" · ""
+ public string Layer = ""; // the velocity token, "" = one layer
+ public bool LayerGuessed; // no layer in the name; joined the softest one
+ public int Rr = 0; // 0 = none
+ public bool Release;
+ public int Confidence; // 0 … 100
+ public bool Duplicate;
+ public int KeyLo = -1, KeyHi = -1, VelLo = 1, VelHi = 127;
+ public bool Stretched, NearGap;
+
+ public string NoteText => Note < 0 ? "—" : MosaicNames.NoteName(Note);
+}
+
+/// <summary>One instrument found in a folder.</summary>
+public sealed class MappedInstrument
+{
+ public string Stem = "";
+ public List<MappedFile> Files = new();
+ public bool Selected = true;
+ public IEnumerable<MappedFile> Used => Files.Where(f => !f.Duplicate && f.Note >= 0);
+ public int Roots => Used.Where(f => !f.Release).Select(f => f.Note).Distinct().Count();
+ public List<string> Layers => Used.Where(f => !f.Release).Select(f => f.Layer).Distinct().OrderBy(MultisampleMapper.LayerOrder).ToList();
+ public int MaxRr => Used.Select(f => f.Rr).DefaultIfEmpty(0).Max();
+ public int Confidence => Used.Any() ? (int)Math.Round(Used.Average(f => f.Confidence)) : 0;
+ public (int Lo, int Hi) Span => Used.Any() ? (Used.Min(f => f.KeyLo), Used.Max(f => f.KeyHi)) : (0, 0);
+ public List<int> Gaps = new(); // root-less keys where neighbours stretched more than 2 st
+}
+
+public sealed class MultisampleOptions
+{
+ /// <summary>How far the outermost roots stretch past themselves, semitones.</summary>
+ public int EdgeStretch = 12;
+ /// <summary>Semitones added to every named note (+12 when C3 = 60). Null = detect.</summary>
+ public int? OctaveShift;
+ public bool ReleaseGroup = true;
+ public int RrMode = 2; // random without repeat
+}
+
+public sealed class MultisampleProposal
+{
+ public string Folder = "";
+ public List<MappedInstrument> Instruments = new();
+ public int OctaveShift; // what was applied
+ public string OctaveWhy = ""; // "Pitch detector on 3 files (gb4, c3, f2): offset is a stable +12."
+ public int Unmapped; // files with no note at all
+ public long Bytes;
+}
+
+public static class MultisampleMapper
+{
+ private static readonly string[] Dynamics = { "pppp", "ppp", "pp", "p", "mp", "mf", "f", "ff", "fff", "ffff" };
+ private static readonly string[] Softness = { "soft", "med", "medium", "mid", "hard", "loud" };
+ private static readonly HashSet<string> Noise = new(StringComparer.OrdinalIgnoreCase)
+ { "take", "copy", "final", "edit", "new", "old", "mono", "stereo", "st", "norm", "normalized", "trimmed", "sample", "samp", "smp" };
+ public static readonly string[] AudioExtensions = { ".wav", ".flac", ".mp3", ".aif", ".aiff" };
+
+ /// <summary>Velocity-layer sort key: dynamics in musical order, then numbers.</summary>
+ public static int LayerOrder(string layer)
+ {
+ if (layer.Length == 0) return 0;
+ int d = Array.IndexOf(Dynamics, layer);
+ if (d >= 0) return 100 + d;
+ int s = Array.IndexOf(Softness, layer);
+ if (s >= 0) return 200 + s;
+ var m = Regex.Match(layer, @"\d+");
+ return m.Success && int.TryParse(m.Value, out int n) ? 300 + n : 999;
+ }
+
+ // ---- tokens ------------------------------------------------------------------------------
+ private static readonly Regex NoteTok = new(@"^([a-g])(#|s|b|♯|♭)?(-?\d)$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ private static readonly Regex MidiTok = new(@"^n?(\d{2,3})$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ private static readonly Regex VelTok = new(@"^(v|vel|vl|velocity|layer|dyn)(\d{1,3})$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ private static readonly Regex RrTok = new(@"^(rr|seq|robin)(\d{1,2})$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+ private static readonly Regex TakeTok = new(@"^(take|t)(\d{1,2})$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+
+ /// <summary>Parses one file name. Exposed for the tests and the MCP.</summary>
+ public static MappedFile ParseName(string path)
+ {
+ var f = new MappedFile { Path = path, Name = System.IO.Path.GetFileName(path) };
+ string baseName = System.IO.Path.GetFileNameWithoutExtension(path);
+ // Split on separators and on letter→digit-group borders a name glues ("PianoC4" stays one: too risky).
+ var tokens = Regex.Split(baseName, @"[\s_\-\.\(\)\[\]]+").Where(t => t.Length > 0).ToList();
+ var stem = new List<string>();
+ int noteAt = -1;
+ // The note: the last note-like token wins ("bass_16_1_c2", "piano_c4_rel").
+ for (int i = tokens.Count - 1; i >= 0 && f.NamedNote < 0; i--)
+ if (NoteOf(tokens[i]) is { } n) { f.NamedNote = n; f.NoteFrom = "name"; noteAt = i; }
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ if (i == noteAt) continue;
+ string t = tokens[i], tl = t.ToLowerInvariant();
+ if (RrTok.Match(tl) is { Success: true } rm) { f.Rr = int.Parse(rm.Groups[2].Value); continue; }
+ if (tl is "rel" or "release" or "rls" or "relse") { f.Release = true; continue; }
+ if (Array.IndexOf(Dynamics, tl) >= 0 && i > 0) { f.Layer = tl; continue; } // "f" first is a name, not forte
+ if (Array.IndexOf(Softness, tl) >= 0) { f.Layer = tl; continue; }
+ if (VelTok.Match(tl) is { Success: true } vm) { f.Layer = "v" + int.Parse(vm.Groups[2].Value); continue; }
+ if (Noise.Contains(tl) || TakeTok.IsMatch(tl)) continue;
+ stem.Add(tl);
+ }
+ // No note name: a MIDI number among the leftovers (the last one in 0 … 127).
+ if (f.NamedNote < 0)
+ for (int i = stem.Count - 1; i >= 0; i--)
+ if (MidiTok.Match(stem[i]) is { Success: true } mm && int.Parse(mm.Groups[1].Value) is var mn && mn is >= 12 and <= 120)
+ { f.NamedNote = mn; f.NoteFrom = "midi"; stem.RemoveAt(i); break; }
+ f.Stem = stem.Count > 0 ? string.Join("_", stem) : "sample";
+ f.Note = f.NamedNote;
+ f.Confidence = f.NoteFrom switch { "name" => 98, "midi" => 95, _ => 0 };
+ if (f.NoteFrom == "name" && f.Layer.Length == 0 && f.Rr == 0 && !f.Release && stem.Count == 0) f.Confidence = 90;
+ return f;
+ }
+
+ /// <summary>A note token: "c4", "c#3", "db2", "cs4", "gb6", "a-1" (C4 = 60). Null otherwise.</summary>
+ public static int? NoteOf(string token)
+ {
+ var m = NoteTok.Match(token);
+ if (!m.Success) return null;
+ int pc = char.ToLowerInvariant(m.Groups[1].Value[0]) switch { 'c' => 0, 'd' => 2, 'e' => 4, 'f' => 5, 'g' => 7, 'a' => 9, _ => 11 };
+ string acc = m.Groups[2].Value.ToLowerInvariant();
+ if (acc is "#" or "s" or "♯") pc++;
+ else if (acc is "b" or "♭") pc--;
+ int note = (int.Parse(m.Groups[3].Value) + 1) * 12 + pc;
+ return note is >= 0 and <= 127 ? note : null;
+ }
+
+ // ---- the folder ------------------------------------------------------------------------------
+ /// <summary>Maps the audio files under <paramref name="folder"/> (recursively). <paramref name="detect"/>
+ /// returns a file's fundamental as a MIDI note (fractional) or null — pitch detection for files
+ /// without a note in their name and for the octave check; null skips both.</summary>
+ public static MultisampleProposal MapFolder(string folder, MultisampleOptions? opt = null, Func<string, double?>? detect = null)
+ {
+ IEnumerable<string> files;
+ try { files = Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Where(IsAudio).OrderBy(p => p, StringComparer.OrdinalIgnoreCase).ToList(); }
+ catch { files = Array.Empty<string>(); }
+ var prop = MapFiles(files, opt, detect);
+ prop.Folder = folder;
+ return prop;
+ }
+
+ public static bool IsAudio(string path) => AudioExtensions.Contains(System.IO.Path.GetExtension(path).ToLowerInvariant());
+
+ public static MultisampleProposal MapFiles(IEnumerable<string> paths, MultisampleOptions? opt = null, Func<string, double?>? detect = null)
+ {
+ opt ??= new MultisampleOptions();
+ var prop = new MultisampleProposal();
+ var parsed = paths.Select(ParseName).ToList();
+ foreach (var f in parsed) { try { prop.Bytes += new FileInfo(f.Path).Length; } catch { } }
+
+ // Octave check: up to three named files across the range.
+ int shift = opt.OctaveShift ?? 0;
+ if (opt.OctaveShift is null && detect is not null)
+ {
+ var named = parsed.Where(f => f.NoteFrom == "name" && !f.Release).OrderBy(f => f.NamedNote).ToList();
+ var probe = named.Count <= 3 ? named : new List<MappedFile> { named[named.Count / 6], named[named.Count / 2], named[named.Count * 5 / 6] };
+ var offs = new List<int>();
+ foreach (var f in probe)
+ if (detect(f.Path) is { } heard)
+ {
+ int off = (int)Math.Round((heard - f.NamedNote) / 12.0) * 12;
+ offs.Add(off);
+ }
+ if (offs.Count > 0 && offs.All(o => o == offs[0]) && Math.Abs(offs[0]) == 12)
+ {
+ shift = offs[0];
+ prop.OctaveWhy = $"Pitch detector on {offs.Count} files ({string.Join(", ", probe.Take(3).Select(f => ShortNote(f.NamedNote)))}): offset is a stable {(shift > 0 ? "+" : "−")}12. Whole set shifted one octave.";
+ }
+ else if (offs.Count > 0)
+ prop.OctaveWhy = $"Pitch detector on {offs.Count} files agrees with the names.";
+ }
+ prop.OctaveShift = shift;
+ foreach (var f in parsed.Where(f => f.NamedNote >= 0)) f.Note = Math.Clamp(f.NamedNote + shift, 0, 127);
+
+ // Files with no note: pitch detection.
+ foreach (var f in parsed.Where(f => f.Note < 0))
+ {
+ if (detect?.Invoke(f.Path) is { } m)
+ {
+ f.Note = Math.Clamp((int)Math.Round(m), 0, 127);
+ f.NoteFrom = "analysis";
+ double cents = Math.Abs(m - Math.Round(m)) * 100;
+ f.Confidence = (int)Math.Clamp(70 - cents / 2, 40, 70);
+ }
+ else prop.Unmapped++;
+ }
+
+ // Instruments by stem; files with no note at all join their stem but play nothing.
+ foreach (var g in parsed.GroupBy(f => f.Stem).OrderBy(g => g.Key, StringComparer.Ordinal))
+ {
+ var inst = new MappedInstrument { Stem = g.Key, Files = g.ToList() };
+ prop.Instruments.Add(inst);
+ }
+ MergeStragglers(prop);
+ foreach (var inst in prop.Instruments) Layout(inst, opt);
+ // Biggest, most confident first.
+ prop.Instruments = prop.Instruments.OrderByDescending(i => i.Used.Count()).ThenBy(i => i.Stem, StringComparer.Ordinal).ToList();
+ return prop;
+ }
+
+ // A one-file "instrument" whose stem starts with a real instrument's stem is a take of it.
+ private static void MergeStragglers(MultisampleProposal prop)
+ {
+ foreach (var small in prop.Instruments.Where(i => i.Files.Count == 1).ToList())
+ {
+ var host = prop.Instruments.Where(i => i != small && i.Files.Count > 1 && small.Stem.StartsWith(i.Stem + "_", StringComparison.Ordinal))
+ .OrderByDescending(i => i.Stem.Length).FirstOrDefault();
+ if (host is null) continue;
+ foreach (var f in small.Files) f.Stem = host.Stem;
+ host.Files.AddRange(small.Files);
+ prop.Instruments.Remove(small);
+ }
+ }
+
+ // Duplicates, velocity splits, key ranges, gaps.
+ private static void Layout(MappedInstrument inst, MultisampleOptions opt)
+ {
+ var seen = new HashSet<(int, string, int, bool)>();
+ foreach (var f in inst.Files.OrderBy(f => f.Name.Contains("copy", StringComparison.OrdinalIgnoreCase) ? 1 : 0).ThenBy(f => f.Name, StringComparer.Ordinal))
+ {
+ if (f.Note < 0) continue;
+ f.Duplicate = !seen.Add((f.Note, f.Layer, f.Rr, f.Release));
+ }
+ // A file without a layer among layered ones (a stray take) joins the softest layer.
+ var named = inst.Used.Where(f => !f.Release && f.Layer.Length > 0).Select(f => f.Layer).Distinct().OrderBy(LayerOrder).ToList();
+ if (named.Count > 0)
+ foreach (var f in inst.Used.Where(f => !f.Release && f.Layer.Length == 0)) { f.Layer = named[0]; f.LayerGuessed = true; }
+ var layers = inst.Layers;
+ for (int li = 0; li < layers.Count; li++)
+ {
+ // Two layers: 1 – 63 · 64 – 127.
+ int lo = li == 0 ? 1 : (int)Math.Round(126.0 * li / layers.Count) + 1;
+ int hi = li == layers.Count - 1 ? 127 : (int)Math.Round(126.0 * (li + 1) / layers.Count);
+ foreach (var f in inst.Used.Where(f => !f.Release && f.Layer == layers[li])) { f.VelLo = lo; f.VelHi = hi; }
+ }
+ // Key ranges per (layer, rr) — and for the release set.
+ inst.Gaps.Clear();
+ foreach (var set in inst.Used.GroupBy(f => (f.Release, f.Release ? "" : f.Layer, f.Rr)))
+ {
+ var roots = set.Select(f => f.Note).Distinct().OrderBy(n => n).ToList();
+ for (int i = 0; i < roots.Count; i++)
+ {
+ int r = roots[i];
+ int lo = i == 0 ? Math.Max(0, r - opt.EdgeStretch) : (roots[i - 1] + r) / 2 + 1;
+ int hi = i == roots.Count - 1 ? Math.Min(127, r + opt.EdgeStretch) : (r + roots[i + 1]) / 2;
+ foreach (var f in set.Where(f => f.Note == r))
+ {
+ f.KeyLo = lo; f.KeyHi = hi;
+ f.Stretched = r - lo > 2 || hi - r > 2;
+ if (set.Key.Release) { f.VelLo = 1; f.VelHi = 127; }
+ }
+ if (i > 0 && r - roots[i - 1] > 5 && !set.Key.Release)
+ {
+ int gapKey = (roots[i - 1] + r) / 2;
+ if (!inst.Gaps.Contains(gapKey)) inst.Gaps.Add(gapKey);
+ foreach (var f in set.Where(f => f.Note == r || f.Note == roots[i - 1])) f.NearGap = true;
+ }
+ }
+ }
+ }
+
+ /// <summary>The program for one instrument: a group per velocity layer (with its round-robin)
+ /// and a release group. <paramref name="toRef"/> maps a path to the stored reference.</summary>
+ public static MosaicProgram Build(MappedInstrument inst, MultisampleOptions? opt = null, Func<string, string>? toRef = null, string? name = null)
+ {
+ opt ??= new MultisampleOptions();
+ var p = new MosaicProgram { Name = name ?? Pretty(inst.Stem), SourceKind = "folder" };
+ var fileIdx = new Dictionary<string, int>(StringComparer.Ordinal);
+ int FileOf(MappedFile f)
+ {
+ if (!fileIdx.TryGetValue(f.Path, out int i)) { i = p.Files.Count; fileIdx[f.Path] = i; p.Files.Add(toRef is null ? f.Path : toRef(f.Path)); }
+ return i;
+ }
+ var layers = inst.Layers;
+ foreach (var layer in layers)
+ {
+ var g = new MosaicGroup { Name = layers.Count > 1 ? "Sustain · " + (layer.Length > 0 ? layer : "—") : "Sustain", SeqLen = Math.Max(1, inst.Used.Where(f => !f.Release && f.Layer == layer).Select(f => f.Rr).DefaultIfEmpty(0).Max()), RrMode = opt.RrMode };
+ p.Groups.Add(g);
+ int gi = p.Groups.Count - 1;
+ foreach (var f in inst.Used.Where(f => !f.Release && f.Layer == layer).OrderBy(f => f.Note).ThenBy(f => f.Rr))
+ p.Zones.Add(new MosaicZone { File = FileOf(f), Group = gi, Root = f.Note, KeyLo = f.KeyLo, KeyHi = f.KeyHi, VelLo = f.VelLo, VelHi = f.VelHi, Seq = Math.Max(1, f.Rr) });
+ }
+ var rel = inst.Used.Where(f => f.Release).ToList();
+ if (rel.Count > 0 && opt.ReleaseGroup)
+ {
+ p.Groups.Add(new MosaicGroup { Name = "Release", SeqLen = Math.Max(1, rel.Max(f => f.Rr)), RrMode = opt.RrMode });
+ int gi = p.Groups.Count - 1;
+ foreach (var f in rel.OrderBy(f => f.Note))
+ p.Zones.Add(new MosaicZone { File = FileOf(f), Group = gi, Root = f.Note, KeyLo = f.KeyLo, KeyHi = f.KeyHi, VelLo = 0, VelHi = 127, Seq = Math.Max(1, f.Rr), Release = true });
+ }
+ if (p.Groups.Count == 0) p.Groups.Add(new MosaicGroup { Name = "Sustain" });
+ // The lowest layer starts at velocity 0 so a note at 0 isn't silent.
+ foreach (var z in p.Zones) if (z.VelLo == 1) z.VelLo = 0;
+ return p;
+ }
+
+ public static string Pretty(string stem)
+ {
+ var words = stem.Split('_', StringSplitOptions.RemoveEmptyEntries);
+ return string.Join(' ', words.Select(w => w.Length == 0 ? w : char.ToUpperInvariant(w[0]) + w[1..]));
+ }
+
+ private static string ShortNote(int n) => n < 0 ? "?" : MosaicNames.NoteName(n).Replace("♯", "#").ToLowerInvariant();
+}
+
+/// <summary>Note names as Nota writes them (C4 = 60, sharps).</summary>
+public static class MosaicNames
+{
+ private static readonly string[] Pc = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+ public static string NoteName(int n) => n is < 0 or > 127 ? "—" : Pc[n % 12] + (n / 12 - 1);
+}
diff --git a/src/managed/Nota.Application/Instruments/Mosaic/SfzImporter.cs b/src/managed/Nota.Application/Instruments/Mosaic/SfzImporter.cs
new file mode 100644
index 00000000..83a4ff3f
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/Mosaic/SfzImporter.cs
@@ -0,0 +1,454 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// SFZ → a Nota Mosaic program. The subset a sample library needs to play: headers
+// <control> <global> <master> <group> <region> with opcode inheritance down that chain,
+// #define / #include, default_path, Windows paths ("..\Samples\x.wav") and case-insensitive
+// file names; key / velocity ranges, roots, tune / transpose / volume / pan / amplitude,
+// offset / end, loops, release triggers, round-robin (seq_length / seq_position and lorand /
+// hirand), exclusive groups (group / off_by / off_mode), key and velocity crossfades.
+//
+// What the instrument can't do is reported, never silently lost: modulation (CC-driven
+// opcodes, flex EGs, LFOs, curves) is counted per family ("eg06*", "pitcheg*", "tune_cc")
+// for the import summary. Articulations switched by CC (locc / hicc) or keyswitches
+// (sw_last) are resolved at import time against the controllers' starting values
+// (set_ccN, sw_default); importing again with other values picks another articulation.
+// The amp envelope of the first played region is offered as the patch's envelope.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Nota.Application.Mosaic;
+
+public sealed class SfzImportReport
+{
+ public string File = "";
+ public int Regions, Imported, Groups, Includes, PathsFixed, Missing, Generators, Inactive;
+ /// <summary>CC numbers whose value selects regions (locc / hicc), with the value used.</summary>
+ public SortedDictionary<int, int> CcState = new();
+ /// <summary>"label_cc" names, for the articulation picker.</summary>
+ public SortedDictionary<int, string> CcLabels = new();
+ /// <summary>Ignored opcode families → how many regions carried them.</summary>
+ public SortedDictionary<string, int> Ignored = new(StringComparer.Ordinal);
+ public double Seconds;
+ /// <summary>The amp envelope the library asks for (seconds / 0..1), when it names one.</summary>
+ public double? Attack, Decay, Sustain, Release;
+ /// <summary>The pitch-bend range (semitones, from bend_up) and a low-pass cutoff (Hz), when named.</summary>
+ public double? BendSemis, CutoffHz;
+
+ public string Summary()
+ {
+ string head = $"Imported {Imported} zones";
+ if (Ignored.Count == 0) return head;
+ return head + "; ignored: " + string.Join(", ", Ignored.OrderByDescending(kv => kv.Value).Take(4).Select(kv => kv.Key));
+ }
+}
+
+public sealed record SfzResult(MosaicProgram Program, SfzImportReport Report);
+
+public static class SfzImporter
+{
+ private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
+
+ /// <summary>Imports <paramref name="sfzPath"/>. <paramref name="ccOverrides"/> sets controller values
+ /// (an articulation); <paramref name="toRef"/> turns an absolute sample path into the reference the
+ /// program stores (the default keeps the path).</summary>
+ public static SfzResult Import(string sfzPath, IReadOnlyDictionary<int, int>? ccOverrides = null, Func<string, string>? toRef = null)
+ {
+ var sw = System.Diagnostics.Stopwatch.StartNew();
+ var report = new SfzImportReport { File = Path.GetFileName(sfzPath) };
+ string rootDir = Path.GetDirectoryName(Path.GetFullPath(sfzPath)) ?? ".";
+ var defines = new Dictionary<string, string>(StringComparer.Ordinal);
+ string text = Load(sfzPath, rootDir, defines, report, 0);
+
+ // ---- tokenize into (header | opcode) ----------------------------------------------
+ var control = new Dictionary<string, string>(StringComparer.Ordinal);
+ var global = new Dictionary<string, string>(StringComparer.Ordinal);
+ var master = new Dictionary<string, string>(StringComparer.Ordinal);
+ var group = new Dictionary<string, string>(StringComparer.Ordinal);
+ Dictionary<string, string>? region = null;
+ string header = "";
+ int groupSerial = 0, masterSerial = 0;
+ var regions = new List<(Dictionary<string, string> Ops, int Group, int Master)>();
+
+ void CloseRegion()
+ {
+ if (region is null) return;
+ var merged = new Dictionary<string, string>(global, StringComparer.Ordinal);
+ foreach (var kv in master) merged[kv.Key] = kv.Value;
+ foreach (var kv in group) merged[kv.Key] = kv.Value;
+ foreach (var kv in region) merged[kv.Key] = kv.Value;
+ regions.Add((merged, groupSerial, masterSerial));
+ region = null;
+ }
+
+ foreach (var (kind, key, value) in Tokens(text))
+ {
+ if (kind == 'h')
+ {
+ CloseRegion();
+ header = key;
+ switch (header)
+ {
+ case "control": control.Clear(); break;
+ case "global": global.Clear(); master.Clear(); group.Clear(); break;
+ case "master": master.Clear(); group.Clear(); masterSerial++; groupSerial++; break;
+ case "group": group.Clear(); groupSerial++; break;
+ case "region": region = new Dictionary<string, string>(StringComparer.Ordinal); break;
+ }
+ continue;
+ }
+ switch (header)
+ {
+ case "control": control[key] = value; break;
+ case "global": global[key] = value; break;
+ case "master": master[key] = value; break;
+ case "group": group[key] = value; break;
+ case "region": region![key] = value; break;
+ default: break; // <curve>, <effect>, <midi>: not ours
+ }
+ }
+ CloseRegion();
+ report.Regions = regions.Count;
+
+ // ---- controllers ------------------------------------------------------------------
+ var cc = new Dictionary<int, int>();
+ foreach (var kv in control)
+ {
+ if (kv.Key.StartsWith("set_cc", StringComparison.Ordinal) && int.TryParse(kv.Key[6..], NumberStyles.Integer, Inv, out int n))
+ cc[n] = (int)Math.Round(Num(kv.Value, 0));
+ else if (kv.Key.StartsWith("label_cc", StringComparison.Ordinal) && int.TryParse(kv.Key[8..], NumberStyles.Integer, Inv, out int l))
+ report.CcLabels[l] = kv.Value;
+ }
+ if (ccOverrides is not null) foreach (var kv in ccOverrides) cc[kv.Key] = kv.Value;
+ int CcVal(int n) => cc.TryGetValue(n, out var v) ? v : 0;
+ string defaultPath = control.TryGetValue("default_path", out var dp) ? dp : "";
+
+ // Keyswitch state: the first sw_default met.
+ int? keySwitch = null;
+ foreach (var (ops, _, _) in regions)
+ if (ops.TryGetValue("sw_default", out var swd) && Note(swd) is { } kn) { keySwitch = kn; break; }
+
+ // ---- regions → zones ----------------------------------------------------------------
+ var p = new MosaicProgram { Name = Path.GetFileNameWithoutExtension(sfzPath), SourceKind = "sfz" };
+ var fileIndex = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
+ var groupIndex = new Dictionary<(int Group, int Master, bool Release, int SeqLen), int>();
+ var dirCache = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
+ bool envTaken = false;
+
+ foreach (var (ops, gSerial, mSerial) in regions)
+ {
+ // Ignored opcode families (counted once per region).
+ var fams = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var k in ops.Keys) if (Family(k) is { } fam) fams.Add(fam);
+ foreach (var f in fams) report.Ignored[f] = report.Ignored.TryGetValue(f, out var c) ? c + 1 : 1;
+
+ if (!ops.TryGetValue("sample", out var sample) || sample.Length == 0) { report.Inactive++; continue; }
+ if (sample.StartsWith('*')) { report.Generators++; continue; } // *sine, *noise …
+
+ // CC / keyswitch conditions.
+ bool active = true;
+ foreach (var kv in ops)
+ {
+ if (kv.Key.StartsWith("locc", StringComparison.Ordinal) && int.TryParse(kv.Key[4..], NumberStyles.Integer, Inv, out int n))
+ { report.CcState[n] = CcVal(n); if (CcVal(n) < Num(kv.Value, 0)) active = false; }
+ else if (kv.Key.StartsWith("hicc", StringComparison.Ordinal) && int.TryParse(kv.Key[4..], NumberStyles.Integer, Inv, out int h))
+ { report.CcState[h] = CcVal(h); if (CcVal(h) > Num(kv.Value, 127)) active = false; }
+ else if (kv.Key.StartsWith("on_locc", StringComparison.Ordinal) || kv.Key.StartsWith("on_hicc", StringComparison.Ordinal))
+ active = false; // fires on a controller move, not a key
+ }
+ if (ops.TryGetValue("sw_last", out var swl) && Note(swl) is { } swn && keySwitch is { } ks && swn != ks) active = false;
+ if (!active) { report.Inactive++; continue; }
+
+ // The file.
+ string rel = (defaultPath + sample).Trim();
+ if (rel.Contains('\\')) { report.PathsFixed++; rel = rel.Replace('\\', '/'); }
+ string? abs = FindFile(rootDir, rel, dirCache);
+ if (abs is null) { report.Missing++; continue; }
+ if (!fileIndex.TryGetValue(abs, out int fi))
+ {
+ fi = p.Files.Count; fileIndex[abs] = fi;
+ p.Files.Add(toRef is null ? abs : toRef(abs));
+ }
+
+ // Ranges and root.
+ int lo = 0, hi = 127, root = 60;
+ if (ops.TryGetValue("key", out var key) && Note(key) is { } k1) { lo = hi = root = k1; }
+ if (ops.TryGetValue("lokey", out var lk) && Note(lk) is { } k2) lo = k2;
+ if (ops.TryGetValue("hikey", out var hk) && Note(hk) is { } k3) hi = k3;
+ if (ops.TryGetValue("pitch_keycenter", out var pkc) && Note(pkc) is { } k4) root = k4;
+ else if (!ops.ContainsKey("key")) root = ops.ContainsKey("lokey") || ops.ContainsKey("hikey") ? (lo + hi) / 2 : 60;
+ // pitch_keytrack=0 (drums): one key, played at that key — the root sits on it.
+ if (ops.TryGetValue("pitch_keytrack", out var pkt) && Math.Abs(Num(pkt, 100)) < 1 && lo == hi) root = lo;
+ int vlo = Clamp7(Num(Get(ops, "lovel"), 0)), vhi = Clamp7(Num(Get(ops, "hivel"), 127));
+ bool release = ops.TryGetValue("trigger", out var tr) && tr is "release" or "release_key";
+ int seqLen = Math.Clamp((int)Num(Get(ops, "seq_length"), 1), 1, 64);
+
+ var gk = (gSerial, mSerial, release, seqLen);
+ if (!groupIndex.TryGetValue(gk, out int gi))
+ {
+ gi = p.Groups.Count; groupIndex[gk] = gi;
+ string label = Get(ops, "group_label") ?? Get(ops, "master_label") ?? (release ? "Release" : $"Group {gi + 1}");
+ p.Groups.Add(new MosaicGroup { Name = label, SeqLen = seqLen, RrMode = 0 });
+ }
+
+ double amp = Num(Get(ops, "amplitude"), 100);
+ var z = new MosaicZone
+ {
+ File = fi, Group = gi, Root = Math.Clamp(root, 0, 127),
+ KeyLo = Math.Clamp(Math.Min(lo, hi), 0, 127), KeyHi = Math.Clamp(Math.Max(lo, hi), 0, 127),
+ VelLo = Math.Min(vlo, vhi), VelHi = Math.Max(vlo, vhi),
+ Tune = Num(Get(ops, "tune"), 0) + 100 * Num(Get(ops, "transpose"), 0),
+ GainDb = Num(Get(ops, "volume"), 0) + (amp > 0 ? 20 * Math.Log10(amp / 100.0) : -96),
+ Pan = Math.Clamp(Num(Get(ops, "pan"), 0) / 100.0, -1, 1),
+ Start = Math.Max(0, Num(Get(ops, "offset"), 0)),
+ End = Num(Get(ops, "end"), -1) is var e && e > 0 ? e : -1,
+ Seq = Math.Clamp((int)Num(Get(ops, "seq_position"), 1), 1, 64),
+ RandLo = Math.Clamp(Num(Get(ops, "lorand"), 0), 0, 1), RandHi = Math.Clamp(Num(Get(ops, "hirand"), 1), 0, 1),
+ Release = release,
+ Excl = (int)Num(Get(ops, "group"), 0), OffBy = (int)Num(Get(ops, "off_by"), 0),
+ OffNormal = Get(ops, "off_mode") == "normal",
+ XKeyInLo = NoteOr(ops, "xfin_lokey"), XKeyInHi = NoteOr(ops, "xfin_hikey"),
+ XKeyOutLo = NoteOr(ops, "xfout_lokey"), XKeyOutHi = NoteOr(ops, "xfout_hikey"),
+ XVelInLo = IntOr(ops, "xfin_lovel"), XVelInHi = IntOr(ops, "xfin_hivel"),
+ XVelOutLo = IntOr(ops, "xfout_lovel"), XVelOutHi = IntOr(ops, "xfout_hivel"),
+ };
+ string lm = Get(ops, "loop_mode") ?? Get(ops, "loopmode") ?? "";
+ z.LoopMode = lm is "loop_continuous" or "loop_sustain" ? 1 : 0;
+ if (z.LoopMode != 0)
+ {
+ z.LoopStart = Num(Get(ops, "loop_start") ?? Get(ops, "loopstart"), -1);
+ z.LoopEnd = Num(Get(ops, "loop_end") ?? Get(ops, "loopend"), -1);
+ z.Crossfade = Math.Clamp(Num(Get(ops, "loop_crossfade"), 0), 0, 2);
+ }
+ p.Zones.Add(z);
+
+ if (!envTaken && !release)
+ {
+ envTaken = true;
+ if (Get(ops, "ampeg_attack") is { } a) report.Attack = Num(a, 0);
+ if (Get(ops, "ampeg_decay") is { } d) report.Decay = Num(d, 0);
+ if (Get(ops, "ampeg_sustain") is { } s) report.Sustain = Math.Clamp(Num(s, 100) / 100.0, 0, 1);
+ if (Get(ops, "ampeg_release") is { } r) report.Release = Num(r, 0);
+ if (Get(ops, "bend_up") is { } bu) report.BendSemis = Math.Round(Math.Abs(Num(bu, 200)) / 100.0);
+ if (Get(ops, "cutoff") is { } cu && (Get(ops, "fil_type") ?? "lpf_2p").StartsWith("lpf", StringComparison.Ordinal)) report.CutoffHz = Num(cu, 20000);
+ }
+ }
+
+ // Random-range groups play their layers by lorand / hirand; a seq group sequentially.
+ foreach (var g in p.Groups) if (g.SeqLen <= 1) g.RrMode = 0;
+ report.Imported = p.Zones.Count;
+ report.Groups = p.Groups.Count;
+ foreach (var kv in report.CcState) p.Ccs[kv.Key] = kv.Value;
+ report.Seconds = sw.Elapsed.TotalSeconds;
+ return new SfzResult(p, report);
+ }
+
+ /// <summary>The articulations an SFZ selects by controller: per CC, the distinct locc / hicc
+ /// ranges its regions use, with the label_cc name — for an articulation picker.</summary>
+ public static SortedDictionary<int, List<(int Lo, int Hi, string Label)>> CcRanges(string sfzPath)
+ {
+ var result = new SortedDictionary<int, List<(int, int, string)>>();
+ var report = new SfzImportReport();
+ string rootDir = Path.GetDirectoryName(Path.GetFullPath(sfzPath)) ?? ".";
+ string text = Load(sfzPath, rootDir, new Dictionary<string, string>(StringComparer.Ordinal), report, 0);
+ var labels = new Dictionary<int, string>();
+ var cur = new Dictionary<int, (int Lo, int Hi)>();
+ var seen = new HashSet<(int, int, int)>();
+ foreach (var (kind, key, value) in Tokens(text))
+ {
+ if (kind == 'h') { if (key is "region" or "group" or "master" or "global") { } continue; }
+ if (key.StartsWith("label_cc", StringComparison.Ordinal) && int.TryParse(key[8..], NumberStyles.Integer, Inv, out int l)) { labels[l] = value; continue; }
+ bool lo = key.StartsWith("locc", StringComparison.Ordinal), hi = key.StartsWith("hicc", StringComparison.Ordinal);
+ if (!lo && !hi) continue;
+ if (!int.TryParse(key[4..], NumberStyles.Integer, Inv, out int cc)) continue;
+ int v = (int)Math.Round(Num(value, lo ? 0 : 127));
+ var r = cur.TryGetValue(cc, out var c) ? c : (0, 127);
+ r = lo ? (v, r.Item2) : (r.Item1, v);
+ cur[cc] = r;
+ if (hi && seen.Add((cc, r.Item1, r.Item2)))
+ {
+ if (!result.TryGetValue(cc, out var list)) result[cc] = list = new List<(int, int, string)>();
+ list.Add((r.Item1, r.Item2, ""));
+ }
+ }
+ foreach (var (cc, list) in result.ToList())
+ {
+ if (list.Count < 2) { result.Remove(cc); continue; }
+ string name = labels.TryGetValue(cc, out var n) ? n : $"cc{cc}";
+ result[cc] = list.OrderBy(x => x.Item1).Select(x => (x.Item1, x.Item2, $"{name} {x.Item1}–{x.Item2}")).ToList();
+ }
+ return result;
+ }
+
+ // ---- loading (#include, #define, comments) ---------------------------------------------
+ private static readonly Regex DefineRx = new(@"#define\s+(\$\w+)\s+(\S+)", RegexOptions.Compiled);
+ private static readonly Regex IncludeRx = new("#include\\s+\"([^\"]+)\"", RegexOptions.Compiled);
+
+ private static string Load(string path, string rootDir, Dictionary<string, string> defines, SfzImportReport report, int depth)
+ {
+ if (depth > 16) return "";
+ string raw;
+ try { raw = File.ReadAllText(path); } catch { return ""; }
+ raw = StripComments(raw);
+ var sb = new StringBuilder(raw.Length);
+ foreach (var lineRaw in raw.Split('\n'))
+ {
+ string line = lineRaw;
+ var dm = DefineRx.Match(line);
+ if (dm.Success) { defines[dm.Groups[1].Value] = dm.Groups[2].Value; line = line.Remove(dm.Index, dm.Length); }
+ line = Substitute(line, defines);
+ var im = IncludeRx.Match(line);
+ while (im.Success)
+ {
+ report.Includes++;
+ string inc = im.Groups[1].Value.Replace('\\', '/');
+ string? found = FindIncluded(inc, rootDir, Path.GetDirectoryName(path) ?? rootDir);
+ string body = found is null ? "" : Load(found, rootDir, defines, report, depth + 1);
+ line = line[..im.Index] + "\n" + body + "\n" + line[(im.Index + im.Length)..];
+ im = IncludeRx.Match(line, im.Index + body.Length + 2);
+ }
+ sb.Append(line).Append('\n');
+ }
+ return sb.ToString();
+ }
+
+ private static string? FindIncluded(string inc, string rootDir, string here)
+ {
+ foreach (var dir in new[] { rootDir, here })
+ {
+ var cand = Path.GetFullPath(Path.Combine(dir, inc));
+ if (File.Exists(cand)) return cand;
+ }
+ return null;
+ }
+
+ private static string Substitute(string line, Dictionary<string, string> defines)
+ {
+ if (defines.Count == 0 || line.IndexOf('$') < 0) return line;
+ // Longest names first so $FOO doesn't eat $FOOBAR.
+ foreach (var kv in defines.OrderByDescending(kv => kv.Key.Length)) line = line.Replace(kv.Key, kv.Value);
+ return line;
+ }
+
+ private static string StripComments(string s)
+ {
+ var sb = new StringBuilder(s.Length);
+ for (int i = 0; i < s.Length; i++)
+ {
+ if (s[i] == '/' && i + 1 < s.Length && s[i + 1] == '/') { while (i < s.Length && s[i] != '\n') i++; if (i < s.Length) sb.Append('\n'); continue; }
+ if (s[i] == '/' && i + 1 < s.Length && s[i + 1] == '*') { int e = s.IndexOf("*/", i + 2, StringComparison.Ordinal); i = e < 0 ? s.Length : e + 1; continue; }
+ sb.Append(s[i]);
+ }
+ return sb.ToString();
+ }
+
+ // ---- tokens: headers and opcodes (a sample= value may hold spaces) ----------------------
+ private static readonly Regex TokRx = new(@"<(\w+)>|([A-Za-z0-9_]+)=", RegexOptions.Compiled);
+
+ private static IEnumerable<(char Kind, string Key, string Value)> Tokens(string text)
+ {
+ foreach (var line in text.Split('\n'))
+ {
+ var ms = TokRx.Matches(line);
+ for (int i = 0; i < ms.Count; i++)
+ {
+ var m = ms[i];
+ if (m.Groups[1].Success) { yield return ('h', m.Groups[1].Value, ""); continue; }
+ int vStart = m.Index + m.Length;
+ int vEnd = i + 1 < ms.Count ? ms[i + 1].Index : line.Length;
+ string key = m.Groups[2].Value;
+ string value = line[vStart..vEnd].Trim();
+ // Only sample (and labels) may contain spaces; any other value is its first word.
+ if (key != "sample" && !key.EndsWith("label", StringComparison.Ordinal) && !key.StartsWith("label_cc", StringComparison.Ordinal))
+ {
+ int sp = value.IndexOfAny(new[] { ' ', '\t' });
+ if (sp > 0) value = value[..sp];
+ }
+ yield return ('o', key, value);
+ }
+ }
+ }
+
+ // ---- files -------------------------------------------------------------------------------
+ // Resolves rel against the SFZ's folder, case-insensitively per path segment (libraries
+ // made on Windows name "Samples/C4.WAV" what sits on disk as "samples/c4.wav").
+ private static string? FindFile(string rootDir, string rel, Dictionary<string, Dictionary<string, string>> dirCache)
+ {
+ string direct;
+ try { direct = Path.GetFullPath(Path.Combine(rootDir, rel)); } catch { return null; }
+ if (File.Exists(direct)) return direct;
+ string cur = rootDir;
+ var parts = rel.Split('/', StringSplitOptions.RemoveEmptyEntries);
+ for (int i = 0; i < parts.Length; i++)
+ {
+ string part = parts[i];
+ if (part == ".") continue;
+ if (part == "..") { cur = Path.GetDirectoryName(cur) ?? cur; continue; }
+ if (!dirCache.TryGetValue(cur, out var entries))
+ {
+ entries = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ try { foreach (var e in Directory.EnumerateFileSystemEntries(cur)) entries[Path.GetFileName(e)] = e; } catch { }
+ dirCache[cur] = entries;
+ }
+ if (!entries.TryGetValue(part, out var next)) return null;
+ cur = next;
+ }
+ return File.Exists(cur) ? cur : null;
+ }
+
+ // ---- values ------------------------------------------------------------------------------
+ private static string? Get(Dictionary<string, string> ops, string key) => ops.TryGetValue(key, out var v) ? v : null;
+ private static int Clamp7(double v) => Math.Clamp((int)Math.Round(v), 0, 127);
+ private static int NoteOr(Dictionary<string, string> ops, string key) => ops.TryGetValue(key, out var v) && Note(v) is { } n ? n : -1;
+ private static int IntOr(Dictionary<string, string> ops, string key) => ops.TryGetValue(key, out var v) ? Clamp7(Num(v, 0)) : -1;
+
+ private static double Num(string? s, double def)
+ => s is not null && double.TryParse(s, NumberStyles.Float, Inv, out var v) && double.IsFinite(v) ? v : def;
+
+ /// <summary>A key: a MIDI number or a note name with SFZ's octave numbering (c4 = 60).</summary>
+ public static int? Note(string s)
+ {
+ s = s.Trim();
+ if (int.TryParse(s, NumberStyles.Integer, Inv, out int n)) return n is >= 0 and <= 127 ? n : null;
+ var m = Regex.Match(s, @"^([A-Ga-g])([#b♯♭]?)(-?\d+)$");
+ if (!m.Success) return null;
+ int pc = char.ToLowerInvariant(m.Groups[1].Value[0]) switch { 'c' => 0, 'd' => 2, 'e' => 4, 'f' => 5, 'g' => 7, 'a' => 9, _ => 11 };
+ if (m.Groups[2].Value is "#" or "♯") pc++;
+ else if (m.Groups[2].Value is "b" or "♭") pc--;
+ int note = (int.Parse(m.Groups[3].Value, Inv) + 1) * 12 + pc;
+ return note is >= 0 and <= 127 ? note : null;
+ }
+
+ // Opcodes Mosaic plays (or uses to choose regions); everything else is a family to report.
+ private static readonly HashSet<string> Known = new(StringComparer.Ordinal)
+ {
+ "sample", "key", "lokey", "hikey", "pitch_keycenter", "pitch_keytrack", "lovel", "hivel", "tune", "transpose", "volume",
+ "pan", "amplitude", "offset", "end", "loop_mode", "loopmode", "loop_start", "loopstart", "loop_end", "loopend",
+ "loop_crossfade", "trigger", "seq_length", "seq_position", "lorand", "hirand", "group", "off_by", "off_mode",
+ "xfin_lokey", "xfin_hikey", "xfout_lokey", "xfout_hikey", "xfin_lovel", "xfin_hivel", "xfout_lovel", "xfout_hivel",
+ "ampeg_attack", "ampeg_decay", "ampeg_sustain", "ampeg_release", "sw_last", "sw_default", "sw_lokey", "sw_hikey",
+ "group_label", "master_label", "region_label", "default_path", "note_offset", "octave_offset",
+ "bend_up", "bend_down", "cutoff", "fil_type",
+ };
+
+ private static string? Family(string op)
+ {
+ if (Known.Contains(op)) return null;
+ if (op.StartsWith("locc", StringComparison.Ordinal) || op.StartsWith("hicc", StringComparison.Ordinal)
+ || op.StartsWith("set_cc", StringComparison.Ordinal) || op.StartsWith("label_cc", StringComparison.Ordinal)) return null;
+ // eg06_time1_oncc → eg06* · lfo02_freq → lfo02* · pitcheg_decay_oncc → pitcheg* · ampeg_release_oncc → ampeg*
+ var m = Regex.Match(op, @"^(eg\d+|lfo\d+|var\d+|pitcheg|fileg|ampeg|pitchlfo|amplfo|fillfo)_");
+ if (m.Success) return m.Groups[1].Value + "*";
+ if (op.StartsWith("amp_velcurve_", StringComparison.Ordinal)) return "amp_velcurve*";
+ // amplitude_cc15 → amplitude_cc* · cutoff_oncc124 → cutoff_cc*
+ var cc = Regex.Match(op, @"^(.+?)_(?:on)?cc\d+$");
+ if (cc.Success) return cc.Groups[1].Value + "_cc*";
+ return op;
+ }
+}
diff --git a/src/managed/Nota.Application/Instruments/MosaicModel.cs b/src/managed/Nota.Application/Instruments/MosaicModel.cs
new file mode 100644
index 00000000..8c111977
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/MosaicModel.cs
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic (kind 17) on the managed side: the value maps the native Mosaic.h uses (so
+// the card, the MCP and the tests speak in dB / ms / voices), the telemetry layout, and a
+// one-line summary of a patch.
+
+using System;
+using System.Collections.Generic;
+using Nota.Application.Mosaic;
+
+namespace Nota.Application;
+
+public static class MosaicModel
+{
+ public const int Kind = 17;
+
+ public static readonly int[] PolyCounts = { 16, 32, 64, 128 };
+ public static readonly string[] VoiceNames = { "Poly", "Mono", "Choke" };
+ public static readonly string[] FilterNames = { "Off", "LP", "HP", "BP" };
+ public static readonly string[] LoopNames = { "Off", "Fwd", "Ping" };
+ public static readonly string[] StealOrder = { "Released", "Quietest", "Oldest" };
+
+ // ---- value maps (native Mosaic.h) --------------------------------------------------------
+ public static int Index(float v, int n) => n <= 1 ? 0 : Math.Clamp((int)Math.Round(v * (n - 1)), 0, n - 1);
+ public static int Poly(float v) => PolyCounts[Index(v, 4)];
+ public static float PolyNorm(int voices) { int i = Array.IndexOf(PolyCounts, voices); return i < 0 ? 2f / 3f : i / 3f; }
+ public static int PerKey(float v) => 1 + Index(v, 4);
+ public static double OldFadeMs(float v) => Math.Pow(200.0, Math.Clamp(v, 0, 1)); // 1 … 200 ms
+ public static float OldFadeNorm(double ms) => (float)Math.Clamp(Math.Log(Math.Max(1, ms)) / Math.Log(200.0), 0, 1);
+ public static double RelVolDb(float v) => -36.0 + 42.0 * Math.Clamp(v, 0, 1);
+ public static float RelVolNorm(double db) => (float)Math.Clamp((db + 36.0) / 42.0, 0, 1);
+ public static double RelLenDb(float v) => -24.0 * Math.Clamp(v, 0, 1);
+ public static float RelLenNorm(double db) => (float)Math.Clamp(-db / 24.0, 0, 1);
+ public static int BendSemis(float v) => (int)Math.Round(24.0 * Math.Clamp(v, 0, 1));
+ /// <summary>The curve as a signed amount, −100 (soft) … +100 (hard).</summary>
+ public static int VelCurve(float v) => (int)Math.Round((Math.Clamp(v, 0, 1) - 0.5) * 200);
+ public static double VelCurveAt(double vel, float c) => Math.Pow(Math.Clamp(vel, 0, 1), Math.Pow(4.0, (Math.Clamp(c, 0, 1) - 0.5) * 2.0));
+ public static double VolumeDb(float v) => v <= 1e-5f ? double.NegativeInfinity : 20 * Math.Log10(v);
+ public static double TransposeSt(float v) => Math.Round((v - 0.5) * 48.0);
+ public static double DetuneCents(float v) => (v - 0.5) * 100.0;
+ public static double GlideSec(float v) => v <= 0.001f ? 0 : 0.001 * Math.Pow(2000.0, Math.Clamp(v, 0, 1));
+ public static double EnvOctaves(float v) => (Math.Clamp(v, 0, 1) - 0.5) * 12.0;
+ public static double AttackSec(float v) => 0.0005 * Math.Pow(4.0 / 0.0005, Math.Clamp(v, 0, 1));
+ public static double DecaySec(float v) => 0.002 * Math.Pow(6.0 / 0.002, Math.Clamp(v, 0, 1));
+ public static double ReleaseSec(float v) => DecaySec(v);
+ public static double CutoffHz(float v) => 20.0 * Math.Pow(1000.0, Math.Clamp(v, 0, 1));
+ /// <summary>Seconds → the normalized attack (0.5 ms … 4 s) / decay or release (2 ms … 6 s).</summary>
+ public static float AttackNorm(double s) => (float)Math.Clamp(Math.Log(Math.Max(0.0005, s) / 0.0005) / Math.Log(4.0 / 0.0005), 0, 1);
+ public static float DecayNorm(double s) => (float)Math.Clamp(Math.Log(Math.Max(0.002, s) / 0.002) / Math.Log(6.0 / 0.002), 0, 1);
+
+ // ---- telemetry (Mosaic::scopeRead) -------------------------------------------------------
+ public const int ScVoices = 0, ScLimit = 1, ScHeld = 2, ScPedalHeld = 3, ScRelease = 4, ScPedal = 5, ScPeak = 6,
+ ScPos = 7, ScEnv = 8, ScStage = 9, ScNote = 10, ScCutoff = 11, ScZone = 12, ScLastNote = 13,
+ ScLastVel = 14, ScSounding = 15, ScHead = 16, ScKeys = 16 + 112, ScopeLength = 16 + 112 + 8;
+
+ /// <summary>A zone that sounds now: 0 held · 1 held by the pedal · 2 release / fading.</summary>
+ public readonly record struct Sounding(int Zone, int State);
+
+ public sealed class Snapshot
+ {
+ public bool Live;
+ public int Voices, Limit, Held, PedalHeld, Release, Zone = -1, LastNote = -1, LastVel, Stage = -1;
+ public bool Pedal;
+ public double Peak, Pos = -1, Env, Note = -1, CutoffHz = -1;
+ public readonly List<Sounding> Zones = new();
+ /// <summary>Keys held or sustained now.</summary>
+ public readonly HashSet<int> Keys = new();
+ }
+
+ public static void Parse(ReadOnlySpan<float> sc, Snapshot s)
+ {
+ s.Zones.Clear(); s.Keys.Clear();
+ if (sc.Length < ScHead) { s.Live = false; s.Voices = 0; return; }
+ s.Voices = (int)sc[ScVoices]; s.Limit = (int)sc[ScLimit]; s.Held = (int)sc[ScHeld];
+ s.PedalHeld = (int)sc[ScPedalHeld]; s.Release = (int)sc[ScRelease]; s.Pedal = sc[ScPedal] > 0.5f;
+ s.Peak = sc[ScPeak]; s.Pos = sc[ScPos]; s.Env = sc[ScEnv]; s.Stage = (int)sc[ScStage];
+ s.Note = sc[ScNote]; s.CutoffHz = sc[ScCutoff]; s.Zone = (int)sc[ScZone];
+ s.LastNote = (int)sc[ScLastNote]; s.LastVel = (int)sc[ScLastVel];
+ s.Live = s.Voices > 0;
+ int n = Math.Min((int)sc[ScSounding], sc.Length - ScHead);
+ for (int i = 0; i < n; i++)
+ {
+ int code = (int)sc[ScHead + i];
+ s.Zones.Add(new Sounding(code / 4, code % 4));
+ }
+ if (sc.Length >= ScopeLength)
+ for (int i = 0; i < 8; i++)
+ {
+ int bits = (int)sc[ScKeys + i];
+ for (int b = 0; b < 16; b++) if ((bits & (1 << b)) != 0) s.Keys.Add(i * 16 + b);
+ }
+ }
+
+ // ---- words -----------------------------------------------------------------------------
+ public static string Megabytes(long bytes) => bytes <= 0 ? "0 MB" : bytes < 1024L * 1024 * 1024
+ ? $"{Math.Max(1, Math.Round(bytes / 1048576.0))} MB"
+ : $"{(bytes / 1073741824.0).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)} GB";
+
+ /// <summary>"Osiris Piano · 30 roots × 4 velocity layers · release 30".</summary>
+ public static string Summary(MosaicProgram p, Func<string, float> g)
+ {
+ if (p.IsEmpty) return "Empty · drop samples or a folder, or pick a preset";
+ string voices = VoiceNames[Index(g("voicemode"), 3)] == "Poly" ? $"Poly {Poly(g("polyphony"))}" : VoiceNames[Index(g("voicemode"), 3)];
+ return $"{(p.Name.Length > 0 ? p.Name + " · " : "")}{p.Summary()} · {voices}";
+ }
+
+ public const string Guide =
+ "Nota Mosaic plays a multisample: zones (a sample on a key × velocity rectangle, with its root) in groups "
+ + "(velocity layers with a shared gain/tune and a round-robin). Every zone covering the key, the velocity and the "
+ + "group's round-robin step sounds; release zones sound when the key (or the pedal) lets go, quieter the longer the "
+ + "note was held. Samples load in the background into RAM — notes are silent until the program is in. "
+ + "Shared controls: amp ADSR, filter (Off/LP/HP/BP, cutoff, reso, key tracking, env → cutoff), glide, Vel → Vol with a "
+ + "velocity curve, polyphony 16/32/64/128, per-key strike limit, old-voice fade, sustain pedal (CC64), MPE "
+ + "(bend range, pressure → level, slide → cutoff).";
+}
diff --git a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs
index 1e4cb9af..ee8ddcbd 100644
--- a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs
+++ b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs
@@ -85,7 +85,10 @@ public static class BuiltinDeviceCatalog
new("Nota Keys", I, 16, "electric piano", D("synth.physical", "epiano e-piano rhodes wurlitzer wurli clavinet clav tine reed suitcase",
"warm vintage", "keys", "", "", "jazz funk",
"Modelled electric piano — tine, suitcase, reed and clav with tremolo, phaser and cabinet.")),
- new("Nota Sampler", I, 1, "built-in", D("sampler", "simpler multisample",
+ new("Nota Mosaic", I, 17, "multisample", D("sampler", "multisample multisampler sfz soundfont piano grand acoustic orchestral orchestra zones velocity round-robin мультисэмпл пианино рояль",
+ "", "keys strings brass choir", "", "", "cinematic",
+ "Multisample instrument — zones by key and velocity, round-robin and release samples; SFZ import and packs.")),
+ new("Nota Sampler", I, 1, "built-in", D("sampler", "simpler oneshot",
"", "keys perc", "", "", "",
"Plays a sample across the keyboard.")),
new("Nota Instrument Rack", I, 3, "built-in", D("rack", "layer split instrumentrack",
diff --git a/src/managed/Nota.Application/Palette/PresetDescriptors.cs b/src/managed/Nota.Application/Palette/PresetDescriptors.cs
index 6f173d5e..45d49594 100644
--- a/src/managed/Nota.Application/Palette/PresetDescriptors.cs
+++ b/src/managed/Nota.Application/Palette/PresetDescriptors.cs
@@ -88,6 +88,8 @@ public static class PresetDescriptors
["reed"] = new() { Sound = ["keys"], Character = ["gritty", "vintage"] },
["clav"] = new() { Sound = ["keys"], Character = ["punchy"], Genre = ["funk"] },
["character"] = new() { Character = ["lofi", "vintage"] },
+ ["mallets & plucks"] = new() { Sound = ["pluck", "bell"] },
+ ["packs"] = new() { Sound = ["keys"] },
};
/// <summary>A factory or user preset's descriptor (CP-13.2/13.3): the device's role,
diff --git a/src/managed/Nota.Application/Ports/IMosaicPacks.cs b/src/managed/Nota.Application/Ports/IMosaicPacks.cs
new file mode 100644
index 00000000..a1ebc564
--- /dev/null
+++ b/src/managed/Nota.Application/Ports/IMosaicPacks.cs
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+
+using Nota.Application.Mosaic;
+
+namespace Nota.Application;
+
+/// <summary>A Nota Mosaic preset made from a sample pack (its SFZ or its file names) or by
+/// "Create multisample": a .notapreset under the Mosaic packs folder, grouped by
+/// <see cref="Folder"/> in the browser (Nota Mosaic → Packs → Folder).</summary>
+public sealed record MosaicPackPreset(string Path, string Name, string Folder, string Source);
+
+/// <summary>Nota Mosaic's preset library beyond the factory set: presets generated for the
+/// installed sample packs and the multisamples the user creates.</summary>
+public interface IMosaicPacks
+{
+ /// <summary>Where the generated presets live (one folder per pack).</summary>
+ string Root { get; }
+
+ /// <summary>Every generated / created preset on disk now.</summary>
+ IReadOnlyList<MosaicPackPreset> Presets();
+
+ /// <summary>Fired (on a worker thread) after a scan wrote new presets.</summary>
+ event Action? Changed;
+
+ /// <summary>Makes presets for every installed pack that has none yet (SFZ first, else the
+ /// file names). Returns how many presets were written.</summary>
+ Task<int> ScanAsync(CancellationToken ct = default);
+
+ /// <summary>Saves a program as a preset in <paramref name="folder"/>; returns the file path.</summary>
+ string Save(MosaicProgram program, string name, string folder, IReadOnlyDictionary<string, float>? param = null);
+
+ /// <summary>Loads a Mosaic preset file into a track's Mosaic in place (its sound and its program).
+ /// Returns "" or a warning.</summary>
+ string ApplyInPlace(IAudioEngine engine, string path, int trackId);
+
+ /// <summary>The program a preset file holds (null when it isn't a Mosaic preset).</summary>
+ MosaicProgram? Read(string path);
+
+ /// <summary>A portable reference for a sample path ("samples:…" inside the Samples folder).</summary>
+ string ToRef(string path);
+
+ /// <summary>The absolute path a program's file reference names, or null.</summary>
+ string? Resolve(string reference);
+
+ /// <summary>A file's fundamental as a MIDI note (fractional), or null — pitch detection for
+ /// the auto-mapper.</summary>
+ double? DetectNote(string path);
+}
diff --git a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs b/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs
index e5c039df..b27e92fa 100644
--- a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs
+++ b/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs
@@ -14,6 +14,8 @@ using System.Collections.Generic;
using System.IO;
using Nota.Application;
+using Nota.Application.Mosaic;
+
namespace Nota.Infrastructure;
public sealed partial class PresetAudition : IPresetAudition
@@ -102,6 +104,14 @@ public sealed partial class PresetAudition : IPresetAudition
var path = Grain.GrainSourceLibrary.Ensure(doc.GrainSource);
if (src is null || path is null || !rig.SetSamplerSample(path, src.Root)) return false;
}
+ // Nota Mosaic: its multisample (a factory source, the preset's program, else the felt piano).
+ if (kind == MosaicModel.Kind)
+ {
+ var prog = !string.IsNullOrEmpty(doc.MosaicSource) ? Mosaic.MosaicSourceLibrary.Program(doc.MosaicSource)
+ : !string.IsNullOrEmpty(doc.MosaicProgram) ? MosaicProgram.Parse(doc.MosaicProgram)
+ : Mosaic.MosaicSourceLibrary.Program("felt-piano");
+ if (prog is null || !rig.SetMosaicProgram(prog.Serialize())) return false;
+ }
return true;
},
phrase.Notes, Bpm, phrase.Beats, phrase.Tail, phrase.Rolling);
@@ -171,7 +181,7 @@ public sealed partial class PresetAudition : IPresetAudition
{
[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", [16] = "Nota Keys",
+ [12] = "Nota Rhythm", [13] = "Nota Monolith", [14] = "Nota Pentad", [15] = "Nota Consort", [16] = "Nota Keys", [17] = "Nota Mosaic",
};
private static readonly Dictionary<int, string> MidiNames = new()
{
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs
index acce0134..84745100 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs
@@ -45,6 +45,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_audition_set_sampler_sample", StringMarshalling = StringMarshalling.Utf8)]
internal static partial int AuditionSetSamplerSample(IntPtr rig, string? path, int rootNote);
+ [LibraryImport(Lib, EntryPoint = "nota_audition_set_mosaic_program", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial int AuditionSetMosaicProgram(IntPtr rig, string text);
+
[LibraryImport(Lib, EntryPoint = "nota_audition_add_source_from")]
internal static partial int AuditionAddSourceFrom(IntPtr rig, IntPtr part, float gain);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index c5aae483..863776c7 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -365,6 +365,27 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_add_keys_track")]
internal static partial int AddKeysTrack(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_add_mosaic_track")]
+ internal static partial int AddMosaicTrack(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_mosaic_set_program", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial int MosaicSetProgram(IntPtr engine, int trackId, string text, int checkpoint);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_mosaic_program")]
+ internal static unsafe partial int MosaicProgram(IntPtr engine, int trackId, byte* output, int cap);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_mosaic_status")]
+ internal static partial int MosaicStatus(IntPtr engine, int trackId, out NotaMosaicStatus status);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_mosaic_zone_sample_id")]
+ internal static partial long MosaicZoneSampleId(IntPtr engine, int trackId, int zone);
+
+ [LibraryImport(Lib, EntryPoint = "nota_path_root_set", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial void PathRootSet(string name, string path);
+
+ [LibraryImport(Lib, EntryPoint = "nota_file_decode_mono", StringMarshalling = StringMarshalling.Utf8)]
+ internal static unsafe partial long FileDecodeMono(string path, double maxSeconds, float* output, long cap, out double sampleRate);
+
[LibraryImport(Lib, EntryPoint = "nota_track_instrument_action")]
internal static partial void InstrumentAction(IntPtr engine, int trackId, int id, int iarg, float farg);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs
index d99f94b5..4ea2d190 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs
@@ -46,6 +46,8 @@ public sealed partial class NotaEngine
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, int rootNote = 60) => NativeMethods.AuditionSetSamplerSample(Handle, path, rootNote) != 0;
+ /// <summary>Nota Mosaic's program; returns once its samples are loaded.</summary>
+ public bool SetMosaicProgram(string text) => NativeMethods.AuditionSetMosaicProgram(Handle, text) != 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;
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index e0374f32..ce797be2 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -805,6 +805,50 @@ public sealed partial class NotaEngine
return id;
}
+ /// <summary>Adds an instrument track with the built-in Nota Mosaic (empty until a program is set). Returns its id.</summary>
+ public int AddMosaicTrack()
+ {
+ ThrowIfDisposed();
+ var id = NativeMethods.AddMosaicTrack(_handle);
+ if (id <= 0) throw new NotaEngineException("Failed to add Mosaic track.");
+ return id;
+ }
+
+ public bool MosaicSetProgram(int trackId, string text, bool undoable = true)
+ { ThrowIfDisposed(); return NativeMethods.MosaicSetProgram(_handle, trackId, text ?? "", undoable ? 1 : 0) != 0; }
+
+ public unsafe string MosaicProgram(int trackId)
+ {
+ ThrowIfDisposed();
+ int n = NativeMethods.MosaicProgram(_handle, trackId, null, 0);
+ if (n <= 0) return "";
+ var buf = new byte[n];
+ fixed (byte* p = buf) n = Math.Min(n, NativeMethods.MosaicProgram(_handle, trackId, p, buf.Length));
+ return System.Text.Encoding.UTF8.GetString(buf, 0, n);
+ }
+
+ public bool TryGetMosaicStatus(int trackId, out NotaMosaicStatus status)
+ { ThrowIfDisposed(); return NativeMethods.MosaicStatus(_handle, trackId, out status) != 0; }
+
+ public long MosaicZoneSampleId(int trackId, int zone)
+ { ThrowIfDisposed(); return NativeMethods.MosaicZoneSampleId(_handle, trackId, zone); }
+
+ /// <summary>Sets a named root Nota Mosaic's sample references resolve against
+ /// ("samples:Downloaded/x.wav" → &lt;root&gt;/Downloaded/x.wav). Process-wide.</summary>
+ public static void SetPathRoot(string name, string path) => NativeMethods.PathRootSet(name, path ?? "");
+
+ /// <summary>Decodes up to <paramref name="maxSeconds"/> of a file's head as mono; null on failure.</summary>
+ public static unsafe float[]? DecodeMono(string path, double maxSeconds, out double sampleRate)
+ {
+ long n = NativeMethods.FileDecodeMono(path, maxSeconds, null, 0, out sampleRate);
+ if (n <= 0 || n > int.MaxValue) return null;
+ var buf = new float[n];
+ fixed (float* p = buf) n = NativeMethods.FileDecodeMono(path, maxSeconds, p, buf.LongLength, out sampleRate);
+ if (n <= 0) return null;
+ if (n < buf.LongLength) Array.Resize(ref buf, (int)n);
+ return buf;
+ }
+
/// <summary>UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns).</summary>
public void InstrumentAction(int trackId, int id, int iarg, float farg)
{ ThrowIfDisposed(); NativeMethods.InstrumentAction(_handle, trackId, id, iarg, farg); }
diff --git a/src/managed/Nota.Infrastructure/Mosaic/MosaicLibrary.cs b/src/managed/Nota.Infrastructure/Mosaic/MosaicLibrary.cs
new file mode 100644
index 00000000..9a4dbad3
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Mosaic/MosaicLibrary.cs
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic's samples and presets on disk:
+//
+// • Path roots. Programs reference samples as "samples:<rel>" (the user's Samples folder,
+// where registry packs install) or "data:<rel>" (Nota's data folder, where the factory
+// multisamples render) — the engine resolves them against the roots set here, at start
+// and whenever Settings move the Samples folder.
+// • Factory multisamples (MosaicSources): rendered into <data>/mosaic-sources/<id>/ the
+// first time a preset needs one, then mapped by their file names into a program.
+// • Pack presets: for every installed sample pack, one preset per instrument it holds —
+// each of its SFZ programs (the ones no other SFZ #includes), or, without SFZ, every
+// instrument the file-name mapper finds — in <presets>/Mosaic Packs/<Pack>/, written
+// once per pack version. "Create multisample" saves there too.
+
+using System.Text.Json;
+using Nota.Application.Mosaic;
+using Nota.Infrastructure.Kits;
+
+namespace Nota.Infrastructure.Mosaic;
+
+public static class MosaicRoots
+{
+ /// <summary>Points the engine's "samples" and "data" roots at the current folders, and keeps
+ /// them there when Settings change.</summary>
+ public static void Install(ISettingsService settings)
+ {
+ void Apply()
+ {
+ try { NotaEngine.SetPathRoot(MosaicPaths.SamplesRoot, settings.ResolvedSamplesFolder()); } catch { }
+ NotaEngine.SetPathRoot(MosaicPaths.DataRoot, NotaPaths.DataDir);
+ }
+ Apply();
+ settings.Changed += Apply;
+ }
+}
+
+public static class MosaicSourceLibrary
+{
+ private const int RendererVersion = 1;
+ private static readonly object Gate = new();
+
+ public static string Root => NotaPaths.SubDir("mosaic-sources");
+ public static string FolderOf(MosaicSource s) => Path.Combine(Root, s.Id);
+ private static string StampOf(MosaicSource s) => Path.Combine(FolderOf(s), ".stamp");
+ private static string StampFor(MosaicSource s) => $"v{RendererVersion}-{s.Id}-r{s.Rev}-{s.Files}";
+
+ public static bool IsRendered(MosaicSource s)
+ {
+ try { return File.Exists(StampOf(s)) && File.ReadAllText(StampOf(s)).Trim() == StampFor(s); }
+ catch { return false; }
+ }
+
+ /// <summary>The source's folder, rendering it first if missing or stale; null on failure.</summary>
+ public static string? Ensure(string id, IProgress<double>? progress = null)
+ {
+ var s = MosaicSources.ById(id);
+ if (s is null) return null;
+ lock (Gate)
+ {
+ if (IsRendered(s)) return FolderOf(s);
+ try
+ {
+ string dir = FolderOf(s);
+ if (Directory.Exists(dir)) Directory.Delete(dir, true);
+ Directory.CreateDirectory(dir);
+ var rng = new Rng(Fnv(s.Id));
+ int total = s.Files, done = 0;
+ foreach (int root in s.Roots)
+ {
+ for (int li = 0; li < s.Layers.Length; li++)
+ for (int rr = 1; rr <= Math.Max(1, s.RoundRobin); rr++)
+ {
+ string name = $"{s.Id}_{NoteToken(root)}_{s.Layers[li]}{(s.RoundRobin > 1 ? $"_rr{rr}" : "")}.wav";
+ Write(Path.Combine(dir, name), s.Render(root, li, rr, false, rng));
+ progress?.Report(++done / (double)total);
+ }
+ if (s.Releases)
+ {
+ Write(Path.Combine(dir, $"{s.Id}_{NoteToken(root)}_rel.wav"), s.Render(root, 0, 1, true, rng));
+ progress?.Report(++done / (double)total);
+ }
+ }
+ File.WriteAllText(StampOf(s), StampFor(s));
+ return dir;
+ }
+ catch { return null; }
+ }
+ }
+
+ /// <summary>The program for a factory source (rendering it first), or null.</summary>
+ public static MosaicProgram? Program(string id, IProgress<double>? progress = null)
+ {
+ var s = MosaicSources.ById(id);
+ string? dir = Ensure(id, progress);
+ if (s is null || dir is null) return null;
+ NotaEngine.SetPathRoot(MosaicPaths.DataRoot, NotaPaths.DataDir); // its files are "data:" references
+ var prop = MultisampleMapper.MapFolder(dir, new MultisampleOptions { OctaveShift = 0, EdgeStretch = 12, RrMode = 2 });
+ var inst = prop.Instruments.FirstOrDefault();
+ if (inst is null) return null;
+ var p = MultisampleMapper.Build(inst, new MultisampleOptions { RrMode = 2 },
+ path => MosaicPaths.ToRef(path, null, NotaPaths.DataDir), s.Name);
+ p.SourceKind = "factory"; p.SourceRef = s.Id;
+ if (s.Loop is { } loop)
+ foreach (var z in p.Zones)
+ {
+ z.LoopMode = 1;
+ z.LoopStart = loop.Start * MosaicSources.Rate; z.LoopEnd = loop.End * MosaicSources.Rate;
+ z.Crossfade = 0.25;
+ }
+ return p;
+ }
+
+ private static string NoteToken(int n)
+ {
+ string[] pc = { "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b" };
+ return pc[n % 12] + (n / 12 - 1);
+ }
+
+ private static void Write(string path, (double[] L, double[] R) b)
+ {
+ int n = b.L.Length;
+ var inter = new float[n * 2];
+ for (int i = 0; i < n; i++) { inter[2 * i] = (float)Math.Clamp(b.L[i], -1, 1); inter[2 * i + 1] = (float)Math.Clamp(b.R[i], -1, 1); }
+ string tmp = path + ".part";
+ using (var w = new WavWriter(tmp, MosaicSources.Rate, 2, WavBitDepth.Pcm16)) w.WriteFrames(inter, n);
+ File.Move(tmp, path, overwrite: true);
+ }
+
+ private static uint Fnv(string s) { uint h = 2166136261; foreach (char c in s) { h ^= c; h *= 16777619; } return h; }
+}
+
+public sealed class MosaicPackLibrary : IMosaicPacks
+{
+ private const string Stamp = ".nota-mosaic";
+ private const int GeneratorVersion = 1;
+ private static readonly JsonSerializerOptions Json = new() { WriteIndented = true };
+ private readonly ISettingsService? _settings;
+ private readonly ISampleStore? _store;
+ private readonly string? _root;
+ private readonly SemaphoreSlim _scan = new(1, 1);
+
+ public MosaicPackLibrary(ISettingsService settings, ISampleStore store) { _settings = settings; _store = store; }
+
+ /// <summary>For tests: a fixed root, no store.</summary>
+ public MosaicPackLibrary(string root) { _root = root; }
+
+ public event Action? Changed;
+
+ public string Root
+ {
+ get
+ {
+ string r = _root ?? Path.Combine(_settings!.PresetsFolder(), "Mosaic Packs");
+ try { Directory.CreateDirectory(r); } catch { }
+ return r;
+ }
+ }
+
+ private string? SamplesFolder { get { try { return _settings?.ResolvedSamplesFolder(); } catch { return null; } } }
+
+ public string ToRef(string path) => MosaicPaths.ToRef(path, SamplesFolder, NotaPaths.DataDir);
+ public string? Resolve(string reference) => MosaicPaths.Resolve(reference, SamplesFolder, NotaPaths.DataDir);
+
+ public IReadOnlyList<MosaicPackPreset> Presets()
+ {
+ var list = new List<MosaicPackPreset>();
+ string root = Root;
+ IEnumerable<string> dirs;
+ try { dirs = Directory.EnumerateDirectories(root).OrderBy(d => d, StringComparer.OrdinalIgnoreCase).ToList(); }
+ catch { return list; }
+ foreach (var dir in dirs)
+ {
+ string folder = Path.GetFileName(dir);
+ IEnumerable<string> files;
+ try { files = Directory.EnumerateFiles(dir, "*" + PresetService.Extension).OrderBy(f => f, StringComparer.OrdinalIgnoreCase).ToList(); }
+ catch { continue; }
+ foreach (var f in files)
+ {
+ string source = "";
+ try
+ {
+ var doc = PresetService.Load(f);
+ if (doc.BuiltinKind != MosaicModel.Kind) continue;
+ source = MosaicProgram.Parse(doc.MosaicProgram).SourceKind;
+ list.Add(new MosaicPackPreset(f, doc.DisplayName.Length > 0 ? doc.DisplayName : Path.GetFileNameWithoutExtension(f), folder, source));
+ }
+ catch { /* not ours / corrupt */ }
+ }
+ }
+ return list;
+ }
+
+ public string ApplyInPlace(IAudioEngine engine, string path, int trackId)
+ {
+ try { return PresetService.ApplyInPlace(PresetService.Load(path), engine, trackId, -1); }
+ catch (Exception e) { return $"Couldn't load the preset: {e.Message}"; }
+ }
+
+ public MosaicProgram? Read(string path)
+ {
+ try
+ {
+ var doc = PresetService.Load(path);
+ return doc.BuiltinKind == MosaicModel.Kind && doc.MosaicProgram is { Length: > 0 } t ? MosaicProgram.Parse(t) : null;
+ }
+ catch { return null; }
+ }
+
+ public string Save(MosaicProgram program, string name, string folder, IReadOnlyDictionary<string, float>? param = null)
+ {
+ var doc = new PresetDocument
+ {
+ DisplayName = name, Type = "builtin-instrument", DeviceName = "Nota Mosaic", BuiltinKind = MosaicModel.Kind,
+ NamedParams = param is null ? new Dictionary<string, float>() : new Dictionary<string, float>(param),
+ MosaicProgram = program.Serialize(),
+ };
+ return PresetService.Save(doc, Path.Combine(Root, Sanitize(folder)));
+ }
+
+ public double? DetectNote(string path)
+ {
+ var mono = NotaEngine.DecodeMono(path, 1.5, out double sr);
+ if (mono is null || sr <= 0 || mono.Length < 8192) return null;
+ // Past the attack: a quarter in, or 50 ms, whichever is later.
+ int start = Math.Max((int)(0.05 * sr), mono.Length / 4);
+ int win = 2048;
+ if (start + win + (int)(sr / 30) >= mono.Length) start = Math.Max(0, mono.Length - win - (int)(sr / 30) - 1);
+ double hz = AudioPitch.YinHz(mono, start, win, sr, 0.15, 30, 2000);
+ return hz > 0 ? 69 + 12 * Math.Log2(hz / 440.0) : null;
+ }
+
+ // ---- packs → presets -------------------------------------------------------------------------
+ public async Task<int> ScanAsync(CancellationToken ct = default)
+ {
+ if (_store is null) return 0;
+ await _scan.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ int written = 0;
+ foreach (var pack in _store.Installed)
+ {
+ ct.ThrowIfCancellationRequested();
+ written += await Task.Run(() => ScanPack(pack.Path, pack.Id, pack.Version), ct).ConfigureAwait(false);
+ }
+ if (written > 0) Changed?.Invoke();
+ return written;
+ }
+ finally { _scan.Release(); }
+ }
+
+ /// <summary>Writes the presets for one pack folder unless its stamp says they're current.</summary>
+ public int ScanPack(string packPath, string packId, string version)
+ {
+ string packName = Path.GetFileName(packPath.TrimEnd('/', '\\'));
+ string dir = Path.Combine(Root, Sanitize(packName));
+ string stampPath = Path.Combine(dir, Stamp);
+ string want = $"v{GeneratorVersion} {packId} {version}";
+ try { if (File.Exists(stampPath) && File.ReadAllText(stampPath).Trim() == want) return 0; } catch { }
+ var made = Generate(packPath, packId, packName);
+ if (made.Count == 0) return 0;
+ Directory.CreateDirectory(dir);
+ foreach (var f in Directory.EnumerateFiles(dir, "*" + PresetService.Extension)) { try { File.Delete(f); } catch { } }
+ int n = 0;
+ foreach (var (name, prog, param) in made) { Save(prog, name, packName, param); n++; }
+ File.WriteAllText(stampPath, want);
+ return n;
+ }
+
+ /// <summary>The instruments in a pack folder: its SFZ programs, else the mapped file names.</summary>
+ public List<(string Name, MosaicProgram Program, Dictionary<string, float> Params)> Generate(string packPath, string packId, string packName)
+ {
+ var made = new List<(string, MosaicProgram, Dictionary<string, float>)>();
+ var sfz = TopLevelSfz(packPath);
+ foreach (var path in sfz)
+ {
+ SfzResult res;
+ try { res = SfzImporter.Import(path, null, ToRef); } catch { continue; }
+ if (res.Program.Zones.Count == 0) continue;
+ string stem = Path.GetFileNameWithoutExtension(path);
+ string name = sfz.Count == 1 || stem.Equals("main", StringComparison.OrdinalIgnoreCase) || stem.Equals(packName, StringComparison.OrdinalIgnoreCase)
+ ? packName : MultisampleMapper.Pretty(stem.Replace(' ', '_'));
+ res.Program.Name = name; res.Program.SourceRef = ToRef(path); res.Program.PackId = packId; res.Program.PackName = packName;
+ made.Add((name, res.Program, ParamsFrom(res.Report)));
+ }
+ if (made.Count > 0) return made;
+
+ var prop = MultisampleMapper.MapFolder(packPath, null, DetectNote);
+ var instruments = prop.Instruments.Where(i => i.Roots >= 2).ToList();
+ foreach (var inst in instruments)
+ {
+ string name = instruments.Count == 1 ? packName : MultisampleMapper.Pretty(inst.Stem);
+ var p = MultisampleMapper.Build(inst, null, ToRef, name);
+ p.SourceKind = "folder"; p.SourceRef = ToRef(packPath); p.PackId = packId; p.PackName = packName;
+ made.Add((name, p, new Dictionary<string, float>()));
+ }
+ return made;
+ }
+
+ // The SFZ files no other SFZ in the pack #includes (an instrument, not a fragment of one).
+ private static List<string> TopLevelSfz(string root)
+ {
+ List<string> all;
+ try { all = Directory.EnumerateFiles(root, "*.sfz", SearchOption.AllDirectories).OrderBy(f => f, StringComparer.OrdinalIgnoreCase).ToList(); }
+ catch { return new List<string>(); }
+ var included = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ var rx = new System.Text.RegularExpressions.Regex("#include\\s+\"([^\"]+)\"");
+ foreach (var f in all)
+ {
+ string text;
+ try { text = File.ReadAllText(f); } catch { continue; }
+ foreach (System.Text.RegularExpressions.Match m in rx.Matches(text))
+ included.Add(Path.GetFileName(m.Groups[1].Value.Replace('\\', '/')));
+ }
+ return all.Where(f => !included.Contains(Path.GetFileName(f))).ToList();
+ }
+
+ // The envelope / bend / filter the SFZ names, as Mosaic params.
+ private static Dictionary<string, float> ParamsFrom(SfzImportReport r)
+ {
+ var d = new Dictionary<string, float>();
+ if (r.Attack is { } a) d["attack"] = MosaicModel.AttackNorm(a);
+ if (r.Decay is { } dc) d["decay"] = MosaicModel.DecayNorm(dc);
+ if (r.Sustain is { } s) d["sustain"] = (float)s;
+ if (r.Release is { } rel) d["release"] = MosaicModel.DecayNorm(rel);
+ if (r.BendSemis is { } b) d["bendrange"] = (float)Math.Clamp(b / 24.0, 0, 1);
+ if (r.CutoffHz is { } c && c < 18000)
+ {
+ d["filtertype"] = 1f / 3f;
+ d["cutoff"] = (float)Math.Clamp(Math.Log(Math.Max(20, c) / 20.0) / Math.Log(1000.0), 0, 1);
+ }
+ return d;
+ }
+
+ private static string Sanitize(string name)
+ {
+ foreach (char c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '_');
+ return name.Trim().Length == 0 ? "Pack" : name.Trim();
+ }
+}
diff --git a/src/managed/Nota.Infrastructure/Mosaic/MosaicSources.cs b/src/managed/Nota.Infrastructure/Mosaic/MosaicSources.cs
new file mode 100644
index 00000000..ece3a94e
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Mosaic/MosaicSources.cs
@@ -0,0 +1,286 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic's factory multisamples. Like Nota Grain's sources they ship as recipes, not
+// audio: each instrument is a synthesis routine that MosaicSourceLibrary renders into the
+// data folder the first time a preset needs it — one WAV per root × velocity layer (× round-
+// robin step), plus release samples where the instrument has them — named the way sample
+// libraries name theirs ("felt-piano_c4_f.wav", "_rr2", "_rel"), so Mosaic's own file-name
+// mapper lays them out. They are real multisamples: a felt piano with soft and hard strikes and
+// a damper thump per key, mallets and a nylon guitar with alternating strikes, a looping pad.
+
+using System;
+using System.Collections.Generic;
+using Nota.Infrastructure.Kits;
+
+namespace Nota.Infrastructure.Mosaic;
+
+/// <summary>A factory multisample. <see cref="Rev"/> is bumped whenever its recipe changes, so the
+/// rendered files are refreshed. Roots are MIDI notes; Layers are velocity tokens in dynamic order.</summary>
+public sealed record MosaicSource(string Id, string Name, int[] Roots, string[] Layers, int RoundRobin, bool Releases, int Rev, string Blurb)
+{
+ /// <summary>Renders one sample: root, layer index (0 = softest), round-robin step (1-based),
+ /// release; fills L / R (48 kHz). Returns the length used, in samples.</summary>
+ internal Func<int, int, int, bool, Rng, (double[] L, double[] R)> Render { get; init; } = (_, _, _, _, _) => (new double[1], new double[1]);
+
+ /// <summary>Loop the sustain (start, end in seconds) — a pad; null for decaying sounds.</summary>
+ public (double Start, double End)? Loop { get; init; }
+
+ public int Files => Roots.Length * Layers.Length * Math.Max(1, RoundRobin) + (Releases ? Roots.Length : 0);
+}
+
+public static class MosaicSources
+{
+ public const int Rate = 48000;
+ private const double Tau = 2 * Math.PI;
+ private static double Hz(double midi) => 440.0 * Math.Pow(2, (midi - 69) / 12.0);
+ private static int[] Steps(int from, int to, int step) { var l = new List<int>(); for (int n = from; n <= to; n += step) l.Add(n); return l.ToArray(); }
+
+ private static IReadOnlyList<MosaicSource>? _all;
+ public static IReadOnlyList<MosaicSource> All => _all ??= new List<MosaicSource>
+ {
+ new("felt-piano", "Felt Piano", Steps(24, 96, 4), new[] { "p", "f" }, 1, true, 1,
+ "a felted upright: two strike strengths every major third, a damper thump per key") { Render = Piano },
+ new("glass-mallets", "Glass Mallets", Steps(48, 96, 6), new[] { "p", "f" }, 2, false, 1,
+ "a vibraphone-like bar, soft and hard mallets, two alternating strikes") { Render = Mallets },
+ new("nylon", "Nylon Guitar", Steps(40, 79, 3), new[] { "p", "f" }, 2, false, 1,
+ "a plucked nylon string with alternating up and down strokes") { Render = Nylon },
+ new("brass-pluck", "Brass Pluck", Steps(36, 84, 6), new[] { "p", "f" }, 1, false, 1,
+ "a short brassy stab that opens up when hit hard") { Render = Brass },
+ new("warm-pad", "Warm Pad", Steps(36, 84, 12), new[] { "mf" }, 1, false, 1,
+ "a detuned saw pad with a looping sustain") { Render = Pad, Loop = (1.2, 3.6) },
+ new("music-box", "Music Box", Steps(60, 96, 4), new[] { "mf" }, 2, false, 1,
+ "a music-box comb, two slightly different teeth per note") { Render = MusicBox },
+ };
+
+ public static MosaicSource? ById(string id)
+ {
+ foreach (var s in All) if (s.Id == id) return s;
+ return null;
+ }
+
+ // ---- helpers --------------------------------------------------------------------------------
+ private static (double[] L, double[] R) Buf(double seconds) { int n = Math.Max(1, (int)(seconds * Rate)); return (new double[n], new double[n]); }
+ private static double Env(int i, double atk, double decay)
+ {
+ double t = i / (double)Rate;
+ double a = atk <= 0 ? 1 : Math.Min(1, t / atk);
+ return a * Math.Exp(-t / Math.Max(1e-4, decay));
+ }
+ // A one-pole low-pass over a buffer (in place).
+ private static void Lp(double[] x, double hz)
+ {
+ double a = Math.Exp(-Tau * hz / Rate), y = 0;
+ for (int i = 0; i < x.Length; i++) { y = (1 - a) * x[i] + a * y; x[i] = y; }
+ }
+ // A decaying sine added into l / r: a rotating phasor (no sin per sample) that stops once
+ // it has died away — most of a piano's upper partials are gone in a fraction of the file.
+ private static void Partial(double[] l, double[] r, double f, double amp, double decay, double atk, double gl, double gr, double phase, Func<int, double>? mod = null)
+ {
+ double w = Tau * f / Rate, c = Math.Cos(w), sn = Math.Sin(w);
+ double x = Math.Cos(Tau * phase), y = Math.Sin(Tau * phase);
+ double d = Math.Exp(-1.0 / (Math.Max(1e-4, decay) * Rate)), a = amp;
+ int atkN = Math.Max(1, (int)(atk * Rate));
+ for (int i = 0; i < l.Length; i++)
+ {
+ double v = y * a * (i < atkN ? i / (double)atkN : 1.0);
+ if (mod is not null) { double m = mod(i); l[i] += v * gl * m; r[i] += v * gr * (2 - m); }
+ else { l[i] += v * gl; r[i] += v * gr; }
+ double nx = x * c - y * sn; y = x * sn + y * c; x = nx;
+ a *= d;
+ if ((i & 1023) == 0) { double norm = 1.0 / Math.Sqrt(x * x + y * y); x *= norm; y *= norm; if (a < 1e-5 * amp + 1e-9) break; }
+ }
+ }
+
+ // A short fade at the end so nothing clicks.
+ private static void Tail(double[] l, double[] r, double sec = 0.03)
+ {
+ int n = Math.Min(l.Length, (int)(sec * Rate));
+ for (int i = 0; i < n; i++) { double g = i / (double)n; l[l.Length - 1 - i] *= g; r[r.Length - 1 - i] *= g; }
+ }
+
+ // ---- Felt Piano -------------------------------------------------------------------------------
+ // Stretched partials of three slightly detuned strings, the upper ones decaying faster; a
+ // felt hammer softens the top (less so when hit hard) and adds a short knock. The release
+ // sample is the damper landing: a low thud and a little string buzz.
+ private static (double[] L, double[] R) Piano(int note, int layer, int rr, bool release, Rng rng)
+ {
+ double f0 = Hz(note);
+ if (release)
+ {
+ var (rl, rr2) = Buf(0.35);
+ var n = new double[rl.Length];
+ for (int i = 0; i < n.Length; i++) n[i] = rng.NextGauss() * Env(i, 0.002, 0.03);
+ Lp(n, 900);
+ for (int i = 0; i < rl.Length; i++)
+ {
+ double t = i / (double)Rate;
+ double thud = Math.Sin(Tau * Math.Min(f0, 220) * 0.5 * t) * Env(i, 0.001, 0.05) * 0.5;
+ double buzz = Math.Sin(Tau * f0 * t) * Env(i, 0.001, 0.08) * 0.15;
+ double s = (thud + buzz + n[i] * 0.8) * 0.5;
+ rl[i] = s; rr2[i] = s * 0.96;
+ }
+ Tail(rl, rr2);
+ return (rl, rr2);
+ }
+ double hard = layer == 0 ? 0.25 : 0.9;
+ double len = Math.Clamp(5.0 - (note - 24) * 0.045, 1.6, 5.0);
+ var (l, r) = Buf(len);
+ double B = 0.00025 * Math.Pow(2, (note - 60) / 18.0); // inharmonicity
+ double baseDecay = Math.Clamp(3.2 - (note - 24) * 0.03, 0.6, 3.2);
+ int parts = Math.Clamp((int)(9000 / f0), 3, 24);
+ double[] det = { -0.9, 0.0, 1.1 }; // cents, three strings
+ for (int k = 1; k <= parts; k++)
+ {
+ double fk = f0 * k * Math.Sqrt(1 + B * k * k);
+ if (fk > 16000) break;
+ double tilt = Math.Pow(k, -(1.55 - hard * 0.75));
+ double strike = Math.Abs(Math.Sin(Math.PI * k / 7.3)); // hammer position comb
+ double amp = tilt * (0.35 + 0.65 * strike);
+ double dec = baseDecay / (1 + 0.22 * (k - 1) * (1.2 - hard * 0.4));
+ for (int s = 0; s < 3; s++)
+ {
+ double pan = (s - 1) * 0.25;
+ Partial(l, r, fk * Math.Pow(2, det[s] / 1200.0), amp, dec, 0.0015, 1 - pan, 1 + pan, rng.Next01());
+ }
+ }
+ // The hammer knock.
+ var knock = new double[Math.Min(l.Length, Rate / 25)];
+ for (int i = 0; i < knock.Length; i++) knock[i] = rng.NextGauss() * Env(i, 0.0005, 0.006);
+ Lp(knock, 1200 + hard * 2500);
+ for (int i = 0; i < knock.Length; i++) { l[i] += knock[i] * (0.15 + hard * 0.35); r[i] += knock[i] * (0.15 + hard * 0.35); }
+ double g = (layer == 0 ? 0.35 : 1.0) * 0.12;
+ for (int i = 0; i < l.Length; i++) { l[i] *= g; r[i] *= g; }
+ Tail(l, r);
+ return (l, r);
+ }
+
+ // ---- Glass Mallets ----------------------------------------------------------------------------
+ private static (double[] L, double[] R) Mallets(int note, int layer, int rr, bool release, Rng rng)
+ {
+ double f0 = Hz(note);
+ var (l, r) = Buf(2.6);
+ double hard = layer == 0 ? 0.2 : 1.0;
+ (double Ratio, double Amp, double Dec)[] modes = { (1, 1, 1.6), (4.0, 0.35 * (0.3 + hard), 0.45), (10.0, 0.12 * hard, 0.12), (2.76, 0.05, 0.3) };
+ double detune = rr == 2 ? 1.0015 : 1.0;
+ foreach (var (ratio, amp, dec) in modes)
+ {
+ double f = f0 * ratio * detune;
+ if (f > 18000) continue;
+ Partial(l, r, f, amp, dec, 0.0008, 1, 1, rng.Next01(), i => 1 + 0.12 * Math.Sin(Tau * 5.2 * i / Rate));
+ }
+ double g = (layer == 0 ? 0.4 : 1.0) * 0.28;
+ for (int i = 0; i < l.Length; i++) { l[i] *= g; r[i] *= g; }
+ Tail(l, r);
+ return (l, r);
+ }
+
+ // ---- Nylon Guitar (Karplus–Strong) ------------------------------------------------------------
+ private static (double[] L, double[] R) Nylon(int note, int layer, int rr, bool release, Rng rng)
+ {
+ double f0 = Hz(note);
+ double len = Math.Clamp(3.6 - (note - 40) * 0.04, 1.4, 3.6);
+ var (l, r) = Buf(len);
+ int period = Math.Max(2, (int)Math.Round(Rate / f0));
+ var line = new double[period];
+ double bright = layer == 0 ? 0.35 : 0.85;
+ for (int i = 0; i < period; i++) line[i] = rng.Next() * (rr == 2 ? -1 : 1);
+ var tmp = new double[period];
+ for (int pass = 0; pass < (int)((1 - bright) * 6); pass++) // soften the pluck
+ {
+ for (int i = 0; i < period; i++) tmp[i] = 0.5 * (line[i] + line[(i + 1) % period]);
+ Array.Copy(tmp, line, period);
+ }
+ double loss = 0.4985 + 0.0013 * Math.Clamp((60 - note) / 30.0, 0, 1);
+ int p = 0; double prev = 0;
+ for (int i = 0; i < l.Length; i++)
+ {
+ double cur = line[p];
+ double nxt = loss * (cur + line[(p + 1) % period]) * (0.996 + 0.004 * bright);
+ line[p] = nxt;
+ p = (p + 1) % period;
+ double body = cur + 0.25 * (cur - prev); prev = cur;
+ l[i] = body; r[i] = body * 0.92 + 0.08 * cur;
+ }
+ double g = (layer == 0 ? 0.45 : 1.0) * 0.5;
+ for (int i = 0; i < l.Length; i++) { l[i] *= g; r[i] *= g; }
+ Tail(l, r);
+ return (l, r);
+ }
+
+ // ---- Brass Pluck --------------------------------------------------------------------------------
+ private static (double[] L, double[] R) Brass(int note, int layer, int rr, bool release, Rng rng)
+ {
+ double f0 = Hz(note);
+ var (l, r) = Buf(1.4);
+ double hard = layer == 0 ? 0.3 : 1.0;
+ double p1 = 0, p2 = 0, lp = 0, lp2 = 0;
+ for (int i = 0; i < l.Length; i++)
+ {
+ double t = i / (double)Rate;
+ double env = Math.Min(1, t / 0.012) * Math.Exp(-t / 0.5);
+ double cut = 300 + (900 + 5200 * hard) * Math.Exp(-t / (0.08 + 0.12 * hard)) + 400 * env;
+ double s1 = 2 * p1 - 1, s2 = 2 * p2 - 1;
+ p1 += f0 / Rate; if (p1 >= 1) p1 -= 1;
+ p2 += f0 * 1.003 / Rate; if (p2 >= 1) p2 -= 1;
+ double a = Math.Exp(-Tau * cut / Rate);
+ lp = (1 - a) * (s1 + s2) * 0.5 + a * lp;
+ lp2 = (1 - a) * lp + a * lp2;
+ double v = lp2 * env;
+ l[i] = v; r[i] = v;
+ }
+ double g = (layer == 0 ? 0.45 : 1.0) * 0.5;
+ for (int i = 0; i < l.Length; i++) { l[i] *= g; r[i] *= g; }
+ Tail(l, r);
+ return (l, r);
+ }
+
+ // ---- Warm Pad (loops 1.2 … 3.6 s) ----------------------------------------------------------------
+ private static (double[] L, double[] R) Pad(int note, int layer, int rr, bool release, Rng rng)
+ {
+ double f0 = Hz(note);
+ var (l, r) = Buf(4.0);
+ double[] det = { -9, -3, 2, 8, 13 };
+ var ph = new double[det.Length];
+ for (int k = 0; k < ph.Length; k++) ph[k] = rng.Next01();
+ double lpL = 0, lpR = 0, lpL2 = 0, lpR2 = 0;
+ for (int i = 0; i < l.Length; i++)
+ {
+ double t = i / (double)Rate;
+ double sl = 0, sr = 0;
+ for (int k = 0; k < det.Length; k++)
+ {
+ double f = f0 * Math.Pow(2, det[k] / 1200.0);
+ double s = 2 * ph[k] - 1;
+ ph[k] += f / Rate; if (ph[k] >= 1) ph[k] -= 1;
+ double pan = (k - 2) / 2.5;
+ sl += s * (1 - pan * 0.5); sr += s * (1 + pan * 0.5);
+ }
+ double cut = 900 + 500 * Math.Sin(Tau * 0.25 * t);
+ double a = Math.Exp(-Tau * cut / Rate);
+ lpL = (1 - a) * sl + a * lpL; lpL2 = (1 - a) * lpL + a * lpL2;
+ lpR = (1 - a) * sr + a * lpR; lpR2 = (1 - a) * lpR + a * lpR2;
+ double env = Math.Min(1, t / 0.6);
+ l[i] = lpL2 * env * 0.09; r[i] = lpR2 * env * 0.09;
+ }
+ Tail(l, r);
+ return (l, r);
+ }
+
+ // ---- Music Box ----------------------------------------------------------------------------------
+ private static (double[] L, double[] R) MusicBox(int note, int layer, int rr, bool release, Rng rng)
+ {
+ double f0 = Hz(note) * (rr == 2 ? 1.002 : 0.999);
+ var (l, r) = Buf(2.2);
+ (double Ratio, double Amp, double Dec)[] modes = { (1, 1, 1.1), (5.4, 0.25, 0.18), (11.2, 0.08, 0.05), (2.0, 0.1, 0.5) };
+ foreach (var (ratio, amp, dec) in modes)
+ {
+ double f = f0 * ratio;
+ if (f > 18000) continue;
+ Partial(l, r, f, amp, dec, 0.0004, 1, rr == 2 ? 0.9 : 1.0, 0);
+ }
+ for (int i = 0; i < l.Length; i++) { l[i] *= 0.3; r[i] *= 0.3; }
+ Tail(l, r);
+ return (l, r);
+ }
+}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 728cbc05..e3ac3646 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -1046,6 +1046,27 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Inst("keys", 16, "Toy Box", ("model", 0.667f), ("hard", 1f), ("bright", 1f), ("decay", 0.3f), ("body", 0.2f), ("keybright", 0.9f), ("cab", 0.667f), ("dist", 0.4f), ("sym", 0.5f));
Inst("keys", 16, "Ambient Tine", ("hard", 0.2f), ("velhard", 0.5f), ("decay", 1f), ("damper", 0.2f), ("choruson", 1f), ("chorusmix", 0.65f), ("phaseron", 1f), ("phaserrate", 0.2f), ("phaserdepth", 0.4f), ("tremon", 1f), ("tremrate", 0.4f), ("tremdepth", 0.35f));
+ // ---- Nota Mosaic (kind 17) — multisample. Each preset loads a factory multisample
+ // (MosaicSources: rendered once into the data folder, mapped by its file names);
+ // Init keeps the loaded program and resets the sound. Pack presets (installed sample
+ // packs, "Create multisample") live under Nota Mosaic → Packs, not here. Release /
+ // decay 2 ms·3000^v (.69 ≈ 0.5 s, .83 ≈ 1.5 s, .91 ≈ 3 s); attack 0.5 ms·8000^v
+ // (.71 ≈ 0.3 s); cutoff 20 Hz·1000^v (.67 ≈ 2 kHz); Vel Curve .5 linear (< .5 soft).
+ Inst("mosaic", 17, "Init");
+ Section("Keys");
+ Mos("Felt Piano", "felt-piano", ("release", 0.75f), ("velamount", 0.8f));
+ Mos("Felt Piano Soft", "felt-piano", ("release", 0.72f), ("velamount", 0.75f), ("velcurve", 0.35f), ("filtertype", 1f / 3f), ("cutoff", 0.62f), ("keytrack", 0.5f), ("relvol", 0.6f));
+ Mos("Felt Piano Bright", "felt-piano", ("release", 0.72f), ("velamount", 0.85f), ("velcurve", 0.65f), ("relvol", 0.7f));
+ Mos("Music Box", "music-box", ("release", 0.78f), ("velamount", 0.6f));
+ Section("Mallets & Plucks");
+ Mos("Glass Mallets", "glass-mallets", ("release", 0.76f), ("velamount", 0.75f));
+ Mos("Nylon Guitar", "nylon", ("release", 0.66f), ("velamount", 0.8f));
+ Mos("Brass Pluck", "brass-pluck", ("release", 0.55f), ("velamount", 0.8f));
+ Mos("Brass Lead", "brass-pluck", ("voicemode", 0.5f), ("glide", 0.54f), ("release", 0.5f), ("velamount", 0.6f));
+ Section("Pads");
+ Mos("Warm Pad", "warm-pad", ("attack", 0.71f), ("release", 0.85f), ("velamount", 0.4f));
+ Mos("Warm Pad Filtered", "warm-pad", ("attack", 0.8f), ("release", 0.9f), ("velamount", 0.4f), ("filtertype", 1f / 3f), ("cutoff", 0.55f), ("envcutoff", 1f), ("envamount", 0.7f));
+
// ---- Nota EQ-8 (kind 0) — raw units. Eq8(…) spells out every band it uses with B(band, type,
// Hz, dB, Q, slope, channel); a band it does not name is switched off. Type: 0 Low cut,
// 1 Low shelf, 2 Bell, 3 Notch, 4 High shelf, 5 High cut. Slope (cuts): 0 = 12, 1 = 24,
@@ -2577,6 +2598,13 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
_byId["grain/" + name].GrainSource = source;
}
+ // A Nota Mosaic preset that loads one of the factory multisamples (MosaicSources id).
+ private void Mos(string name, string source, params (string Id, float Value)[] ps)
+ {
+ Inst("mosaic", MosaicModel.Kind, name, ps);
+ _byId["mosaic/" + name].MosaicSource = source;
+ }
+
private void Fx(string group, int kind, string name, params (string Name, float Value)[] ps)
=> Add(group, name, "builtin-effect", kind, isInstrument: false, isMidi: false, ps);
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs b/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs
index 6aa1da1e..ff7df5b9 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs
@@ -38,6 +38,16 @@ public sealed class PresetDocument
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? GrainSource { get; set; }
+ /// <summary>Nota Mosaic factory presets: the factory multisample (MosaicSources id) the
+ /// preset renders on first use and loads. Null = none.</summary>
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public string? MosaicSource { get; set; }
+
+ /// <summary>Nota Mosaic: the program text (zones + sample references) the preset loads.
+ /// Null = keep the loaded program (a sound-only preset).</summary>
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public string? MosaicProgram { get; set; }
+
// Plugin: stable identity + base64-encoded state blob.
public string PluginId { get; set; } = "";
public string StateBase64 { get; set; } = "";
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
index be60ddcd..3df124a7 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
@@ -33,7 +33,7 @@ public static class PresetService
doc.StateBase64 = Convert.ToBase64String(engine.GetPluginState(trackId, -1));
return string.IsNullOrEmpty(doc.PluginId) ? null : doc;
}
- // Built-in instrument: capture the normalized plugin-params by id. Skip kinds whose
+ // Built-in instrument: capture the normalized plugin-params by id (+ a Mosaic's program). Skip kinds whose
// state isn't fully recallable from params alone — Grain (10) needs the sample and
// the Instrument/Drum racks (3/4) their chains. The Sampler (1) saves its sound —
// envelope, filter, pitch, loop, voices — and applying it keeps whatever sample is
@@ -54,6 +54,8 @@ public static class PresetService
if (InstrumentView.IsViewParam(id)) continue; // the card size is editor state, not sound
doc.NamedParams[id] = engine.PluginParamGet(trackId, -1, i);
}
+ // Nota Mosaic: the zone map travels with the sound (its samples stay referenced).
+ if (ik == MosaicModel.Kind && engine.MosaicProgram(trackId) is { Length: > 0 } prog) doc.MosaicProgram = prog;
return doc;
}
}
@@ -224,6 +226,7 @@ public static class PresetService
14 => engine.AddPentadTrack(),
15 => engine.AddConsortTrack(),
16 => engine.AddKeysTrack(),
+ 17 => engine.AddMosaicTrack(),
_ => engine.AddInstrumentTrack(),
};
if (t <= 0) return "Failed to add instrument.";
@@ -235,7 +238,8 @@ public static class PresetService
&& doc.NamedParams.TryGetValue(pid, out var v))
engine.PluginParamSet(t, -1, i, v);
}
- return LoadGrainSource(doc, engine, t);
+ string mw = LoadMosaicProgram(doc, engine, t);
+ return mw.Length > 0 ? mw : LoadGrainSource(doc, engine, t);
}
case "plugin-effect":
{
@@ -271,6 +275,23 @@ public static class PresetService
return engine.SetTrackGrainSample(trackId, path, src.Root) ? "" : $"Couldn't load the sample \"{src.Name}\".";
}
+ // A Nota Mosaic preset loads its program: a factory multisample (rendered on first use) or
+ // the program text it carries. Loading itself runs in the background in the engine.
+ private static string LoadMosaicProgram(PresetDocument doc, IAudioEngine engine, int trackId)
+ {
+ if (doc.BuiltinKind != MosaicModel.Kind) return "";
+ if (!string.IsNullOrEmpty(doc.MosaicSource))
+ {
+ var prog = global::Nota.Infrastructure.Mosaic.MosaicSourceLibrary.Program(doc.MosaicSource);
+ if (prog is null) return $"Couldn't prepare the multisample \"{doc.MosaicSource}\".";
+ prog.Name = doc.DisplayName.Length > 0 ? doc.DisplayName : prog.Name;
+ engine.MosaicSetProgram(trackId, prog.Serialize());
+ return "";
+ }
+ if (!string.IsNullOrEmpty(doc.MosaicProgram)) engine.MosaicSetProgram(trackId, doc.MosaicProgram);
+ return "";
+ }
+
/// <summary>Applies a preset to an EXISTING instrument/device in place (no new track/
/// device is created) — for the in-header preset picker. Built-in instruments reset all
/// params to default first so the patch is clean; effects set the preset's named params.</summary>
@@ -297,7 +318,8 @@ public static class PresetService
float v = named ? doc.NamedParams![id] : engine.InstrumentParamDefault(trackId, i);
engine.PluginParamSet(trackId, -1, i, v);
}
- return kind == 10 ? LoadGrainSource(doc, engine, trackId) : "";
+ return kind == 10 ? LoadGrainSource(doc, engine, trackId)
+ : kind == MosaicModel.Kind ? LoadMosaicProgram(doc, engine, trackId) : "";
}
case "builtin-effect":
{
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 86ca0429..8ab15bfa 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -535,6 +535,7 @@ public sealed class ProjectService
{ Kind: 14 } => engine.AddPentadTrack(), // Nota Pentad
{ Kind: 15 } => engine.AddConsortTrack(), // Nota Consort
{ Kind: 16 } => engine.AddKeysTrack(), // Nota Keys
+ { Kind: 17 } => engine.AddMosaicTrack(), // Nota Mosaic (its program rides the state blob)
_ => engine.AddInstrumentTrack(), // Nota Synth
};
if (t.Instrument?.State is { } synthState)
diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
index bcc5e6cd..1e27a753 100644
--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
@@ -20,7 +20,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
(4, "Drum Rack"), (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"),
- (16, "Nota Keys"),
+ (16, "Nota Keys"), (17, "Nota Mosaic"),
};
public sealed record InstrumentKind(int Kind, string Name);
@@ -30,7 +30,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
public InstrumentKind[] ListInstrumentKinds() => Array.ConvertAll(Kinds, k => new InstrumentKind(k.Kind, k.Name));
[McpServerTool(Name = "add_instrument_track"), Description("Add an instrument track with the given built-in kind (see list_instrument_kinds). Returns the track id.")]
- public Task<int> AddInstrumentTrack([Description("Instrument kind id (0..16)")] int kind) => Mutate(() => kind switch
+ public Task<int> AddInstrumentTrack([Description("Instrument kind id (0..17)")] int kind) => Mutate(() => kind switch
{
1 => E.AddSamplerInstrumentTrack(),
2 => E.AddPhysicalSynthTrack(),
@@ -48,6 +48,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
14 => E.AddPentadTrack(),
15 => E.AddConsortTrack(),
16 => E.AddKeysTrack(),
+ 17 => E.AddMosaicTrack(),
_ => E.AddInstrumentTrack(), // 0 = Nota Synth
});
diff --git a/src/managed/Nota.Mcp/Tools/MosaicTools.cs b/src/managed/Nota.Mcp/Tools/MosaicTools.cs
new file mode 100644
index 00000000..3ac18465
--- /dev/null
+++ b/src/managed/Nota.Mcp/Tools/MosaicTools.cs
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// MCP tools — Nota Mosaic (instrument kind 17), the multisample instrument: read it, shape its
+// shared sound in musical units, edit zones and groups, import an SFZ, map a folder of samples
+// by their file names, and list / load its presets (factory multisamples and pack presets).
+
+using System.ComponentModel;
+using System.Globalization;
+using ModelContextProtocol.Server;
+using Nota.Application;
+using Nota.Application.Mosaic;
+
+namespace Nota.Mcp.Tools;
+
+[McpServerToolType]
+public sealed class MosaicTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh, IMosaicPacks packs, IFactoryPresets factory)
+ : EngineTools(engine, dispatch, refresh)
+{
+ public sealed record GroupRow(int Index, string Name, int Zones, double GainDb, double TuneCents, int RoundRobin, string RoundRobinMode, bool Release);
+ public sealed record ZoneRow(int Index, string File, string Root, string Keys, string Velocity, int Group, int Step, bool Release,
+ double TuneCents, double GainDb, double Pan, string Loop);
+ public sealed record MosaicReading(string Summary, string Guide, string Name, string Source, string Pack, string Loading,
+ int Files, int MissingFiles, double RamMb, int Zones, int Roots, int VelocityLayers, int ReleaseZones,
+ int ActiveVoices, int VoiceLimit, int PerKey, bool PedalDown, GroupRow[] Groups, ZoneRow[]? ZoneList);
+ public sealed record SfzImport(int TrackId, string Summary, int Regions, int Imported, int Groups, int Includes, int Missing,
+ string[] Ignored, string[] Controllers);
+ public sealed record MappedRow(string File, string Note, string From, string Layer, int Rr, bool Release, int Confidence, bool Duplicate);
+ public sealed record MappedInstrumentRow(string Name, int Files, int Roots, string[] Layers, int RoundRobin, int ReleaseSamples,
+ int Confidence, string[] Gaps, MappedRow[] Rows);
+ public sealed record MultisampleResult(string OctaveVerdict, int OctaveShift, MappedInstrumentRow[] Instruments, int TrackId, string[] Presets);
+ public sealed record PresetRow(string Name, string Kind, string Folder);
+
+ private float Get(int t, string id)
+ {
+ int pc = E.PluginParamCount(t, -1);
+ for (int i = 0; i < pc; i++) if (E.PluginParamId(t, -1, i) == id) return E.PluginParamGet(t, -1, i);
+ return 0f;
+ }
+ private void Set(int t, string id, double v)
+ {
+ int pc = E.PluginParamCount(t, -1);
+ for (int i = 0; i < pc; i++) if (E.PluginParamId(t, -1, i) == id) { E.PluginParamSet(t, -1, i, (float)Math.Clamp(v, 0, 1)); return; }
+ }
+ private bool IsMosaic(int t) => E.TrackInstrumentKind(t) == MosaicModel.Kind;
+
+ [McpServerTool(Name = "read_mosaic"), Description(
+ "Read a Nota Mosaic track (built-in instrument kind 17, the multisample instrument). Returns a summary, a guide, the "
+ + "program (name, source: sfz / folder / factory / sample, the registry pack it uses), loading state (loading / ready, "
+ + "files, missing files, RAM in MB), zones / roots / velocity layers / release zones, the groups (gain, tune, round-robin "
+ + "length and mode) and the voices (sounding / limit, strikes per key, pedal down). includeZones lists every zone "
+ + "(index for set_mosaic_zone, file, root, key and velocity ranges, group, round-robin step, release, tune, gain, pan, loop).")]
+ public Task<MosaicReading?> ReadMosaic(int trackId, bool includeZones = false) => Read<MosaicReading?>(() =>
+ {
+ if (!IsMosaic(trackId)) return null;
+ var p = MosaicProgram.Parse(E.MosaicProgram(trackId));
+ E.TryGetMosaicStatus(trackId, out var st);
+ var sc = new float[MosaicModel.ScopeLength];
+ int n = E.InstrumentScope(trackId, sc);
+ var snap = new MosaicModel.Snapshot();
+ MosaicModel.Parse(sc.AsSpan(0, Math.Max(0, n)), snap);
+ string loading = st.FilesTotal == 0 ? "empty" : st.State == 1 ? $"loading {st.FilesDone}/{st.FilesTotal}" : "ready";
+ var groups = p.Groups.Select((g, i) => new GroupRow(i, g.Name, p.Zones.Count(z => z.Group == i), g.GainDb, g.Tune, g.SeqLen,
+ MosaicProgram.RrNames[Math.Clamp(g.RrMode, 0, 2)], p.Zones.Any(z => z.Group == i) && p.Zones.Where(z => z.Group == i).All(z => z.Release))).ToArray();
+ ZoneRow[]? zones = includeZones
+ ? p.Zones.Select((z, i) => new ZoneRow(i, p.FileName(z.File), MosaicNames.NoteName(z.Root),
+ $"{MosaicNames.NoteName(z.KeyLo)}-{MosaicNames.NoteName(z.KeyHi)}", $"{z.VelLo}-{z.VelHi}", z.Group, z.Seq, z.Release,
+ z.Tune, z.GainDb, z.Pan, MosaicModel.LoopNames[Math.Clamp(z.LoopMode, 0, 2)])).ToArray()
+ : null;
+ return new MosaicReading(MosaicModel.Summary(p, id => Get(trackId, id)), MosaicModel.Guide, p.Name, p.SourceKind, p.PackId, loading,
+ st.FilesTotal, st.Missing, Math.Round(st.RamBytes / 1048576.0, 1), p.Zones.Count, p.Roots.Count(), p.VelocityLayers, p.ReleaseZones,
+ snap.Voices, MosaicModel.Poly(Get(trackId, "polyphony")), MosaicModel.PerKey(Get(trackId, "perkey")), snap.Pedal, groups, zones);
+ });
+
+ [McpServerTool(Name = "set_mosaic"), Description(
+ "Shape a Nota Mosaic's shared sound (kind 17) in musical units; every argument is optional and only the given ones change. "
+ + "voiceMode Poly | Mono | Choke; polyphony 16 | 32 | 64 | 128; perKey 1..4 (strikes of one key ringing together); "
+ + "oldFadeMs 1..200 (how fast a stolen voice fades); releaseTriggers on/off; releaseVolumeDb -36..6; releaseDropDb 0..-24 "
+ + "(how much quieter a release sample is after a 2 s hold); velocityPercent 0..100 (Vel → Vol); velocityCurve -100 (soft) "
+ + "… 100 (hard); pedal (listen to CC64); bendSemitones 0..24; attackMs / decayMs / releaseMs; sustainPercent; "
+ + "filter Off | LP | HP | BP with cutoffHz and resonancePercent; transposeSemitones -24..24; glideMs (0 = off); volumeDb.")]
+ public Task<string> SetMosaic(int trackId, string? voiceMode = null, int? polyphony = null, int? perKey = null, double? oldFadeMs = null,
+ bool? releaseTriggers = null, double? releaseVolumeDb = null, double? releaseDropDb = null, double? velocityPercent = null,
+ double? velocityCurve = null, bool? pedal = null, int? bendSemitones = null, double? attackMs = null, double? decayMs = null,
+ double? sustainPercent = null, double? releaseMs = null, string? filter = null, double? cutoffHz = null, double? resonancePercent = null,
+ double? transposeSemitones = null, double? glideMs = null, double? volumeDb = null) => Mutate(() =>
+ {
+ if (!IsMosaic(trackId)) return $"error: track {trackId} is not a Nota Mosaic";
+ var errors = new List<string>();
+ static int Find(string[] names, string v) => Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase));
+ if (voiceMode is not null) { int m = Find(MosaicModel.VoiceNames, voiceMode); if (m < 0) errors.Add($"voiceMode '{voiceMode}'"); else Set(trackId, "voicemode", m / 2.0); }
+ if (polyphony is { } pv) { int i = Array.IndexOf(MosaicModel.PolyCounts, pv); if (i < 0) errors.Add($"polyphony {pv}"); else Set(trackId, "polyphony", i / 3.0); }
+ if (perKey is { } pk) Set(trackId, "perkey", (Math.Clamp(pk, 1, 4) - 1) / 3.0);
+ if (oldFadeMs is { } of) Set(trackId, "oldfade", MosaicModel.OldFadeNorm(of));
+ if (releaseTriggers is { } rt) Set(trackId, "relon", rt ? 1 : 0);
+ if (releaseVolumeDb is { } rv) Set(trackId, "relvol", MosaicModel.RelVolNorm(rv));
+ if (releaseDropDb is { } rd) Set(trackId, "rellen", MosaicModel.RelLenNorm(-Math.Abs(rd)));
+ if (velocityPercent is { } vp) Set(trackId, "velamount", Math.Clamp(vp, 0, 100) / 100.0);
+ if (velocityCurve is { } vc) Set(trackId, "velcurve", 0.5 + Math.Clamp(vc, -100, 100) / 200.0);
+ if (pedal is { } pd) Set(trackId, "pedal", pd ? 1 : 0);
+ if (bendSemitones is { } bs) Set(trackId, "bendrange", Math.Clamp(bs, 0, 24) / 24.0);
+ if (attackMs is { } a) Set(trackId, "attack", MosaicModel.AttackNorm(a / 1000.0));
+ if (decayMs is { } d) Set(trackId, "decay", MosaicModel.DecayNorm(d / 1000.0));
+ if (releaseMs is { } r) Set(trackId, "release", MosaicModel.DecayNorm(r / 1000.0));
+ if (sustainPercent is { } s) Set(trackId, "sustain", Math.Clamp(s, 0, 100) / 100.0);
+ if (filter is not null) { int f = Find(MosaicModel.FilterNames, filter); if (f < 0) errors.Add($"filter '{filter}'"); else Set(trackId, "filtertype", f / 3.0); }
+ if (cutoffHz is { } c) Set(trackId, "cutoff", Math.Log(Math.Clamp(c, 20, 20000) / 20.0) / Math.Log(1000.0));
+ if (resonancePercent is { } rs) Set(trackId, "resonance", Math.Clamp(rs, 0, 100) / 100.0);
+ if (transposeSemitones is { } ts) Set(trackId, "transpose", 0.5 + Math.Clamp(Math.Round(ts), -24, 24) / 48.0);
+ if (glideMs is { } g) Set(trackId, "glide", g <= 0 ? 0 : Math.Log(Math.Clamp(g, 1, 2000)) / Math.Log(2000.0));
+ if (volumeDb is { } vd) Set(trackId, "volume", Math.Pow(10, Math.Clamp(vd, -60, 0) / 20.0));
+ string summary = MosaicModel.Summary(MosaicProgram.Parse(E.MosaicProgram(trackId)), id => Get(trackId, id));
+ return errors.Count == 0 ? summary : $"error: could not use {string.Join(", ", errors)} · {summary}";
+ });
+
+ [McpServerTool(Name = "set_mosaic_zone"), Description(
+ "Edit one zone of a Nota Mosaic (indices from read_mosaic includeZones); only the given fields change. zone -1 adds a zone "
+ + "playing sampleFile (an absolute path). root / keyLo / keyHi as note names (C4 = 60) or MIDI numbers; velLo / velHi 0..127; "
+ + "tuneCents; gainDb; pan -1..1; loop Off | Fwd | Ping; group (index); step (round-robin position); release (a release "
+ + "trigger); remove deletes the zone. One undo step. Returns the program summary.")]
+ public Task<string> SetMosaicZone(int trackId, int zone, string? sampleFile = null, string? root = null, string? keyLo = null, string? keyHi = null,
+ int? velLo = null, int? velHi = null, double? tuneCents = null, double? gainDb = null, double? pan = null, string? loop = null,
+ int? group = null, int? step = null, bool? release = null, bool remove = false) => Mutate(() =>
+ {
+ if (!IsMosaic(trackId)) return $"error: track {trackId} is not a Nota Mosaic";
+ var p = MosaicProgram.Parse(E.MosaicProgram(trackId));
+ MosaicZone z;
+ if (zone < 0)
+ {
+ if (sampleFile is null || !File.Exists(sampleFile)) return "error: a new zone needs an existing sampleFile";
+ if (p.Groups.Count == 0) p.Groups.Add(new MosaicGroup { Name = "Group 1" });
+ p.Files.Add(packs.ToRef(sampleFile));
+ int r = SamplerModel.DetectRoot(sampleFile) is var dr and >= 0 ? dr : 60;
+ z = new MosaicZone { File = p.Files.Count - 1, Root = r, KeyLo = r, KeyHi = r };
+ p.Zones.Add(z);
+ }
+ else if (zone >= p.Zones.Count) return $"error: zone {zone} doesn't exist ({p.Zones.Count} zones)";
+ else z = p.Zones[zone];
+ if (remove && zone >= 0) p.Zones.RemoveAt(zone);
+ else
+ {
+ static int? Note(string? s) => s is null ? null : SfzImporter.Note(s.Replace("♯", "#"));
+ if (Note(root) is { } rn) z.Root = rn;
+ if (Note(keyLo) is { } kl) z.KeyLo = kl;
+ if (Note(keyHi) is { } kh) z.KeyHi = kh;
+ if (velLo is { } vl) z.VelLo = Math.Clamp(vl, 0, 127);
+ if (velHi is { } vh) z.VelHi = Math.Clamp(vh, 0, 127);
+ if (z.KeyLo > z.KeyHi) (z.KeyLo, z.KeyHi) = (z.KeyHi, z.KeyLo);
+ if (z.VelLo > z.VelHi) (z.VelLo, z.VelHi) = (z.VelHi, z.VelLo);
+ if (tuneCents is { } tc) z.Tune = Math.Clamp(tc, -1200, 1200);
+ if (gainDb is { } gd) z.GainDb = Math.Clamp(gd, -60, 24);
+ if (pan is { } pn) z.Pan = Math.Clamp(pn, -1, 1);
+ if (loop is not null) { int l = Array.FindIndex(MosaicModel.LoopNames, x => string.Equals(x, loop.Trim(), StringComparison.OrdinalIgnoreCase)); if (l >= 0) z.LoopMode = l; }
+ if (group is { } g && g >= 0 && g < p.Groups.Count) z.Group = g;
+ if (step is { } sp) z.Seq = Math.Max(1, sp);
+ if (release is { } rl) z.Release = rl;
+ }
+ E.MosaicSetProgram(trackId, p.Serialize());
+ return p.Summary();
+ });
+
+ [McpServerTool(Name = "set_mosaic_group"), Description(
+ "Edit a group (layer) of a Nota Mosaic: name, gainDb, tuneCents, roundRobin (steps 1..16) and roundRobinMode Sequential | "
+ + "Random | No repeat. group -1 adds a group. One undo step.")]
+ public Task<string> SetMosaicGroup(int trackId, int group, string? name = null, double? gainDb = null, double? tuneCents = null,
+ int? roundRobin = null, string? roundRobinMode = null) => Mutate(() =>
+ {
+ if (!IsMosaic(trackId)) return $"error: track {trackId} is not a Nota Mosaic";
+ var p = MosaicProgram.Parse(E.MosaicProgram(trackId));
+ MosaicGroup g;
+ if (group < 0) { g = new MosaicGroup { Name = $"Group {p.Groups.Count + 1}" }; p.Groups.Add(g); }
+ else if (group >= p.Groups.Count) return $"error: group {group} doesn't exist ({p.Groups.Count} groups)";
+ else g = p.Groups[group];
+ if (name is not null) g.Name = name;
+ if (gainDb is { } gd) g.GainDb = Math.Clamp(gd, -60, 24);
+ if (tuneCents is { } tc) g.Tune = Math.Clamp(tc, -1200, 1200);
+ if (roundRobin is { } rr) g.SeqLen = Math.Clamp(rr, 1, 16);
+ if (roundRobinMode is not null)
+ {
+ int m = Array.FindIndex(MosaicProgram.RrNames, x => string.Equals(x, roundRobinMode.Trim(), StringComparison.OrdinalIgnoreCase));
+ if (m < 0) return $"error: roundRobinMode '{roundRobinMode}'";
+ g.RrMode = m;
+ }
+ E.MosaicSetProgram(trackId, p.Serialize());
+ return p.Summary();
+ });
+
+ [McpServerTool(Name = "import_sfz"), Description(
+ "Load an SFZ instrument into a Nota Mosaic (trackId <= 0 adds a new Mosaic track). controllers selects an articulation "
+ + "the SFZ switches by CC, e.g. \"110=64\" (comma-separated). Samples load in the background. Returns what was imported "
+ + "and what Mosaic ignored (modulation it doesn't play), and the articulation controllers with their values.")]
+ public Task<SfzImport> ImportSfz(string path, int trackId = -1, string? controllers = null) => Mutate(() =>
+ {
+ if (!File.Exists(path)) return new SfzImport(-1, $"error: no such file {path}", 0, 0, 0, 0, 0, Array.Empty<string>(), Array.Empty<string>());
+ var ccs = new Dictionary<int, int>();
+ foreach (var part in (controllers ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var kv = part.Split('=');
+ if (kv.Length == 2 && int.TryParse(kv[0].Trim().TrimStart('c', 'C'), NumberStyles.Integer, CultureInfo.InvariantCulture, out int c)
+ && int.TryParse(kv[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) ccs[c] = v;
+ }
+ var res = SfzImporter.Import(path, ccs, packs.ToRef);
+ res.Program.SourceRef = packs.ToRef(path);
+ int t = trackId > 0 && IsMosaic(trackId) ? trackId : E.AddMosaicTrack();
+ E.MosaicSetProgram(t, res.Program.Serialize());
+ var r = res.Report;
+ return new SfzImport(t, r.Summary(), r.Regions, r.Imported, r.Groups, r.Includes, r.Missing,
+ r.Ignored.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Key} ({kv.Value})").ToArray(),
+ r.CcState.Select(kv => $"cc{kv.Key}={kv.Value}" + (r.CcLabels.TryGetValue(kv.Key, out var l) ? $" {l}" : "")).ToArray());
+ });
+
+ [McpServerTool(Name = "create_multisample"), Description(
+ "Map a folder of samples into Nota Mosaic instruments by their file names (\"trombone_gb4.wav\", \"piano_c4_f_rr2.wav\", "
+ + "\"x_a2_rel.wav\"): each name stem is an instrument; the note, velocity layer (pp…ff, v1…), round-robin step (rr2) and "
+ + "release mark come from the name, a file without a note gets one from pitch detection, and the octave numbering "
+ + "(C3 or C4 = 60) is checked by ear. dryRun (default) returns the proposal: per instrument its files, roots, layers, "
+ + "gaps and every file's reading. With dryRun false, instrument (a name stem, default the first) loads into trackId "
+ + "(<= 0: a new Mosaic track) and savePresets writes a preset per instrument under Nota Mosaic → Packs → the folder's name. "
+ + "octave forces the convention: \"C4\" (names as written) or \"C3\" (shift up an octave).")]
+ public async Task<MultisampleResult> CreateMultisample(string folder, bool dryRun = true, string? instrument = null, int trackId = -1,
+ bool savePresets = false, string? octave = null, int edgeStretch = 12)
+ {
+ var opt = new MultisampleOptions { EdgeStretch = Math.Clamp(edgeStretch, 0, 48) };
+ if (octave is not null) opt.OctaveShift = octave.Trim().ToUpperInvariant() == "C3" ? 12 : 0;
+ var prop = await Task.Run(() => Directory.Exists(folder) ? MultisampleMapper.MapFolder(folder, opt, packs.DetectNote) : new MultisampleProposal());
+ opt.OctaveShift ??= prop.OctaveShift;
+ var rows = prop.Instruments.Select(i => new MappedInstrumentRow(i.Stem, i.Files.Count, i.Roots, i.Layers.ToArray(), i.MaxRr,
+ i.Used.Count(f => f.Release), i.Confidence, i.Gaps.Select(MosaicNames.NoteName).ToArray(),
+ i.Files.Select(f => new MappedRow(f.Name, f.NoteText, f.NoteFrom, f.Layer, f.Rr, f.Release, f.Confidence, f.Duplicate)).ToArray())).ToArray();
+ if (dryRun || prop.Instruments.Count == 0)
+ return new MultisampleResult(prop.OctaveWhy, prop.OctaveShift, rows, -1, Array.Empty<string>());
+ var chosen = instrument is null ? prop.Instruments[0] : prop.Instruments.FirstOrDefault(i => i.Stem == instrument) ?? prop.Instruments[0];
+ string folderName = Path.GetFileName(folder.TrimEnd('/', '\\'));
+ var saved = new List<string>();
+ if (savePresets)
+ foreach (var inst in prop.Instruments.Where(i => i.Used.Any()))
+ {
+ var p = MultisampleMapper.Build(inst, opt, packs.ToRef);
+ saved.Add(packs.Save(p, p.Name, folderName));
+ }
+ var prog = MultisampleMapper.Build(chosen, opt, packs.ToRef);
+ prog.SourceRef = packs.ToRef(folder);
+ int t = await Mutate(() =>
+ {
+ int tt = trackId > 0 && IsMosaic(trackId) ? trackId : E.AddMosaicTrack();
+ E.MosaicSetProgram(tt, prog.Serialize());
+ return tt;
+ });
+ return new MultisampleResult(prop.OctaveWhy, prop.OctaveShift, rows, t, saved.ToArray());
+ }
+
+ [McpServerTool(Name = "list_mosaic_presets"), Description(
+ "List Nota Mosaic's presets: the factory multisamples (rendered on first use) and the pack presets — made for each "
+ + "installed sample pack (its SFZ, else its file names) and by create_multisample. Load one with load_mosaic_preset.")]
+ public Task<PresetRow[]> ListMosaicPresets() => Read(() =>
+ factory.All().Where(p => p.IsInstrument && p.BuiltinKind == MosaicModel.Kind).Select(p => new PresetRow(p.DisplayName, "factory", p.Category))
+ .Concat(packs.Presets().Select(p => new PresetRow(p.Name, p.Source == "sfz" ? "sfz" : "pack", p.Folder))).ToArray());
+
+ [McpServerTool(Name = "load_mosaic_preset"), Description(
+ "Load a Nota Mosaic preset by name (a factory name, or a pack preset's name; folder narrows it) into trackId "
+ + "(<= 0: a new Mosaic track). Samples load in the background. Returns the track id, or -1 when no preset matches.")]
+ public Task<int> LoadMosaicPreset(string name, int trackId = -1, string? folder = null) => Mutate(() =>
+ {
+ var fp = factory.All().FirstOrDefault(p => p.IsInstrument && p.BuiltinKind == MosaicModel.Kind && string.Equals(p.DisplayName, name, StringComparison.OrdinalIgnoreCase));
+ var pp = fp.Id is { Length: > 0 } ? null : packs.Presets().FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)
+ && (folder is null || string.Equals(p.Folder, folder, StringComparison.OrdinalIgnoreCase)));
+ if (fp.Id is not { Length: > 0 } && pp is null) return -1;
+ int t = trackId > 0 && IsMosaic(trackId) ? trackId : E.AddMosaicTrack();
+ if (pp is null) factory.ApplyInPlace(E, fp.Id!, t, -1);
+ else packs.ApplyInPlace(E, pp.Path, t);
+ return t;
+ });
+
+ [McpServerTool(Name = "scan_sample_packs"), Description(
+ "Make Nota Mosaic presets for every installed sample pack that has none yet (normally automatic at start and after an "
+ + "install). Returns how many presets were written.")]
+ public Task<int> ScanSamplePacks() => packs.ScanAsync();
+}
diff --git a/src/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.cs
index 2c2b11a2..bf01b74e 100644
--- a/src/managed/Nota.Presentation/DeviceInsertService.cs
+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs
@@ -134,6 +134,7 @@ public sealed class DeviceInsertService
14 => _engine.AddPentadTrack(),
15 => _engine.AddConsortTrack(),
16 => _engine.AddKeysTrack(),
+ 17 => _engine.AddMosaicTrack(),
1 => _engine.AddSamplerInstrumentTrack(),
_ => _engine.AddInstrumentTrack(),
};
diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
index 52da0e5b..086092af 100644
--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
@@ -108,6 +108,7 @@ public sealed partial class BrowserViewModel : ObservableObject
private readonly IPluginCatalog _catalog;
private readonly IPresetLibrary _presets;
+ private readonly IMosaicPacks? _mosaic;
private readonly IFactoryPresets _factory;
private readonly IDrumKits? _kits;
private readonly ISettingsService? _settings;
@@ -161,8 +162,9 @@ public sealed partial class BrowserViewModel : ObservableObject
public BrowserViewModel(IPluginCatalog catalog, IPresetLibrary presets, IFactoryPresets factory,
ISettingsService? settings = null, IBrowserLibrary? library = null,
- IDrumKits? kits = null, ISampleIndex? sampleIndex = null)
+ IDrumKits? kits = null, ISampleIndex? sampleIndex = null, IMosaicPacks? mosaic = null)
{
+ _mosaic = mosaic;
_index = sampleIndex;
_catalog = catalog;
_presets = presets;
@@ -312,12 +314,30 @@ public sealed partial class BrowserViewModel : ObservableObject
});
}
+ // Nota Mosaic's pack presets (installed sample packs, "Create multisample"): Packs → a pack.
+ if (_mosaic is not null && _instrTree.Find(d => d.Kind == BrowserItemKind.BuiltinInstrument && d.BuiltinKind == MosaicModel.Kind) is { } mosaicDev)
+ {
+ var list = _mosaic.Presets();
+ if (list.Count > 0)
+ {
+ var packs = new BrowserItem { Name = "Packs", Kind = BrowserItemKind.Folder, Path = $"category:{mosaicDev.LibraryKey}/Packs", Depth = 1 };
+ foreach (var g in list.GroupBy(p => p.Folder))
+ {
+ var folder = new BrowserItem { Name = g.Key, Kind = BrowserItemKind.Folder, Path = $"category:{mosaicDev.LibraryKey}/Packs/{g.Key}", Depth = 2 };
+ foreach (var p in g)
+ folder.Children.Add(new BrowserItem { Name = p.Name, Kind = BrowserItemKind.Preset, Sub = p.Source == "sfz" ? "sfz" : "multi", Path = p.Path, Depth = 3 });
+ packs.Children.Add(folder);
+ }
+ mosaicDev.Children.Add(packs);
+ }
+ }
+
// Preset groups start collapsed; the user expands a device to reveal its folders.
foreach (var tree in new[] { _instrTree, _fxTree, _midiTree })
foreach (var d in tree)
{
d.IsExpanded = false;
- foreach (var c in d.Children) c.IsExpanded = false;
+ foreach (var c in d.Children) { c.IsExpanded = false; foreach (var cc in c.Children) cc.IsExpanded = false; }
}
int count = _catalog.Count;
@@ -486,20 +506,21 @@ public sealed partial class BrowserViewModel : ObservableObject
if (q.Length == 0 || Matches(c, q)) dst.Add(c);
continue;
}
+ // Folders nest (Nota Mosaic → Packs → a pack): the same rule one level down.
if (q.Length == 0)
{
dst.Add(c);
- if (c.IsExpanded) foreach (var p in c.Children) dst.Add(p);
+ if (c.IsExpanded) AddPresetRows(c.Children, "", dst);
}
else if (Matches(c, q))
{
dst.Add(c);
- foreach (var p in c.Children) dst.Add(p);
+ AddPresetRows(c.Children, "", dst);
}
- else if (c.Children.Any(p => Matches(p, q)))
+ else if (AnyMatch(c.Children, q))
{
dst.Add(c);
- foreach (var p in c.Children) if (Matches(p, q)) dst.Add(p);
+ AddPresetRows(c.Children, q, dst);
}
}
}
diff --git a/src/managed/Nota.Remote/RemoteParams.cs b/src/managed/Nota.Remote/RemoteParams.cs
index e4941223..71dd8c69 100644
--- a/src/managed/Nota.Remote/RemoteParams.cs
+++ b/src/managed/Nota.Remote/RemoteParams.cs
@@ -44,7 +44,7 @@ public static class RemoteParams
0 => "Nota Synth", 1 => "Sampler", 2 => "Nota Physical", 3 => "Instrument Rack", 4 => "Drum Rack",
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", 16 => "Nota Keys", _ => "",
+ 15 => "Nota Consort", 16 => "Nota Keys", 17 => "Nota Mosaic", _ => "",
};
if (name.Length > 0) return name;
string id = e.TrackInstrumentPluginId(trackId);
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index ac4af1ea..de354ecb 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -133,6 +133,22 @@ typedef struct NotaSamplerInfo {
int32_t loop; /* 0/1 */
} NotaSamplerInfo;
+/* Nota Mosaic loading state. state: 0 empty · 1 loading · 2 ready. disk_* count the files'
+ * bytes on disk (progress), ram_bytes what the decoded samples take; missing = files that
+ * didn't decode (not found / unsupported). serial changes whenever another program is set
+ * (an edit, undo, a preset) — an editor re-reads the program text then. */
+typedef struct NotaMosaicStatus {
+ int32_t state;
+ int32_t files_done;
+ int32_t files_total;
+ int32_t missing;
+ int32_t zones;
+ int32_t serial;
+ int64_t disk_done;
+ int64_t disk_total;
+ int64_t ram_bytes;
+} NotaMosaicStatus;
+
/* Captured audio session take for project save (M7-6b). */
typedef struct NotaSessionAudioSlot {
int64_t sample_id;
@@ -256,6 +272,8 @@ NOTA_API int32_t nota_audition_midi_param(NotaAudition* rig, int32_t index, cons
/* The Sampler's or Nota Grain's sample, played at its own pitch on root_note (NULL / "" =
* the Sampler's procedural keys tone at C4; Grain keeps its built-in pad). */
NOTA_API int32_t nota_audition_set_sampler_sample(NotaAudition* rig, const char* path_utf8, int32_t root_note);
+/* Nota Mosaic's program text; returns once its samples are loaded (1) or on failure (0). */
+NOTA_API int32_t nota_audition_set_mosaic_program(NotaAudition* rig, const char* text_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). */
@@ -605,6 +623,26 @@ NOTA_API int32_t nota_engine_add_pentad_track(NotaEngine* engine);
NOTA_API int32_t nota_engine_add_consort_track(NotaEngine* engine);
/* Adds an instrument track with the built-in Nota Keys (modelled electric piano, kind 16). id (>0). */
NOTA_API int32_t nota_engine_add_keys_track(NotaEngine* engine);
+/* Adds an instrument track with the built-in Nota Mosaic (multisample instrument, kind 17),
+ * empty until a program is set. id (>0). */
+NOTA_API int32_t nota_engine_add_mosaic_track(NotaEngine* engine);
+/* Nota Mosaic's program — UTF-8 text (grammar in Mosaic.h). Set parses it and starts loading
+ * its samples in the background (1 on success, 0 when the track isn't a Mosaic); checkpoint 1
+ * makes it one undo step (the instrument is republished — sounding notes stop), 0 edits the
+ * live instrument in place (no undo). Get copies up to cap bytes (no terminator) and returns
+ * the full length. */
+NOTA_API int32_t nota_track_mosaic_set_program(NotaEngine* engine, int32_t track_id, const char* text_utf8, int32_t checkpoint);
+NOTA_API int32_t nota_track_mosaic_program(const NotaEngine* engine, int32_t track_id, char* out, int32_t cap);
+NOTA_API int32_t nota_track_mosaic_status(const NotaEngine* engine, int32_t track_id, NotaMosaicStatus* out);
+/* The sample id (nota_sample_info / nota_sample_read) behind a zone of the program, 0 = not loaded. */
+NOTA_API int64_t nota_track_mosaic_zone_sample_id(const NotaEngine* engine, int32_t track_id, int32_t zone);
+/* A named root that program sample references resolve against ("samples:Downloaded/x.wav"
+ * → <samples root>/Downloaded/x.wav). Process-wide. */
+NOTA_API void nota_path_root_set(const char* name_utf8, const char* path_utf8);
+/* Decodes up to max_seconds of a file's head as mono (channel average) into out (cap
+ * frames; out may be null to ask). Returns the frames decoded (≤ cap when out is given),
+ * 0 on failure; *sample_rate gets the file's rate. */
+NOTA_API int64_t nota_file_decode_mono(const char* path_utf8, double max_seconds, float* out, int64_t cap, double* sample_rate);
/* UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns):
* id/iarg/farg are instrument-specific (see the instrument's action()). */
NOTA_API void nota_track_instrument_action(NotaEngine* engine, int32_t track_id, int32_t id, int32_t iarg, float farg);
diff --git a/src/native/nota.engine/src/Audition.cpp b/src/native/nota.engine/src/Audition.cpp
index 91bcc4bd..405037ba 100644
--- a/src/native/nota.engine/src/Audition.cpp
+++ b/src/native/nota.engine/src/Audition.cpp
@@ -13,6 +13,9 @@
#include <utility>
#include "AudioFile.h"
+#include "Mosaic.h"
+#include <chrono>
+#include <thread>
#include "Device.h"
#include "DeviceFactory.h"
#include "GrainSynth.h"
@@ -124,6 +127,18 @@ bool AuditionRig::midiParam(int32_t index, const std::string& name, float value)
return false;
}
+bool AuditionRig::setMosaicProgram(const std::string& text, int32_t timeoutMs) {
+ auto* m = dynamic_cast<Mosaic*>(inst_.get());
+ if (!m) return false;
+ m->setProgram(text);
+ for (int32_t waited = 0; waited < timeoutMs; waited += 2) {
+ auto s = m->status();
+ if (s.state != 1) return s.state == 2;
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ }
+ return false;
+}
+
bool AuditionRig::setSamplerSample(const std::string& path, int32_t rootNote) {
if (auto* grain = dynamic_cast<GrainSynth*>(inst_.get())) {
auto buf = path.empty() ? nullptr : decodeAudioFile(path);
diff --git a/src/native/nota.engine/src/Audition.h b/src/native/nota.engine/src/Audition.h
index 9584ab5b..e6a63ff2 100644
--- a/src/native/nota.engine/src/Audition.h
+++ b/src/native/nota.engine/src/Audition.h
@@ -58,6 +58,9 @@ public:
// The Sampler's or Nota Grain's sample, rooted at rootNote: a file, or (empty path, the
// Sampler only) a procedural keys tone rooted at C4.
bool setSamplerSample(const std::string& path, int32_t rootNote = 60);
+ // Nota Mosaic's program; waits (up to timeoutMs) until its samples are in, so the
+ // offline render that follows hears them. False when the instrument isn't a Mosaic.
+ bool setMosaicProgram(const std::string& text, int32_t timeoutMs = 20000);
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);
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index be844408..61a527bd 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -644,6 +644,12 @@ public:
int32_t addPentadTrack(); // built-in Nota Pentad (5-voice Prophet-5 poly, kind 14)
int32_t addConsortTrack(); // built-in Nota Consort (paraphonic semi-modular, kind 15)
int32_t addKeysTrack(); // built-in Nota Keys (modelled electric piano, kind 16)
+ int32_t addMosaicTrack(); // built-in Nota Mosaic (multisample instrument, kind 17)
+ // Nota Mosaic's program (see Mosaic.h): set parses + starts loading, get returns the text.
+ bool mosaicSetProgram(int32_t trackId, const std::string& text, bool checkpoint);
+ std::string mosaicProgram(int32_t trackId) const;
+ bool mosaicStatus(int32_t trackId, NotaMosaicStatus* out) const;
+ int64_t mosaicZoneSampleId(int32_t trackId, int32_t zone) const;
void instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg); // UI editing channel
bool setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::string& path); // Phase 2
bool rhythmVoiceInfo(int32_t trackId, int32_t voice, NotaSamplerInfo* out) const; // sample id per voice
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index 4776d94d..211eb306 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -42,6 +42,7 @@
#include "Pentad.h"
#include "Consort.h"
#include "Keys.h"
+#include "Mosaic.h"
#include "GrainSynth.h"
#include "Arpeggiator.h"
#include "MidiChord.h"
@@ -260,6 +261,57 @@ int32_t Engine::addKeysTrack() {
return id;
}
+int32_t Engine::addMosaicTrack() {
+ auto g = std::make_shared<Graph>(*authoring_);
+ const int32_t id = nextTrackId_++;
+ auto track = std::make_shared<Track>(id, TrackType::Instrument);
+ auto inst = std::make_shared<Mosaic>(); // empty — a program is set later
+ inst->setSampleRate(transport_.sampleRate());
+ track->instrument = inst;
+ g->tracks.push_back(track);
+ publish(g);
+ return id;
+}
+
+// Nota Mosaic's program lives in the instrument, which is shared across snapshots; setting
+// it is lock-free for the audio thread (Mosaic publishes it itself once loaded).
+static Mosaic* mosaicOf(const std::shared_ptr<Track>& t) {
+ return t && t->instrument ? dynamic_cast<Mosaic*>(t->instrument.get()) : nullptr;
+}
+bool Engine::mosaicSetProgram(int32_t trackId, const std::string& text, bool checkpoint) {
+ auto old = findTrackAuthoring(trackId);
+ auto* m = mosaicOf(old);
+ if (!m) return false;
+ if (!checkpoint) { m->setProgram(text); return true; } // live edit: in place, voices keep going
+ // An undoable edit publishes a fresh Mosaic (params + the samples it already holds, so a
+ // zone edit is ready at once) — undo brings the old instrument, with its program, back.
+ auto fresh = std::static_pointer_cast<Mosaic>(m->clone());
+ fresh->setProgram(text);
+ auto nt = cloneTrack(*old);
+ nt->instrument = fresh;
+ republishWithTrack(trackId, nt);
+ return true;
+}
+std::string Engine::mosaicProgram(int32_t trackId) const {
+ auto* m = mosaicOf(findTrackAuthoring(trackId));
+ return m ? m->programText() : std::string{};
+}
+bool Engine::mosaicStatus(int32_t trackId, NotaMosaicStatus* out) const {
+ auto* m = mosaicOf(findTrackAuthoring(trackId));
+ if (!m || !out) return false;
+ const auto s = m->status();
+ out->state = s.state; out->files_done = s.filesDone; out->files_total = s.filesTotal;
+ out->missing = s.missing; out->zones = s.zones; out->serial = s.serial;
+ out->disk_done = s.diskDone; out->disk_total = s.diskTotal; out->ram_bytes = s.ram;
+ return true;
+}
+int64_t Engine::mosaicZoneSampleId(int32_t trackId, int32_t zone) const {
+ auto* m = mosaicOf(findTrackAuthoring(trackId));
+ if (!m) return 0;
+ auto b = m->zoneSample(zone);
+ return b ? b->id : 0;
+}
+
// UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns). The
// instrument object is stable across snapshots, so this mutates it in place (message thread).
void Engine::instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg) {
@@ -650,6 +702,7 @@ std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind) {
case 14: return std::make_shared<Pentad>();
case 15: return std::make_shared<Consort>();
case 16: return std::make_shared<Keys>();
+ case 17: return std::make_shared<Mosaic>(); // empty: a program is set later
default: return nullptr; // Racks (3/4) / unknown: no simple swap
}
}
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index 51b05304..abf50185 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -13,6 +13,7 @@
#include "Reverb.h"
#include "RackCore.h"
#include "Sampler.h"
+#include "Mosaic.h"
#include "GrainSynth.h"
#include "RhythmMachine.h"
#include "Synth.h"
@@ -43,6 +44,9 @@ std::shared_ptr<SampleBuffer> Engine::findSampleById(int64_t sampleId) const {
if (smp->sample() && smp->sample()->id == sampleId) return smp->sample();
if (auto* gr = dynamic_cast<GrainSynth*>(t->instrument.get()))
if (gr->sample() && gr->sample()->id == sampleId) return gr->sample();
+ // Nota Mosaic's zones (the editor's waveform; never bundled — they are referenced).
+ if (auto* mo = dynamic_cast<Mosaic*>(t->instrument.get()))
+ for (auto& b : mo->samples()) if (b->id == sampleId) return b;
// Nota Rhythm per-voice one-shots.
if (auto* rh = dynamic_cast<RhythmMachine*>(t->instrument.get()))
for (int v = 0; v < RhythmMachine::kVoices; ++v)
diff --git a/src/native/nota.engine/src/Mosaic.h b/src/native/nota.engine/src/Mosaic.h
new file mode 100644
index 00000000..880f33af
--- /dev/null
+++ b/src/native/nota.engine/src/Mosaic.h
@@ -0,0 +1,1008 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic — the built-in multisample instrument (kind 17). A *program* maps many
+// samples onto the keyboard: zones (a sample on a key × velocity rectangle with its own
+// root, tune, gain, pan, start/end and loop) gathered in groups (layers with a shared
+// gain / tune and a round-robin). On a note-on every zone that covers the key, the
+// velocity and the group's current round-robin step sounds at once; crossfade ranges
+// blend neighbouring layers. Zones flagged as release triggers sound when the key (or the
+// pedal) lets go — the piano's damper thump — quieter the longer the note was held.
+//
+// The program arrives as text (MosaicProgram.cs writes it; see parseProgram below for the
+// grammar) and lives in the project / preset as that text. Its samples are referenced, not
+// copied: an absolute path, or "<root>:<relative path>" against a root the host sets
+// (samples: the user's Samples folder, data: Nota's data folder), so a pack installed on
+// another computer resolves where it lives there. Loading is asynchronous — a worker pool
+// decodes the files into RAM (shared process-wide by path, so two tracks of one piano hold
+// it once); notes stay silent until the whole program is in, and a program that only edits
+// zones (same files) swaps in at once.
+//
+// Voices: Poly (16 / 32 / 64 / 128), Mono (legato glide) or Choke. The pool steals released
+// voices first, then the quietest, then the oldest, each with a short fade (Old fade); a
+// key keeps at most Per key strikes ringing. The sustain pedal (CC64) holds released keys.
+// Amp ADSR, a TPT state-variable filter (key-tracking, env → cutoff), glide, Vel → Vol and a
+// velocity curve are shared by every zone, like Nota Sampler's. MPE: bend retunes the note
+// (the wheel by Bend range), pressure adds level, slide opens the filter.
+//
+// Threads. The message thread parses and publishes; loader threads decode; the audio thread
+// reads the live program through an atomic raw pointer. Programs are kept alive by the
+// instrument and retired with the audio thread's render epoch (freed once two renders have
+// passed), the engine's own preview pattern, so the audio thread never frees memory.
+// All continuous controls are plugin params (normalized 0..1, stable ids, APPEND-ONLY).
+
+#pragma once
+
+#include "AudioFile.h"
+#include "Instrument.h"
+#include "NoteExpression.h"
+#include "SampleBuffer.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <utility>
+#include <vector>
+
+namespace nota {
+
+namespace mosaic {
+
+// ---- path roots ----------------------------------------------------------------------
+// "samples:Downloaded/Osiris Piano/C4.flac" resolves against the "samples" root. The host
+// sets the roots at start and when the user moves a folder; unknown roots don't resolve.
+inline std::mutex& rootMx() { static std::mutex m; return m; }
+inline std::map<std::string, std::string>& roots() { static std::map<std::string, std::string> r; return r; }
+inline void setRoot(const std::string& name, const std::string& path) {
+ std::lock_guard<std::mutex> lk(rootMx());
+ roots()[name] = path;
+}
+inline std::string resolve(const std::string& ref) {
+ const auto colon = ref.find(':');
+ // "C:\…" (a Windows drive) and plain absolute paths pass through.
+ if (colon == std::string::npos || colon < 2 || ref.compare(0, 1, "/") == 0) return ref;
+ const std::string name = ref.substr(0, colon);
+ std::string base;
+ {
+ std::lock_guard<std::mutex> lk(rootMx());
+ auto it = roots().find(name);
+ if (it == roots().end()) return ref;
+ base = it->second;
+ }
+ std::string rel = ref.substr(colon + 1);
+ if (!base.empty() && base.back() != '/' && base.back() != '\\') base += '/';
+ return base + rel;
+}
+
+// ---- the process-wide sample cache -----------------------------------------------------
+// Weak by path: a buffer lives while some program holds it.
+inline std::mutex& cacheMx() { static std::mutex m; return m; }
+inline std::map<std::string, std::weak_ptr<SampleBuffer>>& cache() { static std::map<std::string, std::weak_ptr<SampleBuffer>> c; return c; }
+inline std::shared_ptr<SampleBuffer> cached(const std::string& path) {
+ std::lock_guard<std::mutex> lk(cacheMx());
+ auto it = cache().find(path);
+ if (it == cache().end()) return nullptr;
+ auto sp = it->second.lock();
+ if (!sp) cache().erase(it);
+ return sp;
+}
+inline void remember(const std::string& path, const std::shared_ptr<SampleBuffer>& b) {
+ std::lock_guard<std::mutex> lk(cacheMx());
+ cache()[path] = b;
+}
+
+// ---- text helpers ----------------------------------------------------------------------
+// Locale-proof number parsing (strtod follows the C locale the host may change).
+inline double num(const char* s, double def) {
+ if (!s || !*s) return def;
+ bool neg = false; double v = 0, scale = 1; bool any = false, frac = false;
+ if (*s == '-') { neg = true; ++s; } else if (*s == '+') ++s;
+ for (; *s; ++s) {
+ if (*s >= '0' && *s <= '9') { any = true; if (frac) { scale *= 0.1; v += (*s - '0') * scale; } else v = v * 10 + (*s - '0'); }
+ else if (*s == '.' && !frac) frac = true;
+ else if (*s == 'e' || *s == 'E') { const double ex = num(s + 1, 0); v *= std::pow(10.0, ex); break; }
+ else break;
+ }
+ if (!any) return def;
+ return neg ? -v : v;
+}
+inline int hexv(char c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; }
+inline std::string unescape(const std::string& s) { // %XX → byte
+ std::string o; o.reserve(s.size());
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] == '%' && i + 2 < s.size() && hexv(s[i + 1]) >= 0 && hexv(s[i + 2]) >= 0) {
+ o += static_cast<char>(hexv(s[i + 1]) * 16 + hexv(s[i + 2])); i += 2;
+ } else o += s[i];
+ }
+ return o;
+}
+
+// ---- the program -------------------------------------------------------------------------
+struct Zone {
+ int32_t file = -1, group = 0, root = 60;
+ int32_t klo = 0, khi = 127, vlo = 0, vhi = 127;
+ float tune = 0.0f, gainDb = 0.0f, pan = 0.0f; // cents · dB · −1..+1
+ double start = 0, end = -1, loopStart = -1, loopEnd = -1; // frames; −1 = the sample's own edge
+ int32_t loopMode = 0; // 0 off · 1 forward · 2 ping-pong
+ float xfade = 0.0f; // loop crossfade, seconds
+ int32_t seq = 1; // round-robin step (1-based)
+ float rlo = 0.0f, rhi = 1.0f; // random range (SFZ lorand / hirand)
+ int32_t xkil = -1, xkih = -1, xkol = -1, xkoh = -1; // key crossfade in / out ranges
+ int32_t xvil = -1, xvih = -1, xvol = -1, xvoh = -1; // velocity crossfade in / out ranges
+ int32_t trig = 0; // 0 attack · 1 release
+ int32_t excl = 0, offBy = 0, offMode = 0; // exclusive group · off by · 0 fast / 1 normal
+};
+struct Group {
+ float gainDb = 0.0f, tune = 0.0f;
+ int32_t rrMode = 0; // 0 sequential · 1 random · 2 random without repeat
+ int32_t seqLen = 1;
+};
+
+struct Program {
+ std::vector<std::string> refs; // as written (persisted)
+ std::vector<std::string> paths; // resolved
+ std::vector<Group> groups;
+ std::vector<Zone> zones;
+ std::string text; // the source text, verbatim
+ // Decoded samples: owned here, published to the audio thread through `ptr`.
+ std::vector<std::shared_ptr<SampleBuffer>> owned;
+ std::unique_ptr<std::atomic<SampleBuffer*>[]> ptr;
+ std::vector<int64_t> diskBytes;
+ std::atomic<int32_t> done{0}, missing{0};
+ std::atomic<int64_t> bytesDone{0}, ramBytes{0};
+ int64_t diskTotal = 0;
+ std::atomic<bool> ready{false}, cancel{false};
+ std::mutex ownMx; // owned[] writes (loader threads)
+ int32_t serial = nextSerial(); // process-unique: an editor notices a new program
+
+ static int32_t nextSerial() { static std::atomic<int32_t> n{1}; return n.fetch_add(1, std::memory_order_relaxed); }
+
+ const SampleBuffer* sample(int32_t f) const {
+ return (f >= 0 && f < static_cast<int32_t>(paths.size())) ? ptr[f].load(std::memory_order_acquire) : nullptr;
+ }
+};
+
+// Parses the program text. One record per line, "key=value" tokens after the record name;
+// names and paths are %-escaped (no spaces). Unknown records and keys are skipped, so a
+// newer program still loads its known part.
+// mosaic 1
+// name <escaped> · source <kind> <escaped ref> · pack <id> <escaped name> (informational)
+// file <escaped ref> (index = order)
+// group gain= tune= rr= seq= name=
+// zone f= g= root= klo= khi= vlo= vhi= tune= gain= pan= s= e= lm= ls= le= xf= seq= rlo= rhi=
+// xkil= xkih= xkol= xkoh= xvil= xvih= xvol= xvoh= trig= excl= off= om=
+inline std::shared_ptr<Program> parseProgram(const std::string& text) {
+ auto p = std::make_shared<Program>();
+ p->text = text;
+ size_t i = 0;
+ std::vector<std::string> tok;
+ while (i <= text.size()) {
+ size_t j = text.find('\n', i);
+ if (j == std::string::npos) j = text.size();
+ std::string line = text.substr(i, j - i);
+ i = j + 1;
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ tok.clear();
+ size_t a = 0;
+ while (a < line.size()) {
+ while (a < line.size() && (line[a] == ' ' || line[a] == '\t')) ++a;
+ size_t b = a;
+ while (b < line.size() && line[b] != ' ' && line[b] != '\t') ++b;
+ if (b > a) tok.push_back(line.substr(a, b - a));
+ a = b;
+ }
+ if (tok.empty()) { if (j >= text.size()) break; continue; }
+ auto kv = [&](const char* key, double def) -> double {
+ const size_t n = std::strlen(key);
+ for (size_t t = 1; t < tok.size(); ++t)
+ if (tok[t].size() > n && tok[t].compare(0, n, key) == 0 && tok[t][n] == '=') return num(tok[t].c_str() + n + 1, def);
+ return def;
+ };
+ const std::string& rec = tok[0];
+ if (rec == "file" && tok.size() >= 2) {
+ p->refs.push_back(unescape(tok[1]));
+ } else if (rec == "group") {
+ Group g;
+ g.gainDb = static_cast<float>(kv("gain", 0)); g.tune = static_cast<float>(kv("tune", 0));
+ g.rrMode = std::clamp(static_cast<int32_t>(kv("rr", 0)), 0, 2);
+ g.seqLen = std::clamp(static_cast<int32_t>(kv("seq", 1)), 1, 64);
+ p->groups.push_back(g);
+ } else if (rec == "zone") {
+ Zone z;
+ z.file = static_cast<int32_t>(kv("f", -1)); z.group = static_cast<int32_t>(kv("g", 0));
+ z.root = std::clamp(static_cast<int32_t>(kv("root", 60)), 0, 127);
+ z.klo = std::clamp(static_cast<int32_t>(kv("klo", 0)), 0, 127); z.khi = std::clamp(static_cast<int32_t>(kv("khi", 127)), 0, 127);
+ z.vlo = std::clamp(static_cast<int32_t>(kv("vlo", 0)), 0, 127); z.vhi = std::clamp(static_cast<int32_t>(kv("vhi", 127)), 0, 127);
+ z.tune = static_cast<float>(kv("tune", 0)); z.gainDb = static_cast<float>(kv("gain", 0));
+ z.pan = std::clamp(static_cast<float>(kv("pan", 0)), -1.0f, 1.0f);
+ z.start = std::max(0.0, kv("s", 0)); z.end = kv("e", -1);
+ z.loopMode = std::clamp(static_cast<int32_t>(kv("lm", 0)), 0, 2);
+ z.loopStart = kv("ls", -1); z.loopEnd = kv("le", -1);
+ z.xfade = static_cast<float>(std::clamp(kv("xf", 0), 0.0, 2.0));
+ z.seq = std::max(1, static_cast<int32_t>(kv("seq", 1)));
+ z.rlo = static_cast<float>(kv("rlo", 0)); z.rhi = static_cast<float>(kv("rhi", 1));
+ z.xkil = static_cast<int32_t>(kv("xkil", -1)); z.xkih = static_cast<int32_t>(kv("xkih", -1));
+ z.xkol = static_cast<int32_t>(kv("xkol", -1)); z.xkoh = static_cast<int32_t>(kv("xkoh", -1));
+ z.xvil = static_cast<int32_t>(kv("xvil", -1)); z.xvih = static_cast<int32_t>(kv("xvih", -1));
+ z.xvol = static_cast<int32_t>(kv("xvol", -1)); z.xvoh = static_cast<int32_t>(kv("xvoh", -1));
+ z.trig = kv("trig", 0) >= 0.5 ? 1 : 0;
+ z.excl = static_cast<int32_t>(kv("excl", 0)); z.offBy = static_cast<int32_t>(kv("off", 0));
+ z.offMode = kv("om", 0) >= 0.5 ? 1 : 0;
+ if (z.klo > z.khi) std::swap(z.klo, z.khi);
+ if (z.vlo > z.vhi) std::swap(z.vlo, z.vhi);
+ p->zones.push_back(z);
+ }
+ if (j >= text.size()) break;
+ }
+ if (p->groups.empty()) p->groups.push_back(Group{});
+ const int32_t nf = static_cast<int32_t>(p->refs.size()), ng = static_cast<int32_t>(p->groups.size());
+ // Drop zones that point nowhere; clamp groups.
+ p->zones.erase(std::remove_if(p->zones.begin(), p->zones.end(), [&](const Zone& z) { return z.file < 0 || z.file >= nf; }), p->zones.end());
+ for (auto& z : p->zones) z.group = std::clamp(z.group, 0, ng - 1);
+ for (const auto& r : p->refs) p->paths.push_back(resolve(r));
+ p->owned.resize(p->paths.size());
+ p->ptr.reset(new std::atomic<SampleBuffer*>[std::max<size_t>(1, p->paths.size())]);
+ for (size_t f = 0; f < p->paths.size(); ++f) p->ptr[f].store(nullptr, std::memory_order_relaxed);
+ p->diskBytes.assign(p->paths.size(), 0);
+ for (size_t f = 0; f < p->paths.size(); ++f) {
+ std::error_code ec;
+ const auto sz = std::filesystem::file_size(std::filesystem::path(std::u8string(p->paths[f].begin(), p->paths[f].end())), ec);
+ p->diskBytes[f] = ec ? 0 : static_cast<int64_t>(sz);
+ p->diskTotal += p->diskBytes[f];
+ }
+ return p;
+}
+
+inline void installSample(Program& p, size_t f, std::shared_ptr<SampleBuffer> b) {
+ {
+ std::lock_guard<std::mutex> lk(p.ownMx);
+ p.owned[f] = b;
+ }
+ p.ptr[f].store(b.get(), std::memory_order_release);
+ p.ramBytes.fetch_add(static_cast<int64_t>(b->samples.size() * sizeof(float)), std::memory_order_relaxed);
+}
+
+// Decodes every file not yet in; marks the program ready at the end. Runs on its own
+// threads (a small pool) — the shared_ptr keeps the program alive however long it takes.
+inline void loadProgram(std::shared_ptr<Program> p) {
+ const size_t n = p->paths.size();
+ std::vector<size_t> todo;
+ for (size_t f = 0; f < n; ++f) {
+ if (p->ptr[f].load(std::memory_order_relaxed)) continue;
+ if (auto c = cached(p->paths[f])) { installSample(*p, f, c); p->done.fetch_add(1); p->bytesDone.fetch_add(p->diskBytes[f]); continue; }
+ todo.push_back(f);
+ }
+ if (todo.empty()) { p->ready.store(true, std::memory_order_release); return; }
+ auto next = std::make_shared<std::atomic<size_t>>(0);
+ const unsigned hw = std::max(1u, std::thread::hardware_concurrency());
+ const int workers = static_cast<int>(std::clamp<unsigned>(hw / 2, 1u, 4u));
+ auto left = std::make_shared<std::atomic<int>>(workers);
+ for (int w = 0; w < workers; ++w) {
+ std::thread([p, todo, next, left]() {
+ for (;;) {
+ if (p->cancel.load(std::memory_order_relaxed)) break;
+ const size_t k = next->fetch_add(1);
+ if (k >= todo.size()) break;
+ const size_t f = todo[k];
+ std::shared_ptr<SampleBuffer> b = cached(p->paths[f]);
+ if (!b) {
+ b = decodeAudioFile(p->paths[f]);
+ if (b && !b->empty()) remember(p->paths[f], b);
+ }
+ if (b && !b->empty()) installSample(*p, f, b);
+ else p->missing.fetch_add(1);
+ p->bytesDone.fetch_add(p->diskBytes[f]);
+ p->done.fetch_add(1);
+ }
+ if (left->fetch_sub(1) == 1 && !p->cancel.load(std::memory_order_relaxed))
+ p->ready.store(true, std::memory_order_release);
+ }).detach();
+ }
+}
+
+} // namespace mosaic
+
+class Mosaic final : public Instrument {
+public:
+ enum Param {
+ Volume = 0, Pan, Transpose, Detune, Attack, Decay, Sustain, Release,
+ FilterType, Cutoff, Resonance, VoiceMode, FilterKeyTrack, VelAmount, Glide, PitchTrack,
+ EnvCutoff, EnvAmount, Output, Polyphony, PerKey, OldFade, RelOn, RelVol, RelLen, VelCurve,
+ Pedal, BendRange, MpePressure, MpeSlide, View, kNumParams
+ };
+ static constexpr int kPool = 160; // voices incl. those fading out after a steal
+
+ Mosaic() {
+ pn_[Volume].store(1.0f); pn_[Pan].store(0.5f); pn_[Transpose].store(0.5f); pn_[Detune].store(0.5f);
+ pn_[Attack].store(0.0f); pn_[Decay].store(0.3f); pn_[Sustain].store(1.0f); pn_[Release].store(0.3f);
+ pn_[FilterType].store(0.0f); pn_[Cutoff].store(1.0f); pn_[Resonance].store(0.0f);
+ pn_[VoiceMode].store(0.0f); pn_[FilterKeyTrack].store(0.0f); pn_[VelAmount].store(0.7f);
+ pn_[Glide].store(0.0f); pn_[PitchTrack].store(1.0f); pn_[EnvCutoff].store(0.0f); pn_[EnvAmount].store(0.75f);
+ pn_[Output].store(0.79f);
+ pn_[Polyphony].store(2.0f / 3.0f); // 64
+ pn_[PerKey].store(1.0f / 3.0f); // 2
+ pn_[OldFade].store(oldFadeNorm(0.020)); // 20 ms
+ pn_[RelOn].store(1.0f);
+ pn_[RelVol].store(static_cast<float>((-9.0 + 36.0) / 42.0)); // −9 dB on −36 … +6
+ pn_[RelLen].store(0.25f); // −6 dB after 2 s on 0 … −24
+ pn_[VelCurve].store(0.5f); // linear
+ pn_[Pedal].store(1.0f);
+ pn_[BendRange].store(2.0f / 24.0f);
+ pn_[MpePressure].store(0.5f); pn_[MpeSlide].store(0.5f);
+ pn_[View].store(0.0f); // L
+ for (auto& v : voices_) v.active = false;
+ for (int k = 0; k < 128; ++k) { noteOnAt_[k] = 0; noteVel_[k] = 0.0f; }
+ }
+
+ ~Mosaic() override {
+ std::lock_guard<std::mutex> lk(holdMx_);
+ if (pending_) pending_->cancel.store(true);
+ }
+
+ // ---- value maps (mirrored by MosaicModel.cs) -----------------------------------------
+ static double glideSeconds(float v) { return v <= 0.001f ? 0.0 : 0.001 * std::pow(2000.0, std::clamp(v, 0.0f, 1.0f)); }
+ static double envOctaves(float v) { return (std::clamp(v, 0.0f, 1.0f) - 0.5) * 12.0; }
+ static int polyOf(float v) { static const int n[] = { 16, 32, 64, 128 }; return n[std::clamp(static_cast<int>(std::lround(v * 3.0f)), 0, 3)]; }
+ static int perKeyOf(float v) { return 1 + std::clamp(static_cast<int>(std::lround(v * 3.0f)), 0, 3); }
+ static double oldFadeSec(float v) { return 0.001 * std::pow(200.0, std::clamp(v, 0.0f, 1.0f)); } // 1 … 200 ms
+ static float oldFadeNorm(double s) { return static_cast<float>(std::log(std::max(0.001, s) / 0.001) / std::log(200.0)); }
+ static double relVolDb(float v) { return -36.0 + 42.0 * std::clamp(v, 0.0f, 1.0f); } // −36 … +6 dB
+ static double relLenDb(float v) { return -24.0 * std::clamp(v, 0.0f, 1.0f); } // drop after 2 s
+ static double bendSemis(float v) { return std::round(24.0 * std::clamp(v, 0.0f, 1.0f)); }
+ // Velocity curve: −1 soft (quiet notes louder) … +1 hard. v in 0..1.
+ static double velCurve(double vel, float c) {
+ const double k = (std::clamp(c, 0.0f, 1.0f) - 0.5) * 2.0; // −1..+1
+ const double e = std::pow(4.0, k); // 0.25 … 4
+ return std::pow(std::clamp(vel, 0.0, 1.0), e);
+ }
+
+ int32_t kind() const override { return 17; }
+ const char* displayName() const override { return "Nota Mosaic"; }
+ void setSampleRate(double sr) override { sr_ = sr > 0 ? sr : 44100.0; }
+ bool supportsMpe() const override { return true; }
+
+ // ---- the program (message thread) ---------------------------------------------------
+ // Parses and starts loading `text`. A program whose files are all loaded already (a zone
+ // edit, a clone) publishes at once; otherwise the instrument is silent until it is in.
+ void setProgram(const std::string& text) {
+ auto p = mosaic::parseProgram(text);
+ // Reuse what this instrument already holds (same resolved path) before the cache.
+ std::shared_ptr<mosaic::Program> cur;
+ { std::lock_guard<std::mutex> lk(holdMx_); cur = pending_; }
+ if (cur) {
+ std::map<std::string, std::shared_ptr<SampleBuffer>> have;
+ { std::lock_guard<std::mutex> lk(cur->ownMx); for (size_t f = 0; f < cur->paths.size(); ++f) if (cur->owned[f]) have[cur->paths[f]] = cur->owned[f]; }
+ for (size_t f = 0; f < p->paths.size(); ++f) {
+ auto it = have.find(p->paths[f]);
+ if (it != have.end()) { mosaic::installSample(*p, f, it->second); p->done.fetch_add(1); p->bytesDone.fetch_add(p->diskBytes[f]); }
+ }
+ if (!cur->ready.load()) cur->cancel.store(true); // stop decoding what nobody plays
+ }
+ publish(p);
+ mosaic::loadProgram(p);
+ reap();
+ }
+
+ // The program text (the newest one set, loaded or not).
+ std::string programText() const {
+ std::lock_guard<std::mutex> lk(holdMx_);
+ return pending_ ? pending_->text : std::string{};
+ }
+
+ // Loading state: 0 empty · 1 loading · 2 ready. Polled by the editor; also frees retired
+ // programs (message thread).
+ struct Status { int32_t state = 0, filesDone = 0, filesTotal = 0, missing = 0, zones = 0, serial = 0; int64_t diskDone = 0, diskTotal = 0, ram = 0; };
+ Status status() {
+ std::shared_ptr<mosaic::Program> p;
+ { std::lock_guard<std::mutex> lk(holdMx_); p = pending_; }
+ Status s;
+ if (!p) { reap(); return s; }
+ s.state = p->paths.empty() ? 0 : (p->ready.load(std::memory_order_acquire) ? 2 : 1);
+ s.filesDone = p->done.load(); s.filesTotal = static_cast<int32_t>(p->paths.size());
+ s.missing = p->missing.load(); s.zones = static_cast<int32_t>(p->zones.size()); s.serial = p->serial;
+ s.diskDone = p->bytesDone.load(); s.diskTotal = p->diskTotal; s.ram = p->ramBytes.load();
+ reap();
+ return s;
+ }
+
+ // The decoded buffer behind a zone of the newest program (the editor's waveform), or null.
+ std::shared_ptr<SampleBuffer> zoneSample(int32_t zone) const {
+ std::lock_guard<std::mutex> lk(holdMx_);
+ if (!pending_ || zone < 0 || zone >= static_cast<int32_t>(pending_->zones.size())) return nullptr;
+ const int32_t f = pending_->zones[zone].file;
+ std::lock_guard<std::mutex> lk2(pending_->ownMx);
+ return (f >= 0 && f < static_cast<int32_t>(pending_->owned.size())) ? pending_->owned[f] : nullptr;
+ }
+ // Every decoded buffer the program holds (project save looks samples up by id).
+ std::vector<std::shared_ptr<SampleBuffer>> samples() const {
+ std::lock_guard<std::mutex> lk(holdMx_);
+ std::vector<std::shared_ptr<SampleBuffer>> out;
+ if (!pending_) return out;
+ std::lock_guard<std::mutex> lk2(pending_->ownMx);
+ for (auto& b : pending_->owned) if (b) out.push_back(b);
+ return out;
+ }
+
+ // ---- state: params + program text ----------------------------------------------------
+ std::vector<uint8_t> getState() const override {
+ const std::string text = programText();
+ std::vector<uint8_t> out;
+ auto put32 = [&](uint32_t v) { for (int i = 0; i < 4; ++i) out.push_back(static_cast<uint8_t>(v >> (8 * i))); };
+ put32(0x43534F4Du); // "MOSC"
+ put32(1);
+ put32(kNumParams);
+ for (int i = 0; i < kNumParams; ++i) { float f = pn_[i].load(std::memory_order_relaxed); uint32_t u; std::memcpy(&u, &f, 4); put32(u); }
+ put32(static_cast<uint32_t>(text.size()));
+ out.insert(out.end(), text.begin(), text.end());
+ return out;
+ }
+ void setState(const uint8_t* data, int32_t size) override {
+ if (!data || size < 12) return;
+ size_t at = 0;
+ auto get32 = [&](uint32_t& v) { if (at + 4 > static_cast<size_t>(size)) return false; v = 0; for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(data[at + i]) << (8 * i); at += 4; return true; };
+ uint32_t magic = 0, ver = 0, n = 0;
+ if (!get32(magic) || magic != 0x43534F4Du || !get32(ver) || !get32(n)) return;
+ for (uint32_t i = 0; i < n; ++i) {
+ uint32_t u; if (!get32(u)) return;
+ float f; std::memcpy(&f, &u, 4);
+ if (i < static_cast<uint32_t>(kNumParams) && std::isfinite(f)) pn_[i].store(std::clamp(f, 0.0f, 1.0f), std::memory_order_relaxed);
+ }
+ uint32_t len = 0;
+ if (!get32(len) || at + len > static_cast<size_t>(size)) return;
+ setProgram(std::string(reinterpret_cast<const char*>(data + at), len));
+ }
+
+ std::shared_ptr<Instrument> clone() const override {
+ auto m = std::make_shared<Mosaic>();
+ m->setSampleRate(sr_);
+ for (int i = 0; i < kNumParams; ++i) m->pn_[i].store(pn_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);
+ std::shared_ptr<mosaic::Program> cur;
+ { std::lock_guard<std::mutex> lk(holdMx_); cur = pending_; }
+ if (cur) { // shares the decoded buffers through setProgram's reuse
+ m->adopt(cur);
+ }
+ return m;
+ }
+
+ // ---- plugin params ----------------------------------------------------------------------
+ int32_t pluginParamCount() const override { return kNumParams; }
+ std::string pluginParamId(int32_t i) const override {
+ static const char* ids[kNumParams] = {
+ "volume", "pan", "transpose", "detune", "attack", "decay", "sustain", "release",
+ "filtertype", "cutoff", "resonance", "voicemode", "keytrack", "velamount", "glide", "pitchtrack",
+ "envcutoff", "envamount", "output", "polyphony", "perkey", "oldfade", "relon", "relvol", "rellen", "velcurve",
+ "pedal", "bendrange", "mpepressure", "mpeslide", "view" };
+ return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};
+ }
+ std::string pluginParamName(int32_t i) const override {
+ // Grouped by the head word in the automation menu; ids persist, names may change.
+ static const char* nm[kNumParams] = {
+ "Out Volume", "Out Pan", "Pitch Transpose", "Pitch Detune", "Env Attack", "Env Decay", "Env Sustain", "Env Release",
+ "Filter Type", "Filter Cutoff", "Filter Resonance", "Voice Mode", "Filter Keytrack", "Voice Velocity", "Voice Glide", "Pitch Keytrack",
+ "Filter Env On", "Filter Env Amount", "Out Level", "Voice Polyphony", "Voice Per Key", "Voice Old Fade",
+ "Release Triggers", "Release Volume", "Release Length", "Voice Vel Curve",
+ "Voice Pedal", "MPE Bend Range", "MPE Pressure", "MPE Slide", "View" };
+ return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};
+ }
+ float pluginParamGet(int32_t i) const override { return (i >= 0 && i < kNumParams) ? pn_[i].load(std::memory_order_relaxed) : 0.0f; }
+ void pluginParamSet(int32_t i, float v) override { if (i >= 0 && i < kNumParams && std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
+ float pluginParamDefault(int32_t i) const override { static const Mosaic d; return d.pluginParamGet(i); }
+ int32_t pluginParamIndexOfId(const std::string& id) const override {
+ for (int32_t i = 0; i < kNumParams; ++i) if (pluginParamId(i) == id) return i;
+ return -1;
+ }
+
+ // ---- telemetry --------------------------------------------------------------------------
+ // [0] voices · [1] voice limit · [2] held · [3] held by the pedal · [4] release-trigger
+ // voices · [5] pedal down · [6] output peak since the last read · [7] loudest voice's play
+ // position 0..1 · [8] its envelope · [9] its stage (0 A · 1 D · 2 S · 3 R) · [10] its note
+ // (fractional while gliding) · [11] its cutoff Hz (−1 off) · [12] its zone · [13] last
+ // note · [14] last velocity 0..127 · [15] sounding entries N, then N entries
+ // zone × 4 + state (0 held · 1 pedal · 2 release / fading); then [128 …] the keys held or
+ // sustained now, 128 bits as 8 floats of 16 bits each.
+ static constexpr int kScHead = 16, kScZones = 112, kScKeys = kScHead + kScZones, kScope = kScKeys + 8;
+ int32_t scopeRead(float* out, int32_t maxN) const override {
+ if (!out || maxN <= 0) return 0;
+ const int n = std::min<int>(maxN, kScope);
+ for (int i = 0; i < n; ++i) out[i] = tele_[i].load(std::memory_order_relaxed);
+ if (n > 6) tele_[6].store(0.0f, std::memory_order_relaxed);
+ return n;
+ }
+ int32_t activeVoiceCount() const override { return static_cast<int32_t>(tele_[0].load(std::memory_order_relaxed)); }
+
+ // ---- notes --------------------------------------------------------------------------------
+ void noteExpression(int32_t pitch, int32_t dim, float value) override {
+ if (pitch < 0) {
+ if (dim == ExprSustain) cc64_ = value >= 0.5f;
+ else gexpr_.set(dim, value);
+ return;
+ }
+ if (dim < 0 || dim >= kExprDims) return;
+ float add[kExprDims]; gexpr_.offsets(static_cast<float>(bendSemis(get(BendRange))), add);
+ for (auto& v : voices_) if (v.active && v.pitch == pitch && v.held) v.ex.set(dim, value, add);
+ }
+
+ void noteOn(int32_t pitch, float velocity) override {
+ if (pitch < 0 || pitch > 127) return;
+ const mosaic::Program* p = live();
+ noteOnAt_[pitch] = clock_; noteVel_[pitch] = velocity; keyDown_[pitch] = true;
+ lastNote_ = pitch; lastVel_ = velocity;
+ if (!p || p->zones.empty()) return;
+ const int vm = voiceModeOf();
+ const bool glide = get(Glide) > 0.001f;
+ const double from = glideFrom_ >= 0 ? static_cast<double>(glideFrom_) : static_cast<double>(pitch);
+ glideFrom_ = pitch;
+ if (vm == 1) {
+ pushHeld(pitch);
+ if (glide) { // legato: sounding voices slide, no new strike
+ bool slid = false;
+ for (auto& v : voices_) if (v.active && v.held && !v.relTrig && v.kill == 0) { v.pitch = pitch; slid = true; }
+ if (slid) return;
+ }
+ for (auto& v : voices_) if (v.active && !v.relTrig && v.kill == 0) fade(v);
+ } else if (vm == 2) {
+ for (auto& v : voices_) if (v.active && v.kill == 0) fade(v, 0.004);
+ }
+ // Per key: older strikes of this key beyond the limit fade out.
+ if (vm == 0) limitPerKey(pitch);
+ const int vel7 = std::clamp(static_cast<int>(std::lround(velocity * 127.0f)), 0, 127);
+ const uint32_t id = ++noteSerial_;
+ spawn(*p, pitch, vel7, velocity, id, /*release*/false, 1.0f, glide ? from : static_cast<double>(pitch));
+ }
+
+ void noteOff(int32_t pitch) override {
+ if (pitch < 0 || pitch > 127) return;
+ const int vm = voiceModeOf();
+ if (vm == 1) {
+ const bool top = heldN_ > 0 && held_[heldN_ - 1] == pitch;
+ popHeld(pitch);
+ if (top && heldN_ > 0 && get(Glide) > 0.001f) { // legato back to the key still down
+ const int32_t back = held_[heldN_ - 1];
+ bool slid = false;
+ for (auto& v : voices_) if (v.active && v.held && v.pitch == pitch && v.kill == 0 && !v.relTrig) { v.pitch = back; slid = true; }
+ if (slid) { glideFrom_ = back; return; }
+ }
+ }
+ for (auto& v : voices_) {
+ if (!v.active || v.pitch != pitch || !v.held || v.relTrig) continue;
+ v.held = false;
+ if (pedalDown_) v.sustained = true;
+ else v.stage = Stage::Release;
+ }
+ // The release sample follows the key (or the pedal), even when the note has died away.
+ if (keyDown_[pitch]) {
+ keyDown_[pitch] = false;
+ if (pedalDown_) pedalKeys_[pitch] = true;
+ else releaseTrigger(pitch);
+ }
+ }
+
+ void allNotesOff() override {
+ for (auto& v : voices_) v.active = false;
+ heldN_ = 0; cc64_ = false; pedalDown_ = false; gexpr_.reset();
+ for (auto& k : pedalKeys_) k = false;
+ for (auto& k : keyDown_) k = false;
+ }
+
+ // ---- render -----------------------------------------------------------------------------
+ void render(float* out, int32_t frames) override {
+ const mosaic::Program* p = live();
+ // A new program: voices keep sounding only if it still holds their sample (a zone
+ // edit keeps the files) — a retired program's buffers live just two more renders.
+ if (p != lastLive_) {
+ for (auto& v : voices_) {
+ if (!v.active) continue;
+ bool kept = false;
+ if (p) for (size_t f = 0; f < p->paths.size() && !kept; ++f) kept = p->sample(static_cast<int32_t>(f)) == v.buf;
+ if (!kept) v.active = false;
+ else if (v.zone >= static_cast<int32_t>(p->zones.size())) v.zone = -1;
+ }
+ lastLive_ = p;
+ }
+
+ // The pedal: CC64 (when Pedal is on). Lifting it releases every held-over key.
+ const bool pedal = get(Pedal) >= 0.5f && cc64_;
+ if (pedalDown_ && !pedal) {
+ for (auto& v : voices_) if (v.active && v.sustained) { v.sustained = false; v.stage = Stage::Release; }
+ pedalDown_ = false;
+ for (int k = 0; k < 128; ++k) if (pedalKeys_[k]) { pedalKeys_[k] = false; releaseTrigger(k); }
+ }
+ pedalDown_ = pedal;
+
+ const double pitchOff = (get(Transpose) - 0.5) * 48.0 + (get(Detune) - 0.5) * 1.0;
+ const double pTrack = get(PitchTrack);
+ const float vol = get(Volume) * get(Output);
+ const double pan = get(Pan) * 2.0 - 1.0;
+ const float atkRate = static_cast<float>(1.0 / (expMap(get(Attack), 0.0005, 4.0) * sr_));
+ const float decRate = static_cast<float>(1.0 / (expMap(get(Decay), 0.002, 6.0) * sr_));
+ const float relRate = static_cast<float>(1.0 / (expMap(get(Release), 0.002, 6.0) * sr_));
+ const float sustain = get(Sustain);
+ const double glideSec = glideSeconds(get(Glide));
+ const double glideK = glideSec > 0.0 ? 1.0 - std::exp(-static_cast<double>(kCtl) / (glideSec * sr_)) : 1.0;
+ const int fType = std::clamp(static_cast<int>(std::lround(get(FilterType) * 3.0f)), 0, 3);
+ const double baseCut = expMap(get(Cutoff), 20.0, 20000.0);
+ const double kTrack = get(FilterKeyTrack);
+ const double k = 2.0 - 1.9 * get(Resonance);
+ const bool envOn = get(EnvCutoff) > 0.5f;
+ const double envOct = envOn ? envOctaves(get(EnvAmount)) : 0.0;
+ const float bendR = static_cast<float>(bendSemis(get(BendRange)));
+ const float mpePress = get(MpePressure), mpeSlide = get(MpeSlide);
+ float exAdd[kExprDims]; gexpr_.offsets(bendR, exAdd);
+ const float exCoef = exprSmoothCoef(sr_);
+
+ int nActive = 0;
+ for (auto& v : voices_) {
+ if (!v.active) continue;
+ const SampleBuffer* sb = v.buf;
+ if (!sb || sb->empty()) { v.active = false; continue; }
+ ++nActive;
+ const double srcRatio = sb->sourceSampleRate / sr_;
+ const double loopLen = v.loopB - v.loopA;
+ double inc = 0.0, a1 = 0, a2 = 0, a3 = 0;
+ for (int32_t i = 0; i < frames; ++i) {
+ v.ex.tick(exAdd, exCoef);
+ if ((i % kCtl) == 0) {
+ v.note += (v.pitch - v.note) * glideK;
+ if (std::abs(v.pitch - v.note) < 1e-4) v.note = v.pitch;
+ const double semis = (v.note - v.root) * pTrack + pitchOff + v.tuneSemis + v.ex.bend();
+ inc = std::pow(2.0, semis / 12.0) * srcRatio;
+ if (fType > 0) {
+ double fc = baseCut;
+ if (kTrack > 0.0) fc *= std::pow(2.0, kTrack * (v.note - 60.0) / 12.0);
+ if (envOn) fc *= std::pow(2.0, envOct * v.env);
+ const double slide = (v.ex.cur[ExprSlide] - 0.5) * 2.0; // −1..+1
+ fc *= std::pow(2.0, slide * (mpeSlide - 0.5) * 8.0); // ±2 oct at the extremes
+ v.cutoff = std::clamp(fc, 20.0, sr_ * 0.49);
+ const double g = std::tan(kPi * v.cutoff / sr_);
+ a1 = 1.0 / (1.0 + g * (g + k)); a2 = g * a1; a3 = g * a2;
+ }
+ }
+ if (v.relTrig) { // a release sample plays through on its own level
+ if (v.env < 1.0f) v.env = std::min(1.0f, v.env + atkRateRel_);
+ } else switch (v.stage) {
+ case Stage::Attack: v.env += atkRate; if (v.env >= 1.0f) { v.env = 1.0f; v.stage = Stage::Decay; } break;
+ case Stage::Decay: v.env -= decRate; if (v.env <= sustain) { v.env = sustain; v.stage = Stage::Sustain; } break;
+ case Stage::Sustain: break;
+ case Stage::Release: v.env -= relRate; if (v.env <= 0.0f) { v.env = 0.0f; v.active = false; } break;
+ }
+ if (!v.active) break;
+ float kg = 1.0f;
+ if (v.kill > 0) { kg = static_cast<float>(v.kill) / static_cast<float>(v.killLen); if (--v.kill == 0) { v.active = false; break; } }
+
+ float ls, rs; readHermite(*sb, v.pos, ls, rs);
+ if (v.loopMode == 1 && v.xf > 1.0 && v.dir > 0 && v.pos > v.loopB - v.xf) {
+ const double t = (v.pos - (v.loopB - v.xf)) / v.xf;
+ float hl, hr; readHermite(*sb, v.pos - loopLen, hl, hr);
+ ls = static_cast<float>(ls * (1.0 - t) + hl * t);
+ rs = static_cast<float>(rs * (1.0 - t) + hr * t);
+ }
+ if (fType > 0) { ls = svf(v.ic1L, v.ic2L, ls, a1, a2, a3, k, fType); rs = svf(v.ic1R, v.ic2R, rs, a1, a2, a3, k, fType); }
+ const float press = 1.0f + (v.ex.pressure() * (mpePress * 2.0f)); // up to +3 at full amount
+ const float amp = v.env * v.level * vol * kg * press;
+ out[i * 2] += ls * amp * v.gl;
+ out[i * 2 + 1] += rs * amp * v.gr;
+ v.peak = std::max(v.peak * 0.9995f, std::abs(ls * amp));
+
+ v.pos += inc * v.dir;
+ if (v.loopMode == 1 && !v.relTrig) {
+ if (v.pos >= v.loopB) v.pos -= loopLen;
+ } else if (v.loopMode == 2 && !v.relTrig) {
+ if (v.pos >= v.loopB) { v.pos = v.loopB - (v.pos - v.loopB); v.dir = -1; }
+ else if (v.pos <= v.loopA && v.dir < 0) { v.pos = v.loopA + (v.loopA - v.pos); v.dir = 1; }
+ } else {
+ if (v.pos >= v.endF) { v.active = false; break; }
+ // A one-shot's last 2 ms fade so a hard cut never clicks.
+ const double left = (v.endF - v.pos) / std::max(1e-9, inc);
+ if (left < fadeTail_ && v.kill == 0) { v.kill = std::max(1, static_cast<int>(left)); v.killLen = v.kill; }
+ }
+ }
+ }
+ clock_ += frames;
+ publishTelemetry(out, frames, nActive, pan);
+ epoch_.fetch_add(1, std::memory_order_release);
+ }
+
+private:
+ static constexpr double kPi = 3.14159265358979323846;
+ static constexpr int kCtl = 16;
+ enum class Stage { Attack, Decay, Sustain, Release };
+ struct Voice {
+ bool active = false, held = false, sustained = false, relTrig = false;
+ int32_t pitch = 0, root = 60, zone = -1, dir = 1, loopMode = 0;
+ uint32_t id = 0;
+ uint64_t age = 0;
+ const SampleBuffer* buf = nullptr;
+ double pos = 0, note = 0, tuneSemis = 0, startF = 0, endF = 0, loopA = 0, loopB = 0, xf = 0, cutoff = 20000;
+ float level = 1, gl = 1, gr = 1, env = 0, peak = 0;
+ int kill = 0, killLen = 1;
+ double ic1L = 0, ic2L = 0, ic1R = 0, ic2R = 0;
+ Stage stage = Stage::Attack;
+ VoiceExpr ex;
+ };
+
+ float get(int p) const { return pn_[p].load(std::memory_order_relaxed); }
+ static double expMap(double v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp(v, 0.0, 1.0)); }
+ int voiceModeOf() const { return std::clamp(static_cast<int>(std::lround(get(VoiceMode) * 2.0f)), 0, 2); }
+
+ // ---- program publication (message thread) -------------------------------------------------
+ void adopt(const std::shared_ptr<mosaic::Program>& src) {
+ // A clone: same text, same buffers — nothing to decode.
+ auto p = mosaic::parseProgram(src->text);
+ {
+ std::lock_guard<std::mutex> lk(src->ownMx);
+ for (size_t f = 0; f < p->paths.size() && f < src->owned.size(); ++f)
+ if (src->owned[f]) { mosaic::installSample(*p, f, src->owned[f]); p->done.fetch_add(1); p->bytesDone.fetch_add(p->diskBytes[f]); }
+ }
+ publish(p);
+ mosaic::loadProgram(p);
+ }
+ // The newest program becomes the one the audio thread reads; it plays once its loaders
+ // mark it ready. The one it replaces is kept until two more renders have finished.
+ void publish(const std::shared_ptr<mosaic::Program>& p) {
+ std::lock_guard<std::mutex> lk(holdMx_);
+ if (pending_) retired_.emplace_back(epoch_.load(std::memory_order_acquire), pending_);
+ pending_ = p;
+ cur_.store(p.get(), std::memory_order_release);
+ }
+ // The program the audio thread plays now: the newest, once loaded (audio thread).
+ const mosaic::Program* live() const {
+ const mosaic::Program* p = cur_.load(std::memory_order_acquire);
+ return p && p->ready.load(std::memory_order_acquire) ? p : nullptr;
+ }
+ void reap() {
+ std::lock_guard<std::mutex> lk(holdMx_);
+ const uint64_t now = epoch_.load(std::memory_order_acquire);
+ retired_.erase(std::remove_if(retired_.begin(), retired_.end(), [&](auto& r) { return now >= r.first + 2; }), retired_.end());
+ }
+
+ // ---- voices ---------------------------------------------------------------------------------
+ void fade(Voice& v, double sec = -1) {
+ if (v.kill > 0) return;
+ const double s = sec > 0 ? sec : oldFadeSec(get(OldFade));
+ v.killLen = std::max(1, static_cast<int>(s * sr_)); v.kill = v.killLen;
+ v.held = false; v.sustained = false;
+ }
+ void limitPerKey(int32_t pitch) {
+ const int lim = perKeyOf(get(PerKey));
+ // Distinct strikes (note ids) of this key still sounding, oldest first.
+ uint32_t ids[kPool]; int n = 0;
+ for (auto& v : voices_)
+ if (v.active && v.pitch == pitch && v.kill == 0 && !v.relTrig) {
+ bool seen = false; for (int i = 0; i < n; ++i) if (ids[i] == v.id) { seen = true; break; }
+ if (!seen && n < kPool) ids[n++] = v.id;
+ }
+ std::sort(ids, ids + n);
+ for (int i = 0; i + lim <= n; ++i) // keep lim − 1 old ones: the new strike is the lim-th
+ for (auto& v : voices_) if (v.active && v.id == ids[i]) fade(v);
+ }
+ int liveCount() const { int c = 0; for (auto& v : voices_) if (v.active && v.kill == 0) ++c; return c; }
+ // The voice to steal: released first, then the quietest, then the oldest.
+ Voice* victim() {
+ Voice* q = nullptr;
+ auto rank = [](const Voice& v) { return v.held ? 2 : (v.sustained ? 1 : 0); };
+ for (auto& v : voices_) {
+ if (!v.active || v.kill > 0) continue;
+ if (!q) { q = &v; continue; }
+ if (rank(v) != rank(*q)) { if (rank(v) < rank(*q)) q = &v; continue; }
+ if (std::abs(v.peak - q->peak) > 1e-4f) { if (v.peak < q->peak) q = &v; continue; }
+ if (v.age < q->age) q = &v;
+ }
+ return q;
+ }
+ Voice* freeSlot() {
+ for (auto& v : voices_) if (!v.active) return &v;
+ Voice* q = &voices_[0]; // everything busy (fades included): the quietest outright
+ for (auto& v : voices_) if (v.peak < q->peak) q = &v;
+ return q;
+ }
+
+ static float xfadeGain(int x, int inLo, int inHi, int outLo, int outHi) {
+ double g = 1.0;
+ if (inLo >= 0 && inHi > inLo) { if (x <= inLo) return 0.0f; if (x < inHi) g *= std::sin(0.5 * kPi * (x - inLo) / double(inHi - inLo)); }
+ if (outLo >= 0 && outHi > outLo) { if (x >= outHi) return 0.0f; if (x > outLo) g *= std::cos(0.5 * kPi * (x - outLo) / double(outHi - outLo)); }
+ return static_cast<float>(g);
+ }
+
+ // Starts the voices of a note (attack zones) or of a key's release (release zones).
+ void spawn(const mosaic::Program& p, int32_t pitch, int vel7, float velocity, uint32_t id, bool release, float relGain, double fromNote) {
+ // One random number per event, shared by every group (SFZ lorand / hirand).
+ rng_ = rng_ * 1664525u + 1013904223u;
+ const float r = static_cast<float>((rng_ >> 8) & 0xFFFFFF) / 16777216.0f;
+ // Round-robin: each group with matching zones steps once per event.
+ const size_t ng = std::min(p.groups.size(), kGroups);
+ bool touched[kGroups] = {};
+ int32_t step[kGroups];
+ for (size_t g = 0; g < ng; ++g) step[g] = 1;
+ for (const auto& z : p.zones) {
+ if ((z.trig == 1) != release || pitch < z.klo || pitch > z.khi || vel7 < z.vlo || vel7 > z.vhi) continue;
+ const size_t g = static_cast<size_t>(z.group);
+ if (g >= kGroups || touched[g]) continue;
+ touched[g] = true;
+ const auto& gr = p.groups[g];
+ if (gr.seqLen <= 1) { step[g] = 1; continue; }
+ if (gr.rrMode == 0) { rrStep_[g] = rrStep_[g] % gr.seqLen + 1; step[g] = rrStep_[g]; }
+ else {
+ rng_ = rng_ * 1664525u + 1013904223u;
+ int s = 1 + static_cast<int>((rng_ >> 8) % static_cast<uint32_t>(gr.seqLen));
+ if (gr.rrMode == 2 && s == rrLast_[g]) s = s % gr.seqLen + 1;
+ rrLast_[g] = s; step[g] = s;
+ }
+ }
+ const double velAmt = get(VelAmount);
+ const double curved = velCurve(velocity, get(VelCurve));
+ const float velGain = static_cast<float>(velAmt * curved + (1.0 - velAmt));
+ const int limit = polyOf(get(Polyphony));
+ const double masterPan = get(Pan) * 2.0 - 1.0;
+ float add[kExprDims]; gexpr_.offsets(static_cast<float>(bendSemis(get(BendRange))), add);
+ for (size_t zi = 0; zi < p.zones.size(); ++zi) {
+ const auto& z = p.zones[zi];
+ if ((z.trig == 1) != release || pitch < z.klo || pitch > z.khi || vel7 < z.vlo || vel7 > z.vhi) continue;
+ const auto& gr = p.groups[static_cast<size_t>(z.group)];
+ if (gr.seqLen > 1 && static_cast<size_t>(z.group) < kGroups && z.seq != step[z.group]) continue;
+ if (z.rlo > 0.0f || z.rhi < 1.0f) { if (r < z.rlo || r >= z.rhi) continue; }
+ const SampleBuffer* sb = p.sample(z.file);
+ if (!sb || sb->empty()) continue;
+ const float xg = xfadeGain(pitch, z.xkil, z.xkih, z.xkol, z.xkoh) * xfadeGain(vel7, z.xvil, z.xvih, z.xvol, z.xvoh);
+ if (xg <= 0.0f) continue;
+ // Exclusive groups: this zone chokes every voice whose off_by names its group.
+ if (z.excl != 0)
+ for (auto& v : voices_)
+ if (v.active && v.zone >= 0 && v.zone < static_cast<int32_t>(p.zones.size()) && p.zones[v.zone].offBy == z.excl)
+ { if (p.zones[v.zone].offMode == 1) { v.held = false; v.sustained = false; v.stage = Stage::Release; } else fade(v, 0.006); }
+ // Make room within the polyphony.
+ while (liveCount() >= limit) { Voice* q = victim(); if (!q) break; fade(*q); }
+ Voice& v = *freeSlot();
+ const double N = static_cast<double>(sb->frames);
+ v = Voice{};
+ v.active = true; v.held = !release; v.relTrig = release;
+ v.pitch = pitch; v.root = z.root; v.zone = static_cast<int32_t>(zi); v.id = id; v.age = ++ageSerial_;
+ v.buf = sb;
+ v.startF = std::clamp(z.start, 0.0, std::max(0.0, N - 1));
+ v.endF = z.end > 0 ? std::clamp(z.end, v.startF + 1, N) : N;
+ v.loopMode = z.loopMode;
+ v.loopA = z.loopStart >= 0 ? std::clamp(z.loopStart, v.startF, v.endF - 1) : v.startF;
+ v.loopB = z.loopEnd > 0 ? std::clamp(z.loopEnd, v.loopA + 1, v.endF) : v.endF;
+ v.xf = std::clamp(static_cast<double>(z.xfade) * sb->sourceSampleRate, 0.0, (v.loopB - v.loopA) * 0.5);
+ v.pos = v.startF; v.dir = 1;
+ v.tuneSemis = (z.tune + gr.tune) / 100.0;
+ v.note = release ? static_cast<double>(pitch) : fromNote;
+ const double zg = std::pow(10.0, (z.gainDb + gr.gainDb) / 20.0);
+ v.level = static_cast<float>(zg) * xg * velGain * relGain;
+ const double pn = std::clamp(masterPan + z.pan, -1.0, 1.0);
+ v.gl = static_cast<float>(std::cos((pn + 1.0) * kPi / 4.0));
+ v.gr = static_cast<float>(std::sin((pn + 1.0) * kPi / 4.0));
+ v.env = release ? 1.0f : 0.0f; // a release sample starts at its own level
+ v.stage = Stage::Attack;
+ v.ex.reset(add);
+ v.peak = v.level;
+ }
+ }
+
+ void releaseTrigger(int32_t pitch) {
+ if (get(RelOn) < 0.5f) return;
+ const mosaic::Program* p = live();
+ if (!p) return;
+ bool has = false;
+ for (const auto& z : p->zones) if (z.trig == 1 && pitch >= z.klo && pitch <= z.khi) { has = true; break; }
+ if (!has) return;
+ const double heldSec = static_cast<double>(clock_ - noteOnAt_[pitch]) / sr_;
+ const double db = relVolDb(get(RelVol)) + relLenDb(get(RelLen)) * std::clamp(heldSec / 2.0, 0.0, 1.0);
+ const float g = static_cast<float>(std::pow(10.0, db / 20.0));
+ const float vel = noteVel_[pitch];
+ const int vel7 = std::clamp(static_cast<int>(std::lround(vel * 127.0f)), 0, 127);
+ spawn(*p, pitch, vel7, vel, ++noteSerial_, true, g, pitch);
+ }
+
+ // 4-point Hermite read of a stereo frame at a fractional position.
+ static void readHermite(const SampleBuffer& b, double pos, float& l, float& r) {
+ const int64_t i1 = static_cast<int64_t>(std::floor(pos));
+ const float t = static_cast<float>(pos - static_cast<double>(i1));
+ float l0, r0, l1, r1, l2, r2, l3, r3;
+ b.readStereo(i1 - 1, l0, r0); b.readStereo(i1, l1, r1); b.readStereo(i1 + 1, l2, r2); b.readStereo(i1 + 2, l3, r3);
+ auto h = [t](float y0, float y1, float y2, float y3) {
+ const float c1 = 0.5f * (y2 - y0), c2 = y0 - 2.5f * y1 + 2.0f * y2 - 0.5f * y3, c3 = 0.5f * (y3 - y0) + 1.5f * (y1 - y2);
+ return ((c3 * t + c2) * t + c1) * t + y1;
+ };
+ l = h(l0, l1, l2, l3); r = h(r0, r1, r2, r3);
+ }
+ static float svf(double& ic1, double& ic2, float xf, double a1, double a2, double a3, double k, int type) {
+ const double x = xf;
+ const double v3 = x - ic2, v1 = a1 * ic1 + a2 * v3, v2 = ic2 + a2 * ic1 + a3 * v3;
+ ic1 = 2.0 * v1 - ic1; ic2 = 2.0 * v2 - ic2;
+ if (type == 1) return static_cast<float>(v2);
+ if (type == 2) return static_cast<float>(x - k * v1 - v2);
+ return static_cast<float>(v1);
+ }
+
+ void publishTelemetry(const float* out, int32_t frames, int nActive, double /*pan*/) {
+ float peak = 0.0f;
+ for (int32_t i = 0; i < frames * 2; ++i) peak = std::max(peak, std::abs(out[i]));
+ int held = 0, sus = 0, rel = 0;
+ const Voice* best = nullptr;
+ int n = 0;
+ uint32_t keys[8] = {};
+ for (auto& v : voices_) {
+ if (!v.active) continue;
+ if (v.relTrig) ++rel; else if (v.held) ++held; else if (v.sustained) ++sus;
+ if ((v.held || v.sustained) && v.kill == 0 && v.pitch >= 0 && v.pitch < 128) keys[v.pitch >> 4] |= 1u << (v.pitch & 15);
+ if (!best || v.peak * v.env > best->peak * best->env) best = &v;
+ if (n < kScZones) {
+ const int st = v.relTrig || v.kill > 0 || (!v.held && !v.sustained) ? 2 : (v.held ? 0 : 1);
+ const float code = static_cast<float>(v.zone * 4 + st);
+ bool dup = false;
+ for (int i = 0; i < n; ++i) if (tele_[kScHead + i].load(std::memory_order_relaxed) == code) { dup = true; break; }
+ if (!dup) tele_[kScHead + n++].store(code, std::memory_order_relaxed);
+ }
+ }
+ tele_[0].store(static_cast<float>(nActive), std::memory_order_relaxed);
+ tele_[1].store(static_cast<float>(polyOf(get(Polyphony))), std::memory_order_relaxed);
+ tele_[2].store(static_cast<float>(held), std::memory_order_relaxed);
+ tele_[3].store(static_cast<float>(sus), std::memory_order_relaxed);
+ tele_[4].store(static_cast<float>(rel), std::memory_order_relaxed);
+ tele_[5].store(pedalDown_ ? 1.0f : 0.0f, std::memory_order_relaxed);
+ if (peak > tele_[6].load(std::memory_order_relaxed)) tele_[6].store(peak, std::memory_order_relaxed);
+ const double bn = best && best->buf ? static_cast<double>(best->buf->frames) : 1.0;
+ tele_[7].store(best ? static_cast<float>(best->pos / bn) : -1.0f, std::memory_order_relaxed);
+ tele_[8].store(best ? best->env : 0.0f, std::memory_order_relaxed);
+ tele_[9].store(best ? static_cast<float>(best->relTrig ? 3 : static_cast<int>(best->stage)) : -1.0f, std::memory_order_relaxed);
+ tele_[10].store(best ? static_cast<float>(best->note) : -1.0f, std::memory_order_relaxed);
+ const int fType = std::clamp(static_cast<int>(std::lround(get(FilterType) * 3.0f)), 0, 3);
+ tele_[11].store(best && fType > 0 ? static_cast<float>(best->cutoff) : -1.0f, std::memory_order_relaxed);
+ tele_[12].store(best ? static_cast<float>(best->zone) : -1.0f, std::memory_order_relaxed);
+ tele_[13].store(static_cast<float>(lastNote_), std::memory_order_relaxed);
+ tele_[14].store(static_cast<float>(std::lround(lastVel_ * 127.0f)), std::memory_order_relaxed);
+ tele_[15].store(static_cast<float>(n), std::memory_order_relaxed);
+ for (int i = 0; i < 8; ++i) tele_[kScKeys + i].store(static_cast<float>(keys[i]), std::memory_order_relaxed);
+ }
+
+ void pushHeld(int32_t p) {
+ popHeld(p);
+ if (heldN_ == kHeld) { std::memmove(held_, held_ + 1, sizeof(int32_t) * (kHeld - 1)); --heldN_; }
+ held_[heldN_++] = p;
+ }
+ void popHeld(int32_t p) {
+ for (int i = 0; i < heldN_; ++i)
+ if (held_[i] == p) { std::memmove(held_ + i, held_ + i + 1, sizeof(int32_t) * (heldN_ - i - 1)); --heldN_; return; }
+ }
+
+ // Program (see the header): the newest set (pending_) and the one the audio thread plays.
+ mutable std::mutex holdMx_;
+ std::shared_ptr<mosaic::Program> pending_;
+ std::vector<std::pair<uint64_t, std::shared_ptr<mosaic::Program>>> retired_;
+ std::atomic<const mosaic::Program*> cur_{nullptr};
+ std::atomic<uint64_t> epoch_{0};
+ const mosaic::Program* lastLive_ = nullptr; // audio thread
+
+ // Audio-thread state.
+ Voice voices_[kPool];
+ static constexpr int kHeld = 16;
+ int32_t held_[kHeld] = {};
+ int heldN_ = 0;
+ int32_t glideFrom_ = -1, lastNote_ = -1;
+ float lastVel_ = 0.0f;
+ uint32_t noteSerial_ = 0, rng_ = 0x2545F491u;
+ uint64_t ageSerial_ = 0, clock_ = 0;
+ uint64_t noteOnAt_[128];
+ float noteVel_[128];
+ bool pedalKeys_[128] = {}, keyDown_[128] = {};
+ static constexpr size_t kGroups = 512; // round-robin state for the first 512 groups
+ int32_t rrStep_[kGroups] = {}, rrLast_[kGroups] = {};
+ GlobalExpr gexpr_;
+ bool cc64_ = false, pedalDown_ = false;
+ double sr_ = 44100.0;
+ double fadeTail_ = 96.0; // frames of fade before a one-shot's end
+ float atkRateRel_ = 1.0f;
+ mutable std::atomic<float> tele_[kScope] = {};
+ std::atomic<float> pn_[kNumParams];
+};
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/nota_engine_audition.cpp b/src/native/nota.engine/src/nota_engine_audition.cpp
index 5c32adf4..788bb179 100644
--- a/src/native/nota.engine/src/nota_engine_audition.cpp
+++ b/src/native/nota.engine/src/nota_engine_audition.cpp
@@ -37,6 +37,9 @@ int32_t nota_audition_midi_param(NotaAudition* rig, int32_t index, const char* n
int32_t nota_audition_set_sampler_sample(NotaAudition* rig, const char* path, int32_t root_note) {
return rig && RIG(rig)->setSamplerSample(path ? std::string(path) : std::string(), root_note) ? 1 : 0;
}
+int32_t nota_audition_set_mosaic_program(NotaAudition* rig, const char* text) {
+ return rig && text && RIG(rig)->setMosaicProgram(std::string(text)) ? 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;
}
diff --git a/src/native/nota.engine/src/nota_engine_import.cpp b/src/native/nota.engine/src/nota_engine_import.cpp
index 956d0b17..8a902004 100644
--- a/src/native/nota.engine/src/nota_engine_import.cpp
+++ b/src/native/nota.engine/src/nota_engine_import.cpp
@@ -101,4 +101,23 @@ NotaResult nota_sample_analyze_file(const char* path, double max_seconds, NotaSa
return NOTA_OK;
}
+int64_t nota_file_decode_mono(const char* path, double max_seconds, float* out, int64_t cap, double* sample_rate) {
+ if (!path) return 0;
+ auto job = nota::AudioImportJob::open(std::string(path), max_seconds);
+ if (!job || !job->buffer()) return 0;
+ while (!job->done())
+ if (job->step(1 << 17) < 0) return 0;
+ const auto& b = *job->buffer();
+ if (b.frames <= 0 || b.channels <= 0) return 0;
+ if (sample_rate) *sample_rate = b.sourceSampleRate;
+ if (!out || cap <= 0) return b.frames;
+ const int64_t n = std::min<int64_t>(b.frames, cap);
+ for (int64_t f = 0; f < n; ++f) {
+ float s = 0.0f;
+ for (int32_t c = 0; c < b.channels; ++c) s += b.samples[static_cast<size_t>(f * b.channels + c)];
+ out[f] = s / static_cast<float>(b.channels);
+ }
+ return n;
+}
+
} // extern "C"
diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cpp
index 72c4533d..55068349 100644
--- a/src/native/nota.engine/src/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/nota_engine_track.cpp
@@ -6,6 +6,7 @@
// getters/setters (M7-6b: audio clips, samples, sampler).
#include "nota_engine_internal.h"
+#include "Mosaic.h"
#include <algorithm>
#include <cstring>
@@ -148,6 +149,27 @@ int32_t nota_engine_add_consort_track(NotaEngine* e) {
int32_t nota_engine_add_keys_track(NotaEngine* e) {
return e ? ENG(e)->addKeysTrack() : 0;
}
+int32_t nota_engine_add_mosaic_track(NotaEngine* e) {
+ return e ? ENG(e)->addMosaicTrack() : 0;
+}
+int32_t nota_track_mosaic_set_program(NotaEngine* e, int32_t track_id, const char* text, int32_t checkpoint) {
+ return e && text && ENG(e)->mosaicSetProgram(track_id, std::string(text), checkpoint != 0) ? 1 : 0;
+}
+int32_t nota_track_mosaic_program(const NotaEngine* e, int32_t track_id, char* out, int32_t cap) {
+ if (!e) return 0;
+ const std::string s = CENG(e)->mosaicProgram(track_id);
+ if (out && cap > 0) std::memcpy(out, s.data(), std::min<size_t>(s.size(), static_cast<size_t>(cap)));
+ return static_cast<int32_t>(s.size());
+}
+int32_t nota_track_mosaic_status(const NotaEngine* e, int32_t track_id, NotaMosaicStatus* out) {
+ return e && out && CENG(e)->mosaicStatus(track_id, out) ? 1 : 0;
+}
+int64_t nota_track_mosaic_zone_sample_id(const NotaEngine* e, int32_t track_id, int32_t zone) {
+ return e ? CENG(e)->mosaicZoneSampleId(track_id, zone) : 0;
+}
+void nota_path_root_set(const char* name, const char* path) {
+ if (name && path) nota::mosaic::setRoot(std::string(name), std::string(path));
+}
void nota_track_instrument_action(NotaEngine* e, int32_t track_id, int32_t id, int32_t iarg, float farg) {
if (e) ENG(e)->instrumentAction(track_id, id, iarg, farg);
}
diff --git a/tests/Nota.SmokeTest/MosaicTests.cs b/tests/Nota.SmokeTest/MosaicTests.cs
new file mode 100644
index 00000000..d0052afe
--- /dev/null
+++ b/tests/Nota.SmokeTest/MosaicTests.cs
@@ -0,0 +1,526 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Mosaic (instrument kind 17): identity and params; the program text round-trip (C# ↔
+// engine); asynchronous loading (silent until ready, missing files counted); zone choice by
+// key, velocity and round-robin; pitch from the root; release triggers quieter after a long
+// hold; the sustain pedal; the polyphony and per-key limits; state / duplicate / swap; MPE
+// bend; SFZ import (#define, #include, backslashes, CC articulations, ignored families);
+// the file-name mapper (notes, layers, rr, release, octave check, duplicates, gaps).
+
+using Nota.Application;
+using Nota.Application.Mosaic;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class MosaicTests
+{
+ private const int Sr = 48000;
+
+ private static int Pi(NotaEngine e, int t, string id)
+ {
+ int n = e.PluginParamCount(t, -1);
+ for (int i = 0; i < n; i++) if (e.PluginParamId(t, -1, i) == id) return i;
+ return -1;
+ }
+ private static void P(NotaEngine e, int t, string id, float v) => e.PluginParamSet(t, -1, Pi(e, t, id), v);
+
+ private static float[] Render(NotaEngine e, int frames, int block = 512)
+ {
+ var all = new float[frames * 2];
+ var b = new float[block * 2];
+ for (int done = 0; done < frames;)
+ {
+ int m = Math.Min(block, frames - done);
+ e.RenderOffline(b, m, Sr);
+ Array.Copy(b, 0, all, done * 2, m * 2);
+ done += m;
+ }
+ return all;
+ }
+ private static double Rms(float[] st, int from = 0, int to = -1)
+ {
+ if (to < 0) to = st.Length / 2;
+ double s = 0;
+ for (int i = from * 2; i < to * 2; i++) s += st[i] * (double)st[i];
+ return Math.Sqrt(s / Math.Max(1, (to - from) * 2));
+ }
+ // The strongest of a few candidate frequencies (Goertzel, mono).
+ private static double Energy(float[] st, double hz, int from = 0)
+ {
+ double w = 2 * Math.PI * hz / Sr, c = 2 * Math.Cos(w), s1 = 0, s2 = 0;
+ for (int i = from * 2; i < st.Length; i += 2) { double s0 = (st[i] + st[i + 1]) * 0.5 + c * s1 - s2; s2 = s1; s1 = s0; }
+ return s1 * s1 + s2 * s2 - c * s1 * s2;
+ }
+ private static double Hz(int midi) => 440.0 * Math.Pow(2, (midi - 69) / 12.0);
+
+ // A sine file at a MIDI note (its root), mono, `sec` long with a short fade.
+ private static string Tone(string dir, string name, double hz, double sec = 1.0, float amp = 0.5f)
+ {
+ string path = Path.Combine(dir, name);
+ int n = (int)(sec * Sr);
+ var d = new float[n * 2];
+ for (int i = 0; i < n; i++)
+ {
+ float env = Math.Min(1f, Math.Min(i / 96f, (n - i) / 480f));
+ float s = (float)(amp * env * Math.Sin(2 * Math.PI * hz * i / Sr));
+ d[2 * i] = s; d[2 * i + 1] = s;
+ }
+ using (var w = new Nota.Infrastructure.WavWriter(path, Sr, 2, WavBitDepth.Pcm24)) w.WriteFrames(d, n);
+ return path;
+ }
+
+ private static bool WaitReady(NotaEngine e, int t, int ms = 5000)
+ {
+ var sw = System.Diagnostics.Stopwatch.StartNew();
+ while (sw.ElapsedMilliseconds < ms)
+ {
+ if (e.TryGetMosaicStatus(t, out var s) && s.State == 2) { Render(e, 256); return true; }
+ Thread.Sleep(5);
+ }
+ return false;
+ }
+
+ private static List<MosaicModel.Sounding> Sounding(NotaEngine e, int t)
+ {
+ var sc = new float[MosaicModel.ScopeLength];
+ int n = e.InstrumentScope(t, sc);
+ var snap = new MosaicModel.Snapshot();
+ MosaicModel.Parse(sc.AsSpan(0, n), snap);
+ return snap.Zones.ToList();
+ }
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ string dir = Path.Combine(Path.GetTempPath(), "nota-mosaic-test-" + Environment.ProcessId);
+ Directory.CreateDirectory(dir);
+ try { foreach (var r in RunIn(dir)) yield return r; }
+ finally { try { Directory.Delete(dir, true); } catch { } }
+ }
+
+ private static IEnumerable<(bool, string)> RunIn(string dir)
+ {
+ // ---- the samples: roots C4 / G4 × layers p / f, rr 1–2 on C4 f, a release at C4 -----
+ string c4p = Tone(dir, "pno_c4_p.wav", Hz(60), 1.0, 0.2f);
+ string c4f1 = Tone(dir, "pno_c4_f_rr1.wav", Hz(60), 1.0, 0.6f);
+ string c4f2 = Tone(dir, "pno_c4_f_rr2.wav", Hz(60), 1.0, 0.6f);
+ string g4p = Tone(dir, "pno_g4_p.wav", Hz(67), 1.0, 0.2f);
+ string g4f = Tone(dir, "pno_g4_f.wav", Hz(67), 1.0, 0.6f);
+ string rel = Tone(dir, "pno_c4_rel.wav", Hz(84), 0.3, 0.5f);
+
+ var prog = new MosaicProgram { Name = "Test Piano", SourceKind = "files" };
+ prog.Files.AddRange(new[] { c4p, c4f1, c4f2, g4p, g4f, rel });
+ prog.Groups.Add(new MosaicGroup { Name = "Sustain · p" });
+ prog.Groups.Add(new MosaicGroup { Name = "Sustain · f", SeqLen = 2, RrMode = 0 });
+ prog.Groups.Add(new MosaicGroup { Name = "Release" });
+ prog.Zones.Add(new MosaicZone { File = 0, Group = 0, Root = 60, KeyLo = 0, KeyHi = 63, VelLo = 0, VelHi = 63 });
+ prog.Zones.Add(new MosaicZone { File = 1, Group = 1, Root = 60, KeyLo = 0, KeyHi = 63, VelLo = 64, VelHi = 127, Seq = 1 });
+ prog.Zones.Add(new MosaicZone { File = 2, Group = 1, Root = 60, KeyLo = 0, KeyHi = 63, VelLo = 64, VelHi = 127, Seq = 2 });
+ prog.Zones.Add(new MosaicZone { File = 3, Group = 0, Root = 67, KeyLo = 64, KeyHi = 127, VelLo = 0, VelHi = 63 });
+ prog.Zones.Add(new MosaicZone { File = 4, Group = 1, Root = 67, KeyLo = 64, KeyHi = 127, VelLo = 64, VelHi = 127, Seq = 1 });
+ prog.Zones.Add(new MosaicZone { File = 4, Group = 1, Root = 67, KeyLo = 64, KeyHi = 127, VelLo = 64, VelHi = 127, Seq = 2 });
+ prog.Zones.Add(new MosaicZone { File = 5, Group = 2, Root = 72, KeyLo = 0, KeyHi = 127, Release = true });
+ string text = prog.Serialize();
+
+ // ---- the text round-trips ------------------------------------------------------------
+ var back = MosaicProgram.Parse(text);
+ yield return (back.Serialize() == text && back.Zones.Count == 7 && back.Groups[1].SeqLen == 2 && back.Zones[6].Release,
+ "MosaicProgram text round-trips (zones, groups, rr, release)");
+ var esc = new MosaicProgram { Name = "Grand 100% = Piano" };
+ esc.Files.Add("samples:Downloaded/Osiris Piano/C4 soft.flac");
+ esc.Zones.Add(new MosaicZone { File = 0 });
+ var esc2 = MosaicProgram.Parse(esc.Serialize());
+ yield return (esc2.Name == "Grand 100% = Piano" && esc2.Files[0] == "samples:Downloaded/Osiris Piano/C4 soft.flac",
+ "names and paths with spaces, % and = survive the text");
+ yield return (MosaicPaths.ToRef("/Users/x/Music/Nota Samples/Downloaded/P/a.wav", "/Users/x/Music/Nota Samples", null) == "samples:Downloaded/P/a.wav"
+ && MosaicPaths.Resolve("samples:Downloaded/P/a.wav", "/S", null) == Path.Combine("/S", "Downloaded", "P", "a.wav"),
+ "sample references are relative to the Samples folder");
+
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddMosaicTrack();
+ yield return (t > 0 && e.TrackInstrumentKind(t) == MosaicModel.Kind && e.DeviceName(t, -1) == "Nota Mosaic",
+ $"AddMosaicTrack adds kind 17 Nota Mosaic (got {e.TrackInstrumentKind(t)} '{e.DeviceName(t, -1)}')");
+ int pc = e.PluginParamCount(t, -1);
+ var ids = new HashSet<string>();
+ bool names = true;
+ for (int i = 0; i < pc; i++) { ids.Add(e.PluginParamId(t, -1, i)); if (e.PluginParamName(t, -1, i).Length == 0) names = false; }
+ yield return (pc == 31 && ids.Count == pc && names, $"Nota Mosaic exposes 31 params with unique ids and names (got {pc})");
+ yield return (e.TrackInstrumentSupportsMpe(t), "Nota Mosaic reports MPE support");
+ yield return (InstrumentView.Index(e, t) >= 0 && !InstrumentView.IsMini(e, t), "Nota Mosaic has an S / L view param and opens as L");
+ yield return (MosaicModel.Poly(e.PluginParamGet(t, -1, Pi(e, t, "polyphony"))) == 64 && MosaicModel.PerKey(e.PluginParamGet(t, -1, Pi(e, t, "perkey"))) == 2,
+ "defaults: Poly 64, 2 strikes per key");
+
+ // Empty → silent.
+ e.TrackNoteOn(t, 60, 0.8f);
+ yield return (Rms(Render(e, 4096)) < 1e-6, "an empty Mosaic is silent");
+ e.TrackNoteOff(t, 60);
+ Render(e, 256);
+
+ yield return (e.MosaicSetProgram(t, text), "the program is accepted");
+ yield return (e.MosaicProgram(t) == text, "the engine returns the program text verbatim");
+ bool ready = WaitReady(e, t);
+ e.TryGetMosaicStatus(t, out var st);
+ yield return (ready && st.FilesTotal == 6 && st.FilesDone == 6 && st.Missing == 0 && st.Zones == 7 && st.RamBytes > 0,
+ $"the samples load in the background (state {st.State}, {st.FilesDone}/{st.FilesTotal}, {st.Zones} zones, {st.RamBytes} B)");
+
+ // Soft C4: the p zone, at its own pitch.
+ e.TrackNoteOn(t, 60, 0.3f);
+ var b = Render(e, Sr / 4);
+ var z = Sounding(e, t);
+ yield return (z.Count == 1 && z[0].Zone == 0 && Rms(b) > 0.01, $"a soft C4 plays the p zone (zones {string.Join(",", z.Select(s => s.Zone))}, rms {Rms(b):F3})");
+ yield return (Energy(b, Hz(60), 2000) > 20 * Energy(b, Hz(62), 2000), "the zone plays at its root's pitch on its root");
+ e.TrackNoteOff(t, 60);
+ Render(e, Sr / 2);
+
+ // D4 from the C4 root: two semitones up.
+ e.TrackNoteOn(t, 62, 0.3f);
+ b = Render(e, Sr / 4);
+ yield return (Energy(b, Hz(62), 2000) > 20 * Energy(b, Hz(60), 2000), "a key away from the root is transposed (D4 from a C4 sample)");
+ e.TrackNoteOff(t, 62);
+ Render(e, Sr / 2);
+
+ // Loud C4: the f layer, round-robin 1 then 2.
+ var seq = new List<int>();
+ for (int k = 0; k < 3; k++)
+ {
+ e.TrackNoteOn(t, 60, 0.9f);
+ Render(e, 512);
+ seq.Add(Sounding(e, t).Where(s => s.State == 0).Select(s => s.Zone).FirstOrDefault(-1));
+ e.TrackNoteOff(t, 60);
+ Render(e, Sr / 2);
+ }
+ yield return (seq.SequenceEqual(new[] { 1, 2, 1 }), $"loud C4 picks the f layer, sequential round-robin 1 → 2 → 1 (got {string.Join(" → ", seq)})");
+
+ // Release trigger: sounds on key-up, quieter after a long hold. (The release sample,
+ // an octave above its key, plays at half speed: 0.6 s — let the loop's ones finish.)
+ P(e, t, "release", 0f); // a short amp release so the release sample stands alone
+ Render(e, Sr);
+ e.TrackNoteOn(t, 60, 0.3f);
+ Render(e, 1024);
+ e.TrackNoteOff(t, 60);
+ var rb = Render(e, Sr / 8);
+ var rz = Sounding(e, t);
+ double shortRel = Energy(rb, Hz(72));
+
+ yield return (rz.Any(s => s.Zone == 6), $"key-up starts the release zone (zones {string.Join(",", rz.Select(s => s.Zone + ":" + s.State))})");
+ Render(e, Sr);
+ e.TrackNoteOn(t, 60, 0.3f);
+ Render(e, Sr * 2 + 100);
+ e.TrackNoteOff(t, 60);
+ double longRel = Energy(Render(e, Sr / 8), Hz(72));
+ double dropDb = 10 * Math.Log10(Math.Max(1e-12, longRel) / Math.Max(1e-12, shortRel));
+ yield return (dropDb < -4.5 && dropDb > -8, $"after a 2 s hold the release sample is about 6 dB quieter ({dropDb:F1} dB)");
+ Render(e, Sr);
+ P(e, t, "relon", 0f);
+ e.TrackNoteOn(t, 60, 0.3f); Render(e, 1024); e.TrackNoteOff(t, 60); Render(e, 256);
+ yield return (!Sounding(e, t).Any(s => s.Zone == 6), "Release triggers off: no release zone");
+ P(e, t, "relon", 1f);
+ Render(e, Sr);
+
+ // Pedal: key-up while CC64 is down keeps the note; lifting it releases.
+ e.TrackNoteExpression(t, -1, NoteExpressionDim.Sustain, 1f);
+ e.TrackNoteOn(t, 60, 0.3f); Render(e, 1024); e.TrackNoteOff(t, 60); Render(e, 2048);
+ var ped = Sounding(e, t);
+ var sc = new float[MosaicModel.ScopeLength]; e.InstrumentScope(t, sc);
+ yield return (ped.Any(s => s.Zone == 0 && s.State == 1) && sc[MosaicModel.ScPedal] > 0.5f && !ped.Any(s => s.Zone == 6),
+ $"with the pedal down a released key keeps sounding, no release sample yet ({string.Join(",", ped.Select(s => s.Zone + ":" + s.State))})");
+ e.TrackNoteExpression(t, -1, NoteExpressionDim.Sustain, 0f);
+ Render(e, 512);
+ yield return (Sounding(e, t).Any(s => s.Zone == 6), "lifting the pedal fires the release sample");
+ Render(e, Sr);
+
+ // MPE bend: +2 semitones on a held note.
+ e.TrackNoteOn(t, 60, 0.3f);
+ e.TrackNoteExpression(t, 60, NoteExpressionDim.Bend, 2f);
+ b = Render(e, Sr / 4);
+ yield return (Energy(b, Hz(62), 4000) > 10 * Energy(b, Hz(60), 4000), "an MPE bend of +2 st retunes the held note");
+ e.TrackNoteOff(t, 60);
+ Render(e, Sr);
+
+ // Per key: four strikes of one key ring at most two at a time.
+ P(e, t, "relon", 0f);
+ for (int k = 0; k < 4; k++) { e.TrackNoteOn(t, 60, 0.3f); Render(e, 256); }
+ Render(e, 4096);
+ int sameKey = e.InstrumentVoiceCount(t);
+ yield return (sameKey == 2, $"Per key 2: four strikes of C4 leave 2 voices (got {sameKey})");
+ e.TrackNoteOff(t, 60);
+ Render(e, Sr);
+
+ // Polyphony 16: 24 keys hold 16 voices.
+ P(e, t, "polyphony", 0f);
+ for (int k = 30; k < 54; k++) e.TrackNoteOn(t, k, 0.3f);
+ Render(e, 4096);
+ int poly = e.InstrumentVoiceCount(t);
+ yield return (poly == 16, $"Poly 16: 24 keys keep 16 voices (got {poly})");
+ for (int k = 30; k < 54; k++) e.TrackNoteOff(t, k);
+ P(e, t, "polyphony", 2f / 3f); P(e, t, "relon", 1f);
+ Render(e, Sr);
+
+ // State, duplicate, swap.
+ P(e, t, "cutoff", 0.4f);
+ var state = e.GetPluginState(t, -1);
+ int t2 = e.AddMosaicTrack();
+ e.SetPluginState(t2, -1, state);
+ yield return (e.MosaicProgram(t2) == text && Math.Abs(e.PluginParamGet(t2, -1, Pi(e, t2, "cutoff")) - 0.4f) < 1e-5 && WaitReady(e, t2),
+ "the state carries params + program to another track, which loads it");
+ int t3 = e.DuplicateTrack(t);
+ yield return (t3 > 0 && e.MosaicProgram(t3) == text && e.TryGetMosaicStatus(t3, out var s3) && s3.State == 2,
+ "duplicating the track shares the loaded samples (ready at once)");
+ yield return (e.SetTrackBuiltinInstrument(e.AddInstrumentTrack(), 17), "a track's instrument can be swapped to Nota Mosaic");
+
+ // A zone edit (same files) swaps in at once and keeps playing.
+ e.TrackNoteOn(t, 60, 0.3f); Render(e, 1024);
+ var edited = MosaicProgram.Parse(text); edited.Zones[0].GainDb = -6;
+ e.MosaicSetProgram(t, edited.Serialize(), undoable: false);
+ e.TryGetMosaicStatus(t, out var se);
+ var eb = Render(e, 2048);
+ yield return (se.State == 2 && Rms(eb) > 0.005, $"a zone edit is ready at once and the held note keeps sounding (state {se.State}, rms {Rms(eb):F3})");
+ e.TrackNoteOff(t, 60);
+
+ // An undoable edit: one undo step brings the old program back.
+ var edited2 = MosaicProgram.Parse(text); edited2.Zones[0].Root = 61;
+ e.MosaicSetProgram(t, edited2.Serialize());
+ bool readyNow = e.TryGetMosaicStatus(t, out var su) && su.State == 2;
+ bool changed = MosaicProgram.Parse(e.MosaicProgram(t)).Zones[0].Root == 61;
+ e.Undo();
+ yield return (readyNow && changed && MosaicProgram.Parse(e.MosaicProgram(t)).Zones[0].Root == 60,
+ "an undoable program edit is ready at once and undoes in one step");
+
+ // A missing file is counted; the rest plays.
+ var miss = MosaicProgram.Parse(text); miss.Files[3] = Path.Combine(dir, "nope.wav");
+ int tm = e.AddMosaicTrack();
+ e.MosaicSetProgram(tm, miss.Serialize());
+ WaitReady(e, tm);
+ e.TryGetMosaicStatus(tm, out var sm);
+ yield return (sm.State == 2 && sm.Missing == 1, $"a missing sample is reported (missing {sm.Missing})");
+
+ // Roots resolve references.
+ NotaEngine.SetPathRoot("samples", dir);
+ var rooted = MosaicProgram.Single("samples:pno_g4_f.wav", 67, "Rooted");
+ int tr = e.AddMosaicTrack();
+ e.MosaicSetProgram(tr, rooted.Serialize());
+ bool rr = WaitReady(e, tr);
+ e.TrackNoteOn(tr, 67, 0.8f);
+ var rbuf = Render(e, 4096);
+ yield return (rr && Rms(rbuf) > 0.01, "a samples: reference resolves against the Samples root");
+ e.TrackNoteOff(tr, 67);
+ }
+
+ // ---- loading is asynchronous: silent until ready ------------------------------------
+ {
+ string big = Tone(dir, "big_c4.wav", Hz(60), 30.0);
+ using var e = new NotaEngine();
+ int t = e.AddMosaicTrack();
+ e.MosaicSetProgram(t, MosaicProgram.Single(big, 60, "Big").Serialize());
+ e.TryGetMosaicStatus(t, out var s0);
+ e.TrackNoteOn(t, 60, 0.8f);
+ var early = Render(e, 256);
+ bool loadedLater = WaitReady(e, t);
+ yield return ((s0.State == 1 && Rms(early) < 1e-6 || s0.State == 2) && loadedLater, $"a program is silent while it loads, then ready (first state {s0.State})");
+ }
+
+ // ---- SFZ ---------------------------------------------------------------------------------
+ {
+ string sfzDir = Path.Combine(dir, "sfz");
+ Directory.CreateDirectory(Path.Combine(sfzDir, "Samples"));
+ Directory.CreateDirectory(Path.Combine(sfzDir, "Programs", "map"));
+ Tone(Path.Combine(sfzDir, "Samples"), "c4_soft.wav", Hz(60), 0.3);
+ Tone(Path.Combine(sfzDir, "Samples"), "c4_hard.wav", Hz(60), 0.3);
+ Tone(Path.Combine(sfzDir, "Samples"), "c4_rel.wav", Hz(60), 0.2);
+ Tone(Path.Combine(sfzDir, "Samples"), "sticks.wav", Hz(60), 0.2);
+ Tone(Path.Combine(sfzDir, "Samples"), "brush.wav", Hz(60), 0.2);
+ File.WriteAllText(Path.Combine(sfzDir, "Programs", "map", "keys.sfz"),
+ "<group> seq_length=2 // round robin\n<region> sample=$S\\C4_SOFT.wav key=c4 hivel=63 seq_position=1 eg06_time=1\n"
+ + "<region> sample=$S\\c4_hard.wav key=c4 lovel=64 seq_position=2 amp_velcurve_127=1\n"
+ + "/* release */ <group> trigger=release\n<region> sample=$S\\c4_rel.wav lokey=c4 hikey=c#4 pitch_keycenter=60 volume=-9\n");
+ File.WriteAllText(Path.Combine(sfzDir, "Programs", "main.sfz"),
+ "<control> set_cc110=0 label_cc110=Artic\n#define $S ..\\Samples\n#include \"map/keys.sfz\"\n"
+ + "<group> key=d4 group=1 off_by=2 tune_cc1=50\n<region> sample=$S\\sticks.wav locc110=0 hicc110=63\n<region> sample=$S\\brush.wav locc110=64 hicc110=127\n");
+ var res = SfzImporter.Import(Path.Combine(sfzDir, "Programs", "main.sfz"));
+ var rp = res.Report;
+ yield return (rp.Imported == 4 && rp.Inactive == 1 && rp.Includes == 1 && rp.PathsFixed == 4 && rp.Missing == 0,
+ $"SFZ import: #include, #define, backslashes, case, CC articulation ({rp.Imported} zones, {rp.Inactive} inactive, {rp.Includes} include, {rp.PathsFixed} paths, {rp.Missing} missing)");
+ var zs = res.Program.Zones;
+ yield return (zs.Count == 4 && zs[0].Seq == 1 && zs[1].Seq == 2 && res.Program.Groups[zs[0].Group].SeqLen == 2
+ && zs[2].Release && Math.Abs(zs[2].GainDb + 9) < 1e-6 && zs[2].KeyHi == 61 && zs[3].Root == 62 && zs[3].Excl == 1 && zs[3].OffBy == 2,
+ "SFZ opcodes map to zones (rr, velocity, release, volume, keys, exclusive group)");
+ yield return (rp.Ignored.ContainsKey("eg06*") && rp.Ignored.ContainsKey("tune_cc*") && rp.Ignored.ContainsKey("amp_velcurve*") && rp.CcState.ContainsKey(110),
+ $"SFZ import reports ignored opcode families ({string.Join(", ", rp.Ignored.Keys)})");
+ var brush = SfzImporter.Import(Path.Combine(sfzDir, "Programs", "main.sfz"), new Dictionary<int, int> { [110] = 100 });
+ yield return (brush.Program.Files.Any(f => f.EndsWith("brush.wav")) && !brush.Program.Files.Any(f => f.EndsWith("sticks.wav")),
+ "importing again with CC110 = 100 picks the other articulation");
+ using var e = new NotaEngine();
+ int t = e.AddMosaicTrack();
+ e.MosaicSetProgram(t, res.Program.Serialize());
+ bool ok = WaitReady(e, t);
+ e.TrackNoteOn(t, 60, 0.3f);
+ yield return (ok && Rms(Render(e, 4096)) > 0.01, "an imported SFZ plays");
+ }
+
+ // ---- factory multisamples: rendered once, mapped by their names, playable -----------------
+ {
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == MosaicModel.Kind).ToList();
+ yield return (mine.Count >= 10 && mine.Any(p => p.DisplayName == "Init"), $"Nota Mosaic ships factory presets (got {mine.Count})");
+ foreach (var src in Nota.Infrastructure.Mosaic.MosaicSources.All)
+ {
+ var sw = System.Diagnostics.Stopwatch.StartNew();
+ var fprog = Nota.Infrastructure.Mosaic.MosaicSourceLibrary.Program(src.Id);
+ double ms = sw.Elapsed.TotalMilliseconds;
+ int roots = fprog?.Roots.Count() ?? 0;
+ yield return (fprog is not null && roots == src.Roots.Length && fprog.VelocityLayers == src.Layers.Length
+ && fprog.MaxRoundRobin == Math.Max(1, src.RoundRobin) && fprog.ReleaseZones == (src.Releases ? src.Roots.Length : 0),
+ $"factory multisample '{src.Name}': {fprog?.Summary()} ({ms:0} ms)");
+ }
+ using var e = new NotaEngine();
+ NotaEngine.SetPathRoot("data", NotaPaths.DataDir);
+ foreach (var fp in mine.Where(p => p.DisplayName != "Init"))
+ {
+ int before = e.TrackCount;
+ string w = cat.Apply(e, fp.Id, -1);
+ int t = 0;
+ for (int i = 0; i < e.TrackCount; i++) if (e.TryGetTrackInfo(i, out var ti)) t = ti.Id;
+ bool ok = w.Length == 0 && WaitReady(e, t, 10000);
+ e.TrackNoteOn(t, 60, 0.8f);
+ var b = Render(e, Sr / 2);
+ e.TrackNoteOff(t, 60);
+ Render(e, Sr);
+ double peak = b.Max(Math.Abs);
+ yield return (ok && b.All(float.IsFinite) && Rms(b) > 0.01 && peak < 1.2, $"factory preset '{fp.DisplayName}' plays C4 (rms {Rms(b):F3}, peak {peak:F2}{(w.Length > 0 ? ", " + w : "")})");
+ }
+ }
+
+ // ---- the file-name mapper ------------------------------------------------------------------
+ {
+ var cases = new (string Name, string Stem, int Note, string Layer, int Rr, bool Rel)[]
+ {
+ ("trombone_gb4.wav", "trombone", 66, "", 0, false),
+ ("trombone_f_c3_rr2.wav", "trombone", 48, "f", 2, false),
+ ("trombone_p_n52.wav", "trombone", 52, "p", 0, false),
+ ("trombone_a2_rel.wav", "trombone", 45, "", 0, true),
+ ("bass_16_1_db2.wav", "bass_16_1", 37, "", 0, false),
+ ("all_all_all_f4.wav", "all_all_all", 65, "", 0, false),
+ ("Piano C#3 v2 rr3.wav", "piano", 49, "v2", 3, false),
+ ("Str_cs4_mf.flac", "str", 61, "mf", 0, false),
+ ("trombone_take3.wav", "trombone", -1, "", 0, false),
+ };
+ foreach (var c in cases)
+ {
+ var f = MultisampleMapper.ParseName(c.Name);
+ yield return (f.Stem == c.Stem && f.NamedNote == c.Note && f.Layer == c.Layer && f.Rr == c.Rr && f.Release == c.Rel,
+ $"name '{c.Name}' → {c.Stem} {MosaicNames.NoteName(c.Note)} {c.Layer} rr{c.Rr}{(c.Rel ? " rel" : "")} (got {f.Stem} {MosaicNames.NoteName(f.NamedNote)} {f.Layer} rr{f.Rr}{(f.Release ? " rel" : "")})");
+ }
+
+ string md = Path.Combine(dir, "mapper");
+ Directory.CreateDirectory(md);
+ // Named one octave low (C3 = 60 convention): the files sound an octave above their names.
+ foreach (var (n, midi) in new[] { ("tb_c3_p.wav", 60), ("tb_c3_f.wav", 60), ("tb_e3_p.wav", 64), ("tb_e3_f.wav", 64), ("tb_c4_p.wav", 72), ("tb_c4_f.wav", 72), ("tb_c4_f_copy.wav", 72), ("tb_c3_rel.wav", 60) })
+ Tone(md, n, Hz(midi), 0.5);
+ Tone(md, "tb_take3.wav", Hz(76), 0.5); // no note in the name: pitch analysis
+ double? Detect(string path)
+ {
+ var mono = NotaEngine.DecodeMono(path, 1.0, out double sr);
+ if (mono is null) return null;
+ double hz = AudioPitch.YinHz(mono, mono.Length / 4, 2048, sr);
+ return hz > 0 ? 69 + 12 * Math.Log2(hz / 440.0) : null;
+ }
+ var prop = MultisampleMapper.MapFolder(md, null, Detect);
+ var inst = prop.Instruments.FirstOrDefault(i => i.Stem == "tb");
+ yield return (prop.OctaveShift == 12 && prop.OctaveWhy.Contains("+12"), $"the octave check shifts a C3 = 60 set by +12 ({prop.OctaveShift}: {prop.OctaveWhy})");
+ yield return (inst is not null && inst.Files.Count(f => f.Duplicate) == 1 && inst.Files.Any(f => f.Duplicate && f.Name.Contains("copy")),
+ "a second file for the same note / layer is a duplicate (the copy)");
+ var take = inst?.Files.FirstOrDefault(f => f.Name == "tb_take3.wav");
+ yield return (take is not null && take.NoteFrom == "analysis" && take.Note == 76 && take.Confidence < 80,
+ $"a file without a note gets one from analysis, with low confidence ({take?.NoteText} {take?.Confidence})");
+ yield return (inst is not null && inst.Layers.SequenceEqual(new[] { "p", "f" })
+ && inst.Files.First(f => f.Name == "tb_c3_p.wav").VelHi == 63 && inst.Files.First(f => f.Name == "tb_c3_f.wav").VelLo == 64,
+ "layers split velocity in dynamic order (p 1–63, f 64–127)");
+ if (inst is not null)
+ {
+ var built = MultisampleMapper.Build(inst);
+ yield return (built.Groups.Count == 3 && built.Zones.Count(z => z.Release) == 1 && built.VelocityLayers == 2 && built.Zones.Where(z => !z.Release).All(z => z.KeyLo <= z.Root && z.Root <= z.KeyHi),
+ $"the mapped instrument builds a program ({built.Summary()})");
+ using var e = new NotaEngine();
+ int t = e.AddMosaicTrack();
+ e.MosaicSetProgram(t, built.Serialize());
+ bool ok = WaitReady(e, t);
+ e.TrackNoteOn(t, 74, 0.9f);
+ var b = Render(e, Sr / 4);
+ yield return (ok && Energy(b, Hz(74), 2000) > 10 * Energy(b, Hz(72), 2000), "a mapped program plays the right pitch between roots");
+ }
+ }
+ // ---- project, presets, packs, MCP -----------------------------------------------------------
+ {
+ using var e = new NotaEngine();
+ int t = e.AddMosaicTrack();
+ e.MosaicSetProgram(t, text);
+ P(e, t, "cutoff", 0.3f);
+ WaitReady(e, t);
+ // A project keeps the program (references) and the params; nothing is bundled.
+ string bundle = Path.Combine(dir, "proj.nota");
+ ProjectService.Save(ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), new List<string>()), bundle, e);
+ bool bundled = Directory.Exists(Path.Combine(bundle, "samples")) && Directory.EnumerateFiles(Path.Combine(bundle, "samples")).Any();
+ using var e2 = new NotaEngine();
+ var warns = ProjectService.Apply(ProjectService.Load(bundle), e2, bundle);
+ int t2 = 0;
+ for (int i = 0; i < e2.TrackCount; i++) if (e2.TryGetTrackInfo(i, out var ti) && e2.TrackInstrumentKind(ti.Id) == MosaicModel.Kind) t2 = ti.Id;
+ yield return (t2 > 0 && e2.MosaicProgram(t2) == text && Math.Abs(e2.PluginParamGet(t2, -1, Pi(e2, t2, "cutoff")) - 0.3f) < 1e-5 && WaitReady(e2, t2) && !bundled,
+ $"a project reopens its Mosaic: program, params, samples referenced not copied ({string.Join("; ", warns)})");
+
+ // A user preset carries the program; applying it in place loads both.
+ var doc = PresetService.Capture(e, t, -1, "Mine");
+ int t3 = e.AddMosaicTrack();
+ string w = doc is null ? "no doc" : PresetService.ApplyInPlace(doc, e, t3, -1);
+ yield return (doc?.MosaicProgram == text && w.Length == 0 && e.MosaicProgram(t3) == text && Math.Abs(e.PluginParamGet(t3, -1, Pi(e, t3, "cutoff")) - 0.3f) < 1e-5,
+ "a saved Mosaic preset carries its program and loads it in place");
+
+ // Packs → presets: an SFZ pack and a pack of named files.
+ string root = Path.Combine(dir, "presets");
+ var lib = new Nota.Infrastructure.Mosaic.MosaicPackLibrary(root);
+ int nSfz = lib.ScanPack(Path.Combine(dir, "sfz"), "test-sfz", "1");
+ int nNamed = lib.ScanPack(Path.Combine(dir, "mapper"), "test-named", "1");
+ int again = lib.ScanPack(Path.Combine(dir, "sfz"), "test-sfz", "1");
+ var list = lib.Presets();
+ yield return (nSfz == 1 && nNamed == 1 && again == 0 && list.Count == 2 && list.Any(p => p.Source == "sfz") && list.Any(p => p.Source == "folder"),
+ $"installed packs become Mosaic presets once per version ({nSfz} sfz, {nNamed} named, rescan {again}; {string.Join(", ", list.Select(p => p.Folder + "/" + p.Name))})");
+ var packProg = lib.Read(list.First(p => p.Source == "sfz").Path);
+ yield return (packProg is not null && packProg.PackId == "test-sfz" && packProg.Zones.Count == 4, "a pack preset names its pack and holds the imported zones");
+ int t4 = e.AddMosaicTrack();
+ string w4 = lib.ApplyInPlace(e, list.First(p => p.Source == "folder").Path, t4);
+ yield return (w4.Length == 0 && WaitReady(e, t4) && MosaicProgram.Parse(e.MosaicProgram(t4)).Zones.Count > 0, "a pack preset loads into a Mosaic");
+
+ // MCP.
+ var mcp = new Nota.Mcp.Tools.MosaicTools(e, new SyncDispatch(), new NoRefresh(), lib, new FactoryPresetCatalog());
+ var inst = new Nota.Mcp.Tools.InstrumentTools(e, new SyncDispatch(), new NoRefresh());
+ yield return (inst.ListInstrumentKinds().Any(k => k.Kind == 17 && k.Name == "Nota Mosaic") && inst.AddInstrumentTrack(17).Result is var mt && e.TrackInstrumentKind(mt) == 17,
+ "MCP add_instrument_track(17) adds a Nota Mosaic");
+ var r = mcp.ReadMosaic(t, includeZones: true).Result;
+ yield return (r is not null && r.Zones == 7 && r.Groups.Length == 3 && r.ZoneList?.Length == 7 && r.Loading == "ready" && r.VoiceLimit == 64,
+ $"read_mosaic reads the program ({r?.Summary})");
+ string s1 = mcp.SetMosaic(t, polyphony: 32, perKey: 3, releaseVolumeDb: -12, velocityCurve: -40, filter: "LP", cutoffHz: 2000).Result;
+ yield return (!s1.StartsWith("error") && MosaicModel.Poly(e.PluginParamGet(t, -1, Pi(e, t, "polyphony"))) == 32
+ && MosaicModel.PerKey(e.PluginParamGet(t, -1, Pi(e, t, "perkey"))) == 3 && Math.Abs(MosaicModel.RelVolDb(e.PluginParamGet(t, -1, Pi(e, t, "relvol"))) + 12) < 0.1
+ && MosaicModel.VelCurve(e.PluginParamGet(t, -1, Pi(e, t, "velcurve"))) == -40 && Math.Abs(MosaicModel.CutoffHz(e.PluginParamGet(t, -1, Pi(e, t, "cutoff"))) - 2000) < 5,
+ $"set_mosaic sets polyphony, per key, release level, velocity curve and filter ({s1})");
+ string s2 = mcp.SetMosaicZone(t, 0, root: "C#4", velHi: 50, gainDb: -3).Result;
+ var z0 = MosaicProgram.Parse(e.MosaicProgram(t)).Zones[0];
+ yield return (z0.Root == 61 && z0.VelHi == 50 && Math.Abs(z0.GainDb + 3) < 1e-6, $"set_mosaic_zone edits a zone ({s2})");
+ string s3 = mcp.SetMosaicGroup(t, 1, roundRobinMode: "Random", gainDb: 2).Result;
+ var g1 = MosaicProgram.Parse(e.MosaicProgram(t)).Groups[1];
+ yield return (g1.RrMode == 1 && Math.Abs(g1.GainDb - 2) < 1e-6, $"set_mosaic_group edits a group ({s3})");
+ var imp = mcp.ImportSfz(Path.Combine(dir, "sfz", "Programs", "main.sfz"), -1, "110=100").Result;
+ yield return (imp.TrackId > 0 && imp.Imported == 4 && e.MosaicProgram(imp.TrackId).Contains("brush.wav"), $"import_sfz loads an SFZ with an articulation ({imp.Summary})");
+ var dry = mcp.CreateMultisample(Path.Combine(dir, "mapper"), dryRun: true).Result;
+ yield return (dry.Instruments.Length == 1 && dry.OctaveShift == 12 && dry.TrackId < 0, $"create_multisample previews ({dry.OctaveVerdict})");
+ var made = mcp.CreateMultisample(Path.Combine(dir, "mapper"), dryRun: false, savePresets: true).Result;
+ yield return (made.TrackId > 0 && made.Presets.Length == 1 && WaitReady(e, made.TrackId), "create_multisample loads the instrument and saves its preset");
+ var presets = mcp.ListMosaicPresets().Result;
+ yield return (presets.Any(p => p.Kind == "factory" && p.Name == "Felt Piano") && presets.Any(p => p.Kind == "sfz"), $"list_mosaic_presets lists factory and pack presets ({presets.Length})");
+ int lt = mcp.LoadMosaicPreset("Glass Mallets").Result;
+ yield return (lt > 0 && WaitReady(e, lt, 10000) && mcp.LoadMosaicPreset("No Such Thing").Result == -1, "load_mosaic_preset loads by name (and refuses an unknown one)");
+ }
+
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 780e142e..b5086757 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -207,6 +207,41 @@ if (args.Length >= 1 && args[0] == "--tap")
Console.WriteLine(failures == 0 ? "TAP PASSED" : $"TAP FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// What Nota Mosaic makes of a real library: `--mosaic-dump <file.sfz | folder>`.
+if (args.Length >= 2 && args[0] == "--mosaic-dump")
+{
+ if (args[1].EndsWith(".sfz", StringComparison.OrdinalIgnoreCase))
+ {
+ var r = Nota.Application.Mosaic.SfzImporter.Import(args[1]);
+ var rp = r.Report;
+ Console.WriteLine($"{rp.File}: {rp.Summary()} · {rp.Regions} regions, {rp.Groups} groups, {rp.Includes} #include, {rp.PathsFixed} paths fixed, {rp.Missing} missing, {rp.Inactive} inactive, {rp.Generators} generators, {rp.Seconds:0.00} s");
+ Console.WriteLine($" CC: {string.Join(", ", rp.CcState.Select(kv => $"cc{kv.Key}={kv.Value}" + (rp.CcLabels.TryGetValue(kv.Key, out var l) ? $" ({l})" : "")))}");
+ Console.WriteLine($" ignored: {string.Join(", ", rp.Ignored.Select(kv => $"{kv.Key} {kv.Value}"))}");
+ Console.WriteLine($" {r.Program.Summary()} · {r.Program.Files.Count} files");
+ }
+ else
+ {
+ var prop = Nota.Application.Mosaic.MultisampleMapper.MapFolder(args[1], null, path =>
+ {
+ var mono = NotaEngine.DecodeMono(path, 1.0, out double sr);
+ if (mono is null || mono.Length < 8192) return null;
+ double hz = AudioPitch.YinHz(mono, mono.Length / 4, 2048, sr);
+ return hz > 0 ? 69 + 12 * Math.Log2(hz / 440.0) : null;
+ });
+ Console.WriteLine($"{prop.Instruments.Count} instruments · octave {prop.OctaveShift:+0;-0;0} ({prop.OctaveWhy}) · {prop.Unmapped} unmapped");
+ foreach (var i in prop.Instruments)
+ Console.WriteLine($" {i.Stem,-24} {i.Files.Count,3} files · {i.Roots} roots · layers [{string.Join(" ", i.Layers)}] · rr {i.MaxRr} · conf {i.Confidence} · gaps {i.Gaps.Count}");
+ }
+ return 0;
+}
+// Nota Mosaic alone (fast iteration): `--mosaic`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--mosaic")
+{
+ Console.WriteLine("-- nota mosaic --");
+ foreach (var (ok, label) in MosaicTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "MOSAIC PASSED" : $"MOSAIC FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Nota Keys alone (fast iteration): `--keys`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--keys")
{
@@ -14227,6 +14262,8 @@ Console.WriteLine("-- mpe: per-note expression --");
foreach (var (ok, label) in MpeTests.Run()) Check(ok, label);
Console.WriteLine("-- nota keys --");
foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);
+Console.WriteLine("-- nota mosaic --");
+foreach (var (ok, label) in MosaicTests.Run()) Check(ok, label);
Console.WriteLine("-- tap tempo --");
foreach (var (ok, label) in TapTempoTests.Run()) Check(ok, label);