Skip to content

armgit / nota

Public Imported from GitHub
0

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

(perf) Split, trim and cut of a warped clip reuse its stretch; long clips draw at full detail (#320)

Chris Laupama84c5174e2394
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a0a52c2..e20c7241 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,13 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
**Ungroup rack**). A device with a sidechain key, automation or CV links stays where it is
and the status line says why. ⌘G on tracks still groups tracks.
+### Changed
+- **Splitting a long warped clip is instant** (nota-daw/nota#299, nota-daw/nota#259): a split,
+ trim or range cut of a warped clip reuses the stretch the clip already has instead of
+ stretching both halves again on the UI thread (13 s for a 20-minute clip before), and the
+ halves play exactly what the clip played. Long or zoomed-in audio clips draw their waveform
+ at full detail instead of in blocks.
+
### Fixed
- **⌘G on a device, follow-ups** (nota-daw/nota#257): grouping a playing effect no longer
resets it (a Reverb kept ringing cut off), an effect an Arp's CC lane drives stays out of a
diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.cs
index bf3e349f..50c7b0c9 100644
--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs
+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs
@@ -42,6 +42,11 @@ public sealed partial class ArrangementView
private float[]? _rpPeaks;
private int _rpCount;
private double _rpMTotal, _rpS0, _rpS1; // material total + committed window (frames for unwarped, beats for warped)
+ private bool _rpWarped;
+ private int _rpTrack, _rpClip;
+ private float[]? _rpDetail; // the lane's visible material at one bucket per pixel (#299)
+ private int _rpDetailCount;
+ private double _rpDetailM0, _rpDetailM1;
private const double EdgePx = 6;
// ADSR handles on audio clips (shown on hover / selection). A drag previews on the
@@ -1653,7 +1658,7 @@ public sealed partial class ArrangementView
// DrawWaveform already clip themselves to the rect they are handed.
var contentRect = new Rect(rect.X, rect.Y + BandH, rect.Width, Math.Max(0, rect.Height - BandH));
if (c.IsMidi) DrawNotes(ctx, c, contentRect, content, pitches, appear);
- else DrawWaveform(ctx, c, contentRect, content);
+ else DrawWaveform(ctx, c, contentRect, content, trackId);
// The title band: the track colour mixed 30% toward black across the top, the
// accent when the clip is selected; the name sits on it in derived ink. It is drawn
@@ -1721,7 +1726,8 @@ public sealed partial class ArrangementView
// peaks over the whole warp, window = played beats. Cleared on release/cancel.
private void CaptureResizePreview(int trackId, int clipIndex)
{
- _rpPeaks = null; _rpCount = 0;
+ _rpPeaks = null; _rpCount = 0; _rpDetail = null;
+ (_rpTrack, _rpClip) = (trackId, clipIndex);
var eng = _o._engine;
if (eng is null || !eng.TryGetAudioClipInfo(trackId, clipIndex, out var ai)) return;
const int buckets = 2048;
@@ -1730,7 +1736,7 @@ public sealed partial class ArrangementView
{
int n = eng.GetClipWarpFullPeaks(trackId, clipIndex, peaks, buckets);
if (n <= 0) return;
- _rpCount = n; _rpPeaks = peaks;
+ _rpCount = n; _rpPeaks = peaks; _rpWarped = true;
_rpMTotal = ai.WarpBeats;
_rpS0 = ai.WarpPlayStart;
_rpS1 = ai.WarpPlayEnd > 0 ? ai.WarpPlayEnd : ai.WarpBeats;
@@ -1740,7 +1746,7 @@ public sealed partial class ArrangementView
if (ai.SampleId == 0 || !eng.TryGetSampleInfo(ai.SampleId, out var si) || si.Frames <= 0) return;
int n = eng.GetClipSourcePeaks(trackId, clipIndex, peaks, buckets);
if (n <= 0) return;
- _rpCount = n; _rpPeaks = peaks;
+ _rpCount = n; _rpPeaks = peaks; _rpWarped = false;
_rpMTotal = si.Frames;
_rpS0 = ai.SourceOffsetFrames;
double len = ai.LengthFrames > 0 ? ai.LengthFrames : si.Frames - ai.SourceOffsetFrames;
@@ -1757,18 +1763,38 @@ public sealed partial class ArrangementView
double ppb = _o._pixelsPerBeat, scroll = _o._scrollBeats;
double rate = (_rpS1 - _rpS0) / _origLen; // material units per timeline beat (committed)
double vx0 = Math.Max(r.X, 0), vx1 = Math.Min(r.Right, Bounds.Width);
+ double MaterialAt(double px) => _rpS0 + (scroll + px / ppb - _origStart) * rate;
+ // The whole-material overview, or — when the lane shows it wider than it has buckets —
+ // the material under the whole lane at one bucket per pixel, fetched once per drag (#299).
+ float[] pk = _rpPeaks!;
+ int count = _rpCount;
+ double m0 = 0, m1 = _rpMTotal;
+ double lm0 = Math.Clamp(MaterialAt(0), 0, _rpMTotal), lm1 = Math.Clamp(MaterialAt(Bounds.Width), 0, _rpMTotal);
+ if (lm1 > lm0 && (lm1 - lm0) / _rpMTotal * _rpCount * 1.5 < Bounds.Width && _o._engine is { } eng)
+ {
+ int n = Math.Clamp((int)Math.Ceiling(Bounds.Width), 1, 8192);
+ if (_rpDetail is null || _rpDetailCount <= 0 || _rpDetailM0 != lm0 || _rpDetailM1 != lm1)
+ {
+ _rpDetail ??= new float[8192 * 2];
+ _rpDetailCount = _rpWarped
+ ? eng.GetClipWarpPeaksRange(_rpTrack, _rpClip, lm0, lm1, _rpDetail, n)
+ : eng.GetClipSourcePeaksRange(_rpTrack, _rpClip, lm0, lm1, _rpDetail, n);
+ (_rpDetailM0, _rpDetailM1) = (lm0, lm1);
+ }
+ if (_rpDetailCount > 0) (pk, count, m0, m1) = (_rpDetail, _rpDetailCount, lm0, lm1);
+ }
var geo = new StreamGeometry();
using (var g = geo.Open())
ForEachWaveColumn(r.X, vx0, vx1, (cx0, cx1, x) =>
{
// Material span under this column, anchored to the committed window.
- double s0 = _rpS0 + (scroll + cx0 / ppb - _origStart) * rate;
- double s1 = _rpS0 + (scroll + cx1 / ppb - _origStart) * rate;
- double f0 = Math.Clamp(s0 / _rpMTotal, 0, 1), f1 = Math.Clamp(s1 / _rpMTotal, 0, 1);
- int b0 = Math.Clamp((int)(f0 * _rpCount), 0, _rpCount - 1);
- int b1 = Math.Clamp((int)Math.Ceiling(f1 * _rpCount), b0 + 1, _rpCount);
+ double s0 = MaterialAt(cx0), s1 = MaterialAt(cx1);
+ double f0 = Math.Clamp((s0 - m0) / (m1 - m0), 0, 1), f1 = Math.Clamp((s1 - m0) / (m1 - m0), 0, 1);
+ if (s1 <= 0 || s0 >= _rpMTotal) return; // past the material's ends: nothing to draw
+ int b0 = Math.Clamp((int)(f0 * count), 0, count - 1);
+ int b1 = Math.Clamp((int)Math.Ceiling(f1 * count), b0 + 1, count);
float min = 1f, max = -1f;
- for (int b = b0; b < b1; b++) { min = Math.Min(min, _rpPeaks![b * 2]); max = Math.Max(max, _rpPeaks[b * 2 + 1]); }
+ for (int b = b0; b < b1; b++) { min = Math.Min(min, pk[b * 2]); max = Math.Max(max, pk[b * 2 + 1]); }
if (min > max) return;
min = Math.Clamp(min * gain, -1f, 1f); max = Math.Clamp(max * gain, -1f, 1f);
AddWaveColumn(g, x, mid, amp, min, max);
@@ -1811,7 +1837,7 @@ public sealed partial class ArrangementView
AddRect(g, x, mid - a, 1, Math.Max(1, 2 * a));
}
- private void DrawWaveform(DrawingContext ctx, ClipVM c, Rect r, IBrush brush)
+ private void DrawWaveform(DrawingContext ctx, ClipVM c, Rect r, IBrush brush, int trackId = -1)
{
// While resizing THIS clip, show the real audio revealed/hidden by the drag.
if ((_drag == Drag.TrimL || _drag == Drag.TrimR) && ReferenceEquals(c, _dragClip)
@@ -1826,16 +1852,29 @@ public sealed partial class ArrangementView
// One column per stroke (see ForEachWaveColumn), aggregating every peak bucket that
// falls in the span it stands for, so nothing between strokes is skipped.
double vx0 = Math.Max(r.X, 0), vx1 = Math.Min(r.Right, Bounds.Width);
+ if (vx1 <= vx0) return;
+ // The whole-clip overview, or — when the clip is drawn wider than it has buckets —
+ // peaks for just the visible slice at one bucket per pixel (#299).
+ float[] pk = c.Peaks;
+ int count = c.PeakCount;
+ double fa = 0, fb = 1;
+ if (r.Width > c.PeakCount * 1.5 && EnsureDetailPeaks(c, trackId, (vx0 - r.X) / r.Width, (vx1 - r.X) / r.Width,
+ (int)Math.Ceiling(vx1 - vx0), r.Width))
+ {
+ (pk, count, fa, fb) = (c.DetailPeaks!, c.DetailCount, c.DetailF0, c.DetailF1);
+ }
+ double span = (fb - fa) * r.Width;
var adsr = c.Adsr.Fit(c.LengthBeats);
bool shaped = !adsr.IsIdentity;
var geo = new StreamGeometry();
using (var gc = geo.Open())
ForEachWaveColumn(r.X, vx0, vx1, (cx0, cx1, x) =>
{
- int b0 = Math.Clamp((int)((cx0 - r.X) / r.Width * c.PeakCount), 0, c.PeakCount - 1);
- int b1 = Math.Clamp((int)Math.Ceiling((cx1 - r.X) / r.Width * c.PeakCount), b0 + 1, c.PeakCount);
+ double ox = r.X + fa * r.Width;
+ int b0 = Math.Clamp((int)((cx0 - ox) / span * count), 0, count - 1);
+ int b1 = Math.Clamp((int)Math.Ceiling((cx1 - ox) / span * count), b0 + 1, count);
float min = 1f, max = -1f;
- for (int b = b0; b < b1; b++) { min = Math.Min(min, c.Peaks[b * 2]); max = Math.Max(max, c.Peaks[b * 2 + 1]); }
+ for (int b = b0; b < b1; b++) { min = Math.Min(min, pk[b * 2]); max = Math.Max(max, pk[b * 2 + 1]); }
if (min > max) return;
// Clip gain (and the ADSR shape) scales the drawn waveform, matching the clip editor.
float g = c.Gain;
@@ -1846,6 +1885,44 @@ public sealed partial class ArrangementView
ctx.DrawGeometry(brush, null, geo);
}
+ // Fill c.DetailPeaks for the played-length fractions [f0, f1] at n buckets, unless what
+ // it holds already matches to within half a pixel. Played order, like Peaks: a reversed
+ // clip reads its window back to front. False when the engine has nothing for it.
+ private bool EnsureDetailPeaks(ClipVM c, int trackId, double f0, double f1, int n, double widthPx)
+ {
+ n = Math.Clamp(n, 1, 8192);
+ if (c.DetailPeaks is not null && c.DetailCount == n
+ && Math.Abs(c.DetailF0 - f0) * widthPx < 0.5 && Math.Abs(c.DetailF1 - f1) * widthPx < 0.5)
+ return true;
+ var eng = _o._engine;
+ if (eng is null || trackId <= 0 || !eng.TryGetAudioClipInfo(trackId, c.ClipIndex, out var ai)) return false;
+ bool rev = ai.Reversed != 0;
+ double a = rev ? 1 - f1 : f0, b = rev ? 1 - f0 : f1; // file-order fractions of the window
+ var buf = c.DetailPeaks is { } old && old.Length >= n * 2 ? old : new float[n * 2];
+ int got;
+ if (ai.WarpEnabled != 0 && ai.WarpBeats > 0)
+ {
+ double ps = ai.WarpPlayStart, pe = ai.WarpPlayEnd > 0 ? ai.WarpPlayEnd : ai.WarpBeats;
+ got = eng.GetClipWarpPeaksRange(trackId, c.ClipIndex, ps + a * (pe - ps), ps + b * (pe - ps), buf, n);
+ }
+ else
+ {
+ double len = ai.LengthFrames;
+ if (len <= 0 && eng.TryGetSampleInfo(ai.SampleId, out var si)) len = si.Frames - ai.SourceOffsetFrames;
+ if (len <= 0) return false;
+ got = eng.GetClipSourcePeaksRange(trackId, c.ClipIndex, ai.SourceOffsetFrames + a * len, ai.SourceOffsetFrames + b * len, buf, n);
+ }
+ if (got <= 0) return false;
+ if (rev)
+ for (int i = 0, j = got - 1; i < j; i++, j--)
+ {
+ (buf[i * 2], buf[j * 2]) = (buf[j * 2], buf[i * 2]);
+ (buf[i * 2 + 1], buf[j * 2 + 1]) = (buf[j * 2 + 1], buf[i * 2 + 1]);
+ }
+ (c.DetailPeaks, c.DetailCount, c.DetailF0, c.DetailF1) = (buf, got, f0, f1);
+ return true;
+ }
+
private static readonly IPen AutoCurvePen = new Pen(NotaPalette.VizInk, 1.6);
private void DrawAutomation(DrawingContext ctx, double w)
diff --git a/src/managed/Nota.App/ArrangementView.Vms.cs b/src/managed/Nota.App/ArrangementView.Vms.cs
index fd357d4a..0dcc983a 100644
--- a/src/managed/Nota.App/ArrangementView.Vms.cs
+++ b/src/managed/Nota.App/ArrangementView.Vms.cs
@@ -76,6 +76,13 @@ public sealed partial class ArrangementView
public bool Active = true; // false = deactivated (key 0): stays but silent + greyed
public float[]? Peaks;
public int PeakCount;
+ /// <summary>Peaks over just the visible slice [DetailF0, DetailF1] of the clip (fractions
+ /// of its played length), at one bucket per pixel — fetched when the clip is drawn wider
+ /// than <see cref="Peaks"/> has buckets, so a long or zoomed-in clip doesn't draw as
+ /// blocks (#299).</summary>
+ public float[]? DetailPeaks;
+ public int DetailCount;
+ public double DetailF0, DetailF1;
/// <summary>Clip gain (linear) — peaks are raw material, the lane scales them by this.</summary>
public float Gain = 1f;
/// <summary>Audio clip ADSR amplitude shape (identity = full length, full level).</summary>
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 12d27f62..6e17b6b6 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -1025,6 +1025,7 @@ public sealed partial class ArrangementView : UserControl
// Unchanged audio clip on a live refresh: reuse the peaks (no native recompute).
cvm.Peaks = prev.Peaks;
cvm.PeakCount = prev.PeakCount;
+ (cvm.DetailPeaks, cvm.DetailCount, cvm.DetailF0, cvm.DetailF1) = (prev.DetailPeaks, prev.DetailCount, prev.DetailF0, prev.DetailF1);
}
else
{
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index fe5ae97f..9c060848 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -1525,17 +1525,21 @@ void Engine::mixAudioClip(
const WarpCache& wc = *clip.warpCache;
// A stale cache (an edit's rebuild still running in the background) keeps playing,
// clipped to the clip's new played length so it never spills past the clip's end.
- const double clipDeviceLen =
- static_cast<double>(std::min<int64_t>(wc.frames, std::llround(clip.warpPlayLen() * spb)));
+ // Both edges sit on whole frames rounded from the timeline (not start + a rounded
+ // length), so clips that meet — the halves of a split — leave no frame between them.
+ const int64_t startF = std::llround(startSamples);
+ const int64_t endF =
+ std::min<int64_t>(startF + wc.frames, std::llround(startSamples + clip.warpPlayLen() * spb));
+ const double clipDeviceLen = static_cast<double>(endF - startF);
lenBeats = clipDeviceLen / spb;
- const double ovStart = std::max(blockStart, startSamples);
- const double ovEnd = std::min(blockStart + frames, startSamples + clipDeviceLen);
+ const double ovStart = std::max(blockStart, static_cast<double>(startF));
+ const double ovEnd = std::min(blockStart + frames, static_cast<double>(endF));
if (ovEnd <= ovStart) return;
const int32_t dstOff = static_cast<int32_t>(std::llround(ovStart - blockStart));
const int32_t segLen = static_cast<int32_t>(std::llround(ovEnd - ovStart));
if (segLen <= 0 || dstOff < 0 || dstOff + segLen > frames) return;
- const int64_t cacheBase = std::llround(ovStart - startSamples); // 0-based into the cache
- const float* csamp = wc.samples.data();
+ const int64_t cacheBase = std::llround(ovStart) - startF; // 0-based into the cache
+ const float* csamp = wc.data();
const float g = clip.gain * extraGain;
for (int32_t j = 0; j < segLen; ++j) {
// Reverse reads the same cache back-to-front: the window is already the
diff --git a/src/native/nota.engine/src/engine/Engine_Session.cpp b/src/native/nota.engine/src/engine/Engine_Session.cpp
index b6b007ab..34f21744 100644
--- a/src/native/nota.engine/src/engine/Engine_Session.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Session.cpp
@@ -516,7 +516,7 @@ SessionSlot Engine::slotFromAudioClip(const AudioClip& a) {
s.audio = a;
s.audio.startBeat = 0.0;
s.audio.active = true;
- if (warpNeedsBuild(s.audio)) // a clipboard copy dropped its cache (or it is stale)
+ if (warpNeedsBuild(s.audio)) // a stale cache, or a copied clip narrowed to the slot
configureClipWarp(s.audio, transport_.samplesPerBeat(), transport_.sampleRate());
s.name = a.name;
const double beats = audioClipBeats(s.audio);
@@ -797,7 +797,6 @@ int32_t Engine::sessionSlotsToArrangement(
b.audio = sl->audio;
b.audio.name = sl->name;
b.audio.active = true;
- b.audio.warpCache = nullptr; // placeBlock rebuilds it
b.len = audioClipBeats(b.audio);
}
at += b.len;
diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
index e74d0dd8..10020449 100644
--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
@@ -188,6 +188,43 @@ bool renderWarpWindow(const WarpInputs& in, const SampleBuffer& sample, float* o
// block); the in-use cache retires with the old snapshot, so it's race-free.
// For a big project this is heavy (stretches every clip's played window), so the load
// path defers it to Engine::warpBuildStep — see Engine::configureClipWarp.
+// Make the clip's cache current without stretching, when its current cache already holds
+// the audio (#299): the same inputs → keep it; the same stretch over a window that contains
+// the clip's new played window (a split, a trim, a range carve) → a slice sharing its samples.
+// The slice is the very audio the wider window played there, so a cut is seamless. False when
+// the cache can't serve (a tempo / pitch / mode / marker change, or a wider window).
+bool reuseWarpCache(AudioClip& c, double spb, double devSR) {
+ if (!c.warpCache) return false;
+ const WarpCache& old = *c.warpCache;
+ WarpInputs want = warpInputsOf(c, spb, devSR);
+ if (old.inputs == want) return true;
+ WarpInputs same = want; // everything but the window must match
+ same.playStart = old.inputs.playStart;
+ same.playEnd = old.inputs.playEnd;
+ constexpr double eps = 1e-9;
+ if (!(old.inputs == same) || want.playStart < old.inputs.playStart - eps || want.playEnd > old.inputs.playEnd + eps)
+ return false;
+ // The offset is taken from the cache that owns the samples, not added up slice by
+ // slice, so repeated splits don't each round and drift off the original audio.
+ std::shared_ptr<const WarpCache> root = old.base ? old.base : c.warpCache;
+ // Both ends are rounded on the owner's frame grid, so neighbouring slices meet exactly.
+ const int64_t offset = std::clamp<int64_t>(
+ std::llround((want.playStart - root->inputs.playStart) * spb), 0, root->frames);
+ const int64_t end = std::clamp<int64_t>(
+ std::llround((want.playEnd - root->inputs.playStart) * spb), offset, root->frames);
+ const int64_t frames = end - offset;
+ if (frames <= 0) return false;
+ auto slice = std::make_shared<WarpCache>();
+ slice->frames = frames;
+ slice->spb = old.spb;
+ slice->devSR = old.devSR;
+ slice->inputs = std::move(want);
+ slice->base = std::move(root);
+ slice->baseOffset = offset;
+ c.warpCache = std::move(slice);
+ return true;
+}
+
void buildWarpCache(AudioClip& c, double spb, double devSR) {
if (c.warpMarkers.size() >= 2) c.warpBeats = c.warpMarkers.back().beat;
const int64_t frames = warpCacheFrames(c, spb, devSR);
@@ -195,6 +232,7 @@ void buildWarpCache(AudioClip& c, double spb, double devSR) {
c.warpCache = nullptr;
return;
}
+ if (reuseWarpCache(c, spb, devSR)) return;
auto cache = std::make_shared<WarpCache>();
cache->frames = frames;
@@ -258,6 +296,8 @@ void Engine::configureClipWarp(AudioClip& c, double spb, double devSR) {
c.warpCache = nullptr;
return;
}
+ if (c.warpMarkers.size() >= 2) c.warpBeats = c.warpMarkers.back().beat;
+ if (warpCacheFrames(c, spb, devSR) > 0 && reuseWarpCache(c, spb, devSR)) return; // free, so even when deferred
if (deferWarpBuild_) return; // stale (or no) cache until warpBuildStep / warpBuildPoll
buildWarpCache(c, spb, devSR);
}
@@ -2403,7 +2443,7 @@ int32_t Engine::duplicateClip(int32_t trackId, int32_t clipIndex) {
auto snips = captureClipAutomation(*nt, srcStart, srcStart + len);
d.startBeat = srcStart + len;
audioOverwriteRange(nt->clips, d.startBeat, d.startBeat + len, spb, devSR);
- if (d.warpEnabled) configureClipWarp(d, spb, devSR); // the copy needs its own stretcher
+ if (d.warpEnabled) configureClipWarp(d, spb, devSR); // shares the source's cache when it's current
nt->clips.push_back(d);
newIdx = static_cast<int32_t>(nt->clips.size()) - 1;
applyClipAutomation(*nt, trackId, snips, d.startBeat, len, /*sameTrack*/ true);
@@ -2529,7 +2569,6 @@ bool Engine::copyClip(int32_t trackId, int32_t clipIndex) {
} else {
if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return false;
clipboardAudio_ = t->clips[clipIndex];
- clipboardAudio_.warpCache = nullptr; // paste rebuilds the cache
clipboardKind_ = 0;
start = clipboardAudio_.startBeat;
len = audioDisplayLenBeats(clipboardAudio_, spb, devSR);
@@ -2555,7 +2594,6 @@ bool Engine::cutClip(int32_t trackId, int32_t clipIndex) {
} else {
if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(nt->clips.size())) return false;
clipboardAudio_ = nt->clips[clipIndex];
- clipboardAudio_.warpCache = nullptr;
clipboardKind_ = 0;
start = clipboardAudio_.startBeat;
len = audioDisplayLenBeats(clipboardAudio_, spb, devSR);
@@ -2626,7 +2664,6 @@ std::vector<Engine::BlockClip> Engine::captureBlock(
if (ci < 0 || ci >= static_cast<int32_t>(t->clips.size())) continue;
b.kind = 0;
b.audio = t->clips[ci];
- b.audio.warpCache = nullptr; // copy rebuilds the cache
s = b.audio.startBeat;
b.len = audioDisplayLenBeats(b.audio, spb, devSR);
}
@@ -2728,7 +2765,7 @@ void Engine::placeBlock(const std::vector<BlockClip>& items, double placedStart,
} else {
AudioClip a = b.audio;
a.startBeat = start;
- if (a.warpEnabled) configureClipWarp(a, spb, devSR); // the copy needs its own stretcher
+ if (a.warpEnabled) configureClipWarp(a, spb, devSR); // reuses the copied cache when it is current
nt.clips.push_back(a);
newIdx = static_cast<int32_t>(nt.clips.size()) - 1;
}
@@ -2793,7 +2830,6 @@ bool Engine::copyRange(const std::vector<int32_t>& trackIds, double start, doubl
BlockClip b;
b.kind = 0;
b.audio = audioSlice(c, start, end, spb, devSR);
- b.audio.warpCache = nullptr; // the paste rebuilds the cache
b.len = audioDisplayLenBeats(b.audio, spb, devSR);
const double s = b.audio.startBeat;
add(std::move(b), s);
diff --git a/src/native/nota.engine/src/media/Warp.h b/src/native/nota.engine/src/media/Warp.h
index efbbd889..06447aaf 100644
--- a/src/native/nota.engine/src/media/Warp.h
+++ b/src/native/nota.engine/src/media/Warp.h
@@ -58,11 +58,18 @@ struct WarpInputs {
// mode, markers, the play window, or the device sample rate. Clip gain is applied
// at read time (NOT baked), so gain changes need no rebuild.
struct WarpCache {
- std::vector<float> samples; // interleaved stereo, frames*2 (device rate)
+ std::vector<float> samples; // interleaved stereo, frames*2 (device rate); empty in a slice
int64_t frames = 0; // played-window length in device frames
double spb = 0.0; // device samples-per-beat this was built for
double devSR = 0.0; // device sample rate this was built for
WarpInputs inputs; // what it was stretched from (staleness check)
+ // A slice (#299): a split, trim or range carve narrows the played window, and the narrower
+ // window is a stretch of the same stream — so it shares the built cache's samples from
+ // `baseOffset` instead of stretching them again (seconds for a long clip). Always points
+ // at the cache that owns the samples, never at another slice.
+ std::shared_ptr<const WarpCache> base;
+ int64_t baseOffset = 0;
+ const float* data() const { return base ? base->samples.data() + baseOffset * 2 : samples.data(); }
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 6341e7e4..db13c0f1 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -385,6 +385,14 @@ if (args.Length >= 1 && args[0] == "--device-undo")
Console.WriteLine(failures == 0 ? "DEVICE UNDO PASSED" : $"DEVICE UNDO FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Warped clip split / range cut alone: `--warp-split`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--warp-split")
+{
+ Console.WriteLine("-- warp split --");
+ foreach (var (ok, label) in WarpSplitTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "WARP SPLIT PASSED" : $"WARP SPLIT FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Device copy / duplicate audit + rack undo alone: `--device-copy`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--device-copy")
{
@@ -15083,6 +15091,8 @@ foreach (var (ok, label) in DeviceCopyTests.Run()) Check(ok, label);
Console.WriteLine("-- stereo map --");
foreach (var (ok, label) in StereoMeasureTests.Run()) Check(ok, label);
+Console.WriteLine("-- warp split --");
+foreach (var (ok, label) in WarpSplitTests.Run()) Check(ok, label);
Console.WriteLine("-- filter knob glide --");
foreach (var (ok, label) in FilterGlideTests.Run()) Check(ok, label);
diff --git a/tests/Nota.SmokeTest/WarpSplitTests.cs b/tests/Nota.SmokeTest/WarpSplitTests.cs
new file mode 100644
index 00000000..a2815dbe
--- /dev/null
+++ b/tests/Nota.SmokeTest/WarpSplitTests.cs
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Splitting a warped clip (#299, #259). The halves of a split, and what a range cut leaves,
+// play the very stretch the clip played before — a slice of it, not a fresh stretch — so the
+// cut is seamless and the edit costs nothing however long the clip is (it used to re-stretch
+// both halves: ~13 s for a 20-minute clip).
+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --warp-split`.
+
+using System.Diagnostics;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class WarpSplitTests
+{
+ private const int Sr = 44100, Block = 512;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ string wav = Path.Combine(Path.GetTempPath(), "nota_smoke_warp_split.wav");
+ WavWriter.WriteSine(wav, seconds: 30.0, freq: 330, sampleRate: Sr);
+
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int t = e.AddAudioTrack();
+ int c = e.AddAudioClip(t, wav, 0.0);
+ e.SetClipWarp(t, c, true, 3);
+ e.SetClipWarpLength(t, c, 64); // 30 s stretched over 64 beats (32 s): a real stretch
+ var whole = Render(e, 16);
+
+ var sw = Stopwatch.StartNew();
+ int right = e.SplitClip(t, c, 7.3);
+ long ms = sw.ElapsedMilliseconds;
+ var split = Render(e, 16);
+ double diff = MaxDiff(whole, split);
+ yield return (right == c + 1 && diff < 1e-6, $"warp split: the halves play exactly what the clip played (max diff {diff:E1})");
+ yield return TimingBudget.Check(right == c + 1, ms < 100, $"warp split of a 30 s clip doesn't re-stretch it ({ms} ms)");
+
+ sw.Restart();
+ bool cut = e.CutRange(new[] { t }, 9.0, 10.0);
+ ms = sw.ElapsedMilliseconds;
+ var afterCut = Render(e, 16);
+ // Up to the cut and from its end on, the audio is the clip's own, untouched.
+ int cutA = (int)(9.0 * Sr / 2) * 2, cutB = (int)(10.0 * Sr / 2) * 2;
+ double before = MaxDiff(whole[..cutA], afterCut[..cutA]), after = MaxDiff(whole[(cutB + 2)..], afterCut[(cutB + 2)..]);
+ yield return (cut && before < 1e-6 && after < 1e-6, $"warp range cut: what's left plays as before ({before:E1}, {after:E1})");
+ yield return TimingBudget.Check(cut, ms < 100, $"warp range cut doesn't re-stretch ({ms} ms)");
+
+ // A beat that isn't a whole number of frames (123 BPM): split after split, each slice
+ // still lines up with the original stretch instead of drifting a frame per split.
+ using var f = new NotaEngine();
+ f.SetBpm(123);
+ Render(f, 1, 123); // the tempo lands before the clip is stretched
+ int ft = f.AddAudioTrack();
+ int fc = f.AddAudioClip(ft, wav, 0.0);
+ f.SetClipWarp(ft, fc, true, 3);
+ f.SetClipWarpLength(ft, fc, 64);
+ var fWhole = Render(f, 16, 123);
+ int last = fc;
+ for (int b = 1; b <= 6 && last >= 0; b++) last = f.SplitClip(ft, last, b);
+ var fr = Render(f, 16, 123);
+ double drift = MaxDiff(fWhole, fr);
+ for (int i = 0; i < fr.Length; i += 2) if (Math.Abs(fr[i] - fWhole[i]) > 1e-6) Console.WriteLine($"DBGD frame {i/2} beat {(i/2)/(Sr*60.0/123):F4} whole {fWhole[i]:F4} split {fr[i]:F4}");
+ yield return (last >= 0 && drift < 1e-6, $"six warp splits at 123 BPM still play the clip's own audio (max diff {drift:E1})");
+ }
+
+ // The first `beats` beats from the top, interleaved stereo.
+ private static float[] Render(NotaEngine e, double beats, double bpm = 120)
+ {
+ int frames = (int)(beats * Sr * 60 / bpm);
+ var all = new float[frames * 2];
+ var buf = new float[Block * 2];
+ e.Seek(0); e.Play();
+ for (int off = 0; off < frames; off += Block)
+ {
+ int n = Math.Min(Block, frames - off);
+ e.RenderOffline(buf, n, Sr);
+ Array.Copy(buf, 0, all, off * 2, n * 2);
+ }
+ e.StopTransport();
+ return all;
+ }
+
+ private static double MaxDiff(float[] a, float[] b)
+ {
+ double m = 0;
+ for (int i = 0; i < Math.Min(a.Length, b.Length); i++) m = Math.Max(m, Math.Abs(a[i] - b[i]));
+ return m;
+ }
+}
diff --git a/tests/perf/nota_perf.cpp b/tests/perf/nota_perf.cpp
index b40a45de..5dfc5da2 100644
--- a/tests/perf/nota_perf.cpp
+++ b/tests/perf/nota_perf.cpp
@@ -16,9 +16,13 @@
#include <algorithm>
#include <chrono>
#include <cmath>
+#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <random>
#include <string>
#include <vector>
@@ -90,6 +94,48 @@ void fillChords6(NotaEngine* e, int track, int transpose, double startBeat, doub
nota_clip_set_notes(e, track, clip, notes.data(), (int)notes.size());
}
+// An 8 s stereo 48 kHz WAV of a chord with a little noise (so the stretch has real work), in
+// the temp dir; the warp scenarios load it.
+// Each process writes its own file (perf-gate runs scenarios in parallel), removed once
+// the clip has loaded it.
+std::string warpTestWav() {
+ const auto path = (std::filesystem::temp_directory_path() /
+ ("nota_perf_warp_" + std::to_string(std::random_device{}()) + ".wav")).string();
+ constexpr double kTwoPi = 6.283185307179586;
+ const int sr = 48000, frames = sr * 8;
+ std::vector<int16_t> pcm((size_t)frames * 2);
+ uint32_t rnd = 1;
+ for (int i = 0; i < frames; ++i) {
+ const double t = (double)i / sr;
+ rnd = rnd * 1664525u + 1013904223u;
+ const double v = 0.25 * (std::sin(kTwoPi * 220 * t) + std::sin(kTwoPi * 277 * t) + std::sin(kTwoPi * 330 * t)) +
+ 0.05 * ((double)(rnd >> 8) / (1 << 24) - 0.5);
+ pcm[(size_t)i * 2] = pcm[(size_t)i * 2 + 1] = (int16_t)(std::clamp(v, -1.0, 1.0) * 32000);
+ }
+ std::ofstream f(path, std::ios::binary);
+ auto u32 = [&](uint32_t v) { f.write(reinterpret_cast<const char*>(&v), 4); };
+ auto u16 = [&](uint16_t v) { f.write(reinterpret_cast<const char*>(&v), 2); };
+ const uint32_t bytes = (uint32_t)pcm.size() * 2;
+ f.write("RIFF", 4); u32(36 + bytes); f.write("WAVEfmt ", 8); u32(16); u16(1); u16(2); u32(sr); u32(sr * 4); u16(4); u16(16);
+ f.write("data", 4); u32(bytes);
+ f.write(reinterpret_cast<const char*>(pcm.data()), bytes);
+ return path;
+}
+
+int gWarpTrack = -1; // the track warpedClipTrack made last
+
+// One audio track holding the 8 s WAV warped (Complex) over 16 beats, its stretch built.
+int warpedClipTrack(NotaEngine* e) {
+ const int t = nota_engine_add_audio_track(e);
+ const std::string wav = warpTestWav();
+ const bool loaded = t >= 0 && nota_track_add_audio_clip(e, t, wav.c_str(), 0.0) == 0;
+ std::error_code ec;
+ std::filesystem::remove(wav, ec);
+ if (!loaded) return -1;
+ if (nota_clip_set_warp(e, t, 0, 1, 3) != NOTA_OK) return -1;
+ return gWarpTrack = t;
+}
+
// Display names for the report; the scenario id (the kind number) is what is compared.
std::string instrumentName(int kind) {
switch (kind) {
@@ -156,6 +202,9 @@ std::vector<Scenario> scenarios() {
for (int n : {1, 4, 8, 16, 32}) s.push_back({"mix-" + std::to_string(n), std::to_string(n) + " tracks, all playing"});
s.push_back({"sparse-32", "32 tracks, 1 in 4 playing"});
s.push_back({"silent-32", "32 tracks, no clips"});
+ s.push_back({"audio-warp-split", "Warped audio clip split in 8, playing"});
+ // An edit, not a render: the measured loop splits a warped clip 8 times and undoes it (#299).
+ s.push_back({"edit-warp-split", "Split a warped 8 s clip 8x + undo (ms per edit)"});
return s;
}
@@ -211,6 +260,14 @@ bool build(NotaEngine* e, const std::string& id) {
}
return true;
}
+ if (id == "audio-warp-split" || id == "edit-warp-split") {
+ const int t = warpedClipTrack(e);
+ if (t < 0) return false;
+ if (id == "audio-warp-split")
+ for (int i = 1; i < 8; ++i)
+ if (nota_clip_split(e, t, i - 1, i * 2.0) < 0) return false;
+ return true;
+ }
int n = 0;
if (std::sscanf(id.c_str(), "mix-%d", &n) == 1) {
// The stress-test chain on each track: Volt + EQ-8 + Compressor + Auto Filter.
@@ -247,6 +304,19 @@ int run(const std::string& id, double seconds) {
nota_engine_destroy(e);
return 2;
}
+ if (id == "edit-warp-split") { // split the last piece 8 times, then undo them
+ constexpr int kEdits = 8;
+ const auto t0 = std::chrono::steady_clock::now();
+ CALLGRIND_START_INSTRUMENTATION;
+ for (int i = 0; i < kEdits; ++i) nota_clip_split(e, gWarpTrack, i, 1.5 + i * 1.75);
+ for (int i = 0; i < kEdits; ++i) nota_engine_undo(e);
+ CALLGRIND_STOP_INSTRUMENTATION;
+ const auto t1 = std::chrono::steady_clock::now();
+ nota_engine_destroy(e);
+ const double ms = std::chrono::duration<double, std::milli>(t1 - t0).count() / (2 * kEdits);
+ std::printf("%s\t%s\t%.3f\t%.4f\n", id.c_str(), label.c_str(), ms, 0.0);
+ return 0;
+ }
nota_transport_set_loop(e, 1, 0.0, 16.0);
nota_transport_seek(e, 0.0);
nota_transport_play(e);