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:
Skyler Lehmkuhl
2026-07-13 14:40:10 -04:00
co-authored by Claude Opus 4.8
parent f957b01dcf
commit 16e3d676d6
19 changed files with 1518 additions and 240 deletions
@@ -6490,6 +6490,25 @@ impl eframe::App for EditorApp {
})
};
// While cycling, the recording keeps running but the clip only ever
// occupies ONE region — each further pass is a new take layered on
// the same span, not more length. Cap the preview there so the bar
// doesn't grow off past the loop end while the playhead wraps.
let cycle_cap = {
let doc = self.action_executor.document();
match (doc.cycle_enabled, doc.cycle_region) {
(true, Some((ls, le))) if le > ls => {
let tm = doc.tempo_map();
Some(tm.beats_to_seconds(le) - tm.beats_to_seconds(ls))
}
_ => None,
}
};
let duration = match cycle_cap {
Some(cap) if duration > cap => cap,
_ => duration,
};
// Then update the clip duration (mutable borrow)
if let Some(doc_clip_id) = doc_clip_id {
if let Some(clip) = self.action_executor.document_mut().audio_clips.get_mut(&doc_clip_id) {
@@ -6501,6 +6520,116 @@ impl eframe::App for EditorApp {
}
ctx.request_repaint();
}
AudioEvent::CycleRecordingStopped { clip_id: backend_clip_id, takes, loop_start, loop_len_beats, loop_len_seconds } => {
eprintln!("[STOP] CycleRecordingStopped: {} takes", takes.len());
// Clean up the live-recording waveform cache (keyed usize::MAX).
self.raw_audio_cache.remove(&usize::MAX);
self.waveform_gpu_dirty.remove(&usize::MAX);
// Pull every take's samples in for waveform rendering — the user can
// switch to any of them, not just the active one.
if let Some(ref controller_arc) = self.audio_controller {
let mut controller = controller_arc.lock().unwrap();
for &(pool_index, _) in &takes {
match controller.get_pool_audio_samples(pool_index) {
Ok((samples, sr, ch)) => {
self.raw_audio_cache.insert(pool_index, (Arc::new(samples), sr, ch));
self.waveform_gpu_dirty.insert(pool_index);
self.audio_pools_with_new_waveforms.insert(pool_index);
}
Err(e) => eprintln!("Failed to fetch take audio: {}", e),
}
self.audio_duration_cache.insert(pool_index, loop_len_seconds.seconds_to_f64());
}
}
let recording_layer = self.recording_clips.iter()
.find(|(_, &cid)| cid == backend_clip_id)
.map(|(&lid, _)| lid);
if let (Some(layer_id), false) = (recording_layer, takes.is_empty()) {
let (clip_id, instance_id) = {
let document = self.action_executor.document();
document.get_layer(&layer_id)
.and_then(|layer| {
if let lightningbeam_core::layer::AnyLayer::Audio(audio_layer) = layer {
audio_layer.clip_instances.last().map(|i| (i.clip_id, i.id))
} else {
None
}
})
.unwrap_or((uuid::Uuid::nil(), uuid::Uuid::nil()))
};
if !clip_id.is_nil() {
self.autosave.pending_event = true;
let last_take = takes.len() - 1;
// Promote the in-progress recording clip to a take folder.
{
let doc = self.action_executor.document_mut();
if let Some(clip) = doc.audio_clips.get_mut(&clip_id) {
clip.clip_type = lightningbeam_core::clip::AudioClipType::TakeFolder {
takes: takes.iter().enumerate().map(|(i, &(pool_index, _))| {
lightningbeam_core::clip::AudioTake {
name: format!("Take {}", i + 1),
content: lightningbeam_core::clip::TakeContent::Audio { audio_pool_index: pool_index },
}
}).collect(),
recorded_loop_beats: loop_len_beats,
};
// Audio takes are seconds-domain, and every take is
// exactly one cycle region long.
clip.set_content_duration(ClipDuration::Seconds(loop_len_seconds));
clip.name = format!("Cycle recording ({} takes)", takes.len());
}
// Anchor the instance to the region and select the most
// recent take, GarageBand-style.
//
// timeline_duration stays None on purpose: pinning it would
// make a later tempo change loop/repeat the take's content
// to fill the span instead of letting it drift naturally.
if let Some(lightningbeam_core::layer::AnyLayer::Audio(al)) = doc.get_layer_mut(&layer_id) {
if let Some(inst) = al.clip_instances.iter_mut().find(|ci| ci.id == instance_id) {
inst.timeline_start = loop_start;
inst.timeline_duration = None;
inst.trim_start = 0.0;
inst.trim_end = Some(loop_len_seconds.seconds_to_f64());
inst.active_take = Some(last_take);
}
}
}
// The backend already has a clip for the active take (the engine
// pointed it at the last take on stop), so map to it rather than
// adding a duplicate.
let backend_id = lightningbeam_core::action::BackendClipInstanceId::Audio(backend_clip_id);
self.clip_instance_to_backend_map.insert(instance_id, backend_id);
// Commit the whole cycle-record session as ONE undoable action.
let clip_instance = self.layer_to_track_map.get(&layer_id).copied().and_then(|track_id| {
self.action_executor.document()
.get_layer(&layer_id)
.and_then(|l| if let AnyLayer::Audio(al) = l {
al.clip_instances.iter().find(|ci| ci.id == instance_id).cloned()
} else { None })
.map(|ci| (track_id, ci))
});
if let Some((track_id, clip_instance)) = clip_instance {
let action = lightningbeam_core::actions::AddClipInstanceAction::already_applied(
layer_id, clip_instance, track_id, backend_id,
);
self.action_executor.push_applied(Box::new(action));
} else {
self.media_modified = true;
}
}
}
self.recording_clips.retain(|_, &mut cid| cid != backend_clip_id);
}
AudioEvent::RecordingStopped(_backend_clip_id, pool_index, _waveform) => {
eprintln!("[STOP] AudioEvent::RecordingStopped received (pool_index={})", pool_index);
@@ -7,7 +7,17 @@
//! - Image Assets (static images)
use eframe::egui;
use lightningbeam_core::clip::{AudioClipType, VectorClip};
use lightningbeam_core::clip::{AudioClip, ResolvedContent, VectorClip};
/// Library label for an audio clip: a take folder advertises how many takes it holds, anything else
/// just names its kind. The library lists *clips*, not placements, so there's no active take here —
/// a folder is previewed by its first take.
fn take_label(clip: &AudioClip, kind: &str) -> String {
match clip.takes() {
Some(takes) => format!("{} ({} takes)", kind, takes.len()),
None => kind.to_string(),
}
}
use lightningbeam_core::document::Document;
use lightningbeam_core::layer::AnyLayer;
use std::collections::{HashMap, HashSet};
@@ -918,11 +928,11 @@ impl AssetLibraryPane {
continue;
}
let (extra_info, drag_clip_type) = match &clip.clip_type {
AudioClipType::Sampled { .. } => ("Sampled".to_string(), DragClipType::AudioSampled),
AudioClipType::Midi { .. } => ("MIDI".to_string(), DragClipType::AudioMidi),
AudioClipType::Recording => {
// Skip recording-in-progress clips from asset library
let (extra_info, drag_clip_type) = match &clip.resolve(None) {
ResolvedContent::Audio { .. } => (take_label(clip, "Sampled"), DragClipType::AudioSampled),
ResolvedContent::Midi { .. } => (take_label(clip, "MIDI"), DragClipType::AudioMidi),
ResolvedContent::Recording => {
// Skip recording-in-progress clips (and empty take folders) from asset library
continue;
}
};
@@ -1118,15 +1128,15 @@ impl AssetLibraryPane {
for (id, clip) in &document.audio_clips {
if !linked_audio_ids.contains(id) && clip.folder_id == current_folder {
let (extra_info, drag_clip_type) = match &clip.clip_type {
AudioClipType::Sampled { .. } => {
("Sampled".to_string(), DragClipType::AudioSampled)
let (extra_info, drag_clip_type) = match &clip.resolve(None) {
ResolvedContent::Audio { .. } => {
(take_label(clip, "Sampled"), DragClipType::AudioSampled)
}
AudioClipType::Midi { .. } => {
("MIDI".to_string(), DragClipType::AudioMidi)
ResolvedContent::Midi { .. } => {
(take_label(clip, "MIDI"), DragClipType::AudioMidi)
}
AudioClipType::Recording => {
// Skip recording-in-progress clips
ResolvedContent::Recording => {
// Skip recording-in-progress clips (and empty take folders)
continue;
}
};
@@ -1765,7 +1775,7 @@ impl AssetLibraryPane {
let prefetched_waveform: Option<Vec<(f32, f32)>> =
if asset_category == AssetCategory::Audio && !self.thumbnail_cache.has(&asset_id) {
if let Some(clip) = document.audio_clips.get(&asset_id) {
if let AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
if let Some(audio_pool_index) = clip.resolved_audio_pool_index(None).as_ref() {
shared.raw_audio_cache.get(audio_pool_index)
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize))
} else {
@@ -1790,8 +1800,8 @@ impl AssetLibraryPane {
AssetCategory::Audio => {
if let Some(clip) = document.audio_clips.get(&asset_id) {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
match &clip.clip_type {
AudioClipType::Sampled { .. } => {
match &clip.resolve(None) {
ResolvedContent::Audio { .. } => {
let wave_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(ref peaks) = prefetched_waveform {
Some(generate_waveform_thumbnail(peaks, bg_color, wave_color))
@@ -1799,7 +1809,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Midi { midi_clip_id } => {
ResolvedContent::Midi { midi_clip_id } => {
let note_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(events) = shared.midi_event_cache.get(midi_clip_id) {
Some(generate_midi_thumbnail(events, clip.content_duration().native(), bg_color, note_color))
@@ -1807,7 +1817,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
// Recording in progress - show placeholder
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
@@ -2344,8 +2354,8 @@ impl AssetLibraryPane {
AssetCategory::Audio => {
if let Some(clip) = document.audio_clips.get(&asset_id) {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
match &clip.clip_type {
AudioClipType::Sampled { audio_pool_index } => {
match &clip.resolve(None) {
ResolvedContent::Audio { audio_pool_index } => {
let wave_color = egui::Color32::from_rgb(100, 200, 100);
let waveform: Option<Vec<(f32, f32)>> = shared.raw_audio_cache.get(audio_pool_index)
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize));
@@ -2355,7 +2365,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Midi { midi_clip_id } => {
ResolvedContent::Midi { midi_clip_id } => {
let note_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(events) = shared.midi_event_cache.get(midi_clip_id) {
Some(generate_midi_thumbnail(events, clip.content_duration().native(), bg_color, note_color))
@@ -2363,7 +2373,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
@@ -2481,8 +2491,8 @@ impl AssetLibraryPane {
AssetCategory::Audio => {
if let Some(clip) = document.audio_clips.get(&asset_id) {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
match &clip.clip_type {
AudioClipType::Sampled { audio_pool_index } => {
match &clip.resolve(None) {
ResolvedContent::Audio { audio_pool_index } => {
let wave_color = egui::Color32::from_rgb(100, 200, 100);
let waveform: Option<Vec<(f32, f32)>> = shared.raw_audio_cache.get(audio_pool_index)
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize));
@@ -2492,7 +2502,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Midi { midi_clip_id } => {
ResolvedContent::Midi { midi_clip_id } => {
let note_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(events) = shared.midi_event_cache.get(midi_clip_id) {
Some(generate_midi_thumbnail(events, clip.content_duration().native(), bg_color, note_color))
@@ -2500,7 +2510,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
@@ -2802,7 +2812,7 @@ impl AssetLibraryPane {
let prefetched_waveform: Option<Vec<(f32, f32)>> =
if asset_category == AssetCategory::Audio && !self.thumbnail_cache.has(&asset_id) {
if let Some(clip) = document.audio_clips.get(&asset_id) {
if let AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
if let Some(audio_pool_index) = clip.resolved_audio_pool_index(None).as_ref() {
let waveform: Option<Vec<(f32, f32)>> = shared.raw_audio_cache.get(audio_pool_index)
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize));
if waveform.is_some() {
@@ -2842,8 +2852,8 @@ impl AssetLibraryPane {
// Check if it's sampled or MIDI
if let Some(clip) = document.audio_clips.get(&asset_id) {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
match &clip.clip_type {
AudioClipType::Sampled { .. } => {
match &clip.resolve(None) {
ResolvedContent::Audio { .. } => {
let wave_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(ref peaks) = prefetched_waveform {
println!("✅ Generating waveform thumbnail with {} peaks for asset {}", peaks.len(), asset_id);
@@ -2853,7 +2863,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Midi { midi_clip_id } => {
ResolvedContent::Midi { midi_clip_id } => {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
let note_color = egui::Color32::from_rgb(100, 200, 100);
@@ -2863,7 +2873,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
@@ -3187,7 +3197,7 @@ impl PaneRenderer for AssetLibraryPane {
println!("🎨 [ASSET_LIB] Checking for thumbnails to invalidate (pools: {:?})", shared.audio_pools_with_new_waveforms);
let mut invalidated_any = false;
for (asset_id, clip) in &document_arc.audio_clips {
if let lightningbeam_core::clip::AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
if let Some(audio_pool_index) = clip.resolved_audio_pool_index(None).as_ref() {
if shared.audio_pools_with_new_waveforms.contains(audio_pool_index) {
println!("❌ [ASSET_LIB] Invalidating thumbnail for asset {} (pool {})", asset_id, audio_pool_index);
self.thumbnail_cache.invalidate(asset_id);
@@ -1797,10 +1797,16 @@ impl InfopanelPane {
ui.label("Name:");
ui.label(&clip.name);
});
let take_count = clip.takes().map(|t| t.len()).unwrap_or(0);
let take_folder_label;
let type_name = match &clip.clip_type {
lightningbeam_core::clip::AudioClipType::Sampled { .. } => "Audio (Sampled)",
lightningbeam_core::clip::AudioClipType::Midi { .. } => "Audio (MIDI)",
lightningbeam_core::clip::AudioClipType::Recording => "Audio (Recording)",
lightningbeam_core::clip::AudioClipType::TakeFolder { .. } => {
take_folder_label = format!("Audio ({} takes)", take_count);
&take_folder_label
}
};
ui.horizontal(|ui| {
ui.label("Type:");
@@ -286,6 +286,15 @@ pub struct TimelinePane {
/// during the last `render_layers`. Used by `handle_input` (next frame) to snap the
/// playhead exactly to a keyframe when its diamond is clicked.
keyframe_diamond_hits: Vec<(egui::Rect, f64)>,
/// Take-badge click targets recorded during render: (badge rect, layer, instance, active take,
/// take count). Collected while painting, dispatched after — the usual two-phase pattern.
take_badge_hits: Vec<(egui::Rect, uuid::Uuid, uuid::Uuid, usize, usize)>,
/// The take-folder instance whose take menu is open, if any.
open_take_menu: Option<(uuid::Uuid, uuid::Uuid)>,
/// Seconds between the cycle region's start and where the current recording actually began.
/// Zero unless the user punched in mid-region. Used to line the live waveform preview up with
/// the region on each pass.
cycle_record_lead_secs: f64,
/// Total duration of the animation
duration: f64,
@@ -723,6 +732,9 @@ impl TimelinePane {
viewport_start_time: 0.0,
viewport_scroll_y: 0.0,
keyframe_diamond_hits: Vec::new(),
take_badge_hits: Vec::new(),
open_take_menu: None,
cycle_record_lead_secs: 0.0,
duration: 10.0, // Default 10 seconds
is_scrubbing: false,
cycle_drag: None,
@@ -1049,7 +1061,41 @@ impl TimelinePane {
true
});
let start_time = *shared.playback_time;
let mut start_time = *shared.playback_time;
// With a cycle region armed, a recording is anchored at the REGION start rather than the
// playhead: every take spans the whole region, so the clip has to as well.
//
// Two ways in. From stopped, we also move the playhead to the region start, so recording
// begins with the loop (the count-in below then rolls in from a measure before it). Punching
// in while already rolling leaves the playhead where it is — the backend prepends silence to
// take 1's head to fill the gap back to the region start.
let cycle_start_secs = {
let doc = shared.action_executor.document();
match (doc.cycle_enabled, doc.cycle_region) {
(true, Some((ls, le))) if le > ls => {
Some(doc.tempo_map().beats_to_seconds(ls).seconds_to_f64())
}
_ => None,
}
};
if let Some(ls_secs) = cycle_start_secs {
// How far into the region we punched in (zero when starting from stopped, since we jump
// the playhead to the region start below). The live waveform preview needs this to know
// where each pass begins inside the recording buffer.
self.cycle_record_lead_secs = if *shared.is_playing {
(*shared.playback_time - ls_secs).max(0.0)
} else {
0.0
};
start_time = ls_secs;
if !*shared.is_playing {
if let Some(controller_arc) = shared.audio_controller {
controller_arc.lock().unwrap().seek(Seconds(ls_secs));
}
*shared.playback_time = ls_secs;
}
}
// Count-in: seek back N beats, start transport + metronome, defer ALL recording commands.
// Must happen before Step 4 so no clips or backend recordings are created yet.
@@ -1594,6 +1640,101 @@ impl TimelinePane {
painter.rect_filled(band, 2.0, fill);
}
/// Click handling + dropdown for the take badge painted on take-folder clips.
///
/// Runs after rendering, off the hit rects collected during it: clicking a badge opens (or
/// closes) a list of the clip's takes, and picking one dispatches `SetActiveTakeAction`.
/// Selection is per-*instance*, so doing this to one half of a split clip and something else to
/// the other half is exactly how you comp.
fn render_take_menu(
&mut self,
ui: &mut egui::Ui,
document: &lightningbeam_core::document::Document,
pending_actions: &mut Vec<Box<dyn lightningbeam_core::action::Action>>,
) {
let click = ui.input(|i| {
i.pointer
.primary_pressed()
.then(|| i.pointer.interact_pos())
.flatten()
});
if let Some(pos) = click {
if let Some((_, layer_id, instance_id, _, _)) =
self.take_badge_hits.iter().find(|(r, ..)| r.contains(pos))
{
let key = (*layer_id, *instance_id);
// Clicking the badge of the open menu closes it again.
self.open_take_menu = (self.open_take_menu != Some(key)).then_some(key);
}
}
let Some((layer_id, instance_id)) = self.open_take_menu else {
return;
};
// The badge is only in the hit list while it's on screen; if the clip scrolled away, the
// menu has nothing to hang off, so drop it.
let Some((badge, _, _, active, count)) = self
.take_badge_hits
.iter()
.find(|(_, l, i, _, _)| *l == layer_id && *i == instance_id)
.copied()
else {
self.open_take_menu = None;
return;
};
// The instance's *stored* selection, which is what rollback must restore — not `active`,
// which is that value clamped for display.
let old_take = document
.get_layer(&layer_id)
.and_then(|l| match l {
lightningbeam_core::layer::AnyLayer::Audio(al) => {
al.clip_instances.iter().find(|ci| ci.id == instance_id)
}
_ => None,
})
.and_then(|ci| ci.active_take);
let mut close = false;
let area = egui::Area::new(ui.id().with(("take_menu", instance_id)))
.order(egui::Order::Foreground)
.fixed_pos(egui::pos2(badge.min.x, badge.max.y + 2.0))
.show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
for i in 0..count {
let is_active = i == active;
if ui
.selectable_label(is_active, format!("Take {}", i + 1))
.clicked()
{
if !is_active {
pending_actions.push(Box::new(
lightningbeam_core::actions::SetActiveTakeAction::new(
layer_id,
instance_id,
i,
old_take,
),
));
}
close = true;
}
}
});
});
// A press anywhere outside the menu (and outside the badge, which toggles) dismisses it.
if let Some(pos) = click {
if !badge.contains(pos) && !area.response.rect.contains(pos) {
close = true;
}
}
if close {
self.open_take_menu = None;
}
}
/// Convert time (seconds) to pixel x-coordinate
fn time_to_x(&self, time: f64) -> f32 {
((time - self.viewport_start_time) * self.pixels_per_second as f64) as f32
@@ -2896,6 +3037,7 @@ impl TimelinePane {
let mut pending_lane_renders: Vec<AutomationLaneRender> = Vec::new();
// Rebuilt each frame; consumed by handle_input (next frame) for click-to-seek.
self.keyframe_diamond_hits.clear();
self.take_badge_hits.clear();
// Collect video clip rects for hover detection (to avoid borrow conflicts)
let mut video_clip_hovers: Vec<(egui::Rect, uuid::Uuid, f64, f32)> = Vec::new();
@@ -3801,9 +3943,11 @@ impl TimelinePane {
// AUDIO VISUALIZATION: Draw piano roll or waveform overlay
if let lightningbeam_core::layer::AnyLayer::Audio(_) = layer {
if let Some(clip) = document.get_audio_clip(&clip_instance.clip_id) {
match &clip.clip_type {
// Resolve through the instance's active take, so a take folder draws
// whichever take it actually plays.
match &clip.resolve(clip_instance.active_take) {
// MIDI: Draw piano roll (with loop iterations)
lightningbeam_core::clip::AudioClipType::Midi { midi_clip_id } => {
lightningbeam_core::clip::ResolvedContent::Midi { midi_clip_id } => {
if let Some(events) = midi_event_cache.get(midi_clip_id) {
// Calculate content window for loop detection
// preview_clip_duration accounts for TrimLeft/TrimRight drag previews
@@ -3862,7 +4006,7 @@ impl TimelinePane {
}
}
// Sampled Audio: Draw waveform via GPU
lightningbeam_core::clip::AudioClipType::Sampled { audio_pool_index } => {
lightningbeam_core::clip::ResolvedContent::Audio { audio_pool_index } => {
if let Some((samples, sr, ch)) = raw_audio_cache.get(audio_pool_index) {
// Min/max overview pools: 4 f32/texel at rate sr/B.
let minmax_b = waveform_minmax_pools.get(audio_pool_index).copied();
@@ -3991,7 +4135,7 @@ impl TimelinePane {
}
}
// Recording in progress: show live waveform
lightningbeam_core::clip::AudioClipType::Recording => {
lightningbeam_core::clip::ResolvedContent::Recording => {
let rec_pool_idx = usize::MAX;
if let Some((samples, sr, ch)) = raw_audio_cache.get(&rec_pool_idx) {
let total_frames = samples.len() / (*ch).max(1) as usize;
@@ -4026,6 +4170,36 @@ impl TimelinePane {
egui::pos2(clip_screen_end.min(clip_rect.max.x), clip_rect.max.y),
);
// Cycle recording: the clip covers ONE region, but the
// recorded buffer keeps growing across passes. Show the
// *current* pass by offsetting into the buffer to where
// that pass began, so the waveform restarts at the region
// start on each wrap and fills in behind the playhead —
// rather than running on past the clip's end.
//
// The playhead gives the position within the region
// directly, so a punch-in (whose first pass starts partway
// in) needs no extra bookkeeping here.
let mut rec_trim_start = preview_trim_start;
if let (true, Some((ls, le))) = (document.cycle_enabled, document.cycle_region) {
let tm = document.tempo_map();
let loop_len = (tm.beats_to_seconds(le)
- tm.beats_to_seconds(ls))
.seconds_to_f64();
if loop_len > 0.0 {
// Which pass we're on, straight from how much
// audio has been captured. Deriving this from
// the playhead instead would jitter: the
// playhead and the recording buffer advance on
// different clocks, so their difference wobbles
// frame to frame and the waveform slides
// horizontally.
let lead = self.cycle_record_lead_secs;
let pass = ((lead + audio_file_duration) / loop_len).floor();
rec_trim_start = (pass * loop_len - lead).max(0.0);
}
}
if waveform_rect.width() > 0.0 && waveform_rect.height() > 0.0 {
let instance_id = clip_instance.id.as_u128() as u64;
let callback = crate::waveform_gpu::WaveformCallback {
@@ -4038,7 +4212,7 @@ impl TimelinePane {
audio_duration: audio_file_duration as f32,
sample_rate: *sr as f32,
clip_start_time: clip_screen_start,
trim_start: preview_trim_start as f32,
trim_start: rec_trim_start as f32,
tex_width: crate::waveform_gpu::tex_width() as f32,
total_frames: total_frames as f32,
segment_start_frame: 0.0,
@@ -4152,6 +4326,68 @@ impl TimelinePane {
);
}
}
// Take badge — "Take 2/4" in the clip's bottom-left, on take-folder clips
// only. Records a hit rect so the click that opens the take menu can be
// dispatched after rendering (the usual two-phase pattern), rather than
// mutating the document mid-paint.
if let Some(take_count) = document
.get_audio_clip(&clip_instance.clip_id)
.and_then(|c| c.takes().map(|t| t.len()))
.filter(|n| *n > 0)
{
let active = clip_instance.active_take.unwrap_or(0).min(take_count - 1);
let label = format!("Take {}/{}", active + 1, take_count);
let text_color = theme.text_color(
&["#timeline", ".take-badge"],
ui.ctx(),
egui::Color32::WHITE,
);
let galley = painter.layout_no_wrap(
label,
egui::FontId::proportional(10.0),
text_color,
);
let pad = egui::vec2(4.0, 2.0);
let size = galley.size() + pad * 2.0;
// Bottom-left of the clip, but only when the clip is wide enough that
// the badge wouldn't swamp it.
if clip_rect.width() > size.x + 10.0 && clip_rect.height() > size.y + 4.0 {
let badge = egui::Rect::from_min_size(
egui::pos2(
clip_rect.min.x + 4.0,
clip_rect.max.y - size.y - 3.0,
),
size,
);
let hovered = ui
.ctx()
.pointer_hover_pos()
.is_some_and(|p| badge.contains(p));
let bg = if hovered {
theme.bg_color(
&["#timeline", ".take-badge:hover"],
ui.ctx(),
egui::Color32::from_black_alpha(210),
)
} else {
theme.bg_color(
&["#timeline", ".take-badge"],
ui.ctx(),
egui::Color32::from_black_alpha(150),
)
};
painter.rect_filled(badge, 3.0, bg);
painter.galley(badge.min + pad, galley, text_color);
self.take_badge_hits.push((
badge,
layer.id(),
clip_instance.id,
active,
take_count,
));
}
}
}
}
}
@@ -4631,7 +4867,12 @@ impl TimelinePane {
if !alt_held && !self.is_scrubbing && !self.is_panning {
if response.drag_started() {
// Use cached mousedown position for edge detection
if let Some(mousedown_pos) = self.mousedown_pos {
if let Some(mousedown_pos) = self
.mousedown_pos
// A press that landed on a take badge is opening the take menu, not grabbing
// the clip it sits on.
.filter(|p| !self.take_badge_hits.iter().any(|(r, ..)| r.contains(*p)))
{
if let Some((drag_type, clip_id)) = self.detect_clip_at_pointer(
mousedown_pos,
document,
@@ -6051,6 +6292,8 @@ impl PaneRenderer for TimelinePane {
editing_clip_id.as_ref(),
);
self.render_take_menu(ui, document, shared.pending_actions);
// Render automation lanes AFTER handle_input so our ui.interact registers last and wins
// egui's interaction priority over handle_input's full-content-area allocation.
// All automation lanes use beats as the x-axis; convert via the tempo map.