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.

Add Reverse for audio clips

Egor Khindikaynenf15afe741c6f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be150f24..228ef130 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,17 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Reverse for audio clips.** A `Reverse` item in a clip's context menu and a DIRECTION
+ toggle in the clip editor play a clip backwards. It is non-destructive — the file and
+ any warp cache stay in playing order and only the read direction flips — so toggling is
+ instant, undoable and free to audition, and it composes with clip gain, pitch, warp and
+ the clip envelopes. Both the arrangement and the clip editor draw the waveform the way
+ it now sounds — the editor mirrors the whole view, so its Start/End brackets, warp
+ markers, BPM chips, beat grid and playback cursor all flip together and the screen still
+ reads left-to-right in playing order (the clip envelope is authored in played time, so
+ it stays put). Trimming, resizing and splitting a reversed clip mirror too, so the
+ audible head and tail follow the edit instead of jumping. Consolidate and Freeze bake
+ the reversal in.
- **Overview — a project strip above the arrangement.** The whole project on one band,
a mini-clip per clip in its track colour (a collapsed group still shows the clips it
hides), with the visible span drawn as a brass window over it and everything outside it
diff --git a/FEATURES.md b/FEATURES.md
index b7a6653b..158f51db 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -147,6 +147,12 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).
- **Import** of audio files by drag and drop: WAV / AIFF / FLAC / MP3.
- **Audio clip**: start and end, waveform drawing, trimming, split, fade in/out, clip
gain. Changing the length shows the material actually being revealed or hidden.
+- **Reverse** (clip editor ▸ DIRECTION, or the clip's context menu): plays the clip
+ backwards without touching the file, so it costs nothing to toggle and composes with
+ gain, pitch and warp. The arrangement lane and the clip editor both draw it the way it
+ sounds — the editor mirrors the whole view (brackets, warp markers, BPM chips, grid and
+ cursor included) so the screen reads left-to-right in playing order — and trims and
+ splits mirror, so the audible head and tail follow the edit.
- **Warp / time-stretch**: **Complex** and **Complex Pro** modes (the latter with formant
preservation, correct even when the sample rate and the device rate differ), plus
transient detection. A grid-snap toggle governs trimming a warped clip.
diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.cs
index 1cf37943..0563dc26 100644
--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs
+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs
@@ -899,6 +899,18 @@ public sealed partial class ArrangementView
InputGesture = new KeyGesture(Key.D0),
};
deact.Click += (_, _) => { EnsureSelected(); _o.ToggleSelectedClipsActive(); };
+ // Reverse (audio only): non-destructive, so the header reflects the clicked clip.
+ MenuItem? reverse = null;
+ if (!clip.IsMidi && _o._engine is { } rev && rev.TryGetAudioClipInfo(trackId, idx, out var rai))
+ {
+ bool on = rai.Reversed != 0;
+ reverse = new MenuItem
+ {
+ Header = on ? (inGroup ? "Un-reverse selection" : "Un-reverse")
+ : (inGroup ? "Reverse selection" : "Reverse"),
+ };
+ reverse.Click += (_, _) => { EnsureSelected(); _o.ToggleSelectedClipsReverse(); };
+ }
// Consolidate: a right-click inside the time selection acts on that range; otherwise
// on the multi-selection's span, or just this clip (bakes its edits into one clip).
bool inRange = _o.TimeSelectionCovers(trackId, beat);
@@ -927,6 +939,7 @@ public sealed partial class ArrangementView
flyout.Items.Add(new Separator());
flyout.Items.Add(split);
flyout.Items.Add(dup);
+ if (reverse is not null) flyout.Items.Add(reverse);
flyout.Items.Add(consolidate);
flyout.Items.Add(deact);
flyout.Items.Add(del);
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 3797b5c2..4d8dece8 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -1172,6 +1172,31 @@ public sealed partial class ArrangementView : UserControl
return any;
}
+ /// <summary>Reverse (non-destructive) on every selected AUDIO clip. Mixed selections
+ /// reverse the audio clips and leave MIDI alone; if any is still forwards the whole
+ /// selection turns on first, so a mixed state resolves to "all reversed".</summary>
+ public bool ToggleSelectedClipsReverse()
+ {
+ if (_engine is null) return false;
+ var sel = SelectionBlock();
+ if (sel.Length == 0) return false;
+ bool anyForward = false, anyAudio = false;
+ foreach (var (track, clip) in sel)
+ if (_engine.TryGetAudioClipInfo(track, clip, out var ai))
+ { anyAudio = true; if (ai.Reversed == 0) anyForward = true; }
+ if (!anyAudio) return false;
+ bool target = anyForward, any = false;
+ foreach (var (track, clip) in sel)
+ {
+ if (!_engine.TryGetAudioClipInfo(track, clip, out _)) continue; // MIDI / stale entry
+ _engine.SetClipReverse(track, clip, target);
+ RaiseClipGeometryChanged(track, clip); // an open clip editor re-reads the new direction
+ any = true;
+ }
+ if (any) Refresh();
+ return any;
+ }
+
public bool DeleteSelectedClips()
{
if (_engine is null || _sel.Count == 0) return false;
diff --git a/src/managed/Nota.App/AudioClipEditorView.cs b/src/managed/Nota.App/AudioClipEditorView.cs
index 08e0c8f0..d21540f2 100644
--- a/src/managed/Nota.App/AudioClipEditorView.cs
+++ b/src/managed/Nota.App/AudioClipEditorView.cs
@@ -48,6 +48,8 @@ public sealed class AudioClipEditorView : UserControl
private double _startBeat;
private double _lengthBeats = 4;
private int _pitch;
+ private bool _reversed;
+ private readonly TextBlock _reverseToggleText;
private bool _warpEnabled;
private int _warpMode = 3; // Complex
private bool _snapToGrid = true; // trim brackets snap to whole beats (default on)
@@ -106,6 +108,7 @@ public sealed class AudioClipEditorView : UserControl
_fileText = new TextBlock { Text = "—", FontSize = 9, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap };
_gain = new MiniFader(1.0, 2.0) { VerticalAlignment = VerticalAlignment.Center };
_gain.ValueChanged += v => { _engine.SetClipGain(TrackId, ClipIndex, (float)v); ShowGain(v); _wave.SetGain(v); _onChanged(); };
+ _reverseToggleText = new TextBlock { Text = "Reverse: Off", FontSize = 10, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
_snapToggleText = new TextBlock { Text = "Grid snap: On", FontSize = 10, Foreground = AccentBright, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
_warpToggleText = new TextBlock { Text = "Warp: Off", FontSize = 10, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
_warpModeText = new TextBlock { Text = "Complex ▾", FontSize = 10, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
@@ -151,6 +154,17 @@ public sealed class AudioClipEditorView : UserControl
Grid.SetColumn(pPlus, 2); pStep.Children.Add(pPlus);
body.Children.Add(Section("PITCH (semitones)", pStep));
+ // Reverse: play the clip's region back-to-front. Non-destructive (the file is
+ // untouched) and free to toggle, so it doubles as an audition switch.
+ var revChip = Chip(_reverseToggleText);
+ revChip.PointerPressed += (_, e) => { e.Handled = true; ToggleReverse(); };
+ var revHint = new TextBlock
+ {
+ Text = "Plays the clip backwards · the waveform below mirrors with it, so it always reads left to right in playing order",
+ FontSize = 9, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap,
+ };
+ body.Children.Add(Section("DIRECTION", new StackPanel { Spacing = 4, Children = { revChip, revHint } }));
+
// Warp: on/off + mode (time-stretch to project tempo, Signalsmith Stretch).
var warpToggle = Chip(_warpToggleText);
warpToggle.PointerPressed += (_, e) => { e.Handled = true; ToggleWarp(); };
@@ -311,6 +325,10 @@ public sealed class AudioClipEditorView : UserControl
_gain.Value = ai.Gain;
ShowGain(ai.Gain);
_wave.SetGain(ai.Gain);
+ _reversed = ai.Reversed != 0;
+ _wave.SetReversed(_reversed); // draw the waveform the way the clip now plays
+ _reverseToggleText.Text = _reversed ? "Reverse: On" : "Reverse: Off";
+ _reverseToggleText.Foreground = _reversed ? AccentBright : TextSecondary;
_warpEnabled = ai.WarpEnabled != 0;
_warpMode = Math.Clamp(ai.WarpMode, 0, WarpModes.Length - 1);
_warpToggleText.Text = _warpEnabled ? "Warp: On" : "Warp: Off";
@@ -394,6 +412,13 @@ public sealed class AudioClipEditorView : UserControl
_wave.SetSnapToGrid(_snapToGrid);
}
+ private void ToggleReverse()
+ {
+ _engine.SetClipReverse(TrackId, ClipIndex, !_reversed);
+ Reload(); // picks the new state up (and re-reads the played peaks)
+ _onChanged();
+ }
+
private void ToggleWarp()
{
_warpEnabled = !_warpEnabled;
@@ -687,8 +712,20 @@ public sealed class AudioClipEditorView : UserControl
public double ScrollFrac => _scrollFrac;
public double MaxScrollFrac => Math.Max(0, 1.0 - 1.0 / _zoom);
public void SetScroll(double frac) { _scrollFrac = Math.Clamp(frac, 0, MaxScrollFrac); InvalidateVisual(); }
- private double FracToX(double f, double w) => (f - _scrollFrac) * _zoom * w;
- private double XToFrac(double x, double w) => x / Math.Max(1, _zoom * w) + _scrollFrac;
+
+ // Reverse: the clip is drawn MIRRORED, so the screen always reads left-to-right in
+ // playing order — a reversed clip's audible head (the region's end) sits on the left.
+ // Everything in the source/warp domain (peaks, brackets, markers, BPM chips, grid)
+ // goes through Frac<->X below, so mirroring here flips the whole view coherently and
+ // every hit-test/drag keeps working in content coordinates. The zoom/scroll window
+ // lives in VIEW space, hence the separate …View pair.
+ private bool _reversed;
+ public void SetReversed(bool on) { if (_reversed == on) return; _reversed = on; InvalidateVisual(); }
+ private double Mirror(double f) => _reversed ? 1.0 - f : f; // involution: content <-> view
+ private double FracToXView(double vf, double w) => (vf - _scrollFrac) * _zoom * w;
+ private double XToFracView(double x, double w) => x / Math.Max(1, _zoom * w) + _scrollFrac;
+ private double FracToX(double f, double w) => FracToXView(Mirror(f), w);
+ private double XToFrac(double x, double w) => Mirror(XToFracView(x, w));
private double SrcToX(double frame, double w) => _srcTotal > 0 ? FracToX(frame / _srcTotal, w) : 0;
private double XToSrc(double x, double w) => Math.Clamp(XToFrac(x, w), 0, 1) * _srcTotal;
@@ -702,8 +739,11 @@ public sealed class AudioClipEditorView : UserControl
for (int i = 0; i < beats.Length; i++) _env.Add(new EnvPt { beat = beats[i], val = values[i], curve = curves[i] });
InvalidateVisual();
}
- private double EnvBeatToX(double beat, double w) => FracToX(beat / _clipBeats, w);
- private double EnvXToBeat(double x, double w) => Math.Clamp(XToFrac(x, w), 0, 1) * _clipBeats;
+ // The clip envelope is authored in PLAYED time (the renderer evaluates it against the
+ // timeline position), so it always runs left-to-right — it must NOT mirror with the
+ // waveform. It stays on the view axis directly.
+ private double EnvBeatToX(double beat, double w) => FracToXView(beat / _clipBeats, w);
+ private double EnvXToBeat(double x, double w) => Math.Clamp(XToFracView(x, w), 0, 1) * _clipBeats;
private double EnvValToY(double v, double h) { double pad = 4; double t = (Math.Clamp(v, _envMin, _envMax) - _envMin) / (_envMax - _envMin); return pad + (1 - t) * (h - 2 * pad); }
private double EnvYToVal(double y, double h) { double pad = 4; double t = (h - pad - y) / Math.Max(1, h - 2 * pad); return _envMin + Math.Clamp(t, 0, 1) * (_envMax - _envMin); }
private static double EnvShape(double t, float curve) => curve == 0f ? t : Math.Pow(t, Math.Pow(2.0, -curve * 4.0));
@@ -873,7 +913,7 @@ public sealed class AudioClipEditorView : UserControl
var mods = e.KeyModifiers;
if ((mods & (KeyModifiers.Control | KeyModifiers.Meta)) != 0)
{
- double anchor = XToFrac(e.GetPosition(this).X, w); // keep the point under the cursor fixed
+ double anchor = XToFracView(e.GetPosition(this).X, w); // keep the point under the cursor fixed (view space)
double old = _zoom;
_zoom = Math.Clamp(_zoom * WheelInput.ZoomFactor(e.Delta.Y, 1.2), 1.0, MaxZoom);
if (Math.Abs(_zoom - old) < 1e-9) { e.Handled = true; return; }
@@ -1066,9 +1106,11 @@ public sealed class AudioClipEditorView : UserControl
double bw = Math.Max(1, _zoom * w / _count);
for (int i = 0; i < _count; i++)
{
+ // FracToX marks the bucket's leading edge — its RIGHT edge once mirrored.
double fx = FracToX((double)i / _count, w);
- if (fx + bw < 0) continue;
- if (fx > w) break;
+ if (_reversed) fx -= bw;
+ if (fx + bw < 0) { if (_reversed) break; continue; }
+ if (fx > w) { if (_reversed) continue; break; }
float mn = (float)Math.Clamp(_peaks[i * 2] * _gain, -1.0, 1.0);
float mx = (float)Math.Clamp(_peaks[i * 2 + 1] * _gain, -1.0, 1.0);
ctx.FillRectangle(_wave, new Rect(fx, mid - mx * amp, bw, Math.Max(1, (mx - mn) * amp)));
@@ -1096,7 +1138,8 @@ public sealed class AudioClipEditorView : UserControl
int barNo = b / BeatsPerBar + 1, beatNo = b % BeatsPerBar + 1;
var ft = new FormattedText($"{barNo}.{beatNo}", CultureInfo.InvariantCulture,
FlowDirection.LeftToRight, GridFace, 8.5, GridLabel);
- ctx.DrawText(ft, new Point(x + 2, h - ft.Height - 2));
+ // Keep the label inside its own beat: that's the other side when mirrored.
+ ctx.DrawText(ft, new Point(_reversed ? x - 2 - ft.Width : x + 2, h - ft.Height - 2));
}
}
}
@@ -1129,7 +1172,7 @@ public sealed class AudioClipEditorView : UserControl
double srcSpan = _mk[i + 1].src - _mk[i].src;
if (beatSpan <= 0 || srcSpan <= 0) continue;
double x0 = BeatToX(_mk[i].beat, w), x1 = BeatToX(_mk[i + 1].beat, w);
- if (x1 - x0 < 46) continue;
+ if (Math.Abs(x1 - x0) < 46) continue; // mirrored: x1 sits left of x0
double bpm = beatSpan * _srcSR * 60.0 / srcSpan;
bool hotChip = i == _bpmHoverSeg || i == _bpmScrubSeg;
var txtBrush = hotChip ? BracketHot : Marker;
@@ -1185,11 +1228,10 @@ public sealed class AudioClipEditorView : UserControl
if (_srcMode && _srcTotal > 0)
{
double xs = SrcToX(_srcOff, w), xe = SrcToX(_srcOff + _srcLen, w);
- double xsc = Math.Clamp(xs, 0, w), xec = Math.Clamp(xe, 0, w);
- if (xsc > 0.5) ctx.FillRectangle(OutsideDim, new Rect(0, 0, xsc, h));
- if (xec < w - 0.5) ctx.FillRectangle(OutsideDim, new Rect(xec, 0, w - xec, h));
- if (xs >= -1 && xs <= w + 1) DrawBracket(ctx, xs, h, true, _srcDrag == 0);
- if (xe >= -1 && xe <= w + 1) DrawBracket(ctx, xe, h, false, _srcDrag == 1);
+ DimOutside(ctx, xs, xe, w, h);
+ // The grips point INTO the region, which is the other way round when mirrored.
+ if (xs >= -1 && xs <= w + 1) DrawBracket(ctx, xs, h, !_reversed, _srcDrag == 0);
+ if (xe >= -1 && xe <= w + 1) DrawBracket(ctx, xe, h, _reversed, _srcDrag == 1);
}
// Warped-clip trim brackets (beat domain over the full warp): dim the trimmed
@@ -1197,29 +1239,41 @@ public sealed class AudioClipEditorView : UserControl
if (_trimMode && _trimTotal > 0)
{
double xs = BeatToX(_trimStart, w), xe = BeatToX(_trimEnd, w);
- double xsc = Math.Clamp(xs, 0, w), xec = Math.Clamp(xe, 0, w);
- if (xsc > 0.5) ctx.FillRectangle(OutsideDim, new Rect(0, 0, xsc, h));
- if (xec < w - 0.5) ctx.FillRectangle(OutsideDim, new Rect(xec, 0, w - xec, h));
- if (xs >= -1 && xs <= w + 1) DrawBracket(ctx, xs, h, true, _trimDrag == 0);
- if (xe >= -1 && xe <= w + 1) DrawBracket(ctx, xe, h, false, _trimDrag == 1);
+ DimOutside(ctx, xs, xe, w, h);
+ if (xs >= -1 && xs <= w + 1) DrawBracket(ctx, xs, h, !_reversed, _trimDrag == 0);
+ if (xe >= -1 && xe <= w + 1) DrawBracket(ctx, xe, h, _reversed, _trimDrag == 1);
}
if (_frac >= 0 && _frac <= 1)
{
// _frac is relative to the played window; map it into the current domain.
- double x = (_srcMode && _srcTotal > 0) ? SrcToX(_srcOff + _frac * _srcLen, w)
- : (_trimMode && _trimTotal > 0) ? BeatToX(_trimStart + _frac * (_trimEnd - _trimStart), w)
- : FracToX(_frac, w);
+ // _frac runs over the PLAYED window, so on a reversed clip it walks the region
+ // from its end back to its start (which the mirror then draws left-to-right).
+ double pf = _reversed ? 1 - _frac : _frac;
+ double x = (_srcMode && _srcTotal > 0) ? SrcToX(_srcOff + pf * _srcLen, w)
+ : (_trimMode && _trimTotal > 0) ? BeatToX(_trimStart + pf * (_trimEnd - _trimStart), w)
+ : FracToX(pf, w);
ctx.DrawLine(new Pen(PlayheadCursor, 1.5), new Point(x, 0), new Point(x, h));
}
}
- // A trim bracket: vertical line + inward-pointing grips at top and bottom.
- private void DrawBracket(DrawingContext ctx, double x, double h, bool start, bool hot)
+ // Shade everything outside the region's two edges. They arrive in content order, which
+ // is right-to-left on a mirrored (reversed) view, so normalise before filling.
+ private void DimOutside(DrawingContext ctx, double xa, double xb, double w, double h)
+ {
+ double lo = Math.Clamp(Math.Min(xa, xb), 0, w), hi = Math.Clamp(Math.Max(xa, xb), 0, w);
+ if (lo > 0.5) ctx.FillRectangle(OutsideDim, new Rect(0, 0, lo, h));
+ if (hi < w - 0.5) ctx.FillRectangle(OutsideDim, new Rect(hi, 0, w - hi, h));
+ }
+
+ // A trim bracket: vertical line + grips at top and bottom pointing into the region.
+ // Which screen side that is depends on the draw order, so the caller passes it —
+ // a mirrored (reversed) view has the region's start on the right.
+ private void DrawBracket(DrawingContext ctx, double x, double h, bool gripRight, bool hot)
{
var brush = hot ? BracketHot : Bracket;
ctx.DrawLine(new Pen(brush, hot ? 2.4 : 1.6), new Point(x, 0), new Point(x, h));
- double dir = start ? 1 : -1; // grip points into the region
+ double dir = gripRight ? 1 : -1;
var g = new StreamGeometry();
using (var gc = g.Open())
{
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index a3978bce..5ab2575a 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -69,6 +69,7 @@ public struct NotaAudioClipInfo
public double WarpBeats; // full warped material length in beats (0 when unwarped)
public double WarpPlayStart; // trimmed play window start (beats within the warp)
public double WarpPlayEnd; // trimmed play window end (0 = to WarpBeats)
+ public int Reversed; // 0/1: plays back-to-front (non-destructive)
}
/// <summary>Decoded-sample metadata. Matches native NotaSampleInfo (M7-6b).</summary>
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 136b40f9..bbaf727b 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -124,6 +124,9 @@ public interface IAudioEngine : IDisposable
void SetClipActive(int trackId, int clipIndex, bool active);
/// <summary>Sets an audio clip's varispeed transpose in semitones (runtime).</summary>
void SetClipPitch(int trackId, int clipIndex, float semitones);
+ /// <summary>Reverses an audio clip (non-destructive): the played region is read
+ /// back-to-front. Composes with gain/pitch/warp; trims and splits mirror.</summary>
+ void SetClipReverse(int trackId, int clipIndex, bool reversed);
/// <summary>Enables/disables warp + mode for an audio clip (rebuilds the stretch cache).</summary>
void SetClipWarp(int trackId, int clipIndex, bool enabled, int mode);
/// <summary>Sets a warped clip's target musical length in beats.</summary>
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 61323d1e..a8138b6a 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -99,6 +99,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_clip_set_pitch")]
internal static partial NotaResult ClipSetPitch(IntPtr engine, int trackId, int clipIndex, float semitones);
+ [LibraryImport(Lib, EntryPoint = "nota_clip_set_reverse")]
+ internal static partial NotaResult ClipSetReverse(IntPtr engine, int trackId, int clipIndex, int reversed);
+
[LibraryImport(Lib, EntryPoint = "nota_clip_set_warp")]
internal static partial NotaResult ClipSetWarp(IntPtr engine, int trackId, int clipIndex, int enabled, int mode);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index 2a4888d0..37c6c138 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -110,6 +110,12 @@ public sealed partial class NotaEngine
public void SetClipPitch(int trackId, int clipIndex, float semitones)
{ ThrowIfDisposed(); Check(NativeMethods.ClipSetPitch(_handle, trackId, clipIndex, semitones)); }
+ /// <summary>Reverses an audio clip: the played region is read back-to-front. Nothing is
+ /// re-rendered (the sample and any warp cache stay in file order), so this is as cheap
+ /// as a gain change.</summary>
+ public void SetClipReverse(int trackId, int clipIndex, bool reversed)
+ { ThrowIfDisposed(); Check(NativeMethods.ClipSetReverse(_handle, trackId, clipIndex, reversed ? 1 : 0)); }
+
/// <summary>Enables/disables warp and picks the mode (rebuilds the stretch cache).</summary>
public void SetClipWarp(int trackId, int clipIndex, bool enabled, int mode)
{ ThrowIfDisposed(); Check(NativeMethods.ClipSetWarp(_handle, trackId, clipIndex, enabled ? 1 : 0, mode)); }
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index f714e378..9cafa720 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -77,6 +77,9 @@ public static class ProjectMigrations
// v17 -> v18: CV modulation (TrackDto.Modulators/CvLinks, Phase 3). Absent in v17
// documents; the defaults (empty lists = no modulation) match old behaviour — no-op.
new Migration(17, _ => { }),
+ // v18 -> v19: audio clips gain Reversed (non-destructive reverse). Absent in v18
+ // documents; the default (false = plays forwards) matches old behaviour — no-op.
+ new Migration(18, _ => { }),
};
/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 892f241a..d7d7f43e 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -224,6 +224,7 @@ public sealed class AudioClipDto
public AutomationPointDto[]? PanEnvelope { get; set; } // clip pan envelope, clip-local beats (v9)
public double WarpPlayStart { get; set; } // warped clip trim window start (beats, v11)
public double WarpPlayEnd { get; set; } // warped clip trim window end (0 = full, v11)
+ public bool Reversed { get; set; } // plays back-to-front (v19); default false
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 444a1e37..078b8f59 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -30,7 +30,7 @@ public sealed class ProjectService
/// per-segment curvature (automationPoint.curve). v5 adds audio-clip pitch + warp
/// (pitchSemitones / warpEnabled / warpMode / warpBeats). v6 adds warp markers.</summary>
/// v18 (Phase 3) adds CV modulation: per-track LFO modulators + CV links to device params.
- public const int CurrentFormatVersion = 18;
+ public const int CurrentFormatVersion = 19;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -211,6 +211,7 @@ public sealed class ProjectService
WarpBeats = ac.WarpBeats,
WarpPlayStart = ac.WarpPlayStart,
WarpPlayEnd = ac.WarpPlayEnd,
+ Reversed = ac.Reversed != 0,
};
if (ac.WarpEnabled != 0)
{
@@ -623,6 +624,7 @@ public sealed class ProjectService
if (ac.Name is { Length: > 0 } acn) engine.SetClipName(id, ci, acn);
if (!ac.Active) engine.SetClipActive(id, ci, false); // clip deactivate (v17)
if (ac.PitchSemitones != 0) engine.SetClipPitch(id, ci, ac.PitchSemitones);
+ if (ac.Reversed) engine.SetClipReverse(id, ci, true); // reverse (v19)
if (ac.WarpEnabled != 0)
{
engine.SetClipWarp(id, ci, true, ac.WarpMode);
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 17295af3..965f4ba0 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -93,6 +93,7 @@ typedef struct NotaAudioClipInfo {
double warp_beats; /* full warped material length in beats (0 when unwarped) */
double warp_play_start; /* trimmed play window start (beats within the warp) */
double warp_play_end; /* trimmed play window end (0 = to warp_beats) */
+ int32_t reversed; /* 0/1: play the region back-to-front (non-destructive) */
} NotaAudioClipInfo;
/* Decoded-sample metadata (M7-6b). */
@@ -611,6 +612,11 @@ NOTA_API NotaResult nota_clip_set_warp_trim(NotaEngine* engine, int32_t track_id
/* Audio-clip runtime edits: gain (linear) and varispeed transpose (semitones). */
NOTA_API NotaResult nota_clip_set_gain(NotaEngine* engine, int32_t track_id, int32_t clip_index, float gain);
NOTA_API NotaResult nota_clip_set_pitch(NotaEngine* engine, int32_t track_id, int32_t clip_index, float semitones);
+/* Reverse an audio clip (non-destructive): the played region is read back-to-front.
+ * The sample and any warp cache stay in file order — only the read direction flips — so
+ * this is as cheap as a gain change and composes with gain/pitch/warp/clip envelopes.
+ * Trims, splits and range carves mirror, so the audible head/tail follow the edit. */
+NOTA_API NotaResult nota_clip_set_reverse(NotaEngine* engine, int32_t track_id, int32_t clip_index, int32_t reversed);
/* Clip deactivate (key 0): active=0 keeps the clip on the timeline but plays nothing
* (audio or MIDI). Works on audio and instrument tracks. */
NOTA_API NotaResult nota_clip_set_active(NotaEngine* engine, int32_t track_id, int32_t clip_index, int32_t active);
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 1a21ceea..516fbe95 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -463,6 +463,7 @@ public:
bool setClipGain(int32_t trackId, int32_t clipIndex, float gain); // audio clip runtime gain
bool setClipActive(int32_t trackId, int32_t clipIndex, bool active); // clip deactivate (key 0): audio+MIDI
bool setClipPitch(int32_t trackId, int32_t clipIndex, float semitones); // audio clip varispeed transpose
+ bool setClipReverse(int32_t trackId, int32_t clipIndex, bool reversed); // audio clip plays back-to-front
bool 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)
double beatWarpClip(int32_t trackId, int32_t clipIndex); // Beats mode: detect transients, pin grid-snapped markers at each hit; returns detected BPM (0 = failed)
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index 8e31762c..58ace059 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -593,7 +593,9 @@ void Engine::renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst
const float* csamp = wc.samples.data();
const float g = clip.gain;
for (int32_t j = 0; j < segLen; ++j) {
- const int64_t ci = cacheBase + j;
+ // Reverse reads the same cache back-to-front: the window is already the
+ // played length, so mirroring the index is exact (no resample).
+ const int64_t ci = clip.reversed ? wc.frames - 1 - (cacheBase + j) : cacheBase + j;
if (ci < 0 || ci >= wc.frames) continue;
float l = csamp[ci * 2], r = csamp[ci * 2 + 1];
if (hasEnv) applyEnv(ovStart + j, l, r);
@@ -617,7 +619,12 @@ void Engine::renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst
for (int32_t i = 0; i < frames; ++i) {
const double p = blockStart + i;
if (p < startSamples || p >= startSamples + clipDeviceLen) continue;
- const double srcPos = clip.sourceOffsetFrames + (p - startSamples) * ratio;
+ // Reverse walks the source region from its last frame back to its first;
+ // the interpolation is unchanged (srcPos is still a real source position).
+ double srcPos = clip.reversed
+ ? clip.sourceOffsetFrames + (len - 1) - (p - startSamples) * ratio
+ : clip.sourceOffsetFrames + (p - startSamples) * ratio;
+ if (srcPos < clip.sourceOffsetFrames) srcPos = clip.sourceOffsetFrames;
const int64_t i0 = static_cast<int64_t>(srcPos);
const double frac = srcPos - i0;
float l0, r0, l1, r1;
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index 4005dd74..b7f13f14 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -71,6 +71,7 @@ bool Engine::audioClipInfo(int32_t trackId, int32_t clipIndex, NotaAudioClipInfo
out->warp_beats = c.warpBeats;
out->warp_play_start = c.warpPlayStart;
out->warp_play_end = c.warpPlayEnd;
+ out->reversed = c.reversed ? 1 : 0;
return true;
}
@@ -341,6 +342,19 @@ bool Engine::setClipPitch(int32_t trackId, int32_t clipIndex, float semitones) {
return true;
}
+// Reverse an audio clip (non-destructive): the played region is read back-to-front.
+// Nothing is re-rendered — the source and the warp cache stay in file order and the
+// renderer mirrors its read index — so this is as cheap as a gain change.
+bool Engine::setClipReverse(int32_t trackId, int32_t clipIndex, bool reversed) {
+ auto old = findTrackAuthoring(trackId);
+ if (!old || old->type() != TrackType::Audio) return false;
+ if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(old->clips.size())) return false;
+ auto nt = cloneTrack(*old);
+ nt->clips[clipIndex].reversed = reversed;
+ republishWithTrack(trackId, nt);
+ return true;
+}
+
bool Engine::setClipWarp(int32_t trackId, int32_t clipIndex, bool enabled, int32_t mode) {
auto old = findTrackAuthoring(trackId);
if (!old || old->type() != TrackType::Audio) return false;
@@ -701,6 +715,15 @@ static int32_t warpPeaksRange(const AudioClip& clip, float* out, int32_t maxPoin
return buckets;
}
+// Flip a min/max peak array end-to-end (each bucket's own min/max is unchanged) so a
+// reversed clip draws the waveform it actually plays.
+static void reversePeaks(float* peaks, int32_t count) {
+ for (int32_t a = 0, b = count - 1; a < b; ++a, --b) {
+ std::swap(peaks[a * 2], peaks[b * 2]);
+ std::swap(peaks[a * 2 + 1], peaks[b * 2 + 1]);
+ }
+}
+
int32_t Engine::getClipPeaks(int32_t trackId, int32_t clipIndex,
float* outMinMax, int32_t maxPoints) const {
if (!outMinMax || maxPoints <= 0) return 0;
@@ -718,8 +741,11 @@ int32_t Engine::getClipPeaks(int32_t trackId, int32_t clipIndex,
const auto& m = clip.warpMarkers;
const bool warped = clip.warpEnabled && m.size() >= 2 && clip.warpBeats > 0.0;
- if (warped) // peaks over the PLAYED window (what the arrangement shows/plays)
- return warpPeaksRange(clip, outMinMax, maxPoints, clip.warpPlayStart, clip.warpPlayEndEff());
+ if (warped) { // peaks over the PLAYED window (what the arrangement shows/plays)
+ const int32_t n = warpPeaksRange(clip, outMinMax, maxPoints, clip.warpPlayStart, clip.warpPlayEndEff());
+ if (clip.reversed) reversePeaks(outMinMax, n);
+ return n;
+ }
const int64_t base = static_cast<int64_t>(clip.sourceOffsetFrames);
const int64_t total = clip.effectiveLength();
@@ -737,12 +763,15 @@ int32_t Engine::getClipPeaks(int32_t trackId, int32_t clipIndex,
}
outMinMax[b * 2] = mn; outMinMax[b * 2 + 1] = mx;
}
+ if (clip.reversed) reversePeaks(outMinMax, buckets);
return buckets;
}
// Peaks over the WHOLE sample (frames 0..sample->frames), regardless of the clip's
// trimmed region — the clip editor draws the full file so the Start/End brackets can
-// reveal audio that was trimmed off. Unwarped only (warped uses getClipPeaks).
+// reveal audio that was trimmed off. Unwarped only (warped uses getClipPeaks). Always in
+// FILE order: the editor draws this view together with source-frame brackets, so it
+// mirrors the two as one when the clip is reversed rather than flipping peaks here.
int32_t Engine::getClipSourcePeaks(int32_t trackId, int32_t clipIndex,
float* outMinMax, int32_t maxPoints) const {
if (!outMinMax || maxPoints <= 0) return 0;
@@ -772,6 +801,8 @@ int32_t Engine::getClipSourcePeaks(int32_t trackId, int32_t clipIndex,
// Peaks over the FULL warped material [0..warpBeats], ignoring the trim window — the
// clip editor draws the whole warp so the Start/End brackets can reveal trimmed beats.
+// In marker (file) order — the editor mirrors this view and its markers together when the
+// clip is reversed, so flipping the peaks alone here would desync them.
int32_t Engine::getClipWarpFullPeaks(int32_t trackId, int32_t clipIndex,
float* outMinMax, int32_t maxPoints) const {
auto t = findTrackAuthoring(trackId);
@@ -854,6 +885,15 @@ double audioDisplayLenBeats(const AudioClip& c, double spb, double devSR) {
if (c.warpEnabled && c.warpMarkers.size() >= 2 && c.warpBeats > 0.0) return c.warpPlayLen();
return audioLenBeats(c, spb, devSR);
}
+// Source frame just past a REVERSED clip's audible head (its region end) after the left
+// edge moved by `deltaBeats`. Trims measure a reversed clip backwards from here.
+double audioReverseHead(const AudioClip& c, double deltaBeats, double spb, double devSR) {
+ double head = c.sourceOffsetFrames + static_cast<double>(c.effectiveLength())
+ - audioBeatsToSrcFrames(c, deltaBeats, spb, devSR);
+ if (c.sample) head = std::min(head, static_cast<double>(c.sample->frames));
+ return std::max(0.0, head);
+}
+
// Push `start` right until [start, start+len) overlaps no existing clip on the track.
double placeMidiNonOverlap(const Track& t, double start, double len) {
bool moved = true;
@@ -891,23 +931,40 @@ MidiClip midiCarveRight(const MidiClip& src, double startLocal) { // keep [sta
for (const auto& n : src.notes) if (n.startBeat >= startLocal) { Note m = n; m.startBeat -= startLocal; r.notes.push_back(m); }
return r;
}
+// Both carves work in PLAYED time, so a reversed clip mirrors: its audible head is the
+// region's end, so keeping the first beats keeps the region's tail and vice versa.
AudioClip audioCarveLeft(const AudioClip& src, double endLocal, double spb, double devSR) {
AudioClip left = src;
if (src.warpEnabled && src.warpMarkers.size() >= 2 && src.warpBeats > 0.0) {
- left.warpPlayEnd = src.warpPlayStart + endLocal; buildWarpCache(left, spb, devSR);
+ if (src.reversed) {
+ left.warpPlayStart = std::max(0.0, src.warpPlayEndEff() - endLocal);
+ left.warpPlayEnd = src.warpPlayEndEff();
+ } else {
+ left.warpPlayEnd = src.warpPlayStart + endLocal;
+ }
+ buildWarpCache(left, spb, devSR);
} else {
- left.lengthFrames = static_cast<int64_t>(audioBeatsToSrcFrames(src, endLocal, spb, devSR));
+ const int64_t keep = static_cast<int64_t>(audioBeatsToSrcFrames(src, endLocal, spb, devSR));
+ if (src.reversed)
+ left.sourceOffsetFrames = src.sourceOffsetFrames + static_cast<double>(src.effectiveLength() - keep);
+ left.lengthFrames = keep;
}
return left;
}
AudioClip audioCarveRight(const AudioClip& src, double startLocal, double spb, double devSR) {
AudioClip right = src; right.startBeat = src.startBeat + startLocal;
if (src.warpEnabled && src.warpMarkers.size() >= 2 && src.warpBeats > 0.0) {
- right.warpPlayStart = src.warpPlayStart + startLocal; right.warpPlayEnd = src.warpPlayEndEff();
+ if (src.reversed) {
+ right.warpPlayStart = src.warpPlayStart;
+ right.warpPlayEnd = std::max(src.warpPlayStart, src.warpPlayEndEff() - startLocal);
+ } else {
+ right.warpPlayStart = src.warpPlayStart + startLocal; right.warpPlayEnd = src.warpPlayEndEff();
+ }
buildWarpCache(right, spb, devSR);
} else {
const int64_t cut = static_cast<int64_t>(audioBeatsToSrcFrames(src, startLocal, spb, devSR));
- right.sourceOffsetFrames = src.sourceOffsetFrames + static_cast<double>(cut);
+ if (!src.reversed) // reversed drops the region's tail instead, so the offset stays
+ right.sourceOffsetFrames = src.sourceOffsetFrames + static_cast<double>(cut);
right.lengthFrames = src.effectiveLength() - cut;
}
return right;
@@ -1367,11 +1424,22 @@ bool Engine::trimClip(int32_t trackId, int32_t clipIndex, double newStartBeat, d
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
const double delta = newStartBeat - c.startBeat;
- double newOffset = c.sourceOffsetFrames + audioBeatsToSrcFrames(c, delta, spb, devSR);
- if (newOffset < 0) newOffset = 0;
- c.startBeat = newStartBeat;
- c.sourceOffsetFrames = newOffset;
- c.lengthFrames = static_cast<int64_t>(audioBeatsToSrcFrames(c, newLengthBeats, spb, devSR));
+ const double want = audioBeatsToSrcFrames(c, newLengthBeats, spb, devSR);
+ if (c.reversed) {
+ // Mirrored: a reversed clip's audible head is the region's END, so the left
+ // edge moves that end in and the length is taken backwards from it.
+ const double headEnd = audioReverseHead(c, delta, spb, devSR);
+ const double off = std::max(0.0, headEnd - want);
+ c.startBeat = newStartBeat;
+ c.sourceOffsetFrames = off;
+ c.lengthFrames = static_cast<int64_t>(std::max(0.0, headEnd - off));
+ } else {
+ double newOffset = c.sourceOffsetFrames + audioBeatsToSrcFrames(c, delta, spb, devSR);
+ if (newOffset < 0) newOffset = 0;
+ c.startBeat = newStartBeat;
+ c.sourceOffsetFrames = newOffset;
+ c.lengthFrames = static_cast<int64_t>(want);
+ }
}
republishWithTrack(trackId, nt);
return true;
@@ -1395,8 +1463,14 @@ bool Engine::resizeAudioClip(int32_t trackId, int32_t clipIndex, double newStart
// the left edge shifts playStart (and startBeat); the right edge moves playEnd.
constexpr double kMinBeat = 0.05;
const double d = newStartBeat - c.startBeat;
- double ps = std::clamp(c.warpPlayStart + d, 0.0, std::max(0.0, c.warpBeats - kMinBeat));
- double pe = std::clamp(ps + newLengthBeats, ps + kMinBeat, c.warpBeats);
+ double ps, pe;
+ if (c.reversed) { // the window's END is the audible head, so the edges swap roles
+ pe = std::clamp(c.warpPlayEndEff() - d, kMinBeat, c.warpBeats);
+ ps = std::clamp(pe - newLengthBeats, 0.0, pe - kMinBeat);
+ } else {
+ ps = std::clamp(c.warpPlayStart + d, 0.0, std::max(0.0, c.warpBeats - kMinBeat));
+ pe = std::clamp(ps + newLengthBeats, ps + kMinBeat, c.warpBeats);
+ }
c.startBeat = newStartBeat;
c.warpPlayStart = ps;
c.warpPlayEnd = pe;
@@ -1409,12 +1483,24 @@ bool Engine::resizeAudioClip(int32_t trackId, int32_t clipIndex, double newStart
// can provide, auto-enable warp and stretch the current content to fit (this is
// what lets a short one-shot be dragged out to a whole bar).
const double delta = newStartBeat - c.startBeat;
- double newOffset = c.sourceOffsetFrames + audioBeatsToSrcFrames(c, delta, spb, devSR);
+ const int64_t wantFrames = static_cast<int64_t>(audioBeatsToSrcFrames(c, newLengthBeats, spb, devSR));
+ // A reversed clip reads the region backwards, so the source a drag can reveal sits
+ // BEFORE its audible head (the region's end) rather than after the offset: the head is
+ // the anchor and the region grows leftwards from it.
+ double newOffset;
+ int64_t srcAvail;
+ if (c.reversed) {
+ const double head = audioReverseHead(c, delta, spb, devSR);
+ srcAvail = static_cast<int64_t>(head);
+ newOffset = head - static_cast<double>(std::min<int64_t>(wantFrames, srcAvail));
+ } else {
+ newOffset = c.sourceOffsetFrames + audioBeatsToSrcFrames(c, delta, spb, devSR);
+ if (newOffset < 0) newOffset = 0;
+ srcAvail = c.sample ? (c.sample->frames - static_cast<int64_t>(newOffset)) : 0;
+ }
if (newOffset < 0) newOffset = 0;
c.startBeat = newStartBeat;
c.sourceOffsetFrames = newOffset;
- const int64_t wantFrames = static_cast<int64_t>(audioBeatsToSrcFrames(c, newLengthBeats, spb, devSR));
- const int64_t srcAvail = c.sample ? (c.sample->frames - static_cast<int64_t>(newOffset)) : 0;
if (!c.sample || wantFrames <= srcAvail) {
c.lengthFrames = wantFrames; // plain trim (reveal/hide source)
} else {
@@ -1482,39 +1568,15 @@ int32_t Engine::splitClip(int32_t trackId, int32_t clipIndex, double atBeat) {
if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(nt->clips.size())) return -1;
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
- AudioClip src = nt->clips[clipIndex];
+ const AudioClip src = nt->clips[clipIndex];
const double local = atBeat - src.startBeat;
- const bool warped = src.warpEnabled && src.warpMarkers.size() >= 2 && src.warpBeats > 0.0;
- if (warped) {
- // Warped clips play the beat window [warpPlayStart, warpPlayEndEff()] — split
- // in that domain (lengthFrames/sourceOffsetFrames are ignored when warped, so
- // editing them left both halves showing/playing the whole material).
- const double playLen = src.warpPlayLen();
- if (local <= 0.0 || local >= playLen) return -1;
- const double splitPlay = src.warpPlayStart + local; // warp-material beat of the cut
- AudioClip left = src, right = src;
- left.warpPlayEnd = splitPlay; // concrete end (> start)
- right.startBeat = atBeat;
- right.warpPlayStart = splitPlay;
- right.warpPlayEnd = src.warpPlayEndEff();
- // Each half needs its own streaming stretcher (seek state is per-clip).
- configureClipWarp(left, spb, devSR);
- configureClipWarp(right, spb, devSR);
- nt->clips[clipIndex] = left;
- nt->clips.insert(nt->clips.begin() + clipIndex + 1, right);
- } else {
- const double lenBeats = audioLenBeats(src, spb, devSR);
- if (local <= 0 || local >= lenBeats) return -1;
- const int64_t splitSrc = static_cast<int64_t>(audioBeatsToSrcFrames(src, local, spb, devSR));
- const int64_t total = src.effectiveLength();
- AudioClip left = src, right = src;
- left.lengthFrames = splitSrc;
- right.startBeat = atBeat;
- right.sourceOffsetFrames = src.sourceOffsetFrames + static_cast<double>(splitSrc);
- right.lengthFrames = total - splitSrc;
- nt->clips[clipIndex] = left;
- nt->clips.insert(nt->clips.begin() + clipIndex + 1, right);
- }
+ if (local <= 0.0 || local >= audioDisplayLenBeats(src, spb, devSR)) return -1;
+ // The same carves the range ops use: they cut in played time, so warped halves
+ // split over the beat window (not lengthFrames, which warp ignores) and a reversed
+ // clip's halves keep the audio each one sounded. Each warped half also gets its own
+ // stretch cache, since the stretcher's seek state is per-clip.
+ nt->clips[clipIndex] = audioCarveLeft(src, local, spb, devSR);
+ nt->clips.insert(nt->clips.begin() + clipIndex + 1, audioCarveRight(src, local, spb, devSR));
}
republishWithTrack(trackId, nt);
return clipIndex + 1;
diff --git a/src/native/nota.engine/src/Track.h b/src/native/nota.engine/src/Track.h
index 83654aa2..b42756dc 100644
--- a/src/native/nota.engine/src/Track.h
+++ b/src/native/nota.engine/src/Track.h
@@ -39,6 +39,11 @@ struct AudioClip {
bool active = true; // clip deactivate (key 0): false = stays but silent
float gain = 1.0f;
float pitchSemitones = 0.0f; // varispeed transpose (no warp): also scales duration
+ // Reverse (non-destructive): the played region is read back-to-front. The source and
+ // the warp cache stay in file order — only the read direction flips — so toggling it
+ // is free (no re-decode, no cache rebuild) and it composes with gain/pitch/warp.
+ // Trims, splits and range carves mirror so the audible head/tail follow the edit.
+ bool reversed = false;
// Warp (time-stretch to tempo). When enabled, `warpCache` (below) holds the played
// window pre-stretched at the current tempo/device rate and the audio thread copies
// it straight (pitch baked in). Rebuilt on tempo/pitch/mode/marker/window/SR change.
diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cpp
index b0cde791..8c3b4593 100644
--- a/src/native/nota.engine/src/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/nota_engine_track.cpp
@@ -231,6 +231,10 @@ NotaResult nota_clip_set_pitch(NotaEngine* e, int32_t track_id, int32_t clip_ind
if (!e) return NOTA_ERR_INVALID_ARG;
return ENG(e)->setClipPitch(track_id, clip_index, semitones) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
}
+NotaResult nota_clip_set_reverse(NotaEngine* e, int32_t track_id, int32_t clip_index, int32_t reversed) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->setClipReverse(track_id, clip_index, reversed != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
NotaResult nota_clip_set_warp(NotaEngine* e, int32_t track_id, int32_t clip_index, int32_t enabled, int32_t mode) {
if (!e) return NOTA_ERR_INVALID_ARG;
return ENG(e)->setClipWarp(track_id, clip_index, enabled != 0, mode) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index ea1065fc..70bf8a1e 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -758,6 +758,149 @@ Console.WriteLine("-- warped clip trimming --");
"warp trim clamped to [0, warpBeats]");
}
+// ============== clip reverse (non-destructive playback direction) ===========
+Console.WriteLine("-- clip reverse --");
+{
+ // A silence|tone file makes direction audible: forwards is quiet-then-loud, reversed
+ // is loud-then-quiet. The clip is 2 beats at 120 BPM, so each half is one beat.
+ string rvw = Path.Combine(Path.GetTempPath(), "nota_smoke_reverse.wav");
+ Nota.SmokeTest.WavWriter.WriteSilenceThenTone(rvw, seconds: 1.0, freq: 440.0, sampleRate: 44100);
+ using var rv = new NotaEngine();
+ rv.SetBpm(120); rv.SetTimeSignature(4, 4);
+ int rt = rv.AddAudioTrack();
+ int rc = rv.AddAudioClip(rt, rvw, 0.0);
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rv0) && rv0.Reversed == 0, "clips start forwards");
+ long srcTotal = rv.TryGetSampleInfo(rv0.SampleId, out var rvs) ? rvs.Frames : 0;
+ Check(srcTotal > 0, "reverse: source frames known");
+
+ // Halves of the clip's own device span, so the check is independent of device rate.
+ Check(rv.TryGetClipInfo(rt, rc, out var rvc0) && rvc0.LengthBeats > 0, "reverse: clip length known");
+ double rvSpb = (rv.SampleRate > 0 ? rv.SampleRate : 48000.0) * 60.0 / 120.0; // 120 BPM
+ int clipFrames = (int)Math.Round(rvc0.LengthBeats * rvSpb);
+ var rbuf = new float[(clipFrames + 64) * 2];
+ (float head, float tail) Halves()
+ {
+ Array.Clear(rbuf);
+ rv.Seek(0); rv.Play(); rv.RenderOffline(rbuf, clipFrames); rv.StopTransport();
+ return (RmsRange(rbuf, clipFrames / 8, clipFrames * 3 / 8),
+ RmsRange(rbuf, clipFrames * 5 / 8, clipFrames * 7 / 8));
+ }
+ static float RmsRange(float[] b, int from, int to)
+ { double sum = 0; for (int i = from * 2; i < to * 2; i++) sum += b[i] * (double)b[i]; return (float)Math.Sqrt(sum / Math.Max(1, (to - from) * 2)); }
+
+ var (fwdHead, fwdTail) = Halves();
+ Check(fwdTail > fwdHead + 0.05f, $"forwards plays silence then tone ({fwdHead:F3} -> {fwdTail:F3})");
+
+ rv.SetClipReverse(rt, rc, true);
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rv1) && rv1.Reversed != 0, "reverse flag set");
+ var (revHead, revTail) = Halves();
+ Check(revHead > revTail + 0.05f, $"reversed plays tone then silence ({revHead:F3} -> {revTail:F3})");
+ // Reverse only flips the read direction: the region and its musical length are untouched.
+ Check(Math.Abs(rv1.SourceOffsetFrames - rv0.SourceOffsetFrames) < 1e-9
+ && rv.TryGetClipInfo(rt, rc, out var rvc1) && Math.Abs(rvc1.LengthBeats - rvc0.LengthBeats) < 1e-9,
+ "reverse leaves geometry (offset + length) alone");
+ // Energy is conserved (same audio, other way round) — a resample bug would shift it.
+ Check(Math.Abs(Rms(rbuf, clipFrames) - Math.Sqrt((fwdHead * fwdHead + fwdTail * fwdTail) / 2.0)) < 0.06,
+ "reverse preserves overall level");
+
+ // The lane's peaks follow the ear: the loud half moves to the front.
+ var rpk = new float[512 * 2];
+ int rpn = rv.GetClipPeaks(rt, rc, rpk, 512);
+ float pkHead = 0, pkTail = 0;
+ for (int b = 0; b < rpn; b++)
+ {
+ float a = Math.Max(Math.Abs(rpk[b * 2]), Math.Abs(rpk[b * 2 + 1]));
+ if (b < rpn / 2) pkHead = Math.Max(pkHead, a); else pkTail = Math.Max(pkTail, a);
+ }
+ Check(rpn > 0 && pkHead > 0.3f && pkTail < 0.05f, $"reversed peaks are flipped too ({pkHead:F2}|{pkTail:F2})");
+ // The clip-editor view stays in FILE order (its brackets are source coordinates).
+ var rsp = new float[512 * 2];
+ int rsn = rv.GetClipSourcePeaks(rt, rc, rsp, 512);
+ float spHead = 0, spTail = 0;
+ for (int b = 0; b < rsn; b++)
+ {
+ float a = Math.Max(Math.Abs(rsp[b * 2]), Math.Abs(rsp[b * 2 + 1]));
+ if (b < rsn / 2) spHead = Math.Max(spHead, a); else spTail = Math.Max(spTail, a);
+ }
+ Check(rsn > 0 && spTail > 0.3f && spHead < 0.05f, "source peaks stay in file order when reversed");
+
+ // Undo/redo: reverse is one structural edit like any other clip property.
+ rv.Undo();
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rv2) && rv2.Reversed == 0, "undo un-reverses");
+ rv.Redo();
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rv3) && rv3.Reversed != 0, "redo re-reverses");
+
+ // Split mirrors: the reversed clip sounds tone|silence, so the LEFT half must keep the
+ // region's tail (the tone, at source offset ~half) and the right half its head.
+ double mid = rvc0.LengthBeats / 2;
+ Check(rv.SplitClip(rt, rc, mid) == rc + 1, "reverse: split returns the new clip index");
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rl) && rl.Reversed != 0
+ && Math.Abs(rl.SourceOffsetFrames - srcTotal / 2.0) < srcTotal * 0.02,
+ $"reversed split: left half keeps the region tail (offset {rl.SourceOffsetFrames:F0} of {srcTotal})");
+ Check(rv.TryGetAudioClipInfo(rt, rc + 1, out var rr) && rr.Reversed != 0 && rr.SourceOffsetFrames < srcTotal * 0.02,
+ $"reversed split: right half keeps the region head (offset {rr.SourceOffsetFrames:F0})");
+ rv.Undo(); // back to one clip for the trim check
+
+ // Trim mirrors: shortening the right edge cuts the TAIL of what you hear, so the
+ // audible head (the region's end) stays put and the offset moves up instead.
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rt0), "reverse: pre-trim info");
+ double head0 = rt0.SourceOffsetFrames + (rt0.LengthFrames > 0 ? rt0.LengthFrames : srcTotal);
+ rv.TrimClip(rt, rc, 0.0, rvc0.LengthBeats / 2);
+ Check(rv.TryGetAudioClipInfo(rt, rc, out var rt1)
+ && Math.Abs(rt1.SourceOffsetFrames + rt1.LengthFrames - head0) < srcTotal * 0.02
+ && rt1.SourceOffsetFrames > srcTotal * 0.4,
+ $"reversed trim keeps the audible head (region now {rt1.SourceOffsetFrames:F0}+{rt1.LengthFrames})");
+ // The trimmed clip is half as long, so measure over ITS span: the region it kept is
+ // the tone, so the whole thing sounds — nothing is silent any more.
+ Array.Clear(rbuf);
+ rv.Seek(0); rv.Play(); rv.RenderOffline(rbuf, clipFrames); rv.StopTransport();
+ int halfSpan = clipFrames / 2;
+ float trA = RmsRange(rbuf, halfSpan / 8, halfSpan * 3 / 8), trB = RmsRange(rbuf, halfSpan * 5 / 8, halfSpan * 7 / 8);
+ Check(trA > 0.05f && trB > 0.05f, $"reversed half-clip is all tone ({trA:F3}|{trB:F3})");
+}
+
+// ============== reverse on a WARPED clip (mirrors the stretch cache) =========
+Console.WriteLine("-- clip reverse (warped) --");
+{
+ string rww = Path.Combine(Path.GetTempPath(), "nota_smoke_reverse_warp.wav");
+ Nota.SmokeTest.WavWriter.WriteSilenceThenTone(rww, seconds: 1.0, freq: 440.0, sampleRate: 44100);
+ using var rw = new NotaEngine();
+ rw.SetBpm(120); rw.SetTimeSignature(4, 4);
+ int wt2 = rw.AddAudioTrack();
+ int wc2 = rw.AddAudioClip(wt2, rww, 0.0);
+ rw.SetClipWarp(wt2, wc2, true, 3); // Complex; flat source -> neutral seed
+ Check(rw.TryGetAudioClipInfo(wt2, wc2, out var wi0) && wi0.WarpEnabled != 0 && wi0.WarpBeats > 0,
+ "reverse-warp: warp enabled");
+ Check(rw.TryGetClipInfo(wt2, wc2, out var wci) && wci.LengthBeats > 0, "reverse-warp: length known");
+ double rwSpb = (rw.SampleRate > 0 ? rw.SampleRate : 48000.0) * 60.0 / 120.0; // 120 BPM
+ int wFrames = (int)Math.Round(wci.LengthBeats * rwSpb);
+ var wbuf = new float[(wFrames + 64) * 2];
+ (float head, float tail) WHalves()
+ {
+ Array.Clear(wbuf);
+ rw.Seek(0); rw.Play(); rw.RenderOffline(wbuf, wFrames); rw.StopTransport();
+ double a = 0, b = 0;
+ for (int i = wFrames / 8; i < wFrames * 3 / 8; i++) a += wbuf[i * 2] * (double)wbuf[i * 2];
+ for (int i = wFrames * 5 / 8; i < wFrames * 7 / 8; i++) b += wbuf[i * 2] * (double)wbuf[i * 2];
+ int n = Math.Max(1, wFrames / 4);
+ return ((float)Math.Sqrt(a / n), (float)Math.Sqrt(b / n));
+ }
+ var (wf1, wf2) = WHalves();
+ Check(wf2 > wf1 + 0.02f, $"warped forwards plays silence then tone ({wf1:F3} -> {wf2:F3})");
+ rw.SetClipReverse(wt2, wc2, true);
+ // Reverse must NOT invalidate the stretch cache: the warp geometry is untouched.
+ Check(rw.TryGetAudioClipInfo(wt2, wc2, out var wi1) && wi1.Reversed != 0
+ && Math.Abs(wi1.WarpBeats - wi0.WarpBeats) < 1e-9, "reverse-warp: warp geometry untouched");
+ var (wr1, wr2) = WHalves();
+ Check(wr1 > wr2 + 0.02f, $"warped reversed plays tone then silence ({wr1:F3} -> {wr2:F3})");
+
+ // Consolidate bakes the reversal into a fresh, forward sample.
+ Check(rw.ConsolidateRange(new[] { wt2 }, 0.0, wci.LengthBeats), "reverse-warp: consolidate range");
+ Check(rw.TryGetAudioClipInfo(wt2, 0, out var wi2) && wi2.Reversed == 0, "consolidate bakes reverse (clip is forwards)");
+ var (wc1, wc2b) = WHalves();
+ Check(wc1 > wc2b + 0.02f, $"consolidated clip still sounds reversed ({wc1:F3} -> {wc2b:F3})");
+}
+
// ============== warp preserves pitch across a src≠device sample rate ==========
Console.WriteLine("-- warp pitch vs sample rate --");
{
@@ -4321,6 +4464,7 @@ Console.WriteLine("-- M7-6b: audio round-trip --");
// Pitch + warp should survive a save/load round-trip (v5).
src.SetClipPitch(aTrk, aClip, 4.0f);
+ src.SetClipReverse(aTrk, aClip, true); // reverse (v19)
src.SetClipWarp(aTrk, aClip, true, 3); // Complex
src.SetClipWarpLength(aTrk, aClip, 2.0);
// Warp markers (v6): enable seeds two end markers; add a midpoint.
@@ -4368,6 +4512,7 @@ Console.WriteLine("-- M7-6b: audio round-trip --");
&& Math.Abs(aci1.SourceOffsetFrames - 1000) < 1e-6, "audio clip geometry restored");
Check(Math.Abs(aci1.PitchSemitones - 4.0f) < 1e-4 && aci1.WarpEnabled != 0
&& aci1.WarpMode == 3 && Math.Abs(aci1.WarpBeats - 2.0) < 1e-4, "audio clip pitch + warp restored");
+ Check(aci1.Reversed != 0, "audio clip reverse restored (v19)");
var lms = new double[16]; var lmb = new double[16];
Check(dst.GetClipWarpMarkers(dAudio, 0, lms, lmb) == 3, "warp markers restored (3)");
var lenv = dst.GetClipVolumeEnvelope(dAudio, 0);