Cycle recording: MIDI separate-takes mode, and append to existing folders

Completes the cycle-recording spec. Three related pieces:

MIDI separate takes (Preferences > Audio > "Cycle MIDI recording"):
- Each pass becomes its own MIDI clip, folded into a take folder — the same
  shape audio always gets — instead of merging into one clip. Merge stays
  the default.
- Notes are bucketed by the pass they were played in. The pass counter bumps
  BETWEEN close_active_notes and the re-note_on at a wrap, so a key held
  across the boundary has its sounding half filed under the pass that's
  ending and its re-opened half under the pass that's beginning. Put the bump
  on either side of that pair and the whole note lands in one pass; there's a
  test named for exactly that.
- A silent INTERIOR pass still yields an empty take, so take N is always pass
  N — otherwise the numbering silently shifts and "take 3" stops meaning "the
  third time round". A TRAILING empty pass is dropped: that's what hitting
  stop shortly after a wrap gives you, a stop artifact rather than a take you
  played. (Audio already behaved this way via its short-final-take rule.)
- Still triggers on the wrap: stop inside the first pass and it's an ordinary
  single recording, whatever the preference says.

Append to an existing take folder (AppendTakesAction):
- Cycle-recording over a region that already holds a take folder now ADDS to
  that folder rather than dropping a second clip on top of it, which stranded
  the new takes in an overlapping clip you couldn't audition against the old.
- "Same region" means same start AND same loop length: resize the cycle region
  and you get a fresh folder, rather than takes of a different length appended
  to an existing one, which would break the uniform-take invariant that
  comping-via-split depends on.
- The recording's own clip/instance are throwaway scaffolding here (the takes
  already live in the backend pools), so they're discarded; the single
  AppendTakesAction is the whole undoable step.

Don't play the region you're recording over:
- While recording into a MIDI track, every clip on that track is silenced
  EXCEPT the one being recorded into. A take folder already sitting in the
  cycle region was otherwise playing its active take underneath you on every
  pass, fighting the part you were trying to record.
- The recording clip itself is exempt, because in merge mode that's precisely
  what you want to hear: the overdub you've been building up. Other tracks are
  untouched.
This commit is contained in:
Skyler Lehmkuhl
2026-07-14 12:10:08 -04:00
parent 6629adc7d2
commit c62164c365
13 changed files with 869 additions and 28 deletions
+110 -3
View File
@@ -41,6 +41,9 @@ pub struct Engine {
/// Cycle-region sample bounds frozen for the duration of an **audio** recording.
/// See `loop_bounds_samples` for why. `None` = derive live from the tempo map.
loop_bounds_frozen: Option<(i64, i64)>,
/// How a cycle MIDI recording treats its passes: merge into one clip (default), or one clip per
/// pass for the editor to fold into a take folder.
cycle_midi_separate_takes: bool,
// Lock-free communication
command_rx: rtrb::Consumer<Command>,
@@ -167,6 +170,7 @@ impl Engine {
loop_region: None,
loop_enabled: false,
loop_bounds_frozen: None,
cycle_midi_separate_takes: false,
command_rx,
midi_command_rx: None,
event_tx,
@@ -494,6 +498,11 @@ impl Engine {
self.project.reset_read_ahead_targets();
// Render the entire project hierarchy into the mix buffer
// Silence everything else on the track being recorded into (see RenderContext).
let recording_midi = self
.midi_recording_state
.as_ref()
.map(|rec| (rec.track_id, rec.clip_id));
self.project.render(
&mut self.mix_buffer,
&self.audio_pool,
@@ -503,6 +512,7 @@ impl Engine {
self.sample_rate,
self.channels,
false,
recording_midi,
);
// Copy mix to output
@@ -543,7 +553,7 @@ impl Engine {
rec.wrap_at_cycle(le_beats, ls_beats);
}
// Overdub monitoring. In merge mode every pass layers onto the same clip, so
// Overdub monitoring. In MERGE mode every pass layers onto the same clip, so
// the next pass has to PLAY BACK what was just laid down — otherwise you're
// overdubbing against silence, which defeats the point of merging (you can't
// put a hi-hat on a kick you can't hear).
@@ -551,7 +561,12 @@ impl Engine {
// The notes only reach the pool clip at stop otherwise, so fold what's been
// captured so far into it now, at the boundary. Disjoint field borrows:
// `midi_recording_state` read, `project` written.
if let Some(rec) = self.midi_recording_state.as_ref() {
//
// Deliberately NOT done in separate-takes mode: there, each pass is an
// alternative rather than a layer, so hearing the previous take play back
// under you would just be confusing — you'd be playing along with the take
// you're trying to replace.
if let Some(rec) = self.midi_recording_state.as_ref().filter(|_| !self.cycle_midi_separate_takes) {
if let Some(clip) =
self.project.midi_clip_pool.get_clip_mut(rec.clip_id)
{
@@ -633,7 +648,19 @@ impl Engine {
let duration = recording
.cycle_loop_len
.unwrap_or(current_time - recording.start_time);
let notes = recording.get_notes_with_active(current_time);
// In separate-takes mode the preview shows only the pass being played now — the
// earlier passes are alternative takes, not layers, so drawing them all on top of
// each other would misrepresent what's being recorded.
let notes = if self.cycle_midi_separate_takes && recording.cycle_loop_len.is_some() {
let mut current = recording
.notes_by_pass(recording.pass_count())
.pop()
.unwrap_or_default();
current.extend(recording.active_notes_with_provisional_end(current_time));
current
} else {
recording.get_notes_with_active(current_time)
};
let _ = self.event_tx.push(AudioEvent::MidiRecordingProgress(
recording.track_id,
recording.clip_id,
@@ -671,6 +698,7 @@ impl Engine {
self.sample_rate,
self.channels,
true, // live_only
None, // no clips are scheduled at all in live_only, so nothing to mute
);
output.copy_from_slice(&self.mix_buffer);
}
@@ -955,6 +983,9 @@ impl Engine {
Command::SetLoopEnabled(enabled) => {
self.loop_enabled = enabled;
}
Command::SetCycleMidiSeparateTakes(separate) => {
self.cycle_midi_separate_takes = separate;
}
Command::Stop => {
self.playing = false;
self.playhead = 0;
@@ -3564,6 +3595,76 @@ impl Engine {
let clip_id = recording.clip_id;
let track_id = recording.track_id;
// ---- Separate takes: one pool clip per cycle pass ----
//
// Only when the transport actually wrapped; a recording that stopped inside the first
// pass is an ordinary single recording and falls through to the merge path below, just
// as it does for audio.
if let (true, Some(loop_len)) =
(self.cycle_midi_separate_takes, recording.cycle_loop_len)
{
let loop_start = recording.start_time; // a cycle recording is anchored at the region
let passes = recording.pass_count();
let buckets = recording.notes_by_pass(passes);
eprintln!(
"[MIDI_RECORDING] Cycle recording (separate takes): {} passes",
passes
);
let mut clip_ids: Vec<MidiClipId> = Vec::with_capacity(buckets.len());
for (i, bucket) in buckets.iter().enumerate() {
// Pass 0 reuses the clip the recording started on; later passes get fresh ones.
let take_clip_id = if i == 0 {
clip_id
} else {
let id = self.next_midi_clip_id_atomic.fetch_add(1, Ordering::Relaxed);
let clip = MidiClip::empty(id, loop_len, format!("Take {}", i + 1));
self.project.midi_clip_pool.add_existing_clip(clip);
id
};
if let Some(clip) = self.project.midi_clip_pool.get_clip_mut(take_clip_id) {
clip.events.clear();
clip.duration = loop_len;
for (start, note, velocity, duration) in bucket {
clip.events.push(MidiEvent::note_on(*start, 0, *note, *velocity));
clip.events.push(MidiEvent::note_off(*start + *duration, 0, *note, 64));
}
clip.events
.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
}
clip_ids.push(take_clip_id);
}
// Point the track's instance at the take the editor will make active (the last one,
// GarageBand-style) and stretch it over the region.
if let Some(&last) = clip_ids.last() {
if let Some(crate::audio::track::TrackNode::Midi(track)) =
self.project.get_track_mut(track_id)
{
if let Some(instance) =
track.clip_instances.iter_mut().find(|i| i.clip_id == clip_id)
{
instance.clip_id = last;
instance.internal_start = Beats::ZERO;
instance.internal_end = loop_len;
instance.external_start = loop_start;
instance.external_duration = loop_len;
}
}
}
self.refresh_clip_snapshot();
let _ = self.event_tx.push(AudioEvent::MidiCycleRecordingStopped {
track_id,
clip_ids,
loop_start,
loop_len_beats: loop_len,
});
return;
}
let notes = recording.get_notes().to_vec();
let note_count = notes.len();
// A cycle MIDI recording is anchored at the region start and every pass overdubs into
@@ -3698,6 +3799,12 @@ impl EngineController {
let _ = self.command_tx.push(Command::SetLoopEnabled(enabled));
}
/// How a cycle MIDI recording treats its passes: merge into one clip (false, the default), or
/// one clip per pass (true) for the editor to fold into a take folder.
pub fn set_cycle_midi_separate_takes(&mut self, separate: bool) {
let _ = self.command_tx.push(Command::SetCycleMidiSeparateTakes(separate));
}
/// Stop playback and reset to beginning
pub fn stop(&mut self) {
let _ = self.command_tx.push(Command::Stop);
+3
View File
@@ -211,6 +211,7 @@ pub fn render_to_memory(
settings.sample_rate,
settings.channels,
false,
None, // export never runs with a recording in flight
);
// Calculate how many samples we actually need from this chunk
@@ -557,6 +558,7 @@ fn export_mp3<P: AsRef<Path>>(
settings.sample_rate,
settings.channels,
false,
None, // export never runs with a recording in flight
);
// Calculate how many samples we need from this chunk
@@ -727,6 +729,7 @@ fn export_aac<P: AsRef<Path>>(
settings.sample_rate,
settings.channels,
false,
None, // export never runs with a recording in flight
);
// Calculate how many samples we need from this chunk
+2
View File
@@ -383,6 +383,7 @@ impl Project {
sample_rate: u32,
channels: u32,
live_only: bool,
recording_midi: Option<(TrackId, MidiClipId)>,
) {
output.fill(0.0);
@@ -391,6 +392,7 @@ impl Project {
// Create initial render context
let ctx = RenderContext {
live_only,
recording_midi,
..RenderContext::new(playhead_seconds, tempo_map, sample_rate, channels, output.len())
};
+176 -23
View File
@@ -302,6 +302,13 @@ pub struct MidiRecordingState {
/// note's offset already lands inside `[0, loop_len)` and successive passes overdub onto each
/// other with no folding needed. Set only if the transport actually wrapped.
pub cycle_loop_len: Option<Beats>,
/// Which cycle pass is currently being recorded (0-based). Bumped at each wrap.
current_pass: usize,
/// The pass each completed note belongs to, parallel to `completed_notes`.
///
/// Only meaningful in "separate takes" mode, where each pass becomes its own MIDI clip. Merge
/// mode ignores it — all passes fold into one clip, which is the whole point.
note_pass: Vec<usize>,
}
impl MidiRecordingState {
@@ -313,9 +320,25 @@ impl MidiRecordingState {
active_notes: HashMap::new(),
completed_notes: Vec::new(),
cycle_loop_len: None,
current_pass: 0,
note_pass: Vec::new(),
}
}
/// Record a finished note, tagging it with the pass it was played in.
///
/// Every completion goes through here so `completed_notes` and `note_pass` can't drift apart.
fn push_completed(&mut self, note: &ActiveMidiNote, end_time: Beats) {
let note_start = note.start_time.max(self.start_time);
self.completed_notes.push((
note_start - self.start_time,
note.note,
note.velocity,
end_time - note_start,
));
self.note_pass.push(self.current_pass);
}
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: Beats) {
self.active_notes.insert(note, ActiveMidiNote { note, velocity, start_time: absolute_time });
}
@@ -325,16 +348,38 @@ impl MidiRecordingState {
if absolute_time <= self.start_time {
return;
}
let note_start = active_note.start_time.max(self.start_time);
self.completed_notes.push((
note_start - self.start_time,
active_note.note,
active_note.velocity,
absolute_time - note_start,
));
self.push_completed(&active_note, absolute_time);
}
}
/// Completed notes grouped by cycle pass — one bucket per pass, in recording order.
///
/// Used by "separate takes" mode, where each pass becomes its own MIDI clip.
///
/// An *interior* pass in which nothing was played still yields an empty take, so take N in the
/// folder is always pass N on the transport — otherwise the numbering would silently shift and
/// "take 3" would stop meaning "the third time round". A *trailing* empty pass is dropped
/// though: that's what you get by hitting stop shortly after a wrap, and it's a stop artifact
/// rather than a take you played. (Same reasoning as the audio path's short-final-take rule.)
pub fn notes_by_pass(&self, passes: usize) -> Vec<Vec<(Beats, u8, u8, Beats)>> {
let mut buckets = vec![Vec::new(); passes.max(1)];
for (note, &pass) in self.completed_notes.iter().zip(self.note_pass.iter()) {
if let Some(bucket) = buckets.get_mut(pass) {
bucket.push(*note);
}
}
// Never drop the only take.
while buckets.len() > 1 && buckets.last().is_some_and(|b| b.is_empty()) {
buckets.pop();
}
buckets
}
/// How many cycle passes this recording covered (1 if the transport never wrapped).
pub fn pass_count(&self) -> usize {
self.current_pass + 1
}
pub fn get_notes(&self) -> &[(Beats, u8, u8, Beats)] {
&self.completed_notes
}
@@ -343,18 +388,28 @@ impl MidiRecordingState {
self.completed_notes.len()
}
/// The still-held notes, given a provisional duration running to `current_time`.
///
/// These belong to whatever pass is in progress, so a per-pass view can append them as-is.
pub fn active_notes_with_provisional_end(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
self.active_notes
.values()
.map(|active| {
let note_start = active.start_time.max(self.start_time);
(
note_start - self.start_time,
active.note,
active.velocity,
(current_time - note_start).max(Beats::ZERO),
)
})
.collect()
}
/// Get all completed notes plus currently-held notes with a provisional duration.
pub fn get_notes_with_active(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
let mut notes = self.completed_notes.clone();
for active in self.active_notes.values() {
let note_start = active.start_time.max(self.start_time);
notes.push((
note_start - self.start_time,
active.note,
active.velocity,
(current_time - note_start).max(Beats::ZERO),
));
}
notes.extend(self.active_notes_with_provisional_end(current_time));
notes
}
@@ -366,13 +421,7 @@ impl MidiRecordingState {
let active_notes: Vec<_> = self.active_notes.drain().collect();
for (_note_num, active_note) in active_notes {
let note_start = active_note.start_time.max(self.start_time);
self.completed_notes.push((
note_start - self.start_time,
active_note.note,
active_note.velocity,
end_time - note_start,
));
self.push_completed(&active_note, end_time);
}
}
@@ -392,7 +441,10 @@ impl MidiRecordingState {
.map(|n| (n.note, n.velocity))
.collect();
// Close first, so a note held across the boundary has its tail attributed to the pass that's
// ending; then advance, so the re-opened half belongs to the pass that's beginning.
self.close_active_notes(region_end);
self.current_pass += 1;
for (note, velocity) in held {
self.note_on(note, velocity, region_start);
@@ -502,3 +554,104 @@ mod cycle_tests {
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
}
}
#[cfg(test)]
mod midi_cycle_tests {
use super::*;
/// A MIDI recording anchored at the region start (beat 0), region 4 beats long.
fn rec() -> MidiRecordingState {
MidiRecordingState::new(0, 0, Beats(0.0))
}
/// One pass of the transport around a 4-beat region.
fn wrap(r: &mut MidiRecordingState) {
r.wrap_at_cycle(Beats(4.0), Beats(0.0));
}
#[test]
fn notes_are_bucketed_by_the_pass_they_were_played_in() {
let mut r = rec();
r.note_on(60, 100, Beats(1.0));
r.note_off(60, Beats(2.0)); // pass 0
wrap(&mut r);
r.note_on(62, 100, Beats(1.0));
r.note_off(62, Beats(2.0)); // pass 1
wrap(&mut r);
r.note_on(64, 100, Beats(1.0));
r.note_off(64, Beats(2.0)); // pass 2
assert_eq!(r.pass_count(), 3);
let by_pass = r.notes_by_pass(r.pass_count());
let pitches: Vec<Vec<u8>> = by_pass
.iter()
.map(|p| p.iter().map(|n| n.1).collect())
.collect();
assert_eq!(pitches, vec![vec![60], vec![62], vec![64]]);
}
#[test]
fn a_note_held_across_a_wrap_splits_between_the_two_passes() {
// The key is still down at the boundary: the sounding half belongs to the pass that's
// ending, and the re-opened half to the pass that's beginning. Getting the pass bump on the
// wrong side of close_active_notes would file the whole note under one pass.
let mut r = rec();
r.note_on(60, 100, Beats(3.0));
wrap(&mut r); // still held
r.note_off(60, Beats(1.0)); // released 1 beat into the next pass
assert_eq!(r.pass_count(), 2);
let by_pass = r.notes_by_pass(r.pass_count());
assert_eq!(by_pass[0].len(), 1, "the held half lands in the pass that ended");
assert_eq!(by_pass[1].len(), 1, "the re-opened half lands in the next pass");
// Pass 0's half runs from beat 3 to the region end at 4.
assert_eq!(by_pass[0][0].0, Beats(3.0));
assert_eq!(by_pass[0][0].3, Beats(1.0));
// Pass 1's half starts at the region start and runs to the release.
assert_eq!(by_pass[1][0].0, Beats(0.0));
assert_eq!(by_pass[1][0].3, Beats(1.0));
}
#[test]
fn a_silent_interior_pass_still_yields_an_empty_take() {
// Take N in the folder must be pass N on the transport, even if nothing was played — else
// the take numbering silently shifts under the user.
let mut r = rec();
r.note_on(60, 100, Beats(1.0));
r.note_off(60, Beats(2.0)); // pass 0
wrap(&mut r);
wrap(&mut r); // pass 1: played nothing
r.note_on(64, 100, Beats(1.0));
r.note_off(64, Beats(2.0)); // pass 2
let by_pass = r.notes_by_pass(r.pass_count());
assert_eq!(by_pass.len(), 3);
assert_eq!(by_pass[1].len(), 0, "the silent pass is still take 2");
assert_eq!(by_pass[2][0].1, 64);
}
#[test]
fn a_trailing_empty_pass_is_dropped() {
// Hitting stop shortly after a wrap leaves a pass you never played into. That's a stop
// artifact, not a take — unlike a silent pass in the middle, which was a deliberate rest.
let mut r = rec();
r.note_on(60, 100, Beats(1.0));
r.note_off(60, Beats(2.0)); // pass 0
wrap(&mut r);
r.note_on(62, 100, Beats(1.0));
r.note_off(62, Beats(2.0)); // pass 1
wrap(&mut r); // pass 2 begins... and the user hits stop
assert_eq!(r.pass_count(), 3);
let by_pass = r.notes_by_pass(r.pass_count());
assert_eq!(by_pass.len(), 2, "the empty trailing pass is not a take");
}
#[test]
fn an_empty_recording_still_yields_one_take() {
let mut r = rec();
wrap(&mut r);
wrap(&mut r);
assert_eq!(r.notes_by_pass(r.pass_count()).len(), 1);
}
}
+21 -1
View File
@@ -1,6 +1,6 @@
use super::automation::{AutomationLane, AutomationLaneId, ParameterId};
use super::clip::{AudioClipInstance, AudioClipInstanceId};
use super::midi::{MidiClipInstance, MidiClipInstanceId, MidiEvent};
use super::midi::{MidiClipId, MidiClipInstance, MidiClipInstanceId, MidiEvent};
use super::midi_pool::MidiClipPool;
use super::node_graph::AudioGraph;
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
@@ -43,6 +43,13 @@ pub struct RenderContext<'a> {
/// Used after pause/stop to route note-off tails through the normal group hierarchy
/// without re-triggering notes from clips at the paused position.
pub live_only: bool,
/// The MIDI recording in progress, if any: (track being recorded to, clip being recorded into).
///
/// On that track, every OTHER clip is silenced for the duration of the recording. You're playing
/// a part into this region — hearing what's already there (a previous take, say) fighting with
/// what you're playing now is just noise. The clip being recorded into is exempt, because in
/// merge mode that's exactly what you DO want to hear: the overdub you've been building up.
pub recording_midi: Option<(TrackId, MidiClipId)>,
}
impl<'a> RenderContext<'a> {
@@ -61,6 +68,7 @@ impl<'a> RenderContext<'a> {
buffer_size,
time_stretch: 1.0,
live_only: false,
recording_midi: None,
}
}
@@ -864,9 +872,21 @@ impl MidiTrack {
let playhead_beats = ctx.playhead_beats();
let buffer_end_beats = ctx.buffer_end_beats();
// While recording into this track, every clip EXCEPT the one being recorded into is
// silenced. Otherwise a take folder already sitting in the cycle region would play its
// active take underneath you on every pass, fighting the part you're trying to record.
// The recording clip itself is exempt: in merge mode that's the overdub monitoring.
let muted_clip = match ctx.recording_midi {
Some((track_id, clip_id)) if track_id == self.id => Some(clip_id),
_ => None,
};
// Collect MIDI events from all clip instances that overlap with current beat range
let mut currently_active = HashSet::new();
for instance in &self.clip_instances {
if muted_clip.is_some_and(|recording| instance.clip_id != recording) {
continue;
}
if instance.overlaps_range(playhead_beats, buffer_end_beats) {
currently_active.insert(instance.id);
}
+19
View File
@@ -133,6 +133,12 @@ pub enum Command {
SetLoopRegion(Option<(Beats, Beats)>),
/// Enable/disable wrapping at the cycle region's end.
SetLoopEnabled(bool),
/// How a cycle MIDI recording treats its passes.
///
/// `false` (default) = MERGE: every pass overdubs into one clip. `true` = SEPARATE TAKES: each
/// pass becomes its own MIDI clip, and the editor folds them into a take folder — the same shape
/// audio always gets.
SetCycleMidiSeparateTakes(bool),
// Recording commands
/// Start recording on a track (track_id, start_time)
@@ -313,6 +319,19 @@ pub enum AudioEvent {
RecordingProgress(ClipId, Seconds),
/// Recording stopped (clip_id, pool_index, waveform)
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
/// A MIDI recording that wrapped the cycle region at least once, in SEPARATE TAKES mode.
///
/// One MIDI clip per pass, in recording order. (Merge mode emits the ordinary
/// `MidiRecordingStopped` instead — all passes are already folded into the one clip.)
MidiCycleRecordingStopped {
track_id: TrackId,
/// One pool MIDI clip per pass. The first is the clip the recording started on.
clip_ids: Vec<MidiClipId>,
/// Where the takes sit on the timeline — the cycle region's start.
loop_start: Beats,
/// The region's length in beats: every take spans exactly this.
loop_len_beats: Beats,
},
/// A recording that wrapped the cycle region at least once, and so became multi-take.
///
/// Each take spans the full region and they're all the same length (partial passes are padded