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
Audio async loading, fix sc names
Egor Khindikaynen243d26e8613d
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex cd9f5a35..98d1211c 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -145,6 +145,12 @@ referenced samples into `samples/` and plugin state blobs into `plugin-states/`,writes `project.json` atomically (temp file + rename) with an auto-backup. Loadingreplays the document through the same structural-edit operations the UI uses.+`analysis/` holds a cache of imported audio — each file's waveform overview (min/max per+512 frames) and detected tempo, as `<content fingerprint>.npk` — so re-importing a file+is instant. It is disposable: delete it and entries are rebuilt on the next import. While+a project is unsaved the entries are staged in the per-user data folder and copied in on+the first save (`AudioAnalysisCache`).+See `Nota.Infrastructure/Persistence/ProjectService.cs`.## UIdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 738b054b..c1b4cb53 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,15 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.check the output, and **CPU check** measures the audio load for 5 seconds and tells youwhether the current buffer size leaves enough headroom. The test tone now fades in and outinstead of clicking.+- **Importing audio no longer freezes the app.** A dropped or imported file (WAV, FLAC,+ MP3) shows up at once as a greyed-out **Processing…** track whose waveform fills in as+ the file loads; tempo detection and warping run in the background, and when it's done+ the track takes its colours and is selected. Deleting the track while it's processing+ cancels the import. Long clips also draw faster when you move or trim them.+- **Analysis cache in the project folder.** Nota remembers each imported file's waveform+ and tempo in the project's `analysis/` folder (not next to your audio, as `.asd` files+ are), so importing the same file again shows its whole waveform right away and skips+ tempo detection.### Changed- The audio engine now has its own version (starting at 0.2.5, shown in About) instead of a@@ -30,6 +39,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.- Record and Metronome now need ⌘ / Ctrl: **⌘R** toggles Record and **⌘M** the metronome, sobare R and M no longer flip them by accident while you play. The Mixer moves to **⌘⇧M**.+### Fixed+- Sidechain and source pickers on devices (Compressor, Dynamic EQ-8, Ceiling, Shutter,+ Auto Filter, Auto Shift, Level, Prism, plugins with a sidechain input) and the Mixer's MIDI+ source list now name tracks the same way as the arrangement — e.g. an instrument track you+ haven't renamed shows its instrument's name instead of "Track 2" or "2 · Audio".+## [0.41.0] — 2026-09-24### Highlightsdiff --git a/src/managed/Nota.App/ArrangementView.Imports.cs b/src/managed/Nota.App/ArrangementView.Imports.csnew file mode 100644index 00000000..b8d4f258--- /dev/null+++ b/src/managed/Nota.App/ArrangementView.Imports.cs@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Audio files being imported in the background (MainWindow.AudioImport). Until the decode+// lands, the arrangement shows a placeholder clip whose waveform fills in block by block;+// a track created for the import is drawn translucent and titled "Processing…" until the+// whole import (decode + warp) has finished.++using System.Collections.Generic;++namespace Nota.App;++public sealed partial class ArrangementView+{+ /// <summary>One in-flight import, owned by the importer and read by the lanes.</summary>+ internal sealed class PendingImport+ {+ public int TrackId;+ /// <summary>The track was created for this import → the whole row is "processing".</summary>+ public bool OwnsTrack;+ public double StartBeat;+ public double LengthBeats;+ /// <summary>Waveform so far: (min,max) pairs; (1,-1) buckets are not decoded yet.</summary>+ public float[]? Peaks;+ public int PeakCount;+ public string Label = "";+ /// <summary>The real clip is on the track (now warping): stop drawing the placeholder.</summary>+ public bool ClipPlaced;+ }++ private readonly List<PendingImport> _pendingImports = new();++ internal void AddPendingImport(PendingImport p)+ {+ _pendingImports.Add(p);+ Refresh();+ }++ /// <summary>Repaint after the importer changed a pending entry (new peaks / label). Lanes+ /// only — no engine read — so it's cheap enough for every decoded block.</summary>+ internal void UpdatePendingImport() => _lanes.InvalidateVisual();++ internal void RemovePendingImport(PendingImport p)+ {+ if (_pendingImports.Remove(p)) Refresh();+ }++ /// <summary>Forget every placeholder (New/Open: the in-flight imports belong to the old+ /// graph and bow out on their own). The caller refreshes.</summary>+ internal void ClearPendingImports() => _pendingImports.Clear();++ internal bool IsProcessingTrack(int trackId)+ {+ foreach (var p in _pendingImports) if (p.OwnsTrack && p.TrackId == trackId) return true;+ return false;+ }++ // Placeholder clips on a track, as throwaway VMs the normal clip painter can draw. Not in+ // TrackVM.Clips, so they're never hit-tested, selected or sent to the engine.+ private IEnumerable<ClipVM> PendingClipsFor(int trackId)+ {+ foreach (var p in _pendingImports)+ if (p.TrackId == trackId && !p.ClipPlaced && p.LengthBeats > 0)+ yield return new ClipVM+ {+ ClipIndex = -1, StartBeat = p.StartBeat, LengthBeats = p.LengthBeats,+ Peaks = p.Peaks, PeakCount = p.PeakCount, Name = p.Label,+ };+ }+}diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex f788c491..ea3d63c6 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -1057,15 +1057,21 @@ public sealed partial class ArrangementViewDrawGroupLane(ctx, _o._tracks[i], y, rh, w, _o.IsGroupCollapsed(tid));continue;}- foreach (var c in _o._tracks[i].Clips)- {- if (IsDraggingCrossTrack(tid, c.ClipIndex)) continue;- // Highlight the edge a resize would grab (hover), or the edge actively being trimmed.- var edgeHi = Drag.None;- if (_hoverEdge != Drag.None && _hoverEdgeTrack == tid && _hoverEdgeClip == c.ClipIndex) edgeHi = _hoverEdge;- else if ((_drag == Drag.TrimL || _drag == Drag.TrimR) && _dragTrackId == tid && _dragClipIndex == c.ClipIndex) edgeHi = _drag;- DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, _o.IsSelected(tid, c.ClipIndex), edgeHi);- }+ // A track still being filled by a background import reads as translucent.+ using (ctx.PushOpacity(_o.IsProcessingTrack(tid) ? 0.5 : 1.0))+ foreach (var c in _o._tracks[i].Clips)+ {+ if (IsDraggingCrossTrack(tid, c.ClipIndex)) continue;+ // Highlight the edge a resize would grab (hover), or the edge actively being trimmed.+ var edgeHi = Drag.None;+ if (_hoverEdge != Drag.None && _hoverEdgeTrack == tid && _hoverEdgeClip == c.ClipIndex) edgeHi = _hoverEdge;+ else if ((_drag == Drag.TrimL || _drag == Drag.TrimR) && _dragTrackId == tid && _dragClipIndex == c.ClipIndex) edgeHi = _drag;+ DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, _o.IsSelected(tid, c.ClipIndex), edgeHi);+ }+ // Imports still decoding: a translucent placeholder whose waveform fills in.+ using (ctx.PushOpacity(0.5))+ foreach (var c in _o.PendingClipsFor(tid))+ DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, false);}// In-progress audio take (M-fix): audio clips only materialise on stop,diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex ce672b4f..46a01c3e 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -582,18 +582,6 @@ public sealed partial class ArrangementView : UserControl}}- // Instrument tracks show their instrument (plugin) name; audio/return use a default.- private static string TrackDisplayName(IAudioEngine eng, int id, bool isInstrument, bool isReturn)- {- if (isReturn) return $"Return {eng.TrackReturnIndex(id) + 1}";- if (isInstrument)- {- string inst = eng.DeviceName(id, -1); // Synth / Sampler / plugin name- return string.IsNullOrWhiteSpace(inst) ? "Inst " + id : inst;- }- return "Audio " + id;- }-private void Zoom(double factor){_pixelsPerBeat = Math.Clamp(_pixelsPerBeat * factor, 4, 240);@@ -666,8 +654,6 @@ public sealed partial class ArrangementView : UserControlif (!eng.TryGetTrackInfo(i, out var ti)) continue;// Stored colour (set via the header menu) wins; otherwise auto by position.int effColor = EffectiveColorIndex(eng, ti.Id);- // A stored name (set via the header menu) wins; otherwise the derived default.- string storedName = eng.GetTrackName(ti.Id);var tvm = new TrackVM{Id = ti.Id,@@ -681,9 +667,8 @@ public sealed partial class ArrangementView : UserControlArmed = ti.Armed != 0,Frozen = !ti.IsReturn && !ti.IsGroup && eng.IsTrackFrozen(ti.Id), // M7LiveRole = FreezeRole?.Invoke(ti.Id) ?? 0, // live-freeze (v1.1)- Name = storedName.Length > 0 ? storedName- : ti.IsGroup ? "Group"- : TrackDisplayName(eng, ti.Id, ti.IsInstrument, ti.IsReturn),+ // A stored name (set via the header menu) wins; otherwise the derived default.+ Name = IsProcessingTrack(ti.Id) ? "Processing…" : TrackNames.Of(eng, ti),Volume = ti.Volume,Pan = ti.Pan,};@@ -1621,6 +1606,9 @@ public sealed partial class ArrangementView : UserControlBorderThickness = new Thickness(0, 0, 1, 1),Child = grid,};+ // A background import is still filling the track: the disabled look (by colour, not+ // opacity), still clickable so the track can be deleted to cancel.+ if (IsProcessingTrack(t.Id)) card.AttachedToVisualTree += (_, _) => Inactive.Set(card, true, interactive: true);_headerCards[t.Id] = (card, name, t.IsGroup, spine, spineBrush); // for in-place selection repaintif (selected) spine.Background = NotaPalette.Accent;AttachHeaderGestures(card, t);diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.csindex a9a8deda..b1aec90f 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoFilterDeviceBody.cs@@ -463,13 +463,7 @@ internal sealed class AutoFilterDeviceBody : IDeviceBodyint centreTab = 0;// Sidechain key: the switch picks a source (a flyout with the tracks and the key gain).- string SrcName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }- return "—";- }+ string SrcName(int id) => TrackNames.Of(engine, id);Control SidechainSwitch(){Border? host = null;diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.csindex 07a16843..0c1ab5d4 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoGainDeviceBody.cs@@ -68,13 +68,7 @@ internal sealed class AutoGainDeviceBody : IDeviceBodydouble MaxG() => MaxGainDb(P(MaxGain));// ---- reference track (the device's sidechain) ---------------------------------------- string TrackName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }- return "—";- }+ string TrackName(int id) => TrackNames.Of(engine, id);int Ref() => engine.DeviceSidechainSource(track, di);bool HasRef() => Ref() >= 0;diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.csindex b0d8a009..f2055b03 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoShiftDeviceBody.cs@@ -126,13 +126,7 @@ internal sealed class AutoShiftDeviceBody : IDeviceBody// Key-source MIDI track: the sidechain source slot.int MidiSrc() => engine.DeviceSidechainSource(track, di);- string TrackName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }- return "—";- }+ string TrackName(int id) => TrackNames.Of(engine, id);string MidiSrcName() => MidiSrc() >= 0 ? TrackName(MidiSrc()) : "none";// Key change: a Custom scale moves with its tonic.diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.csindex a1bc6ab1..e80b35f3 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/CeilingDeviceBody.cs@@ -251,13 +251,7 @@ internal sealed class CeilingDeviceBody : IDeviceBody}// Key source: Internal, or another track (the device's sidechain routing).- string SrcName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }- return "—";- }+ string SrcName(int id) => TrackNames.Of(engine, id);int Src() => engine.DeviceSidechainSource(track, di);bool ExtOn() => Src() >= 0;string KeyName() => ExtOn() ? SrcName(Src()) : "Internal";diff --git a/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.csindex f4bc5b3c..03c4b32b 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/CompressorDeviceBody.cs@@ -357,7 +357,7 @@ internal sealed class CompressorDeviceBody : IDeviceBody{if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;srcIds.Add(ti.Id);- srcNames.Add(NotaNum.F($"{i + 1} · {(ti.IsReturn ? "Return" : ti.IsInstrument ? "Instr" : "Audio")}"));+ srcNames.Add(TrackNames.Of(engine, ti));}string SourceName() { int k = srcIds.IndexOf(engine.DeviceSidechainSource(track, di)); return k > 0 ? srcNames[k] : "Internal"; }bool ExtActive() => Sc(S_ExtKey) > 0.5;diff --git a/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.csindex f5aac997..1e65b182 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/DynamicEqDeviceBody.cs@@ -85,13 +85,7 @@ internal sealed class DynamicEqDeviceBody : IDeviceBodystatic T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }// Key source: the device's sidechain routing (a track), picked from a menu.- string SrcName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }- return "—";- }+ string SrcName(int id) => TrackNames.Of(engine, id);int Src() => engine.DeviceSidechainSource(track, di);void ShowKeyMenu(Control at){diff --git a/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.csindex e404eded..30061ab4 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/PrismDeviceBody.cs@@ -511,13 +511,7 @@ internal sealed class PrismDeviceBody : IDeviceBody// Sidechain source (None + every other track).var scName = new TextBlock { FontSize = 8, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };bool scOk = engine.DeviceAcceptsSidechain(track, di);- string SrcName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : Inv($"Track {i + 1}"); }- return "None";- }+ string SrcName(int id) { string n = TrackNames.Of(engine, id); return n == "—" ? "None" : n; }readouts.Add(() =>{int src = scOk ? engine.DeviceSidechainSource(track, di) : -1;@@ -659,7 +653,7 @@ internal sealed class PrismDeviceBody : IDeviceBody{var autos = Enumerable.Range(0, 3).Where(b => BandActive(b) && On(BP(b, AutoRelease))).Select(b => PrismInk.Names[b]).ToList();int src = engine.DeviceAcceptsSidechain(track, di) ? engine.DeviceSidechainSource(track, di) : -1;- string sc = src >= 0 ? "sidechain: " + engine.GetTrackName(src) : "own input";+ string sc = src >= 0 ? "sidechain: " + TrackNames.Of(engine, src) : "own input";return Inv($"{(On(Detect) ? "RMS" : "Peak")} detector · {(autos.Count > 0 ? "auto release on " + string.Join(", ", autos) : "fixed release")} · {sc}");}default:diff --git a/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.csindex f68fd30e..4ffc567d 100644--- a/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Bodies/ShutterDeviceBody.cs@@ -104,13 +104,7 @@ internal sealed class ShutterDeviceBody : IDeviceBodyint State() => Math.Clamp((int)Math.Round(Sc(S_State)), 0, 4);// Sidechain key: the source track and whether it is in use.- string SrcName(int id)- {- for (int i = 0; i < engine.TrackCount; i++)- if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == id)- { string n = engine.GetTrackName(id); return n.Length > 0 ? n : NotaNum.F($"Track {i + 1}"); }- return "—";- }+ string SrcName(int id) => TrackNames.Of(engine, id);int Src() => engine.DeviceSidechainSource(track, di);bool ExtOn() => On(ExternalKey) && Src() >= 0;string KeyName() => ExtOn() ? SrcName(Src()) : "Internal";diff --git a/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs b/src/managed/Nota.App/DeviceCards/DeviceParamControls.csindex 3baf59fa..732f2c25 100644--- a/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs+++ b/src/managed/Nota.App/DeviceCards/DeviceParamControls.cs@@ -83,9 +83,8 @@ internal static class DeviceParamControlsfor (int i = 0; i < n; i++){if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == track) continue;- string kind = ti.IsReturn ? "Return" : ti.IsInstrument ? "Instrument" : "Audio";ids.Add(ti.Id);- combo.Items.Add($"{i + 1} · {kind}");+ combo.Items.Add(TrackNames.Of(engine, ti));}combo.SelectedIndex = Math.Max(0, ids.IndexOf(engine.DeviceSidechainSource(track, di)));combo.SelectionChanged += (_, _) =>diff --git a/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.csindex 098cb5b3..f15da066 100644--- a/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs+++ b/src/managed/Nota.App/DeviceCards/Instruments/FluxInstrumentCard.cs@@ -216,8 +216,7 @@ internal sealed class FluxInstrumentCard : IInstrumentCardfor (int i = 0; i < engine.TrackCount; i++){if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id != id) continue;- string name = engine.GetTrackName(id);- if (string.IsNullOrWhiteSpace(name)) name = $"Track {i + 1}";+ string name = TrackNames.Of(engine, ti);string kind = ti.Type switch { 2 => " · return", 3 => " · bus", _ => "" };return name + kind;}diff --git a/src/managed/Nota.App/MainWindow.AudioImport.cs b/src/managed/Nota.App/MainWindow.AudioImport.csnew file mode 100644index 00000000..4258db90--- /dev/null+++ b/src/managed/Nota.App/MainWindow.AudioImport.cs@@ -0,0 +1,191 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Background audio import. A long WAV used to freeze the UI while it decoded, tempo-+// detected and time-stretched on the UI thread. Now:+// 1. the target track appears at once (translucent, "Processing…") with a placeholder clip;+// 2. a worker decodes the file block by block — the placeholder's waveform fills in as it+// goes (instantly when the analysis cache already knows the file) — then detects tempo;+// 3. back on the UI thread the decoded buffer is placed (no disk I/O) and auto-warped with+// the measured tempo, the warp cache building in small steps so the UI keeps drawing;+// 4. the track turns opaque and is selected.++using System;+using System.Diagnostics;+using System.Threading;+using System.Threading.Tasks;+using Avalonia.Threading;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.App;++public partial class MainWindow+{+ private readonly AudioAnalysisCache _analysis = new();++ // Bumped on New/Open: an import still running belongs to the previous graph (its track id+ // may now name a different track), so it bows out instead of placing its clip.+ private int _importEpoch;++ private const int ImportPeakBuckets = 2048; // placeholder waveform resolution (as the lane's)+ private const long ImportBlockFrames = 1 << 17; // ~3 s of 44.1 kHz per decode step+ private const int ImportTickMs = 50; // placeholder repaint cadence while decoding++ private readonly record struct ImportTick(float[] Peaks, int Count, double Fraction, long TotalFrames, double SampleRate);++ /// <summary>Imports an audio file without blocking the UI. <paramref name="trackId"/> ≤ 0+ /// puts it on a new audio track. Never throws; reports through the status bar.</summary>+ private async Task ImportAudioInBackgroundAsync(string path, int trackId, double beat)+ {+ if (_vm is null) return;+ string name = System.IO.Path.GetFileName(path);+ int epoch = _importEpoch;+ bool ownsTrack = trackId <= 0;+ int t = ownsTrack ? Engine.AddAudioTrack() : trackId;+ var pending = new ArrangementView.PendingImport+ {+ TrackId = t, OwnsTrack = ownsTrack, StartBeat = beat,+ LengthBeats = 4, Label = $"{name} · Processing…", // real length arrives with the header+ };+ Timeline.AddPendingImport(pending);+ _session?.Refresh();+ _vm.StatusText = $"Importing {name}…";++ // Not disposed: Progress<T> posts ticks asynchronously, so one can still arrive after+ // this method returned — `finished` makes it a no-op instead of touching a dead import.+ var cts = new CancellationTokenSource();+ bool finished = false;+ bool Alive() => epoch == _importEpoch && TrackExists(t);+ var progress = new Progress<ImportTick>(tick =>+ {+ if (finished) return;+ if (!Alive()) { cts.Cancel(); return; } // track deleted / undone, or another project opened+ if (tick.SampleRate > 0)+ pending.LengthBeats = tick.TotalFrames / tick.SampleRate * (double)_vm.Transport.Bpm / 60.0;+ pending.Peaks = tick.Peaks;+ pending.PeakCount = tick.Count;+ pending.Label = $"{name} · Processing… {tick.Fraction * 100:0} %";+ Timeline.UpdatePendingImport();+ });++ IAudioImport? job = null;+ bool placed = false;+ try+ {+ string? project = _projectPath;+ (job, double bpm) = await Task.Run(() => DecodeImport(path, project, progress, cts.Token));+ if (job is null) { _vm.StatusText = $"Failed to load {name}"; return; }+ if (!Alive()) { _vm.StatusText = $"Import of {name} cancelled"; return; }++ int clip = Engine.AddImportedAudioClip(t, job, beat);+ job.Dispose(); job = null; // the engine holds its own reference to the buffer+ if (clip < 0) { _vm.StatusText = $"Failed to load {name}"; return; }+ placed = true;+ pending.ClipPlaced = true;++ if (bpm > 0)+ {+ // Warp with the tempo the worker measured, deferring the (heavy) stretch so it+ // can be built in slices below instead of in one UI-thread block.+ Engine.SetDeferWarpBuild(true);+ try { bpm = Engine.AutoWarpClipAtBpm(t, clip, bpm); }+ finally { Engine.SetDeferWarpBuild(false); }+ Timeline.Refresh();+ await BuildImportWarpAsync(name, Alive);+ }+ if (!Alive()) return;++ Timeline.RemovePendingImport(pending);+ Timeline.Select(t, clip); // the finished import becomes the active track+ _vm.StatusText = bpm > 0+ ? string.Format(NotaNum.Culture, "Imported {0} · warped to tempo ({1:0.0} BPM)", name, bpm)+ : $"Imported {name}";+ }+ catch (OperationCanceledException)+ {+ _vm.StatusText = $"Import of {name} cancelled";+ }+ catch (Exception ex)+ {+ _vm.StatusText = $"Failed to load {name}: {ex.Message}";+ }+ finally+ {+ finished = true;+ job?.Dispose();+ Timeline.RemovePendingImport(pending);+ // Nothing landed on a track made just for this import → don't leave an empty row.+ if (!placed && ownsTrack && Alive()) { Engine.RemoveTrack(t); Timeline.Refresh(); }+ _session?.Refresh();+ }+ }++ // Worker thread: fingerprint + cache lookup, block-wise decode with throttled waveform+ // ticks, tempo detection, cache write. Returns (null, 0) when the file can't be decoded.+ private (IAudioImport? job, double bpm) DecodeImport(string path, string? project,+ IProgress<ImportTick> progress, CancellationToken ct)+ {+ string? key = AudioAnalysisCache.Fingerprint(path);+ var cached = key is null ? null : _analysis.TryLoad(key, project);+ var job = Engine.OpenAudioImport(path);+ if (job is null) return (null, 0);+ try+ {+ if (cached is not null) job.SeedPeakTable(cached.PeakTable);+ long total = job.TotalFrames;+ double sr = job.SampleRate;+ void Report()+ {+ var peaks = new float[ImportPeakBuckets * 2];+ int n = job.ReadPeaks(peaks, ImportPeakBuckets);+ double frac = total > 0 ? (double)job.DecodedFrames / total : 0;+ progress.Report(new ImportTick(peaks, n, frac, total, sr));+ }+ Report();+ var sinceTick = Stopwatch.StartNew();+ while (true)+ {+ ct.ThrowIfCancellationRequested();+ int r = job.Step(ImportBlockFrames);+ if (r < 0) { job.Dispose(); return (null, 0); }+ if (r == 0) break;+ if (sinceTick.ElapsedMilliseconds >= ImportTickMs) { Report(); sinceTick.Restart(); }+ }+ total = job.TotalFrames; // a truncated file reports fewer frames once done+ Report();++ double bpm = cached?.Bpm ?? job.DetectTempo();+ if (key is not null && cached is null) _analysis.Store(key, new AudioAnalysis(job.ReadPeakTable(), bpm), project);+ return (job, bpm);+ }+ catch+ {+ job.Dispose();+ throw;+ }+ }++ // Build the deferred warp cache in slices on the UI thread, yielding at Background+ // priority between them so input and rendering always go first.+ private async Task BuildImportWarpAsync(string name, Func<bool> alive)+ {+ long total = Engine.WarpBuildRemaining;+ long remaining = total;+ while (remaining > 0 && alive())+ {+ remaining = Engine.WarpBuildStep(48000);+ double frac = total > 0 ? Math.Clamp(1.0 - (double)remaining / total, 0.0, 1.0) : 1.0;+ if (_vm is not null) _vm.StatusText = $"Warping {name}… {frac * 100:0} %";+ await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);+ }+ }++ private bool TrackExists(int trackId)+ {+ int n = Engine.TrackCount;+ for (int i = 0; i < n; i++)+ if (Engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId) return true;+ return false;+ }+}diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.csindex 0e160a99..3ac98665 100644--- a/src/managed/Nota.App/MainWindow.Browser.cs+++ b/src/managed/Nota.App/MainWindow.Browser.cs@@ -184,14 +184,8 @@ public partial class MainWindowbreak;}case BrowserItemKind.Sample:- {- int t = Engine.AddAudioTrack();- int c = Engine.AddAudioClip(t, item.Path, 0.0);- AutoWarpImported(t, c);- Timeline.Refresh();- _vm.StatusText = $"Added {item.Name} (track {t})";+ _ = ImportAudioInBackgroundAsync(item.Path, -1, 0.0);break;- }case BrowserItemKind.Project:OpenProject(item.Path);return; // OpenProject rebuilds everything itselfdiff --git a/src/managed/Nota.App/MainWindow.Dnd.cs b/src/managed/Nota.App/MainWindow.Dnd.csindex 9c0119d7..64ab8cb7 100644--- a/src/managed/Nota.App/MainWindow.Dnd.cs+++ b/src/managed/Nota.App/MainWindow.Dnd.cs@@ -30,13 +30,9 @@ public partial class MainWindowswitch (item.Kind){case BrowserItemKind.Sample:- {- int t = TrackIsAudio(trackId) ? trackId : Engine.AddAudioTrack();- int c = Engine.AddAudioClip(t, item.Path, beat);- AutoWarpImported(t, c);- _vm.StatusText = $"Added {item.Name} (track {t})";+ // Decodes in the background; the track shows a filling placeholder meanwhile.+ _ = ImportAudioInBackgroundAsync(item.Path, TrackIsAudio(trackId) ? trackId : -1, beat);break;- }case BrowserItemKind.BuiltinInstrument:{// Dropped on an existing (non-rack) instrument track → swap its instrument;diff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.csindex 9bcf2ce6..3eec3f9e 100644--- a/src/managed/Nota.App/MainWindow.Files.cs+++ b/src/managed/Nota.App/MainWindow.Files.cs@@ -43,33 +43,7 @@ public partial class MainWindowvar path = files[0].TryGetLocalPath();if (path is null) { _vm.StatusText = "Unsupported file location."; return; }- string name = System.IO.Path.GetFileName(path);- // Decode + tempo-detect run on the UI thread (they mutate the engine), but they can be- // slow for a long file — surface a background strip in the status bar so it never looks- // frozen. Yield first so the strip paints before the (blocking) engine calls.- await RunBackgroundAsync($"Importing {name}…", async prog =>- {- await Task.Yield();- int trackId = Engine.AddAudioTrack();- int clip = Engine.AddAudioClip(trackId, path, 0.0);- if (clip < 0) { _vm.StatusText = $"Failed to load {name}"; return; }-- prog.Report(ProgressReport.Indeterminate("Analysing tempo…"));- await Task.Yield();- double bpm = AutoWarpImported(trackId, clip);- Timeline.Refresh();- _vm.StatusText = bpm > 0- ? string.Format(NotaNum.Culture, "Imported {0} · warped to tempo ({1:0.0}\u2009BPM)", name, bpm)- : $"Imported {name}";- });- }-- // Auto-warp a freshly imported audio clip so it conforms to the project tempo.- // Returns the detected BPM (0 when detection fails and the clip is left as-is).- private double AutoWarpImported(int trackId, int clipIndex)- {- try { return clipIndex >= 0 ? Engine.AutoWarpClip(trackId, clipIndex) : 0.0; }- catch { return 0.0; }+ await ImportAudioInBackgroundAsync(path, -1, 0.0);}// --- Export master to WAV (M6-4) ---------------------------------------@@ -335,6 +309,7 @@ public partial class MainWindow_modular?.SaveLayout(dir); // modular-editor node/island positions (sidecar)Timeline.SaveSections(dir); // arrangement song sections (sidecar)SaveFreezeLinks(dir); // live-freeze links (v1.1) ride in the bundle sidecar+ _analysis.AdoptInto(dir); // analysis cached while unsaved moves into the bundle_projectPath = dir;RecordRecentProject(dir); // surface it on the welcome screen next launchUpdateWindowTitle();@@ -355,6 +330,8 @@ public partial class MainWindow// per-clip editor state and rebuild every view (cf. RefreshAfterUndoRedo).private void RefreshAfterLoad(){+ _importEpoch++; // imports still running belong to the old graph+ Timeline.ClearPendingImports();_editorRoll = null;_clipEditor = null;_editorTrackId = -1;diff --git a/src/managed/Nota.App/MixerView.cs b/src/managed/Nota.App/MixerView.csindex f2fe32c6..d4bb92d5 100644--- a/src/managed/Nota.App/MixerView.cs+++ b/src/managed/Nota.App/MixerView.cs@@ -256,7 +256,7 @@ public sealed class MixerView : UserControlint n = _engine.TrackCount;for (int i = 0; i < n; i++)if (_engine.TryGetTrackInfo(i, out var ti) && ti.IsInstrument && ti.Id != id)- Add(_engine.GetTrackName(ti.Id) is { Length: > 0 } nm ? nm : $"Inst {ti.Id}", ti.Id);+ Add(TrackNames.Of(_engine, ti), ti.Id);int cur = _engine.GetTrackMidiSource(id);int sel = sources.IndexOf(cur);cb.SelectedIndex = sel >= 0 ? sel : 0;diff --git a/src/managed/Nota.App/TrackNames.cs b/src/managed/Nota.App/TrackNames.csnew file mode 100644index 00000000..2fdd3a42--- /dev/null+++ b/src/managed/Nota.App/TrackNames.cs@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+using Nota.Application;++namespace Nota.App;++/// <summary>The name a track shows everywhere (arrangement header, sidechain and source+/// pickers): the stored name when the user set one, otherwise the derived default — the+/// instrument's name for an instrument track, "Group", "Return N" or "Audio N".</summary>+internal static class TrackNames+{+ public static string Of(IAudioEngine eng, in NotaTrackInfo ti)+ {+ string stored = eng.GetTrackName(ti.Id);+ if (stored.Length > 0) return stored;+ if (ti.IsGroup) return "Group";+ if (ti.IsReturn) return $"Return {eng.TrackReturnIndex(ti.Id) + 1}";+ if (ti.IsInstrument)+ {+ string inst = eng.DeviceName(ti.Id, -1); // Synth / Sampler / plugin name+ return string.IsNullOrWhiteSpace(inst) ? "Inst " + ti.Id : inst;+ }+ return "Audio " + ti.Id;+ }++ /// <summary>By track id; "—" when no such track exists.</summary>+ public static string Of(IAudioEngine eng, int id)+ {+ for (int i = 0; i < eng.TrackCount; i++)+ if (eng.TryGetTrackInfo(i, out var ti) && ti.Id == id) return Of(eng, ti);+ return "—";+ }+}diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex ce90b91d..1eeca1af 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -42,6 +42,11 @@ public interface IAudioEngine : IDisposable// --- Tracks & clips ----------------------------------------------------int AddAudioTrack();int AddAudioClip(int trackId, string path, double startBeat);+ /// <summary>Starts a background decode of a WAV/FLAC/MP3 (null if it can't be opened).+ /// Safe to drive off the UI thread — see <see cref="IAudioImport"/>.</summary>+ IAudioImport? OpenAudioImport(string path);+ /// <summary>Places a finished import on a track (no disk I/O). Returns the clip index or -1.</summary>+ int AddImportedAudioClip(int trackId, IAudioImport import, double startBeat);void SetTrackVolume(int trackId, float volume);void SetTrackPan(int trackId, float pan);void SetTrackMute(int trackId, bool mute);@@ -134,6 +139,8 @@ public interface IAudioEngine : IDisposable/// <summary>Detects the clip's source tempo, enables warp, and snaps its length to/// the beat grid so it conforms to the project BPM. Returns the detected BPM (0 = failed).</summary>double AutoWarpClip(int trackId, int clipIndex);+ /// <summary><see cref="AutoWarpClip"/> with an already-detected tempo (skips detection).</summary>+ double AutoWarpClipAtBpm(int trackId, int clipIndex, double bpm);/// <summary>Beats-mode warp: detects transients and pins a grid-snapped marker at each/// hit so percussion locks tightly to the grid. Returns the detected BPM (0 = failed).</summary>double BeatWarpClip(int trackId, int clipIndex);diff --git a/src/managed/Nota.Application/Engine/IAudioImport.cs b/src/managed/Nota.Application/Engine/IAudioImport.csnew file mode 100644index 00000000..6829d575--- /dev/null+++ b/src/managed/Nota.Application/Engine/IAudioImport.cs@@ -0,0 +1,34 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Application;++/// <summary>A background decode of one audio file (see <see cref="IAudioEngine.OpenAudioImport"/>).+/// Touches no engine state, so it runs on a worker thread; it is NOT thread-safe itself —+/// drive it from one thread at a time. Hand the finished import to+/// <see cref="IAudioEngine.AddImportedAudioClip"/> on the UI thread, then dispose it.</summary>+public interface IAudioImport : IDisposable+{+ int Channels { get; }+ double SampleRate { get; }+ long TotalFrames { get; }+ long DecodedFrames { get; }+ bool IsDone { get; }++ /// <summary>Decodes up to <paramref name="maxFrames"/> more. 1 = more to do, 0 = done, -1 = error.</summary>+ int Step(long maxFrames);++ /// <summary>Waveform over the whole file as (min,max) pairs; not-yet-decoded buckets are+ /// (1,-1) unless a cached overview was seeded. Returns the bucket count.</summary>+ int ReadPeaks(float[] outMinMax, int maxPoints);++ /// <summary>The per-block min/max overview, for the on-disk analysis cache.</summary>+ float[] ReadPeakTable();++ /// <summary>Seeds the overview from the cache so the full waveform shows immediately.+ /// False when the table doesn't fit this file.</summary>+ bool SeedPeakTable(float[] table);++ /// <summary>Tempo of the whole file once done (0 = not detectable).</summary>+ double DetectTempo();+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.csnew file mode 100644index 00000000..f1d91836--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Import.cs@@ -0,0 +1,51 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Runtime.InteropServices;++namespace Nota.Infrastructure;++/// <summary>Background audio import (block-wise decode off the UI thread).</summary>+/// <remarks>Part of <see cref="NotaEngine"/>'s P/Invoke surface; see nota_engine.h.</remarks>+internal static partial class NativeMethods+{+ [StructLayout(LayoutKind.Sequential)]+ internal struct NotaAudioImportInfo+ {+ public int Channels;+ public double SampleRate;+ public long TotalFrames;+ public long DecodedFrames;+ public int Done;+ }++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_open", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial IntPtr AudioImportOpen(string path);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_close")]+ internal static partial void AudioImportClose(IntPtr job);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_step")]+ internal static partial int AudioImportStep(IntPtr job, long maxFrames);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_info")]+ internal static partial NotaResult AudioImportInfo(IntPtr job, out NotaAudioImportInfo info);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_peaks")]+ internal static partial int AudioImportPeaks(IntPtr job, [Out] float[] outMinMax, int maxPoints);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_peak_table")]+ internal static partial long AudioImportPeakTable(IntPtr job, [Out] float[]? outTable, long maxFloats);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_seed_peak_table")]+ internal static partial int AudioImportSeedPeakTable(IntPtr job, float[] table, long count);++ [LibraryImport(Lib, EntryPoint = "nota_audio_import_detect_tempo")]+ internal static partial double AudioImportDetectTempo(IntPtr job);++ [LibraryImport(Lib, EntryPoint = "nota_track_add_imported_clip")]+ internal static partial int TrackAddImportedClip(IntPtr engine, int trackId, IntPtr job, double startBeat);++ [LibraryImport(Lib, EntryPoint = "nota_clip_auto_warp_bpm")]+ internal static partial double ClipAutoWarpBpm(IntPtr engine, int trackId, int clipIndex, double bpm);+}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.csnew file mode 100644index 00000000..31f29200--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Import.cs@@ -0,0 +1,73 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Infrastructure;++public sealed partial class NotaEngine+{+ // --- Background audio import -------------------------------------------++ /// <summary>Opens a block-wise decode of a WAV/FLAC/MP3 (null if unreadable). Doesn't+ /// touch the engine, so the returned job can be driven from a worker thread.</summary>+ public IAudioImport? OpenAudioImport(string path)+ {+ ThrowIfDisposed();+ var h = NativeMethods.AudioImportOpen(path);+ return h == IntPtr.Zero ? null : new AudioImport(h);+ }++ /// <summary>Places a finished import on a track. Returns the clip index, or -1.</summary>+ public int AddImportedAudioClip(int trackId, IAudioImport import, double startBeat)+ {+ ThrowIfDisposed();+ if (import is not AudioImport ai) throw new ArgumentException("Not a NotaEngine import.", nameof(import));+ return NativeMethods.TrackAddImportedClip(_handle, trackId, ai.Handle, startBeat);+ }++ /// <summary>Auto-warp with an already-detected tempo. Returns the BPM used (0 = failed).</summary>+ public double AutoWarpClipAtBpm(int trackId, int clipIndex, double bpm)+ { ThrowIfDisposed(); return NativeMethods.ClipAutoWarpBpm(_handle, trackId, clipIndex, bpm); }++ private sealed class AudioImport : IAudioImport+ {+ private IntPtr _h;+ public AudioImport(IntPtr h) => _h = h;++ internal IntPtr Handle => _h != IntPtr.Zero ? _h : throw new ObjectDisposedException(nameof(AudioImport));++ private NativeMethods.NotaAudioImportInfo Info+ {+ get { NativeMethods.AudioImportInfo(Handle, out var i); return i; }+ }++ public int Channels => Info.Channels;+ public double SampleRate => Info.SampleRate;+ public long TotalFrames => Info.TotalFrames;+ public long DecodedFrames => Info.DecodedFrames;+ public bool IsDone => Info.Done != 0;++ public int Step(long maxFrames) => NativeMethods.AudioImportStep(Handle, maxFrames);+ public int ReadPeaks(float[] outMinMax, int maxPoints)+ => NativeMethods.AudioImportPeaks(Handle, outMinMax, Math.Min(maxPoints, outMinMax.Length / 2));++ public float[] ReadPeakTable()+ {+ long n = NativeMethods.AudioImportPeakTable(Handle, null, 0);+ if (n <= 0) return Array.Empty<float>();+ var t = new float[n];+ NativeMethods.AudioImportPeakTable(Handle, t, n);+ return t;+ }++ public bool SeedPeakTable(float[] table)+ => NativeMethods.AudioImportSeedPeakTable(Handle, table, table.Length) != 0;++ public double DetectTempo() => NativeMethods.AudioImportDetectTempo(Handle);++ public void Dispose()+ {+ var h = Interlocked.Exchange(ref _h, IntPtr.Zero);+ if (h != IntPtr.Zero) NativeMethods.AudioImportClose(h);+ }+ }+}diff --git a/src/managed/Nota.Infrastructure/Persistence/AudioAnalysisCache.cs b/src/managed/Nota.Infrastructure/Persistence/AudioAnalysisCache.csnew file mode 100644index 00000000..cf587288--- /dev/null+++ b/src/managed/Nota.Infrastructure/Persistence/AudioAnalysisCache.cs@@ -0,0 +1,167 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// On-disk cache of an imported file's analysis — its waveform overview (min/max per+// 512-frame block) and detected tempo — so re-importing the same audio shows the whole+// waveform at once and skips tempo detection. Unlike Ableton's .asd files these are not+// written next to the user's audio: they live in the project bundle's `analysis/` folder+// (or, for a project that was never saved, a per-user staging folder, adopted into the+// bundle on its first save). Entries are keyed by a content fingerprint, so a moved or+// renamed file still hits and an edited one misses.++using System.Security.Cryptography;++namespace Nota.Infrastructure;++/// <summary>A cached analysis: the peak overview and the detected tempo (0 = none).</summary>+public sealed record AudioAnalysis(float[] PeakTable, double Bpm);++/// <summary>Reads/writes <see cref="AudioAnalysis"/> entries (thread-safe; used from the+/// import worker). <c>projectDir</c> is the open `.nota` bundle, or null while unsaved.</summary>+public sealed class AudioAnalysisCache+{+ public const string FolderName = "analysis";+ private const string Ext = ".npk";+ private const uint Magic = 0x314B504E; // "NPK1"+ private const int FormatVersion = 1;+ private const int SampleBytes = 64 * 1024; // fingerprint window (head / middle / tail)+ private static readonly TimeSpan StagingMaxAge = TimeSpan.FromDays(30);++ private readonly object _gate = new();+ private readonly HashSet<string> _stagedKeys = new(); // used from staging this session++ private static string StagingDir => NotaPaths.SubDir("analysis-cache");++ /// <summary>Content fingerprint of an audio file: its length plus three 64 KB windows.+ /// Cheap on a multi-GB file, stable across copies/renames. Null if unreadable.</summary>+ public static string? Fingerprint(string path)+ {+ try+ {+ using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);+ long len = fs.Length;+ using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ sha.AppendData(BitConverter.GetBytes(len));+ var buf = new byte[SampleBytes];+ foreach (long at in new[] { 0L, Math.Max(0, len / 2 - SampleBytes / 2), Math.Max(0, len - SampleBytes) })+ {+ fs.Position = at;+ int n = fs.ReadAtLeast(buf, buf.Length, throwOnEndOfStream: false);+ sha.AppendData(buf, 0, n);+ }+ return Convert.ToHexString(sha.GetHashAndReset(), 0, 16).ToLowerInvariant();+ }+ catch (IOException) { return null; }+ catch (UnauthorizedAccessException) { return null; }+ }++ /// <summary>The cached analysis for <paramref name="key"/>: the project's copy first,+ /// then the staging folder. Null on a miss or an unreadable/foreign file.</summary>+ public AudioAnalysis? TryLoad(string key, string? project)+ {+ if (project is not null && Read(Path.Combine(project, FolderName, key + Ext)) is { } own) return own;+ var staged = Read(Path.Combine(StagingDir, key + Ext));+ // A staged hit now belongs to this project too: copy it in (or remember it for the+ // first save) so the bundle stays self-contained.+ if (staged is not null)+ {+ if (project is not null) Store(key, staged, project);+ else lock (_gate) _stagedKeys.Add(key);+ }+ return staged;+ }++ /// <summary>Stores an analysis in the project (or staging while unsaved). Best-effort.</summary>+ public void Store(string key, AudioAnalysis a, string? project)+ {+ string dir = project is null ? StagingDir : Path.Combine(project, FolderName);+ try+ {+ Directory.CreateDirectory(dir);+ Write(Path.Combine(dir, key + Ext), a);+ if (project is null)+ {+ lock (_gate) _stagedKeys.Add(key);+ PruneStaging();+ }+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }++ /// <summary>Copies this session's staged entries into a bundle — called when an+ /// unsaved project is first saved, so its analysis moves in with it.</summary>+ public void AdoptInto(string bundleDir)+ {+ string[] keys;+ lock (_gate) { keys = _stagedKeys.ToArray(); _stagedKeys.Clear(); }+ if (keys.Length == 0) return;+ string dest = Path.Combine(bundleDir, FolderName);+ try+ {+ Directory.CreateDirectory(dest);+ foreach (var k in keys)+ {+ string src = Path.Combine(StagingDir, k + Ext), dst = Path.Combine(dest, k + Ext);+ if (File.Exists(src) && !File.Exists(dst)) File.Copy(src, dst);+ }+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }++ // --- file format --------------------------------------------------------+ // u32 magic "NPK1", i32 version, i32 block frames, f64 bpm, i64 float count, f32[count].++ private static AudioAnalysis? Read(string path)+ {+ try+ {+ if (!File.Exists(path)) return null;+ using var r = new BinaryReader(File.OpenRead(path));+ if (r.ReadUInt32() != Magic || r.ReadInt32() != FormatVersion) return null;+ if (r.ReadInt32() != 512) return null; // must match SampleBuffer::kPeakBlock+ double bpm = r.ReadDouble();+ long count = r.ReadInt64();+ if (count <= 0 || count > int.MaxValue || count * sizeof(float) > r.BaseStream.Length) return null;+ var table = new float[count];+ var bytes = r.ReadBytes((int)count * sizeof(float));+ if (bytes.Length != count * sizeof(float)) return null;+ Buffer.BlockCopy(bytes, 0, table, 0, bytes.Length);+ return new AudioAnalysis(table, bpm);+ }+ catch (IOException) { return null; }+ catch (UnauthorizedAccessException) { return null; }+ }++ private static void Write(string path, AudioAnalysis a)+ {+ string tmp = path + ".tmp";+ using (var w = new BinaryWriter(File.Create(tmp)))+ {+ w.Write(Magic);+ w.Write(FormatVersion);+ w.Write(512);+ w.Write(a.Bpm);+ w.Write((long)a.PeakTable.Length);+ var bytes = new byte[a.PeakTable.Length * sizeof(float)];+ Buffer.BlockCopy(a.PeakTable, 0, bytes, 0, bytes.Length);+ w.Write(bytes);+ }+ File.Move(tmp, path, overwrite: true);+ }++ // The staging folder is shared by every unsaved session, so it would only grow: drop+ // entries nobody has written in a month.+ private static void PruneStaging()+ {+ try+ {+ var cutoff = DateTime.UtcNow - StagingMaxAge;+ foreach (var f in Directory.EnumerateFiles(StagingDir, "*" + Ext))+ if (File.GetLastWriteTimeUtc(f) < cutoff) File.Delete(f);+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }+}diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex 9b836f60..3fa1de99 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -63,6 +63,8 @@ set(NOTA_ENGINE_SOURCESsrc/WarpStream.cppsrc/TempoDetect.cppsrc/AudioFile.cpp+ src/AudioImport.cpp+ src/nota_engine_import.cppsrc/AudioBackendFactory.cpp # platform-selected backend construction)diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex e3cca90a..502ead39 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -367,6 +367,43 @@ NOTA_API int32_t nota_clip_get_source_peaks(const NotaEngine* engine, int32_t trNOTA_API int32_t nota_clip_get_warp_full_peaks(const NotaEngine* engine, int32_t track_id,int32_t clip_index, float* out_min_max, int32_t max_points);+/* ---- Background audio import -------------------------------------------- */+/* Decodes a WAV/FLAC/MP3 block by block on ANY thread (it touches no engine state), so+ * the UI stays responsive and can draw the waveform as it fills in. One job is not+ * thread-safe: serialise all calls on it. Flow: open → step until 0 (peaks meanwhile) →+ * detect_tempo → nota_track_add_imported_clip (authoring thread) → close. */+typedef struct NotaAudioImport NotaAudioImport;+typedef struct NotaAudioImportInfo {+ int32_t channels;+ double sample_rate;+ int64_t total_frames;+ int64_t decoded_frames;+ int32_t done;+} NotaAudioImportInfo;+/* Opens the file and reads its header. NULL if it can't be opened / is unsupported. */+NOTA_API NotaAudioImport* nota_audio_import_open(const char* path_utf8);+NOTA_API void nota_audio_import_close(NotaAudioImport* job);+/* Decodes up to max_frames more. Returns 1 while frames remain, 0 when done, -1 on error. */+NOTA_API int32_t nota_audio_import_step(NotaAudioImport* job, int64_t max_frames);+NOTA_API NotaResult nota_audio_import_info(const NotaAudioImport* job, NotaAudioImportInfo* out);+/* Waveform over the whole file, same layout as nota_clip_get_peaks. Buckets not decoded+ * yet are (1,-1) (min > max = nothing to draw) unless a cached overview was seeded. */+NOTA_API int32_t nota_audio_import_peaks(const NotaAudioImport* job, float* out_min_max, int32_t max_points);+/* The per-512-frame min/max overview (for an on-disk cache). Returns its length in+ * floats; copies up to max_floats into out (out may be NULL to query the length). */+NOTA_API int64_t nota_audio_import_peak_table(const NotaAudioImport* job, float* out, int64_t max_floats);+/* Seeds the overview from a cache so the full waveform shows before decoding finishes.+ * Returns 1 if accepted (count must match this file's table length), else 0. */+NOTA_API int32_t nota_audio_import_seed_peak_table(NotaAudioImport* job, const float* table, int64_t count);+/* Tempo of the whole file once done (0 = not detectable). */+NOTA_API double nota_audio_import_detect_tempo(const NotaAudioImport* job);+/* Places the finished import on a track (authoring thread; no disk I/O). Returns the clip+ * index, or -1. The job may be closed afterwards — the engine keeps its own reference. */+NOTA_API int32_t nota_track_add_imported_clip(NotaEngine* engine, int32_t track_id,+ const NotaAudioImport* job, double start_beat);+/* 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);+/* ---- 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/AudioFile.cpp b/src/native/nota.engine/src/AudioFile.cppindex 1eb4e7fb..103ef465 100644--- a/src/native/nota.engine/src/AudioFile.cpp+++ b/src/native/nota.engine/src/AudioFile.cpp@@ -75,10 +75,13 @@ std::shared_ptr<SampleBuffer> decodeMp3(const std::string& path) {std::shared_ptr<SampleBuffer> decodeAudioFile(const std::string& path) {const std::string ext = extLower(path);- if (ext == "wav") return decodeWav(path);- if (ext == "flac") return decodeFlac(path);- if (ext == "mp3") return decodeMp3(path);- return nullptr; // aiff and others: deferred+ std::shared_ptr<SampleBuffer> buf;+ if (ext == "wav") buf = decodeWav(path);+ else if (ext == "flac") buf = decodeFlac(path);+ else if (ext == "mp3") buf = decodeMp3(path);+ // aiff and others: deferred+ if (buf) buf->buildPeakTable(); // one pass now; every later waveform query reads blocks+ return buf;}} // namespace notadiff --git a/src/native/nota.engine/src/AudioImport.cpp b/src/native/nota.engine/src/AudioImport.cppnew file mode 100644index 00000000..c0a7a0fb--- /dev/null+++ b/src/native/nota.engine/src/AudioImport.cpp@@ -0,0 +1,175 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "AudioImport.h"+#include "AudioFile.h"+#include "TempoDetect.h"++// Declarations only — the implementations live in AudioFile.cpp.+#include "dr_wav.h"+#include "dr_flac.h"+#include "dr_mp3.h"++#include <algorithm>+#include <cctype>++namespace nota {++// One streaming decoder, chosen by extension. Each exposes the header (channels,+// rate, total frames) up front and then reads interleaved f32 frames on demand.+struct AudioImportJob::Decoder {+ enum class Kind { Wav, Flac, Mp3 } kind = Kind::Wav;+ drwav wav{};+ drflac* flac = nullptr;+ drmp3 mp3{};+ bool open = false;++ ~Decoder() { close(); }++ void close() {+ if (!open) return;+ switch (kind) {+ case Kind::Wav: drwav_uninit(&wav); break;+ case Kind::Flac: drflac_close(flac); flac = nullptr; break;+ case Kind::Mp3: drmp3_uninit(&mp3); break;+ }+ open = false;+ }++ uint64_t read(uint64_t frames, float* out) {+ switch (kind) {+ case Kind::Wav: return drwav_read_pcm_frames_f32(&wav, frames, out);+ case Kind::Flac: return drflac_read_pcm_frames_f32(flac, frames, out);+ case Kind::Mp3: return drmp3_read_pcm_frames_f32(&mp3, frames, out);+ }+ return 0;+ }+};++AudioImportJob::~AudioImportJob() = default;++std::unique_ptr<AudioImportJob> AudioImportJob::open(const std::string& path) {+ 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(),+ [](unsigned char c) { return static_cast<char>(std::tolower(c)); });++ auto dec = std::make_unique<Decoder>();+ uint32_t channels = 0; double rate = 0.0; uint64_t total = 0;+ if (ext == "wav") {+ dec->kind = Decoder::Kind::Wav;+ if (!drwav_init_file(&dec->wav, path.c_str(), nullptr)) return nullptr;+ dec->open = true;+ channels = dec->wav.channels; rate = dec->wav.sampleRate; total = dec->wav.totalPCMFrameCount;+ } else if (ext == "flac") {+ dec->kind = Decoder::Kind::Flac;+ dec->flac = drflac_open_file(path.c_str(), nullptr);+ if (!dec->flac) return nullptr;+ dec->open = true;+ channels = dec->flac->channels; rate = dec->flac->sampleRate; total = dec->flac->totalPCMFrameCount;+ } else if (ext == "mp3") {+ dec->kind = Decoder::Kind::Mp3;+ if (!drmp3_init_file(&dec->mp3, path.c_str(), nullptr)) return nullptr;+ dec->open = true;+ channels = dec->mp3.channels; rate = dec->mp3.sampleRate;+ total = drmp3_get_pcm_frame_count(&dec->mp3); // a linear scan, but we're off the UI thread+ } else {+ return nullptr; // aiff and others: deferred (as decodeAudioFile)+ }++ auto job = std::unique_ptr<AudioImportJob>(new AudioImportJob());+ job->buf_ = std::make_shared<SampleBuffer>();+ job->buf_->sourceSampleRate = rate;+ if (channels == 0 || rate <= 0.0) return nullptr;++ if (total == 0) {+ // Length unknown up front (a streamed FLAC without it in STREAMINFO): no block-wise+ // progress possible, so fall back to decoding it whole here.+ dec->close();+ auto whole = decodeAudioFile(path);+ if (!whole || whole->empty()) return nullptr;+ job->buf_ = std::move(whole);+ job->decoded_ = job->buf_->frames;+ job->done_ = true;+ return job;+ }++ 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);+ job->buf_->updatePeakTable(0, 0); // allocate the overview (all "no data")+ job->dec_ = std::move(dec);+ return job;+}++int32_t AudioImportJob::step(int64_t maxFrames) {+ if (done_) return 0;+ if (!dec_ || !buf_) return -1;+ SampleBuffer& b = *buf_;+ const int64_t want = std::min<int64_t>(std::max<int64_t>(1, maxFrames), b.frames - decoded_);+ const uint64_t got = dec_->read(static_cast<uint64_t>(want), b.samples.data() + decoded_ * b.channels);+ const int64_t before = decoded_;+ decoded_ += static_cast<int64_t>(got);+ if (!seeded_) b.updatePeakTable(before, decoded_);+ if (got < static_cast<uint64_t>(want) || decoded_ >= b.frames) finish();+ return done_ ? 0 : 1;+}++// End of stream: trim to what actually decoded (a header can over-report a truncated+// file), rebuild the overview from the real samples, release the decoder.+void AudioImportJob::finish() {+ SampleBuffer& b = *buf_;+ if (decoded_ < b.frames) {+ b.frames = decoded_;+ b.samples.resize(static_cast<size_t>(decoded_) * b.channels);+ b.peakTable.clear();+ b.buildPeakTable();+ } else if (seeded_) {+ b.buildPeakTable(); // a seeded (cached) overview is replaced by the measured one+ }+ if (dec_) dec_->close();+ dec_.reset();+ done_ = true;+}++int32_t AudioImportJob::peaks(float* out, int32_t maxPoints) const {+ if (!out || maxPoints <= 0 || !buf_) return 0;+ const SampleBuffer& b = *buf_;+ if (b.frames <= 0) return 0;+ const int32_t buckets = static_cast<int32_t>(std::min<int64_t>(maxPoints, b.frames));+ // Seeded and still decoding: read the cached blocks only — the samples under a partial+ // edge block may not be decoded yet, and scanning those zeros would skew the bucket.+ const bool fromTable = seeded_ && !done_;+ const int64_t ready = done_ ? b.frames : decoded_; // else only the decoded prefix+ for (int32_t i = 0; i < buckets; ++i) {+ const int64_t f0 = b.frames * i / buckets, f1 = b.frames * (i + 1) / buckets;+ float mn = 1.0f, mx = -1.0f; // "not decoded yet"+ if (fromTable) {+ const int64_t b1 = std::max(f0 / SampleBuffer::kPeakBlock + 1,+ (f1 + SampleBuffer::kPeakBlock - 1) / SampleBuffer::kPeakBlock);+ for (int64_t k = f0 / SampleBuffer::kPeakBlock; k < b1 && k < b.peakBlocks(); ++k) {+ mn = std::min(mn, b.peakTable[k * 2]); mx = std::max(mx, b.peakTable[k * 2 + 1]);+ }+ } else if (f0 < ready) {+ b.peakRange(f0, std::min(f1, ready), mn, mx);+ }+ out[i * 2] = mn; out[i * 2 + 1] = mx;+ }+ return buckets;+}++bool AudioImportJob::seedPeakTable(const float* table, int64_t count) {+ if (!table || !buf_ || done_) return false;+ SampleBuffer& b = *buf_;+ if (count != b.peakBlocks() * 2) return false; // cache is for a different file/length+ b.peakTable.assign(table, table + count);+ seeded_ = true;+ return true;+}++double AudioImportJob::detectTempo() const {+ if (!done_ || !buf_ || buf_->empty()) return 0.0;+ return nota::detectTempo(*buf_, 0, buf_->frames, buf_->sourceSampleRate);+}++} // namespace notadiff --git a/src/native/nota.engine/src/AudioImport.h b/src/native/nota.engine/src/AudioImport.hnew file mode 100644index 00000000..8ba19b38--- /dev/null+++ b/src/native/nota.engine/src/AudioImport.h@@ -0,0 +1,56 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Background audio import: decodes a file block by block into a SampleBuffer,+// building its waveform overview as it goes, so a long file can be loaded on a+// worker thread while the UI draws the waveform filling in. Touches no engine state;+// the finished buffer is handed to Engine::addAudioClipBuffer on the authoring thread.+// A job is single-threaded — the caller serialises every call on one instance.++#pragma once++#include "SampleBuffer.h"+#include <cstdint>+#include <memory>+#include <string>++namespace nota {++class AudioImportJob {+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);++ // 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_; }+ const std::shared_ptr<SampleBuffer>& buffer() const { return buf_; }++ // Display peaks over the WHOLE file (maxPoints buckets, min/max pairs). Buckets not+ // decoded yet hold (1,-1) so the UI can draw what's ready — unless a cached overview+ // was seeded, in which case the full waveform is available from the start.+ int32_t peaks(float* outMinMax, int32_t maxPoints) const;++ // Seed the overview from a cached table (same length as the buffer's peak table).+ bool seedPeakTable(const float* table, int64_t count);++ // Tempo of the whole decoded file (0 = not detectable). Call once done.+ double detectTempo() const;++private:+ AudioImportJob() = default;+ void finish();++ struct Decoder;+ std::unique_ptr<Decoder> dec_;+ std::shared_ptr<SampleBuffer> buf_;+ int64_t decoded_ = 0;+ bool done_ = false;+ bool seeded_ = false;+};++} // namespace notadiff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex fccc8c02..56516634 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -273,6 +273,8 @@ public:// --- structural edits: audio (M1) ---int32_t addAudioTrack();int32_t addAudioClip(int32_t trackId, const std::string& path, double startBeat);+ // Places an already-decoded buffer (background import) — no disk I/O on this thread.+ int32_t addAudioClipBuffer(int32_t trackId, std::shared_ptr<SampleBuffer> sample, double startBeat);void setTrackVolume(int32_t trackId, float v);void setTrackPan(int32_t trackId, float p);void setTrackMute(int32_t trackId, bool m);@@ -470,7 +472,9 @@ public:bool setClipPitch(int32_t trackId, int32_t clipIndex, float semitones); // audio clip varispeed transposebool setClipReverse(int32_t trackId, int32_t clipIndex, bool reversed); // audio clip plays back-to-frontbool setClipWarp(int32_t trackId, int32_t clipIndex, bool enabled, int32_t mode); // toggle/mode + rebuild cache- double autoWarpClip(int32_t trackId, int32_t clipIndex); // detect tempo, enable warp, snap length to grid; returns detected BPM (0 = failed)+ // Detect tempo, enable warp, snap length to grid; returns the BPM used (0 = failed).+ // knownBpm > 0 skips detection (the background import already measured it).+ double autoWarpClip(int32_t trackId, int32_t clipIndex, double knownBpm = 0.0);double beatWarpClip(int32_t trackId, int32_t clipIndex); // Beats mode: detect transients, pin grid-snapped markers at each hit; returns detected BPM (0 = failed)bool setClipWarpLength(int32_t trackId, int32_t clipIndex, double beats); // warped clip target lengthbool setClipWarpMarkers(int32_t trackId, int32_t clipIndex, const double* srcFrames, const double* beats, int32_t count);diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cppindex ce517f33..c56e37de 100644--- a/src/native/nota.engine/src/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/Engine_Tracks.cpp@@ -159,10 +159,12 @@ void seedNeutralWarp(AudioClip& c, double spb, double devSR) {// to the beat grid, and seed two end markers so the whole clip stretches to that// many beats at the project tempo (i.e. conforms to the current BPM). Returns the// detected BPM, or 0 when detection fails (leaving markers untouched by caller).-double seedAutoWarp(AudioClip& c, double spb, double devSR) {+double seedAutoWarp(AudioClip& c, double spb, double devSR, double knownBpm = 0.0) {const double srcSR = c.sample->sourceSampleRate;const int64_t srcLen = c.effectiveLength();- const double bpm = detectTempo(*c.sample, static_cast<int64_t>(c.sourceOffsetFrames), srcLen, srcSR);+ const double bpm = knownBpm > 0.0+ ? knownBpm+ : detectTempo(*c.sample, static_cast<int64_t>(c.sourceOffsetFrames), srcLen, srcSR);if (bpm <= 0.0 || srcLen <= 0) return 0.0;const double durationSec = static_cast<double>(srcLen) / srcSR;const double beatsRaw = durationSec * bpm / 60.0;@@ -376,7 +378,7 @@ bool Engine::setClipWarp(int32_t trackId, int32_t clipIndex, bool enabled, int32return true;}-double Engine::autoWarpClip(int32_t trackId, int32_t clipIndex) {+double Engine::autoWarpClip(int32_t trackId, int32_t clipIndex, double knownBpm) {auto old = findTrackAuthoring(trackId);if (!old || old->type() != TrackType::Audio) return 0.0;if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(old->clips.size())) return 0.0;@@ -385,7 +387,7 @@ double Engine::autoWarpClip(int32_t trackId, int32_t clipIndex) {auto nt = cloneTrack(*old);AudioClip& c = nt->clips[clipIndex];if (!c.sample || spb <= 0.0 || devSR <= 0.0 || c.sample->sourceSampleRate <= 0.0) return 0.0;- const double bpm = seedAutoWarp(c, spb, devSR);+ const double bpm = seedAutoWarp(c, spb, devSR, knownBpm);if (bpm <= 0.0) return 0.0; // detection failed: leave the clip unchangedc.warpEnabled = true;configureClipWarp(c, spb, devSR);@@ -684,7 +686,10 @@ int32_t Engine::addAudioTrack() {}int32_t Engine::addAudioClip(int32_t trackId, const std::string& path, double startBeat) {- auto sample = decodeAudioFile(path);+ return addAudioClipBuffer(trackId, decodeAudioFile(path), startBeat);+}++int32_t Engine::addAudioClipBuffer(int32_t trackId, std::shared_ptr<SampleBuffer> sample, double startBeat) {if (!sample || sample->empty()) return -1;auto old = findTrackAuthoring(trackId);if (!old) return -1;@@ -762,13 +767,8 @@ static int32_t warpPeaksRange(const AudioClip& clip, float* out, int32_t maxPoinint64_t s0 = static_cast<int64_t>(srcAtBeat(beat0 + span * b / buckets));int64_t s1 = static_cast<int64_t>(srcAtBeat(beat0 + span * (b + 1) / buckets));if (s1 < s0) std::swap(s0, s1);- float mn = 1.0f, mx = -1.0f;- for (int64_t f = s0; f <= s1; ++f) {- float l, r; sb.readStereo(f, l, r);- const float mid = 0.5f * (l + r);- mn = std::min(mn, mid); mx = std::max(mx, mid);- }- if (mn > mx) { mn = mx = 0.0f; }+ float mn, mx;+ sb.peakRange(s0, s1 + 1, mn, mx);out[b * 2] = mn; out[b * 2 + 1] = mx;}return buckets;@@ -812,14 +812,9 @@ int32_t Engine::getClipPeaks(int32_t trackId, int32_t clipIndex,const int32_t buckets = static_cast<int32_t>(std::min<int64_t>(maxPoints, total));const int64_t per = total / buckets;for (int32_t b = 0; b < buckets; ++b) {- int64_t begin = base + b * per;- int64_t end = begin + per;- float mn = 1.0f, mx = -1.0f;- for (int64_t f = begin; f < end; ++f) {- float l, r; sb.readStereo(f, l, r);- const float mid = 0.5f * (l + r);- mn = std::min(mn, mid); mx = std::max(mx, mid);- }+ const int64_t begin = base + b * per;+ float mn, mx;+ sb.peakRange(begin, begin + per, mn, mx);outMinMax[b * 2] = mn; outMinMax[b * 2 + 1] = mx;}if (clip.reversed) reversePeaks(outMinMax, buckets);@@ -844,15 +839,8 @@ int32_t Engine::getClipSourcePeaks(int32_t trackId, int32_t clipIndex,const int32_t buckets = static_cast<int32_t>(std::min<int64_t>(maxPoints, total));const int64_t per = total / buckets;for (int32_t b = 0; b < buckets; ++b) {- int64_t begin = b * per;- int64_t end = begin + per;- float mn = 1.0f, mx = -1.0f;- for (int64_t f = begin; f < end; ++f) {- float l, r; sb.readStereo(f, l, r);- const float mid = 0.5f * (l + r);- mn = std::min(mn, mid); mx = std::max(mx, mid);- }- if (mn > mx) { mn = mx = 0.0f; }+ float mn, mx;+ sb.peakRange(b * per, (b + 1) * per, mn, mx);outMinMax[b * 2] = mn; outMinMax[b * 2 + 1] = mx;}return buckets;diff --git a/src/native/nota.engine/src/SampleBuffer.h b/src/native/nota.engine/src/SampleBuffer.hindex 409034aa..2fadf783 100644--- a/src/native/nota.engine/src/SampleBuffer.h+++ b/src/native/nota.engine/src/SampleBuffer.h@@ -6,6 +6,7 @@#pragma once+#include <algorithm>#include <atomic>#include <cstdint>#include <vector>@@ -43,6 +44,64 @@ struct SampleBuffer {if (channels == 1) { l = r = p[0]; }else { l = p[0]; r = p[1]; }}++ // --- waveform overview ---------------------------------------------------+ // Min/max of the stereo mid per kPeakBlock frames, interleaved [min0,max0,min1,max1,…].+ // Built when a file is decoded so waveform queries over long spans read blocks instead+ // of every frame (a 10-minute file is ~29M frames). Empty = not built; peakRange then+ // scans frames. Blocks not computed yet hold the (1,-1) "no data" sentinel.+ static constexpr int64_t kPeakBlock = 512;+ std::vector<float> peakTable;++ int64_t peakBlocks() const { return (frames + kPeakBlock - 1) / kPeakBlock; }+ bool hasPeakTable() const { return static_cast<int64_t>(peakTable.size()) == peakBlocks() * 2; }++ void buildPeakTable() { updatePeakTable(0, frames); }++ // (Re)compute the blocks overlapping frames [f0, f1). Used incrementally while a file+ // decodes block by block; a block straddling f0 is recomputed whole.+ void updatePeakTable(int64_t f0, int64_t f1) {+ if (!hasPeakTable()) {+ peakTable.assign(static_cast<size_t>(peakBlocks() * 2), 0.0f);+ fillSentinel(0, peakBlocks());+ }+ f0 = std::max<int64_t>(0, f0); f1 = std::min(f1, frames);+ if (f1 <= f0) return;+ for (int64_t b = f0 / kPeakBlock; b <= (f1 - 1) / kPeakBlock; ++b) {+ float mn, mx;+ scanRange(b * kPeakBlock, std::min(frames, (b + 1) * kPeakBlock), mn, mx);+ peakTable[b * 2] = mn; peakTable[b * 2 + 1] = mx;+ }+ }++ void fillSentinel(int64_t b0, int64_t b1) {+ for (int64_t b = b0; b < b1; ++b) { peakTable[b * 2] = 1.0f; peakTable[b * 2 + 1] = -1.0f; }+ }++ // Min/max of the stereo mid over frames [f0, f1): whole table blocks in the middle,+ // exact frame scans for the partial blocks at either end. (0,0) for an empty range.+ void peakRange(int64_t f0, int64_t f1, float& mn, float& mx) const {+ f0 = std::max<int64_t>(0, f0); f1 = std::min(f1, frames);+ mn = 1.0f; mx = -1.0f;+ if (f1 <= f0) { mn = mx = 0.0f; return; }+ if (f1 - f0 < 4 * kPeakBlock || !hasPeakTable()) { scanRange(f0, f1, mn, mx); return; }+ const int64_t b0 = (f0 + kPeakBlock - 1) / kPeakBlock, b1 = f1 / kPeakBlock; // whole blocks+ float a, z;+ scanRange(f0, b0 * kPeakBlock, a, z); mn = std::min(mn, a); mx = std::max(mx, z);+ for (int64_t b = b0; b < b1; ++b) { mn = std::min(mn, peakTable[b * 2]); mx = std::max(mx, peakTable[b * 2 + 1]); }+ scanRange(b1 * kPeakBlock, f1, a, z); mn = std::min(mn, a); mx = std::max(mx, z);+ if (mn > mx) mn = mx = 0.0f;+ }++private:+ void scanRange(int64_t f0, int64_t f1, float& mn, float& mx) const {+ mn = 1.0f; mx = -1.0f;+ for (int64_t f = f0; f < f1; ++f) {+ float l, r; readStereo(f, l, r);+ const float mid = 0.5f * (l + r);+ mn = std::min(mn, mid); mx = std::max(mx, mid);+ }+ }};} // namespace notadiff --git a/src/native/nota.engine/src/nota_engine_import.cpp b/src/native/nota.engine/src/nota_engine_import.cppnew file mode 100644index 00000000..0a8b4105--- /dev/null+++ b/src/native/nota.engine/src/nota_engine_import.cpp@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// C ABI — background audio import (decode off the UI thread, then place the buffer).++#include "nota_engine_internal.h"+#include "AudioImport.h"++#include <algorithm>+#include <cstring>+#include <string>++#define JOB(j) reinterpret_cast<nota::AudioImportJob*>(j)+#define CJOB(j) reinterpret_cast<const nota::AudioImportJob*>(j)++extern "C" {++NotaAudioImport* nota_audio_import_open(const char* path) {+ if (!path) return nullptr;+ return reinterpret_cast<NotaAudioImport*>(nota::AudioImportJob::open(std::string(path)).release());+}+void nota_audio_import_close(NotaAudioImport* job) {+ delete JOB(job);+}+int32_t nota_audio_import_step(NotaAudioImport* job, int64_t max_frames) {+ return job ? JOB(job)->step(max_frames) : -1;+}+NotaResult nota_audio_import_info(const NotaAudioImport* job, NotaAudioImportInfo* out) {+ if (!job || !out) return NOTA_ERR_INVALID_ARG;+ const auto& b = CJOB(job)->buffer();+ out->channels = b ? b->channels : 0;+ out->sample_rate = b ? b->sourceSampleRate : 0.0;+ out->total_frames = b ? b->frames : 0;+ out->decoded_frames = CJOB(job)->decodedFrames();+ out->done = CJOB(job)->done() ? 1 : 0;+ return NOTA_OK;+}+int32_t nota_audio_import_peaks(const NotaAudioImport* job, float* out_min_max, int32_t max_points) {+ return job ? CJOB(job)->peaks(out_min_max, max_points) : 0;+}+int64_t nota_audio_import_peak_table(const NotaAudioImport* job, float* out, int64_t max_floats) {+ if (!job || !CJOB(job)->buffer()) return 0;+ const auto& t = CJOB(job)->buffer()->peakTable;+ const int64_t n = static_cast<int64_t>(t.size());+ if (out && max_floats > 0) std::memcpy(out, t.data(), sizeof(float) * static_cast<size_t>(std::min(n, max_floats)));+ return n;+}+int32_t nota_audio_import_seed_peak_table(NotaAudioImport* job, const float* table, int64_t count) {+ return job && JOB(job)->seedPeakTable(table, count) ? 1 : 0;+}+double nota_audio_import_detect_tempo(const NotaAudioImport* job) {+ return job ? CJOB(job)->detectTempo() : 0.0;+}+int32_t nota_track_add_imported_clip(NotaEngine* e, int32_t track_id, const NotaAudioImport* job, double start_beat) {+ if (!e || !job || !CJOB(job)->done()) return -1;+ return ENG(e)->addAudioClipBuffer(track_id, CJOB(job)->buffer(), start_beat);+}+double nota_clip_auto_warp_bpm(NotaEngine* e, int32_t track_id, int32_t clip_index, double bpm) {+ return e ? ENG(e)->autoWarpClip(track_id, clip_index, bpm) : 0.0;+}++} // extern "C"diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex b07080c5..27eb9498 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -12203,5 +12203,141 @@ Console.WriteLine("-- MCP tools --");Check(te.Undo() && te.GetClipNotes(tt, tc).Length == toolSrc.Length, "applying a tool is one undo step");}+// --- background audio import: block-wise decode off the UI thread ---+Console.WriteLine("-- background audio import --");+{+ string dir = Path.Combine(Path.GetTempPath(), "nota_import_" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(dir);+ try+ {+ // 30 s of 128 BPM clicks in stereo with a slow swell, long enough for the peak table path.+ string clicks = Path.Combine(dir, "clicks.wav");+ Nota.SmokeTest.WavWriter.WriteClicks(clicks, bpm: 128.0, seconds: 30.0, sampleRate: 44100);+ string swell = Path.Combine(dir, "swell.wav");+ Nota.SmokeTest.WavWriter.WriteStereo(swell, 30.0, 44100, i =>+ {+ double env = 0.1 + 0.8 * Math.Abs(Math.Sin(Math.PI * i / (44100.0 * 7)));+ double v = env * Math.Sin(2 * Math.PI * 220 * i / 44100.0);+ return (v, 0.5 * v);+ });++ using var ie = new NotaEngine();+ ie.SetBpm(120); ie.SetTimeSignature(4, 4);++ Check(ie.OpenAudioImport(Path.Combine(dir, "missing.wav")) is null, "import: unreadable file → null");++ using (var job = ie.OpenAudioImport(swell)!)+ {+ Check(job is not null && job.TotalFrames == 44100 * 30 && job.Channels == 2 && job.SampleRate == 44100,+ $"import: header read up front ({job?.TotalFrames} frames, {job?.Channels} ch)");+ // Decode one small block → only the head of the waveform is drawable.+ Check(job!.Step(44100) == 1 && job.DecodedFrames == 44100, "import: step decodes one block");+ var early = new float[256 * 2];+ int en = job.ReadPeaks(early, 256);+ bool headReady = early[0] <= early[1], tailPending = early[(en - 1) * 2] > early[(en - 1) * 2 + 1];+ Check(en == 256 && headReady && tailPending, "import: partial peaks — decoded head drawn, tail pending (1,-1)");+ int guard = 0;+ while (job.Step(1 << 16) == 1 && ++guard < 10000) { }+ Check(job.IsDone && job.DecodedFrames == job.TotalFrames, "import: decodes to completion");+ var done = new float[256 * 2];+ job.ReadPeaks(done, 256);+ bool allReady = true;+ for (int b = 0; b < 256; b++) if (done[b * 2] > done[b * 2 + 1]) allReady = false;+ Check(allReady, "import: every bucket drawable once done");++ int it = ie.AddAudioTrack();+ int ic = ie.AddImportedAudioClip(it, job, 0.0);+ Check(ic >= 0, "import: finished buffer placed on a track");++ // Engine peaks (table path: 256 buckets over 1.3M frames) vs a brute-force reference.+ Check(ie.TryGetAudioClipInfo(it, ic, out var iai), "import: clip info");+ var raw = ie.ReadSample(iai.SampleId);+ long rawFrames = raw.Length / 2;+ var got = new float[256 * 2];+ int gn = ie.GetClipPeaks(it, ic, got, 256);+ long per = rawFrames / gn;+ double worst = 0;+ for (int b = 0; b < gn; b++)+ {+ float mn = 1, mx = -1;+ for (long f = b * per; f < (b + 1) * per; f++) { float m = 0.5f * (raw[f * 2] + raw[f * 2 + 1]); mn = Math.Min(mn, m); mx = Math.Max(mx, m); }+ worst = Math.Max(worst, Math.Max(Math.Abs(mn - got[b * 2]), Math.Abs(mx - got[b * 2 + 1])));+ }+ Check(gn == 256 && worst < 1e-6, $"import: table-based peaks match a full scan (max err {worst:E1})");++ // Seeding a fresh job with the table shows the WHOLE waveform before any decode.+ var table = job.ReadPeakTable();+ using var seeded = ie.OpenAudioImport(swell)!;+ Check(seeded.SeedPeakTable(table), "import: cached overview accepted");+ var sp = new float[256 * 2];+ seeded.ReadPeaks(sp, 256);+ double sd = 0;+ for (int i = 0; i < 512; i++) sd = Math.Max(sd, Math.Abs(sp[i] - done[i]));+ Check(seeded.DecodedFrames == 0 && sd < 0.02, $"import: seeded waveform complete before decoding (max diff {sd:E1})");+ Check(!seeded.SeedPeakTable(new float[10]), "import: overview of another length rejected");+ }++ // Same file through the old synchronous path and the import job → identical audio.+ using var se = new NotaEngine();+ se.SetBpm(120); se.SetTimeSignature(4, 4);+ int st2 = se.AddAudioTrack();+ int sc2 = se.AddAudioClip(st2, clicks, 0.0);+ double syncBpm = se.AutoWarpClip(st2, sc2);++ int ct = ie.AddAudioTrack();+ double jobBpm;+ int cc;+ using (var cj = ie.OpenAudioImport(clicks)!)+ {+ while (cj.Step(1 << 16) == 1) { }+ jobBpm = cj.DetectTempo();+ cc = ie.AddImportedAudioClip(ct, cj, 0.0);+ } // disposing the job must not free the buffer the engine now plays+ Check(Math.Abs(jobBpm - syncBpm) < 1e-9 && Math.Abs(jobBpm - 128) < 8,+ $"import: worker tempo matches auto-warp's ({jobBpm:F1} vs {syncBpm:F1})");+ ie.SetDeferWarpBuild(true);+ double used = ie.AutoWarpClipAtBpm(ct, cc, jobBpm);+ ie.SetDeferWarpBuild(false);+ ie.TryGetAudioClipInfo(ct, cc, out var wa);+ se.TryGetAudioClipInfo(st2, sc2, out var wb);+ Check(used == jobBpm && wa.WarpEnabled != 0 && wa.WarpBeats == wb.WarpBeats,+ $"import: warp with the known tempo matches auto-warp ({wa.WarpBeats} vs {wb.WarpBeats} beats)");+ Check(ie.WarpBuildRemaining > 0, "import: warp cache deferred for sliced building");+ long guard2 = 0;+ while (ie.WarpBuildStep(48000) > 0 && ++guard2 < 100000) { }+ Check(ie.WarpBuildRemaining == 0, "import: sliced warp build completes");++ // Only the imported clicks track plays in both engines → the renders must agree.+ for (int i = 0; i < ie.TrackCount; i++)+ if (ie.TryGetTrackInfo(i, out var ti2) && ti2.Id != ct) ie.SetTrackMute(ti2.Id, true);+ var ra = new float[8192 * 2]; var rb = new float[8192 * 2];+ ie.Play(); se.Play();+ ie.RenderOffline(ra, 8192); se.RenderOffline(rb, 8192);+ double rd = 0; for (int i = 0; i < ra.Length; i++) rd = Math.Max(rd, Math.Abs(ra[i] - rb[i]));+ Check(Rms(ra, 8192) > 0.001f && rd < 1e-5, $"import: plays identically to the synchronous load (max diff {rd:E1})");++ // Analysis cache: content fingerprint + round trip in a project's analysis/ folder.+ string? k1 = Nota.Infrastructure.AudioAnalysisCache.Fingerprint(clicks);+ string copy = Path.Combine(dir, "renamed copy.wav");+ File.Copy(clicks, copy);+ Check(k1 is not null && k1 == Nota.Infrastructure.AudioAnalysisCache.Fingerprint(copy),+ "cache: fingerprint follows content, not the file name");+ Check(k1 != Nota.Infrastructure.AudioAnalysisCache.Fingerprint(swell), "cache: different audio → different key");+ var cache = new Nota.Infrastructure.AudioAnalysisCache();+ string bundle = Path.Combine(dir, "Song.nota");+ Directory.CreateDirectory(bundle);+ var entry = new Nota.Infrastructure.AudioAnalysis(new float[] { -0.5f, 0.5f, -0.25f, 0.75f }, 128.0);+ cache.Store(k1!, entry, bundle);+ Check(File.Exists(Path.Combine(bundle, "analysis", k1 + ".npk")), "cache: stored in the project's analysis/ folder");+ var back = cache.TryLoad(k1!, bundle);+ Check(back is not null && back.Bpm == 128.0 && back.PeakTable.SequenceEqual(entry.PeakTable), "cache: round trip");+ Check(cache.TryLoad("0000000000000000", bundle) is null, "cache: miss → null");+ }+ finally+ {+ try { Directory.Delete(dir, true); } catch { }+ }+}+Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");return failures == 0 ? 0 : 1;