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.

(fix) Session view fixes

Egor Khindikaynen9b403607aa62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8dd5b864..dc81f6b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,7 +52,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
column that folds its tracks away; returns and the master close the row; the mixer under the
grid has I/O, Sends and Mixer sections to show or hide. An empty slot's stop button can be
removed so a scene keeps that track playing, and the **ARR** badge hands one track back to the
- Arrangement. All of it is saved with the project and reachable over MCP.
+ Arrangement. Audio slots are full audio clips now — double-click one for the same clip editor
+ as the Arrangement (start / end, warp with markers, pitch, reverse, gain, envelopes, ADSR); a
+ warped loop stays in time when the tempo changes, and an Arrangement clip dragged into a slot
+ keeps its trim and warp. Right-click a column header, a slot or the empty grid to add an
+ instrument, audio or return track (or rename / delete one). All of it is saved with the
+ project and reachable over MCP.
### Changed
- **Import audio** moved to ⌘⇧I — ⌘I now inserts a scene in the Session view. Launch
diff --git a/src/managed/Nota.App/AudioClipEditorView.cs b/src/managed/Nota.App/AudioClipEditorView.cs
index e3b12a1e..ea83b6cd 100644
--- a/src/managed/Nota.App/AudioClipEditorView.cs
+++ b/src/managed/Nota.App/AudioClipEditorView.cs
@@ -329,8 +329,17 @@ public sealed class AudioClipEditorView : UserControl
// this clip, else hide it.
public void OnPlayhead(double beats, bool playing)
{
- double frac = (playing && _lengthBeats > 0 && beats >= _startBeat && beats <= _startBeat + _lengthBeats)
- ? (beats - _startBeat) / _lengthBeats : -1;
+ double frac;
+ int scene = SessionClip.SceneOf(ClipIndex);
+ if (scene >= 0)
+ {
+ // A Session slot runs on its own loop clock: follow the slot, not the song position.
+ double pos = _engine.SessionSlotState(TrackId, scene) == 3 ? _engine.SessionSlotPosition(TrackId) : -1;
+ frac = pos >= 0 && _lengthBeats > 0 && pos <= _lengthBeats ? pos / _lengthBeats : -1;
+ }
+ else
+ frac = (playing && _lengthBeats > 0 && beats >= _startBeat && beats <= _startBeat + _lengthBeats)
+ ? (beats - _startBeat) / _lengthBeats : -1;
_wave.SetPlayhead(frac);
}
diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.cs
index 416a89b8..de288bb1 100644
--- a/src/managed/Nota.App/MainWindow.Detail.cs
+++ b/src/managed/Nota.App/MainWindow.Detail.cs
@@ -201,7 +201,7 @@ public partial class MainWindow
internal void SyncClipTab()
{
DetailClipBtn.IsEnabled = _session?.IsVisible == true
- ? _clipEditor is not null
+ ? _clipEditor is not null || SessionAudioEditorOpen
: SelectedClip(out _, out _, out _);
DetailPatternBtn.IsEnabled = PatternTarget(out _, out _, out _);
}
@@ -224,6 +224,9 @@ public partial class MainWindow
return true;
}
+ // The audio clip editor is open on a Session slot's take.
+ private bool SessionAudioEditorOpen => _audioEditor is not null && SessionClip.SceneOf(_audioEditorClipIndex) >= 0;
+
private bool IsDrumRackTrack(int trackId) => trackId > 0 && Engine.TrackInstrumentKind(trackId) == 4;
// Build the step grid over one clip (scene >= 0: a Session slot). Both note sources are
@@ -361,8 +364,11 @@ public partial class MainWindow
private void BuildAudioClipEditor(int trackId, int clipIndex)
{
if (_vm is null) return;
+ // A Session slot's take edits through the same clip API (SessionClip index); its
+ // edits repaint the Session grid instead of the timeline.
+ bool slot = SessionClip.SceneOf(clipIndex) >= 0;
_audioEditor = new AudioClipEditorView(Engine, trackId, clipIndex,
- TrackBrush(trackId), () => Timeline.Refresh());
+ TrackBrush(trackId), slot ? () => _session?.Refresh() : () => Timeline.Refresh());
_audioEditorTrackId = trackId;
_audioEditorClipIndex = clipIndex;
}
@@ -525,6 +531,7 @@ public partial class MainWindow
if (_session?.IsVisible == true)
{
if (_clipEditor is not null) ShowClipPanel();
+ else if (SessionAudioEditorOpen) ShowAudioClipPanel();
else RejectClipTab("Double-click a slot to edit it.");
return;
}
@@ -569,19 +576,13 @@ public partial class MainWindow
// Audio slot → the compact audio-slot editor; MIDI slot → the piano roll.
if (Engine.TryGetSessionAudioSlot(trackId, scene, out var _))
{
+ // Audio slot: the full audio clip editor (region, warp, pitch, envelopes, ADSR).
_sessionSlotTrack = -1; _sessionSlotScene = -1; // audio slot: no pattern to step
- SyncClipTab();
- var audioEd = new SessionAudioSlotEditor(Engine, trackId, scene, TrackBrush(trackId));
_editorRoll = null; _clipEditor = null;
_editorTrackId = -1; _editorClipIndex = -1;
- _lastClipEditor = audioEd;
- SetHost(ClipDetailHost, audioEd);
- SetDetailChip(trackId);
- if (DetailFloating) return;
- DetailClipBtn.IsEnabled = true;
- DetailClipBtn.IsChecked = true;
- DetailDevicesBtn.IsChecked = false;
- ShowDetail(250, honorPersist: true);
+ BuildAudioClipEditor(trackId, SessionClip.Index(scene));
+ SyncClipTab();
+ ShowAudioClipPanel();
return;
}
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index c3a60177..13c0bc24 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -330,6 +330,12 @@ public partial class MainWindow : Window
_session.ItemDropped += OnSessionDrop; // browser drag & drop (M7-5)
_session.ArrangementChanged += () => Timeline.Refresh(); // M5-6
_session.Status += msg => vm.StatusText = msg;
+ // Session context menus add tracks through the same path as the arrangement's.
+ _session.AddTrackRequested += (kind, anchor) =>
+ {
+ if (kind == NewTrackKind.Return) OnAddReturnClicked(this, new RoutedEventArgs());
+ else AddTrack(kind, anchor);
+ };
// Selecting a slot selects its track everywhere: devices below, arrangement header.
_session.SlotSelected += (trackId, _) => Timeline.Select(trackId, -1);
Timeline.SessionChanged += () => _session?.Refresh(); // M5-6
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index ee64b21a..3d21bc02 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -997,6 +997,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("Drag scene", "Reorder scenes"),
("Double-click slot", "Edit the clip · an empty MIDI slot gets a new clip"),
("Double-click header", "Rename the track"),
+ ("Right-click header or grid", "Add an instrument, audio or return track · rename or delete one"),
}),
("PIANO ROLL", new[]
{
diff --git a/src/managed/Nota.App/SessionAudioSlotEditor.cs b/src/managed/Nota.App/SessionAudioSlotEditor.cs
deleted file mode 100644
index 8bb6e32c..00000000
--- a/src/managed/Nota.App/SessionAudioSlotEditor.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// A compact editor for a Session-view AUDIO slot — the audio counterpart of the piano-roll
-// slot editor. Session audio loops the whole sample over the slot's loop length, so the
-// editable properties are the loop length and playback gain; the waveform is shown for
-// reference. (Trim / warp / pitch aren't honoured by the session render, so they're omitted.)
-
-using System;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Layout;
-using Avalonia.Media;
-using Nota.Application;
-using Nota.Presentation;
-
-namespace Nota.App;
-
-public sealed class SessionAudioSlotEditor : UserControl
-{
- private static readonly IBrush Card = NotaPalette.SurfaceCard;
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush Text2 = NotaPalette.TextSecondary;
- private static readonly IBrush Text3 = NotaPalette.TextTertiary;
-
- private readonly IAudioEngine _engine;
- private readonly int _trackId, _scene;
-
- public SessionAudioSlotEditor(IAudioEngine engine, int trackId, int scene, IBrush color)
- {
- _engine = engine; _trackId = trackId; _scene = scene;
-
- var title = new TextBlock
- {
- Text = $"Track {trackId} · Scene {scene + 1} · audio", FontSize = 11, FontWeight = FontWeight.SemiBold,
- Foreground = NotaPalette.TextPrimary, VerticalAlignment = VerticalAlignment.Center,
- };
-
- var wave = new WaveStrip(LoadPeaks(), color) { Height = 96 };
- var waveBox = new Border
- {
- Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
- CornerRadius = NotaRadius.Tile, Child = wave, ClipToBounds = true,
- };
-
- // Gain: fader maps 0..1 -> 0..2 linear (unity at 0.5), with a dB readout.
- float gain = _engine.SessionSlotGain(trackId, scene);
- var gainFader = new MiniFader(Math.Clamp(gain / 2.0, 0, 1), 1.0) { Default = 0.5, Width = 180 };
- var gainDb = new TextBlock { FontSize = 10, Classes = { "Mono" }, Foreground = Text3, Width = 48, TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center };
- void ShowGain(double f) { double g = f * 2.0; gainDb.Text = g <= 1e-4 ? "−∞" : $"{AudioMath.LinToDb(g):+0.0;−0.0}\u2009dB"; }
- gainFader.ValueChanged += f => { _engine.SetSessionSlotGain(trackId, scene, (float)(f * 2.0)); ShowGain(f); };
- ShowGain(gainFader.Value);
- var gainRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { Label("GAIN"), gainFader, gainDb } };
-
- // Loop length: quick presets (the same set as the slot's right-click menu).
- var lenRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center };
- lenRow.Children.Add(Label("LOOP"));
- double curLen = _engine.SessionSlotLength(trackId, scene);
- foreach (double beats in new[] { 1.0, 2.0, 4.0, 8.0, 16.0 })
- {
- double b = beats;
- var chip = LengthChip($"{b:0.#}", Math.Abs(curLen - b) < 1e-6);
- chip.PointerPressed += (_, _) =>
- {
- _engine.SetSessionSlotLength(trackId, scene, b);
- foreach (var c in lenRow.Children) if (c is Border cb && cb.Tag is double tb)
- Paint(cb, Math.Abs(tb - b) < 1e-6);
- };
- lenRow.Children.Add(chip);
- }
-
- var controls = new StackPanel { Spacing = 10, Margin = new Thickness(12, 10, 12, 12), Children = { gainRow, lenRow } };
-
- var body = new DockPanel { LastChildFill = true };
- var head = new Border { Height = 34, Padding = new Thickness(12, 0), BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = title };
- DockPanel.SetDock(head, Dock.Top);
- DockPanel.SetDock(controls, Dock.Bottom);
- body.Children.Add(head);
- body.Children.Add(controls);
- var waveWrap = new Border { Padding = new Thickness(12, 12, 12, 0), Child = waveBox };
- body.Children.Add(waveWrap);
-
- Content = new Border { Background = Card, Child = body };
- }
-
- private static TextBlock Label(string t) => new() { Text = t, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = Text3, VerticalAlignment = VerticalAlignment.Center, Width = 34 };
-
- private static Border LengthChip(string t, bool active)
- {
- var b = new Border
- {
- Height = 22, MinWidth = 34, CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1),
- Padding = new Thickness(8, 0), Tag = double.Parse(t, NotaNum.Culture),
- Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
- Child = new TextBlock { Text = t + "b", FontSize = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },
- };
- Paint(b, active);
- return b;
- }
-
- private static void Paint(Border chip, bool active)
- {
- chip.Background = active ? NotaPalette.AccentSubtle : NotaPalette.SurfaceRaised;
- chip.BorderBrush = active ? NotaPalette.Accent : NotaPalette.BorderStrong;
- if (chip.Child is TextBlock tb) tb.Foreground = active ? NotaPalette.AccentBright : Text2;
- }
-
- // Downsample the slot's sample into ~600 min/max buckets for the waveform strip.
- private float[] LoadPeaks()
- {
- if (!_engine.TryGetSessionAudioSlot(_trackId, _scene, out var slot) || slot.SampleId == 0)
- return Array.Empty<float>();
- float[] data = _engine.ReadSample(slot.SampleId); // interleaved stereo
- long frames = data.Length / 2;
- if (frames <= 0) return Array.Empty<float>();
- const int buckets = 600;
- var peaks = new float[buckets * 2]; // min,max per bucket
- long per = Math.Max(1, frames / buckets);
- for (int i = 0; i < buckets; i++)
- {
- long start = i * per, end = Math.Min(frames, start + per);
- float mn = 0, mx = 0;
- for (long f = start; f < end; f++)
- {
- float s = 0.5f * (data[f * 2] + data[f * 2 + 1]);
- if (s < mn) mn = s; if (s > mx) mx = s;
- }
- peaks[i * 2] = mn; peaks[i * 2 + 1] = mx;
- }
- return peaks;
- }
-
- // Filled min/max waveform.
- private sealed class WaveStrip : Control
- {
- private readonly float[] _peaks;
- private readonly IBrush _fill;
- public WaveStrip(float[] peaks, IBrush fill) { _peaks = peaks; _fill = fill; }
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height, mid = h / 2;
- int n = _peaks.Length / 2;
- if (n == 0 || w <= 0) return;
- var geo = new StreamGeometry();
- using (var g = geo.Open())
- {
- g.BeginFigure(new Point(0, mid), true);
- for (int i = 0; i < n; i++) { double x = i / (double)(n - 1) * w; g.LineTo(new Point(x, mid - _peaks[i * 2 + 1] * mid)); }
- for (int i = n - 1; i >= 0; i--) { double x = i / (double)(n - 1) * w; g.LineTo(new Point(x, mid - _peaks[i * 2] * mid)); }
- g.EndFigure(true);
- }
- ctx.DrawGeometry(_fill, null, geo);
- }
- }
-}
diff --git a/src/managed/Nota.App/SessionView.Grid.cs b/src/managed/Nota.App/SessionView.Grid.cs
index 755d34d0..4d41bb3e 100644
--- a/src/managed/Nota.App/SessionView.Grid.cs
+++ b/src/managed/Nota.App/SessionView.Grid.cs
@@ -271,22 +271,14 @@ public sealed partial class SessionView
var stack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 3, 8, 0), Children = { top, kind } };
Child = new Panel { Children = { stripe, stack } };
- if (c.Kind is ColKind.Track or ColKind.Group)
- PointerPressed += (_, e) =>
- {
- if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
- if (e.ClickCount == 2)
- {
- o.PromptText(this, o._engine.GetTrackName(c.TrackId), t =>
- {
- o._engine.SetTrackName(c.TrackId, t);
- o.Refresh();
- o.ArrangementChanged?.Invoke(); // the arrangement header shows the same name
- });
- return;
- }
- o.Select(new Selection(SelKind.Slot, c.TrackId, o._sel.Scene));
- };
+ PointerPressed += (_, e) =>
+ {
+ var pp = e.GetCurrentPoint(this).Properties;
+ if (pp.IsRightButtonPressed) { e.Handled = true; o.ShowHeaderMenu(this, c); return; }
+ if (!pp.IsLeftButtonPressed || c.Kind is not (ColKind.Track or ColKind.Group)) return;
+ if (e.ClickCount == 2) { o.PromptRenameTrack(this, c.TrackId); return; }
+ o.Select(new Selection(SelKind.Slot, c.TrackId, o._sel.Scene));
+ };
Sync();
}
@@ -852,9 +844,53 @@ public sealed partial class SessionView
bool stop = _engine.GetSessionSlotStopButton(c.TrackId, scene);
f.Items.Add(MenuKit.Item(stop ? "Remove stop button" : "Add stop button", GlyphKind.Stop, () => { _engine.SetSessionSlotStopButton(c.TrackId, scene, !stop); RefreshSlot(c.TrackId, scene); }));
}
+ f.Items.Add(new Separator());
+ foreach (var mi in AddTrackItems(c.TrackId)) f.Items.Add(mi);
+ f.ShowAt(anchor, showAtPointer: true);
+ }
+
+ // "Add …" entries: the new track lands after `anchorTrackId` (inside it for a group), or at the end.
+ private IEnumerable<MenuItem> AddTrackItems(int anchorTrackId)
+ {
+ yield return MenuKit.Item("Add instrument track", GlyphKind.Plus, () => AddTrackRequested?.Invoke(NewTrackKind.Instrument, anchorTrackId));
+ yield return MenuKit.Item("Add audio track", GlyphKind.Plus, () => AddTrackRequested?.Invoke(NewTrackKind.Audio, anchorTrackId));
+ yield return MenuKit.Item("Add return track", GlyphKind.Plus, () => AddTrackRequested?.Invoke(NewTrackKind.Return, anchorTrackId));
+ }
+
+ private void ShowAddTrackMenu(Control anchor, int anchorTrackId)
+ {
+ var f = new MenuFlyout();
+ foreach (var mi in AddTrackItems(anchorTrackId)) f.Items.Add(mi);
f.ShowAt(anchor, showAtPointer: true);
}
+ // Column header menu: rename / delete the track, or add one next to it.
+ private void ShowHeaderMenu(Control anchor, Column c)
+ {
+ var f = new MenuFlyout();
+ if (c.Kind != ColKind.Master)
+ {
+ f.Items.Add(MenuKit.Item("Rename…", GlyphKind.Edit, () => PromptRenameTrack(anchor, c.TrackId)));
+ f.Items.Add(MenuKit.Item(c.Kind == ColKind.Group ? "Delete group and its tracks" : "Delete track", GlyphKind.Trash, () =>
+ {
+ _engine.RemoveTracks(new[] { c.TrackId }); // a group takes its tracks along, one undo step
+ Refresh();
+ ArrangementChanged?.Invoke();
+ }));
+ f.Items.Add(new Separator());
+ }
+ foreach (var mi in AddTrackItems(c.Kind == ColKind.Master ? -1 : c.TrackId)) f.Items.Add(mi);
+ f.ShowAt(anchor, showAtPointer: true);
+ }
+
+ private void PromptRenameTrack(Control anchor, int trackId)
+ => PromptText(anchor, _engine.GetTrackName(trackId), t =>
+ {
+ _engine.SetTrackName(trackId, t);
+ Refresh();
+ ArrangementChanged?.Invoke(); // the arrangement header shows the same name
+ });
+
private void ShowSceneMenu(Control anchor, int scene)
{
var f = new MenuFlyout();
diff --git a/src/managed/Nota.App/SessionView.cs b/src/managed/Nota.App/SessionView.cs
index 0dbe4a52..3d4b71cc 100644
--- a/src/managed/Nota.App/SessionView.cs
+++ b/src/managed/Nota.App/SessionView.cs
@@ -76,6 +76,8 @@ public sealed partial class SessionView : UserControl
public event Action<int, int>? SlotSelected;
/// <summary>Raised after a slot is copied into the arrangement (M5-6) or a track is renamed.</summary>
public event Action? ArrangementChanged;
+ /// <summary>A context menu asked for a new track (kind, the track to place it after, or -1 = at the end).</summary>
+ public event Action<NewTrackKind, int>? AddTrackRequested;
/// <summary>A one-line status message for the main window's status bar.</summary>
public event Action<string>? Status;
/// <summary>Raised when a browser item is dropped on a slot (M7-5): item, track id,
@@ -107,6 +109,15 @@ public sealed partial class SessionView : UserControl
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
};
var gridArea = new Border { Background = NotaPalette.BgSunken, Child = hScroll };
+ // Right-click on the empty part of the grid: add a track (cells and headers handle their own).
+ gridArea.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(gridArea).Properties.IsRightButtonPressed) return;
+ // Only on the background — a fader's right-click belongs to MIDI Learn.
+ if (e.Source is not (Panel or Border or Avalonia.Controls.Presenters.ScrollContentPresenter or ScrollViewer or BlankCell)) return;
+ e.Handled = true;
+ ShowAddTrackMenu(gridArea, -1);
+ };
_inspectorHost.Background = NotaPalette.Panel;
_inspectorHost.BorderBrush = NotaPalette.BorderDefault;
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index 8dda5649..026d4e1d 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -143,6 +143,17 @@ public struct NotaSessionAudioSlot
public float Gain;
}
+/// <summary>Session audio slots edit through the audio-clip API: a slot's take is the clip at
+/// index <c>-(scene + 2)</c> on its track (arrangement clips are &gt;= 0). Matches the engine's
+/// kSessionClipBase addressing.</summary>
+public static class SessionClip
+{
+ public const int Base = -2;
+ public static int Index(int scene) => Base - scene;
+ /// <summary>The scene a clip index addresses, or -1 for an arrangement clip.</summary>
+ public static int SceneOf(int clipIndex) => clipIndex <= Base ? Base - clipIndex : -1;
+}
+
/// <summary>How a session clip reacts to its launch button (Session P0).</summary>
public enum SessionLaunchMode { Trigger = 0, Gate = 1, Toggle = 2, Repeat = 3 }
diff --git a/src/managed/Nota.Infrastructure/Persistence/AudioClipState.cs b/src/managed/Nota.Infrastructure/Persistence/AudioClipState.cs
index 155759d7..2d0639f5 100644
--- a/src/managed/Nota.Infrastructure/Persistence/AudioClipState.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/AudioClipState.cs
@@ -56,6 +56,14 @@ internal static class AudioClipState
if (ci < 0) return -1;
if (ac.Name is { Length: > 0 } acn) engine.SetClipName(trackId, ci, acn);
if (!ac.Active) engine.SetClipActive(trackId, ci, false); // clip deactivate (v17)
+ ApplyShape(engine, trackId, ci, ac);
+ return ci;
+ }
+
+ /// <summary>Pitch, reverse, warp, envelopes and ADSR onto an existing clip — an
+ /// arrangement clip, or a Session slot's take addressed by <see cref="SessionClip.Index"/>.</summary>
+ public static void ApplyShape(IAudioEngine engine, int trackId, int ci, AudioClipDto ac)
+ {
if (ac.PitchSemitones != 0) engine.SetClipPitch(trackId, ci, ac.PitchSemitones);
if (ac.Reversed) engine.SetClipReverse(trackId, ci, true); // reverse (v19)
if (ac.WarpEnabled != 0)
@@ -77,6 +85,5 @@ internal static class AudioClipState
engine.SetClipPanEnvelope(trackId, ci, Array.ConvertAll(penv, p => p.ToPoint()));
if (ac.Adsr is { } adsr) // ADSR (v20)
engine.SetClipAdsr(trackId, ci, adsr.ToAdsr());
- return ci;
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 61cb0ab9..7224f511 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -232,17 +232,17 @@ public sealed class ProjectService
{
string? rel = RegisterSample(doc, engine, sa.SampleId, warnings);
if (rel == null) continue;
+ // The take is a full audio clip (region, warp, pitch, envelopes): saved like one.
+ var audio = engine.TryGetAudioClipInfo(ti.Id, SessionClip.Index(s), out var sac)
+ ? AudioClipState.Capture(engine, ti.Id, SessionClip.Index(s), sac)
+ : new AudioClipDto { SourceOffsetFrames = sa.SourceOffsetFrames, LengthFrames = sa.LengthFrames, Gain = sa.Gain };
+ audio.Sample = rel;
+ audio.Name = null; // the slot carries its own name
t.SessionSlots.Add(WithClipProps(engine, ti.Id, new SessionSlotDto
{
Scene = s,
LengthBeats = sa.LengthBeats,
- Audio = new AudioClipDto
- {
- Sample = rel,
- SourceOffsetFrames = sa.SourceOffsetFrames,
- LengthFrames = sa.LengthFrames,
- Gain = sa.Gain,
- },
+ Audio = audio,
}));
}
}
@@ -645,8 +645,13 @@ public sealed class ProjectService
if (!engine.AddSessionAudioClip(id, sl.Scene, ResolveInBundle(bundleDir, sa.Sample),
sl.LengthBeats, sa.SourceOffsetFrames, sa.LengthFrames, sa.Gain))
warnings.Add($"Couldn't reload session take \"{sa.Sample}\".");
- else if (engine.TryGetSessionAudioSlot(id, sl.Scene, out var lsa))
- BundleContent.SeedSample(engine, lsa.SampleId, sa.Sample);
+ else
+ {
+ if (engine.TryGetSessionAudioSlot(id, sl.Scene, out var lsa))
+ BundleContent.SeedSample(engine, lsa.SampleId, sa.Sample);
+ AudioClipState.ApplyShape(engine, id, SessionClip.Index(sl.Scene), sa);
+ engine.SetSessionSlotLength(id, sl.Scene, sl.LengthBeats); // clip edits resync it; the saved loop wins
+ }
}
else
{
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 2aa7bfdd..e09f1e60 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -1197,6 +1197,11 @@ private:
static constexpr double kGrowingTakeBeats = 4096.0;
bool recordSessionGrowing_ = false;
double roundedTakeBeats(double beats) const;
+ double audioClipBeats(const AudioClip& c) const;
+ void syncSessionAudioSlot(Track& t, int32_t clipIndex) const;
+ // Mix one audio clip (warp cache / resampled source, envelopes, ADSR, edge fades) into
+ // `dst` for the block at blockStart samples on the clip's timeline. Adds; never clears.
+ void mixAudioClip(const AudioClip& clip, float* dst, int32_t frames, double blockStart, double spb, float extraGain);
// recording target (message thread)
int32_t recordTrackId_ = 0;
diff --git a/src/native/nota.engine/src/Engine_Automation.cpp b/src/native/nota.engine/src/Engine_Automation.cpp
index eee2fd1d..d73d012b 100644
--- a/src/native/nota.engine/src/Engine_Automation.cpp
+++ b/src/native/nota.engine/src/Engine_Automation.cpp
@@ -645,8 +645,8 @@ bool Engine::setMasterVolumeAutomation(const NotaAutomationPoint* pts, int32_t c
int32_t Engine::getAudioClipVolumeEnvelope(int32_t trackId, int32_t clipIndex, NotaAutomationPoint* out, int32_t cap) const {
auto t = findTrackAuthoring(trackId);
if (!t || t->type() != TrackType::Audio) return 0;
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;
- const auto& pts = t->clips[clipIndex].volumeEnvelope.points;
+ if (!audioClipRef(*t, clipIndex)) return 0;
+ const auto& pts = (*audioClipRef(*t, clipIndex)).volumeEnvelope.points;
if (!out) return static_cast<int32_t>(pts.size());
const int32_t n = std::min<int32_t>(cap, static_cast<int32_t>(pts.size()));
for (int32_t i = 0; i < n; ++i) { out[i].beat = pts[i].beat; out[i].value = pts[i].value; out[i].curve = pts[i].curve; }
@@ -656,14 +656,15 @@ int32_t Engine::getAudioClipVolumeEnvelope(int32_t trackId, int32_t clipIndex, N
bool Engine::setAudioClipVolumeEnvelope(int32_t trackId, int32_t clipIndex, const NotaAutomationPoint* pts, int32_t count) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto nt = cloneTrack(*old);
- auto& lane = nt->clips[clipIndex].volumeEnvelope;
+ auto& lane = (*audioClipRef(*nt, clipIndex)).volumeEnvelope;
lane.points.clear();
lane.points.reserve(count);
for (int32_t i = 0; i < count; ++i) lane.points.push_back({pts[i].beat, pts[i].value, pts[i].curve});
std::sort(lane.points.begin(), lane.points.end(),
[](const AutomationPoint& a, const AutomationPoint& b) { return a.beat < b.beat; });
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt); // structural edit → undo checkpoint
return true;
}
@@ -671,8 +672,8 @@ bool Engine::setAudioClipVolumeEnvelope(int32_t trackId, int32_t clipIndex, cons
int32_t Engine::getAudioClipPanEnvelope(int32_t trackId, int32_t clipIndex, NotaAutomationPoint* out, int32_t cap) const {
auto t = findTrackAuthoring(trackId);
if (!t || t->type() != TrackType::Audio) return 0;
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;
- const auto& pts = t->clips[clipIndex].panEnvelope.points;
+ if (!audioClipRef(*t, clipIndex)) return 0;
+ const auto& pts = (*audioClipRef(*t, clipIndex)).panEnvelope.points;
if (!out) return static_cast<int32_t>(pts.size());
const int32_t n = std::min<int32_t>(cap, static_cast<int32_t>(pts.size()));
for (int32_t i = 0; i < n; ++i) { out[i].beat = pts[i].beat; out[i].value = pts[i].value; out[i].curve = pts[i].curve; }
@@ -682,14 +683,15 @@ int32_t Engine::getAudioClipPanEnvelope(int32_t trackId, int32_t clipIndex, Nota
bool Engine::setAudioClipPanEnvelope(int32_t trackId, int32_t clipIndex, const NotaAutomationPoint* pts, int32_t count) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto nt = cloneTrack(*old);
- auto& lane = nt->clips[clipIndex].panEnvelope;
+ auto& lane = (*audioClipRef(*nt, clipIndex)).panEnvelope;
lane.points.clear();
lane.points.reserve(count);
for (int32_t i = 0; i < count; ++i) lane.points.push_back({pts[i].beat, pts[i].value, pts[i].curve});
std::sort(lane.points.begin(), lane.points.end(),
[](const AutomationPoint& a, const AutomationPoint& b) { return a.beat < b.beat; });
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index d29c8cb7..1562bf90 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -555,35 +555,31 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double s
sp.localBeats = p + db;
}
-// Renders an audio track's playing Session slot (pre-fader), looping the captured
-// take over the slot's length (M5-4). Position tracks the slot's own loop clock.
+// Renders an audio track's playing Session slot (pre-fader): the slot's clip — the same
+// clip model as the arrangement (region, warp, pitch, reverse, envelopes) — looped over the
+// slot's length on the slot's own clock (S-06). A block that crosses the loop end renders
+// in two pieces; a one-shot slot stops at the end.
void Engine::renderSessionAudioSlotRaw(Track& t, float* dst, int32_t frames, double spb) {
for (int32_t i = 0; i < frames * 2; ++i) dst[i] = 0.0f;
auto& sp = *t.sessionPlayer;
const int32_t slot = sp.playing.load(std::memory_order_relaxed);
- if (slot < 0 || slot >= static_cast<int32_t>(t.sessionSlots.size())) return;
+ if (slot < 0 || slot >= static_cast<int32_t>(t.sessionSlots.size()) || spb <= 0.0) return;
const SessionSlot& s = t.sessionSlots[slot];
if (!s.hasClip || !s.audio.sample) return;
- const SampleBuffer& sb = *s.audio.sample;
- const double sr = transport_.sampleRate();
- const double ratio = sr > 0 ? sb.sourceSampleRate / sr : 1.0; // source frames per device frame
const double L = s.lengthBeats > 0 ? s.lengthBeats : 4.0;
- const float gain = s.audio.gain * sp.gain;
-
- for (int32_t i = 0; i < frames; ++i) {
- if (!s.loop && sp.localBeats + i / spb >= L) break; // one-shot: silence past the end
- double loopBeat = std::fmod(sp.localBeats + i / spb, L);
- if (loopBeat < 0.0) loopBeat += L;
- const double srcPos = loopBeat * spb * ratio; // -> source frames
- const int64_t i0 = static_cast<int64_t>(srcPos);
- if (i0 < 0 || i0 >= sb.frames) continue;
- const double frac = srcPos - i0;
- float l0, r0, l1, r1;
- sb.readStereo(i0, l0, r0);
- sb.readStereo(i0 + 1, l1, r1);
- dst[i * 2] = static_cast<float>(l0 + (l1 - l0) * frac) * gain;
- dst[i * 2 + 1] = static_cast<float>(r0 + (r1 - r0) * frac) * gain;
+ double p = sp.localBeats;
+ int32_t done = 0;
+ while (done < frames) {
+ if (!s.loop && p >= L) break;
+ double local = std::fmod(p, L);
+ if (local < 0.0) local += L;
+ const double toEnd = (L - local) * spb;
+ int32_t seg = static_cast<int32_t>(std::min<double>(frames - done, std::ceil(toEnd - 1e-9)));
+ if (seg <= 0) seg = 1;
+ mixAudioClip(s.audio, dst + done * 2, seg, local * spb, spb, sp.gain);
+ done += seg;
+ p += seg / spb;
}
sp.localBeats += frames / spb;
}
@@ -593,101 +589,105 @@ void Engine::renderSessionAudioSlotRaw(Track& t, float* dst, int32_t frames, dou
void Engine::renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst, int32_t frames,
double blockStart, double spb) {
for (int32_t i = 0; i < frames * 2; ++i) dst[i] = 0.0f;
- const double sr = transport_.sampleRate();
- for (const AudioClip& clip : clips) {
- if (!clip.active) continue; // deactivated clip (key 0): stays on the timeline but silent
- const double startSamples = clip.startBeat * spb;
- // Clip envelopes (M9 follow-up): 0..1 volume + -1..1 pan curves in clip-local
- // beats, applied per sample. Empty = fast path (no cost). Pan uses a balance
- // law (unity at centre) so it composes with the track's own pan stage.
- const bool hasVol = !clip.volumeEnvelope.points.empty();
- const bool hasPan = !clip.panEnvelope.points.empty();
- const bool hasAdsr = !clip.adsr.isIdentity();
- const bool hasEnv = hasVol || hasPan || hasAdsr;
- double lenBeats = 0.0; // played length (beats) for the ADSR release — set per path below
- auto applyEnv = [&](double p, float& l, float& r) {
- const double b = (p - startSamples) / spb;
- if (hasAdsr) { const float g = clip.adsr.gainAt(b, lenBeats); l *= g; r *= g; }
- if (hasVol) { const float g = std::clamp(clip.volumeEnvelope.valueAt(b), 0.0f, 1.0f); l *= g; r *= g; }
- if (hasPan) {
- const float pan = std::clamp(clip.panEnvelope.valueAt(b), -1.0f, 1.0f);
- if (pan > 0.0f) l *= (1.0f - pan); else if (pan < 0.0f) r *= (1.0f + pan);
- }
- };
+ for (const AudioClip& clip : clips) mixAudioClip(clip, dst, frames, blockStart, spb, 1.0f);
+}
- // Warped clips: copy straight from the offline stretch cache.
- // The cache holds the played window [warpPlayStart, warpPlayEndEff] pre-rendered
- // at the device rate, so there is no realtime stretch here — just a memcpy-cheap
- // read (no per-clip-start priming spike). The clip's on-timeline length is the
- // cache's frame count (both are warpPlayLen×spb once rebuilt for the tempo).
- if (clip.warpEnabled && clip.warpCache && clip.warpCache->frames > 0) {
- const WarpCache& wc = *clip.warpCache;
- const double clipDeviceLen = static_cast<double>(wc.frames);
- lenBeats = clipDeviceLen / spb;
- const double ovStart = std::max(blockStart, startSamples);
- const double ovEnd = std::min(blockStart + frames, startSamples + clipDeviceLen);
- if (ovEnd <= ovStart) continue;
- 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) continue;
- const int64_t cacheBase = std::llround(ovStart - startSamples); // 0-based into the cache
- const float* csamp = wc.samples.data();
- const float g = clip.gain;
- for (int32_t j = 0; j < segLen; ++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);
- dst[(dstOff + j) * 2] += l * g;
- dst[(dstOff + j) * 2 + 1] += r * g;
- }
- continue;
+// One clip of renderAudioClipsRaw — shared with Session audio slots, which loop a clip on
+// their own clock (renderSessionAudioSlotRaw).
+void Engine::mixAudioClip(const AudioClip& clip, float* dst, int32_t frames, double blockStart, double spb, float extraGain) {
+ if (!clip.active) return; // deactivated clip (key 0): stays on the timeline but silent
+ const double sr = transport_.sampleRate();
+ const double startSamples = clip.startBeat * spb;
+ // Clip envelopes (M9 follow-up): 0..1 volume + -1..1 pan curves in clip-local
+ // beats, applied per sample. Empty = fast path (no cost). Pan uses a balance
+ // law (unity at centre) so it composes with the track's own pan stage.
+ const bool hasVol = !clip.volumeEnvelope.points.empty();
+ const bool hasPan = !clip.panEnvelope.points.empty();
+ const bool hasAdsr = !clip.adsr.isIdentity();
+ const bool hasEnv = hasVol || hasPan || hasAdsr;
+ double lenBeats = 0.0; // played length (beats) for the ADSR release — set per path below
+ auto applyEnv = [&](double p, float& l, float& r) {
+ const double b = (p - startSamples) / spb;
+ if (hasAdsr) { const float g = clip.adsr.gainAt(b, lenBeats); l *= g; r *= g; }
+ if (hasVol) { const float g = std::clamp(clip.volumeEnvelope.valueAt(b), 0.0f, 1.0f); l *= g; r *= g; }
+ if (hasPan) {
+ const float pan = std::clamp(clip.panEnvelope.valueAt(b), -1.0f, 1.0f);
+ if (pan > 0.0f) l *= (1.0f - pan); else if (pan < 0.0f) r *= (1.0f + pan);
}
- // Warp enabled but the cache isn't ready yet (a rebuild is pending after an
- // edit/tempo change): stay silent rather than fall through and play the clip
- // unwarped (wrong length/pitch) for the brief window until the cache publishes.
- if (clip.warpEnabled) continue;
-
- // Unwarped clips resample at their natural rate with varispeed transpose
- // folded into the read ratio.
- if (!clip.sample) continue;
- const SampleBuffer& sb = *clip.sample;
- const double ratio = sb.sourceSampleRate / sr * clip.pitchRatio();
- const int64_t len = clip.effectiveLength();
- const double clipDeviceLen = len / ratio;
+ };
+
+ // Warped clips: copy straight from the offline stretch cache.
+ // The cache holds the played window [warpPlayStart, warpPlayEndEff] pre-rendered
+ // at the device rate, so there is no realtime stretch here — just a memcpy-cheap
+ // read (no per-clip-start priming spike). The clip's on-timeline length is the
+ // cache's frame count (both are warpPlayLen×spb once rebuilt for the tempo).
+ if (clip.warpEnabled && clip.warpCache && clip.warpCache->frames > 0) {
+ const WarpCache& wc = *clip.warpCache;
+ const double clipDeviceLen = static_cast<double>(wc.frames);
lenBeats = clipDeviceLen / spb;
- for (int32_t i = 0; i < frames; ++i) {
- const double p = blockStart + i;
- if (p < startSamples || p >= startSamples + clipDeviceLen) continue;
- // 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;
- sb.readStereo(i0, l0, r0);
- sb.readStereo(i0 + 1, l1, r1);
- float l = static_cast<float>(l0 + (l1 - l0) * frac) * clip.gain;
- float r = static_cast<float>(r0 + (r1 - r0) * frac) * clip.gain;
- // Short edge fade (~3 ms) so a clip that starts/ends mid-waveform doesn't click.
- const double edge = std::min(3.0 * sr / 1000.0, clipDeviceLen * 0.5);
- if (edge > 1.0) {
- const double into = p - startSamples;
- double eg = 1.0;
- if (into < edge) eg = into / edge;
- else if (into > clipDeviceLen - edge) eg = (clipDeviceLen - into) / edge;
- eg = std::clamp(eg, 0.0, 1.0);
- l *= (float)eg; r *= (float)eg;
- }
- applyEnv(p, l, r);
- dst[i * 2] += l;
- dst[i * 2 + 1] += r;
+ const double ovStart = std::max(blockStart, startSamples);
+ const double ovEnd = std::min(blockStart + frames, startSamples + clipDeviceLen);
+ 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 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
+ // 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);
+ dst[(dstOff + j) * 2] += l * g;
+ dst[(dstOff + j) * 2 + 1] += r * g;
+ }
+ return;
+ }
+ // Warp enabled but the cache isn't ready yet (a rebuild is pending after an
+ // edit/tempo change): stay silent rather than fall through and play the clip
+ // unwarped (wrong length/pitch) for the brief window until the cache publishes.
+ if (clip.warpEnabled) return;
+
+ // Unwarped clips resample at their natural rate with varispeed transpose
+ // folded into the read ratio.
+ if (!clip.sample) return;
+ const SampleBuffer& sb = *clip.sample;
+ const double ratio = sb.sourceSampleRate / sr * clip.pitchRatio();
+ const int64_t len = clip.effectiveLength();
+ const double clipDeviceLen = len / ratio;
+ lenBeats = clipDeviceLen / spb;
+ for (int32_t i = 0; i < frames; ++i) {
+ const double p = blockStart + i;
+ if (p < startSamples || p >= startSamples + clipDeviceLen) continue;
+ // 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;
+ sb.readStereo(i0, l0, r0);
+ sb.readStereo(i0 + 1, l1, r1);
+ float l = static_cast<float>(l0 + (l1 - l0) * frac) * clip.gain * extraGain;
+ float r = static_cast<float>(r0 + (r1 - r0) * frac) * clip.gain * extraGain;
+ // Short edge fade (~3 ms) so a clip that starts/ends mid-waveform doesn't click.
+ const double edge = std::min(3.0 * sr / 1000.0, clipDeviceLen * 0.5);
+ if (edge > 1.0) {
+ const double into = p - startSamples;
+ double eg = 1.0;
+ if (into < edge) eg = into / edge;
+ else if (into > clipDeviceLen - edge) eg = (clipDeviceLen - into) / edge;
+ eg = std::clamp(eg, 0.0, 1.0);
+ l *= (float)eg; r *= (float)eg;
}
+ applyEnv(p, l, r);
+ dst[i * 2] += l;
+ dst[i * 2 + 1] += r;
}
}
diff --git a/src/native/nota.engine/src/Engine_Session.cpp b/src/native/nota.engine/src/Engine_Session.cpp
index 4da99da8..44163f51 100644
--- a/src/native/nota.engine/src/Engine_Session.cpp
+++ b/src/native/nota.engine/src/Engine_Session.cpp
@@ -412,27 +412,21 @@ bool Engine::arrangementAudioClipToSession(int32_t trackId, int32_t clipIndex, i
if (!old || old->type() != TrackType::Audio) return false;
if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(old->clips.size())) return false;
if (scene < 0 || scene >= authoring_->sceneCount) return false;
- const auto sample = old->clips[clipIndex].sample;
- if (!sample) return false;
- const float gain = old->clips[clipIndex].gain;
- const std::string clipName = old->clips[clipIndex].name;
+ if (!old->clips[clipIndex].sample) return false;
auto nt = cloneTrack(*old);
if (static_cast<int32_t>(nt->sessionSlots.size()) < authoring_->sceneCount)
nt->sessionSlots.resize(authoring_->sceneCount);
+ // The whole clip comes along — its region, warp, pitch, reverse, gain and envelopes —
+ // and the slot loops exactly what the clip plays.
SessionSlot& s = nt->sessionSlots[scene];
s.hasClip = true;
- s.audio = AudioClip{};
- s.audio.sample = sample; // session audio loops the whole sample over lengthBeats
- s.audio.sourceOffsetFrames = 0.0;
- s.audio.lengthFrames = sample->frames;
- s.audio.gain = gain;
- s.name = clipName;
- // Loop length = the sample's real duration in beats at the current tempo (like a file drop).
- const double sr = transport_.sampleRate();
- const double spb = transport_.samplesPerBeat();
- const double seconds = sample->sourceSampleRate > 0 ? sample->frames / sample->sourceSampleRate : 0.0;
- s.lengthBeats = (spb > 0.0 && sr > 0.0) ? seconds * sr / spb : 4.0;
- if (!(s.lengthBeats > 0.0)) s.lengthBeats = 4.0;
+ s.midi = MidiClip{};
+ s.audio = nt->clips[clipIndex];
+ s.audio.startBeat = 0.0;
+ s.audio.active = true;
+ s.name = s.audio.name;
+ s.lengthBeats = 4.0;
+ syncSessionAudioSlot(*nt, sessionClipIndex(scene));
republishWithTrack(trackId, nt);
return true;
}
@@ -541,6 +535,30 @@ int32_t Engine::sessionNoteCount(int32_t trackId, int32_t scene) const {
return static_cast<int32_t>(t->sessionSlots[scene].midi.notes.size());
}
+// --- Session audio slots as clips (S-06) ------------------------------------------
+
+// A clip's played length in beats: the warp window when warped, else its source region at
+// the current tempo (varispeed included).
+double Engine::audioClipBeats(const AudioClip& c) const {
+ if (c.warpEnabled && c.warpBeats > 0.0) return c.warpPlayLen();
+ const double spb = transport_.samplesPerBeat();
+ const double devSR = transport_.sampleRate();
+ if (!c.sample || spb <= 0.0 || devSR <= 0.0 || c.sample->sourceSampleRate <= 0.0) return 0.0;
+ return static_cast<double>(c.effectiveLength()) * devSR / c.sample->sourceSampleRate / c.pitchRatio() / spb;
+}
+
+// After a clip edit on a slot's audio (clipIndex <= kSessionClipBase): the slot loops the
+// clip, so its loop length follows the clip's played length.
+void Engine::syncSessionAudioSlot(Track& t, int32_t clipIndex) const {
+ const int32_t scene = sessionSceneOfClip(clipIndex);
+ if (scene < 0 || scene >= static_cast<int32_t>(t.sessionSlots.size())) return;
+ SessionSlot& s = t.sessionSlots[scene];
+ if (!s.hasClip || !s.audio.sample) return;
+ s.audio.startBeat = 0.0;
+ const double beats = audioClipBeats(s.audio);
+ if (beats > 0.0) s.lengthBeats = beats;
+}
+
// --- Session P0: clip + scene properties --------------------------------------
namespace {
@@ -850,21 +868,7 @@ void Engine::serviceSessionFollow() {
// Peaks of an audio slot's take (whole sample) for the grid / inspector preview.
int32_t Engine::sessionSlotPeaks(int32_t trackId, int32_t scene, float* outMinMax, int32_t maxPoints) const {
- if (!outMinMax || maxPoints <= 0) return 0;
- auto t = findTrackAuthoring(trackId);
- const SessionSlot* s = t ? slotAt(*t, scene) : nullptr;
- if (!s || !s->hasClip || !s->audio.sample) return 0;
- const SampleBuffer& sb = *s->audio.sample;
- const int64_t total = sb.frames;
- if (total <= 0) return 0;
- 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) {
- float mn, mx;
- sb.peakRange(b * per, (b + 1) * per, mn, mx);
- outMinMax[b * 2] = mn; outMinMax[b * 2 + 1] = mx;
- }
- return buckets;
+ return getClipPeaks(trackId, sessionClipIndex(scene), outMinMax, maxPoints);
}
// --- Session P0: audio thread ---------------------------------------------------
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index ac4e51be..2b2c952f 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -60,8 +60,8 @@ bool Engine::audioClipInfo(int32_t trackId, int32_t clipIndex, NotaAudioClipInfo
if (!out) return false;
auto t = findTrackAuthoring(trackId);
if (!t || t->type() != TrackType::Audio) return false;
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return false;
- const AudioClip& c = t->clips[clipIndex];
+ if (!audioClipRef(*t, clipIndex)) return false;
+ const AudioClip& c = (*audioClipRef(*t, clipIndex));
out->start_beat = c.startBeat;
out->source_offset_frames = c.sourceOffsetFrames;
out->length_frames = c.lengthFrames;
@@ -80,9 +80,10 @@ bool Engine::audioClipInfo(int32_t trackId, int32_t clipIndex, NotaAudioClipInfo
bool Engine::setClipGain(int32_t trackId, int32_t clipIndex, float gain) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto nt = cloneTrack(*old);
- nt->clips[clipIndex].gain = gain < 0.0f ? 0.0f : gain;
+ (*audioClipRef(*nt, clipIndex)).gain = gain < 0.0f ? 0.0f : gain;
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -91,8 +92,8 @@ bool Engine::clipAdsr(int32_t trackId, int32_t clipIndex, NotaClipAdsr* out) con
if (!out) return false;
auto t = findTrackAuthoring(trackId);
if (!t || t->type() != TrackType::Audio) return false;
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return false;
- const ClipAdsr& a = t->clips[clipIndex].adsr;
+ if (!audioClipRef(*t, clipIndex)) return false;
+ const ClipAdsr& a = (*audioClipRef(*t, clipIndex)).adsr;
out->attack_beats = a.attack;
out->decay_beats = a.decay;
out->release_beats = a.release;
@@ -105,7 +106,7 @@ bool Engine::clipAdsr(int32_t trackId, int32_t clipIndex, NotaClipAdsr* out) con
bool Engine::setClipAdsr(int32_t trackId, int32_t clipIndex, const NotaClipAdsr& in) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto finite = [](double v) { return std::isfinite(v) ? std::max(0.0, v) : 0.0; };
ClipAdsr a;
a.attack = finite(in.attack_beats);
@@ -113,7 +114,8 @@ bool Engine::setClipAdsr(int32_t trackId, int32_t clipIndex, const NotaClipAdsr&
a.release = finite(in.release_beats);
a.sustain = std::isfinite(in.sustain) ? std::clamp(in.sustain, 0.0f, 1.0f) : 1.0f;
auto nt = cloneTrack(*old);
- nt->clips[clipIndex].adsr = a;
+ (*audioClipRef(*nt, clipIndex)).adsr = a;
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -240,8 +242,9 @@ const AudioClip* Engine::warpBuildTargetClip() const {
if (!wb_.building) return nullptr;
auto t = findTrackAuthoring(wb_.trackId);
if (!t || t->type() != TrackType::Audio) return nullptr;
- if (wb_.clipIndex < 0 || wb_.clipIndex >= static_cast<int32_t>(t->clips.size())) return nullptr;
- const AudioClip& c = t->clips[wb_.clipIndex];
+ const AudioClip* cp = audioClipRef(*t, wb_.clipIndex); // an arrangement clip or a session slot's
+ if (!cp) return nullptr;
+ const AudioClip& c = *cp;
if (!c.warpEnabled || c.warpCache) return nullptr;
if (!wb_.cache || warpCacheFrames(c, transport_.samplesPerBeat(), transport_.sampleRate()) != wb_.cache->frames)
return nullptr;
@@ -258,6 +261,8 @@ int64_t Engine::warpBuildRemainingFrames() const {
if (t->type() != TrackType::Audio) continue;
for (auto& c : t->clips)
if (c.warpEnabled && !c.warpCache) sum += warpCacheFrames(c, spb, devSR);
+ for (auto& sl : t->sessionSlots)
+ if (sl.hasClip && sl.audio.warpEnabled && !sl.audio.warpCache) sum += warpCacheFrames(sl.audio, spb, devSR);
}
// The in-progress clip is still un-cached above, so its full length was counted —
// subtract what's already rendered so the bar reflects real progress.
@@ -287,6 +292,12 @@ int64_t Engine::warpBuildStep(int32_t maxFrames) {
target = &c; tid = t->id(); ci = static_cast<int32_t>(i); break;
}
}
+ for (size_t sc = 0; !target && sc < t->sessionSlots.size(); ++sc) {
+ const SessionSlot& sl = t->sessionSlots[sc];
+ if (sl.hasClip && sl.audio.warpEnabled && !sl.audio.warpCache && warpCacheFrames(sl.audio, spb, devSR) > 0) {
+ target = &sl.audio; tid = t->id(); ci = sessionClipIndex(static_cast<int32_t>(sc));
+ }
+ }
if (target) break;
}
if (!target) break; // nothing left to build
@@ -321,10 +332,9 @@ int64_t Engine::warpBuildStep(int32_t maxFrames) {
// Finished this clip: install its cache via an atomic republish, then continue.
if (wb_.offset >= wb_.cache->frames) {
auto old = findTrackAuthoring(wb_.trackId);
- if (old && old->type() == TrackType::Audio
- && wb_.clipIndex < static_cast<int32_t>(old->clips.size())) {
+ if (old && audioClipRef(*old, wb_.clipIndex)) {
auto nt = cloneTrack(*old);
- nt->clips[wb_.clipIndex].warpCache = std::const_pointer_cast<const WarpCache>(wb_.cache);
+ audioClipRef(*nt, wb_.clipIndex)->warpCache = std::const_pointer_cast<const WarpCache>(wb_.cache);
republishWithTrackRaw(wb_.trackId, nt); // no undo entry — a cache isn't an edit
}
wb_ = {}; // clear the cursor (also frees the stretcher)
@@ -356,11 +366,15 @@ void Engine::reconfigureAllWarpStreams(double spb, double devSR) {
g->tracks.reserve(authoring_->tracks.size());
for (auto& t : authoring_->tracks) {
bool warped = false;
- if (t->type() == TrackType::Audio)
+ if (t->type() == TrackType::Audio) {
for (auto& c : t->clips) if (c.warpEnabled && c.sample) { warped = true; break; }
+ for (auto& sl : t->sessionSlots) if (sl.hasClip && sl.audio.warpEnabled && sl.audio.sample) { warped = true; break; }
+ }
if (!warped) { g->tracks.push_back(t); continue; }
auto nt = cloneTrack(*t);
for (auto& c : nt->clips) if (c.warpEnabled && c.sample) configureClipWarp(c, spb, devSR);
+ for (auto& sl : nt->sessionSlots) // session audio slots warp like clips (S-06)
+ if (sl.hasClip && sl.audio.warpEnabled && sl.audio.sample) configureClipWarp(sl.audio, spb, devSR);
g->tracks.push_back(std::move(nt));
any = true;
}
@@ -370,10 +384,11 @@ void Engine::reconfigureAllWarpStreams(double spb, double devSR) {
bool Engine::setClipPitch(int32_t trackId, int32_t clipIndex, float semitones) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto nt = cloneTrack(*old);
- nt->clips[clipIndex].pitchSemitones = semitones;
- configureClipWarp(nt->clips[clipIndex], transport_.samplesPerBeat(), transport_.sampleRate()); // pitch is baked into the warp
+ (*audioClipRef(*nt, clipIndex)).pitchSemitones = semitones;
+ configureClipWarp((*audioClipRef(*nt, clipIndex)), transport_.samplesPerBeat(), transport_.sampleRate()); // pitch is baked into the warp
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -384,9 +399,10 @@ bool Engine::setClipPitch(int32_t trackId, int32_t clipIndex, float semitones) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto nt = cloneTrack(*old);
- nt->clips[clipIndex].reversed = reversed;
+ (*audioClipRef(*nt, clipIndex)).reversed = reversed;
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -394,9 +410,9 @@ bool Engine::setClipReverse(int32_t trackId, int32_t clipIndex, bool reversed) {
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;
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(old->clips.size())) return false;
+ if (!audioClipRef(*old, clipIndex)) return false;
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
// On enable, auto-detect the source tempo and snap the clip's length to the
@@ -408,6 +424,7 @@ bool Engine::setClipWarp(int32_t trackId, int32_t clipIndex, bool enabled, int32
c.warpEnabled = enabled;
if (mode >= 0) c.warpMode = static_cast<WarpMode>(mode);
configureClipWarp(c, spb, devSR);
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -415,16 +432,17 @@ bool Engine::setClipWarp(int32_t trackId, int32_t clipIndex, bool enabled, int32
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;
+ if (!audioClipRef(*old, clipIndex)) return 0.0;
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, 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, knownBpm);
if (bpm <= 0.0) return 0.0; // detection failed: leave the clip unchanged
c.warpEnabled = true;
configureClipWarp(c, spb, devSR);
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return bpm;
}
@@ -432,11 +450,11 @@ double Engine::autoWarpClip(int32_t trackId, int32_t clipIndex, double knownBpm)
double Engine::beatWarpClip(int32_t trackId, int32_t clipIndex) {
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;
+ if (!audioClipRef(*old, clipIndex)) return 0.0;
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
if (!c.sample || spb <= 0.0 || devSR <= 0.0 || c.sample->sourceSampleRate <= 0.0) return 0.0;
// Establish the beat grid from the detected tempo (rounded musical length).
@@ -472,6 +490,7 @@ double Engine::beatWarpClip(int32_t trackId, int32_t clipIndex) {
c.warpMarkers = std::move(markers);
c.warpPlayStart = 0.0; c.warpPlayEnd = 0.0; // fresh warp → play the whole material
configureClipWarp(c, spb, devSR);
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return bpm;
}
@@ -479,10 +498,10 @@ double Engine::beatWarpClip(int32_t trackId, int32_t clipIndex) {
bool Engine::setClipWarpLength(int32_t trackId, int32_t clipIndex, double beats) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
if (beats < 0.25) beats = 0.25;
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
c.warpBeats = beats;
// The end marker owns the total length; keep interior markers within it.
if (!c.warpMarkers.empty()) {
@@ -491,6 +510,7 @@ bool Engine::setClipWarpLength(int32_t trackId, int32_t clipIndex, double beats)
}
clampWarpPlay(c); // keep the trim window valid for the new length
configureClipWarp(c, transport_.samplesPerBeat(), transport_.sampleRate());
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -499,10 +519,10 @@ bool Engine::setClipWarpMarkers(int32_t trackId, int32_t clipIndex,
const double* srcFrames, const double* beats, int32_t count) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
if (count < 2 || !srcFrames || !beats) return false;
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
c.warpMarkers.clear();
c.warpMarkers.reserve(count);
for (int32_t i = 0; i < count; ++i) c.warpMarkers.push_back({ srcFrames[i], beats[i] });
@@ -511,6 +531,7 @@ bool Engine::setClipWarpMarkers(int32_t trackId, int32_t clipIndex,
c.warpBeats = c.warpMarkers.back().beat;
clampWarpPlay(c); // preserve the trim window across marker edits (clamped to new length)
configureClipWarp(c, transport_.samplesPerBeat(), transport_.sampleRate());
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -521,17 +542,18 @@ bool Engine::setClipWarpMarkers(int32_t trackId, int32_t clipIndex,
bool Engine::setClipWarpTrim(int32_t trackId, int32_t clipIndex, double playStart, double playEnd) {
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;
- const AudioClip& oc = old->clips[clipIndex];
+ if (!audioClipRef(*old, clipIndex)) return false;
+ const AudioClip& oc = (*audioClipRef(*old, clipIndex));
if (!oc.warpEnabled || oc.warpBeats <= 0.0) return false;
constexpr double kMinBeat = 0.05;
double ps = std::clamp(playStart, 0.0, std::max(0.0, oc.warpBeats - kMinBeat));
double pe = std::clamp(playEnd, ps + kMinBeat, oc.warpBeats);
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
c.warpPlayStart = ps;
c.warpPlayEnd = pe;
configureClipWarp(c, transport_.samplesPerBeat(), transport_.sampleRate()); // window is baked into the cache
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -540,8 +562,8 @@ int32_t Engine::clipWarpMarkers(int32_t trackId, int32_t clipIndex,
double* outSrc, double* outBeat, int32_t maxCount) const {
auto t = findTrackAuthoring(trackId);
if (!t || t->type() != TrackType::Audio) return 0;
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;
- const auto& m = t->clips[clipIndex].warpMarkers;
+ if (!audioClipRef(*t, clipIndex)) return 0;
+ const auto& m = (*audioClipRef(*t, clipIndex)).warpMarkers;
const int32_t n = std::min<int32_t>(maxCount, static_cast<int32_t>(m.size()));
for (int32_t i = 0; i < n; ++i) { if (outSrc) outSrc[i] = m[i].srcFrame; if (outBeat) outBeat[i] = m[i].beat; }
return static_cast<int32_t>(m.size());
@@ -821,8 +843,8 @@ int32_t Engine::getClipPeaks(int32_t trackId, int32_t clipIndex,
float* outMinMax, int32_t maxPoints) const {
if (!outMinMax || maxPoints <= 0) return 0;
auto t = findTrackAuthoring(trackId);
- if (!t || clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;
- const AudioClip& clip = t->clips[clipIndex];
+ if (!t || !audioClipRef(*t, clipIndex)) return 0;
+ const AudioClip& clip = (*audioClipRef(*t, clipIndex));
if (!clip.sample) return 0;
const SampleBuffer& sb = *clip.sample;
@@ -864,8 +886,8 @@ int32_t Engine::getClipSourcePeaks(int32_t trackId, int32_t clipIndex,
float* outMinMax, int32_t maxPoints) const {
if (!outMinMax || maxPoints <= 0) return 0;
auto t = findTrackAuthoring(trackId);
- if (!t || clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;
- const AudioClip& clip = t->clips[clipIndex];
+ if (!t || !audioClipRef(*t, clipIndex)) return 0;
+ const AudioClip& clip = (*audioClipRef(*t, clipIndex));
if (!clip.sample) return 0;
const SampleBuffer& sb = *clip.sample;
const int64_t total = sb.frames;
@@ -887,8 +909,8 @@ int32_t Engine::getClipSourcePeaks(int32_t trackId, int32_t clipIndex,
int32_t Engine::getClipWarpFullPeaks(int32_t trackId, int32_t clipIndex,
float* outMinMax, int32_t maxPoints) const {
auto t = findTrackAuthoring(trackId);
- if (!t || clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;
- const AudioClip& clip = t->clips[clipIndex];
+ if (!t || !audioClipRef(*t, clipIndex)) return 0;
+ const AudioClip& clip = (*audioClipRef(*t, clipIndex));
if (!(clip.warpEnabled && clip.warpBeats > 0.0)) return 0;
return warpPeaksRange(clip, outMinMax, maxPoints, 0.0, clip.warpBeats);
}
@@ -928,8 +950,8 @@ bool Engine::clipInfo(int32_t trackId, int32_t clipIndex, NotaClipInfo* out) con
out->active = c.active ? 1 : 0;
return true;
}
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return false;
- const AudioClip& c = t->clips[clipIndex];
+ if (!audioClipRef(*t, clipIndex)) return false;
+ const AudioClip& c = (*audioClipRef(*t, clipIndex));
out->start_beat = c.startBeat;
out->kind = 0;
out->active = c.active ? 1 : 0;
@@ -1655,8 +1677,8 @@ bool Engine::trimClip(int32_t trackId, int32_t clipIndex, double newStartBeat, d
c.startBeat = newStartBeat;
c.lengthBeats = newLengthBeats;
} else {
- if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(nt->clips.size())) return false;
- AudioClip& c = nt->clips[clipIndex];
+ if (!audioClipRef(*nt, clipIndex)) return false;
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
const double delta = newStartBeat - c.startBeat;
@@ -1677,6 +1699,7 @@ bool Engine::trimClip(int32_t trackId, int32_t clipIndex, double newStartBeat, d
c.lengthFrames = static_cast<int64_t>(want);
}
}
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -1684,13 +1707,13 @@ bool Engine::trimClip(int32_t trackId, int32_t clipIndex, double newStartBeat, d
bool Engine::resizeAudioClip(int32_t trackId, int32_t clipIndex, double newStartBeat, double newLengthBeats) {
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;
+ if (!audioClipRef(*old, clipIndex)) return false;
if (newStartBeat < 0) newStartBeat = 0;
if (newLengthBeats < 0.25) newLengthBeats = 0.25;
const double spb = transport_.samplesPerBeat();
const double devSR = transport_.sampleRate();
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
if (c.warpEnabled) {
// Warped: TRIM the played window — do NOT stretch (stretch is the
@@ -1711,6 +1734,7 @@ bool Engine::resizeAudioClip(int32_t trackId, int32_t clipIndex, double newStart
c.warpPlayStart = ps;
c.warpPlayEnd = pe;
configureClipWarp(c, spb, devSR); // the played window is baked into the cache
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -1749,6 +1773,7 @@ bool Engine::resizeAudioClip(int32_t trackId, int32_t clipIndex, double newStart
{static_cast<double>(newOffset) + static_cast<double>(c.effectiveLength()), newLengthBeats} };
configureClipWarp(c, spb, devSR);
}
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -1761,8 +1786,8 @@ bool Engine::setClipSourceRegion(int32_t trackId, int32_t clipIndex,
double offsetFrames, int64_t lengthFrames) {
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;
- const AudioClip& oc = old->clips[clipIndex];
+ if (!audioClipRef(*old, clipIndex)) return false;
+ const AudioClip& oc = (*audioClipRef(*old, clipIndex));
if (!oc.sample || oc.warpEnabled) return false; // warped: region is marker-driven
const int64_t total = oc.sample->frames;
if (total <= 0) return false;
@@ -1775,9 +1800,10 @@ bool Engine::setClipSourceRegion(int32_t trackId, int32_t clipIndex,
const int64_t avail = total - static_cast<int64_t>(off);
len = std::clamp<int64_t>(len, std::min<int64_t>(kMinFrames, avail), avail);
auto nt = cloneTrack(*old);
- AudioClip& c = nt->clips[clipIndex];
+ AudioClip& c = (*audioClipRef(*nt, clipIndex));
c.sourceOffsetFrames = off;
c.lengthFrames = len;
+ syncSessionAudioSlot(*nt, clipIndex);
republishWithTrack(trackId, nt);
return true;
}
@@ -2291,6 +2317,8 @@ int32_t copyStr(const std::string& s, char* out, int32_t cap) {
} // namespace
bool Engine::setClipName(int32_t trackId, int32_t clipIndex, const std::string& name) {
+ // A Session slot (SessionClip index, MIDI or audio): its name is the slot's.
+ if (const int32_t scene = sessionSceneOfClip(clipIndex); scene >= 0) return setSessionClipName(trackId, scene, name);
auto old = findTrackAuthoring(trackId);
if (!old) return false;
auto nt = cloneTrack(*old);
@@ -2305,6 +2333,10 @@ bool Engine::setClipName(int32_t trackId, int32_t clipIndex, const std::string&
return true;
}
int32_t Engine::clipName(int32_t trackId, int32_t clipIndex, char* out, int32_t cap) const {
+ if (const int32_t scene = sessionSceneOfClip(clipIndex); scene >= 0) {
+ std::string n;
+ return sessionClipName(trackId, scene, n) ? copyStr(n, out, cap) : copyStr(std::string(), out, cap);
+ }
auto t = findTrackAuthoring(trackId);
if (!t) return 0;
if (t->type() == TrackType::Instrument) {
diff --git a/src/native/nota.engine/src/Track.h b/src/native/nota.engine/src/Track.h
index 87d75b76..c973d87b 100644
--- a/src/native/nota.engine/src/Track.h
+++ b/src/native/nota.engine/src/Track.h
@@ -317,4 +317,23 @@ private:
std::atomic<bool> frozen_{false}; // M7: play frozenBuf instead of the live chain
};
+// Audio clips are addressed by index: >= 0 is an arrangement clip, <= kSessionClipBase is
+// the audio take in a Session slot (scene = kSessionClipBase - index). The clip editing API
+// (warp, region, pitch, gain, envelopes, peaks) takes either, so a slot edits like a clip.
+inline constexpr int32_t kSessionClipBase = -2;
+inline int32_t sessionSceneOfClip(int32_t clipIndex) { return clipIndex <= kSessionClipBase ? kSessionClipBase - clipIndex : -1; }
+inline int32_t sessionClipIndex(int32_t scene) { return kSessionClipBase - scene; }
+
+inline const AudioClip* audioClipRef(const Track& t, int32_t clipIndex) {
+ if (t.type() != TrackType::Audio) return nullptr;
+ if (clipIndex >= 0) return clipIndex < static_cast<int32_t>(t.clips.size()) ? &t.clips[clipIndex] : nullptr;
+ const int32_t scene = sessionSceneOfClip(clipIndex);
+ if (scene < 0 || scene >= static_cast<int32_t>(t.sessionSlots.size())) return nullptr;
+ const SessionSlot& s = t.sessionSlots[scene];
+ return s.hasClip && s.audio.sample ? &s.audio : nullptr;
+}
+inline AudioClip* audioClipRef(Track& t, int32_t clipIndex) {
+ return const_cast<AudioClip*>(audioClipRef(static_cast<const Track&>(t), clipIndex));
+}
+
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 3093c9ed..cce59a01 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -7962,6 +7962,62 @@ engine.StopTransport();
Check(e2.TryGetSceneProps(2, out var lsp) && Math.Abs(lsp.Tempo - 140) < 1e-9, "scene props survive save/load");
}
+// -- Session audio slots are full clips (S-06): warp, region, tempo, arrangement transfer, save --
+{
+ using var e = new NotaEngine();
+ e.SetBpm(120); e.SetLaunchQuant(0.0);
+ var pb = new float[256 * 2];
+ void Run(double beats) { double from = e.PositionBeats; for (int g = 0; g < 20000 && e.PositionBeats - from < beats; g++) { e.RenderOffline(pb, 256); e.Poll(); } }
+ int at = e.AddAudioTrack();
+ Check(e.AddSessionAudioFile(at, 0, wav), "audio slot filled");
+ int sci = SessionClip.Index(0);
+ Check(e.TryGetAudioClipInfo(at, sci, out var sai) && sai.SampleId != 0, "an audio slot reads as an audio clip (session clip index)");
+ Check(e.TryGetClipInfo(at, sci, out var sci0) && Math.Abs(sci0.LengthBeats - e.SessionSlotLength(at, 0)) < 1e-6,
+ "slot clip length matches the slot loop");
+
+ e.SetClipWarp(at, sci, true, 3);
+ e.SetClipWarpLength(at, sci, 4.0);
+ Check(e.TryGetAudioClipInfo(at, sci, out var wai) && wai.WarpEnabled != 0, "warp turns on for a slot");
+ Check(Math.Abs(e.SessionSlotLength(at, 0) - 4.0) < 1e-6, $"slot loop follows the warped clip length ({e.SessionSlotLength(at, 0):F2})");
+ e.SetBpm(90);
+ Check(Math.Abs(e.SessionSlotLength(at, 0) - 4.0) < 1e-6, "warped slot keeps its length in beats across a tempo change");
+ e.LaunchSlot(at, 0);
+ e.Seek(0); Run(0.1);
+ e.RenderOffline(pb, 256);
+ Check(Rms(pb, 256) > 0.001f, $"warped audio slot plays (rms={Rms(pb, 256):F4})");
+ e.StopAllSession(); Run(0.1); e.StopTransport();
+ e.SetBpm(120);
+
+ e.SetClipGain(at, sci, 0.5f);
+ e.SetClipPitch(at, sci, 3);
+ Check(e.TryGetAudioClipInfo(at, sci, out var gai) && Math.Abs(gai.Gain - 0.5f) < 1e-6 && Math.Abs(gai.PitchSemitones - 3) < 1e-6,
+ "gain + pitch edit a slot like a clip");
+
+ // Arrangement -> slot keeps the clip's warp and region.
+ int ac = e.AddAudioClip(at, wav, 8.0);
+ e.SetClipWarp(at, ac, true, 0);
+ e.SetClipWarpLength(at, ac, 2.0);
+ Check(e.ArrangementAudioClipToSession(at, ac, 1), "arrangement audio clip copied to a slot");
+ Check(e.TryGetAudioClipInfo(at, SessionClip.Index(1), out var cai) && cai.WarpEnabled != 0 && Math.Abs(cai.StartBeat) < 1e-9
+ && Math.Abs(e.SessionSlotLength(at, 1) - 2.0) < 1e-6, "the slot keeps the clip's warp + length");
+ int back = e.SessionSlotToArrangement(at, 0, 16.0);
+ Check(back >= 0 && e.TryGetAudioClipInfo(at, back, out var bai) && bai.WarpEnabled != 0 && Math.Abs(bai.StartBeat - 16) < 1e-9,
+ "audio slot -> arrangement carries the warp");
+
+ // Save / load keeps the slot's warp, gain and pitch.
+ var w = new System.Collections.Generic.List<string>();
+ var doc = ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), w);
+ string bundle = Path.Combine(Path.GetTempPath(), "nota-slotclip-" + System.Guid.NewGuid().ToString("N") + ".nota");
+ ProjectService.Save(doc, bundle, e);
+ using var e2 = new NotaEngine();
+ ProjectService.Apply(ProjectService.Load(bundle), e2, bundle);
+ int at2 = -1;
+ for (int i = 0; i < e2.TrackCount; i++) if (e2.TryGetTrackInfo(i, out var ti) && ti.Type == 0) at2 = ti.Id;
+ Check(at2 > 0 && e2.TryGetAudioClipInfo(at2, SessionClip.Index(0), out var lai) && lai.WarpEnabled != 0
+ && Math.Abs(lai.Gain - 0.5f) < 1e-6 && Math.Abs(lai.PitchSemitones - 3) < 1e-6
+ && Math.Abs(e2.SessionSlotLength(at2, 0) - 4.0) < 1e-6, "audio slot warp / gain / pitch survive save/load");
+}
+
// -- Session: copy an arrangement AUDIO clip into a slot --
{
using var e = new NotaEngine();