Massive tempo refactor - make beats canonical time rep and allow them to be non constant
This commit is contained in:
@@ -79,8 +79,6 @@ impl Action for AddClipInstanceAction {
|
||||
if let Some(valid_start) = adjusted_start {
|
||||
// Update instance to use the valid position
|
||||
self.clip_instance.timeline_start = valid_start;
|
||||
let (bpm, fps) = (document.bpm, document.framerate);
|
||||
self.clip_instance.sync_from_seconds(bpm, fps);
|
||||
} else {
|
||||
// No valid position found - reject the operation
|
||||
return Err("Cannot add clip: no valid position found on layer (layer is full)".to_string());
|
||||
@@ -210,10 +208,10 @@ impl Action for AddClipInstanceAction {
|
||||
let instance = daw_backend::MidiClipInstance::new(
|
||||
0, // Instance ID will be assigned by backend
|
||||
*midi_clip_id,
|
||||
internal_start,
|
||||
internal_end,
|
||||
external_start,
|
||||
external_duration,
|
||||
daw_backend::Beats(internal_start),
|
||||
daw_backend::Beats(internal_end),
|
||||
daw_backend::Beats(external_start),
|
||||
daw_backend::Beats(external_duration),
|
||||
);
|
||||
|
||||
// Send query to add instance and get instance ID
|
||||
|
||||
@@ -1,248 +1,49 @@
|
||||
//! Change BPM action
|
||||
//! Change BPM / Tempo action
|
||||
//!
|
||||
//! Atomically changes the document BPM and rescales all clip instance positions and
|
||||
//! MIDI event timestamps so that beat positions are preserved (Measures mode behaviour).
|
||||
//! Atomically swaps the document `TempoMap`, sending the new map to the engine.
|
||||
//! All clip and note positions are stored in **beats** so no position rescaling
|
||||
//! is required — only the TempoMap entry changes.
|
||||
|
||||
use crate::action::{Action, BackendContext};
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
use crate::tempo_map::TempoMap;
|
||||
|
||||
/// Snapshot of all timing fields on a `ClipInstance`
|
||||
/// Action that changes the global BPM by replacing the tempo map.
|
||||
#[derive(Clone)]
|
||||
struct TimingFields {
|
||||
timeline_start: f64,
|
||||
timeline_start_beats: f64,
|
||||
timeline_start_frames: f64,
|
||||
trim_start: f64,
|
||||
trim_start_beats: f64,
|
||||
trim_start_frames: f64,
|
||||
trim_end: Option<f64>,
|
||||
trim_end_beats: Option<f64>,
|
||||
trim_end_frames: Option<f64>,
|
||||
timeline_duration: Option<f64>,
|
||||
timeline_duration_beats: Option<f64>,
|
||||
timeline_duration_frames: Option<f64>,
|
||||
}
|
||||
|
||||
impl TimingFields {
|
||||
fn from_instance(ci: &ClipInstance) -> Self {
|
||||
Self {
|
||||
timeline_start: ci.timeline_start,
|
||||
timeline_start_beats: ci.timeline_start_beats,
|
||||
timeline_start_frames: ci.timeline_start_frames,
|
||||
trim_start: ci.trim_start,
|
||||
trim_start_beats: ci.trim_start_beats,
|
||||
trim_start_frames: ci.trim_start_frames,
|
||||
trim_end: ci.trim_end,
|
||||
trim_end_beats: ci.trim_end_beats,
|
||||
trim_end_frames: ci.trim_end_frames,
|
||||
timeline_duration: ci.timeline_duration,
|
||||
timeline_duration_beats: ci.timeline_duration_beats,
|
||||
timeline_duration_frames: ci.timeline_duration_frames,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_to(&self, ci: &mut ClipInstance) {
|
||||
ci.timeline_start = self.timeline_start;
|
||||
ci.timeline_start_beats = self.timeline_start_beats;
|
||||
ci.timeline_start_frames = self.timeline_start_frames;
|
||||
ci.trim_start = self.trim_start;
|
||||
ci.trim_start_beats = self.trim_start_beats;
|
||||
ci.trim_start_frames = self.trim_start_frames;
|
||||
ci.trim_end = self.trim_end;
|
||||
ci.trim_end_beats = self.trim_end_beats;
|
||||
ci.trim_end_frames = self.trim_end_frames;
|
||||
ci.timeline_duration = self.timeline_duration;
|
||||
ci.timeline_duration_beats = self.timeline_duration_beats;
|
||||
ci.timeline_duration_frames = self.timeline_duration_frames;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ClipTimingSnapshot {
|
||||
layer_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
old_fields: TimingFields,
|
||||
new_fields: TimingFields,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MidiClipSnapshot {
|
||||
layer_id: Uuid,
|
||||
midi_clip_id: u32,
|
||||
clip_id: Uuid,
|
||||
old_clip_duration: f64,
|
||||
new_clip_duration: f64,
|
||||
old_events: Vec<daw_backend::audio::midi::MidiEvent>,
|
||||
new_events: Vec<daw_backend::audio::midi::MidiEvent>,
|
||||
}
|
||||
|
||||
/// Action that atomically changes BPM and rescales all clip/note positions to preserve beats
|
||||
pub struct ChangeBpmAction {
|
||||
old_bpm: f64,
|
||||
new_bpm: f64,
|
||||
old_map: TempoMap,
|
||||
new_map: TempoMap,
|
||||
time_sig: (u32, u32),
|
||||
clip_snapshots: Vec<ClipTimingSnapshot>,
|
||||
midi_snapshots: Vec<MidiClipSnapshot>,
|
||||
}
|
||||
|
||||
impl ChangeBpmAction {
|
||||
/// Build the action, computing new positions for all clip instances and MIDI events.
|
||||
///
|
||||
/// `midi_event_cache` maps backend MIDI clip ID → current event list.
|
||||
pub fn new(
|
||||
old_bpm: f64,
|
||||
new_bpm: f64,
|
||||
document: &Document,
|
||||
midi_event_cache: &HashMap<u32, Vec<daw_backend::audio::midi::MidiEvent>>,
|
||||
) -> Self {
|
||||
let fps = document.framerate;
|
||||
let time_sig = (
|
||||
document.time_signature.numerator,
|
||||
document.time_signature.denominator,
|
||||
);
|
||||
|
||||
let mut clip_snapshots: Vec<ClipTimingSnapshot> = Vec::new();
|
||||
let mut midi_snapshots: Vec<MidiClipSnapshot> = Vec::new();
|
||||
|
||||
// Collect MIDI clip IDs we've already snapshotted (avoid duplicates)
|
||||
let mut seen_midi_clips: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
|
||||
for layer in document.all_layers() {
|
||||
let layer_id = layer.id();
|
||||
|
||||
let clip_instances: &[ClipInstance] = match layer {
|
||||
AnyLayer::Vector(vl) => &vl.clip_instances,
|
||||
AnyLayer::Audio(al) => &al.clip_instances,
|
||||
AnyLayer::Video(vl) => &vl.clip_instances,
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) | AnyLayer::Raster(_) => continue,
|
||||
};
|
||||
|
||||
for ci in clip_instances {
|
||||
let old_fields = TimingFields::from_instance(ci);
|
||||
|
||||
// Compute new fields: beats are canonical, recompute seconds + frames.
|
||||
// Guard: if timeline_start_beats was never populated (clips added without
|
||||
// sync_from_seconds), derive beats from seconds before applying.
|
||||
let mut new_ci = ci.clone();
|
||||
if new_ci.timeline_start_beats == 0.0 && new_ci.timeline_start.abs() > 1e-9 {
|
||||
new_ci.sync_from_seconds(old_bpm, fps);
|
||||
}
|
||||
new_ci.apply_beats(new_bpm, fps);
|
||||
let new_fields = TimingFields::from_instance(&new_ci);
|
||||
|
||||
clip_snapshots.push(ClipTimingSnapshot {
|
||||
layer_id,
|
||||
instance_id: ci.id,
|
||||
old_fields,
|
||||
new_fields,
|
||||
});
|
||||
|
||||
// If this is a MIDI clip on an audio layer, collect MIDI events + rescale duration.
|
||||
// Always snapshot the clip (even if empty) so clip.duration is rescaled.
|
||||
if let AnyLayer::Audio(_) = layer {
|
||||
if let Some(audio_clip) = document.get_audio_clip(&ci.clip_id) {
|
||||
use crate::clip::AudioClipType;
|
||||
if let AudioClipType::Midi { midi_clip_id } = &audio_clip.clip_type {
|
||||
let midi_id = *midi_clip_id;
|
||||
if !seen_midi_clips.contains(&midi_id) {
|
||||
seen_midi_clips.insert(midi_id);
|
||||
|
||||
let old_clip_duration = audio_clip.duration;
|
||||
let new_clip_duration = old_clip_duration * old_bpm / new_bpm;
|
||||
|
||||
// Use cached events if present; empty vec for clips with no events yet.
|
||||
let old_events = midi_event_cache.get(&midi_id).cloned().unwrap_or_default();
|
||||
let new_events: Vec<_> = old_events.iter().map(|ev| {
|
||||
let mut e = ev.clone();
|
||||
// Ensure beats are populated before using them as canonical.
|
||||
// Events created before triple-rep (e.g. from recording)
|
||||
// have timestamp_beats == 0.0 — sync from seconds first.
|
||||
if e.timestamp_beats == 0.0 && e.timestamp.abs() > 1e-9 {
|
||||
e.sync_from_seconds(old_bpm, fps);
|
||||
}
|
||||
e.apply_beats(new_bpm, fps);
|
||||
e
|
||||
}).collect();
|
||||
|
||||
midi_snapshots.push(MidiClipSnapshot {
|
||||
layer_id,
|
||||
midi_clip_id: midi_id,
|
||||
clip_id: ci.clip_id,
|
||||
old_clip_duration,
|
||||
new_clip_duration,
|
||||
old_events,
|
||||
new_events,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
old_bpm,
|
||||
new_bpm,
|
||||
time_sig,
|
||||
clip_snapshots,
|
||||
midi_snapshots,
|
||||
}
|
||||
/// Build the action from the current document state and a desired new BPM.
|
||||
pub fn new(new_bpm: f64, document: &Document) -> Self {
|
||||
let old_map = document.tempo_map().clone();
|
||||
let mut new_map = old_map.clone();
|
||||
new_map.set_global_bpm(new_bpm);
|
||||
let time_sig = (document.time_signature.numerator, document.time_signature.denominator);
|
||||
Self { old_map, new_map, time_sig }
|
||||
}
|
||||
|
||||
/// Return the new MIDI event lists for each affected clip (for immediate cache update).
|
||||
pub fn new_midi_events(&self) -> impl Iterator<Item = (u32, &Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
self.midi_snapshots.iter().map(|s| (s.midi_clip_id, &s.new_events))
|
||||
/// Build from explicit old/new maps (used when the map already changed in-place,
|
||||
/// e.g., after live drag preview; the caller provides start and end states).
|
||||
pub fn from_maps(old_map: TempoMap, new_map: TempoMap, time_sig: (u32, u32)) -> Self {
|
||||
Self { old_map, new_map, time_sig }
|
||||
}
|
||||
|
||||
fn apply_clips(document: &mut Document, snapshots: &[ClipTimingSnapshot], use_new: bool) {
|
||||
for snap in snapshots {
|
||||
let fields = if use_new { &snap.new_fields } else { &snap.old_fields };
|
||||
|
||||
let layer = match document.get_layer_mut(&snap.layer_id) {
|
||||
Some(l) => l,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let clip_instances = match layer {
|
||||
AnyLayer::Vector(vl) => &mut vl.clip_instances,
|
||||
AnyLayer::Audio(al) => &mut al.clip_instances,
|
||||
AnyLayer::Video(vl) => &mut vl.clip_instances,
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) | AnyLayer::Raster(_) => continue,
|
||||
};
|
||||
|
||||
if let Some(ci) = clip_instances.iter_mut().find(|ci| ci.id == snap.instance_id) {
|
||||
fields.apply_to(ci);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_midi_durations(document: &mut Document, snapshots: &[MidiClipSnapshot], use_new: bool) {
|
||||
for snap in snapshots {
|
||||
if let Some(clip) = document.get_audio_clip_mut(&snap.clip_id) {
|
||||
clip.duration = if use_new { snap.new_clip_duration } else { snap.old_clip_duration };
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn new_bpm(&self) -> f64 { self.new_map.global_bpm() }
|
||||
pub fn old_bpm(&self) -> f64 { self.old_map.global_bpm() }
|
||||
}
|
||||
|
||||
impl Action for ChangeBpmAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.bpm = self.new_bpm;
|
||||
Self::apply_clips(document, &self.clip_snapshots, true);
|
||||
Self::apply_midi_durations(document, &self.midi_snapshots, true);
|
||||
*document.tempo_map_mut() = self.new_map.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.bpm = self.old_bpm;
|
||||
Self::apply_clips(document, &self.clip_snapshots, false);
|
||||
Self::apply_midi_durations(document, &self.midi_snapshots, false);
|
||||
*document.tempo_map_mut() = self.old_map.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -253,111 +54,26 @@ impl Action for ChangeBpmAction {
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
// Update tempo
|
||||
controller.set_tempo(self.new_bpm as f32, self.time_sig);
|
||||
|
||||
// Update MIDI clip events and positions
|
||||
for snap in &self.midi_snapshots {
|
||||
let track_id = match backend.layer_to_track_map.get(&snap.layer_id) {
|
||||
Some(&id) => id,
|
||||
None => continue,
|
||||
};
|
||||
controller.update_midi_clip_events(track_id, snap.midi_clip_id, snap.new_events.clone());
|
||||
}
|
||||
|
||||
// Move clip instances in the backend
|
||||
for snap in &self.clip_snapshots {
|
||||
let track_id = match backend.layer_to_track_map.get(&snap.layer_id) {
|
||||
Some(&id) => id,
|
||||
None => continue,
|
||||
};
|
||||
let backend_id = backend.clip_instance_to_backend_map.get(&snap.instance_id);
|
||||
match backend_id {
|
||||
Some(crate::action::BackendClipInstanceId::Audio(audio_id)) => {
|
||||
controller.move_clip(track_id, *audio_id, snap.new_fields.timeline_start);
|
||||
}
|
||||
Some(crate::action::BackendClipInstanceId::Midi(midi_id)) => {
|
||||
controller.move_clip(track_id, *midi_id, snap.new_fields.timeline_start);
|
||||
}
|
||||
None => {} // Vector/video clips — no backend move needed
|
||||
}
|
||||
}
|
||||
|
||||
// Sync beat/frame representations, rescale MIDI clip durations, and rescale
|
||||
// automation keyframe times in the backend
|
||||
let fps = document.framerate;
|
||||
let midi_durations: Vec<(u32, f64)> = self.midi_snapshots.iter()
|
||||
.map(|s| (s.midi_clip_id, s.new_clip_duration))
|
||||
.collect();
|
||||
controller.apply_bpm_change(self.old_bpm, self.new_bpm, fps, midi_durations);
|
||||
|
||||
controller.set_tempo(self.new_map.global_bpm() as f32, self.time_sig);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
controller.set_tempo(self.old_bpm as f32, self.time_sig);
|
||||
|
||||
for snap in &self.midi_snapshots {
|
||||
let track_id = match backend.layer_to_track_map.get(&snap.layer_id) {
|
||||
Some(&id) => id,
|
||||
None => continue,
|
||||
};
|
||||
controller.update_midi_clip_events(track_id, snap.midi_clip_id, snap.old_events.clone());
|
||||
}
|
||||
|
||||
for snap in &self.clip_snapshots {
|
||||
let track_id = match backend.layer_to_track_map.get(&snap.layer_id) {
|
||||
Some(&id) => id,
|
||||
None => continue,
|
||||
};
|
||||
let backend_id = backend.clip_instance_to_backend_map.get(&snap.instance_id);
|
||||
match backend_id {
|
||||
Some(crate::action::BackendClipInstanceId::Audio(audio_id)) => {
|
||||
controller.move_clip(track_id, *audio_id, snap.old_fields.timeline_start);
|
||||
}
|
||||
Some(crate::action::BackendClipInstanceId::Midi(midi_id)) => {
|
||||
controller.move_clip(track_id, *midi_id, snap.old_fields.timeline_start);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Sync beat/frame representations, restore MIDI clip durations, and restore
|
||||
// automation keyframe times in the backend
|
||||
let fps = document.framerate;
|
||||
let midi_durations: Vec<(u32, f64)> = self.midi_snapshots.iter()
|
||||
.map(|s| (s.midi_clip_id, s.old_clip_duration))
|
||||
.collect();
|
||||
controller.apply_bpm_change(self.new_bpm, self.old_bpm, fps, midi_durations);
|
||||
|
||||
controller.set_tempo(self.old_map.global_bpm() as f32, self.time_sig);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn all_midi_events_after_execute(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
self.midi_snapshots.iter()
|
||||
.map(|s| (s.midi_clip_id, s.new_events.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn all_midi_events_after_rollback(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
self.midi_snapshots.iter()
|
||||
.map(|s| (s.midi_clip_id, s.old_events.clone()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,156 +1,33 @@
|
||||
//! Change FPS action
|
||||
//!
|
||||
//! Atomically changes the document framerate and rescales all clip instance positions
|
||||
//! so that frame positions are preserved (Frames mode behaviour).
|
||||
//! Atomically changes the document framerate.
|
||||
//! All clip positions are stored in **beats** so no position rescaling is
|
||||
//! required — only the framerate field changes.
|
||||
|
||||
use crate::action::{Action, BackendContext};
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Snapshot of all timing fields on a `ClipInstance`
|
||||
#[derive(Clone)]
|
||||
struct TimingFields {
|
||||
timeline_start: f64,
|
||||
timeline_start_beats: f64,
|
||||
timeline_start_frames: f64,
|
||||
trim_start: f64,
|
||||
trim_start_beats: f64,
|
||||
trim_start_frames: f64,
|
||||
trim_end: Option<f64>,
|
||||
trim_end_beats: Option<f64>,
|
||||
trim_end_frames: Option<f64>,
|
||||
timeline_duration: Option<f64>,
|
||||
timeline_duration_beats: Option<f64>,
|
||||
timeline_duration_frames: Option<f64>,
|
||||
}
|
||||
|
||||
impl TimingFields {
|
||||
fn from_instance(ci: &ClipInstance) -> Self {
|
||||
Self {
|
||||
timeline_start: ci.timeline_start,
|
||||
timeline_start_beats: ci.timeline_start_beats,
|
||||
timeline_start_frames: ci.timeline_start_frames,
|
||||
trim_start: ci.trim_start,
|
||||
trim_start_beats: ci.trim_start_beats,
|
||||
trim_start_frames: ci.trim_start_frames,
|
||||
trim_end: ci.trim_end,
|
||||
trim_end_beats: ci.trim_end_beats,
|
||||
trim_end_frames: ci.trim_end_frames,
|
||||
timeline_duration: ci.timeline_duration,
|
||||
timeline_duration_beats: ci.timeline_duration_beats,
|
||||
timeline_duration_frames: ci.timeline_duration_frames,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_to(&self, ci: &mut ClipInstance) {
|
||||
ci.timeline_start = self.timeline_start;
|
||||
ci.timeline_start_beats = self.timeline_start_beats;
|
||||
ci.timeline_start_frames = self.timeline_start_frames;
|
||||
ci.trim_start = self.trim_start;
|
||||
ci.trim_start_beats = self.trim_start_beats;
|
||||
ci.trim_start_frames = self.trim_start_frames;
|
||||
ci.trim_end = self.trim_end;
|
||||
ci.trim_end_beats = self.trim_end_beats;
|
||||
ci.trim_end_frames = self.trim_end_frames;
|
||||
ci.timeline_duration = self.timeline_duration;
|
||||
ci.timeline_duration_beats = self.timeline_duration_beats;
|
||||
ci.timeline_duration_frames = self.timeline_duration_frames;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ClipTimingSnapshot {
|
||||
layer_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
old_fields: TimingFields,
|
||||
new_fields: TimingFields,
|
||||
}
|
||||
|
||||
/// Action that atomically changes framerate and rescales all clip positions to preserve frames
|
||||
/// Action that changes the document framerate.
|
||||
pub struct ChangeFpsAction {
|
||||
old_fps: f64,
|
||||
new_fps: f64,
|
||||
clip_snapshots: Vec<ClipTimingSnapshot>,
|
||||
}
|
||||
|
||||
impl ChangeFpsAction {
|
||||
/// Build the action, computing new positions for all clip instances.
|
||||
pub fn new(old_fps: f64, new_fps: f64, document: &Document) -> Self {
|
||||
let bpm = document.bpm;
|
||||
|
||||
let mut clip_snapshots: Vec<ClipTimingSnapshot> = Vec::new();
|
||||
|
||||
for layer in document.all_layers() {
|
||||
let layer_id = layer.id();
|
||||
|
||||
let clip_instances: &[ClipInstance] = match layer {
|
||||
AnyLayer::Vector(vl) => &vl.clip_instances,
|
||||
AnyLayer::Audio(al) => &al.clip_instances,
|
||||
AnyLayer::Video(vl) => &vl.clip_instances,
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) | AnyLayer::Raster(_) => continue,
|
||||
};
|
||||
|
||||
for ci in clip_instances {
|
||||
let old_fields = TimingFields::from_instance(ci);
|
||||
|
||||
// Compute new fields: frames are canonical, recompute seconds + beats
|
||||
let mut new_ci = ci.clone();
|
||||
new_ci.apply_frames(new_fps, bpm);
|
||||
let new_fields = TimingFields::from_instance(&new_ci);
|
||||
|
||||
clip_snapshots.push(ClipTimingSnapshot {
|
||||
layer_id,
|
||||
instance_id: ci.id,
|
||||
old_fields,
|
||||
new_fields,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
old_fps,
|
||||
new_fps,
|
||||
clip_snapshots,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_clips(document: &mut Document, snapshots: &[ClipTimingSnapshot], use_new: bool) {
|
||||
for snap in snapshots {
|
||||
let fields = if use_new { &snap.new_fields } else { &snap.old_fields };
|
||||
|
||||
let layer = match document.get_layer_mut(&snap.layer_id) {
|
||||
Some(l) => l,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let clip_instances = match layer {
|
||||
AnyLayer::Vector(vl) => &mut vl.clip_instances,
|
||||
AnyLayer::Audio(al) => &mut al.clip_instances,
|
||||
AnyLayer::Video(vl) => &mut vl.clip_instances,
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) | AnyLayer::Raster(_) => continue,
|
||||
};
|
||||
|
||||
if let Some(ci) = clip_instances.iter_mut().find(|ci| ci.id == snap.instance_id) {
|
||||
fields.apply_to(ci);
|
||||
}
|
||||
}
|
||||
/// Build the action from old and new framerates.
|
||||
pub fn new(old_fps: f64, new_fps: f64, _document: &Document) -> Self {
|
||||
Self { old_fps, new_fps }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ChangeFpsAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.framerate = self.new_fps;
|
||||
Self::apply_clips(document, &self.clip_snapshots, true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.framerate = self.old_fps;
|
||||
Self::apply_clips(document, &self.clip_snapshots, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -160,68 +37,18 @@ impl Action for ChangeFpsAction {
|
||||
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
_backend: &mut BackendContext,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
// FPS change does not affect audio timing — only move clips that changed position
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
for snap in &self.clip_snapshots {
|
||||
if (snap.new_fields.timeline_start - snap.old_fields.timeline_start).abs() < 1e-9 {
|
||||
continue; // No movement, skip
|
||||
}
|
||||
let track_id = match backend.layer_to_track_map.get(&snap.layer_id) {
|
||||
Some(&id) => id,
|
||||
None => continue,
|
||||
};
|
||||
let backend_id = backend.clip_instance_to_backend_map.get(&snap.instance_id);
|
||||
match backend_id {
|
||||
Some(crate::action::BackendClipInstanceId::Audio(audio_id)) => {
|
||||
controller.move_clip(track_id, *audio_id, snap.new_fields.timeline_start);
|
||||
}
|
||||
Some(crate::action::BackendClipInstanceId::Midi(midi_id)) => {
|
||||
controller.move_clip(track_id, *midi_id, snap.new_fields.timeline_start);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
// FPS does not affect audio scheduling — nothing to do in the backend.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
_backend: &mut BackendContext,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
for snap in &self.clip_snapshots {
|
||||
if (snap.new_fields.timeline_start - snap.old_fields.timeline_start).abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let track_id = match backend.layer_to_track_map.get(&snap.layer_id) {
|
||||
Some(&id) => id,
|
||||
None => continue,
|
||||
};
|
||||
let backend_id = backend.clip_instance_to_backend_map.get(&snap.instance_id);
|
||||
match backend_id {
|
||||
Some(crate::action::BackendClipInstanceId::Audio(audio_id)) => {
|
||||
controller.move_clip(track_id, *audio_id, snap.old_fields.timeline_start);
|
||||
}
|
||||
Some(crate::action::BackendClipInstanceId::Midi(midi_id)) => {
|
||||
controller.move_clip(track_id, *midi_id, snap.old_fields.timeline_start);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,9 +119,6 @@ impl Action for MoveClipInstancesAction {
|
||||
// Store adjusted moves for rollback
|
||||
self.layer_moves = adjusted_moves.clone();
|
||||
|
||||
let bpm = document.bpm;
|
||||
let fps = document.framerate;
|
||||
|
||||
// Apply all adjusted moves
|
||||
for (layer_id, moves) in &adjusted_moves {
|
||||
let layer = document.get_layer_mut(layer_id)
|
||||
@@ -142,7 +139,6 @@ impl Action for MoveClipInstancesAction {
|
||||
if let Some(clip_instance) = clip_instances.iter_mut().find(|ci| ci.id == *clip_id)
|
||||
{
|
||||
clip_instance.timeline_start = *new;
|
||||
clip_instance.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,8 +147,6 @@ impl Action for MoveClipInstancesAction {
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let bpm = document.bpm;
|
||||
let fps = document.framerate;
|
||||
for (layer_id, moves) in &self.layer_moves {
|
||||
let layer = document.get_layer_mut(layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
|
||||
@@ -172,7 +166,6 @@ impl Action for MoveClipInstancesAction {
|
||||
if let Some(clip_instance) = clip_instances.iter_mut().find(|ci| ci.id == *clip_id)
|
||||
{
|
||||
clip_instance.timeline_start = *old;
|
||||
clip_instance.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,10 +177,10 @@ impl Action for RemoveClipInstancesAction {
|
||||
let midi_instance = daw_backend::MidiClipInstance::new(
|
||||
0,
|
||||
*midi_clip_id,
|
||||
internal_start,
|
||||
internal_end,
|
||||
external_start,
|
||||
external_duration,
|
||||
daw_backend::Beats(internal_start),
|
||||
daw_backend::Beats(internal_end),
|
||||
daw_backend::Beats(external_start),
|
||||
daw_backend::Beats(external_duration),
|
||||
);
|
||||
|
||||
let query = Query::AddMidiClipInstanceSync(track_id, midi_instance);
|
||||
|
||||
@@ -126,8 +126,8 @@ impl Action for SplitClipInstanceAction {
|
||||
.get_clip_duration(&instance.clip_id)
|
||||
.ok_or_else(|| format!("Clip {} not found", instance.clip_id))?;
|
||||
|
||||
// Calculate the effective duration and timeline end
|
||||
let effective_duration = instance.effective_duration(clip_duration);
|
||||
// Calculate the effective duration and timeline end (both in beats)
|
||||
let effective_duration = instance.effective_duration(clip_duration, document.tempo_map());
|
||||
let timeline_end = instance.timeline_start + effective_duration;
|
||||
|
||||
// Validate: split_time must be strictly within the clip's timeline span
|
||||
@@ -179,7 +179,6 @@ impl Action for SplitClipInstanceAction {
|
||||
}
|
||||
|
||||
self.new_instance_id = Some(right_instance.id);
|
||||
right_instance.sync_from_seconds(document.bpm, document.framerate);
|
||||
|
||||
// Now modify the original (left) instance and add the new (right) instance
|
||||
let layer_mut = document
|
||||
@@ -239,21 +238,6 @@ impl Action for SplitClipInstanceAction {
|
||||
}
|
||||
}
|
||||
|
||||
// Sync derived fields on the left (original) instance
|
||||
let (bpm, fps) = (document.bpm, document.framerate);
|
||||
if let Some(layer) = document.get_layer_mut(&self.layer_id) {
|
||||
let cis: &mut Vec<crate::clip::ClipInstance> = match layer {
|
||||
AnyLayer::Vector(vl) => &mut vl.clip_instances,
|
||||
AnyLayer::Audio(al) => &mut al.clip_instances,
|
||||
AnyLayer::Video(vl) => &mut vl.clip_instances,
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
_ => return { self.executed = true; Ok(()) },
|
||||
};
|
||||
if let Some(inst) = cis.iter_mut().find(|ci| ci.id == self.instance_id) {
|
||||
inst.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
|
||||
self.executed = true;
|
||||
Ok(())
|
||||
}
|
||||
@@ -406,10 +390,10 @@ impl Action for SplitClipInstanceAction {
|
||||
let instance = daw_backend::MidiClipInstance::new(
|
||||
0,
|
||||
*midi_clip_id,
|
||||
internal_start,
|
||||
internal_end,
|
||||
external_start,
|
||||
external_duration,
|
||||
daw_backend::Beats(internal_start),
|
||||
daw_backend::Beats(internal_end),
|
||||
daw_backend::Beats(external_start),
|
||||
daw_backend::Beats(external_duration),
|
||||
);
|
||||
|
||||
let query = Query::AddMidiClipInstanceSync(*backend_track_id, instance);
|
||||
|
||||
@@ -101,7 +101,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
};
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
let member_old_trim = instance.trim_start;
|
||||
@@ -138,7 +138,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
};
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
let member_old_trim_end = instance.trim_end;
|
||||
@@ -182,7 +182,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
};
|
||||
};
|
||||
|
||||
let instance = clip_instances.iter()
|
||||
.find(|ci| &ci.id == instance_id)
|
||||
@@ -260,9 +260,6 @@ impl Action for TrimClipInstancesAction {
|
||||
// Store clamped trims for rollback
|
||||
self.layer_trims = clamped_trims.clone();
|
||||
|
||||
let bpm = document.bpm;
|
||||
let fps = document.framerate;
|
||||
|
||||
// Apply all clamped trims
|
||||
for (layer_id, trims) in &clamped_trims {
|
||||
let layer = match document.get_layer_mut(layer_id) {
|
||||
@@ -297,7 +294,6 @@ impl Action for TrimClipInstancesAction {
|
||||
clip_instance.trim_end = new.trim_value;
|
||||
}
|
||||
}
|
||||
clip_instance.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,8 +301,6 @@ impl Action for TrimClipInstancesAction {
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let bpm = document.bpm;
|
||||
let fps = document.framerate;
|
||||
for (layer_id, trims) in &self.layer_trims {
|
||||
let layer = match document.get_layer_mut(layer_id) {
|
||||
Some(l) => l,
|
||||
@@ -340,7 +334,6 @@ impl Action for TrimClipInstancesAction {
|
||||
clip_instance.trim_end = old.trim_value;
|
||||
}
|
||||
}
|
||||
clip_instance.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Beat/measure ↔ seconds conversion utilities
|
||||
|
||||
use crate::document::TimeSignature;
|
||||
use crate::tempo_map::TempoMap;
|
||||
|
||||
/// Position expressed as measure, beat, tick
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -11,9 +12,8 @@ pub struct MeasurePosition {
|
||||
}
|
||||
|
||||
/// Convert a time in seconds to a measure position
|
||||
pub fn time_to_measure(time: f64, bpm: f64, time_sig: &TimeSignature) -> MeasurePosition {
|
||||
let beats_per_second = bpm / 60.0;
|
||||
let total_beats = (time * beats_per_second).max(0.0);
|
||||
pub fn time_to_measure(time: f64, tempo_map: &TempoMap, time_sig: &TimeSignature) -> MeasurePosition {
|
||||
let total_beats = tempo_map.inverse_transform(time).max(0.0);
|
||||
let beats_per_measure = time_sig.numerator as f64;
|
||||
|
||||
let measure = (total_beats / beats_per_measure).floor() as u32 + 1;
|
||||
@@ -24,21 +24,20 @@ pub fn time_to_measure(time: f64, bpm: f64, time_sig: &TimeSignature) -> Measure
|
||||
}
|
||||
|
||||
/// Convert a measure position to seconds
|
||||
pub fn measure_to_time(pos: MeasurePosition, bpm: f64, time_sig: &TimeSignature) -> f64 {
|
||||
pub fn measure_to_time(pos: MeasurePosition, tempo_map: &TempoMap, time_sig: &TimeSignature) -> f64 {
|
||||
let beats_per_measure = time_sig.numerator as f64;
|
||||
let total_beats = (pos.measure as f64 - 1.0) * beats_per_measure
|
||||
+ (pos.beat as f64 - 1.0)
|
||||
+ (pos.tick as f64 / 1000.0);
|
||||
let beats_per_second = bpm / 60.0;
|
||||
total_beats / beats_per_second
|
||||
tempo_map.transform(total_beats)
|
||||
}
|
||||
|
||||
/// Get the duration of one beat in seconds
|
||||
pub fn beat_duration(bpm: f64) -> f64 {
|
||||
60.0 / bpm
|
||||
/// Get the duration of one beat in seconds at the given beat position
|
||||
pub fn beat_duration(beat: f64, tempo_map: &TempoMap) -> f64 {
|
||||
60.0 / tempo_map.bpm_at(daw_backend::Beats(beat))
|
||||
}
|
||||
|
||||
/// Get the duration of one measure in seconds
|
||||
pub fn measure_duration(bpm: f64, time_sig: &TimeSignature) -> f64 {
|
||||
beat_duration(bpm) * time_sig.numerator as f64
|
||||
/// Get the duration of one measure in seconds at the given beat position
|
||||
pub fn measure_duration(beat: f64, tempo_map: &TempoMap, time_sig: &TimeSignature) -> f64 {
|
||||
beat_duration(beat, tempo_map) * time_sig.numerator as f64
|
||||
}
|
||||
|
||||
@@ -98,15 +98,20 @@ impl VectorClip {
|
||||
///
|
||||
/// The `clip_duration_fn` resolves referenced clip durations for non-vector layers.
|
||||
/// Falls back to the stored `duration` field if no content exists.
|
||||
pub fn content_duration(&self, framerate: f64) -> f64 {
|
||||
self.content_duration_with(framerate, |_| None)
|
||||
pub fn content_duration(&self, framerate: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
self.content_duration_with(framerate, tempo_map, |_| None)
|
||||
}
|
||||
|
||||
/// Like `content_duration`, but with a closure that resolves clip durations
|
||||
/// for audio/video/effect clip instances inside this movie clip.
|
||||
pub fn content_duration_with(&self, framerate: f64, clip_duration_fn: impl Fn(&Uuid) -> Option<f64>) -> f64 {
|
||||
///
|
||||
/// `clip_duration_fn` returns clip content duration **in seconds**.
|
||||
/// Result is in **seconds**.
|
||||
pub fn content_duration_with(&self, framerate: f64, tempo_map: &crate::tempo_map::TempoMap, clip_duration_fn: impl Fn(&Uuid) -> Option<f64>) -> f64 {
|
||||
let frame_duration = 1.0 / framerate;
|
||||
let mut last_time: Option<f64> = None;
|
||||
// Work in beats, convert to seconds at the end.
|
||||
let mut last_beats: Option<f64> = None;
|
||||
let mut last_secs: Option<f64> = None;
|
||||
|
||||
for layer_node in self.layers.iter() {
|
||||
// Check clip instances on ALL layer types (vector, audio, video, effect)
|
||||
@@ -119,33 +124,38 @@ impl VectorClip {
|
||||
AnyLayer::Raster(_) => &[],
|
||||
};
|
||||
for ci in clip_instances {
|
||||
let end = if let Some(td) = ci.timeline_duration {
|
||||
ci.timeline_start + td
|
||||
// Compute end position of this clip instance in beats
|
||||
let end_beats = if let Some(td_beats) = ci.timeline_duration {
|
||||
ci.timeline_start + td_beats
|
||||
} else if let Some(te) = ci.trim_end {
|
||||
ci.timeline_start + (te - ci.trim_start).max(0.0)
|
||||
} else if let Some(clip_dur) = clip_duration_fn(&ci.clip_id) {
|
||||
ci.timeline_start + (clip_dur - ci.trim_start).max(0.0)
|
||||
let secs = (te - ci.trim_start).max(0.0);
|
||||
ci.timeline_start + tempo_map.inverse_transform(tempo_map.transform(ci.timeline_start) + secs) - ci.timeline_start
|
||||
} else if let Some(clip_dur_secs) = clip_duration_fn(&ci.clip_id) {
|
||||
let secs = (clip_dur_secs - ci.trim_start).max(0.0);
|
||||
ci.timeline_start + tempo_map.inverse_transform(tempo_map.transform(ci.timeline_start) + secs) - ci.timeline_start
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
last_time = Some(match last_time {
|
||||
Some(t) => t.max(end),
|
||||
None => end,
|
||||
});
|
||||
last_beats = Some(last_beats.map_or(end_beats, |t: f64| t.max(end_beats)));
|
||||
}
|
||||
|
||||
// Also check vector layer keyframes
|
||||
// Vector layer keyframes are in seconds
|
||||
if let AnyLayer::Vector(vector_layer) = &layer_node.data {
|
||||
if let Some(last_kf) = vector_layer.keyframes.last() {
|
||||
last_time = Some(match last_time {
|
||||
Some(t) => t.max(last_kf.time),
|
||||
None => last_kf.time,
|
||||
});
|
||||
last_secs = Some(last_secs.map_or(last_kf.time, |t: f64| t.max(last_kf.time)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match last_time {
|
||||
let from_clips = last_beats.map(|b| tempo_map.transform(b));
|
||||
let combined = match (from_clips, last_secs) {
|
||||
(Some(a), Some(b)) => Some(a.max(b)),
|
||||
(Some(a), None) => Some(a),
|
||||
(None, Some(b)) => Some(b),
|
||||
(None, None) => None,
|
||||
};
|
||||
|
||||
match combined {
|
||||
Some(t) => t + frame_duration,
|
||||
None => self.duration,
|
||||
}
|
||||
@@ -186,9 +196,10 @@ impl VectorClip {
|
||||
|
||||
// Handle nested clip instances recursively
|
||||
for clip_instance in &vector_layer.clip_instances {
|
||||
// Convert parent clip time to nested clip local time
|
||||
// Apply timeline offset and playback speed, then add trim offset
|
||||
let nested_clip_time = ((clip_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
// Convert parent clip time (seconds) to nested clip local time (seconds).
|
||||
// timeline_start is in beats; convert to seconds using document BPM.
|
||||
let start_secs = document.tempo_map().transform(clip_instance.timeline_start);
|
||||
let nested_clip_time = ((clip_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
|
||||
// Look up the nested clip definition
|
||||
let nested_bounds = if let Some(nested_clip) = document.get_vector_clip(&clip_instance.clip_id) {
|
||||
@@ -485,12 +496,12 @@ impl AudioClip {
|
||||
pub fn new_midi(
|
||||
name: impl Into<String>,
|
||||
midi_clip_id: u32,
|
||||
duration: f64,
|
||||
duration: daw_backend::Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4(),
|
||||
name: name.into(),
|
||||
duration,
|
||||
duration: duration.beats_to_f64(),
|
||||
clip_type: AudioClipType::Midi { midi_clip_id },
|
||||
folder_id: None,
|
||||
}
|
||||
@@ -589,6 +600,12 @@ impl AnyClip {
|
||||
/// - Timeline placement (when this instance appears on the parent layer's timeline)
|
||||
/// - Trimming (trim_start, trim_end within the clip's internal content)
|
||||
/// - Playback speed (time remapping)
|
||||
///
|
||||
/// ## Coordinate systems
|
||||
/// - `timeline_start` / `timeline_duration` are in **beats** (quarter-note beats).
|
||||
/// Use [`crate::tempo_map::TempoMap::beats_to_seconds`] to convert to seconds.
|
||||
/// - `trim_start` / `trim_end` are in **seconds** (audio/video file seek offsets;
|
||||
/// not affected by BPM changes).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ClipInstance {
|
||||
/// Unique identifier for this instance
|
||||
@@ -606,52 +623,25 @@ pub struct ClipInstance {
|
||||
/// Optional name for this instance
|
||||
pub name: Option<String>,
|
||||
|
||||
/// When this instance starts on the timeline (in seconds, relative to parent layer)
|
||||
/// This is the external positioning - where the instance appears on the timeline
|
||||
/// Default: 0.0 (start at beginning of layer)
|
||||
/// When this instance starts on the timeline, in **beats**.
|
||||
/// Default: 0.0
|
||||
pub timeline_start: f64,
|
||||
/// timeline_start in beats (quarter-note beats); derived from timeline_start
|
||||
#[serde(default)]
|
||||
pub timeline_start_beats: f64,
|
||||
/// timeline_start in frames; derived from timeline_start
|
||||
#[serde(default)]
|
||||
pub timeline_start_frames: f64,
|
||||
|
||||
/// How long this instance appears on the timeline (in seconds)
|
||||
/// If timeline_duration > (trim_end - trim_start), the trimmed content will loop
|
||||
/// How long this instance appears on the timeline, in **beats**.
|
||||
/// If set and longer than the trimmed content, the content will loop.
|
||||
/// Default: None (use trimmed clip duration, no looping)
|
||||
pub timeline_duration: Option<f64>,
|
||||
/// timeline_duration in beats; derived from timeline_duration
|
||||
#[serde(default)]
|
||||
pub timeline_duration_beats: Option<f64>,
|
||||
/// timeline_duration in frames; derived from timeline_duration
|
||||
#[serde(default)]
|
||||
pub timeline_duration_frames: Option<f64>,
|
||||
|
||||
/// Trim start: offset into the clip's internal content (in seconds)
|
||||
/// Allows trimming the beginning of the clip
|
||||
/// - For audio: offset into the audio file
|
||||
/// - For video: offset into the video file
|
||||
/// - For vector: offset into the animation timeline
|
||||
/// Default: 0.0 (start at beginning of clip)
|
||||
/// Trim start: offset into the clip's internal content, in **seconds**.
|
||||
/// - For audio: byte-offset into the audio file
|
||||
/// - For video: seek position in the video file
|
||||
/// - For vector: time offset into the animation
|
||||
/// Default: 0.0
|
||||
pub trim_start: f64,
|
||||
/// trim_start in beats; derived from trim_start
|
||||
#[serde(default)]
|
||||
pub trim_start_beats: f64,
|
||||
/// trim_start in frames; derived from trim_start
|
||||
#[serde(default)]
|
||||
pub trim_start_frames: f64,
|
||||
|
||||
/// Trim end: offset into the clip's internal content (in seconds)
|
||||
/// Allows trimming the end of the clip
|
||||
/// Trim end: offset into the clip's internal content, in **seconds**.
|
||||
/// Default: None (use full clip duration)
|
||||
pub trim_end: Option<f64>,
|
||||
/// trim_end in beats; derived from trim_end
|
||||
#[serde(default)]
|
||||
pub trim_end_beats: Option<f64>,
|
||||
/// trim_end in frames; derived from trim_end
|
||||
#[serde(default)]
|
||||
pub trim_end_frames: Option<f64>,
|
||||
|
||||
/// Playback speed multiplier
|
||||
/// 1.0 = normal speed, 0.5 = half speed, 2.0 = double speed
|
||||
@@ -663,7 +653,7 @@ pub struct ClipInstance {
|
||||
/// Default: 1.0
|
||||
pub gain: f32,
|
||||
|
||||
/// How far (in seconds) the looped content extends before timeline_start.
|
||||
/// How far (in beats) the looped content extends before timeline_start.
|
||||
/// When set, loop iterations are drawn/played before the content start.
|
||||
/// Default: None (no pre-loop)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -720,17 +710,9 @@ impl ClipInstance {
|
||||
opacity: 1.0,
|
||||
name: None,
|
||||
timeline_start: 0.0,
|
||||
timeline_start_beats: 0.0,
|
||||
timeline_start_frames: 0.0,
|
||||
timeline_duration: None,
|
||||
timeline_duration_beats: None,
|
||||
timeline_duration_frames: None,
|
||||
trim_start: 0.0,
|
||||
trim_start_beats: 0.0,
|
||||
trim_start_frames: 0.0,
|
||||
trim_end: None,
|
||||
trim_end_beats: None,
|
||||
trim_end_frames: None,
|
||||
playback_speed: 1.0,
|
||||
gain: 1.0,
|
||||
loop_before: None,
|
||||
@@ -746,71 +728,15 @@ impl ClipInstance {
|
||||
opacity: 1.0,
|
||||
name: None,
|
||||
timeline_start: 0.0,
|
||||
timeline_start_beats: 0.0,
|
||||
timeline_start_frames: 0.0,
|
||||
timeline_duration: None,
|
||||
timeline_duration_beats: None,
|
||||
timeline_duration_frames: None,
|
||||
trim_start: 0.0,
|
||||
trim_start_beats: 0.0,
|
||||
trim_start_frames: 0.0,
|
||||
trim_end: None,
|
||||
trim_end_beats: None,
|
||||
trim_end_frames: None,
|
||||
playback_speed: 1.0,
|
||||
gain: 1.0,
|
||||
loop_before: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sync beats and frames from the seconds fields (call after any seconds-based write).
|
||||
pub fn sync_from_seconds(&mut self, bpm: f64, fps: f64) {
|
||||
self.timeline_start_beats = self.timeline_start * bpm / 60.0;
|
||||
self.timeline_start_frames = self.timeline_start * fps;
|
||||
self.trim_start_beats = self.trim_start * bpm / 60.0;
|
||||
self.trim_start_frames = self.trim_start * fps;
|
||||
self.trim_end_beats = self.trim_end.map(|v| v * bpm / 60.0);
|
||||
self.trim_end_frames = self.trim_end.map(|v| v * fps);
|
||||
self.timeline_duration_beats = self.timeline_duration.map(|v| v * bpm / 60.0);
|
||||
self.timeline_duration_frames = self.timeline_duration.map(|v| v * fps);
|
||||
}
|
||||
|
||||
/// Recompute seconds and frames from beats (call when BPM changes in Measures mode).
|
||||
pub fn apply_beats(&mut self, bpm: f64, fps: f64) {
|
||||
self.timeline_start = self.timeline_start_beats * 60.0 / bpm;
|
||||
self.timeline_start_frames = self.timeline_start * fps;
|
||||
self.trim_start = self.trim_start_beats * 60.0 / bpm;
|
||||
self.trim_start_frames = self.trim_start * fps;
|
||||
if let Some(b) = self.trim_end_beats {
|
||||
let s = b * 60.0 / bpm;
|
||||
self.trim_end = Some(s);
|
||||
self.trim_end_frames = Some(s * fps);
|
||||
}
|
||||
if let Some(b) = self.timeline_duration_beats {
|
||||
let s = b * 60.0 / bpm;
|
||||
self.timeline_duration = Some(s);
|
||||
self.timeline_duration_frames = Some(s * fps);
|
||||
}
|
||||
}
|
||||
|
||||
/// Recompute seconds and beats from frames (call when FPS changes in Frames mode).
|
||||
pub fn apply_frames(&mut self, fps: f64, bpm: f64) {
|
||||
self.timeline_start = self.timeline_start_frames / fps;
|
||||
self.timeline_start_beats = self.timeline_start * bpm / 60.0;
|
||||
self.trim_start = self.trim_start_frames / fps;
|
||||
self.trim_start_beats = self.trim_start * bpm / 60.0;
|
||||
if let Some(f) = self.trim_end_frames {
|
||||
let s = f / fps;
|
||||
self.trim_end = Some(s);
|
||||
self.trim_end_beats = Some(s * bpm / 60.0);
|
||||
}
|
||||
if let Some(f) = self.timeline_duration_frames {
|
||||
let s = f / fps;
|
||||
self.timeline_duration = Some(s);
|
||||
self.timeline_duration_beats = Some(s * bpm / 60.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the transform
|
||||
pub fn with_transform(mut self, transform: Transform) -> Self {
|
||||
self.transform = transform;
|
||||
@@ -861,83 +787,83 @@ impl ClipInstance {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set explicit timeline duration by setting trim_end
|
||||
///
|
||||
/// For effect instances, this effectively sets the duration since
|
||||
/// effects have infinite internal duration (trim_start defaults to 0).
|
||||
pub fn with_timeline_duration(mut self, duration: f64) -> Self {
|
||||
self.trim_end = Some(self.trim_start + duration);
|
||||
/// Set explicit timeline duration (in beats) by directly setting `timeline_duration`.
|
||||
pub fn with_timeline_duration(mut self, duration_beats: f64) -> Self {
|
||||
self.timeline_duration = Some(duration_beats);
|
||||
self
|
||||
}
|
||||
|
||||
/// Get the effective duration of this instance (accounting for trimming and looping)
|
||||
/// If timeline_duration is set, returns that (enabling content looping)
|
||||
/// Otherwise returns the trimmed content duration
|
||||
pub fn effective_duration(&self, clip_duration: f64) -> f64 {
|
||||
// If timeline_duration is explicitly set, use that (for looping)
|
||||
if let Some(timeline_dur) = self.timeline_duration {
|
||||
return timeline_dur;
|
||||
}
|
||||
|
||||
// Otherwise, return the trimmed content duration
|
||||
let end = self.trim_end.unwrap_or(clip_duration);
|
||||
/// Content window size in seconds: `trim_end - trim_start`.
|
||||
/// Used for internal looping calculations.
|
||||
pub fn content_window_secs(&self, clip_duration_secs: f64) -> f64 {
|
||||
let end = self.trim_end.unwrap_or(clip_duration_secs);
|
||||
(end - self.trim_start).max(0.0)
|
||||
}
|
||||
|
||||
/// Get the effective start position on the timeline, accounting for loop_before.
|
||||
/// This is the left edge of the clip's visual extent.
|
||||
/// How long this instance appears on the timeline, in **beats**.
|
||||
///
|
||||
/// If `timeline_duration` is set, returns that (enabling content looping).
|
||||
/// Otherwise converts the content window from seconds to beats using the tempo map.
|
||||
pub fn effective_duration_beats(&self, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
if let Some(td) = self.timeline_duration {
|
||||
return td;
|
||||
}
|
||||
let window_secs = self.content_window_secs(clip_duration_secs);
|
||||
let start_secs = tempo_map.transform(self.timeline_start);
|
||||
tempo_map.inverse_transform(start_secs + window_secs) - self.timeline_start
|
||||
}
|
||||
|
||||
/// Left edge of the clip's visual extent on the timeline, in **beats**.
|
||||
pub fn effective_start(&self) -> f64 {
|
||||
self.timeline_start - self.loop_before.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Get the total visual duration including both loop_before and effective_duration.
|
||||
pub fn total_duration(&self, clip_duration: f64) -> f64 {
|
||||
self.loop_before.unwrap_or(0.0) + self.effective_duration(clip_duration)
|
||||
/// Total visual duration (loop_before + effective_duration), in **beats**.
|
||||
pub fn total_duration(&self, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
self.loop_before.unwrap_or(0.0) + self.effective_duration_beats(clip_duration_secs, tempo_map)
|
||||
}
|
||||
|
||||
/// Remap timeline time to clip content time
|
||||
/// Map a playback time (in **seconds**) to clip-local content time (in **seconds**).
|
||||
///
|
||||
/// Takes a global timeline time and returns the corresponding time within this
|
||||
/// clip's content, accounting for:
|
||||
/// - Instance position (timeline_start)
|
||||
/// - Playback speed
|
||||
/// - Trimming (trim_start, trim_end)
|
||||
/// - Looping (if timeline_duration > content window)
|
||||
///
|
||||
/// Returns None if the clip instance is not active at the given timeline time.
|
||||
pub fn remap_time(&self, timeline_time: f64, clip_duration: f64) -> Option<f64> {
|
||||
// Check if clip instance is active at this time
|
||||
let instance_end = self.timeline_start + self.effective_duration(clip_duration);
|
||||
if timeline_time < self.timeline_start || timeline_time >= instance_end {
|
||||
/// Returns `None` if the clip instance is not active at `time_secs`.
|
||||
pub fn remap_time_secs(&self, time_secs: f64, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> Option<f64> {
|
||||
let start_secs = tempo_map.transform(self.timeline_start);
|
||||
let dur_beats = self.effective_duration_beats(clip_duration_secs, tempo_map);
|
||||
let end_secs = tempo_map.transform(self.timeline_start + dur_beats);
|
||||
|
||||
if time_secs < start_secs || time_secs >= end_secs {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Calculate relative time within the instance (0.0 = start of instance)
|
||||
let relative_time = timeline_time - self.timeline_start;
|
||||
let relative_secs = time_secs - start_secs;
|
||||
let content_time = relative_secs * self.playback_speed;
|
||||
let content_window = self.content_window_secs(clip_duration_secs);
|
||||
|
||||
// Account for playback speed
|
||||
let content_time = relative_time * self.playback_speed;
|
||||
|
||||
// Get the content window size (the portion of clip we're sampling)
|
||||
let trim_end = self.trim_end.unwrap_or(clip_duration);
|
||||
let content_window = (trim_end - self.trim_start).max(0.0);
|
||||
|
||||
// If content_window is zero, can't sample anything
|
||||
if content_window == 0.0 {
|
||||
return Some(self.trim_start);
|
||||
}
|
||||
|
||||
// Apply looping if content exceeds the window
|
||||
let looped_time = if content_time > content_window {
|
||||
content_time % content_window
|
||||
} else {
|
||||
content_time
|
||||
};
|
||||
|
||||
// Add trim_start offset to get final clip time
|
||||
Some(self.trim_start + looped_time)
|
||||
}
|
||||
|
||||
/// Alias for `remap_time_secs`.
|
||||
#[inline]
|
||||
pub fn remap_time(&self, time_secs: f64, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> Option<f64> {
|
||||
self.remap_time_secs(time_secs, clip_duration_secs, tempo_map)
|
||||
}
|
||||
|
||||
/// Alias for `effective_duration_beats`.
|
||||
#[inline]
|
||||
pub fn effective_duration(&self, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
self.effective_duration_beats(clip_duration_secs, tempo_map)
|
||||
}
|
||||
|
||||
/// Convert to affine transform
|
||||
pub fn to_affine(&self) -> vello::kurbo::Affine {
|
||||
self.transform.to_affine()
|
||||
|
||||
@@ -6,10 +6,11 @@
|
||||
use crate::asset_folder::AssetFolderTree;
|
||||
use crate::clip::{AudioClip, ClipInstance, ImageAsset, VideoClip, VectorClip};
|
||||
use crate::effect::EffectDefinition;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::layer::{AnyLayer, GroupLayer};
|
||||
use crate::script::ScriptDefinition;
|
||||
use crate::layout::LayoutNode;
|
||||
use crate::shape::ShapeColor;
|
||||
use crate::tempo_map::TempoMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
@@ -131,6 +132,8 @@ impl Default for TimeSignature {
|
||||
}
|
||||
}
|
||||
|
||||
// Keep for backward serde compat (old files may have a `bpm` field); no longer used.
|
||||
#[allow(dead_code)]
|
||||
fn default_bpm() -> f64 { 120.0 }
|
||||
|
||||
/// How time is displayed in the timeline
|
||||
@@ -173,14 +176,16 @@ pub struct Document {
|
||||
/// Framerate (frames per second)
|
||||
pub framerate: f64,
|
||||
|
||||
/// Tempo in beats per minute
|
||||
#[serde(default = "default_bpm")]
|
||||
pub bpm: f64,
|
||||
|
||||
/// Time signature
|
||||
#[serde(default)]
|
||||
pub time_signature: TimeSignature,
|
||||
|
||||
/// Master track (master bus + tempo automation lane).
|
||||
/// Stored separately from the root layer tree; shown in timeline when
|
||||
/// `show_master_track` is enabled in the editor state.
|
||||
#[serde(default)]
|
||||
pub master_layer: GroupLayer,
|
||||
|
||||
/// Duration in seconds
|
||||
pub duration: f64,
|
||||
|
||||
@@ -266,8 +271,12 @@ impl Default for Document {
|
||||
width: 1920.0,
|
||||
height: 1080.0,
|
||||
framerate: 60.0,
|
||||
bpm: 120.0,
|
||||
time_signature: TimeSignature::default(),
|
||||
master_layer: {
|
||||
let mut ml = GroupLayer::new_master(120.0);
|
||||
ml.layer.id = uuid::Uuid::new_v4();
|
||||
ml
|
||||
},
|
||||
duration: 10.0,
|
||||
root: GraphicsObject::default(),
|
||||
vector_clips: HashMap::new(),
|
||||
@@ -311,6 +320,28 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference to the document's tempo map (stored on the master layer).
|
||||
pub fn tempo_map(&self) -> &TempoMap {
|
||||
self.master_layer.tempo_map.as_ref()
|
||||
.expect("master_layer always has a tempo_map")
|
||||
}
|
||||
|
||||
/// Mutable reference to the document's tempo map.
|
||||
pub fn tempo_map_mut(&mut self) -> &mut TempoMap {
|
||||
self.master_layer.tempo_map.as_mut()
|
||||
.expect("master_layer always has a tempo_map")
|
||||
}
|
||||
|
||||
/// Convenience accessor for the global BPM (first entry of the tempo map).
|
||||
pub fn bpm(&self) -> f64 {
|
||||
self.tempo_map().global_bpm()
|
||||
}
|
||||
|
||||
/// Set the global BPM. Rebuilds the tempo map's seconds cache.
|
||||
pub fn set_bpm(&mut self, bpm: f64) {
|
||||
self.tempo_map_mut().set_global_bpm(bpm);
|
||||
}
|
||||
|
||||
/// Rebuild the layer→clip reverse lookup map from all vector clips.
|
||||
/// Call after deserialization or bulk clip modifications.
|
||||
pub fn rebuild_layer_to_clip_map(&mut self) {
|
||||
@@ -619,56 +650,6 @@ impl Document {
|
||||
layers
|
||||
}
|
||||
|
||||
/// Migrate old documents: compute beats/frames from seconds for any ClipInstance whose
|
||||
/// derived fields are still zero (i.e., documents saved before triple-representation).
|
||||
/// Call once after loading a document.
|
||||
pub fn sync_all_clip_positions(&mut self) {
|
||||
let bpm = self.bpm;
|
||||
let fps = self.framerate;
|
||||
|
||||
fn sync_list(list: &mut [crate::layer::AnyLayer], bpm: f64, fps: f64) {
|
||||
for layer in list.iter_mut() {
|
||||
match layer {
|
||||
crate::layer::AnyLayer::Vector(vl) => {
|
||||
for ci in &mut vl.clip_instances {
|
||||
if ci.timeline_start_beats == 0.0 { ci.sync_from_seconds(bpm, fps); }
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Audio(al) => {
|
||||
for ci in &mut al.clip_instances {
|
||||
if ci.timeline_start_beats == 0.0 { ci.sync_from_seconds(bpm, fps); }
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Video(vl) => {
|
||||
for ci in &mut vl.clip_instances {
|
||||
if ci.timeline_start_beats == 0.0 { ci.sync_from_seconds(bpm, fps); }
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Effect(el) => {
|
||||
for ci in &mut el.clip_instances {
|
||||
if ci.timeline_start_beats == 0.0 { ci.sync_from_seconds(bpm, fps); }
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Group(g) => {
|
||||
sync_list(&mut g.children, bpm, fps);
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sync_list(&mut self.root.children, bpm, fps);
|
||||
for clip in self.vector_clips.values_mut() {
|
||||
for node in &mut clip.layers.roots {
|
||||
if let crate::layer::AnyLayer::Vector(vl) = &mut node.data {
|
||||
for ci in &mut vl.clip_instances {
|
||||
if ci.timeline_start_beats == 0.0 { ci.sync_from_seconds(bpm, fps); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === CLIP LIBRARY METHODS ===
|
||||
|
||||
/// Add a vector clip to the library
|
||||
@@ -866,11 +847,12 @@ impl Document {
|
||||
if clip.is_group {
|
||||
Some(clip.duration)
|
||||
} else {
|
||||
Some(clip.content_duration_with(self.framerate, |id| {
|
||||
let tempo_map = self.tempo_map();
|
||||
Some(clip.content_duration_with(self.framerate, tempo_map, |id| {
|
||||
// Resolve nested clip durations (audio, video, other vector clips)
|
||||
if let Some(vc) = self.vector_clips.get(id) {
|
||||
// Avoid deep recursion — use stored duration for nested vector clips
|
||||
Some(vc.content_duration(self.framerate))
|
||||
Some(vc.content_duration(self.framerate, tempo_map))
|
||||
} else if let Some(ac) = self.audio_clips.get(id) {
|
||||
Some(ac.duration)
|
||||
} else if let Some(vc) = self.video_clips.get(id) {
|
||||
@@ -961,7 +943,7 @@ impl Document {
|
||||
};
|
||||
|
||||
let instance_start = instance.effective_start();
|
||||
let instance_end = instance.timeline_start + instance.effective_duration(clip_duration);
|
||||
let instance_end = instance.timeline_start + instance.effective_duration(clip_duration, self.tempo_map());
|
||||
|
||||
// Check overlap: start_a < end_b AND start_b < end_a
|
||||
if start_time < instance_end && instance_start < end_time {
|
||||
@@ -1019,7 +1001,7 @@ impl Document {
|
||||
|
||||
if let Some(clip_dur) = self.get_clip_duration(&instance.clip_id) {
|
||||
let inst_start = instance.effective_start();
|
||||
let inst_end = instance.timeline_start + instance.effective_duration(clip_dur);
|
||||
let inst_end = instance.timeline_start + instance.effective_duration(clip_dur, self.tempo_map());
|
||||
occupied_ranges.push((inst_start, inst_end, instance.id));
|
||||
}
|
||||
}
|
||||
@@ -1114,7 +1096,7 @@ impl Document {
|
||||
}
|
||||
if let Some(dur) = self.get_clip_duration(&inst.clip_id) {
|
||||
let start = inst.effective_start();
|
||||
let end = inst.timeline_start + inst.effective_duration(dur);
|
||||
let end = inst.timeline_start + inst.effective_duration(dur, self.tempo_map());
|
||||
non_group.push((start, end));
|
||||
}
|
||||
}
|
||||
@@ -1184,7 +1166,7 @@ impl Document {
|
||||
|
||||
// Calculate other clip's extent (accounting for loop_before)
|
||||
if let Some(clip_duration) = self.get_clip_duration(&other.clip_id) {
|
||||
let other_end = other.timeline_start + other.effective_duration(clip_duration);
|
||||
let other_end = other.timeline_start + other.effective_duration(clip_duration, self.tempo_map());
|
||||
|
||||
// If this clip is to the left and closer than current nearest
|
||||
if other_end <= current_timeline_start && other_end > nearest_end {
|
||||
@@ -1280,7 +1262,7 @@ impl Document {
|
||||
}
|
||||
|
||||
if let Some(clip_duration) = self.get_clip_duration(&other.clip_id) {
|
||||
let other_end = other.timeline_start + other.effective_duration(clip_duration);
|
||||
let other_end = other.timeline_start + other.effective_duration(clip_duration, self.tempo_map());
|
||||
|
||||
if other_end <= current_effective_start && other_end > nearest_end {
|
||||
nearest_end = other_end;
|
||||
|
||||
@@ -142,16 +142,18 @@ impl EffectLayer {
|
||||
self.clip_instances.iter_mut().find(|e| &e.id == id)
|
||||
}
|
||||
|
||||
/// Get all clip instances (effects) that are active at a given time
|
||||
/// Get all clip instances (effects) that are active at a given time.
|
||||
///
|
||||
/// Uses `EFFECT_DURATION` to calculate effective duration for each instance.
|
||||
pub fn active_clip_instances_at(&self, time: f64) -> Vec<&ClipInstance> {
|
||||
/// `time_secs` is the playback time in seconds; `bpm` is used to convert
|
||||
/// `timeline_start` (beats) to seconds for comparison.
|
||||
pub fn active_clip_instances_at(&self, time_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> Vec<&ClipInstance> {
|
||||
use crate::effect::EFFECT_DURATION;
|
||||
let time_beats = tempo_map.inverse_transform(time_secs);
|
||||
self.clip_instances
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
let end = e.timeline_start + e.effective_duration(EFFECT_DURATION);
|
||||
time >= e.timeline_start && time < end
|
||||
let end = e.timeline_start + e.effective_duration(EFFECT_DURATION, tempo_map);
|
||||
time_beats >= e.timeline_start && time_beats < end
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -239,13 +241,13 @@ mod tests {
|
||||
layer.add_clip_instance(effect2);
|
||||
|
||||
// At time 2: only effect1 active
|
||||
assert_eq!(layer.active_clip_instances_at(2.0).len(), 1);
|
||||
assert_eq!(layer.active_clip_instances_at(2.0, 60.0).len(), 1);
|
||||
|
||||
// At time 4: both effects active
|
||||
assert_eq!(layer.active_clip_instances_at(4.0).len(), 2);
|
||||
assert_eq!(layer.active_clip_instances_at(4.0, 60.0).len(), 2);
|
||||
|
||||
// At time 7: only effect2 active
|
||||
assert_eq!(layer.active_clip_instances_at(7.0).len(), 1);
|
||||
assert_eq!(layer.active_clip_instances_at(7.0, 60.0).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -76,6 +76,9 @@ pub struct AudioExportSettings {
|
||||
|
||||
/// End time in seconds
|
||||
pub end_time: f64,
|
||||
|
||||
/// Project BPM (for beat-position scheduling during export)
|
||||
pub bpm: f64,
|
||||
}
|
||||
|
||||
impl Default for AudioExportSettings {
|
||||
@@ -88,6 +91,7 @@ impl Default for AudioExportSettings {
|
||||
bitrate_kbps: 320,
|
||||
start_time: 0.0,
|
||||
end_time: 60.0,
|
||||
bpm: 120.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,6 +491,8 @@ pub fn load_beam(path: &Path) -> Result<LoadedProject, String> {
|
||||
// 5. Extract document and audio backend state
|
||||
let step5_start = std::time::Instant::now();
|
||||
let mut document = beam_project.ui_state;
|
||||
// Rebuild derived seconds cache on all TempoMap entries after deserialization.
|
||||
document.tempo_map_mut().rebuild_seconds();
|
||||
let mut audio_project = beam_project.audio_backend.project;
|
||||
let audio_pool_entries = beam_project.audio_backend.audio_pool_entries;
|
||||
let layer_to_track_map = beam_project.audio_backend.layer_to_track_map;
|
||||
|
||||
@@ -256,15 +256,20 @@ pub fn hit_test_clip_instances(
|
||||
parent_transform: Affine,
|
||||
timeline_time: f64,
|
||||
) -> Option<Uuid> {
|
||||
let tempo_map = document.tempo_map();
|
||||
for clip_instance in clip_instances.iter().rev() {
|
||||
// Check time bounds: skip clip instances not active at this time
|
||||
// timeline_start/instance_end are in beats; convert timeline_time (seconds) to beats.
|
||||
let clip_duration = document.get_clip_duration(&clip_instance.clip_id).unwrap_or(0.0);
|
||||
let instance_end = clip_instance.timeline_start + clip_instance.effective_duration(clip_duration);
|
||||
if timeline_time < clip_instance.timeline_start || timeline_time >= instance_end {
|
||||
let instance_end = clip_instance.timeline_start + clip_instance.effective_duration(clip_duration, tempo_map);
|
||||
let timeline_beats = tempo_map.inverse_transform(timeline_time);
|
||||
if timeline_beats < clip_instance.timeline_start || timeline_beats >= instance_end {
|
||||
continue;
|
||||
}
|
||||
|
||||
let clip_time = ((timeline_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
// clip_time is in seconds; offset from clip start (in seconds) + trim_start (seconds)
|
||||
let start_secs = tempo_map.transform(clip_instance.timeline_start);
|
||||
let clip_time = ((timeline_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
|
||||
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&clip_instance.clip_id) {
|
||||
vector_clip.calculate_content_bounds(document, clip_time)
|
||||
@@ -294,16 +299,20 @@ pub fn hit_test_clip_instances_in_rect(
|
||||
timeline_time: f64,
|
||||
) -> Vec<Uuid> {
|
||||
let mut hits = Vec::new();
|
||||
let tempo_map = document.tempo_map();
|
||||
|
||||
for clip_instance in clip_instances {
|
||||
// Check time bounds: skip clip instances not active at this time
|
||||
// timeline_start/instance_end are in beats; convert timeline_time (seconds) to beats.
|
||||
let clip_duration = document.get_clip_duration(&clip_instance.clip_id).unwrap_or(0.0);
|
||||
let instance_end = clip_instance.timeline_start + clip_instance.effective_duration(clip_duration);
|
||||
if timeline_time < clip_instance.timeline_start || timeline_time >= instance_end {
|
||||
let instance_end = clip_instance.timeline_start + clip_instance.effective_duration(clip_duration, tempo_map);
|
||||
let timeline_beats = tempo_map.inverse_transform(timeline_time);
|
||||
if timeline_beats < clip_instance.timeline_start || timeline_beats >= instance_end {
|
||||
continue;
|
||||
}
|
||||
|
||||
let clip_time = ((timeline_time - clip_instance.timeline_start) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
let start_secs = tempo_map.transform(clip_instance.timeline_start);
|
||||
let clip_time = ((timeline_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
|
||||
let content_bounds = if let Some(vector_clip) = document.get_vector_clip(&clip_instance.clip_id) {
|
||||
vector_clip.calculate_content_bounds(document, clip_time)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Layers organize objects and shapes, and contain animation data.
|
||||
|
||||
use crate::animation::AnimationData;
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::vector_graph::VectorGraph;
|
||||
use crate::effect_layer::EffectLayer;
|
||||
@@ -720,6 +721,12 @@ pub struct GroupLayer {
|
||||
/// Whether the group is expanded in the timeline
|
||||
#[serde(default = "default_true")]
|
||||
pub expanded: bool,
|
||||
|
||||
/// Optional tempo map for this group. When `Some`, the group's children use
|
||||
/// this tempo map for beat-to-parent-time conversion. The master group always
|
||||
/// has `Some`; regular groups default to `None` (inherit parent tempo).
|
||||
#[serde(default)]
|
||||
pub tempo_map: Option<TempoMap>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
@@ -746,6 +753,12 @@ impl LayerTrait for GroupLayer {
|
||||
fn set_locked(&mut self, locked: bool) { self.layer.locked = locked; }
|
||||
}
|
||||
|
||||
impl Default for GroupLayer {
|
||||
fn default() -> Self {
|
||||
Self::new("Group")
|
||||
}
|
||||
}
|
||||
|
||||
impl GroupLayer {
|
||||
/// Create a new group layer
|
||||
pub fn new(name: impl Into<String>) -> Self {
|
||||
@@ -753,6 +766,21 @@ impl GroupLayer {
|
||||
layer: Layer::new(LayerType::Group, name),
|
||||
children: Vec::new(),
|
||||
expanded: true,
|
||||
tempo_map: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a master group layer with a constant tempo.
|
||||
pub fn new_master(bpm: f64) -> Self {
|
||||
Self {
|
||||
layer: Layer::with_id(
|
||||
uuid::Uuid::nil(), // replaced by Document::new
|
||||
LayerType::Group,
|
||||
"Master",
|
||||
),
|
||||
children: Vec::new(),
|
||||
expanded: true,
|
||||
tempo_map: Some(TempoMap::constant(bpm)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -773,7 +801,7 @@ impl GroupLayer {
|
||||
AnyLayer::Effect(l) => &l.clip_instances,
|
||||
AnyLayer::Group(_) => &[], // no nested groups
|
||||
AnyLayer::Raster(_) => &[], // raster layers have no clip instances
|
||||
};
|
||||
};
|
||||
for ci in instances {
|
||||
result.push((child_id, ci));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Shared data structures and types
|
||||
|
||||
pub mod beat_time;
|
||||
pub mod tempo_map;
|
||||
pub mod gpu;
|
||||
pub mod layout;
|
||||
pub mod pane;
|
||||
|
||||
@@ -391,9 +391,10 @@ pub fn render_layer_isolated(
|
||||
let mut video_mgr = video_manager.lock().unwrap();
|
||||
let mut instances = Vec::new();
|
||||
|
||||
let tempo_map = document.tempo_map();
|
||||
for clip_instance in &video_layer.clip_instances {
|
||||
let Some(video_clip) = document.video_clips.get(&clip_instance.clip_id) else { continue };
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration) else { continue };
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration, tempo_map) else { continue };
|
||||
let Some(frame) = video_mgr.get_frame(&clip_instance.clip_id, clip_time) else { continue };
|
||||
|
||||
// Evaluate animated transform properties.
|
||||
@@ -458,8 +459,9 @@ pub fn render_layer_isolated(
|
||||
AnyLayer::Effect(effect_layer) => {
|
||||
// Effect layers are processed during compositing, not rendered to scene
|
||||
// Return early with a dedicated effect layer type
|
||||
let tempo_map = document.tempo_map();
|
||||
let active_effects: Vec<ClipInstance> = effect_layer
|
||||
.active_clip_instances_at(time)
|
||||
.active_clip_instances_at(time, tempo_map)
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
@@ -728,16 +730,19 @@ fn render_clip_instance(
|
||||
};
|
||||
|
||||
// Remap timeline time to clip's internal time
|
||||
let tempo_map = document.tempo_map();
|
||||
let clip_time = if vector_clip.is_group {
|
||||
// Groups are static — visible from timeline_start to the next keyframe boundary
|
||||
let end = group_end_time.unwrap_or(clip_instance.timeline_start);
|
||||
if time < clip_instance.timeline_start || time >= end {
|
||||
// Groups are static — visible from timeline_start to the next keyframe boundary.
|
||||
// timeline_start is in beats; group_end_time is in seconds (render time).
|
||||
let start_secs = tempo_map.transform(clip_instance.timeline_start);
|
||||
let end = group_end_time.unwrap_or(start_secs);
|
||||
if time < start_secs || time >= end {
|
||||
return;
|
||||
}
|
||||
0.0
|
||||
} else {
|
||||
let clip_dur = document.get_clip_duration(&vector_clip.id).unwrap_or(vector_clip.duration);
|
||||
let Some(t) = clip_instance.remap_time(time, clip_dur) else {
|
||||
let Some(t) = clip_instance.remap_time(time, clip_dur, tempo_map) else {
|
||||
return; // Clip instance not active at this time
|
||||
};
|
||||
t
|
||||
@@ -889,7 +894,8 @@ fn render_video_layer(
|
||||
};
|
||||
|
||||
// Remap timeline time to clip's internal time
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration) else {
|
||||
let tempo_map = document.tempo_map();
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration, tempo_map) else {
|
||||
continue; // Clip instance not active at this time
|
||||
};
|
||||
|
||||
@@ -1553,13 +1559,15 @@ fn render_clip_instance_cpu(
|
||||
) {
|
||||
let Some(vector_clip) = document.vector_clips.get(&clip_instance.clip_id) else { return };
|
||||
|
||||
let tempo_map = document.tempo_map();
|
||||
let clip_time = if vector_clip.is_group {
|
||||
let end = group_end_time.unwrap_or(clip_instance.timeline_start);
|
||||
if time < clip_instance.timeline_start || time >= end { return; }
|
||||
let start_secs = tempo_map.transform(clip_instance.timeline_start);
|
||||
let end = group_end_time.unwrap_or(start_secs);
|
||||
if time < start_secs || time >= end { return; }
|
||||
0.0
|
||||
} else {
|
||||
let clip_dur = document.get_clip_duration(&vector_clip.id).unwrap_or(vector_clip.duration);
|
||||
let Some(t) = clip_instance.remap_time(time, clip_dur) else { return };
|
||||
let Some(t) = clip_instance.remap_time(time, clip_dur, tempo_map) else { return };
|
||||
t
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
pub use daw_backend::tempo_map::{TempoEntry, TempoMap};
|
||||
Reference in New Issue
Block a user