Cycle recording: multi-take capture, take folders, comping
Recording into a cycle region now produces one take per pass. Pick a take
from a badge on the clip; split the clip and pick different takes on the
halves, and you've comped.
Data model (phase 2):
- AudioClipType::TakeFolder { takes, recorded_loop_beats } holds the take
list on the CLIP; ClipInstance::active_take holds the selection on the
INSTANCE. That split is what makes comping fall out of the existing
split action for free — split clones the instance, so the two halves
share one take list but choose independently. recorded_loop_beats lets
a future time-stretch/conform pass reconcile audio takes if the tempo
moves under them.
- AudioClip::resolve(active_take) -> ResolvedContent{Audio|Midi|Recording}
collapses a take folder to what an instance actually plays. A folder is
not a distinct *case* at call sites — it's an audio or MIDI clip whose
identity depends on which take is live — so every backend-sync site now
resolves through this instead of matching clip_type raw. Reverse lookups
go through owns_audio_pool_index/owns_midi_clip_id, since a folder owns
one pool file per take, not just the active one.
- BackendContext::add_clip_instance/remove_clip_instance: switching takes
is a remove + re-add (there's no in-place pool-swap command), and that's
the same work AddClipInstanceAction does. One implementation, on the
context that already owns the controller and both ID maps, so the
seconds-vs-beats conversions can't drift between copies.
Capture (phase 3):
- Takes are cut GEOMETRICALLY at stop, in exact loop-length multiples. The
playhead advances before the capture block in process(), so the wrap
instant isn't sample-exact against the buffer just captured — but the
geometry is. wrap_count only decides *whether* the recording is
multi-take, never where the cuts land.
- Partial passes are padded with silence: punch in mid-region and take 1
gets silence prepended back to the region start; stop mid-pass and the
last take gets silence appended. Every take is the same length, which is
the invariant comping depends on. A final take under 50ms of real audio
is dropped as a stop artifact (but a take that FILLED the region never
is, however short the region).
- MIDI merges, and it falls out for free: anchoring the recording at
loop_start rather than the punch-in point means the transport always
wraps back INTO the region, so every note's offset already lands inside
[0, loop_len) and passes overdub with no folding logic at all.
- The whole session commits as ONE undoable action via push_applied.
Fixes found on the way:
- Split was seconds/beats confused on MIDI. trim_start/trim_end are
domain-polymorphic exactly like AudioClip::duration was — SECONDS for
audio/video/vector, BEATS for MIDI — and split mapped the split point
into clip content in seconds unconditionally. Now it works in the clip's
own domain via Document::clip_trim_duration(). Regression test included.
- TrimClip took raw f64s whose meaning flipped by track type, and the
engine set an AUDIO clip's external_duration = Beats(end - start) where
those bounds were SECONDS — so a 1-second split played back as half a
second at 120 BPM. Replaced with a domain-tagged TrimRange, built from
the clip (clip.trim_range()) so the wrong unit isn't expressible, and
the span is now converted at the clip's position on the timeline.
- The live preview grew past the loop end while the playhead wrapped. It
now grows through the first pass then pins at the region length, and the
waveform inside restarts at the region start on each pass. The pass
offset is derived from the captured buffer, not the playhead — those
advance on different clocks, and differencing them made the waveform
jitter horizontally.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
f957b01dcf
commit
16e3d676d6
+178
-24
@@ -543,6 +543,17 @@ impl Engine {
|
||||
rec.wrap_at_cycle(le_beats, ls_beats);
|
||||
}
|
||||
|
||||
// An audio recording in progress just completed a pass. This only decides
|
||||
// *whether* the recording becomes multi-take — the takes themselves are cut
|
||||
// geometrically at stop, since the playhead advances before the capture
|
||||
// block below, so the wrap instant isn't sample-exact against the buffer
|
||||
// that was just captured. The geometry is.
|
||||
if let Some(ref mut rec) = self.recording_state {
|
||||
if let Some(ref mut cycle) = rec.cycle {
|
||||
cycle.wrap_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref mut dr) = self.disk_reader {
|
||||
dr.send(crate::audio::disk_reader::DiskReaderCommand::Seek {
|
||||
frame: self.playhead.max(0) as u64,
|
||||
@@ -944,36 +955,56 @@ impl Engine {
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.external_start = Beats(new_start_time);
|
||||
clip.external_start = new_start_time;
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(instance) = track.clip_instances.iter_mut().find(|c| c.id == clip_id) {
|
||||
instance.external_start = Beats(new_start_time);
|
||||
instance.external_start = new_start_time;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.refresh_clip_snapshot();
|
||||
}
|
||||
Command::TrimClip(track_id, clip_id, new_internal_start, new_internal_end) => {
|
||||
// Trim changes which portion of the source content is used
|
||||
// Also updates external_duration to match internal duration (no looping after trim)
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
Command::TrimClip(track_id, clip_id, range) => {
|
||||
// Trim changes which portion of the source content is used.
|
||||
// Also collapses external_duration to the trimmed content length (no looping after
|
||||
// a trim).
|
||||
let tempo_map = self.tempo_map.clone();
|
||||
match (self.project.get_track_mut(track_id), range) {
|
||||
(
|
||||
Some(crate::audio::track::TrackNode::Audio(track)),
|
||||
crate::command::TrimRange::Seconds { start, end },
|
||||
) => {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.internal_start = Seconds(new_internal_start);
|
||||
clip.internal_end = Seconds(new_internal_end);
|
||||
clip.external_duration = Beats(new_internal_end - new_internal_start);
|
||||
clip.internal_start = start;
|
||||
clip.internal_end = end;
|
||||
// external_duration is BEATS while the trims are SECONDS, so the span
|
||||
// has to be converted at the clip's position on the timeline — NOT
|
||||
// reinterpreted as `Beats(end - start)`, which played a 1-second trim
|
||||
// back as half a second at 120 BPM.
|
||||
clip.external_duration = tempo_map.seconds_to_beats(
|
||||
tempo_map.beats_to_seconds(clip.external_start) + (end - start),
|
||||
) - clip.external_start;
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
(
|
||||
Some(crate::audio::track::TrackNode::Midi(track)),
|
||||
crate::command::TrimRange::Beats { start, end },
|
||||
) => {
|
||||
if let Some(instance) = track.clip_instances.iter_mut().find(|c| c.clip_id == clip_id) {
|
||||
instance.internal_start = Beats(new_internal_start);
|
||||
instance.internal_end = Beats(new_internal_end);
|
||||
instance.external_duration = Beats(new_internal_end - new_internal_start);
|
||||
instance.internal_start = start;
|
||||
instance.internal_end = end;
|
||||
// MIDI content time IS beats, so the span carries over directly.
|
||||
instance.external_duration = end - start;
|
||||
}
|
||||
}
|
||||
// A domain that doesn't match the track kind (seconds at a MIDI track, or vice
|
||||
// versa) is a caller bug, not something to guess at.
|
||||
(Some(_), _) => {
|
||||
debug_assert!(false, "TrimClip domain does not match the track kind");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.refresh_clip_snapshot();
|
||||
@@ -3212,8 +3243,28 @@ impl Engine {
|
||||
self.recording_state = Some(recording_state);
|
||||
self.recording_progress_counter = 0; // Reset progress counter
|
||||
|
||||
// Arm cycle recording. `start_time` is the region start (the editor anchors a
|
||||
// cycle recording there, for punch-in too), while capture actually begins at
|
||||
// the current playhead — the gap between them is the lead pad that take 1 gets
|
||||
// prepended as silence so it still spans the whole region.
|
||||
let cycle_info = if self.loop_enabled {
|
||||
self.loop_region.map(|(ls_beats, le_beats)| {
|
||||
let (ls, le) = self.loop_bounds_samples(ls_beats, le_beats);
|
||||
crate::audio::recording::CycleRecordInfo {
|
||||
loop_start: ls_beats,
|
||||
loop_len_beats: le_beats - ls_beats,
|
||||
loop_len_frames: (le - ls).max(0) as usize,
|
||||
lead_pad_frames: (self.playhead - ls).max(0) as usize,
|
||||
wrap_count: 0,
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Set samples to skip (drained incrementally across callbacks)
|
||||
if let Some(recording) = &mut self.recording_state {
|
||||
recording.cycle = cycle_info;
|
||||
recording.samples_to_skip = samples_in_buffer;
|
||||
if self.debug_audio && samples_in_buffer > 0 {
|
||||
eprintln!("[AUDIO DEBUG] Will skip {} stale samples from input buffer", samples_in_buffer);
|
||||
@@ -3238,6 +3289,40 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write one cycle take to a temp WAV, add it to the audio pool, and return its pool index.
|
||||
///
|
||||
/// Mirrors what the single-recording path does with its own buffer: the pool file is backed by
|
||||
/// the in-memory samples, and the temp WAV is written and then removed (the pool only reads the
|
||||
/// path opportunistically, e.g. to keep original bytes on save).
|
||||
fn write_take_to_pool(
|
||||
&mut self,
|
||||
samples: Vec<f32>,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
clip_id: ClipId,
|
||||
take_index: usize,
|
||||
) -> Result<usize, std::io::Error> {
|
||||
use crate::io::WavWriter;
|
||||
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("daw_take_{}_{}.wav", clip_id, take_index));
|
||||
|
||||
let mut writer = WavWriter::create(&path, sample_rate, channels)?;
|
||||
writer.write_samples(&samples)?;
|
||||
writer.finalize()?;
|
||||
|
||||
let pool_file = crate::audio::pool::AudioFile::with_format(
|
||||
path.clone(),
|
||||
samples,
|
||||
channels,
|
||||
sample_rate,
|
||||
Some("wav".to_string()),
|
||||
);
|
||||
let pool_index = self.audio_pool.add_file(pool_file);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
Ok(pool_index)
|
||||
}
|
||||
|
||||
/// Handle stopping a recording
|
||||
fn handle_stop_recording(&mut self) {
|
||||
eprintln!("[STOP_RECORDING] handle_stop_recording called");
|
||||
@@ -3261,11 +3346,74 @@ impl Engine {
|
||||
|
||||
eprintln!("[STOP_RECORDING] Stopping recording for clip_id={}, track_id={}", clip_id, track_id);
|
||||
|
||||
// Slice cycle takes BEFORE finalize consumes the recording. `None` here means the
|
||||
// transport never wrapped, which stays an ordinary single recording on the path below.
|
||||
let cycle = recording.cycle;
|
||||
let frames_per_peak = recording.frames_per_peak;
|
||||
let cycle_takes = recording.slice_takes();
|
||||
|
||||
// Finalize the recording (flush buffers, close file, get waveform and audio data)
|
||||
let frames_recorded = recording.frames_written;
|
||||
eprintln!("[STOP_RECORDING] Calling finalize() - frames_recorded={}", frames_recorded);
|
||||
match recording.finalize() {
|
||||
Ok((temp_file_path, waveform, audio_data)) => {
|
||||
// ---- Cycle recording: one take per pass, each spanning the whole region ----
|
||||
if let (Some(takes), Some(cycle)) = (cycle_takes, cycle) {
|
||||
eprintln!(
|
||||
"[STOP_RECORDING] Cycle recording: {} wraps -> {} takes of {} frames",
|
||||
cycle.wrap_count, takes.len(), cycle.loop_len_frames
|
||||
);
|
||||
let _ = std::fs::remove_file(&temp_file_path);
|
||||
|
||||
let mut pool_takes: Vec<(usize, Vec<crate::io::WaveformPeak>)> = Vec::new();
|
||||
for (i, take) in takes.into_iter().enumerate() {
|
||||
let peaks = crate::audio::recording::compute_peaks(
|
||||
&take,
|
||||
channels,
|
||||
frames_per_peak,
|
||||
);
|
||||
match self.write_take_to_pool(take, sample_rate, channels, clip_id, i) {
|
||||
Ok(pool_index) => pool_takes.push((pool_index, peaks)),
|
||||
Err(e) => {
|
||||
let _ = self.event_tx.push(AudioEvent::RecordingError(
|
||||
format!("Failed to store take {}: {}", i + 1, e),
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Point the engine's clip at the take the editor will make active (the last
|
||||
// one, GarageBand-style) and stretch it to cover the whole cycle region —
|
||||
// the clip was created at the punch-in point with zero length.
|
||||
let loop_len_secs =
|
||||
Seconds(cycle.loop_len_frames as f64 / sample_rate as f64);
|
||||
if let Some(&(last_pool_index, _)) = pool_takes.last() {
|
||||
if let Some(crate::audio::track::TrackNode::Audio(track)) =
|
||||
self.project.get_track_mut(track_id)
|
||||
{
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id)
|
||||
{
|
||||
clip.audio_pool_index = last_pool_index;
|
||||
clip.internal_start = Seconds(0.0);
|
||||
clip.internal_end = loop_len_secs;
|
||||
clip.external_start = cycle.loop_start;
|
||||
clip.external_duration = cycle.loop_len_beats;
|
||||
}
|
||||
}
|
||||
self.refresh_clip_snapshot();
|
||||
}
|
||||
|
||||
let _ = self.event_tx.push(AudioEvent::CycleRecordingStopped {
|
||||
clip_id,
|
||||
takes: pool_takes,
|
||||
loop_start: cycle.loop_start,
|
||||
loop_len_beats: cycle.loop_len_beats,
|
||||
loop_len_seconds: loop_len_secs,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
eprintln!("[STOP_RECORDING] Finalize succeeded: {} frames written to {:?}, {} waveform peaks generated, {} samples in memory",
|
||||
frames_recorded, temp_file_path, waveform.len(), audio_data.len());
|
||||
|
||||
@@ -3357,7 +3505,13 @@ impl Engine {
|
||||
let track_id = recording.track_id;
|
||||
let notes = recording.get_notes().to_vec();
|
||||
let note_count = notes.len();
|
||||
let recording_duration = end_time - recording.start_time;
|
||||
// A cycle MIDI recording is anchored at the region start and every pass overdubs into
|
||||
// the same clip (MERGE), so the clip is exactly one region long — not however long the
|
||||
// user held the record button, which would run past the loop end.
|
||||
let recording_duration = match recording.cycle_loop_len {
|
||||
Some(loop_len) => loop_len,
|
||||
None => end_time - recording.start_time,
|
||||
};
|
||||
|
||||
eprintln!("[MIDI_RECORDING] Stopping MIDI recording for clip_id={}, track_id={}, captured {} notes, duration={:.3} beats",
|
||||
clip_id, track_id, note_count, recording_duration.0);
|
||||
@@ -3522,17 +3676,17 @@ impl EngineController {
|
||||
|
||||
/// Move a clip to a new timeline position (changes external_start)
|
||||
pub fn move_clip(&mut self, track_id: TrackId, clip_id: ClipId, new_start_time: Beats) {
|
||||
let _ = self.command_tx.push(Command::MoveClip(track_id, clip_id, new_start_time.beats_to_f64()));
|
||||
let _ = self.command_tx.push(Command::MoveClip(track_id, clip_id, new_start_time));
|
||||
}
|
||||
|
||||
/// Trim a clip's internal boundaries (changes which portion of source content is used)
|
||||
/// This also resets external_duration to match internal duration (disables looping)
|
||||
/// Trim a clip's internal content bounds. The units are content-domain and depend on the
|
||||
/// track type: SECONDS for a sampled-audio clip, BEATS for a MIDI clip (see the TrimClip
|
||||
/// handler). Left as raw f64 because a single newtype can't express both; callers pass the
|
||||
/// clip's own `trim_start`/`trim_end`, which already match its content domain.
|
||||
pub fn trim_clip(&mut self, track_id: TrackId, clip_id: ClipId, new_internal_start: f64, new_internal_end: f64) {
|
||||
let _ = self.command_tx.push(Command::TrimClip(track_id, clip_id, new_internal_start, new_internal_end));
|
||||
/// Trim a clip's internal content bounds — which portion of the source content plays.
|
||||
///
|
||||
/// Collapses external_duration to the trimmed length (disables looping). The bounds are
|
||||
/// content-domain, which differs by clip kind, so they're passed as a [`TrimRange`] that names
|
||||
/// the domain: `Seconds` for sampled audio, `Beats` for MIDI. The engine rejects a range whose
|
||||
/// domain doesn't match the track.
|
||||
pub fn trim_clip(&mut self, track_id: TrackId, clip_id: ClipId, range: crate::command::TrimRange) {
|
||||
let _ = self.command_tx.push(Command::TrimClip(track_id, clip_id, range));
|
||||
}
|
||||
|
||||
/// Extend or shrink a clip's external duration (enables looping if > internal duration)
|
||||
|
||||
@@ -5,6 +5,50 @@ use crate::time::{Beats, Seconds};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Cycle-recording bookkeeping attached to a recording that started with a cycle region armed.
|
||||
///
|
||||
/// Takes are sliced **geometrically** at stop, in exact `loop_len_frames` multiples — not at the
|
||||
/// instant the wrap was detected. The playhead advances before the capture block in `process()`, so
|
||||
/// the wrap instant isn't sample-exact against the buffer that was just captured, but the geometry
|
||||
/// is. `wrap_count` therefore only decides *whether* this is a multi-take recording, never where the
|
||||
/// cuts land.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct CycleRecordInfo {
|
||||
/// Where the cycle region starts, in beats. Takes are laid down here, not at the punch-in point.
|
||||
pub loop_start: Beats,
|
||||
/// The cycle region's length in beats — what the take folder records as `recorded_loop_beats`.
|
||||
pub loop_len_beats: Beats,
|
||||
/// One cycle pass, in frames. The take size.
|
||||
pub loop_len_frames: usize,
|
||||
/// Frames between the region start and where capture actually began. Non-zero only for a
|
||||
/// punch-in (record while already rolling); take 1 gets this much silence prepended so it still
|
||||
/// spans the whole region.
|
||||
pub lead_pad_frames: usize,
|
||||
/// How many times the transport wrapped during this recording. Zero means the user stopped
|
||||
/// before completing a pass, which stays an ordinary single recording.
|
||||
pub wrap_count: usize,
|
||||
}
|
||||
|
||||
/// Min/max waveform peaks for a finished buffer of interleaved samples.
|
||||
///
|
||||
/// The live recording path builds its peaks incrementally as samples arrive; cycle takes don't
|
||||
/// exist until the recording is sliced at stop, so they get theirs in one pass here.
|
||||
pub fn compute_peaks(samples: &[f32], channels: u32, frames_per_peak: usize) -> Vec<WaveformPeak> {
|
||||
let samples_per_peak = (frames_per_peak * channels.max(1) as usize).max(1);
|
||||
samples
|
||||
.chunks(samples_per_peak)
|
||||
.map(|chunk| {
|
||||
let mut min = 0.0f32;
|
||||
let mut max = 0.0f32;
|
||||
for s in chunk {
|
||||
min = min.min(*s);
|
||||
max = max.max(*s);
|
||||
}
|
||||
WaveformPeak { min, max }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// State of an active recording session
|
||||
pub struct RecordingState {
|
||||
/// Track being recorded to
|
||||
@@ -35,6 +79,8 @@ pub struct RecordingState {
|
||||
pub frames_per_peak: usize,
|
||||
/// All recorded audio data accumulated in memory (written to disk at finalization)
|
||||
pub audio_data: Vec<f32>,
|
||||
/// Cycle-recording bookkeeping, when a cycle region was armed at record start.
|
||||
pub cycle: Option<CycleRecordInfo>,
|
||||
}
|
||||
|
||||
impl RecordingState {
|
||||
@@ -69,9 +115,69 @@ impl RecordingState {
|
||||
waveform_buffer: Vec::new(),
|
||||
frames_per_peak,
|
||||
audio_data: Vec::new(),
|
||||
cycle: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slice the recording into cycle takes: one per pass, each spanning the FULL cycle region.
|
||||
///
|
||||
/// Partial passes are padded with silence — the head of take 1 for a punch-in, the tail of the
|
||||
/// last take when the user stops mid-pass — so every take is the same length and aligned to the
|
||||
/// region. That uniformity is what makes comping-via-split work: take 1 on the left half and
|
||||
/// take 3 on the right always line up.
|
||||
///
|
||||
/// Returns `None` if this wasn't a cycle recording or the transport never wrapped (an ordinary
|
||||
/// single recording, which keeps the existing path untouched).
|
||||
pub fn slice_takes(&self) -> Option<Vec<Vec<f32>>> {
|
||||
let cycle = self.cycle?;
|
||||
if cycle.wrap_count == 0 || cycle.loop_len_frames == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let ch = self.channels.max(1) as usize;
|
||||
let take_len = cycle.loop_len_frames * ch;
|
||||
let lead = cycle.lead_pad_frames * ch;
|
||||
|
||||
// The recording as positioned *within the region*: silence for the gap between the region
|
||||
// start and the punch-in, then the captured audio. Slicing this at whole-take boundaries is
|
||||
// the whole trick — take 1 comes out short-by-`lead` at the front, already padded.
|
||||
let virtual_len = lead + self.audio_data.len();
|
||||
let take_count = virtual_len.div_ceil(take_len);
|
||||
|
||||
let mut takes: Vec<Vec<f32>> = Vec::with_capacity(take_count);
|
||||
for i in 0..take_count {
|
||||
let mut take = vec![0.0f32; take_len];
|
||||
let take_begin = i * take_len;
|
||||
for slot in 0..take_len {
|
||||
// Position in the virtual (lead-padded) buffer.
|
||||
let v = take_begin + slot;
|
||||
if v < lead {
|
||||
continue; // still in the punch-in silence
|
||||
}
|
||||
match self.audio_data.get(v - lead) {
|
||||
Some(s) => take[slot] = *s,
|
||||
None => break, // past the end of capture; the rest stays silent
|
||||
}
|
||||
}
|
||||
takes.push(take);
|
||||
}
|
||||
|
||||
// A final take holding only a sliver of real audio is a stop artifact (the user hit stop a
|
||||
// moment after the wrap), not a performance. Drop it — but only if it's actually a PARTIAL
|
||||
// pass, and never the only take. A pass that filled the region is a real take no matter how
|
||||
// short the region is.
|
||||
const MIN_TAKE_SECONDS: f64 = 0.05;
|
||||
if takes.len() > 1 {
|
||||
let last_real_samples = virtual_len - (takes.len() - 1) * take_len;
|
||||
let last_real_seconds = (last_real_samples / ch) as f64 / self.sample_rate as f64;
|
||||
if last_real_samples < take_len && last_real_seconds < MIN_TAKE_SECONDS {
|
||||
takes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
Some(takes)
|
||||
}
|
||||
|
||||
/// Add samples to the accumulation buffer
|
||||
/// Returns true if a flush occurred
|
||||
pub fn add_samples(&mut self, samples: &[f32]) -> Result<bool, std::io::Error> {
|
||||
@@ -189,6 +295,13 @@ pub struct MidiRecordingState {
|
||||
active_notes: HashMap<u8, ActiveMidiNote>,
|
||||
/// Completed notes: (time_offset, note, velocity, duration) — all times in beats
|
||||
pub completed_notes: Vec<(Beats, u8, u8, Beats)>,
|
||||
/// The cycle region's length in beats, when recording into a cycle.
|
||||
///
|
||||
/// A cycle MIDI recording is anchored at the region start (`start_time == loop_start`), which is
|
||||
/// what makes MERGE fall out for free: the transport always wraps back into the region, so every
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl MidiRecordingState {
|
||||
@@ -199,6 +312,7 @@ impl MidiRecordingState {
|
||||
start_time,
|
||||
active_notes: HashMap::new(),
|
||||
completed_notes: Vec::new(),
|
||||
cycle_loop_len: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,5 +397,108 @@ impl MidiRecordingState {
|
||||
for (note, velocity) in held {
|
||||
self.note_on(note, velocity, region_start);
|
||||
}
|
||||
|
||||
// The transport wrapped, so this is a cycle recording: the clip spans the whole region
|
||||
// rather than however long the user happened to hold the record button.
|
||||
self.cycle_loop_len = Some(region_end - region_start);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cycle_tests {
|
||||
use super::*;
|
||||
|
||||
/// A recording state holding `audio_data`, armed for cycle recording. Mono, 100 Hz, so a frame
|
||||
/// is a sample and 5 frames is 50 ms (exactly the min-take threshold).
|
||||
fn rec(audio: Vec<f32>, loop_len_frames: usize, lead_pad_frames: usize, wraps: usize) -> RecordingState {
|
||||
let mut r = RecordingState::new(
|
||||
0,
|
||||
0,
|
||||
PathBuf::from("/dev/null"),
|
||||
WavWriter::create(&PathBuf::from("/dev/null"), 100, 1).expect("wav writer"),
|
||||
100,
|
||||
1,
|
||||
Beats(0.0),
|
||||
1.0,
|
||||
);
|
||||
r.audio_data = audio;
|
||||
r.cycle = Some(CycleRecordInfo {
|
||||
loop_start: Beats(0.0),
|
||||
loop_len_beats: Beats(4.0),
|
||||
loop_len_frames,
|
||||
lead_pad_frames,
|
||||
wrap_count: wraps,
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_wrap_is_not_a_cycle_recording() {
|
||||
// Stopping before the transport ever wraps stays an ordinary single recording — the whole
|
||||
// point of triggering on the wrap rather than on the cycle region merely existing.
|
||||
let r = rec(vec![1.0; 10], 4, 0, 0);
|
||||
assert!(r.slice_takes().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_are_cut_at_exact_loop_multiples() {
|
||||
// 12 frames of audio, 4-frame loop, started at the region start => 3 clean takes.
|
||||
let audio: Vec<f32> = (1..=12).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 4, 0, 2).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 3);
|
||||
assert_eq!(takes[0], vec![1.0, 2.0, 3.0, 4.0]);
|
||||
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
|
||||
assert_eq!(takes[2], vec![9.0, 10.0, 11.0, 12.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn punch_in_pads_the_head_of_take_one() {
|
||||
// Punched in 2 frames into the region: take 1 gets 2 frames of silence at the FRONT so it
|
||||
// still spans the whole region and lines up with every other take.
|
||||
let audio: Vec<f32> = (1..=10).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 4, 2, 2).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 3);
|
||||
assert_eq!(takes[0], vec![0.0, 0.0, 1.0, 2.0]);
|
||||
assert_eq!(takes[1], vec![3.0, 4.0, 5.0, 6.0]);
|
||||
assert_eq!(takes[2], vec![7.0, 8.0, 9.0, 10.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_mid_pass_pads_the_tail_of_the_last_take() {
|
||||
// 13 frames, 8-frame loop => the second take holds 5 real frames (50 ms at 100 Hz, right at
|
||||
// the keep threshold) and 3 of silence.
|
||||
let audio: Vec<f32> = (1..=13).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 8, 0, 1).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 2);
|
||||
assert_eq!(takes[1], vec![9.0, 10.0, 11.0, 12.0, 13.0, 0.0, 0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_take_is_the_same_length() {
|
||||
// Uniform length is the invariant comping-via-split depends on.
|
||||
let audio: Vec<f32> = (1..=23).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 8, 3, 3).slice_takes().expect("cycle takes");
|
||||
assert!(takes.iter().all(|t| t.len() == 8), "takes must be uniform");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliver_of_a_final_take_is_dropped() {
|
||||
// Stopped 1 frame (10 ms at 100 Hz) after the wrap — below the 50 ms floor, so that stub of
|
||||
// a take is a stop artifact and goes.
|
||||
let audio: Vec<f32> = (1..=9).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 8, 0, 1).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 1, "a 10ms tail take should be dropped");
|
||||
assert_eq!(takes[0].len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_final_take_is_never_dropped() {
|
||||
// Regression: the sliver rule must only fire on a PARTIAL pass. A pass that filled the
|
||||
// region is a real take however short the region is — an earlier version compared a full
|
||||
// take's duration to the floor and silently ate it.
|
||||
let audio: Vec<f32> = (1..=8).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 4, 0, 1).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 2, "both passes filled the region");
|
||||
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
pub mod types;
|
||||
|
||||
pub use types::{AudioEvent, Command, MidiClipData, OscilloscopeData, Query, QueryResponse};
|
||||
pub use types::{AudioEvent, Command, MidiClipData, OscilloscopeData, Query, QueryResponse, TrimRange};
|
||||
|
||||
@@ -8,6 +8,21 @@ use crate::audio::node_graph::nodes::LoopMode;
|
||||
use crate::io::WaveformPeak;
|
||||
use crate::time::{Beats, Seconds};
|
||||
|
||||
/// A clip's internal (content) boundaries, tagged with the domain they're measured in.
|
||||
///
|
||||
/// A clip's content time is SECONDS for sampled audio but BEATS for MIDI — the same polymorphism
|
||||
/// `ClipInstance::trim_start`/`trim_end` carry. Passing these as bare `f64`s meant the caller and
|
||||
/// the engine could disagree about the unit with nothing to catch it: an audio trim of "1.0" was
|
||||
/// once stored as `Beats(1.0)` for the clip's external duration, so a 1-second split played back as
|
||||
/// half a second at 120 BPM. Tagging the domain makes that a type error instead of a bug report.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum TrimRange {
|
||||
/// Sampled-audio content time.
|
||||
Seconds { start: Seconds, end: Seconds },
|
||||
/// MIDI content time.
|
||||
Beats { start: Beats, end: Beats },
|
||||
}
|
||||
|
||||
/// Commands sent from UI/control thread to audio thread
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Command {
|
||||
@@ -31,10 +46,9 @@ pub enum Command {
|
||||
|
||||
// Clip management commands
|
||||
/// Move a clip to a new timeline position (track_id, clip_id, new_external_start)
|
||||
MoveClip(TrackId, ClipId, f64),
|
||||
/// Trim a clip's internal boundaries (track_id, clip_id, new_internal_start, new_internal_end)
|
||||
/// This changes which portion of the source content is used
|
||||
TrimClip(TrackId, ClipId, f64, f64),
|
||||
MoveClip(TrackId, ClipId, Beats),
|
||||
/// Trim a clip's internal boundaries — which portion of the source content is used.
|
||||
TrimClip(TrackId, ClipId, TrimRange),
|
||||
/// Extend/shrink a clip's external duration (track_id, clip_id, new_external_duration)
|
||||
/// If duration > internal duration, the clip will loop
|
||||
ExtendClip(TrackId, ClipId, f64),
|
||||
@@ -299,6 +313,22 @@ pub enum AudioEvent {
|
||||
RecordingProgress(ClipId, Seconds),
|
||||
/// Recording stopped (clip_id, pool_index, waveform)
|
||||
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
|
||||
/// 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
|
||||
/// with silence), so the editor can promote the recording clip straight to a take folder.
|
||||
CycleRecordingStopped {
|
||||
clip_id: ClipId,
|
||||
/// One entry per pass: (audio pool index, waveform peaks), in recording order.
|
||||
takes: Vec<(usize, Vec<WaveformPeak>)>,
|
||||
/// Where the takes sit on the timeline — the cycle region's start, not the punch-in point.
|
||||
loop_start: Beats,
|
||||
/// The region's length in beats (what the take folder stores as `recorded_loop_beats`).
|
||||
loop_len_beats: Beats,
|
||||
/// The same length in seconds — the take folder's content duration, which is seconds-domain
|
||||
/// for audio.
|
||||
loop_len_seconds: Seconds,
|
||||
},
|
||||
/// Recording error (error_message)
|
||||
RecordingError(String),
|
||||
/// MIDI recording stopped (track_id, clip_id, note_count)
|
||||
|
||||
Reference in New Issue
Block a user