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 Consolidate (Cmd+J) for MIDI and audio clips

Egor Khindikaynen2b754f0509fa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7d60de3..5d82ef1e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,18 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
tabs, a voice-activity strip, meters, a Voice setup flyout), 40 factory presets, and full
automation, MIDI learn, persistence and MCP support. It also builds as a standalone VST3
(`-DNOTA_BUILD_PENTAD_VST3=ON`) for testing in other hosts.
+- **Consolidate (⌘J).** Merges clips into one, as in Ableton: select a time range, or some
+ clips, and press ⌘J (Ctrl+J on Windows and Linux), use **Edit ▸ Consolidate**, or pick
+ **Consolidate** from the clip's right-click menu. Each track gets one clip covering the
+ whole range, and any clip parts outside it stay as they were. On MIDI tracks the notes are
+ merged: notes cut short by a clip's end stay cut, and the velocity envelope is baked into
+ the notes. On audio tracks the clips are rendered into a new sample exactly as they play,
+ with clip gain, transpose, warping, fades and clip envelopes baked in and silence in the
+ gaps. If any of the source clips was warped, the new clip is warped too, so it keeps
+ following tempo changes. Deactivated clips count as silence. The new clips are selected,
+ and one Undo reverts the whole operation. Also available over MCP as `consolidate_clips`.
+- **Shortcuts screen: the missing Edit-menu keys.** ⌘Z / ⌘⇧Z, ⌘D, ⌘E and ⌘L are now listed
+ alongside the new ⌘J.
- **Fine knob adjustment.** Hold ⌘ or ⇧ (Ctrl on Windows and Linux) while dragging a device
knob to change its value in steps ten times finer.
- **MCP: `set_instrument_param_by_id`** sets an instrument parameter by its stable id
diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.cs
index c366eff3..1e2bfae3 100644
--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs
+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs
@@ -836,17 +836,33 @@ public sealed partial class ArrangementView
flyout.ShowAt(this, showAtPointer: true);
}
- // Right-click on empty lane space: paste the clipboard clip here (type permitting).
+ // ⌘J / Ctrl+J, shown next to the context-menu Consolidate items.
+ private static readonly KeyGesture ConsolidateGesture =
+ new(Key.J, OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control);
+
+ // Right-click on empty lane space: paste the clipboard clip here (type permitting), and
+ // consolidate the time selection when the click lands inside it.
private void ShowLaneMenu(Point pos, double beat)
{
int ti = (int)(pos.Y / ArrangementView.RowHeight);
- if (ti < 0 || ti >= _o._tracks.Count || !_o.HasClipClipboard) return;
+ if (ti < 0 || ti >= _o._tracks.Count) return;
int trackId = _o._tracks[ti].Id;
+ bool inRange = _o.TimeSelectionCovers(trackId, beat);
+ if (!_o.HasClipClipboard && !inRange) return;
double at = _o.Snap(beat);
var flyout = new MenuFlyout();
- var paste = new MenuItem { Header = "Paste" };
- paste.Click += (_, _) => _o.PasteClipboardAt(trackId, at);
- flyout.Items.Add(paste);
+ if (_o.HasClipClipboard)
+ {
+ var paste = new MenuItem { Header = "Paste" };
+ paste.Click += (_, _) => _o.PasteClipboardAt(trackId, at);
+ flyout.Items.Add(paste);
+ }
+ if (inRange)
+ {
+ var consolidate = new MenuItem { Header = "Consolidate selection", InputGesture = ConsolidateGesture };
+ consolidate.Click += (_, _) => _o.ConsolidateSelection();
+ flyout.Items.Add(consolidate);
+ }
flyout.ShowAt(this, showAtPointer: true);
}
@@ -878,6 +894,19 @@ public sealed partial class ArrangementView
InputGesture = new KeyGesture(Key.D0),
};
deact.Click += (_, _) => { EnsureSelected(); _o.ToggleSelectedClipsActive(); };
+ // 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);
+ var consolidate = new MenuItem
+ {
+ Header = inRange || inGroup ? "Consolidate selection" : "Consolidate",
+ InputGesture = ConsolidateGesture,
+ };
+ consolidate.Click += (_, _) =>
+ {
+ if (!inRange) EnsureSelected();
+ _o.ConsolidateSelection();
+ };
var copy = new MenuItem { Header = inGroup ? "Copy selection" : "Copy" };
copy.Click += (_, _) => { EnsureSelected(); _o.CopySelectedClip(); };
var cut = new MenuItem { Header = inGroup ? "Cut selection" : "Cut" };
@@ -893,6 +922,7 @@ public sealed partial class ArrangementView
flyout.Items.Add(new Separator());
flyout.Items.Add(split);
flyout.Items.Add(dup);
+ 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 6bb8f7f9..948cc4e0 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -983,6 +983,16 @@ public sealed partial class ArrangementView : UserControl
return ids.ToArray();
}
+
+ /// <summary>True when the time selection spans this track's row at this beat (right-click
+ /// inside the range acts on the range).</summary>
+ internal bool TimeSelectionCovers(int trackId, double beat)
+ {
+ if (!HasTimeSelection) return false;
+ int r = RowOfTrack(trackId);
+ return r >= _timeSelRowLo && r <= _timeSelRowHi && beat >= _timeSelStart && beat <= _timeSelEnd;
+ }
+
/// <summary>Delete the covered clip content in the time selection (split at edges, no
/// ripple; req 5.3). Consumes the key whenever a range is active.</summary>
public bool DeleteTimeSelection()
@@ -1005,6 +1015,35 @@ public sealed partial class ArrangementView : UserControl
return true;
}
+ /// <summary>Cmd+J Consolidate: merge the time selection — or, without one, the span of the
+ /// clip selection on the selected clips' tracks — into one clip per track (MIDI notes merged,
+ /// audio rendered to a new sample). The new clips become the selection. False when there's
+ /// nothing to consolidate.</summary>
+ public bool ConsolidateSelection()
+ {
+ if (_engine is null) return false;
+ int[] ids;
+ double start, end;
+ if (HasTimeSelection)
+ {
+ ids = TimeSelectionTrackIds();
+ start = _timeSelStart; end = _timeSelEnd;
+ }
+ else
+ {
+ var sel = SelectionBlock();
+ start = double.MaxValue; end = double.MinValue;
+ foreach (var (track, clip) in sel)
+ if (FindClipVM(track, clip) is { } c)
+ { start = Math.Min(start, c.StartBeat); end = Math.Max(end, c.StartBeat + c.LengthBeats); }
+ ids = sel.Select(s => s.trackId).Distinct().ToArray();
+ }
+ if (ids.Length == 0 || end <= start || !_engine.ConsolidateRange(ids, start, end)) return false;
+ Refresh();
+ ReselectPlaced();
+ return true;
+ }
+
/// <summary>Cmd+L over a time selection: loop exactly that range. False when there's no range.</summary>
public bool LoopTimeSelection()
{
diff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.cs
index 49ef1732..dbd5c67c 100644
--- a/src/managed/Nota.App/MainWindow.Menu.cs
+++ b/src/managed/Nota.App/MainWindow.Menu.cs
@@ -95,6 +95,14 @@ public partial class MainWindow
else _vm.StatusText = "Select a range, or a clip the playhead crosses.";
}
+ private void OnMenuConsolidate(object? sender, EventArgs e)
+ {
+ if (_vm is null) return;
+ // A time-range selection wins; otherwise the span of the selected clips.
+ if (Timeline.ConsolidateSelection()) { _session?.Refresh(); _vm.StatusText = "Consolidated"; }
+ else _vm.StatusText = "Select a range or clips to consolidate.";
+ }
+
private void OnToggleLockEnvelopes(object? sender, EventArgs e)
{
if (_vm is null) return;
diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axaml
index 30c3c5d8..89452385 100644
--- a/src/managed/Nota.App/MainWindow.axaml
+++ b/src/managed/Nota.App/MainWindow.axaml
@@ -41,6 +41,7 @@
<NativeMenuItemSeparator/>
<NativeMenuItem Header="Duplicate clip" Click="OnMenuDuplicate" Gesture="Cmd+D"/>
<NativeMenuItem Header="Split at playhead" Click="OnMenuSplit" Gesture="Cmd+E"/>
+ <NativeMenuItem Header="Consolidate" Click="OnMenuConsolidate" Gesture="Cmd+J"/>
<NativeMenuItemSeparator/>
<NativeMenuItem Header="Lock Envelopes" Click="OnToggleLockEnvelopes" ToggleType="CheckBox"/>
<NativeMenuItemSeparator/>
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 81ecaa25..33e027fa 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -538,15 +538,20 @@ public sealed class PreferencesWindow : NotaWindow
("Return", "Stop (again → back to the start)"),
("R", "Record"),
("M", "Metronome"),
+ ("⌘L", "Loop on / off · loop the time selection"),
}),
("ARRANGEMENT & EDITING", new[]
{
+ ("⌘Z ⌘⇧Z", "Undo / redo"),
("⌘A", "Toggle automation mode"),
("⌘M", "Toggle the Mixer view"),
("Tab", "Switch Devices / Clip in the detail panel"),
("Esc", "Cancel the current gesture / clear the selection"),
("⌘G ⌘⇧G", "Group / ungroup selected tracks"),
("⌘C ⌘X ⌘V", "Copy / cut / paste clip (or automation range)"),
+ ("⌘D", "Duplicate the selected clip(s) / range"),
+ ("⌘E", "Split at the playhead · at the range edges"),
+ ("⌘J", "Consolidate the selection into one clip per track"),
("0", "Deactivate / activate the selected clip(s)"),
("Delete", "Delete the selected clip / range"),
}),
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 1aa5142e..86764179 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -162,6 +162,11 @@ public interface IAudioEngine : IDisposable
/// <summary>Splits the given tracks' clips at both [start] and [end] (keeping all content) so
/// the covered slice becomes its own clip(s). One undo step, no ripple. False = nothing changed.</summary>
bool SplitClipsInRange(int[] trackIds, double start, double end);
+ /// <summary>Consolidate: replaces each given track's content in [start,end) with ONE clip
+ /// spanning the range — MIDI notes merged, audio clips rendered (gain/pitch/warp/fades/clip
+ /// envelopes baked) into a new sample. Parts of clips outside the range survive. One undo
+ /// step; <see cref="LastPlacedClips"/> then reports the new clips. False = nothing changed.</summary>
+ bool ConsolidateRange(int[] trackIds, double start, double end);
/// <summary>Locks track envelopes so clip moves stop carrying automation (req 8.3.3).</summary>
void SetAutomationLock(bool locked);
bool AutomationLock { get; }
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 756fd31e..85dafeee 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -189,6 +189,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_clips_split_range")]
internal static partial NotaResult ClipsSplitRange(IntPtr engine, [In] int[] trackIds, int n, double start, double end);
+ [LibraryImport(Lib, EntryPoint = "nota_clips_consolidate_range")]
+ internal static partial NotaResult ClipsConsolidateRange(IntPtr engine, [In] int[] trackIds, int n, double start, double end);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_set_automation_lock")]
internal static partial void SetAutomationLock(IntPtr engine, int locked);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index b3c765bb..4c5e5c25 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -225,6 +225,12 @@ public sealed partial class NotaEngine
public bool SplitClipsInRange(int[] trackIds, double start, double end)
{ ThrowIfDisposed(); return NativeMethods.ClipsSplitRange(_handle, trackIds, trackIds.Length, start, end) == NativeMethods.NotaResult.Ok; }
+ /// <summary>Consolidate: replaces each given track's content in [start,end) with one clip
+ /// spanning the range (MIDI merged, audio rendered to a new sample). One undo step; the new
+ /// clips are reported by <see cref="LastPlacedClips"/>. False when no track had content.</summary>
+ public bool ConsolidateRange(int[] trackIds, double start, double end)
+ { ThrowIfDisposed(); return NativeMethods.ClipsConsolidateRange(_handle, trackIds, trackIds.Length, start, end) == NativeMethods.NotaResult.Ok; }
+
/// <summary>Freezes track envelopes so clip moves no longer carry automation (req 8.3.3).</summary>
public void SetAutomationLock(bool locked)
{ ThrowIfDisposed(); NativeMethods.SetAutomationLock(_handle, locked ? 1 : 0); }
diff --git a/src/managed/Nota.Mcp/Tools/MidiTools.cs b/src/managed/Nota.Mcp/Tools/MidiTools.cs
index 0c571128..03c2ca94 100644
--- a/src/managed/Nota.Mcp/Tools/MidiTools.cs
+++ b/src/managed/Nota.Mcp/Tools/MidiTools.cs
@@ -54,4 +54,16 @@ public sealed class MidiTools(IAudioEngine engine, IEngineDispatch dispatch, IAr
[McpServerTool(Name = "trim_clip"), Description("Resize a clip to a new start + length in beats.")]
public Task TrimClip(int trackId, int clipIndex, double newStartBeat, double newLengthBeats)
=> Mutate(() => E.TrimClip(trackId, clipIndex, Math.Max(0, newStartBeat), Math.Max(0.25, newLengthBeats)));
+
+ public sealed record ClipRef(int TrackId, int ClipIndex);
+
+ [McpServerTool(Name = "consolidate_clips"), Description(
+ "Consolidate (like Ableton's Cmd+J): on each given MIDI or audio track, replace everything in " +
+ "[startBeat, endBeat) with ONE clip spanning the range. MIDI notes are merged; audio clips are " +
+ "rendered (gain, pitch, warp, fades, clip envelopes baked in) into a new sample. Parts of clips " +
+ "outside the range are kept. Returns the new clips (empty when no track had content there).")]
+ public Task<ClipRef[]> ConsolidateClips(int[] trackIds, double startBeat, double endBeat) => Mutate(() =>
+ E.ConsolidateRange(trackIds, Math.Max(0, startBeat), endBeat)
+ ? Array.ConvertAll(E.LastPlacedClips(), p => new ClipRef(p.trackId, p.clipIndex))
+ : Array.Empty<ClipRef>());
}
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 9b80a7f4..ea448fa6 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -657,6 +657,11 @@ NOTA_API double nota_clips_duplicate_range(NotaEngine* engine, const int32_t
/* split_range cuts each listed track's clips at both boundaries, keeping all content, so the
* covered slice becomes its own clip(s). One undo step, no ripple. */
NOTA_API NotaResult nota_clips_split_range(NotaEngine* engine, const int32_t* track_ids, int32_t n, double start, double end);
+/* consolidate_range (Consolidate) replaces each listed track's content in [start,end) with one
+ * clip spanning the range: MIDI merges the covered notes, audio renders the covered clips
+ * (gain, pitch, warp, fades, clip envelopes baked) into a new sample. Parts of clips outside
+ * the range survive. One undo step; nota_clips_last_placed then reports the new clips. */
+NOTA_API NotaResult nota_clips_consolidate_range(NotaEngine* engine, const int32_t* track_ids, int32_t n, double start, double end);
/* Automation-follows-clips (req 8.3). Lock freezes envelopes so clip moves don't carry them.
* last_move_kept_device_automation is 1 when the most recent cross-track move left device/plugin
* automation on the source (UI hint); it resets at the start of each move. */
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 26bc01ef..94b9d587 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -381,6 +381,14 @@ public:
// splitClipsAtRange cuts every listed track's clips at both `start` and `end` (keeping
// all content) so the covered slice becomes its own clip(s). One undo step; no ripple.
bool splitClipsAtRange(const std::vector<int32_t>& trackIds, double start, double end);
+ // consolidateRange (Consolidate, ⌘J) replaces every listed track's content in
+ // [start,end) with ONE clip spanning the range; the parts of clips outside it survive.
+ // MIDI merges the covered notes (tails cut by a clip end stay cut, velocity envelopes
+ // baked into the notes, volume envelopes stitched into one). Audio renders what the
+ // covered clips play — gain, pitch, warp, edge fades, clip envelopes — into a new
+ // sample (warped when any source was, so it keeps following tempo). Deactivated
+ // clips contribute silence. One undo step; lastPlaced() reports the new clips.
+ bool consolidateRange(const std::vector<int32_t>& trackIds, double start, double end);
// Automation-follows-clips (req 8.3). When unlocked (default), moving a clip carries the
// track automation in its span with it: same-track moves take everything; cross-track moves
@@ -809,8 +817,10 @@ private:
int32_t frames, double beatStart, double spb, bool playing);
void applyMidiCcRouting(Track& t);
void renderSessionAudioSlotRaw(Track& t, float* dst, int32_t frames, double spb); // M5-4
- void renderAudioClipsRaw(Track& t, float* dst, int32_t frames,
+ void renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst, int32_t frames,
double blockStart, double spb);
+ // Consolidate (audio): bounce the clips covering [start,end) into one new clip.
+ AudioClip consolidateAudioClips(const std::vector<AudioClip>& clips, double start, double end);
// Freeze playback (M7): fill dst with the track's frozen buffer for this segment,
// sampling by beat (frame = beat·frozenSpb) with linear interpolation.
void fillFrozen(Track& t, float* dst, int32_t frames, double blockStart, double spb);
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index a6352bc8..8e31762c 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -551,12 +551,13 @@ void Engine::renderSessionAudioSlotRaw(Track& t, float* dst, int32_t frames, dou
sp.localBeats += frames / spb;
}
-// Renders a track's dry audio clips (pre-fader) into `dst` (zeroed here).
-void Engine::renderAudioClipsRaw(Track& t, float* dst, int32_t frames,
+// Renders a track's dry audio clips (pre-fader) into `dst` (zeroed here). Also drives
+// Consolidate's offline bounce (consolidateRange) over a detached clip list.
+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 : t.clips) {
+ 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
@@ -916,7 +917,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
else if (t.type() == TrackType::Instrument)
renderInstrumentRaw(g, t, scratch_.data(), frames, blockStart, spb, playing);
else if (playing && arrangementActive)
- renderAudioClipsRaw(t, scratch_.data(), frames, blockStart, spb);
+ renderAudioClipsRaw(t.clips, scratch_.data(), frames, blockStart, spb);
else
{ t.setMeter(0, 0, 0, 0); continue; } // stopped / session-only audio track: nothing to do
}
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index 64177c8c..4005dd74 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -1195,6 +1195,159 @@ double Engine::duplicateRange(const std::vector<int32_t>& trackIds, double start
return len;
}
+// --- consolidate (⌘J): one clip per track over a range ------------------------
+namespace {
+// One source clip's audible slice [a,b) of a consolidate range (timeline beats), with the
+// clip's start and its envelope (null/empty = unity) for stitching.
+struct EnvSpan { double a, b, clipStart; const AutomationLane* lane; };
+
+// Stitch per-clip envelopes into one lane in consolidated-clip-local beats: each span keeps
+// its clip's curve, clips without one and the gaps between clips hold unity, and a boundary
+// between two clips is a step (two points on the same beat). Empty when no span carries an
+// envelope, so the result keeps the no-envelope fast path.
+AutomationLane stitchEnvelopes(const std::vector<EnvSpan>& spans, double start, double end) {
+ AutomationLane out;
+ if (std::none_of(spans.begin(), spans.end(), [](const EnvSpan& s) { return s.lane && !s.lane->points.empty(); }))
+ return out;
+ auto add = [&](double beat, float v, float curve = 0.0f) { out.points.push_back({beat - start, v, curve}); };
+ double cursor = start;
+ for (const auto& s : spans) {
+ const double a = std::max(s.a, cursor), b = s.b;
+ if (b <= a) continue;
+ if (a > cursor) { add(cursor, 1.0f); add(a, 1.0f); }
+ const bool has = s.lane && !s.lane->points.empty();
+ add(a, has ? s.lane->valueAt(a - s.clipStart) : 1.0f);
+ if (has)
+ for (const auto& p : s.lane->points) {
+ const double x = s.clipStart + p.beat;
+ if (x > a && x < b) add(x, p.value, p.curve);
+ }
+ add(b, has ? s.lane->valueAt(b - s.clipStart) : 1.0f);
+ cursor = b;
+ }
+ if (cursor < end) { add(cursor, 1.0f); add(end, 1.0f); }
+ return out;
+}
+
+// The covered MIDI clips merged into one clip over [s,e): exactly the notes that play —
+// a note must start inside its clip's window and the range, and its tail stops at its clip's
+// end (or the range end), as playback cuts it. Velocity envelopes are baked into the notes.
+MidiClip consolidateMidiClips(const std::vector<MidiClip>& clips, double s, double e) {
+ constexpr double eps = 1e-6;
+ std::vector<const MidiClip*> src;
+ for (const auto& c : clips)
+ if (c.startBeat + c.lengthBeats > s + eps && c.startBeat < e - eps) src.push_back(&c);
+ std::sort(src.begin(), src.end(), [](const MidiClip* x, const MidiClip* y) { return x->startBeat < y->startBeat; });
+
+ MidiClip out;
+ out.startBeat = s;
+ out.lengthBeats = e - s;
+ for (const MidiClip* c : src) if (!c->name.empty()) { out.name = c->name; break; }
+ std::vector<EnvSpan> spans;
+ for (const MidiClip* c : src) {
+ if (!c->active) continue; // a deactivated clip is silent
+ const double cs = c->startBeat, ce = std::min(cs + c->lengthBeats, e);
+ spans.push_back({std::max(cs, s), ce, cs, &c->volumeEnvelope});
+ const bool hasVel = !c->velocityEnvelope.points.empty();
+ for (const Note& n : c->notes) {
+ if (n.startBeat < 0.0 || n.startBeat >= c->lengthBeats) continue;
+ const double on = cs + n.startBeat;
+ if (on < s - eps || on >= e - eps) continue;
+ Note m = n;
+ m.startBeat = std::max(0.0, on - s);
+ m.lengthBeats = std::min(on + n.lengthBeats, ce) - on;
+ if (m.lengthBeats <= 0.0) continue;
+ if (hasVel) m.velocity = n.velocity * std::clamp(c->velocityEnvelope.valueAt(n.startBeat), 0.0f, 1.0f);
+ out.notes.push_back(m);
+ }
+ }
+ out.volumeEnvelope = stitchEnvelopes(spans, s, e);
+ return out;
+}
+} // namespace
+
+// Bounce what the covered clips play over [s,e) — the same renderer the audio thread uses,
+// so gain, varispeed, warp, edge fades and clip envelopes are all baked — into a new
+// device-rate stereo sample, placed as one clip at `s`. If any audible source was warped the
+// result is warped too (neutral markers, that clip's mode) so it keeps following tempo; an
+// all-unwarped range stays an unwarped, sample-exact copy.
+AudioClip Engine::consolidateAudioClips(const std::vector<AudioClip>& clips, double s, double e) {
+ constexpr double eps = 1e-6;
+ const double spb = transport_.samplesPerBeat(), devSR = transport_.sampleRate();
+ std::vector<AudioClip> src;
+ for (const auto& c : clips) {
+ const double cs = c.startBeat, ce = cs + audioDisplayLenBeats(c, spb, devSR);
+ if (ce <= s + eps || cs >= e - eps) continue;
+ src.push_back(c);
+ // A deferred (project-load) warp cache isn't built yet; the renderer would skip it.
+ if (src.back().warpEnabled && !src.back().warpCache) buildWarpCache(src.back(), spb, devSR);
+ }
+ std::sort(src.begin(), src.end(), [](const AudioClip& x, const AudioClip& y) { return x.startBeat < y.startBeat; });
+
+ const int64_t frames = std::max<int64_t>(1, std::llround((e - s) * spb));
+ auto sb = std::make_shared<SampleBuffer>();
+ sb->channels = 2;
+ sb->frames = frames;
+ sb->sourceSampleRate = devSR;
+ sb->samples.assign(static_cast<size_t>(frames) * 2, 0.0f);
+ constexpr int64_t kBlock = 4096;
+ for (int64_t off = 0; off < frames; off += kBlock) {
+ const int32_t n = static_cast<int32_t>(std::min(kBlock, frames - off));
+ renderAudioClipsRaw(src, sb->samples.data() + off * 2, n, s * spb + static_cast<double>(off), spb);
+ }
+
+ AudioClip out;
+ out.sample = std::move(sb);
+ out.startBeat = s;
+ out.lengthFrames = frames;
+ for (const auto& c : src) if (!c.name.empty()) { out.name = c.name; break; }
+ const auto warped = std::find_if(src.begin(), src.end(), [](const AudioClip& c) { return c.active && c.warpEnabled; });
+ if (warped != src.end()) {
+ out.warpEnabled = true;
+ out.warpMode = warped->warpMode;
+ seedNeutralWarp(out, spb, devSR);
+ configureClipWarp(out, spb, devSR);
+ }
+ return out;
+}
+
+bool Engine::consolidateRange(const std::vector<int32_t>& trackIds, double start, double end) {
+ start = std::max(0.0, start);
+ if (end <= start + 1e-9 || trackIds.empty()) return false;
+ const double spb = transport_.samplesPerBeat(), devSR = transport_.sampleRate();
+ if (spb <= 0.0 || devSR <= 0.0) return false;
+ auto listed = [&](int32_t id){ return std::find(trackIds.begin(), trackIds.end(), id) != trackIds.end(); };
+ std::vector<std::pair<int32_t,int32_t>> placed;
+ auto g = std::make_shared<Graph>();
+ g->sceneCount = authoring_->sceneCount;
+ g->masterVolume = authoring_->masterVolume;
+ g->masterTrack = authoring_->masterTrack;
+ g->tracks.reserve(authoring_->tracks.size());
+ for (auto& t : authoring_->tracks) {
+ const bool clipTrack = t->type() == TrackType::Instrument || t->type() == TrackType::Audio;
+ if (!clipTrack || !listed(t->id()) || !rangeTouchesTrack(*t, start, end, spb, devSR))
+ { g->tracks.push_back(t); continue; }
+ auto nt = cloneTrack(*t);
+ if (nt->type() == TrackType::Instrument) {
+ MidiClip merged = consolidateMidiClips(nt->midiClips, start, end);
+ midiOverwriteRange(nt->midiClips, start, end);
+ nt->midiClips.push_back(std::move(merged));
+ placed.emplace_back(nt->id(), static_cast<int32_t>(nt->midiClips.size()) - 1);
+ } else {
+ AudioClip bounced = consolidateAudioClips(nt->clips, start, end);
+ audioOverwriteRange(nt->clips, start, end, spb, devSR);
+ nt->clips.push_back(std::move(bounced));
+ placed.emplace_back(nt->id(), static_cast<int32_t>(nt->clips.size()) - 1);
+ }
+ g->tracks.push_back(nt);
+ }
+ if (placed.empty()) return false;
+ pushUndo();
+ publishRaw(std::move(g));
+ lastPlaced_ = std::move(placed);
+ return true;
+}
+
bool Engine::trimClip(int32_t trackId, int32_t clipIndex, double newStartBeat, double newLengthBeats) {
auto old = findTrackAuthoring(trackId);
if (!old) return false;
diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cpp
index 05ce63fb..0227a97b 100644
--- a/src/native/nota.engine/src/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/nota_engine_track.cpp
@@ -360,6 +360,11 @@ NotaResult nota_clips_split_range(NotaEngine* e, const int32_t* track_ids, int32
std::vector<int32_t> ids; if (track_ids && n > 0) ids.assign(track_ids, track_ids + n);
return ENG(e)->splitClipsAtRange(ids, start, end) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
}
+NotaResult nota_clips_consolidate_range(NotaEngine* e, const int32_t* track_ids, int32_t n, double start, double end) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ std::vector<int32_t> ids; if (track_ids && n > 0) ids.assign(track_ids, track_ids + n);
+ return ENG(e)->consolidateRange(ids, start, end) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
void nota_engine_set_automation_lock(NotaEngine* e, int32_t locked) { if (e) ENG(e)->setAutomationLock(locked != 0); }
int32_t nota_engine_automation_lock(const NotaEngine* e) { return (e && CENG(e)->automationLock()) ? 1 : 0; }
int32_t nota_engine_last_move_kept_device_automation(const NotaEngine* e) {
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index aa77d4a4..eed561e6 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -4998,6 +4998,141 @@ Console.WriteLine("-- block clip ops (multi-selection) --");
}
}
+// ============ consolidate (⌘J): one clip per track over a range ===========
+Console.WriteLine("-- consolidate --");
+{
+ const double eps = 1e-6;
+ static Nota.Application.NotaNote N(int p, double s, double l, float v = 0.8f) => new(p, s, l, v);
+
+ // MIDI: two clips merge into one [0,8). A tail cut by its clip's end stays cut, a note
+ // hidden outside its clip window is dropped, and the first clip's name carries over.
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int t = e.AddInstrumentTrack();
+ int c0 = e.AddMidiClip(t, 0.0, 4.0);
+ int c1 = e.AddMidiClip(t, 6.0, 2.0);
+ e.SetClipNotes(t, c0, new[] { N(60, 0, 1), N(62, 3, 2), N(65, 5, 1) }); // 62's tail cut at 4; 65 hidden
+ e.SetClipNotes(t, c1, new[] { N(64, 0.5, 1) });
+ e.SetClipName(t, c0, "Verse");
+ Check(e.ConsolidateRange(new[] { t }, 0.0, 8.0), "consolidate MIDI returns true");
+ Check(e.TryGetTrackInfo(FindTrackIndex(e, t), out var ti) && ti.ClipCount == 1, "MIDI: two clips became one");
+ var placed = e.LastPlacedClips();
+ Check(placed.Length == 1 && placed[0].trackId == t, "MIDI: last-placed reports the new clip");
+ int nc = placed[0].clipIndex;
+ Check(e.TryGetClipInfo(t, nc, out var ci) && Math.Abs(ci.StartBeat) < eps && Math.Abs(ci.LengthBeats - 8.0) < eps, "MIDI: new clip spans [0,8)");
+ var got = e.GetClipNotes(t, nc).OrderBy(n => n.StartBeat).ToArray();
+ Check(got.Length == 3, $"MIDI: 3 audible notes kept (got {got.Length})");
+ Check(got.Length == 3 && got[1].Pitch == 62 && Math.Abs(got[1].LengthBeats - 1.0) < eps, "MIDI: tail cut by the clip end stays cut");
+ Check(got.Length == 3 && got[2].Pitch == 64 && Math.Abs(got[2].StartBeat - 6.5) < eps, "MIDI: second clip's note re-based to 6.5");
+ Check(e.GetClipName(t, nc) == "Verse", "MIDI: first clip's name carried over");
+ Check(e.Undo() && e.TryGetTrackInfo(FindTrackIndex(e, t), out var tu) && tu.ClipCount == 2, "MIDI: undo restores both clips");
+ }
+
+ // MIDI time range inside one clip: remainders survive on both sides; a note crossing the
+ // range end is cut there; got outside the range stay in the remainders.
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(t, 0.0, 8.0);
+ e.SetClipNotes(t, c, new[] { N(60, 1, 1), N(62, 3, 1), N(64, 5, 2), N(67, 7, 1) });
+ Check(e.ConsolidateRange(new[] { t }, 2.0, 6.0), "consolidate MIDI range");
+ Check(e.TryGetTrackInfo(FindTrackIndex(e, t), out var ti) && ti.ClipCount == 3, "MIDI range: left + consolidated + right");
+ int nc = e.LastPlacedClips()[0].clipIndex;
+ var got = e.GetClipNotes(t, nc).OrderBy(n => n.StartBeat).ToArray();
+ Check(got.Length == 2 && Math.Abs(got[0].StartBeat - 1.0) < eps && Math.Abs(got[1].StartBeat - 3.0) < eps,
+ "MIDI range: notes at 3 and 5 re-based to 1 and 3");
+ Check(got.Length == 2 && Math.Abs(got[1].LengthBeats - 1.0) < eps, "MIDI range: note crossing the range end cut there");
+ }
+
+ // MIDI envelopes: velocity baked into the got; volume envelopes stitched (unity where a
+ // clip had none); a deactivated clip contributes nothing.
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ int a = e.AddMidiClip(t, 0.0, 4.0);
+ int b = e.AddMidiClip(t, 4.0, 4.0);
+ int d = e.AddMidiClip(t, 8.0, 4.0);
+ e.SetClipNotes(t, a, new[] { N(60, 0, 1, 0.8f) });
+ e.SetClipNotes(t, b, new[] { N(62, 0, 1, 0.8f) });
+ e.SetClipNotes(t, d, new[] { N(64, 0, 1, 0.8f) });
+ e.SetMidiClipEnvelope(t, a, Nota.Application.MidiClipEnvelope.Velocity, new[] { new Nota.Application.AutomationPoint(0, 0.5f), new Nota.Application.AutomationPoint(4, 0.5f) });
+ e.SetMidiClipEnvelope(t, a, Nota.Application.MidiClipEnvelope.Volume, new[] { new Nota.Application.AutomationPoint(0, 0.25f), new Nota.Application.AutomationPoint(4, 0.25f) });
+ e.SetClipActive(t, d, false);
+ Check(e.ConsolidateRange(new[] { t }, 0.0, 12.0), "consolidate MIDI with envelopes");
+ int nc = e.LastPlacedClips()[0].clipIndex;
+ var got = e.GetClipNotes(t, nc).OrderBy(n => n.StartBeat).ToArray();
+ Check(got.Length == 2, $"MIDI env: deactivated clip's note dropped ({got.Length} notes)");
+ Check(got.Length == 2 && Math.Abs(got[0].Velocity - 0.4f) < 1e-4 && Math.Abs(got[1].Velocity - 0.8f) < 1e-4,
+ "MIDI env: velocity envelope baked (0.8 x 0.5 = 0.4), other clip untouched");
+ Check(e.GetMidiClipEnvelope(t, nc, Nota.Application.MidiClipEnvelope.Velocity).Length == 0, "MIDI env: no velocity envelope left");
+ var vol = e.GetMidiClipEnvelope(t, nc, Nota.Application.MidiClipEnvelope.Volume);
+ static float At(Nota.Application.AutomationPoint[] p, double beat)
+ {
+ if (beat <= p[0].Beat) return p[0].Value;
+ for (int i = 1; i < p.Length; i++)
+ if (beat <= p[i].Beat)
+ return p[i].Beat - p[i - 1].Beat <= 0 ? p[i].Value
+ : (float)(p[i - 1].Value + (p[i].Value - p[i - 1].Value) * (beat - p[i - 1].Beat) / (p[i].Beat - p[i - 1].Beat));
+ return p[^1].Value;
+ }
+ Check(vol.Length > 0 && Math.Abs(At(vol, 2.0) - 0.25f) < 1e-4 && Math.Abs(At(vol, 6.0) - 1.0f) < 1e-4,
+ "MIDI env: volume envelope stitched (0.25 in the first clip, unity after)");
+ }
+
+ // Audio: the bounce plays exactly what the source did (gain + varispeed baked), as one
+ // unwarped, unity-gain clip spanning the range.
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120); e.SetTimeSignature(4, 4);
+ int t = e.AddAudioTrack();
+ int c = e.AddAudioClip(t, wav, 0.0); // 1 s sine = 2 beats at 120
+ e.SetClipGain(t, c, 0.5f);
+ e.SetClipPitch(t, c, 3.0f);
+ const int fr = 44100;
+ var before = new float[fr * 2];
+ var after = new float[fr * 2];
+ e.Seek(0); e.Play(); e.RenderOffline(before, fr); e.StopTransport();
+ Check(e.ConsolidateRange(new[] { t }, 0.0, 4.0), "consolidate audio returns true");
+ Check(e.TryGetTrackInfo(FindTrackIndex(e, t), out var ti) && ti.ClipCount == 1, "audio: one clip after consolidate");
+ int nc = e.LastPlacedClips()[0].clipIndex;
+ Check(e.TryGetClipInfo(t, nc, out var ci) && Math.Abs(ci.StartBeat) < eps && Math.Abs(ci.LengthBeats - 4.0) < 1e-3,
+ $"audio: new clip spans [0,4) (len {ci.LengthBeats:F4})");
+ Check(e.TryGetAudioClipInfo(t, nc, out var ai) && ai.WarpEnabled == 0 && Math.Abs(ai.Gain - 1f) < 1e-6 && Math.Abs(ai.PitchSemitones) < 1e-6,
+ "audio: result is unwarped, unity gain, no transpose");
+ e.Seek(0); e.Play(); e.RenderOffline(after, fr); e.StopTransport();
+ double maxDiff = 0;
+ for (int i = 1024 * 2; i < fr * 2; i++) maxDiff = Math.Max(maxDiff, Math.Abs(before[i] - after[i]));
+ Check(Rms(before, fr) > 0.01f && maxDiff < 1e-3, $"audio: consolidated render matches the original (max diff {maxDiff:E2})");
+ Check(e.Undo() && e.TryGetAudioClipInfo(t, 0, out var ui) && Math.Abs(ui.Gain - 0.5f) < 1e-6, "audio: undo restores the source clip");
+ }
+
+ // Audio time range inside a clip: remainders survive; a warped source yields a warped
+ // (tempo-following) result.
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int t = e.AddAudioTrack();
+ int c = e.AddAudioClip(t, wav, 0.0);
+ e.SetClipWarp(t, c, true, 3);
+ Check(e.ConsolidateRange(new[] { t }, 0.5, 1.5), "consolidate warped audio range");
+ Check(e.TryGetTrackInfo(FindTrackIndex(e, t), out var ti) && ti.ClipCount == 3, "audio range: left + consolidated + right");
+ int nc = e.LastPlacedClips()[0].clipIndex;
+ Check(e.TryGetAudioClipInfo(t, nc, out var ai) && ai.WarpEnabled == 1 && ai.WarpMode == 3, "audio range: warped source -> warped result (same mode)");
+ Check(e.TryGetClipInfo(t, nc, out var ci) && Math.Abs(ci.StartBeat - 0.5) < eps && Math.Abs(ci.LengthBeats - 1.0) < 1e-3,
+ "audio range: new clip spans [0.5,1.5)");
+ }
+
+ // Nothing to consolidate (empty range / no listed track with content) is a no-op.
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.AddMidiClip(t, 0.0, 2.0);
+ Check(!e.ConsolidateRange(new[] { t }, 4.0, 8.0), "consolidate over empty space is a no-op");
+ Check(e.TryGetTrackInfo(FindTrackIndex(e, t), out var ti) && ti.ClipCount == 1, "no-op consolidate leaves the clip alone");
+ }
+}
+
// ============ track/clip names + colour + track clipboard ==================
Console.WriteLine("-- names, colour, track clipboard --");
{
@@ -5546,6 +5681,9 @@ Console.WriteLine("-- MCP tools --");
}).Wait();
var mcpNotes = mcpMidi.GetClipNotes(mcpT, mcpClip).Result;
Check(mcpNotes.Length == 3 && mcpNotes[0].Pitch == 60 && Math.Abs(mcpNotes[2].Length - 2) < 1e-3, $"MCP set/get_clip_notes round-trip ({mcpNotes.Length})");
+ var mcpCons = mcpMidi.ConsolidateClips(new[] { mcpT }, 0, 4).Result;
+ Check(mcpCons.Length == 1 && mcpCons[0].TrackId == mcpT && mcpMidi.GetClipNotes(mcpT, mcpCons[0].ClipIndex).Result.Length == 3,
+ "MCP consolidate_clips keeps the notes in one clip");
int mcpDev = mcpDevices.AddDevice(mcpT, 2).Result; // 2 = Reverb
Check(mcpDev >= 0 && mcpEng.TrackDeviceBuiltinKind(mcpT, mcpDev) == 2, "MCP add_device (Reverb)");