Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Smart samples: tempo, key and loop analysis, and the sample library index
Egor Khindikaynen01b521b4f01e
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.csindex c34ce176..b495e4f5 100644--- a/src/managed/Nota.App/App.axaml.cs+++ b/src/managed/Nota.App/App.axaml.cs@@ -39,6 +39,8 @@ public partial class App : Avalonia.Applicationservices.AddSingleton<IPluginCatalog, PluginCatalog>();services.AddSingleton<IPluginStore, PluginStore>();services.AddSingleton<ISampleStore, SampleStore>();+ services.AddSingleton<ISampleAnalyzer, SampleAnalyzer>();+ services.AddSingleton<ISampleIndex, SampleLibraryIndex>();services.AddSingleton<IModelStore>(_ => new ModelStore());services.AddSingleton<IClipAi, ClipAi>();services.AddSingleton<IPresetLibrary, PresetLibrary>();diff --git a/src/managed/Nota.Application/Engine/IAudioImport.cs b/src/managed/Nota.Application/Engine/IAudioImport.csindex 6829d575..c0a6a712 100644--- a/src/managed/Nota.Application/Engine/IAudioImport.cs+++ b/src/managed/Nota.Application/Engine/IAudioImport.cs@@ -31,4 +31,7 @@ public interface IAudioImport : IDisposable/// <summary>Tempo of the whole file once done (0 = not detectable).</summary>double DetectTempo();++ /// <summary>Tempo, key, envelope and timbre of the whole file once done (null on failure).</summary>+ Nota.Application.Samples.SampleAnalysis? Analyze();}diff --git a/src/managed/Nota.Application/Ports/ISampleIndex.cs b/src/managed/Nota.Application/Ports/ISampleIndex.csnew file mode 100644index 00000000..a4cbb36c--- /dev/null+++ b/src/managed/Nota.Application/Ports/ISampleIndex.cs@@ -0,0 +1,56 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using Nota.Application.Samples;++namespace Nota.Application;++/// <summary>Decodes and measures a sample file (tempo, key, envelope, timbre). Thread-safe;+/// slow (it decodes) — call it off the UI thread.</summary>+public interface ISampleAnalyzer+{+ /// <summary>Analyses the file's first <paramref name="maxSeconds"/>. Null when it can't be decoded.</summary>+ SampleAnalysis? Analyze(string path, double maxSeconds);+}++/// <summary>A sample found by <see cref="ISampleIndex.Similar"/>; smaller distance = closer.</summary>+public readonly record struct SimilarSample(SampleInfo Info, double Distance);++/// <summary>The sample library's analysis index: every audio file in the Samples folder,+/// analysed once in the background and remembered across launches (keyed by path, refreshed+/// when a file's size or date changes). Feeds the Files tab's tags, filters and "similar+/// sounds", and tells a dropped loop its tempo without re-measuring it.</summary>+public interface ISampleIndex+{+ /// <summary>What the index knows about <paramref name="path"/> (no disk access), or null+ /// when it hasn't been analysed yet.</summary>+ SampleInfo? Get(string path);++ /// <summary>Like <see cref="Get"/>, but checks the file is unchanged and analyses it now if+ /// not (decodes — worker thread). Null when it can't be decoded.</summary>+ SampleInfo? GetOrAnalyze(string path);++ /// <summary>Records an analysis made elsewhere (the import path already decoded the file).</summary>+ SampleInfo Store(string path, SampleAnalysis analysis);++ /// <summary>Indexes everything under <paramref name="root"/> in the background (replaces+ /// any running scan). Files the index already knows are skipped.</summary>+ void Watch(string root);++ /// <summary>Moves <paramref name="folder"/> to the front of the queue — a pack just installed.</summary>+ void Prioritize(string folder);++ /// <summary>Files analysed and found so far in the current scan; Total 0 when idle.</summary>+ (int Done, int Total) Progress { get; }++ /// <summary>Raised (throttled, on a worker thread) as analyses land and when a scan ends.</summary>+ event Action? Changed;++ /// <summary>The <paramref name="count"/> analysed samples that sound most like+ /// <paramref name="path"/> (itself excluded), closest first.</summary>+ IReadOnlyList<SimilarSample> Similar(string path, int count);++ /// <summary>Analysed samples passing <paramref name="filter"/> whose path contains every+ /// word of <paramref name="text"/>, up to <paramref name="limit"/>, by path.</summary>+ IReadOnlyList<SampleInfo> Search(SampleFilter filter, string? text, int limit);+}diff --git a/src/managed/Nota.Application/Samples/MusicalKey.cs b/src/managed/Nota.Application/Samples/MusicalKey.csnew file mode 100644index 00000000..e6bbfff4--- /dev/null+++ b/src/managed/Nota.Application/Samples/MusicalKey.cs@@ -0,0 +1,104 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Text.RegularExpressions;++namespace Nota.Application.Samples;++/// <summary>Major, minor, or a pitch whose mode can't be told (a single note, an 808).</summary>+public enum KeyMode : byte { Major, Minor, Note }++/// <summary>A musical key (tonic 0..11 = C..B plus a mode) — what the Files tab filters on+/// and what the project key is. <see cref="KeyMode.Note"/> is a tonal one-shot: it has a+/// pitch but no scale.</summary>+public readonly record struct MusicalKey(int Tonic, KeyMode Mode)+{+ // Spelled the way sample packs and chord charts usually spell them.+ private static readonly string[] MajorNames = { "C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B" };+ private static readonly string[] MinorNames = { "C", "C#", "D", "Eb", "E", "F", "F#", "G", "G#", "A", "Bb", "B" };++ /// <summary>The 24 keys in picker order: C major, C minor, Db major, C# minor, …</summary>+ public static IReadOnlyList<MusicalKey> All { get; } =+ Enumerable.Range(0, 12).SelectMany(t => new[] { new MusicalKey(t, KeyMode.Major), new MusicalKey(t, KeyMode.Minor) }).ToArray();++ public string TonicName => (Mode == KeyMode.Minor ? MinorNames : MajorNames)[Mod12(Tonic)];++ /// <summary>"Am", "F#", "Eb" (a note reads like its major key: the letter alone).</summary>+ public string Short => Mode == KeyMode.Minor ? TonicName + "m" : TonicName;++ /// <summary>"A minor", "Eb major", "F#".</summary>+ public string Long => Mode switch+ {+ KeyMode.Major => TonicName + " major",+ KeyMode.Minor => TonicName + " minor",+ _ => TonicName,+ };++ public override string ToString() => Short;++ /// <summary>The relative key — same notes, other tonic (A minor ↔ C major). A note has none.</summary>+ public MusicalKey? Relative => Mode switch+ {+ KeyMode.Major => new MusicalKey(Mod12(Tonic + 9), KeyMode.Minor),+ KeyMode.Minor => new MusicalKey(Mod12(Tonic + 3), KeyMode.Major),+ _ => null,+ };++ /// <summary>Whether a sample in this key sits in <paramref name="target"/> as is: the same+ /// key, its relative, or a note that is the target's tonic.</summary>+ public bool FitsIn(MusicalKey target)+ {+ if (Mode == KeyMode.Note || target.Mode == KeyMode.Note) return Mod12(Tonic) == Mod12(target.Tonic);+ return this == target || Relative == target;+ }++ /// <summary>Semitones (−6..+5, the shorter way) that move this key onto <paramref name="target"/>.+ /// Across modes the relative is used, so A minor → C major is 0 (same notes, nothing to move)+ /// and A minor → D major is +2 (A minor's notes become B minor's, D major's relative).</summary>+ public int SemitonesTo(MusicalKey target)+ {+ int from = Mod12(Tonic), to = Mod12(target.Tonic);+ if (Mode != KeyMode.Note && target.Mode != KeyMode.Note && Mode != target.Mode)+ to = Mod12(target.Relative!.Value.Tonic);+ int d = Mod12(to - from);+ return d > 5 ? d - 12 : d;+ }++ /// <summary>Compact persistence code: 0..11 major, 12..23 minor, 24..35 note.</summary>+ public int Code => (int)Mode * 12 + Mod12(Tonic);++ public static MusicalKey? FromCode(int code)+ => code is >= 0 and < 36 ? new MusicalKey(code % 12, (KeyMode)(code / 12)) : null;++ private static readonly Regex KeyText = new(+ @"^\s*([A-Ga-g])\s*([#♯b♭]|sharp|flat)?\s*(major|maj|minor|min|m)?\s*$",+ RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);++ /// <summary>Parses "Am", "A minor", "F#", "Eb maj", "Bbmin", "c#m". A bare letter is a+ /// major key. Null for anything else.</summary>+ public static MusicalKey? Parse(string? text)+ {+ if (string.IsNullOrWhiteSpace(text)) return null;+ var m = KeyText.Match(text);+ if (!m.Success) return null;+ int tonic = TonicOf(m.Groups[1].Value, m.Groups[2].Value);+ // "M" alone is ambiguous in the wild ("CM" = C major to some, a typo to most); only the+ // lowercase m and the spelled-out words say minor.+ string mode = m.Groups[3].Value;+ bool minor = mode == "m" || mode.StartsWith("min", StringComparison.OrdinalIgnoreCase);+ return new MusicalKey(tonic, minor ? KeyMode.Minor : KeyMode.Major);+ }++ internal static int TonicOf(string letter, string accidental)+ {+ int t = char.ToUpperInvariant(letter[0]) switch+ {+ 'C' => 0, 'D' => 2, 'E' => 4, 'F' => 5, 'G' => 7, 'A' => 9, _ => 11,+ };+ if (accidental is "#" or "♯" || accidental.Equals("sharp", StringComparison.OrdinalIgnoreCase)) t++;+ else if (accidental is "b" or "♭" || accidental.Equals("flat", StringComparison.OrdinalIgnoreCase)) t--;+ return Mod12(t);+ }++ private static int Mod12(int v) => ((v % 12) + 12) % 12;+}diff --git a/src/managed/Nota.Application/Samples/SampleClassifier.cs b/src/managed/Nota.Application/Samples/SampleClassifier.csnew file mode 100644index 00000000..eeb7bf03--- /dev/null+++ b/src/managed/Nota.Application/Samples/SampleClassifier.cs@@ -0,0 +1,118 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application.Samples;++/// <summary>Turns a sample's name hints and measured analysis into a <see cref="SampleInfo"/>.+/// Names are trusted over the ear: an author who wrote "124" meant 124. The analysis fills+/// the gaps and settles a loop's exact tempo from its length — a loop is a whole number of+/// beats, so "16 beats in 7.742 s" is 124.0 BPM even when the onset tracker heard 123.5.</summary>+public static class SampleClassifier+{+ public const double OneShotMaxSec = 1.2; // shorter than this is a hit, whatever it is called+ private const double DecayedTail = 0.12; // last-tenth RMS under this share: it rang out+ private const double DecayedMaxSec = 6.0; // …and a decaying sound longer than this is a texture, not a hit+ private const double FitTolerance = 0.04; // length-derived tempo within 4 % of the heard one+ private const double KeyMinConfidence = 0.55;+ private const double TempoForLongMinSec = 8.0; // a non-loop needs a few bars before its tempo means much+ private const double ShortMaxSec = 2.5; // shorter, with no loop length: a hit, a vowel, a phrase++ // Loop lengths in beats: whole bars of 4/4 first, then the odd ones (3/4, half bars).+ private static readonly int[] LoopBeats = { 4, 8, 16, 32, 64, 2, 12, 24, 48, 3, 6 };++ public static SampleInfo Classify(string path, SampleNameHints hints, SampleAnalysis? a)+ {+ double dur = a?.DurationSec ?? 0;+ float[] timbre = a?.Timbre ?? Array.Empty<float>();++ // --- loop or one-shot -------------------------------------------------------------+ var kind = SampleKind.Unknown;+ var kindSrc = SampleFactSource.None;+ if (hints.NameKind != SampleKind.Unknown) { kind = hints.NameKind; kindSrc = SampleFactSource.Name; }+ else if (hints.FolderKind != SampleKind.Unknown) { kind = hints.FolderKind; kindSrc = SampleFactSource.Folder; }+ // Too short to loop is decisive, whatever a folder said.+ if (a is not null && dur > 0 && dur < OneShotMaxSec && kindSrc != SampleFactSource.Name)+ { kind = SampleKind.OneShot; kindSrc = SampleFactSource.Duration; }++ // --- tempo ------------------------------------------------------------------------+ double bpm = 0;+ var bpmSrc = SampleFactSource.None;+ double fit = a is not null && kind != SampleKind.OneShot ? LoopFit(dur, a.Bpm) : 0;+ if (hints.Bpm > 0 && (hints.BpmExplicit || kind == SampleKind.Loop || Agrees(hints.Bpm, fit, a?.Bpm ?? 0, dur)))+ {+ bpm = hints.Bpm; bpmSrc = SampleFactSource.Name;+ if (kind == SampleKind.Unknown && dur >= OneShotMaxSec) { kind = SampleKind.Loop; kindSrc = SampleFactSource.Name; }+ }+ else if (fit > 0 && kind != SampleKind.OneShot)+ {+ bpm = fit; bpmSrc = SampleFactSource.Duration;+ if (kind == SampleKind.Unknown && !(a!.TailRatio < DecayedTail && dur < DecayedMaxSec))+ { kind = SampleKind.Loop; kindSrc = SampleFactSource.Duration; }+ }+ else if (a is not null && a.Bpm > 0 && kind != SampleKind.OneShot && (kind == SampleKind.Loop || dur >= TempoForLongMinSec))+ {+ bpm = a.Bpm; bpmSrc = SampleFactSource.Audio;+ }++ if (kind == SampleKind.Unknown && a is not null)+ {+ // Rang out to silence, or named like a drum hit and short: a one-shot.+ if (a.TailRatio < DecayedTail && dur < DecayedMaxSec) { kind = SampleKind.OneShot; kindSrc = SampleFactSource.Audio; }+ else if (hints.DrumWord && dur < ShortMaxSec) { kind = SampleKind.OneShot; kindSrc = SampleFactSource.Name; }+ else if (dur < ShortMaxSec && bpm == 0) { kind = SampleKind.OneShot; kindSrc = SampleFactSource.Duration; }+ }+ if (kind == SampleKind.OneShot && bpmSrc != SampleFactSource.Name) { bpm = 0; bpmSrc = SampleFactSource.None; }++ // --- key --------------------------------------------------------------------------+ MusicalKey? key = null;+ var keySrc = SampleFactSource.None;+ if (hints.Key is { } nk) { key = nk; keySrc = SampleFactSource.Name; }+ else if (a is not null && a.KeyTonic is >= 0 and < 12 && a.KeyConfidence >= KeyMinConfidence)+ {+ // A hit has a pitch, not a scale: its "mode" is a coin toss between two profiles.+ var mode = kind == SampleKind.OneShot || a.KeyMode < 0 ? KeyMode.Note : (KeyMode)a.KeyMode;+ key = new MusicalKey(a.KeyTonic, mode);+ keySrc = SampleFactSource.Audio;+ }++ return new SampleInfo(path, dur, kind, kindSrc, Math.Round(bpm, 2), bpmSrc, key, keySrc, timbre);+ }++ /// <summary>The exact tempo of a loop <paramref name="durationSec"/> long whose pulse was+ /// heard at <paramref name="heardBpm"/>: the whole-beat count closest to it (the heard tempo+ /// may be off by an octave), or 0 when no musical loop length is within tolerance.</summary>+ public static double LoopFit(double durationSec, double heardBpm)+ {+ if (durationSec < OneShotMaxSec || heardBpm <= 0) return 0;+ double best = 0, bestErr = double.MaxValue;+ for (int i = 0; i < LoopBeats.Length; i++)+ {+ double bpm = LoopBeats[i] * 60.0 / durationSec;+ if (bpm is < 60 or > 200) continue;+ double err = double.MaxValue;+ foreach (double oct in new[] { 1.0, 2.0, 0.5 })+ err = Math.Min(err, Math.Abs(bpm - heardBpm * oct) / (heardBpm * oct) + (oct == 1.0 ? 0 : 0.005));+ err += i >= 5 ? 0.008 : 0; // prefer whole 4/4 bars on a near tie…+ err += bpm is < 75 or > 170 ? 0.015 : 0; // …and the tempos loops are usually made at+ if (err < bestErr) { bestErr = err; best = bpm; }+ }+ if (bestErr > FitTolerance) return 0;+ // A file a few samples long or short of the grid still means a round tempo.+ double round = Math.Round(best);+ return Math.Abs(best - round) < 0.06 ? round : best;+ }++ // A bare number in a name is a tempo when the audio agrees: the loop-length fit or the+ // heard pulse lands within tolerance of it (or an octave of it).+ private static bool Agrees(double named, double fit, double heard, double dur)+ {+ if (fit > 0 && Math.Abs(fit - named) / named < FitTolerance) return true;+ if (heard > 0)+ foreach (double oct in new[] { 1.0, 2.0, 0.5 })+ if (Math.Abs(heard * oct - named) / named < FitTolerance) return true;+ // Or the file is a loop length of the named tempo's beats, to a few milliseconds.+ if (dur < OneShotMaxSec) return false;+ double beats = dur * named / 60.0;+ return Math.Abs(beats - Math.Round(beats)) < 0.02 && Array.IndexOf(LoopBeats, (int)Math.Round(beats)) >= 0;+ }+}diff --git a/src/managed/Nota.Application/Samples/SampleFilter.cs b/src/managed/Nota.Application/Samples/SampleFilter.csnew file mode 100644index 00000000..74a847b8--- /dev/null+++ b/src/managed/Nota.Application/Samples/SampleFilter.cs@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application.Samples;++/// <summary>The Files tab's sample filter — "loops · 120–128 · A minor". Every part is+/// optional; a sample the index hasn't analysed yet passes only the empty filter.</summary>+public sealed record SampleFilter(SampleKind Kind = SampleKind.Unknown, double BpmMin = 0, double BpmMax = 0, MusicalKey? Key = null)+{+ public static readonly SampleFilter Empty = new();++ public bool IsEmpty => Kind == SampleKind.Unknown && !HasBpm && Key is null;+ public bool HasBpm => BpmMin > 0 || BpmMax > 0;++ public bool Matches(SampleInfo? s)+ {+ if (IsEmpty) return true;+ if (s is null) return false;+ if (Kind != SampleKind.Unknown && s.Kind != Kind) return false;+ if (HasBpm)+ {+ if (s.Bpm <= 0) return false;+ // Ranges are inclusive of what the row shows: 127.96 reads "128" and passes 120–128.+ double b = Math.Round(s.Bpm, 1);+ if (BpmMin > 0 && b < BpmMin - 0.05) return false;+ if (BpmMax > 0 && b > BpmMax + 0.05) return false;+ }+ // A key matches itself and its relative (A minor shows C major loops — same notes).+ if (Key is { } k && (s.Key is not { } sk || !sk.FitsIn(k))) return false;+ return true;+ }++ /// <summary>"120–128", "≥ 120", "≤ 90", "" — the BPM chip's caption.</summary>+ public string BpmCaption => (BpmMin > 0, BpmMax > 0) switch+ {+ (true, true) when Math.Abs(BpmMin - BpmMax) < 0.05 => SampleInfo.FormatBpm(BpmMin),+ (true, true) => $"{SampleInfo.FormatBpm(BpmMin)}–{SampleInfo.FormatBpm(BpmMax)}",+ (true, false) => $"≥ {SampleInfo.FormatBpm(BpmMin)}",+ (false, true) => $"≤ {SampleInfo.FormatBpm(BpmMax)}",+ _ => "",+ };+}diff --git a/src/managed/Nota.Application/Samples/SampleInfo.cs b/src/managed/Nota.Application/Samples/SampleInfo.csnew file mode 100644index 00000000..36af2d31--- /dev/null+++ b/src/managed/Nota.Application/Samples/SampleInfo.cs@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application.Samples;++public enum SampleKind : byte { Unknown, Loop, OneShot }++/// <summary>Where a fact about a sample came from — a name the pack's author wrote is+/// trusted over what the analysis heard.</summary>+public enum SampleFactSource : byte { None, Name, Folder, Duration, Audio }++/// <summary>What the engine measured in a sample (<c>NotaSampleAnalysis</c>). Raw: the+/// <see cref="SampleClassifier"/> turns it, with the file's name, into a <see cref="SampleInfo"/>.</summary>+public sealed record SampleAnalysis(+ double DurationSec,+ double SampleRate,+ int Channels,+ double Bpm, // 0 = no steady pulse+ int KeyTonic, // -1 = atonal+ int KeyMode, // 0 major, 1 minor, -1 tonic only+ float KeyConfidence,+ float TailRatio, // last-tenth RMS / whole RMS+ float PeakDb,+ float RmsDb,+ float[] Timbre)+{+ public const int TimbreDims = 16;++ /// <summary>Bumped when the engine's analysis changes enough that stored results should be redone.</summary>+ public const int Version = 1;+}++/// <summary>The browser's view of one sample: loop or one-shot, tempo, key, and the+/// timbre fingerprint "similar sounds" compares.</summary>+public sealed record SampleInfo(+ string Path,+ double DurationSec,+ SampleKind Kind,+ SampleFactSource KindSource,+ double Bpm, // 0 = none+ SampleFactSource BpmSource,+ MusicalKey? Key,+ SampleFactSource KeySource,+ float[] Timbre)+{+ /// <summary>Beats the sample spans at its own tempo (0 without one).</summary>+ public double Beats => Bpm > 0 ? DurationSec * Bpm / 60.0 : 0;++ /// <summary>The row tag: "124 · Am", "93.5", "F#", "" — tempo first, it is what loops are picked by.</summary>+ public string Tag+ {+ get+ {+ var parts = new List<string>(2);+ if (Bpm > 0) parts.Add(FormatBpm(Bpm));+ if (Key is { } k) parts.Add(k.Short);+ return string.Join(" · ", parts);+ }+ }++ /// <summary>"124 BPM · A minor · loop · 7.7 s" (thin spaces before units) for the row's tooltip.</summary>+ public string Describe()+ {+ var parts = new List<string>(4);+ if (Bpm > 0) parts.Add(FormatBpm(Bpm) + "\u2009BPM");+ if (Key is { } k) parts.Add(k.Long);+ if (Kind != SampleKind.Unknown) parts.Add(Kind == SampleKind.Loop ? "loop" : "one-shot");+ if (DurationSec > 0) parts.Add(DurationSec.ToString(DurationSec < 10 ? "0.0" : "0", System.Globalization.CultureInfo.InvariantCulture) + "\u2009s");+ return string.Join(" · ", parts);+ }++ public static string FormatBpm(double bpm)+ {+ double r = Math.Round(bpm, 1);+ return r.ToString(Math.Abs(r - Math.Round(r)) < 0.05 ? "0" : "0.0", System.Globalization.CultureInfo.InvariantCulture);+ }+}diff --git a/src/managed/Nota.Application/Samples/SampleNameHints.cs b/src/managed/Nota.Application/Samples/SampleNameHints.csnew file mode 100644index 00000000..8dc38b05--- /dev/null+++ b/src/managed/Nota.Application/Samples/SampleNameHints.cs@@ -0,0 +1,152 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Globalization;+using System.Text.RegularExpressions;++namespace Nota.Application.Samples;++/// <summary>What a sample's file name and folders say about it. Pack authors usually write+/// the tempo and key into the name ("DH_Loop_124_Am.wav", "Pad C#m 90bpm") and sort loops+/// from one-shots by folder — facts the analysis can only estimate.</summary>+public sealed record SampleNameHints(+ double Bpm, // 0 = none+ bool BpmExplicit, // written with "bpm"; a bare number is only a candidate+ MusicalKey? Key,+ SampleKind NameKind, // from the file name+ SampleKind FolderKind, // from the folders between the library root and the file+ bool DrumWord) // kick / snare / hat … — a weak one-shot hint+{+ public static readonly SampleNameHints None = new(0, false, null, SampleKind.Unknown, SampleKind.Unknown, false);++ private static readonly Regex BpmBefore = new(@"(?<![\d.])(\d{2,3}(?:\.\d{1,2})?)\s*-?\s*bpm(?![a-z])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);+ private static readonly Regex BpmAfter = new(@"(?<![a-z])bpm\s*[-_ ]?\s*(\d{2,3}(?:\.\d{1,2})?)(?![\d])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);+ private static readonly Regex Separators = new(@"[\s_\-.,()\[\]{}+&=~]+", RegexOptions.CultureInvariant);++ // A key token. Group 1 letter, 2 accidental, 3 mode word, 4 trailing chord extension / octave.+ private static readonly Regex KeyToken = new(+ @"^([A-Ga-g])(#|♯|♭|b|sharp|flat)?(major|maj|minor|min|m)?(\d{0,2})$", RegexOptions.CultureInvariant);++ private static readonly HashSet<string> LoopWords = new(StringComparer.OrdinalIgnoreCase) { "loop", "loops", "looped", "groove", "grooves" };+ private static readonly HashSet<string> ShotWords = new(StringComparer.OrdinalIgnoreCase) { "oneshot", "oneshots", "shot", "shots", "hit", "hits", "stab", "stabs" };+ private static readonly HashSet<string> DrumWords = new(StringComparer.OrdinalIgnoreCase)+ {+ "kick", "kicks", "bd", "snare", "snares", "sd", "clap", "claps", "hat", "hats", "hihat", "hihats", "hh",+ "perc", "percs", "rim", "rimshot", "tom", "toms", "cymbal", "cymbals", "crash", "ride", "shaker", "snap", "snaps",+ };++ /// <summary>Reads the hints for <paramref name="path"/>. <paramref name="root"/> (the+ /// library folder) bounds which folders count; null = only the file's own folder.</summary>+ public static SampleNameHints Parse(string path, string? root = null)+ {+ string name = Path.GetFileNameWithoutExtension(path);+ var tokens = Tokens(name);++ double bpm = 0; bool bpmExplicit = false;+ var bm = BpmBefore.Match(name);+ if (!bm.Success) bm = BpmAfter.Match(name);+ if (bm.Success && double.TryParse(bm.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var b) && b is >= 40 and <= 250)+ { bpm = b; bpmExplicit = true; }+ int bpmToken = -1;+ if (bpm == 0)+ {+ // A bare number in tempo range is a candidate; the classifier checks it against the audio.+ for (int i = tokens.Count - 1; i >= 0; i--)+ if (tokens[i].Length is 2 or 3 && int.TryParse(tokens[i], NumberStyles.None, CultureInfo.InvariantCulture, out int n) && n is >= 60 and <= 200)+ { bpm = n; bpmToken = i; break; }+ }+ else+ {+ for (int i = 0; i < tokens.Count; i++)+ if (tokens[i].Contains("bpm", StringComparison.OrdinalIgnoreCase) || (i + 1 < tokens.Count && tokens[i + 1].Equals("bpm", StringComparison.OrdinalIgnoreCase)))+ { bpmToken = i; break; }+ }++ var key = KeyOf(tokens, bpmToken, bpm > 0);+ var nameKind = KindOf(tokens, out bool drum);++ var folderKind = SampleKind.Unknown;+ foreach (var seg in Folders(path, root))+ {+ var k = KindOf(Tokens(seg), out bool d);+ drum |= d;+ if (k != SampleKind.Unknown) folderKind = k; // the innermost folder that says wins+ }+ return new SampleNameHints(bpm, bpmExplicit, key, nameKind, folderKind, drum);+ }++ private static List<string> Tokens(string s)+ => Separators.Split(s).Where(t => t.Length > 0).ToList();++ private static IEnumerable<string> Folders(string path, string? root)+ {+ var dir = Path.GetDirectoryName(path);+ if (string.IsNullOrEmpty(dir)) yield break;+ if (root is null) { yield return Path.GetFileName(dir); yield break; }+ var rel = Path.GetRelativePath(root, dir);+ if (rel == "." || rel.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(rel))+ { yield return Path.GetFileName(dir); yield break; }+ foreach (var seg in rel.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))+ yield return seg;+ }++ private static SampleKind KindOf(List<string> tokens, out bool drum)+ {+ drum = false;+ var kind = SampleKind.Unknown;+ for (int i = 0; i < tokens.Count; i++)+ {+ string t = tokens[i];+ if (LoopWords.Contains(t)) return SampleKind.Loop; // "Kick Loop" is a loop+ if (ShotWords.Contains(t) || (t.Equals("one", StringComparison.OrdinalIgnoreCase)+ && i + 1 < tokens.Count && tokens[i + 1].StartsWith("shot", StringComparison.OrdinalIgnoreCase)))+ kind = SampleKind.OneShot;+ if (DrumWords.Contains(t)) drum = true;+ }+ return kind;+ }++ private static MusicalKey? KeyOf(List<string> tokens, int bpmToken, bool hasBpm)+ {+ MusicalKey? strong = null, weak = null;+ for (int i = 0; i < tokens.Count; i++)+ {+ var m = KeyToken.Match(tokens[i]);+ if (!m.Success) continue;+ string letter = m.Groups[1].Value, acc = m.Groups[2].Value, mode = m.Groups[3].Value, tail = m.Groups[4].Value;+ bool upper = char.IsUpper(letter[0]);+ // A lowercase 'b' after a letter is a flat; "Bb" — but "bb" / "db" are words, not keys.+ if (acc == "b" && !upper) continue;+ int tonic = MusicalKey.TonicOf(letter, acc);+ string next = i + 1 < tokens.Count ? tokens[i + 1] : "";++ if (mode.Length == 0 && tail.Length == 0+ && (next.StartsWith("min", StringComparison.OrdinalIgnoreCase) || next.StartsWith("maj", StringComparison.OrdinalIgnoreCase))+ && next.Length is 3 or 5)+ { // "A minor", "Eb maj"+ strong = new MusicalKey(tonic, next.StartsWith("min", StringComparison.OrdinalIgnoreCase) ? KeyMode.Minor : KeyMode.Major);+ continue;+ }+ if (mode.Length > 1 || (mode == "m" && upper))+ { // "Amin", "Cmaj7", "C#m", "Dm9" — "am" / "em" alone are words+ bool minor = mode == "m" || mode.StartsWith("min", StringComparison.OrdinalIgnoreCase);+ strong = new MusicalKey(tonic, minor ? KeyMode.Minor : KeyMode.Major);+ continue;+ }+ if (mode.Length > 0) continue;+ if (tail.Length == 1)+ { // "C4", "F#2": a one-shot's pitch+ strong = new MusicalKey(tonic, KeyMode.Note);+ continue;+ }+ if (tail.Length > 0 || !upper) continue;+ if (acc.Length > 0) { strong = new MusicalKey(tonic, KeyMode.Major); continue; } // "F#", "Eb"+ // A lone capital letter is as often a take ("Kick A") as a key: only next to the+ // tempo, after the word "key", or closing a name that carries a tempo.+ bool byBpm = bpmToken >= 0 && Math.Abs(i - bpmToken) == 1;+ bool afterKey = i > 0 && tokens[i - 1].Equals("key", StringComparison.OrdinalIgnoreCase);+ if (byBpm || afterKey || (hasBpm && i == tokens.Count - 1)) weak = new MusicalKey(tonic, KeyMode.Major);+ }+ return strong ?? weak;+ }+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.csindex f1d91836..6c9be033 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.cs@@ -48,4 +48,35 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_clip_auto_warp_bpm")]internal static partial double ClipAutoWarpBpm(IntPtr engine, int trackId, int clipIndex, double bpm);++ /// <summary>Mirrors NotaSampleAnalysis (doubles first, so no padding surprises).</summary>+ [StructLayout(LayoutKind.Sequential)]+ internal unsafe struct NotaSampleAnalysis+ {+ public double DurationSec;+ public double SampleRate;+ public double Bpm;+ public int Channels;+ public int KeyTonic;+ public int KeyMode;+ public float KeyConfidence;+ public float TailRatio;+ public float PeakDb;+ public float RmsDb;+ public fixed float Timbre[16]; // NOTA_TIMBRE_DIMS++ public readonly Nota.Application.Samples.SampleAnalysis ToAnalysis()+ {+ var t = new float[16];+ for (int i = 0; i < t.Length; i++) t[i] = Timbre[i];+ return new(DurationSec, SampleRate, Channels, Bpm, KeyTonic, KeyMode, KeyConfidence,+ TailRatio, PeakDb, RmsDb, t);+ }+ }++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_analyze")]+ internal static partial NotaResult AudioImportAnalyze(IntPtr job, out NotaSampleAnalysis analysis);++ [LibraryImport(Lib, EntryPoint = "nota_sample_analyze_file", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial NotaResult SampleAnalyzeFile(string path, double maxSeconds, out NotaSampleAnalysis analysis);}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.csindex 31f29200..46d0d385 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.cs@@ -64,6 +64,9 @@ public sealed partial class NotaEnginepublic double DetectTempo() => NativeMethods.AudioImportDetectTempo(Handle);+ public Nota.Application.Samples.SampleAnalysis? Analyze()+ => NativeMethods.AudioImportAnalyze(Handle, out var a) == NativeMethods.NotaResult.Ok ? a.ToAnalysis() : null;+public void Dispose(){var h = Interlocked.Exchange(ref _h, IntPtr.Zero);diff --git a/src/managed/Nota.Infrastructure/SampleStore/SampleLibraryIndex.cs b/src/managed/Nota.Infrastructure/SampleStore/SampleLibraryIndex.csnew file mode 100644index 00000000..b05a1b52--- /dev/null+++ b/src/managed/Nota.Infrastructure/SampleStore/SampleLibraryIndex.cs@@ -0,0 +1,493 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The sample library's analysis index (ISampleIndex). A background scan walks the Samples+// folder and has the engine measure every audio file it doesn't know yet — tempo, key,+// envelope, timbre — on a few below-normal-priority threads, a just-installed pack first.+// Results persist in <data>/sample-index/index.bin, keyed by path and invalidated by size or+// date, so a library of tens of thousands of files is analysed once, not on every launch.+// Only the raw analysis is stored: what it means (loop or one-shot, which tempo to trust)+// is worked out again from the name on load, so classifier fixes need no re-analysis.++using System.Collections.Concurrent;+using Nota.Application;+using Nota.Application.Samples;++namespace Nota.Infrastructure;++public sealed class SampleAnalyzer : ISampleAnalyzer+{+ public SampleAnalysis? Analyze(string path, double maxSeconds)+ {+ try+ {+ return NativeMethods.SampleAnalyzeFile(path, maxSeconds, out var a) == NativeMethods.NotaResult.Ok+ ? a.ToAnalysis() : null;+ }+ catch (DllNotFoundException) { return null; }+ catch (EntryPointNotFoundException) { return null; }+ }+}++public sealed class SampleLibraryIndex : ISampleIndex, IDisposable+{+ /// <summary>Seconds of a file the analysis decodes — a loop's worth and then some; a long+ /// recording's tempo and key show well before the end.</summary>+ public const double AnalyzeSeconds = 60;++ private static readonly string[] AudioExts = { ".wav", ".flac", ".mp3" };+ private const uint Magic = 0x3158534E; // "NSX1"+ private const int FileVersion = 1;+ private static readonly TimeSpan SaveEvery = TimeSpan.FromSeconds(5);+ private static readonly TimeSpan NotifyEvery = TimeSpan.FromMilliseconds(750);++ // Timbre weights for "similar sounds": the band shape is the sound's colour; brightness,+ // noisiness and attack separate a clap from a rim; length keeps hits away from loops.+ private static readonly float[] TimbreWeights = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2.5f, 2f, 2f, 1.5f };++ private sealed class Entry+ {+ public long Size;+ public long Ticks;+ public SampleAnalysis? Analysis; // null = couldn't be decoded+ public SampleInfo? Info; // derived, cleared when the root changes+ }++ private readonly ISampleAnalyzer _analyzer;+ private readonly string _file;+ private readonly object _gate = new();+ private readonly Dictionary<string, Entry> _entries = new(PathComparer);+ private readonly List<string> _priority = new();+ private bool _loaded;+ private string? _root;+ private CancellationTokenSource? _scanCts;+ private int _scanGen;+ private int _done, _total;+ private int _mutations; // bumps on every change; keys the stats cache+ private (int Mutations, float[] Mean, float[] Std)? _stats;+ private DateTime _lastNotify = DateTime.MinValue;+ private DateTime _lastSave = DateTime.UtcNow;+ private bool _dirty;++ public event Action? Changed;++ private static StringComparer PathComparer+ => OperatingSystem.IsLinux() ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;++ public SampleLibraryIndex(ISampleAnalyzer analyzer) : this(analyzer, Path.Combine(NotaPaths.SubDir("sample-index"), "index.bin")) { }++ /// <summary>Tests: an index persisted at <paramref name="file"/>.</summary>+ public SampleLibraryIndex(ISampleAnalyzer analyzer, string file)+ {+ _analyzer = analyzer;+ _file = file;+ }++ public (int Done, int Total) Progress { get { lock (_gate) return (_done, _total); } }++ public SampleInfo? Get(string path)+ {+ lock (_gate)+ {+ EnsureLoaded();+ return _entries.TryGetValue(path, out var e) ? InfoOf(path, e) : null;+ }+ }++ public SampleInfo? GetOrAnalyze(string path)+ {+ var fi = new FileInfo(path);+ if (!fi.Exists) return null;+ lock (_gate)+ {+ EnsureLoaded();+ if (_entries.TryGetValue(path, out var e) && Fresh(e, fi)) return e.Analysis is null ? null : InfoOf(path, e);+ }+ var a = _analyzer.Analyze(path, AnalyzeSeconds);+ return a is null ? null : Store(path, a);+ }++ public SampleInfo Store(string path, SampleAnalysis analysis)+ {+ var fi = new FileInfo(path);+ var e = new Entry { Size = fi.Exists ? fi.Length : -1, Ticks = fi.Exists ? fi.LastWriteTimeUtc.Ticks : 0, Analysis = analysis };+ SampleInfo info;+ lock (_gate)+ {+ EnsureLoaded();+ _entries[path] = e;+ info = InfoOf(path, e);+ _mutations++;+ _dirty = true;+ }+ Notify(force: true);+ return info;+ }++ public void Watch(string root)+ {+ CancellationTokenSource cts;+ int gen;+ lock (_gate)+ {+ if (_root is null || !PathComparer.Equals(_root, root))+ {+ _root = root;+ foreach (var e in _entries.Values) e.Info = null; // folder hints are relative to the root+ }+ _scanCts?.Cancel();+ _scanCts = cts = new CancellationTokenSource();+ gen = ++_scanGen;+ }+ var thread = new Thread(() => Scan(root, gen, cts.Token)) { IsBackground = true, Name = "Sample index", Priority = ThreadPriority.BelowNormal };+ thread.Start();+ }++ public void Prioritize(string folder)+ {+ string? root;+ lock (_gate)+ {+ _priority.Remove(folder);+ _priority.Insert(0, folder);+ root = _root;+ }+ if (root is not null) Watch(root); // re-scan: the new files sort to the front+ }++ public IReadOnlyList<SimilarSample> Similar(string path, int count)+ {+ var anchor = GetOrAnalyze(path);+ if (anchor is null || anchor.Timbre.Length != SampleAnalysis.TimbreDims) return Array.Empty<SimilarSample>();+ lock (_gate)+ {+ var (mean, std) = Stats();+ var a = Normalize(anchor.Timbre, mean, std);+ var best = new List<SimilarSample>();+ foreach (var (p, e) in _entries)+ {+ if (e.Analysis is not { Timbre.Length: SampleAnalysis.TimbreDims } || PathComparer.Equals(p, path)) continue;+ var info = InfoOf(p, e);+ // A loop is never "like" a hit, however close their spectra.+ if (anchor.Kind != SampleKind.Unknown && info.Kind != SampleKind.Unknown && anchor.Kind != info.Kind) continue;+ double d = Distance(a, Normalize(info.Timbre, mean, std));+ best.Add(new SimilarSample(info, d));+ }+ best.Sort((x, y) => x.Distance.CompareTo(y.Distance));+ return best.Count > count ? best.GetRange(0, count) : best;+ }+ }++ public IReadOnlyList<SampleInfo> Search(SampleFilter filter, string? text, int limit)+ {+ var words = (text ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);+ var hits = new List<SampleInfo>();+ lock (_gate)+ {+ EnsureLoaded();+ foreach (var (p, e) in _entries)+ {+ if (e.Analysis is null) continue;+ if (words.Any(w => !p.Contains(w, StringComparison.OrdinalIgnoreCase))) continue;+ var info = InfoOf(p, e);+ if (filter.Matches(info)) hits.Add(info);+ }+ }+ hits.Sort((x, y) => string.Compare(x.Path, y.Path, StringComparison.OrdinalIgnoreCase));+ return hits.Count > limit ? hits.GetRange(0, limit) : hits;+ }++ public void Dispose()+ {+ lock (_gate) { _scanCts?.Cancel(); }+ Save();+ }++ // --- scan -----------------------------------------------------------------------------++ private void Scan(string root, int gen, CancellationToken ct)+ {+ try+ {+ List<string> pending;+ lock (_gate) EnsureLoaded();+ WarmInfos(gen, ct);+ var found = Enumerate(root, ct);+ var present = new HashSet<string>(found, PathComparer);+ var stamps = new Dictionary<string, (long Size, long Ticks)>(found.Count, PathComparer);+ foreach (var p in found)+ {+ ct.ThrowIfCancellationRequested();+ var fi = new FileInfo(p);+ if (fi.Exists) stamps[p] = (fi.Length, fi.LastWriteTimeUtc.Ticks);+ }+ lock (_gate)+ {+ if (gen != _scanGen) return;+ // Forget files that left the library (anything outside it, dragged in from+ // elsewhere, stays until its file is gone).+ var gone = _entries.Keys.Where(p => IsUnder(p, root) ? !present.Contains(p) : !File.Exists(p)).ToList();+ foreach (var p in gone) _entries.Remove(p);+ if (gone.Count > 0) { _mutations++; _dirty = true; }++ pending = new List<string>();+ foreach (var (p, st) in stamps)+ if (!_entries.TryGetValue(p, out var e) || e.Size != st.Size || e.Ticks != st.Ticks) pending.Add(p);+ var priority = _priority.ToList();+ pending.Sort((a, b) =>+ {+ int pa = PriorityOf(a, priority), pb = PriorityOf(b, priority);+ return pa != pb ? pa.CompareTo(pb) : string.Compare(a, b, StringComparison.OrdinalIgnoreCase);+ });+ _done = 0;+ _total = pending.Count;+ }+ if (pending.Count > 0) Notify(force: true);++ int next = -1;+ int workers = Math.Clamp(Environment.ProcessorCount / 2, 1, 4);+ var threads = new List<Thread>();+ for (int w = 0; w < workers; w++)+ {+ var t = new Thread(() =>+ {+ while (!ct.IsCancellationRequested)+ {+ int i = Interlocked.Increment(ref next);+ if (i >= pending.Count) break;+ Analyze(pending[i], gen);+ }+ }) { IsBackground = true, Name = "Sample analysis", Priority = ThreadPriority.BelowNormal };+ threads.Add(t);+ t.Start();+ }+ foreach (var t in threads) t.Join();+ if (ct.IsCancellationRequested) return;+ lock (_gate)+ {+ if (gen != _scanGen) return;+ _done = _total = 0;+ _priority.Clear();+ }+ Save();+ Notify(force: true);+ }+ catch (Exception) when (ct.IsCancellationRequested) { }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }++ // Classify what loaded from disk here, a few hundred at a time, so the browser's first+ // pass over tens of thousands of rows is lookups, not name parsing on the UI thread.+ private void WarmInfos(int gen, CancellationToken ct)+ {+ string[] paths;+ lock (_gate) paths = _entries.Keys.ToArray();+ for (int i = 0; i < paths.Length; i += 500)+ {+ ct.ThrowIfCancellationRequested();+ lock (_gate)+ {+ if (gen != _scanGen) return;+ for (int k = i; k < Math.Min(paths.Length, i + 500); k++)+ if (_entries.TryGetValue(paths[k], out var e)) InfoOf(paths[k], e);+ }+ }+ Notify(force: true);+ }++ private void Analyze(string path, int gen)+ {+ FileInfo fi;+ SampleAnalysis? a;+ try+ {+ fi = new FileInfo(path);+ if (!fi.Exists) return;+ a = _analyzer.Analyze(path, AnalyzeSeconds);+ }+ catch (IOException) { return; }+ lock (_gate)+ {+ _entries[path] = new Entry { Size = fi.Length, Ticks = fi.LastWriteTimeUtc.Ticks, Analysis = a };+ _mutations++;+ _dirty = true;+ if (gen == _scanGen) _done++;+ }+ if (DateTime.UtcNow - _lastSave > SaveEvery) Save();+ Notify(force: false);+ }++ private static int PriorityOf(string path, List<string> priority)+ {+ for (int i = 0; i < priority.Count; i++) if (IsUnder(path, priority[i])) return i;+ return priority.Count;+ }++ private static bool IsUnder(string path, string folder)+ {+ var rel = Path.GetRelativePath(folder, path);+ return rel != "." && !rel.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(rel);+ }++ private static List<string> Enumerate(string root, CancellationToken ct)+ {+ var files = new List<string>();+ if (!Directory.Exists(root)) return files;+ var opts = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.Hidden | FileAttributes.System };+ foreach (var f in Directory.EnumerateFiles(root, "*", opts))+ {+ ct.ThrowIfCancellationRequested();+ if (AudioExts.Contains(Path.GetExtension(f).ToLowerInvariant())) files.Add(f);+ }+ return files;+ }++ private void Notify(bool force)+ {+ var now = DateTime.UtcNow;+ lock (_gate)+ {+ if (!force && now - _lastNotify < NotifyEvery) return;+ _lastNotify = now;+ }+ Changed?.Invoke();+ }++ // --- derived ----------------------------------------------------------------------------++ private static bool Fresh(Entry e, FileInfo fi) => e.Size == fi.Length && e.Ticks == fi.LastWriteTimeUtc.Ticks;++ private SampleInfo InfoOf(string path, Entry e)+ => e.Info ??= SampleClassifier.Classify(path, SampleNameHints.Parse(path, _root), e.Analysis);++ // Per-dimension mean / spread over the library, so a dB band and a 0..1 flatness weigh alike.+ private (float[] Mean, float[] Std) Stats()+ {+ if (_stats is { } s && s.Mutations == _mutations) return (s.Mean, s.Std);+ int n = SampleAnalysis.TimbreDims;+ var mean = new double[n];+ var sq = new double[n];+ int count = 0;+ foreach (var e in _entries.Values)+ {+ if (e.Analysis is not { Timbre.Length: SampleAnalysis.TimbreDims } a) continue;+ for (int i = 0; i < n; i++) { mean[i] += a.Timbre[i]; sq[i] += a.Timbre[i] * (double)a.Timbre[i]; }+ count++;+ }+ var m = new float[n];+ var sd = new float[n];+ for (int i = 0; i < n; i++)+ {+ double mu = count > 0 ? mean[i] / count : 0;+ double v = count > 1 ? Math.Max(0, sq[i] / count - mu * mu) : 1;+ m[i] = (float)mu;+ sd[i] = (float)Math.Max(Math.Sqrt(v), 0.05); // a dimension the library barely varies on can't dominate+ }+ _stats = (_mutations, m, sd);+ return (m, sd);+ }++ private static float[] Normalize(float[] t, float[] mean, float[] std)+ {+ var z = new float[t.Length];+ for (int i = 0; i < t.Length; i++) z[i] = (t[i] - mean[i]) / std[i];+ return z;+ }++ private static double Distance(float[] a, float[] b)+ {+ double sum = 0, wsum = 0;+ for (int i = 0; i < a.Length; i++)+ {+ double d = a[i] - b[i];+ sum += TimbreWeights[i] * d * d;+ wsum += TimbreWeights[i];+ }+ return Math.Sqrt(sum / wsum);+ }++ // --- persistence --------------------------------------------------------------------------+ // u32 magic, i32 file version, i32 analysis version, i32 count, then per entry:+ // string path, i64 size, i64 ticks, bool analysed, [f64 dur, f64 sr, i32 ch, f64 bpm,+ // i32 tonic, i32 mode, f32 conf, f32 tail, f32 peak, f32 rms, i32 n, f32[n] timbre].++ private void EnsureLoaded()+ {+ if (_loaded) return;+ _loaded = true;+ try+ {+ if (!File.Exists(_file)) return;+ using var r = new BinaryReader(File.OpenRead(_file));+ if (r.ReadUInt32() != Magic || r.ReadInt32() != FileVersion || r.ReadInt32() != SampleAnalysis.Version) return;+ int count = r.ReadInt32();+ for (int i = 0; i < count; i++)+ {+ string path = r.ReadString();+ var e = new Entry { Size = r.ReadInt64(), Ticks = r.ReadInt64() };+ if (r.ReadBoolean())+ {+ double dur = r.ReadDouble(), sr = r.ReadDouble();+ int ch = r.ReadInt32();+ double bpm = r.ReadDouble();+ int tonic = r.ReadInt32(), mode = r.ReadInt32();+ float conf = r.ReadSingle(), tail = r.ReadSingle(), peak = r.ReadSingle(), rms = r.ReadSingle();+ int n = r.ReadInt32();+ if (n is < 0 or > 64) return; // corrupt: keep what loaded, rescan the rest+ var t = new float[n];+ for (int k = 0; k < n; k++) t[k] = r.ReadSingle();+ e.Analysis = new SampleAnalysis(dur, sr, ch, bpm, tonic, mode, conf, tail, peak, rms, t);+ }+ _entries[path] = e;+ }+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }++ private void Save()+ {+ KeyValuePair<string, Entry>[] snapshot;+ lock (_gate)+ {+ if (!_dirty || !_loaded) return;+ _dirty = false;+ _lastSave = DateTime.UtcNow;+ snapshot = _entries.ToArray();+ }+ string tmp = _file + "." + Environment.CurrentManagedThreadId + ".tmp";+ try+ {+ Directory.CreateDirectory(Path.GetDirectoryName(_file)!);+ using (var w = new BinaryWriter(File.Create(tmp)))+ {+ w.Write(Magic);+ w.Write(FileVersion);+ w.Write(SampleAnalysis.Version);+ w.Write(snapshot.Length);+ foreach (var (path, e) in snapshot)+ {+ w.Write(path);+ w.Write(e.Size);+ w.Write(e.Ticks);+ w.Write(e.Analysis is not null);+ if (e.Analysis is not { } a) continue;+ w.Write(a.DurationSec); w.Write(a.SampleRate); w.Write(a.Channels); w.Write(a.Bpm);+ w.Write(a.KeyTonic); w.Write(a.KeyMode);+ w.Write(a.KeyConfidence); w.Write(a.TailRatio); w.Write(a.PeakDb); w.Write(a.RmsDb);+ w.Write(a.Timbre.Length);+ foreach (var v in a.Timbre) w.Write(v);+ }+ }+ File.Move(tmp, _file, overwrite: true);+ }+ catch (IOException) { lock (_gate) _dirty = true; TryDelete(tmp); }+ catch (UnauthorizedAccessException) { lock (_gate) _dirty = true; TryDelete(tmp); }+ }++ private static void TryDelete(string path)+ {+ try { File.Delete(path); } catch (IOException) { } catch (UnauthorizedAccessException) { }+ }+}diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex b9c9d0e9..f3bfa690 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -62,6 +62,7 @@ set(NOTA_ENGINE_SOURCESsrc/Engine_Render.cppsrc/WarpStream.cppsrc/TempoDetect.cpp+ src/SampleAnalysis.cppsrc/AudioFile.cppsrc/AudioImport.cppsrc/nota_engine_import.cppdiff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 1bf0c6d2..38ec1bd1 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -503,6 +503,30 @@ NOTA_API int32_t nota_track_add_imported_clip(NotaEngine* engine, int32_t tra/* Auto-warp with an already-detected tempo (skips detection). Returns the BPM used (0 = failed). */NOTA_API double nota_clip_auto_warp_bpm(NotaEngine* engine, int32_t track_id, int32_t clip_index, double bpm);+/* ---- Sample analysis (browser sample index) ------------------------------ */+/* What the Files tab knows about a sample: tempo, key, the envelope facts that tell a loop+ * from a one-shot, and a timbre fingerprint for "similar sounds". Worker-thread safe (no+ * engine state). timbre layout: 0..11 log-band energy shares (dB/30, 40 Hz–16 kHz),+ * 12 centroid log2(Hz/1000), 13 flatness 0..1, 14 log10 attack s, 15 log2 analysed s. */+#define NOTA_TIMBRE_DIMS 16+typedef struct NotaSampleAnalysis {+ double duration_sec; /* the whole file, not just the analysed head */+ double sample_rate;+ double bpm; /* 0 = no steady pulse */+ int32_t channels;+ int32_t key_tonic; /* -1 = atonal, else 0..11 (C..B) */+ int32_t key_mode; /* 0 major, 1 minor, -1 tonic only (mode unclear) */+ float key_confidence; /* 0..1 */+ float tail_ratio; /* RMS of the last tenth / whole: ~1 loops, ~0 decaying hits */+ float peak_db;+ float rms_db;+ float timbre[NOTA_TIMBRE_DIMS];+} NotaSampleAnalysis;+/* Analyses a finished import (the whole decoded buffer). */+NOTA_API NotaResult nota_audio_import_analyze(const NotaAudioImport* job, NotaSampleAnalysis* out);+/* Decodes a file's first max_seconds (<= 0 = all of it) and analyses that. */+NOTA_API NotaResult nota_sample_analyze_file(const char* path_utf8, double max_seconds, NotaSampleAnalysis* out);+/* ---- Instrument tracks, MIDI clips & notes (M2) -------------------------- *//* Adds an instrument track with the built-in Nota Synth. Returns id (>0). */NOTA_API int32_t nota_engine_add_instrument_track(NotaEngine* engine);diff --git a/src/native/nota.engine/src/AudioImport.cpp b/src/native/nota.engine/src/AudioImport.cppindex c0a7a0fb..b1be9d9c 100644--- a/src/native/nota.engine/src/AudioImport.cpp+++ b/src/native/nota.engine/src/AudioImport.cpp@@ -48,7 +48,7 @@ struct AudioImportJob::Decoder {AudioImportJob::~AudioImportJob() = default;-std::unique_ptr<AudioImportJob> AudioImportJob::open(const std::string& path) {+std::unique_ptr<AudioImportJob> AudioImportJob::open(const std::string& path, double maxSeconds) {std::string ext;if (auto dot = path.find_last_of('.'); dot != std::string::npos) ext = path.substr(dot + 1);std::transform(ext.begin(), ext.end(), ext.begin(),@@ -90,10 +90,13 @@ std::unique_ptr<AudioImportJob> AudioImportJob::open(const std::string& path) {if (!whole || whole->empty()) return nullptr;job->buf_ = std::move(whole);job->decoded_ = job->buf_->frames;+ job->sourceFrames_ = job->buf_->frames;job->done_ = true;return job;}+ job->sourceFrames_ = static_cast<int64_t>(total);+ if (maxSeconds > 0.0) total = std::min<uint64_t>(total, static_cast<uint64_t>(std::max(1.0, maxSeconds * rate)));job->buf_->channels = static_cast<int32_t>(channels);job->buf_->frames = static_cast<int64_t>(total);job->buf_->samples.assign(static_cast<size_t>(total) * channels, 0.0f);diff --git a/src/native/nota.engine/src/AudioImport.h b/src/native/nota.engine/src/AudioImport.hindex 8ba19b38..b2d4241e 100644--- a/src/native/nota.engine/src/AudioImport.h+++ b/src/native/nota.engine/src/AudioImport.h@@ -21,13 +21,16 @@ public:~AudioImportJob();// Opens `path` and reads its header. Null when the file can't be opened/decoded.- static std::unique_ptr<AudioImportJob> open(const std::string& path);+ // maxSeconds > 0 decodes only the file's head (analysis): the buffer holds at most that+ // much and the job is done once it is in; sourceFrames() keeps the real length.+ static std::unique_ptr<AudioImportJob> open(const std::string& path, double maxSeconds = 0.0);// Decodes up to maxFrames more. Returns 1 while frames remain, 0 once done, -1 on error.int32_t step(int64_t maxFrames);bool done() const { return done_; }int64_t decodedFrames() const { return decoded_; }+ int64_t sourceFrames() const { return sourceFrames_; } // the whole file, even when cappedconst std::shared_ptr<SampleBuffer>& buffer() const { return buf_; }// Display peaks over the WHOLE file (maxPoints buckets, min/max pairs). Buckets not@@ -49,6 +52,7 @@ private:std::unique_ptr<Decoder> dec_;std::shared_ptr<SampleBuffer> buf_;int64_t decoded_ = 0;+ int64_t sourceFrames_ = 0;bool done_ = false;bool seeded_ = false;};diff --git a/src/native/nota.engine/src/SampleAnalysis.cpp b/src/native/nota.engine/src/SampleAnalysis.cppnew file mode 100644index 00000000..5b84e25c--- /dev/null+++ b/src/native/nota.engine/src/SampleAnalysis.cpp@@ -0,0 +1,252 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "SampleAnalysis.h"+#include "TempoDetect.h"++#include "signalsmith-linear/fft.h"++#include <algorithm>+#include <cmath>+#include <complex>+#include <vector>++namespace nota {++namespace {++// Krumhansl–Kessler probe-tone profiles (1982), tonic first.+constexpr double kMajorProfile[12] = { 6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88 };+constexpr double kMinorProfile[12] = { 6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17 };++constexpr double kPi = 3.14159265358979323846;++constexpr double kKeyLoHz = 50.0; // chroma band: low enough for a bass line…+constexpr double kKeyHiHz = 2500.0; // …high enough for the melody's fundamentals+constexpr double kPeakOverLocal = 4.0; // a spectral peak counts as a partial at 4× its neighbourhood+constexpr int kLocalHalf = 16; // neighbourhood half-width in bins+constexpr double kMinTonalFrac = 0.04; // partials' share of the band's magnitude; drums sit below it+constexpr double kMinChromaCrest = 1.5;+constexpr double kMinKeyR = 0.5;+constexpr double kModeMargin = 0.04; // major vs minor on one tonic closer than this = mode unclear++constexpr int kTimbreFft = 2048;+constexpr double kTimbreSeconds = 10.0;+constexpr int kBands = 12;+constexpr double kBandLoHz = 40.0, kBandHiHz = 16000.0;++std::vector<float> monoOf(const SampleBuffer& src, int64_t offset, int64_t len) {+ std::vector<float> m(static_cast<size_t>(std::max<int64_t>(0, len)));+ const int ch = std::max(1, src.channels);+ for (int64_t i = 0; i < len; ++i) {+ const float* p = &src.samples[static_cast<size_t>((offset + i) * src.channels)];+ float s = 0.0f;+ for (int c = 0; c < src.channels; ++c) s += p[c];+ m[static_cast<size_t>(i)] = s / static_cast<float>(ch);+ }+ return m;+}++std::vector<float> hann(int n) {+ std::vector<float> w(static_cast<size_t>(n));+ for (int i = 0; i < n; ++i) w[static_cast<size_t>(i)] = 0.5f - 0.5f * static_cast<float>(std::cos(2.0 * kPi * i / n));+ return w;+}++double pearson(const double* a, const double* b, int n) {+ double ma = 0, mb = 0;+ for (int i = 0; i < n; ++i) { ma += a[i]; mb += b[i]; }+ ma /= n; mb /= n;+ double cov = 0, va = 0, vb = 0;+ for (int i = 0; i < n; ++i) {+ const double da = a[i] - ma, db = b[i] - mb;+ cov += da * db; va += da * da; vb += db * db;+ }+ return (va <= 0 || vb <= 0) ? 0.0 : cov / std::sqrt(va * vb);+}++void keyFromMono(const std::vector<float>& mono, double sr, int32_t& tonic, int32_t& mode, float& confidence) {+ tonic = -1; mode = -1; confidence = 0.0f;+ if (mono.empty() || sr <= 0) return;+ const int n = sr > 32000.0 ? 16384 : 8192; // ~2.7 Hz bins: semitones resolve down to the bass+ const int hop = n / 2;+ const int bins = n / 2;+ const double binHz = sr / n;+ const int kLo = std::max(2, static_cast<int>(std::ceil(kKeyLoHz / binHz)));+ const int kHi = std::min(bins - 2, static_cast<int>(kKeyHiHz / binHz));+ if (kHi <= kLo + 2) return;++ signalsmith::linear::RealFFT<float> fft(static_cast<size_t>(n));+ const auto win = hann(n);+ std::vector<float> time(static_cast<size_t>(n));+ std::vector<std::complex<float>> freq(static_cast<size_t>(bins));+ std::vector<double> mag(static_cast<size_t>(bins)), prefix(static_cast<size_t>(bins) + 1);++ double chroma[12] = {};+ double partials = 0.0, band = 0.0;+ const int64_t len = static_cast<int64_t>(mono.size());+ for (int64_t start = 0; start == 0 || start + n / 4 < len; start += hop) {+ for (int i = 0; i < n; ++i) {+ const int64_t at = start + i;+ time[static_cast<size_t>(i)] = at < len ? mono[static_cast<size_t>(at)] * win[static_cast<size_t>(i)] : 0.0f;+ }+ fft.fft(time.data(), freq.data());+ prefix[0] = 0.0;+ for (int k = 0; k < bins; ++k) {+ mag[static_cast<size_t>(k)] = std::abs(freq[static_cast<size_t>(k)]);+ prefix[static_cast<size_t>(k) + 1] = prefix[static_cast<size_t>(k)] + mag[static_cast<size_t>(k)];+ }+ for (int k = kLo; k <= kHi; ++k) {+ const double m = mag[static_cast<size_t>(k)];+ band += m;+ if (!(m > mag[static_cast<size_t>(k) - 1] && m >= mag[static_cast<size_t>(k) + 1])) continue;+ const int a = std::max(0, k - kLocalHalf), b = std::min(bins - 1, k + kLocalHalf);+ const double local = (prefix[static_cast<size_t>(b) + 1] - prefix[static_cast<size_t>(a)]) / (b - a + 1);+ if (m < kPeakOverLocal * local || m <= 1e-9) continue;+ // Parabolic interpolation on log magnitude for the partial's true frequency.+ const double la = std::log(mag[static_cast<size_t>(k) - 1] + 1e-12), lb = std::log(m + 1e-12),+ lc = std::log(mag[static_cast<size_t>(k) + 1] + 1e-12);+ const double den = la - 2.0 * lb + lc;+ const double p = std::fabs(den) > 1e-12 ? std::clamp(0.5 * (la - lc) / den, -0.5, 0.5) : 0.0;+ const double hz = (k + p) * binHz;+ const double midi = 69.0 + 12.0 * std::log2(hz / 440.0);+ const int pc = ((static_cast<int>(std::lround(midi)) % 12) + 12) % 12;+ chroma[pc] += m;+ partials += m;+ }+ if (start + n >= len) break;+ }+ if (band <= 1e-9 || partials / band < kMinTonalFrac) return; // no partials worth naming++ double cmax = 0, cmean = 0;+ for (double c : chroma) { cmax = std::max(cmax, c); cmean += c; }+ cmean /= 12.0;+ if (cmean <= 0 || cmax / cmean < kMinChromaCrest) return; // spread evenly: noise, clusters++ double rMaj[12], rMin[12], rot[12];+ double best = -2.0; int bestT = 0, bestM = 0;+ for (int t = 0; t < 12; ++t) {+ for (int i = 0; i < 12; ++i) rot[i] = kMajorProfile[(i - t + 12) % 12];+ rMaj[t] = pearson(chroma, rot, 12);+ for (int i = 0; i < 12; ++i) rot[i] = kMinorProfile[(i - t + 12) % 12];+ rMin[t] = pearson(chroma, rot, 12);+ if (rMaj[t] > best) { best = rMaj[t]; bestT = t; bestM = 0; }+ if (rMin[t] > best) { best = rMin[t]; bestT = t; bestM = 1; }+ }+ if (best < kMinKeyR) return;+ tonic = bestT;+ mode = std::fabs(rMaj[bestT] - rMin[bestT]) < kModeMargin ? -1 : bestM;+ confidence = static_cast<float>(std::clamp(best, 0.0, 1.0));+}++// Timbre fingerprint over the first ~10 s (layout of SampleFeatures::timbre):+// 0..11 energy share of 12 log-spaced bands, 40 Hz–16 kHz, in dB / 30+// 12 spectral centroid, log2(Hz / 1000)+// 13 spectral flatness (0 tonal … 1 noise), energy-weighted+// 14 attack: log10(seconds to 90 % of the envelope peak + 1 ms)+// 15 length: log2(seconds analysed + 0.05)+void timbreOf(const std::vector<float>& mono, double sr, SampleFeatures& f) {+ const int64_t len = std::min<int64_t>(static_cast<int64_t>(mono.size()), static_cast<int64_t>(kTimbreSeconds * sr));+ const int n = kTimbreFft, bins = n / 2, hop = n / 2;+ const double binHz = sr / n;+ int bandOf[kTimbreFft / 2];+ const double ratio = std::pow(kBandHiHz / kBandLoHz, 1.0 / kBands);+ for (int k = 0; k < bins; ++k) {+ const double hz = k * binHz;+ bandOf[k] = (hz < kBandLoHz || hz >= kBandHiHz) ? -1+ : std::min(kBands - 1, static_cast<int>(std::log(hz / kBandLoHz) / std::log(ratio)));+ }++ signalsmith::linear::RealFFT<float> fft(static_cast<size_t>(n));+ const auto win = hann(n);+ std::vector<float> time(static_cast<size_t>(n));+ std::vector<std::complex<float>> freq(static_cast<size_t>(bins));+ double bandPow[kBands] = {};+ double total = 0, centroidNum = 0, flatNum = 0, flatDen = 0;+ for (int64_t start = 0; start == 0 || start + n / 4 < len; start += hop) {+ for (int i = 0; i < n; ++i) {+ const int64_t at = start + i;+ time[static_cast<size_t>(i)] = at < len ? mono[static_cast<size_t>(at)] * win[static_cast<size_t>(i)] : 0.0f;+ }+ fft.fft(time.data(), freq.data());+ double frame = 0, logSum = 0; int counted = 0;+ for (int k = 1; k < bins; ++k) {+ if (bandOf[k] < 0) continue;+ const double p = std::norm(freq[static_cast<size_t>(k)]);+ bandPow[bandOf[k]] += p;+ frame += p;+ centroidNum += p * k * binHz;+ logSum += std::log(p + 1e-20);+ ++counted;+ }+ total += frame;+ if (counted > 0 && frame > 1e-12) {+ const double flat = std::exp(logSum / counted) / (frame / counted);+ flatNum += flat * frame; flatDen += frame;+ }+ if (start + n >= len) break;+ }+ for (int b = 0; b < kBands; ++b)+ f.timbre[static_cast<size_t>(b)] = total > 0 ? static_cast<float>(10.0 * std::log10(bandPow[b] / total + 1e-9) / 30.0) : -3.0f;+ f.timbre[12] = total > 0 ? static_cast<float>(std::log2(std::max(20.0, centroidNum / total) / 1000.0)) : 0.0f;+ f.timbre[13] = flatDen > 0 ? static_cast<float>(flatNum / flatDen) : 1.0f;++ // Envelope at 10 ms: attack, tail ratio, peak / RMS.+ const int64_t eh = std::max<int64_t>(1, static_cast<int64_t>(sr * 0.01));+ const int64_t all = static_cast<int64_t>(mono.size());+ double sumSq = 0, peak = 0, envMax = 0; int64_t envMaxAt = 0;+ std::vector<double> env;+ env.reserve(static_cast<size_t>(all / eh + 1));+ for (int64_t s = 0; s < all; s += eh) {+ double acc = 0;+ const int64_t e = std::min(all, s + eh);+ for (int64_t i = s; i < e; ++i) {+ const double v = mono[static_cast<size_t>(i)];+ acc += v * v; peak = std::max(peak, std::fabs(v));+ }+ sumSq += acc;+ const double rms = std::sqrt(acc / static_cast<double>(e - s));+ env.push_back(rms);+ if (rms > envMax) { envMax = rms; envMaxAt = static_cast<int64_t>(env.size()) - 1; }+ }+ int64_t attackAt = envMaxAt;+ for (int64_t i = 0; i <= envMaxAt; ++i)+ if (env[static_cast<size_t>(i)] >= 0.9 * envMax) { attackAt = i; break; }+ f.timbre[14] = static_cast<float>(std::log10(attackAt * 0.01 + 0.001));+ f.timbre[15] = static_cast<float>(std::log2(all / sr + 0.05));++ const double rmsAll = all > 0 ? std::sqrt(sumSq / static_cast<double>(all)) : 0.0;+ f.peakDb = static_cast<float>(20.0 * std::log10(peak + 1e-6));+ f.rmsDb = static_cast<float>(20.0 * std::log10(rmsAll + 1e-6));+ const int64_t tail = std::max<int64_t>(1, all / 10);+ double tailSq = 0;+ for (int64_t i = all - tail; i < all; ++i) tailSq += static_cast<double>(mono[static_cast<size_t>(i)]) * mono[static_cast<size_t>(i)];+ const double rmsTail = std::sqrt(tailSq / static_cast<double>(tail));+ f.tailRatio = rmsAll > 1e-9 ? static_cast<float>(std::min(4.0, rmsTail / rmsAll)) : 0.0f;+}++} // namespace++void detectKey(const SampleBuffer& src, int64_t offset, int64_t len, double sampleRate,+ int32_t& tonic, int32_t& mode, float& confidence) {+ tonic = -1; mode = -1; confidence = 0.0f;+ if (src.channels <= 0 || sampleRate <= 0) return;+ offset = std::clamp<int64_t>(offset, 0, src.frames);+ len = std::min<int64_t>(len, src.frames - offset);+ if (len <= 0) return;+ keyFromMono(monoOf(src, offset, len), sampleRate, tonic, mode, confidence);+}++SampleFeatures analyzeSample(const SampleBuffer& src, int64_t frames) {+ SampleFeatures f;+ frames = std::min<int64_t>(frames, src.frames);+ const double sr = src.sourceSampleRate;+ if (frames <= 0 || src.channels <= 0 || sr <= 0) return f;+ const auto mono = monoOf(src, 0, frames);+ f.bpm = detectTempo(src, 0, frames, sr);+ keyFromMono(mono, sr, f.keyTonic, f.keyMode, f.keyConfidence);+ timbreOf(mono, sr, f);+ return f;+}++} // namespace notadiff --git a/src/native/nota.engine/src/SampleAnalysis.h b/src/native/nota.engine/src/SampleAnalysis.hnew file mode 100644index 00000000..9f0fb23d--- /dev/null+++ b/src/native/nota.engine/src/SampleAnalysis.h@@ -0,0 +1,37 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Offline analysis of a decoded sample for the browser's sample index: tempo (via+// TempoDetect), musical key (chroma against the Krumhansl–Kessler key profiles), a short+// timbre fingerprint for "similar sounds", and the envelope facts that tell a loop from a+// one-shot. Worker-thread only; allocates freely, touches no engine state.++#pragma once++#include "SampleBuffer.h"+#include <array>+#include <cstdint>++namespace nota {++inline constexpr int kTimbreDims = 16;++struct SampleFeatures {+ double bpm = 0.0; // 0 = no steady pulse+ int32_t keyTonic = -1; // -1 = atonal (drums, noise), else 0..11 (C..B)+ int32_t keyMode = -1; // 0 major, 1 minor, -1 tonic only (mode unclear)+ float keyConfidence = 0.0f; // 0..1 (profile correlation of the winning key)+ float tailRatio = 0.0f; // RMS of the last tenth over the whole RMS: ~1 loops, ~0 hits+ float peakDb = -120.0f;+ float rmsDb = -120.0f;+ std::array<float, kTimbreDims> timbre{}; // see SampleAnalysis.cpp for the layout+};++// Analyses the first `frames` frames of `src` (the decoded prefix; ≤ src.frames).+SampleFeatures analyzeSample(const SampleBuffer& src, int64_t frames);++// Key estimate only: tonic −1..11, mode −1/0/1, confidence 0..1.+void detectKey(const SampleBuffer& src, int64_t offset, int64_t len, double sampleRate,+ int32_t& tonic, int32_t& mode, float& confidence);++} // namespace notadiff --git a/src/native/nota.engine/src/nota_engine_import.cpp b/src/native/nota.engine/src/nota_engine_import.cppindex 0a8b4105..956d0b17 100644--- a/src/native/nota.engine/src/nota_engine_import.cpp+++ b/src/native/nota.engine/src/nota_engine_import.cpp@@ -5,6 +5,7 @@#include "nota_engine_internal.h"#include "AudioImport.h"+#include "SampleAnalysis.h"#include <algorithm>#include <cstring>@@ -13,6 +14,24 @@#define JOB(j) reinterpret_cast<nota::AudioImportJob*>(j)#define CJOB(j) reinterpret_cast<const nota::AudioImportJob*>(j)+namespace {+void fillAnalysis(const nota::SampleBuffer& b, int64_t frames, double totalFrames, NotaSampleAnalysis* out) {+ const auto f = nota::analyzeSample(b, frames);+ *out = NotaSampleAnalysis{};+ out->sample_rate = b.sourceSampleRate;+ out->duration_sec = b.sourceSampleRate > 0 ? totalFrames / b.sourceSampleRate : 0.0;+ out->channels = b.channels;+ out->bpm = f.bpm;+ out->key_tonic = f.keyTonic;+ out->key_mode = f.keyMode;+ out->key_confidence = f.keyConfidence;+ out->tail_ratio = f.tailRatio;+ out->peak_db = f.peakDb;+ out->rms_db = f.rmsDb;+ std::copy(f.timbre.begin(), f.timbre.end(), out->timbre);+}+} // namespace+extern "C" {NotaAudioImport* nota_audio_import_open(const char* path) {@@ -59,4 +78,27 @@ double nota_clip_auto_warp_bpm(NotaEngine* e, int32_t track_id, int32_t clip_indreturn e ? ENG(e)->autoWarpClip(track_id, clip_index, bpm) : 0.0;}++NotaResult nota_audio_import_analyze(const NotaAudioImport* job, NotaSampleAnalysis* out) {+ if (!job || !out || !CJOB(job)->done() || !CJOB(job)->buffer()) return NOTA_ERR_INVALID_ARG;+ const auto& b = *CJOB(job)->buffer();+ fillAnalysis(b, b.frames, static_cast<double>(b.frames), out);+ return NOTA_OK;+}++NotaResult nota_sample_analyze_file(const char* path, double max_seconds, NotaSampleAnalysis* out) {+ if (!path || !out) return NOTA_ERR_INVALID_ARG;+ // Only the head is decoded (and allocated): a long file costs max_seconds, not its length.+ auto job = nota::AudioImportJob::open(std::string(path), max_seconds);+ if (!job || !job->buffer()) return NOTA_ERR_INVALID_ARG;+ while (!job->done())+ if (job->step(1 << 17) < 0) return NOTA_ERR_INVALID_ARG;+ const auto& b = *job->buffer();+ if (b.frames <= 0) return NOTA_ERR_INVALID_ARG;+ // Uncapped (or a truncated file): what decoded is the file; capped: the header's length.+ const bool capped = b.frames < job->sourceFrames() && job->decodedFrames() >= b.frames;+ fillAnalysis(b, b.frames, static_cast<double>(capped ? job->sourceFrames() : b.frames), out);+ return NOTA_OK;+}+} // extern "C"diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex b7e60f08..737900cd 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -116,6 +116,15 @@ if (args.Length >= 1 && args[0] == "--samples")Console.WriteLine(failures == 0 ? "SAMPLES PASSED" : $"SAMPLES FAILED ({failures})");return failures == 0 ? 0 : 1;}+if (args.Length >= 2 && args[0] == "--sample-dump") { SmartSampleTests.Dump(args[1]); return 0; }+// Smart samples (key / tempo / loop analysis, the library index) alone: `--smart-samples`.+if (args.Length >= 1 && args[0] == "--smart-samples")+{+ Console.WriteLine("-- smart samples: analysis + library index --");+ foreach (var (ok, label) in SmartSampleTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "SMART SAMPLES PASSED" : $"SMART SAMPLES FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// AI models store alone: `--models`.if (args.Length >= 1 && args[0] == "--models"){@@ -13650,6 +13659,10 @@ foreach (var (ok, label) in PluginStoreTests.Run()) Check(ok, label);Console.WriteLine("-- get samples: sample registry store --");foreach (var (ok, label) in SampleStoreTests.Run()) Check(ok, label);+// --- smart samples: tempo / key / loop analysis, the library index, filters, similar ---+Console.WriteLine("-- smart samples: analysis + library index --");+foreach (var (ok, label) in SmartSampleTests.Run()) Check(ok, label);+// --- ai models: model + runtime install/uninstall from local assets ---Console.WriteLine("-- ai models: store --");foreach (var (ok, label) in ModelStoreTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/SmartSampleTests.cs b/tests/Nota.SmokeTest/SmartSampleTests.csnew file mode 100644index 00000000..45737e98--- /dev/null+++ b/tests/Nota.SmokeTest/SmartSampleTests.cs@@ -0,0 +1,316 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Smart samples: key math, what file names say (tempo / key / loop or one-shot), the+// classifier, the engine's analysis on generated audio (chord loops in known keys at known+// tempos, a kick, a plucked note, a hi-hat loop), and the library index end to end — scan,+// persistence, filters and "similar sounds". Also runnable alone:+// `dotnet run --project tests/Nota.SmokeTest -- --smart-samples`.++using Nota.Application;+using Nota.Application.Samples;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class SmartSampleTests+{+ private const int Sr = 44100;++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ foreach (var r in KeyMath()) yield return r;+ foreach (var r in NameHints()) yield return r;+ foreach (var r in Classifier()) yield return r;+ foreach (var r in EngineAndIndex()) yield return r;+ }++ /// <summary>`--sample-dump <folder>`: indexes a real library into a throwaway index and+ /// prints what it made of every file — for eyeballing the classifier on actual packs.</summary>+ public static void Dump(string folder)+ {+ var file = Path.Combine(Path.GetTempPath(), "nota-sample-dump-" + Guid.NewGuid().ToString("N")[..8] + ".bin");+ var index = new SampleLibraryIndex(new SampleAnalyzer(), file);+ var done = new ManualResetEventSlim();+ var sw = System.Diagnostics.Stopwatch.StartNew();+ index.Changed += () => { var (d, t) = index.Progress; if (t == 0) done.Set(); else Console.Error.Write($"\r{d}/{t}"); };+ index.Watch(folder);+ done.Wait();+ Console.Error.WriteLine($"\rindexed in {sw.Elapsed.TotalSeconds:0.0} s");+ foreach (var s in index.Search(SampleFilter.Empty, null, int.MaxValue))+ Console.WriteLine($"{Path.GetRelativePath(folder, s.Path),-70} {s.Kind,-8} {s.KindSource,-8} {s.Tag,-12} {s.Describe()}");+ index.Dispose();+ File.Delete(file);+ }++ // ---- key math ------------------------------------------------------------------------------++ private static IEnumerable<(bool, string)> KeyMath()+ {+ var am = MusicalKey.Parse("Am")!.Value;+ var c = MusicalKey.Parse("C major")!.Value;+ yield return (am == new MusicalKey(9, KeyMode.Minor) && c == new MusicalKey(0, KeyMode.Major)+ && MusicalKey.Parse("f#min") == new MusicalKey(6, KeyMode.Minor) && MusicalKey.Parse("Bb") == new MusicalKey(10, KeyMode.Major)+ && MusicalKey.Parse("Ebm") == new MusicalKey(3, KeyMode.Minor) && MusicalKey.Parse("H") is null,+ "keys parse from the usual spellings");+ yield return (am.Short == "Am" && am.Long == "A minor" && new MusicalKey(1, KeyMode.Minor).Short == "C#m"+ && new MusicalKey(1, KeyMode.Major).Short == "Db" && new MusicalKey(6, KeyMode.Note).Long == "F#",+ "…and print the way packs spell them");+ yield return (am.Relative == c && c.Relative == am && am.FitsIn(c) && c.FitsIn(am) && !am.FitsIn(new MusicalKey(9, KeyMode.Major)),+ "a key fits itself and its relative, not its parallel");+ yield return (am.SemitonesTo(c) == 0 && am.SemitonesTo(new MusicalKey(11, KeyMode.Minor)) == 2+ && c.SemitonesTo(new MusicalKey(7, KeyMode.Major)) == -5 && am.SemitonesTo(new MusicalKey(2, KeyMode.Major)) == 2+ && new MusicalKey(5, KeyMode.Note).SemitonesTo(c) == -5,+ "transposing to a key takes the short way, via the relative across modes");+ yield return (MusicalKey.All.Count == 24 && MusicalKey.All.All(k => MusicalKey.FromCode(k.Code) == k) && MusicalKey.FromCode(-1) is null,+ "the 24 keys round-trip through their codes");+ }++ // ---- file names --------------------------------------------------------------------------++ private static IEnumerable<(bool, string)> NameHints()+ {+ var root = Path.Combine(Path.GetTempPath(), "lib");+ SampleNameHints H(string rel) => SampleNameHints.Parse(Path.Combine(root, rel), root);++ var a = H("Deep House/Loops/DH_Loop_124_Am.wav");+ yield return (a.Bpm == 124 && !a.BpmExplicit && a.Key == new MusicalKey(9, KeyMode.Minor) && a.NameKind == SampleKind.Loop,+ "\"DH_Loop_124_Am\": a loop at 124 in A minor");+ var b = H("Pads/Warm Pad C#m 90bpm.flac");+ yield return (b.Bpm == 90 && b.BpmExplicit && b.Key == new MusicalKey(1, KeyMode.Minor),+ "\"Warm Pad C#m 90bpm\": tempo written with bpm, sharp minor key");+ var c = H("Bass/bass_bpm128_F_minor.wav");+ yield return (c.Bpm == 128 && c.BpmExplicit && c.Key == new MusicalKey(5, KeyMode.Minor), "\"bpm128 … F minor\": words across tokens");+ var d = H("Drums/One Shots/Kick A.wav");+ yield return (d.Key is null && d.FolderKind == SampleKind.OneShot && d.DrumWord && d.Bpm == 0,+ "\"One Shots/Kick A\": a one-shot folder, and a take letter is not a key");+ var e = H("Keys/Piano_F#3_soft.wav");+ yield return (e.Key == new MusicalKey(6, KeyMode.Note), "\"Piano_F#3\": a note with its octave is a pitch");+ var f = H("Synth/Stab Cmaj7 120.wav");+ yield return (f.Key == new MusicalKey(0, KeyMode.Major) && f.Bpm == 120, "\"Stab Cmaj7 120\": a chord names its key");+ var g = H("Loops/Snare_Roll_01.wav");+ yield return (g.Bpm == 0 && g.Key is null && g.FolderKind == SampleKind.Loop, "a take number is not a tempo");+ var h = H("Guitar/Riff_E_95.wav");+ yield return (h.Key == new MusicalKey(4, KeyMode.Major) && h.Bpm == 95, "a lone letter next to the tempo is a key");+ var i = H("Vox/i am here.wav");+ yield return (i.Key is null, "lowercase words aren't keys");+ }++ // ---- classifier --------------------------------------------------------------------------++ private static IEnumerable<(bool, string)> Classifier()+ {+ static SampleAnalysis A(double dur, double bpm, int tonic = -1, int mode = -1, float conf = 0, float tail = 1)+ => new(dur, Sr, 2, bpm, tonic, mode, conf, tail, -3, -12, new float[SampleAnalysis.TimbreDims]);++ yield return (SampleClassifier.LoopFit(7.742, 123.5) == 124 && SampleClassifier.LoopFit(8.0, 60.5) == 120+ && SampleClassifier.LoopFit(8.0, 97) == 0 && SampleClassifier.LoopFit(0.5, 120) == 0,+ "a loop's tempo comes from its length: whole beats near the heard pulse (an octave either way)");++ var loop = SampleClassifier.Classify("/x/thing.wav", SampleNameHints.None, A(7.742, 123.5, 9, 1, 0.8f));+ yield return (loop is { Kind: SampleKind.Loop, Bpm: 124, BpmSource: SampleFactSource.Duration } && loop.Key == new MusicalKey(9, KeyMode.Minor),+ "an unnamed 16-beat file with a pulse is a loop, at the exact tempo, with its heard key");+ var named = SampleClassifier.Classify("/x/Loop_126_Gm.wav", SampleNameHints.Parse("/x/Loop_126_Gm.wav"), A(7.62, 124, 0, 0, 0.9f));+ yield return (named.Bpm == 126 && named.BpmSource == SampleFactSource.Name && named.Key == new MusicalKey(7, KeyMode.Minor),+ "the name's tempo and key beat what the analysis heard");+ var hit = SampleClassifier.Classify("/x/thing2.wav", SampleNameHints.None, A(0.45, 130, 5, 0, 0.8f, tail: 0.01f));+ yield return (hit is { Kind: SampleKind.OneShot, Bpm: 0 } && hit.Key == new MusicalKey(5, KeyMode.Note),+ "a short hit is a one-shot: no tempo, and its pitch is a note, not a key");+ var tail = SampleClassifier.Classify("/x/boom.wav", SampleNameHints.None, A(3.1, 110, tail: 0.02f));+ yield return (tail.Kind == SampleKind.OneShot && tail.Bpm == 0, "a sound that rings out to silence is a one-shot, however long");+ var song = SampleClassifier.Classify("/x/take.wav", SampleNameHints.None, A(47.3, 97));+ yield return (song is { Kind: SampleKind.Unknown, Bpm: 97, BpmSource: SampleFactSource.Audio },+ "a long recording that isn't a loop length keeps its heard tempo but stays unclassified");+ var bare = SampleClassifier.Classify("/x/Riser 95.wav", SampleNameHints.Parse("/x/Riser 95.wav"), A(5.3, 0, tail: 0.5f));+ yield return (bare.Bpm == 0, "a bare number the audio doesn't back up is not a tempo");++ var f = new SampleFilter(SampleKind.Loop, 120, 128, new MusicalKey(0, KeyMode.Major));+ yield return (f.Matches(loop with { Key = new MusicalKey(9, KeyMode.Minor) }) && !f.Matches(loop with { Bpm = 130 })+ && !f.Matches(hit) && !f.Matches(null) && SampleFilter.Empty.Matches(null) && f.BpmCaption == "120–128",+ "the filter: kind, inclusive BPM range, key with its relative; unanalysed files only pass the empty filter");+ yield return (loop.Tag == "124 · Am" && hit.Tag == "F" && loop.Describe().StartsWith("124\u2009BPM · A minor · loop", StringComparison.Ordinal),+ "rows show \"124 · Am\"; a hit shows its note");+ }++ // ---- engine analysis + index ----------------------------------------------------------------++ private static IEnumerable<(bool, string)> EngineAndIndex()+ {+ var dir = Path.Combine(Path.GetTempPath(), "nota-smart-samples-" + Guid.NewGuid().ToString("N")[..8]);+ var lib = Path.Combine(dir, "Samples");+ Directory.CreateDirectory(Path.Combine(lib, "Pack", "Loops"));+ Directory.CreateDirectory(Path.Combine(lib, "Pack", "Hits"));+ try+ {+ string cLoop = Path.Combine(lib, "Pack", "Loops", "keys_a.wav");+ string amLoop = Path.Combine(lib, "Pack", "Loops", "keys_b.wav");+ string hats = Path.Combine(lib, "Pack", "Loops", "tops.wav");+ string kick = Path.Combine(lib, "Pack", "Hits", "low_1.wav");+ string kick2 = Path.Combine(lib, "Pack", "Hits", "low_2.wav");+ string pluck = Path.Combine(lib, "Pack", "Hits", "pluck.wav");+ Write(cLoop, ChordLoop(120, new[] { new[] { 0, 4, 7 }, new[] { 5, 9, 0 }, new[] { 7, 11, 2 }, new[] { 0, 4, 7 } }, 48));+ Write(amLoop, ChordLoop(124, new[] { new[] { 9, 0, 4 }, new[] { 2, 5, 9 }, new[] { 4, 8, 11 }, new[] { 9, 0, 4 } }, 45));+ Write(hats, HatLoop(128, 4));+ Write(kick, Kick(150, 48, 0.45));+ Write(kick2, Kick(140, 45, 0.5));+ Write(pluck, Pluck(54, 0.9)); // F#3++ var analyzer = new SampleAnalyzer();+ var ac = analyzer.Analyze(cLoop, 60);+ yield return (ac is not null && Math.Abs(ac.DurationSec - 8.0) < 0.01 && ac.KeyTonic == 0 && ac.KeyMode == 0,+ $"engine: a I–IV–V–I loop is heard in C major (tonic {ac?.KeyTonic}, mode {ac?.KeyMode}, r {ac?.KeyConfidence:0.00})");+ var aa = analyzer.Analyze(amLoop, 60);+ yield return (aa is not null && aa.KeyTonic == 9 && aa.KeyMode == 1,+ $"engine: an i–iv–V–i loop is heard in A minor (tonic {aa?.KeyTonic}, mode {aa?.KeyMode}, r {aa?.KeyConfidence:0.00})");+ var ah = analyzer.Analyze(hats, 60);+ yield return (ah is not null && ah.KeyTonic < 0 && ah.Bpm > 0,+ $"engine: a hi-hat loop has a pulse ({ah?.Bpm:0.0}) and no key (tonic {ah?.KeyTonic})");+ var ak = analyzer.Analyze(kick, 60);+ yield return (ak is not null && ak.TailRatio < 0.12 && ak.Timbre.Length == SampleAnalysis.TimbreDims,+ $"engine: a kick rings out (tail {ak?.TailRatio:0.000}) and has a timbre fingerprint");+ var ap = analyzer.Analyze(pluck, 60);+ yield return (ap is not null && ap.KeyTonic == 6,+ $"engine: a plucked F#3 is heard as F# (tonic {ap?.KeyTonic}, mode {ap?.KeyMode})");+ var head = analyzer.Analyze(cLoop, 2);+ yield return (head is not null && Math.Abs(head.DurationSec - 8.0) < 0.01 && head.Timbre[15] < 1.5,+ "engine: analysing only the head still reports the whole file's length");++ // The index, end to end.+ string file = Path.Combine(dir, "index.bin");+ var index = new SampleLibraryIndex(analyzer, file);+ var done = new ManualResetEventSlim();+ index.Changed += () => { if (index.Progress.Total == 0 && index.Get(pluck) is not null) done.Set(); };+ index.Watch(lib);+ bool finished = done.Wait(TimeSpan.FromSeconds(60));+ yield return (finished && index.Progress == (0, 0), "index: a scan of the library finishes");++ var ic = index.Get(cLoop);+ yield return (ic is { Kind: SampleKind.Loop, Bpm: 120, KindSource: SampleFactSource.Folder } && ic.Key == new MusicalKey(0, KeyMode.Major),+ $"index: the C loop — a loop (its folder), 120 BPM (its length), C major [{ic?.Tag}]");+ var ia = index.Get(amLoop);+ yield return (ia is { Bpm: 124 } && ia.Key == new MusicalKey(9, KeyMode.Minor), $"index: the A minor loop at 124 [{ia?.Tag}]");+ var ih = index.Get(hats);+ yield return (ih is { Kind: SampleKind.Loop, Bpm: 128, Key: null }, $"index: the hats at 128, no key [{ih?.Tag}]");+ var ik = index.Get(kick);+ yield return (ik is { Kind: SampleKind.OneShot, Bpm: 0 }, $"index: the kick is a one-shot [{ik?.Describe()}]");+ var ip = index.Get(pluck);+ yield return (ip is { Kind: SampleKind.OneShot } && ip.Key == new MusicalKey(6, KeyMode.Note), $"index: the pluck is an F# one-shot [{ip?.Tag}]");++ var loops = index.Search(new SampleFilter(SampleKind.Loop, 120, 125), null, 100).Select(s => s.Path).ToList();+ yield return (loops.Count == 2 && loops.Contains(cLoop) && loops.Contains(amLoop), "index: \"loops · 120–125\" finds the two chord loops");+ var inC = index.Search(new SampleFilter(Key: new MusicalKey(0, KeyMode.Major)), null, 100).Select(s => s.Path).ToList();+ yield return (inC.Count == 2 && inC.Contains(amLoop), "index: \"C major\" also finds its relative, the A minor loop");+ var sim = index.Similar(kick, 3);+ yield return (sim.Count >= 1 && sim[0].Info.Path == kick2, $"index: the sound most like a kick is the other kick ({Path.GetFileName(sim.FirstOrDefault().Info?.Path ?? "-")})");+ yield return (sim.All(x => x.Info.Kind != SampleKind.Loop), "index: …and no loop is \"like\" a hit");++ index.Dispose();+ var reopened = new SampleLibraryIndex(new NoAnalyzer(), file);+ reopened.Watch(lib);+ var again = reopened.Get(amLoop);+ reopened.Dispose();+ yield return (again is { Bpm: 124 }, "index: results persist — a new session knows the library without analysing it again");++ File.AppendAllText(hats, "x"); // changed on disk → stale+ var re = new SampleLibraryIndex(analyzer, file);+ var fresh = re.GetOrAnalyze(hats);+ re.Dispose();+ yield return (fresh is { Bpm: 128 }, "index: a changed file is analysed again");+ }+ finally+ {+ try { Directory.Delete(dir, recursive: true); } catch (IOException) { }+ }+ }++ private sealed class NoAnalyzer : ISampleAnalyzer+ {+ public SampleAnalysis? Analyze(string path, double maxSeconds) => null;+ }++ // ---- generated audio -------------------------------------------------------------------------++ private static double Hz(int midi) => 440.0 * Math.Pow(2, (midi - 69) / 12.0);++ // Four bars of 4/4: one chord per bar (pitch classes, voiced around C4, the root also in+ // the bass), decaying saw-ish stabs on every beat, a click on each beat for the pulse.+ private static float[] ChordLoop(double bpm, int[][] bars, int bassBase)+ {+ double beat = 60.0 / bpm;+ int frames = (int)Math.Round(16 * beat * Sr);+ var x = new float[frames];+ for (int b = 0; b < 16; b++)+ {+ var chord = bars[b / 4];+ int start = (int)Math.Round(b * beat * Sr);+ int len = (int)(beat * Sr);+ foreach (var pc in chord)+ AddTone(x, start, len, Hz(60 + pc), 0.12, decay: 2.5, partials: 5);+ AddTone(x, start, len, Hz(bassBase + (chord[0] + 12 - bassBase % 12) % 12), 0.18, decay: 2.0, partials: 3);+ for (int i = 0; i < 200 && start + i < frames; i++) x[start + i] += (float)(0.5 * Math.Exp(-i / 30.0) * (i % 2 == 0 ? 1 : -1));+ }+ return x;+ }++ private static float[] HatLoop(double bpm, int bars)+ {+ var rng = new Random(7);+ double eighth = 30.0 / bpm;+ int frames = (int)Math.Round(bars * 8 * eighth * Sr);+ var x = new float[frames];+ for (int k = 0; k < bars * 8; k++)+ {+ int start = (int)Math.Round(k * eighth * Sr);+ double amp = k % 2 == 0 ? 0.6 : 0.3;+ for (int i = 0; i < Sr / 20 && start + i < frames; i++)+ x[start + i] += (float)(amp * (rng.NextDouble() * 2 - 1) * Math.Exp(-i / (Sr * 0.012)));+ }+ return x;+ }++ private static float[] Kick(double f0, double f1, double seconds)+ {+ int frames = (int)(seconds * Sr);+ var x = new float[frames];+ double phase = 0;+ for (int i = 0; i < frames; i++)+ {+ double t = (double)i / Sr;+ double f = f1 + (f0 - f1) * Math.Exp(-t * 30);+ phase += 2 * Math.PI * f / Sr;+ x[i] = (float)(0.9 * Math.Sin(phase) * Math.Exp(-t * 9));+ }+ return x;+ }++ private static float[] Pluck(int midi, double seconds)+ {+ var x = new float[(int)(seconds * Sr)];+ AddTone(x, 0, x.Length, Hz(midi), 0.5, decay: 5, partials: 6);+ return x;+ }++ private static void AddTone(float[] x, int start, int len, double hz, double amp, double decay, int partials)+ {+ for (int i = 0; i < len && start + i < x.Length; i++)+ {+ double t = (double)i / Sr, s = 0;+ for (int p = 1; p <= partials; p++) s += Math.Sin(2 * Math.PI * hz * p * t) / p;+ double attack = Math.Min(1.0, i / (0.004 * Sr));+ x[start + i] += (float)(amp * s * attack * Math.Exp(-t * decay));+ }+ }++ private static void Write(string path, float[] x)+ {+ float peak = x.Max(v => Math.Abs(v));+ float g = peak > 0.95f ? 0.95f / peak : 1f;+ using var w = new BinaryWriter(File.Create(path));+ int bytes = x.Length * 2;+ w.Write("RIFF"u8.ToArray()); w.Write(36 + bytes); w.Write("WAVE"u8.ToArray());+ w.Write("fmt "u8.ToArray()); w.Write(16); w.Write((short)1); w.Write((short)1);+ w.Write(Sr); w.Write(Sr * 2); w.Write((short)2); w.Write((short)16);+ w.Write("data"u8.ToArray()); w.Write(bytes);+ foreach (var v in x) w.Write((short)Math.Clamp(v * g * short.MaxValue, short.MinValue, short.MaxValue));+ }+}