Merge take management into painting UX branch

Conflicts were almost all upstream's take work inserting code next to
lines our earlier cycle-recording commits had touched, plus one API
change we had to follow:

- ClipInstance trim access changed (ci.trim_start -> a ci_trim_start
  local; trim_end now needs .raw()). Took upstream's form throughout
  timeline.rs; the already-merged lines around each hunk were using it,
  so keeping ours would not have compiled.
- recording.rs wrap_at_cycle now bumps current_pass after
  close_active_notes, so a note held across the boundary has its tail
  attributed to the pass that's ending and its re-opened half to the one
  beginning. Upstream's version is a superset of ours.
- Kept our headers-only timeline mode (drop the track area below 1.5x the
  layer-header width); upstream had not touched that block.

Everything else (TRASH glyph, take actions, SetCycleMidiSeparateTakes,
engine cycle-MIDI plumbing, render_take_menu) was purely additive.

Workspace compiles; daw-backend's 32 tests pass, including the cycle and
MIDI take-slicing suites that sit directly on the resolved code.
This commit is contained in:
Skyler Lehmkuhl
2026-07-14 13:27:01 -04:00
36 changed files with 3688 additions and 774 deletions
@@ -35,6 +35,18 @@ pub struct AppConfig {
#[serde(default = "defaults::audio_buffer_size")]
pub audio_buffer_size: u32,
/// How a cycle MIDI recording treats its passes.
///
/// `false` (default) = **merge**: every pass overdubs into one clip, and earlier passes play back
/// as you record so you can layer against them. `true` = **separate takes**: each pass becomes
/// its own take in a take folder, exactly as audio always does, and earlier passes stay silent
/// (they're alternatives, not layers).
///
/// Only applies when the transport actually wraps; a recording that stops inside the first pass
/// is an ordinary single recording either way.
#[serde(default = "defaults::cycle_midi_separate_takes")]
pub cycle_midi_separate_takes: bool,
/// Reopen last session on startup
#[serde(default = "defaults::reopen_last_session")]
pub reopen_last_session: bool,
@@ -131,6 +143,7 @@ impl Default for AppConfig {
file_height: defaults::file_height(),
scroll_speed: defaults::scroll_speed(),
audio_buffer_size: defaults::audio_buffer_size(),
cycle_midi_separate_takes: defaults::cycle_midi_separate_takes(),
reopen_last_session: defaults::reopen_last_session(),
restore_layout_from_file: defaults::restore_layout_from_file(),
debug: defaults::debug(),
@@ -342,6 +355,7 @@ mod defaults {
pub fn file_height() -> u32 { 600 }
pub fn scroll_speed() -> f64 { 1.0 }
pub fn audio_buffer_size() -> u32 { 256 }
pub fn cycle_midi_separate_takes() -> bool { false }
pub fn reopen_last_session() -> bool { false }
pub fn restore_layout_from_file() -> bool { true }
pub fn debug() -> bool { false }
@@ -1064,7 +1064,12 @@ fn composite_document_to_hdr(
}
let tempo_map = document.tempo_map();
let effect_end_beats = effect_instance.timeline_start
+ effect_instance.effective_duration(daw_backend::Seconds(lightningbeam_core::effect::EFFECT_DURATION), tempo_map);
+ effect_instance.effective_duration(
lightningbeam_core::clip::ClipDuration::Seconds(daw_backend::Seconds(
lightningbeam_core::effect::EFFECT_DURATION,
)),
tempo_map,
);
let effect_inst = lightningbeam_core::effect::EffectInstance::new(
effect_def,
tempo_map.beats_to_seconds(effect_instance.timeline_start).seconds_to_f64(),
@@ -1105,6 +1105,23 @@ impl EditingContext {
}
}
/// A finished cycle recording whose takes belong to a take folder that already exists at that
/// region, queued for [`EditorApp::append_cycle_takes`].
struct PendingTakeAppend {
layer_id: Uuid,
/// The throwaway clip + instance the recording itself was captured into.
recording_instance_id: Uuid,
recording_clip_id: Uuid,
/// The recording's backend clip, which has to be torn down or it keeps playing alongside the
/// take folder we're appending to. Carried explicitly rather than looked up in
/// `clip_instance_to_backend_map`, because on the audio path the recording instance isn't in
/// that map yet — it's only added after promotion, which the append path skips.
recording_backend_id: Option<lightningbeam_core::action::BackendClipInstanceId>,
loop_start: Beats,
loop_len: Beats,
takes: Vec<lightningbeam_core::clip::AudioTake>,
}
struct EditorApp {
layouts: Vec<LayoutDefinition>,
current_layout_index: usize,
@@ -1212,6 +1229,10 @@ struct EditorApp {
metronome_enabled: bool, // Whether metronome clicks during recording
count_in_enabled: bool, // Whether count-in fires before recording
recording_clips: HashMap<Uuid, u32>, // layer_id -> backend clip_id during recording
/// Cycle takes waiting to be folded into an existing take folder. Queued from the audio-event
/// loop (which holds a borrow on the event queue, so it can't call a `&mut self` method) and
/// drained just after it.
pending_take_appends: Vec<PendingTakeAppend>,
recording_start_time: f64, // Playback time when recording started
recording_layer_ids: Vec<Uuid>, // Layers being recorded to (for creating clips)
// Asset drag-and-drop state
@@ -1583,6 +1604,7 @@ impl EditorApp {
metronome_enabled: false, // Metronome off by default
count_in_enabled: false, // Count-in off by default
recording_clips: HashMap::new(), // No active recording clips
pending_take_appends: Vec::new(),
recording_start_time: 0.0, // Will be set when recording starts
recording_layer_ids: Vec::new(), // Will be populated when recording starts
dragging_asset: None, // No asset being dragged initially
@@ -2038,6 +2060,91 @@ impl EditorApp {
/// 2. For MIDI: Loads the default instrument
/// 3. Stores the bidirectional mapping
/// 4. Syncs any existing clips on the layer
/// Fold freshly-recorded cycle takes into an existing take folder covering the same region, if
/// there is one. Returns true if it did.
///
/// Recording more takes over a region you've already recorded should extend that folder, not
/// stack a second clip on top of it — otherwise the new takes are stranded in an overlapping
/// clip and you can't audition them against the ones already there.
///
/// The in-progress recording's own clip and instance are throwaway scaffolding in this case (the
/// takes themselves already live in the backend pools), so they're discarded. They were never
/// committed as an action, so there's nothing on the undo stack to unwind — the single
/// `AppendTakesAction` is the whole undoable step.
fn append_cycle_takes(
&mut self,
layer_id: uuid::Uuid,
recording_instance_id: uuid::Uuid,
recording_clip_id: uuid::Uuid,
recording_backend_id: Option<lightningbeam_core::action::BackendClipInstanceId>,
loop_start: Beats,
loop_len: Beats,
takes: Vec<lightningbeam_core::clip::AudioTake>,
) -> bool {
let Some(target_instance_id) = self.action_executor.document().take_folder_at(
&layer_id,
loop_start,
loop_len,
&recording_instance_id,
) else {
return false;
};
// Tear down the recording's own backend clip. Without this it keeps playing on top of the
// take folder we're appending to — two takes sounding at once. The target instance's clip is
// separately repointed at the new active take by the action's backend sync below.
let backend_id = recording_backend_id
.or_else(|| self.clip_instance_to_backend_map.remove(&recording_instance_id));
self.clip_instance_to_backend_map.remove(&recording_instance_id);
let track_id = self.layer_to_track_map.get(&layer_id).copied();
if let (Some(backend_id), Some(track_id), Some(controller_arc)) =
(backend_id, track_id, self.audio_controller.as_ref())
{
let mut controller = controller_arc.lock().unwrap();
match backend_id {
lightningbeam_core::action::BackendClipInstanceId::Audio(id) => {
controller.remove_audio_clip(track_id, id)
}
lightningbeam_core::action::BackendClipInstanceId::Midi(id) => {
controller.remove_midi_clip(track_id, id)
}
}
}
// Discard the scaffolding clip + instance.
{
let doc = self.action_executor.document_mut();
if let Some(AnyLayer::Audio(al)) = doc.get_layer_mut(&layer_id) {
al.clip_instances.retain(|ci| ci.id != recording_instance_id);
}
doc.audio_clips.remove(&recording_clip_id);
}
let action = lightningbeam_core::actions::AppendTakesAction::new(
layer_id,
target_instance_id,
takes,
);
if let Some(controller_arc) = self.audio_controller.clone() {
let mut controller = controller_arc.lock().unwrap();
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut *controller),
layer_to_track_map: &self.layer_to_track_map,
clip_instance_to_backend_map: &mut self.clip_instance_to_backend_map,
};
if let Err(e) = self
.action_executor
.execute_with_backend(Box::new(action), &mut backend_context)
{
eprintln!("Failed to append cycle takes: {}", e);
}
}
self.autosave.pending_event = true;
true
}
fn sync_audio_layers_to_backend(&mut self) {
use lightningbeam_core::layer::{AnyLayer, AudioLayerType};
@@ -2054,6 +2161,9 @@ impl EditorApp {
let mut controller = controller_arc.lock().unwrap();
controller.set_loop_region(region);
controller.set_loop_enabled(enabled);
// Cycle MIDI mode is a *preference*, not document state, so it rides along here
// rather than through an action.
controller.set_cycle_midi_separate_takes(self.config.cycle_midi_separate_takes);
}
}
@@ -2389,7 +2499,7 @@ impl EditorApp {
) -> Vec<uuid::Uuid> {
let mut result = Vec::new();
for instance in clip_instances {
if let Some(clip_duration) = document.get_clip_duration(&instance.clip_id) {
if let Some(clip_duration) = document.clip_trim_duration(&instance.clip_id) {
let effective_duration = instance.effective_duration(clip_duration, document.tempo_map());
let timeline_end = instance.timeline_start + effective_duration;
@@ -3278,7 +3388,9 @@ impl EditorApp {
let duplicates: Vec<lightningbeam_core::clip::ClipInstance> = clips_to_duplicate.iter().map(|original| {
let mut duplicate = original.clone();
duplicate.id = uuid::Uuid::new_v4();
let clip_duration = document.get_clip_duration(&original.clip_id).unwrap_or(Seconds(1.0));
let clip_duration = document
.clip_trim_duration(&original.clip_id)
.unwrap_or(ClipDuration::Seconds(Seconds(1.0)));
let effective_duration = original.effective_duration(clip_duration, document.tempo_map());
duplicate.timeline_start = original.timeline_start + effective_duration;
if let Some((new_clip_def_id, _)) = midi_clip_replacements.get(&original.clip_id) {
@@ -5479,7 +5591,7 @@ impl EditorApp {
// matches the video clip exactly).
let (_dur, sample_rate, channels) = controller
.get_pool_file_info(pool_index)
.unwrap_or((video_duration, 0, 0));
.unwrap_or((Seconds(video_duration), 0, 0));
drop(controller);
let audio_clip_name = format!("{} (Audio)", video_name);
@@ -6386,7 +6498,9 @@ impl eframe::App for EditorApp {
use daw_backend::AudioEvent;
match event {
AudioEvent::PlaybackPosition(time) => {
self.playback_time = time;
// `playback_time` is the UI's seconds playhead (see the timeline's
// seconds/beats model); unwrap at this boundary, not before it.
self.playback_time = time.seconds_to_f64();
}
AudioEvent::PlaybackStopped => {
self.is_playing = false;
@@ -6492,6 +6606,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) {
@@ -6503,6 +6636,158 @@ 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;
let new_takes: Vec<lightningbeam_core::clip::AudioTake> = takes
.iter()
.map(|&(pool_index, _)| lightningbeam_core::clip::AudioTake {
// Renumbered by the folder that ends up owning them.
name: String::new(),
content: lightningbeam_core::clip::TakeContent::Audio { audio_pool_index: pool_index },
})
.collect();
// If this region already holds a take folder, extend it rather
// than dropping a second clip on top. Queued and run just after
// this loop, which holds a borrow on the event queue.
if self.action_executor.document()
.take_folder_at(&layer_id, loop_start, loop_len_beats, &instance_id)
.is_some()
{
self.pending_take_appends.push(PendingTakeAppend {
layer_id,
recording_instance_id: instance_id,
recording_clip_id: clip_id,
// The engine's recording clip. It isn't in
// clip_instance_to_backend_map yet (that only happens on
// promotion, which we're skipping), so hand it over
// directly or it'll keep sounding alongside the folder.
recording_backend_id: Some(
lightningbeam_core::action::BackendClipInstanceId::Audio(backend_clip_id),
),
loop_start,
loop_len: loop_len_beats,
takes: new_takes,
});
self.recording_clips.retain(|_, &mut cid| cid != backend_clip_id);
ctx.request_repaint();
continue;
}
// Finalize the recording clip, and hang the takes off the INSTANCE.
{
let doc = self.action_executor.document_mut();
if let Some(clip) = doc.audio_clips.get_mut(&clip_id) {
// The clip's own content is take 1; the instance's take
// list overrides it with whichever take is active. Every
// take is exactly one cycle region long, so the clip's
// duration is the region.
clip.finalize_recording(
takes[0].0,
loop_len_seconds.seconds_to_f64(),
);
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;
// Audio take content is seconds, and each take spans
// exactly one cycle region.
inst.trim_start = daw_backend::ContentTime::ZERO;
inst.trim_end =
Some(daw_backend::ContentTime(loop_len_seconds.seconds_to_f64()));
inst.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();
inst.active_take = Some(last_take);
inst.recorded_loop_beats = Some(loop_len_beats);
}
}
}
// 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);
@@ -6528,6 +6813,7 @@ impl eframe::App for EditorApp {
let mut controller = controller_arc.lock().unwrap();
match controller.get_pool_file_info(pool_index) {
Ok((dur, _, _)) => {
let dur = dur.seconds_to_f64();
eprintln!("[AUDIO] Got duration from backend: {:.4}s", dur);
self.audio_duration_cache.insert(pool_index, dur);
dur
@@ -6561,7 +6847,7 @@ impl eframe::App for EditorApp {
None
}
})
.unwrap_or((uuid::Uuid::nil(), uuid::Uuid::nil(), Beats::ZERO, 0.0))
.unwrap_or((uuid::Uuid::nil(), uuid::Uuid::nil(), Beats::ZERO, daw_backend::ContentTime::ZERO))
};
if !clip_id.is_nil() {
@@ -6685,7 +6971,11 @@ impl eframe::App for EditorApp {
);
}
}
// Update the clip's duration so the timeline bar grows
// Update the clip's duration so the timeline bar grows. Once the
// transport has wrapped, the backend reports the whole cycle
// region here and keeps reporting it, so the bar grows through
// the first pass and then holds — every further pass merges into
// the same clip rather than extending it.
if let Some(clip) = self.action_executor.document_mut().audio_clips.get_mut(&doc_clip_id) {
clip.set_content_duration(ClipDuration::Beats(duration));
}
@@ -6705,6 +6995,144 @@ impl eframe::App for EditorApp {
}
ctx.request_repaint();
}
AudioEvent::MidiCycleRecordingStopped { track_id, clip_ids, loop_start, loop_len_beats } => {
println!("🎹 MIDI cycle recording stopped: {} takes", clip_ids.len());
// Pull every take's events into the cache — 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 &take_clip_id in &clip_ids {
if let Ok(data) = controller.query_midi_clip(track_id, take_clip_id) {
self.midi_event_cache.insert(take_clip_id, data.events);
}
}
}
let layer_id = self.track_to_layer_map.get(&track_id).copied();
if let (Some(layer_id), Some(&first_clip_id)) = (layer_id, clip_ids.first()) {
// The doc clip is the one the recording started on — which the backend
// reused as take 1.
let doc_clip_id = self.action_executor.document()
.audio_clip_by_midi_clip_id(first_clip_id)
.map(|(id, _)| id);
if let Some(doc_clip_id) = doc_clip_id {
self.autosave.pending_event = true;
let last_take = clip_ids.len() - 1;
let recording_instance_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.clip_id == doc_clip_id).map(|ci| ci.id)
} else { None });
let new_takes: Vec<lightningbeam_core::clip::AudioTake> = clip_ids
.iter()
.map(|&mid| lightningbeam_core::clip::AudioTake {
// Renumbered by the folder that ends up owning them.
name: String::new(),
content: lightningbeam_core::clip::TakeContent::Midi { midi_clip_id: mid },
})
.collect();
// If this region already holds a take folder, extend it rather
// than dropping a second clip on top. Queued and run just after
// this loop, which holds a borrow on the event queue.
let existing_folder = recording_instance_id.filter(|rec_inst| {
self.action_executor.document()
.take_folder_at(&layer_id, loop_start, loop_len_beats, rec_inst)
.is_some()
});
if let Some(rec_inst) = existing_folder {
self.pending_take_appends.push(PendingTakeAppend {
layer_id,
recording_instance_id: rec_inst,
recording_clip_id: doc_clip_id,
// The MIDI path maps its recording instance during
// MidiRecordingProgress, so the map has it.
recording_backend_id: None,
loop_start,
loop_len: loop_len_beats,
takes: new_takes,
});
self.recording_layer_ids.retain(|id| *id != layer_id);
self.recording_clips.remove(&layer_id);
if self.recording_layer_ids.is_empty() {
self.is_recording = false;
self.recording_clips.clear();
}
ctx.request_repaint();
continue;
}
{
let doc = self.action_executor.document_mut();
if let Some(clip) = doc.audio_clips.get_mut(&doc_clip_id) {
// The clip's own content stays take 1 (the clip the
// recording started on); the instance's take list
// overrides it with whichever take is active. MIDI takes
// are beats-domain and each spans one cycle region.
clip.set_content_duration(ClipDuration::Beats(loop_len_beats));
clip.name = format!("Cycle recording ({} takes)", clip_ids.len());
}
// Anchor to the region and select the most recent take.
// timeline_duration stays None on purpose — pinning it would
// make a later tempo change loop the take's content to fill
// the span instead of letting it drift naturally.
if let Some(AnyLayer::Audio(al)) = doc.get_layer_mut(&layer_id) {
if let Some(inst) = al.clip_instances.iter_mut().find(|ci| ci.clip_id == doc_clip_id) {
inst.timeline_start = loop_start;
inst.timeline_duration = None;
inst.trim_start = daw_backend::ContentTime::ZERO;
inst.trim_end = Some(daw_backend::ContentTime(loop_len_beats.beats_to_f64()));
inst.takes = clip_ids.iter().enumerate().map(|(i, &mid)| {
lightningbeam_core::clip::AudioTake {
name: format!("Take {}", i + 1),
content: lightningbeam_core::clip::TakeContent::Midi { midi_clip_id: mid },
}
}).collect();
inst.active_take = Some(last_take);
inst.recorded_loop_beats = Some(loop_len_beats);
}
}
}
// Commit the whole cycle-record session as ONE undoable action.
// The backend instance was mapped during MidiRecordingProgress and
// the engine already repointed it at the active take.
let instance = self.action_executor.document()
.get_layer(&layer_id)
.and_then(|l| if let AnyLayer::Audio(al) = l {
al.clip_instances.iter().find(|ci| ci.clip_id == doc_clip_id).cloned()
} else { None });
if let Some(instance) = instance {
match (self.layer_to_track_map.get(&layer_id).copied(),
self.clip_instance_to_backend_map.get(&instance.id).copied()) {
(Some(tid), Some(backend_id)) => {
let action = lightningbeam_core::actions::AddClipInstanceAction::already_applied(
layer_id, instance, tid, backend_id,
);
self.action_executor.push_applied(Box::new(action));
}
_ => self.media_modified = true,
}
}
}
}
// Clear recording state, same as the single-clip MIDI path.
if let Some(&layer_id) = self.track_to_layer_map.get(&track_id) {
self.recording_layer_ids.retain(|id| *id != layer_id);
self.recording_clips.remove(&layer_id);
}
if self.recording_layer_ids.is_empty() {
self.is_recording = false;
self.recording_clips.clear();
}
ctx.request_repaint();
}
AudioEvent::MidiRecordingStopped(track_id, clip_id, note_count) => {
println!("🎹 MIDI recording stopped: track={:?}, clip_id={}, {} notes",
track_id, clip_id, note_count);
@@ -6723,7 +7151,7 @@ impl eframe::App for EditorApp {
.map(|(id, _)| id);
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) {
clip.set_content_duration(ClipDuration::Beats(Beats(midi_clip_data.duration)));
clip.set_content_duration(ClipDuration::Beats(midi_clip_data.duration));
clip.name = format!("MIDI Recording {}", clip_id);
}
}
@@ -6851,6 +7279,20 @@ impl eframe::App for EditorApp {
}
// Cycle takes that landed on an existing take folder. Deferred out of the event loop above,
// which holds a borrow on the event queue and so can't call a `&mut self` method.
for req in std::mem::take(&mut self.pending_take_appends) {
self.append_cycle_takes(
req.layer_id,
req.recording_instance_id,
req.recording_clip_id,
req.recording_backend_id,
req.loop_start,
req.loop_len,
req.takes,
);
}
// Update input monitoring based on active layer (only send command when changed)
{
let should_monitor = self.audio_controller.is_some() && self.active_layer_id.map_or(false, |layer_id| {
@@ -7045,6 +7487,11 @@ impl eframe::App for EditorApp {
if result.buffer_size_changed {
println!("⚠️ Audio buffer size will be applied on next app restart");
}
// Cycle MIDI mode takes effect immediately — no restart needed, unlike the buffer size.
if let Some(ref controller_arc) = self.audio_controller {
let mut controller = controller_arc.lock().unwrap();
controller.set_cycle_midi_separate_takes(self.config.cycle_midi_separate_takes);
}
// Apply new keybindings if changed
if let Some(new_keymap) = result.new_keymap {
self.keymap = new_keymap;
@@ -43,6 +43,7 @@ pub const CHEVRONS_UP: &str = "\u{e074}";
pub const PLAY: &str = "\u{e13c}";
pub const PAUSE: &str = "\u{e12e}";
pub const REPEAT: &str = "\u{e146}"; // cycle / loop region toggle
pub const TRASH: &str = "\u{e18d}"; // delete a take
pub const SETTINGS: &str = "\u{e154}";
pub const SEARCH: &str = "\u{e151}";
pub const PLUS: &str = "\u{e13d}";
@@ -7,7 +7,7 @@
//! - Image Assets (static images)
use eframe::egui;
use lightningbeam_core::clip::{AudioClipType, VectorClip};
use lightningbeam_core::clip::{ResolvedContent, VectorClip};
use lightningbeam_core::document::Document;
use lightningbeam_core::layer::AnyLayer;
use std::collections::{HashMap, HashSet};
@@ -918,11 +918,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() {
ResolvedContent::Audio { .. } => ("Sampled".to_string(), DragClipType::AudioSampled),
ResolvedContent::Midi { .. } => ("MIDI".to_string(), DragClipType::AudioMidi),
ResolvedContent::Recording => {
// Skip recording-in-progress clips (and empty take folders) from asset library
continue;
}
};
@@ -1118,15 +1118,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 { .. } => {
let (extra_info, drag_clip_type) = match &clip.resolve() {
ResolvedContent::Audio { .. } => {
("Sampled".to_string(), DragClipType::AudioSampled)
}
AudioClipType::Midi { .. } => {
ResolvedContent::Midi { .. } => {
("MIDI".to_string(), DragClipType::AudioMidi)
}
AudioClipType::Recording => {
// Skip recording-in-progress clips
ResolvedContent::Recording => {
// Skip recording-in-progress clips (and empty take folders)
continue;
}
};
@@ -1765,7 +1765,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.audio_pool_index().as_ref() {
shared.raw_audio_cache.get(audio_pool_index)
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize))
} else {
@@ -1790,8 +1790,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() {
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 +1799,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 +1807,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 +2344,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() {
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 +2355,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 +2363,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
@@ -2481,8 +2481,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() {
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 +2492,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 +2500,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
@@ -2802,7 +2802,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.audio_pool_index().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 +2842,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() {
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 +2853,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 +2863,7 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
@@ -3187,7 +3187,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.audio_pool_index().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);
@@ -1590,8 +1590,12 @@ impl InfopanelPane {
ui.label(format!("{:.2}s", document.tempo_map().beats_to_seconds(ci.effective_start()).seconds_to_f64()));
});
let clip_dur = document.get_clip_duration(&ci.clip_id)
.unwrap_or_else(|| daw_backend::Seconds(ci.trim_end.unwrap_or(1.0) - ci.trim_start));
let clip_dur = document.clip_trim_duration(&ci.clip_id)
.unwrap_or_else(|| lightningbeam_core::clip::ClipDuration::Seconds(
daw_backend::Seconds(
(ci.trim_end.unwrap_or(daw_backend::ContentTime(1.0)) - ci.trim_start).raw(),
),
));
let total_dur = ci.total_duration(clip_dur, document.tempo_map());
let total_dur_secs = (document.tempo_map().beats_to_seconds(ci.effective_start() + total_dur)
- document.tempo_map().beats_to_seconds(ci.effective_start())).seconds_to_f64();
@@ -1600,10 +1604,16 @@ impl InfopanelPane {
ui.label(format!("{:.2}s", total_dur_secs));
});
if ci.trim_start > 0.0 {
if ci.trim_start > daw_backend::ContentTime::ZERO {
ui.horizontal(|ui| {
ui.label("Trim Start:");
ui.label(format!("{:.2}s", ci.trim_start));
// Content time in the clip's own domain: seconds for sampled
// audio/video/vector, beats for MIDI. Label it accordingly.
let unit = match clip_dur {
lightningbeam_core::clip::ClipDuration::Beats(_) => "beats",
lightningbeam_core::clip::ClipDuration::Seconds(_) => "s",
};
ui.label(format!("{:.2}{}", ci.trim_start.raw(), unit));
});
}
@@ -465,9 +465,13 @@ impl PianoRollPane {
if let Some(AnyLayer::Audio(audio_layer)) = document.get_layer(&layer_id) {
for instance in &audio_layer.clip_instances {
if let Some(clip) = document.audio_clips.get(&instance.clip_id) {
if let AudioClipType::Midi { midi_clip_id } = clip.clip_type {
let duration = instance.effective_duration(clip.content_duration().to_seconds(document.tempo_map()), document.tempo_map());
clip_data.push((midi_clip_id, instance.timeline_start.beats_to_f64(), instance.trim_start, duration.beats_to_f64(), instance.id));
// Resolve through the instance's active take, so a MIDI take folder edits
// whichever take it's actually playing.
if let Some(midi_clip_id) = instance.resolved_midi_clip_id(clip) {
let duration = instance.effective_duration(clip.content_duration(), document.tempo_map());
// A MIDI clip's content time IS beats, which is what the piano roll's
// x-axis uses.
clip_data.push((midi_clip_id, instance.timeline_start.beats_to_f64(), instance.trim_start.raw(), duration.beats_to_f64(), instance.id));
}
}
}
@@ -2463,7 +2467,8 @@ impl PianoRollPane {
});
// Get sample rate from raw_audio_cache
if let Some((_samples, sr, _ch)) = shared.raw_audio_cache.get(&audio_pool_index) {
clip_infos.push((audio_pool_index, instance.timeline_start.beats_to_f64(), instance.trim_start, duration.beats_to_f64(), *sr));
// A sampled clip's content time is seconds.
clip_infos.push((audio_pool_index, instance.timeline_start.beats_to_f64(), instance.trim_start.raw(), duration.beats_to_f64(), *sr));
}
}
}
@@ -6,7 +6,7 @@
use eframe::egui;
use daw_backend::Seconds;
use lightningbeam_core::action::Action;
use lightningbeam_core::clip::ClipInstance;
use lightningbeam_core::clip::{ClipDuration, ClipInstance};
use lightningbeam_core::gpu::{BufferPool, BufferFormat, BufferSpec, Compositor, EffectProcessor, SrgbToLinearConverter};
use lightningbeam_core::layer::{AnyLayer, AudioLayer};
use lightningbeam_core::renderer::RenderedLayerType;
@@ -1854,7 +1854,10 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// For now, create a simple effect instance with default parameters
let tempo_map = self.ctx.document.tempo_map();
let effect_end_beats = effect_instance.timeline_start
+ effect_instance.effective_duration(Seconds(lightningbeam_core::effect::EFFECT_DURATION), tempo_map);
+ effect_instance.effective_duration(
ClipDuration::Seconds(Seconds(lightningbeam_core::effect::EFFECT_DURATION)),
tempo_map,
);
let effect_inst = lightningbeam_core::effect::EffectInstance::new(
effect_def,
tempo_map.beats_to_seconds(effect_instance.timeline_start).seconds_to_f64(),
@@ -2209,7 +2212,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// Calculate clip bounds for preview
let start_secs = self.ctx.document.tempo_map().beats_to_seconds(clip_inst.timeline_start).seconds_to_f64();
let clip_time = ((self.ctx.playback_time - start_secs) * clip_inst.playback_speed) + clip_inst.trim_start;
let clip_time = ((self.ctx.playback_time - start_secs) * clip_inst.playback_speed) + clip_inst.trim_start.raw();
let content_bounds = if let Some(vector_clip) = self.ctx.document.get_vector_clip(&clip_inst.clip_id) {
vector_clip.calculate_content_bounds(&self.ctx.document, clip_time)
} else if let Some(video_clip) = self.ctx.document.get_video_clip(&clip_inst.clip_id) {
@@ -2299,7 +2302,9 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
for &clip_id in self.ctx.selection.clip_instances() {
if let Some(clip_instance) = vector_layer.clip_instances.iter().find(|ci| ci.id == clip_id) {
// Skip clip instances not active at current time (compare in seconds).
let clip_dur = self.ctx.document.get_clip_duration(&clip_instance.clip_id).unwrap_or(Seconds::ZERO);
let clip_dur = ClipDuration::Seconds(
self.ctx.document.get_clip_duration(&clip_instance.clip_id).unwrap_or(Seconds::ZERO),
);
let tempo_map = self.ctx.document.tempo_map();
let start_secs = tempo_map.beats_to_seconds(clip_instance.timeline_start).seconds_to_f64();
let instance_end = tempo_map.beats_to_seconds(
@@ -2310,7 +2315,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
}
// Calculate clip-local time
let clip_time = ((self.ctx.playback_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
let clip_time = ((self.ctx.playback_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start.raw();
// Get dynamic clip bounds from content at current time
let bbox = if let Some(vector_clip) = self.ctx.document.get_vector_clip(&clip_instance.clip_id) {
@@ -2680,7 +2685,9 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// Find clip instance visible at playback time
let visible_clip = video_layer.clip_instances.iter().find(|inst| {
let clip_duration = self.ctx.document.get_clip_duration(&inst.clip_id).unwrap_or(Seconds::ZERO);
let clip_duration = ClipDuration::Seconds(
self.ctx.document.get_clip_duration(&inst.clip_id).unwrap_or(Seconds::ZERO),
);
let tempo_map = self.ctx.document.tempo_map();
let start_secs = tempo_map.beats_to_seconds(inst.timeline_start).seconds_to_f64();
let end_secs = tempo_map.beats_to_seconds(inst.timeline_start + inst.effective_duration(clip_duration, tempo_map)).seconds_to_f64();
@@ -10153,7 +10160,7 @@ impl StagePane {
if let Some(clip_instance) = vector_layer.clip_instances.iter().find(|ci| ci.id == clip_id) {
// Calculate clip-local time
let start_secs = shared.action_executor.document().tempo_map().beats_to_seconds(clip_instance.timeline_start).seconds_to_f64();
let clip_time = ((*shared.playback_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
let clip_time = ((*shared.playback_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start.raw();
// Get dynamic clip bounds from content at current time
use vello::kurbo::Rect as KurboRect;
@@ -10354,7 +10361,7 @@ impl StagePane {
if let Some(clip_instance) = vector_layer.clip_instances.iter().find(|ci| ci.id == object_id) {
// Calculate clip-local time
let start_secs = shared.action_executor.document().tempo_map().beats_to_seconds(clip_instance.timeline_start).seconds_to_f64();
let clip_time = ((*shared.playback_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
let clip_time = ((*shared.playback_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start.raw();
// Get dynamic clip bounds from content at current time
let local_bbox = if let Some(vector_clip) = shared.action_executor.document().get_vector_clip(&clip_instance.clip_id) {
@@ -11070,7 +11077,9 @@ impl StagePane {
let document = shared.action_executor.document();
if let Some(AnyLayer::Video(video_layer)) = document.get_layer(layer_id) {
video_layer.clip_instances.iter().find(|inst| {
let clip_duration = document.get_clip_duration(&inst.clip_id).unwrap_or(Seconds::ZERO);
let clip_duration = ClipDuration::Seconds(
document.get_clip_duration(&inst.clip_id).unwrap_or(Seconds::ZERO),
);
let tempo_map = document.tempo_map();
let start_secs = tempo_map.beats_to_seconds(inst.timeline_start).seconds_to_f64();
let end_secs = tempo_map.beats_to_seconds(inst.timeline_start + inst.effective_duration(clip_duration, tempo_map)).seconds_to_f64();
@@ -7,8 +7,8 @@
/// - Basic layer visualization
use eframe::egui;
use daw_backend::{Beats, Seconds};
use lightningbeam_core::clip::ClipInstance;
use daw_backend::{Beats, ContentTime, Seconds};
use lightningbeam_core::clip::{ClipDuration, ClipInstance};
use lightningbeam_core::layer::{AnyLayer, AudioLayerType, GroupLayer, LayerTrait};
use crate::mobile::icons;
use super::{DragClipType, NodePath, PaneRenderer, SharedPaneState};
@@ -116,7 +116,7 @@ fn compute_clip_stacking(
let tempo_map = document.tempo_map();
// Stacking only needs relative overlap, so compare in the beats domain.
let ranges: Vec<(f64, f64)> = clip_instances.iter().map(|ci| {
let clip_dur = effective_clip_duration(document, layer, ci).unwrap_or(Seconds::ZERO);
let clip_dur = effective_clip_duration(document, layer, ci).unwrap_or(ClipDuration::Seconds(Seconds::ZERO));
let start = ci.effective_start();
let end = start + ci.total_duration(clip_dur, tempo_map);
(start.beats_to_f64(), end.beats_to_f64())
@@ -230,11 +230,14 @@ fn draw_video_thumbnail_strip(
/// Get the effective clip duration for a clip instance on a given layer.
/// For groups on vector layers, the duration spans all consecutive keyframes
/// where the group is present. For regular clips, returns the clip's internal duration.
/// A clip's content duration **in its own domain** — seconds for vector/video/effect and sampled
/// audio, BEATS for MIDI. Returning a `ClipDuration` rather than bare `Seconds` is what lets the
/// instance's trim bounds (which are content times, in that same domain) be resolved correctly.
fn effective_clip_duration(
document: &lightningbeam_core::document::Document,
layer: &AnyLayer,
clip_instance: &ClipInstance,
) -> Option<Seconds> {
) -> Option<ClipDuration> {
match layer {
AnyLayer::Vector(vl) => {
let vc = document.get_vector_clip(&clip_instance.clip_id)?;
@@ -242,17 +245,21 @@ fn effective_clip_duration(
let frame_duration = 1.0 / document.framerate;
let start_secs = document.tempo_map().beats_to_seconds(clip_instance.timeline_start).seconds_to_f64();
let end = vl.group_visibility_end(&clip_instance.id, start_secs, frame_duration);
Some(Seconds((end - start_secs).max(0.0)))
Some(ClipDuration::Seconds(Seconds((end - start_secs).max(0.0))))
} else {
// Movie clips: duration based on all internal content (keyframes + clip instances)
document.get_clip_duration(&clip_instance.clip_id)
document.get_clip_duration(&clip_instance.clip_id).map(ClipDuration::Seconds)
}
}
// Delegate to get_clip_duration so MIDI clips (whose `duration` is stored in beats,
// not seconds) are converted correctly rather than read as raw seconds.
AnyLayer::Audio(_) => document.get_clip_duration(&clip_instance.clip_id),
AnyLayer::Video(_) => document.get_video_clip(&clip_instance.clip_id).map(|c| Seconds(c.duration)),
AnyLayer::Effect(_) => Some(Seconds(lightningbeam_core::effect::EFFECT_DURATION)),
// An audio layer can hold a sampled clip (seconds content) or a MIDI clip (beats content),
// so ask the clip which it is rather than flattening both to seconds.
AnyLayer::Audio(_) => document.clip_trim_duration(&clip_instance.clip_id),
AnyLayer::Video(_) => document
.get_video_clip(&clip_instance.clip_id)
.map(|c| ClipDuration::Seconds(Seconds(c.duration))),
AnyLayer::Effect(_) => Some(ClipDuration::Seconds(Seconds(
lightningbeam_core::effect::EFFECT_DURATION,
))),
AnyLayer::Group(_) => None,
AnyLayer::Raster(_) => None,
AnyLayer::Text(_) => None,
@@ -313,6 +320,18 @@ 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)>,
/// The (instance, take index) being renamed inline in the take menu.
renaming_take: Option<(uuid::Uuid, usize)>,
take_rename_buffer: String,
/// 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,
@@ -750,6 +769,11 @@ 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,
renaming_take: None,
take_rename_buffer: String::new(),
cycle_record_lead_secs: 0.0,
duration: 10.0, // Default 10 seconds
is_scrubbing: false,
cycle_drag: None,
@@ -874,7 +898,9 @@ impl TimelinePane {
.unwrap_or_default()
.iter()
.map(|k| crate::curve_editor::CurvePoint {
time: k.time, // beats (backend stores beats; curve editor x-axis is beats)
// The curve editor's x-axis is beats, same as the backend — unwrap at this
// boundary because CurvePoint stores a plain f64.
time: k.time.beats_to_f64(),
value: k.value,
interpolation: match k.interpolation.as_str() {
"bezier" => crate::curve_editor::CurveInterpolation::Bezier,
@@ -1076,7 +1102,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.
@@ -1120,6 +1180,28 @@ impl TimelinePane {
// The backend records in the beats domain; start_time is the seconds playhead.
let start_beats = shared.action_executor.document().tempo_map().seconds_to_beats(Seconds(start_time));
// Does this layer already hold takes over the cycle region? If so this recording is another
// take, however short it runs — without this, stopping before the loop came round would land
// it as a separate overlapping clip instead of joining the take list. The engine can't work
// this out for itself: whether takes exist is document state.
let force_takes: std::collections::HashMap<uuid::Uuid, bool> = {
let doc = shared.action_executor.document();
let region = match (doc.cycle_enabled, doc.cycle_region) {
(true, Some((ls, le))) if le > ls => Some((ls, le - ls)),
_ => None,
};
candidates
.iter()
.map(|&(layer_id, _, _)| {
let forced = region.is_some_and(|(loop_start, loop_len)| {
doc.take_folder_at(&layer_id, loop_start, loop_len, &uuid::Uuid::nil())
.is_some()
});
(layer_id, forced)
})
.collect()
};
// Step 4: Dispatch recording for each candidate
for &(layer_id, ref cat, _) in &candidates {
match cat {
@@ -1143,7 +1225,7 @@ impl TimelinePane {
}
if let Some(controller_arc) = shared.audio_controller {
let mut controller = controller_arc.lock().unwrap();
controller.start_recording(track_id, start_beats);
controller.start_recording(track_id, start_beats, force_takes.get(&layer_id).copied().unwrap_or(false));
println!("🎤 Started audio recording on track {:?} at {:.2}s", track_id, start_time);
}
shared.recording_layer_ids.push(layer_id);
@@ -1156,7 +1238,7 @@ impl TimelinePane {
if let Some(controller_arc) = shared.audio_controller {
let mut controller = controller_arc.lock().unwrap();
let clip_id = controller.create_midi_clip(track_id, start_beats, Beats::ZERO);
controller.start_midi_recording(track_id, clip_id, start_beats);
controller.start_midi_recording(track_id, clip_id, start_beats, force_takes.get(&layer_id).copied().unwrap_or(false));
shared.recording_clips.insert(layer_id, clip_id);
println!("🎹 Started MIDI recording on track {:?} at {:.2}s, clip_id={}",
track_id, start_time, clip_id);
@@ -1422,8 +1504,10 @@ impl TimelinePane {
let tempo_map = document.tempo_map();
for (_child_layer_id, ci) in &child_clips {
let clip_dur = document.get_clip_duration(&ci.clip_id).unwrap_or_else(|| {
Seconds(ci.trim_end.unwrap_or(1.0) - ci.trim_start)
let clip_dur = document.clip_trim_duration(&ci.clip_id).unwrap_or_else(|| {
ClipDuration::Seconds(Seconds(
(ci.trim_end.unwrap_or(ContentTime(1.0)) - ci.trim_start).raw(),
))
});
let start = ci.effective_start();
let end = start + ci.total_duration(clip_dur, tempo_map);
@@ -1621,6 +1705,138 @@ 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;
};
let Some(instance) = 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,
})
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 = instance.active_take;
let take_names: Vec<String> = instance.takes.iter().map(|t| t.name.clone()).collect();
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;
let renaming = self.renaming_take == Some((instance_id, i));
ui.horizontal(|ui| {
if renaming {
let edit = ui.add(
egui::TextEdit::singleline(&mut self.take_rename_buffer)
.desired_width(110.0),
);
edit.request_focus();
// Commit on Enter or on clicking away; Escape abandons.
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
let escape = ui.input(|i| i.key_pressed(egui::Key::Escape));
if enter || edit.lost_focus() && !escape {
let name = self.take_rename_buffer.trim().to_string();
if !name.is_empty() && name != take_names[i] {
pending_actions.push(Box::new(
lightningbeam_core::actions::RenameTakeAction::new(
layer_id, instance_id, i, name,
),
));
}
self.renaming_take = None;
} else if escape {
self.renaming_take = None;
}
return;
}
let label = ui.selectable_label(is_active, &take_names[i]);
if label.clicked() {
if !is_active {
pending_actions.push(Box::new(
lightningbeam_core::actions::SetActiveTakeAction::new(
layer_id, instance_id, i, old_take,
),
));
}
close = true;
}
// Double-click a take to rename it in place. Deleting lives on the clip's
// right-click menu, not here — a trash icon per row is a small target
// sitting right next to the one you actually meant to click.
if label.double_clicked() {
self.renaming_take = Some((instance_id, i));
self.take_rename_buffer = take_names[i].clone();
}
});
}
});
});
// 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;
self.renaming_take = 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
@@ -1642,15 +1858,18 @@ impl TimelinePane {
/// Effective on-timeline duration for a clip instance, in seconds.
///
/// `total_duration` is in beats; converts to seconds using the current (preview) BPM.
fn instance_display_duration(&self, ci: &lightningbeam_core::clip::ClipInstance, clip_dur_secs: Seconds, tempo_map: &daw_backend::TempoMap) -> f64 {
(tempo_map.beats_to_seconds(ci.timeline_start + ci.total_duration(clip_dur_secs, tempo_map))
fn instance_display_duration(&self, ci: &lightningbeam_core::clip::ClipInstance, clip_content: ClipDuration, tempo_map: &daw_backend::TempoMap) -> f64 {
(tempo_map.beats_to_seconds(ci.timeline_start + ci.total_duration(clip_content, tempo_map))
- tempo_map.beats_to_seconds(ci.effective_start())).seconds_to_f64()
}
/// Returns the clip content start (trim_start) and duration in display seconds.
fn content_display_range(&self, ci: &lightningbeam_core::clip::ClipInstance, clip_dur_secs: Seconds, _bpm: f64) -> (f64, f64) {
let trim_end = ci.trim_end.unwrap_or(clip_dur_secs.seconds_to_f64());
(ci.trim_start, (trim_end - ci.trim_start).max(0.0))
/// The clip's content start (trim_start) and window length, as raw magnitudes in the clip's own
/// content domain — seconds for audio/video/vector, beats for MIDI. The drag/preview math below
/// works in that domain throughout, converting to the timeline only at the edges.
fn content_display_range(&self, ci: &lightningbeam_core::clip::ClipInstance, clip_content: ClipDuration, _bpm: f64) -> (f64, f64) {
let trim_end = ci.trim_end.map_or(clip_content.native(), |t| t.raw());
let start = ci.trim_start.raw();
(start, (trim_end - start).max(0.0))
}
/// Convert pixel x-coordinate to time (seconds)
@@ -3011,6 +3230,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();
@@ -3228,8 +3448,10 @@ impl TimelinePane {
let is_move_drag = self.clip_drag_state == Some(ClipDragType::Move);
let mut ranges: Vec<(Beats, Beats)> = Vec::new();
for (_child_layer_id, ci) in &child_clips {
let clip_dur = document.get_clip_duration(&ci.clip_id).unwrap_or_else(|| {
Seconds(ci.trim_end.unwrap_or(1.0) - ci.trim_start)
let clip_dur = document.clip_trim_duration(&ci.clip_id).unwrap_or_else(|| {
ClipDuration::Seconds(Seconds(
(ci.trim_end.unwrap_or(ContentTime(1.0)) - ci.trim_start).raw(),
))
});
let mut start = ci.effective_start();
let dur = ci.total_duration(clip_dur, document.tempo_map());
@@ -3302,8 +3524,10 @@ impl TimelinePane {
if let Some(video_child) = g.children.iter().find(|c| matches!(c, AnyLayer::Video(_))) {
if let AnyLayer::Video(vl) = video_child {
for ci in &vl.clip_instances {
let clip_dur = document.get_clip_duration(&ci.clip_id)
.unwrap_or_else(|| Seconds(ci.trim_end.unwrap_or(1.0) - ci.trim_start));
let clip_dur = document.clip_trim_duration(&ci.clip_id)
.unwrap_or_else(|| ClipDuration::Seconds(Seconds(
(ci.trim_end.unwrap_or(ContentTime(1.0)) - ci.trim_start).raw(),
)));
let mut ci_start = ci.effective_start();
if is_move_drag && selection.contains_clip_instance(&ci.id) {
ci_start = self.moved_start(ci_start, document.tempo_map(), &document.time_signature, document.framerate);
@@ -3330,7 +3554,8 @@ impl TimelinePane {
);
// 4th elem = clip's TRUE (unclamped) origin x, for correct
// hover content time when scrolled partly off the left.
video_clip_hovers.push((hover_rect, ci.clip_id, ci.trim_start, rect.min.x + sx));
// Video content is wall-clock, so its content time IS seconds.
video_clip_hovers.push((hover_rect, ci.clip_id, ci.trim_start.raw(), rect.min.x + sx));
let thumb_display_height = (thumb_y_max - span_y_min) - 4.0;
if thumb_display_height > 8.0 {
@@ -3343,7 +3568,7 @@ impl TimelinePane {
&video_mgr,
&mut self.video_thumbnail_textures,
ci.clip_id,
ci.trim_start,
ci.trim_start.raw(),
rect.min.x + sx,
ex - sx,
ci_rect,
@@ -3392,7 +3617,7 @@ impl TimelinePane {
};
let audio_file_duration = total_frames as f64 / eff_sr as f64;
let clip_dur = audio_clip.content_duration().to_seconds(document.tempo_map());
let clip_dur = audio_clip.content_duration();
let mut ci_start = ci.effective_start();
if is_move_drag && selection.contains_clip_instance(&ci.id) {
ci_start = self.moved_start(ci_start, document.tempo_map(), &document.time_signature, document.framerate);
@@ -3443,7 +3668,8 @@ impl TimelinePane {
audio_duration: audio_file_duration as f32,
sample_rate: eff_sr,
clip_start_time: ci_screen_start,
trim_start: ci.trim_start as f32,
// A sampled clip's content time is seconds.
trim_start: ci.trim_start.raw() as f32,
tex_width: crate::waveform_gpu::tex_width() as f32,
total_frames: total_frames as f32,
segment_start_frame: 0.0,
@@ -3526,7 +3752,7 @@ impl TimelinePane {
let group: Vec<(uuid::Uuid, Beats, Beats)> = clip_instances.iter()
.filter(|ci| selection.contains_clip_instance(&ci.id))
.filter_map(|ci| {
let dur = document.get_clip_duration(&ci.clip_id)?;
let dur = document.clip_trim_duration(&ci.clip_id)?;
Some((ci.id, ci.effective_start(), ci.total_duration(dur, document.tempo_map())))
})
.collect();
@@ -3550,8 +3776,11 @@ impl TimelinePane {
let shift_beats = |anchor: Beats, secs: f64|
tmap.seconds_to_beats(tmap.beats_to_seconds(anchor) + Seconds(secs));
let clip_dur = effective_clip_duration(document, layer, ci).unwrap_or(Seconds::ZERO);
let clip_dur_secs = clip_dur.seconds_to_f64();
let clip_dur = effective_clip_duration(document, layer, ci).unwrap_or(ClipDuration::Seconds(Seconds::ZERO));
// Raw magnitudes in the clip's own content domain — the drag math below stays in
// that domain and only converts at the timeline edges.
let clip_dur_secs = clip_dur.native();
let ci_trim_start = ci.trim_start.raw();
let mut start = ci.effective_start();
let mut duration = ci.total_duration(clip_dur, tmap);
@@ -3573,25 +3802,25 @@ impl TimelinePane {
}
}
ClipDragType::TrimLeft => {
let new_trim = self.snap_to_grid(ci.trim_start + self.drag_offset, tmap, &document.time_signature, document.framerate, SNAP_PX_FINE).max(0.0).min(clip_dur_secs);
let trim_offset_secs = new_trim - ci.trim_start;
let new_trim = self.snap_to_grid(ci_trim_start + self.drag_offset, tmap, &document.time_signature, document.framerate, SNAP_PX_FINE).max(0.0).min(clip_dur_secs);
let trim_offset_secs = new_trim - ci_trim_start;
start = shift_beats(ci.timeline_start, trim_offset_secs).max(Beats::ZERO);
let dur_secs = if let Some(trim_end) = ci.trim_end {
(trim_end - new_trim).max(0.0)
(trim_end.raw() - new_trim).max(0.0)
} else {
(clip_dur_secs - new_trim).max(0.0)
};
duration = secs_to_beats_at(start, dur_secs);
}
ClipDragType::TrimRight => {
let old_trim_end = ci.trim_end.unwrap_or(clip_dur_secs);
let new_trim_end = self.snap_to_grid(old_trim_end + self.drag_offset, tmap, &document.time_signature, document.framerate, SNAP_PX_FINE).max(ci.trim_start).min(clip_dur_secs);
let dur_secs = (new_trim_end - ci.trim_start).max(0.0);
let old_trim_end = ci.trim_end.map_or(clip_dur_secs, |t| t.raw());
let new_trim_end = self.snap_to_grid(old_trim_end + self.drag_offset, tmap, &document.time_signature, document.framerate, SNAP_PX_FINE).max(ci_trim_start).min(clip_dur_secs);
let dur_secs = (new_trim_end - ci_trim_start).max(0.0);
duration = secs_to_beats_at(start, dur_secs);
}
ClipDragType::LoopExtendRight => {
let trim_end = ci.trim_end.unwrap_or(clip_dur_secs);
let content_window_secs = (trim_end - ci.trim_start).max(0.0);
let trim_end = ci.trim_end.map_or(clip_dur_secs, |t| t.raw());
let content_window_secs = (trim_end - ci_trim_start).max(0.0);
let content_window = secs_to_beats_at(ci.timeline_start, content_window_secs);
let current_right = ci.timeline_duration.unwrap_or(content_window);
let right_edge_secs = tmap.beats_to_seconds(ci.timeline_start + current_right).seconds_to_f64() + self.drag_offset;
@@ -3602,8 +3831,8 @@ impl TimelinePane {
duration = loop_before + new_right;
}
ClipDragType::LoopExtendLeft => {
let trim_end = ci.trim_end.unwrap_or(clip_dur_secs);
let content_window_secs = (trim_end - ci.trim_start).max(0.001);
let trim_end = ci.trim_end.map_or(clip_dur_secs, |t| t.raw());
let content_window_secs = (trim_end - ci_trim_start).max(0.001);
let content_window = secs_to_beats_at(ci.timeline_start, content_window_secs);
let current_loop_before = ci.loop_before.unwrap_or(Beats::ZERO);
// drag_offset (seconds) as a beats delta at this clip's start.
@@ -3664,6 +3893,9 @@ impl TimelinePane {
// Track preview trim values for note/waveform rendering.
// In Measures mode, derive from beats so they track BPM during live drag.
let (base_trim_start, base_clip_duration) = self.content_display_range(clip_instance, clip_duration, document.bpm());
// The instance's trim start as a raw magnitude in the clip's content domain; the
// preview math below stays in that domain.
let ci_trim_start = clip_instance.trim_start.raw();
let mut preview_trim_start = base_trim_start;
let mut preview_clip_duration = base_clip_duration;
@@ -3679,11 +3911,11 @@ impl TimelinePane {
}
ClipDragType::TrimLeft => {
// Trim left: calculate new trim_start with snap to adjacent clips
let desired_trim_start = self.snap_to_grid(clip_instance.trim_start + self.drag_offset, document.tempo_map(), &document.time_signature, document.framerate, SNAP_PX_FINE)
let desired_trim_start = self.snap_to_grid(ci_trim_start + self.drag_offset, document.tempo_map(), &document.time_signature, document.framerate, SNAP_PX_FINE)
.max(0.0)
.min(clip_duration.seconds_to_f64());
.min(clip_duration.native());
let new_trim_start = if desired_trim_start < clip_instance.trim_start {
let new_trim_start = if desired_trim_start < ci_trim_start {
// Extending left - limit is the content-seconds gap to the previous clip.
let max_extend_secs = document.find_max_trim_extend_left(
&layer.id(),
@@ -3691,25 +3923,25 @@ impl TimelinePane {
clip_instance.effective_start(),
).seconds_to_f64();
let desired_extend = clip_instance.trim_start - desired_trim_start;
let desired_extend = ci_trim_start - desired_trim_start;
let actual_extend = desired_extend.min(max_extend_secs);
clip_instance.trim_start - actual_extend
ci_trim_start - actual_extend
} else {
// Shrinking - no snap needed
desired_trim_start
};
let actual_offset = new_trim_start - clip_instance.trim_start;
let actual_offset = new_trim_start - ci_trim_start;
// Move start (display seconds) and reduce duration by the clamped offset.
instance_start = (document.tempo_map().beats_to_seconds(clip_instance.timeline_start).seconds_to_f64() + actual_offset)
.max(0.0);
instance_duration = (clip_duration.seconds_to_f64() - new_trim_start).max(0.0);
instance_duration = (clip_duration.native() - new_trim_start).max(0.0);
// Adjust for existing trim_end
if let Some(trim_end) = clip_instance.trim_end {
instance_duration = (trim_end - new_trim_start).max(0.0);
instance_duration = (trim_end.raw() - new_trim_start).max(0.0);
}
// Update preview trim for waveform rendering
@@ -3718,14 +3950,14 @@ impl TimelinePane {
}
ClipDragType::TrimRight => {
// Trim right: extend or reduce duration with snap to adjacent clips
let old_trim_end = clip_instance.trim_end.unwrap_or(clip_duration.seconds_to_f64());
let old_trim_end = clip_instance.trim_end.map_or(clip_duration.native(), |t| t.raw());
let desired_trim_end = self.snap_to_grid(old_trim_end + self.drag_offset, document.tempo_map(), &document.time_signature, document.framerate, SNAP_PX_FINE)
.max(clip_instance.trim_start)
.min(clip_duration.seconds_to_f64());
.max(ci_trim_start)
.min(clip_duration.native());
let new_trim_end = if desired_trim_end > old_trim_end {
// Extending right - limit is the content-seconds gap to the next clip.
let current_duration_secs = old_trim_end - clip_instance.trim_start;
let current_duration_secs = old_trim_end - ci_trim_start;
let tmap = document.tempo_map();
let current_duration = tmap.seconds_to_beats(
tmap.beats_to_seconds(clip_instance.timeline_start) + Seconds(current_duration_secs)
@@ -3745,7 +3977,7 @@ impl TimelinePane {
desired_trim_end
};
instance_duration = (new_trim_end - clip_instance.trim_start).max(0.0);
instance_duration = (new_trim_end - ci_trim_start).max(0.0);
// Update preview clip duration for waveform rendering
// (the waveform system uses clip_duration to determine visible range)
@@ -3753,8 +3985,8 @@ impl TimelinePane {
}
ClipDragType::LoopExtendRight => {
// Loop extend right: extend clip beyond content window
let trim_end = clip_instance.trim_end.unwrap_or(clip_duration.seconds_to_f64());
let content_window_secs = (trim_end - clip_instance.trim_start).max(0.0);
let trim_end = clip_instance.trim_end.map_or(clip_duration.native(), |t| t.raw());
let content_window_secs = (trim_end - ci_trim_start).max(0.0);
let tmap = document.tempo_map();
let ts = clip_instance.timeline_start;
// content window and right-duration are beats-domain timeline spans.
@@ -3789,8 +4021,8 @@ impl TimelinePane {
ClipDragType::LoopExtendLeft => {
// Loop extend left: extend loop_before (pre-loop region)
// Snap to multiples of content_window so iterations align with backend
let trim_end = clip_instance.trim_end.unwrap_or(clip_duration.seconds_to_f64());
let content_window_secs = (trim_end - clip_instance.trim_start).max(0.001);
let trim_end = clip_instance.trim_end.map_or(clip_duration.native(), |t| t.raw());
let content_window_secs = (trim_end - ci_trim_start).max(0.001);
let tmap = document.tempo_map();
let ts = clip_instance.timeline_start;
// content window is a beats-domain span; guard against zero for division.
@@ -3916,9 +4148,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_instance.resolve(clip) {
// 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
@@ -3977,7 +4211,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();
@@ -4028,7 +4262,7 @@ impl TimelinePane {
// Calculate content window for loop detection
// Use trimmed content window (preview_trim_start accounts for TrimLeft drag)
let preview_trim_end = clip_instance.trim_end.unwrap_or(clip_duration.seconds_to_f64());
let preview_trim_end = clip_instance.trim_end.map_or(clip_duration.native(), |t| t.raw());
let content_window = (preview_trim_end - preview_trim_start).max(0.0);
let is_looping = instance_duration > content_window + 0.001;
@@ -4106,7 +4340,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;
@@ -4141,6 +4375,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 {
@@ -4153,7 +4417,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,
@@ -4195,7 +4459,7 @@ impl TimelinePane {
&video_mgr,
&mut self.video_thumbnail_textures,
clip_instance.clip_id,
clip_instance.trim_start,
clip_instance.trim_start.raw(),
rect.min.x + start_x,
end_x - start_x,
clip_rect,
@@ -4210,7 +4474,7 @@ impl TimelinePane {
// clip's TRUE (unclamped) origin x so the hover content time is
// correct even when the clip is scrolled partly off the left.
if let lightningbeam_core::layer::AnyLayer::Video(_) = layer {
video_clip_hovers.push((clip_rect, clip_instance.clip_id, clip_instance.trim_start, rect.min.x + start_x));
video_clip_hovers.push((clip_rect, clip_instance.clip_id, clip_instance.trim_start.raw(), rect.min.x + start_x));
}
// Draw border per segment (per loop iteration for looping clips)
@@ -4267,6 +4531,66 @@ 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.
// Only worth showing when there's actually a choice to make.
if clip_instance.takes.len() > 1 {
let take_count = clip_instance.takes.len();
let active = clip_instance.active_take_index();
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,
));
}
}
}
}
}
@@ -4746,7 +5070,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,
@@ -4883,18 +5212,23 @@ impl TimelinePane {
for clip_instance in clip_instances {
if selection.contains_clip_instance(&clip_instance.id) {
let clip_duration = effective_clip_duration(document, layer, clip_instance);
// Raw magnitude in the clip's content domain; re-tagged as a
// ContentTime when it goes back into TrimData.
let ci_trim_start = clip_instance.trim_start.raw();
if let Some(clip_duration) = clip_duration {
match drag_type {
ClipDragType::TrimLeft => {
let old_trim_start = clip_instance.trim_start;
// Raw magnitude in the clip's content domain; re-tagged as a
// ContentTime when it goes back into TrimData below.
let old_trim_start = clip_instance.trim_start.raw();
let old_timeline_start =
clip_instance.timeline_start;
// New trim_start is snapped then clamped to valid range
let desired_trim_start = self.snap_to_grid(
old_trim_start + self.drag_offset, document.tempo_map(), &document.time_signature, document.framerate, SNAP_PX_FINE,
).max(0.0).min(clip_duration.seconds_to_f64());
).max(0.0).min(clip_duration.native());
// Apply overlap prevention when extending left (content-seconds gap).
let new_trim_start = if desired_trim_start < old_trim_start {
@@ -4924,11 +5258,11 @@ impl TimelinePane {
clip_instance.id,
lightningbeam_core::actions::TrimType::TrimLeft,
lightningbeam_core::actions::TrimData::left(
old_trim_start,
ContentTime(old_trim_start),
old_timeline_start,
),
lightningbeam_core::actions::TrimData::left(
new_trim_start,
ContentTime(new_trim_start),
new_timeline_start,
),
));
@@ -4939,10 +5273,10 @@ impl TimelinePane {
// Calculate new trim_end based on current duration
let current_duration =
clip_instance.effective_duration(clip_duration, document.tempo_map());
let old_trim_end_val = clip_instance.trim_end.unwrap_or(clip_duration.seconds_to_f64());
let old_trim_end_val = clip_instance.trim_end.map_or(clip_duration.native(), |t| t.raw());
let desired_trim_end = self.snap_to_grid(
old_trim_end_val + self.drag_offset, document.tempo_map(), &document.time_signature, document.framerate, SNAP_PX_FINE,
).max(clip_instance.trim_start).min(clip_duration.seconds_to_f64());
).max(ci_trim_start).min(clip_duration.native());
// Apply overlap prevention when extending right (content-seconds gap).
let new_trim_end_val = if desired_trim_end > old_trim_end_val {
@@ -4959,13 +5293,15 @@ impl TimelinePane {
desired_trim_end
};
let new_duration = (new_trim_end_val - clip_instance.trim_start).max(0.0);
let new_duration = (new_trim_end_val - ci_trim_start).max(0.0);
// Convert new duration back to trim_end value
let new_trim_end = if new_duration >= clip_duration.seconds_to_f64() {
let new_trim_end = if new_duration >= clip_duration.native() {
None // Use full clip duration
} else {
Some((clip_instance.trim_start + new_duration).min(clip_duration.seconds_to_f64()))
Some(ContentTime(
(ci_trim_start + new_duration).min(clip_duration.native()),
))
};
layer_trims
@@ -5017,8 +5353,9 @@ impl TimelinePane {
if let Some(clip_duration) = clip_duration {
let tmap = document.tempo_map();
let ts = clip_instance.timeline_start;
let trim_end = clip_instance.trim_end.unwrap_or(clip_duration);
let content_window_secs = (trim_end - clip_instance.trim_start).max(0.0);
let ci_trim_start = clip_instance.trim_start.raw();
let trim_end = clip_instance.trim_end.map_or(clip_duration, |t| t.raw());
let content_window_secs = (trim_end - ci_trim_start).max(0.0);
let content_window = tmap.seconds_to_beats(tmap.beats_to_seconds(ts) + Seconds(content_window_secs)) - ts;
let current_right = clip_instance.timeline_duration.unwrap_or(content_window);
// Snap the right edge in the seconds/pixel domain.
@@ -5091,8 +5428,9 @@ impl TimelinePane {
if let Some(clip_duration) = clip_duration {
let tmap = document.tempo_map();
let ts = clip_instance.timeline_start;
let trim_end = clip_instance.trim_end.unwrap_or(clip_duration);
let content_window_secs = (trim_end - clip_instance.trim_start).max(0.001);
let ci_trim_start = clip_instance.trim_start.raw();
let trim_end = clip_instance.trim_end.map_or(clip_duration, |t| t.raw());
let content_window_secs = (trim_end - ci_trim_start).max(0.001);
let content_window = tmap.seconds_to_beats(tmap.beats_to_seconds(ts) + Seconds(content_window_secs)) - ts;
let cw = content_window.beats_to_f64().max(1e-9);
let current_loop_before = clip_instance.loop_before.unwrap_or(Beats::ZERO);
@@ -6181,6 +6519,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.
@@ -6348,7 +6688,7 @@ impl PaneRenderer for TimelinePane {
let instances = layer_clips(layer);
for inst in instances {
if !shared.selection.contains_clip_instance(&inst.id) { continue; }
if let Some(dur) = document.get_clip_duration(&inst.clip_id) {
if let Some(dur) = document.clip_trim_duration(&inst.clip_id) {
let eff = inst.effective_duration(dur, document.tempo_map());
let start = document.tempo_map().beats_to_seconds(inst.timeline_start).seconds_to_f64();
let end = document.tempo_map().beats_to_seconds(inst.timeline_start + eff).seconds_to_f64();
@@ -6374,7 +6714,7 @@ impl PaneRenderer for TimelinePane {
enabled = instances.iter()
.filter(|ci| shared.selection.contains_clip_instance(&ci.id))
.all(|ci| {
if let Some(dur) = document.get_clip_duration(&ci.clip_id) {
if let Some(dur) = document.clip_trim_duration(&ci.clip_id) {
let eff = ci.effective_duration(dur, document.tempo_map());
// Room to duplicate = seconds gap to the right ≥ this clip's own length.
let max_extend_secs = document.find_max_trim_extend_right(
@@ -6419,7 +6759,7 @@ impl PaneRenderer for TimelinePane {
enabled = instances.iter().all(|ci| {
let paste_start = (ci.timeline_start + offset).max(Beats::ZERO);
if let Some(dur) = document.get_clip_duration(&ci.clip_id) {
if let Some(dur) = document.clip_trim_duration(&ci.clip_id) {
let eff = ci.effective_duration(dur, document.tempo_map());
document
.find_nearest_valid_position(
@@ -6448,6 +6788,22 @@ impl PaneRenderer for TimelinePane {
enabled
};
// Take management for the clip that was right-clicked. Only offered when there's more
// than one take — with a single take there's nothing to choose between, and "delete the
// only take" would leave the instance with nothing to play.
let take_target: Option<(uuid::Uuid, uuid::Uuid, usize, String)> = ctx_clip_id.and_then(|instance_id| {
let context_layers = document.context_layers(shared.editing_clip_id.as_ref());
for (layer, instances) in all_layer_clip_instances(&context_layers) {
if let Some(ci) = instances.iter().find(|ci| ci.id == instance_id) {
if ci.takes.len() > 1 {
let active = ci.active_take_index();
return Some((layer.id(), instance_id, active, ci.takes[active].name.clone()));
}
}
}
None
});
let area_id = ui.id().with("clip_context_menu");
let mut item_clicked = false;
let area_response = egui::Area::new(area_id)
@@ -6513,6 +6869,34 @@ impl PaneRenderer for TimelinePane {
shared.pending_menu_actions.push(crate::menu::MenuAction::Delete);
item_clicked = true;
}
// Take management, on the clip that was right-clicked. Takes live on the
// INSTANCE, so on a comped split this prunes the half you clicked and leaves
// the other half's alternatives alone.
if let Some((take_layer_id, take_instance_id, active_index, active_name)) = &take_target {
ui.separator();
// Deletes the take that's PLAYING — the one the badge is showing — so
// it's named rather than just "Delete Take".
if menu_item(ui, &format!("Delete \"{}\"", active_name), true) {
shared.pending_actions.push(Box::new(
lightningbeam_core::actions::DeleteTakeAction::new(
*take_layer_id,
*take_instance_id,
*active_index,
),
));
item_clicked = true;
}
if menu_item(ui, "Delete Unused Takes", true) {
shared.pending_actions.push(Box::new(
lightningbeam_core::actions::DeleteUnusedTakesAction::new(
*take_layer_id,
*take_instance_id,
),
));
item_clicked = true;
}
}
});
});
@@ -55,6 +55,7 @@ struct PreferencesState {
file_height: u32,
scroll_speed: f64,
audio_buffer_size: u32,
cycle_midi_separate_takes: bool,
reopen_last_session: bool,
restore_layout_from_file: bool,
debug: bool,
@@ -74,6 +75,7 @@ impl From<(&AppConfig, &Theme)> for PreferencesState {
file_height: config.file_height,
scroll_speed: config.scroll_speed,
audio_buffer_size: config.audio_buffer_size,
cycle_midi_separate_takes: config.cycle_midi_separate_takes,
reopen_last_session: config.reopen_last_session,
restore_layout_from_file: config.restore_layout_from_file,
debug: config.debug,
@@ -95,6 +97,7 @@ impl Default for PreferencesState {
file_height: 600,
scroll_speed: 1.0,
audio_buffer_size: 256,
cycle_midi_separate_takes: false,
reopen_last_session: false,
restore_layout_from_file: true,
debug: false,
@@ -551,6 +554,39 @@ impl PreferencesDialog {
});
ui.label("Requires app restart to take effect");
ui.separator();
ui.horizontal(|ui| {
ui.label("Cycle MIDI recording:");
egui::ComboBox::from_id_salt("cycle_midi_mode")
.selected_text(if self.working_prefs.cycle_midi_separate_takes {
"Separate takes"
} else {
"Merge"
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.working_prefs.cycle_midi_separate_takes,
false,
"Merge",
)
.on_hover_text(
"Every pass overdubs into one clip, and earlier passes play back as \
you record so you can layer against them.",
);
ui.selectable_value(
&mut self.working_prefs.cycle_midi_separate_takes,
true,
"Separate takes",
)
.on_hover_text(
"Each pass becomes its own take in a take folder, as audio always \
does. Earlier passes stay silent — they're alternatives, not layers.",
);
});
});
});
}
@@ -684,6 +720,7 @@ impl PreferencesDialog {
temp_config.file_height = self.working_prefs.file_height;
temp_config.scroll_speed = self.working_prefs.scroll_speed;
temp_config.audio_buffer_size = self.working_prefs.audio_buffer_size;
temp_config.cycle_midi_separate_takes = self.working_prefs.cycle_midi_separate_takes;
temp_config.reopen_last_session = self.working_prefs.reopen_last_session;
temp_config.restore_layout_from_file = self.working_prefs.restore_layout_from_file;
temp_config.debug = self.working_prefs.debug;
@@ -720,6 +757,7 @@ impl PreferencesDialog {
config.file_height = self.working_prefs.file_height;
config.scroll_speed = self.working_prefs.scroll_speed;
config.audio_buffer_size = self.working_prefs.audio_buffer_size;
config.cycle_midi_separate_takes = self.working_prefs.cycle_midi_separate_takes;
config.reopen_last_session = self.working_prefs.reopen_last_session;
config.restore_layout_from_file = self.working_prefs.restore_layout_from_file;
config.debug = self.working_prefs.debug;