Type the time domains: no raw f64 in any time-carrying API

Three bugs in a row came from the same root: a time value crossing an API
boundary as a bare f64, with the caller and the callee disagreeing about
whether it meant seconds or beats. Recording landed at the wrong time,
MIDI clips grew too fast, and a 1-second split played back as half a
second. Each was "obviously" one domain at the call site and read as the
other on the far side. This makes the mismatch a compile error.

Backend API — every time-carrying f64 is gone:
- Commands: Seek/SetOffset/SetTrimStart/SetTrimEnd -> Seconds; MoveClip/
  ExtendClip/CreateMidiClip/AddMidiNote/AddLoadedMidiClip/
  UpdateMidiClipNotes/AddMidiClipSync and all four automation commands ->
  Beats; TrimClip -> TrimRange.
- Events/queries: PlaybackPosition, WaveformChunksReady's time range,
  AudioFileReady::duration, PoolFileInfo, get_playhead_seconds -> Seconds.
- Serialized: MidiClipData::duration and AutomationKeyframeData::time ->
  Beats. Both newtypes are #[serde(transparent)], so the .beam on-disk
  format is unchanged.
- Several controller methods ALREADY took Beats and unwrapped it to shove
  into the command — the newtype was being discarded at the very boundary
  it existed to protect.

TrimRange, for the domain-polymorphic case: a clip's content time is
SECONDS for sampled audio but BEATS for MIDI, so a single newtype can't
express it (there was even a comment in engine.rs saying so, and that
rationalization is what let the bug through). A domain-tagged enum can.
The engine rejects a range whose domain doesn't match the track, and the
range is built from the clip (clip.trim_range()) so callers can't pick
the wrong variant.

ContentTime, for the trim fields: ClipInstance::trim_start/trim_end are
content times, and were the last untyped f64 — the actual root of the
split bug. ContentTime is deliberately a DEAD END: no .to_seconds(), no
.to_beats(), no arithmetic with Seconds or Beats. Content times combine
freely with each other (same clip, same domain — safe), so the ~100
passthrough sites cost nothing; the only exit is resolving against the
clip that knows the domain (AudioClip::resolve_content_time /
Document::resolve_content_time / ClipDuration::same_domain). Mixing
domains no longer compiles.

Two more live bugs the types surfaced:
- ClipInstance::effective_duration_beats took a SECONDS clip duration and
  subtracted trim_start from it. For a TRIMMED MIDI clip that subtracted
  a beats offset from a seconds duration, so the clip's timeline length
  was wrong at any tempo but 60 BPM. Untrimmed clips happened to work,
  which is why it hid. It now takes a ClipDuration and resolves in the
  clip's own domain: beats content carries over directly (tempo-
  invariant), wall-clock content converts at the clip's position.
  Regression test asserts a clip trimmed to beats 2..6 is 4 beats long at
  60/90/120 BPM.
- Trim validation clamped a content-domain trim against a wall-clock gap.
  gap_to_content/content_to_secs now convert at the clip's position.

Also folds two more copies of the backend add-logic into
BackendContext::add_clip_instance (split and remove_clip_instances both
re-add clips), so the trim/duration conversions live in exactly one place
instead of four.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Skyler Lehmkuhl
2026-07-14 09:31:04 -04:00
co-authored by Claude Opus 4.8
parent 16e3d676d6
commit a5cdbfd0fd
23 changed files with 738 additions and 565 deletions
+57 -47
View File
@@ -572,7 +572,7 @@ impl Engine {
if self.frames_since_last_event >= self.event_interval_frames / self.channels as usize
{
// Clamp to 0 during count-in pre-roll (negative playhead = before project start)
let position_seconds = self.playhead.max(0) as f64 / self.sample_rate as f64;
let position_seconds = Seconds(self.playhead.max(0) as f64 / self.sample_rate as f64);
let _ = self
.event_tx
.push(AudioEvent::PlaybackPosition(position_seconds));
@@ -922,7 +922,7 @@ impl Engine {
self.project.stop_all_notes();
}
Command::Seek(seconds) => {
self.playhead = (seconds * self.sample_rate as f64) as i64;
self.playhead = (seconds.seconds_to_f64() * self.sample_rate as f64) as i64;
// Clamp to 0 for atomic/disk-reader; negative = count-in pre-roll (no disk reads needed)
let clamped = self.playhead.max(0) as u64;
self.playhead_atomic.store(clamped, Ordering::Relaxed);
@@ -1014,12 +1014,12 @@ impl Engine {
match self.project.get_track_mut(track_id) {
Some(crate::audio::track::TrackNode::Audio(track)) => {
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
clip.external_duration = Beats(new_external_duration);
clip.external_duration = new_external_duration;
}
}
Some(crate::audio::track::TrackNode::Midi(track)) => {
if let Some(instance) = track.clip_instances.iter_mut().find(|c| c.clip_id == clip_id) {
instance.external_duration = Beats(new_external_duration);
instance.external_duration = new_external_duration;
}
}
_ => {}
@@ -1046,7 +1046,7 @@ impl Engine {
}
Command::SetOffset(track_id, offset) => {
if let Some(crate::audio::track::TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
metatrack.offset = Seconds(offset);
metatrack.offset = offset;
}
}
Command::SetPitchShift(track_id, semitones) => {
@@ -1056,12 +1056,12 @@ impl Engine {
}
Command::SetTrimStart(track_id, trim_start) => {
if let Some(crate::audio::track::TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
metatrack.trim_start = Seconds(trim_start.max(0.0));
metatrack.trim_start = Seconds(trim_start.seconds_to_f64().max(0.0));
}
}
Command::SetTrimEnd(track_id, trim_end) => {
if let Some(crate::audio::track::TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
metatrack.trim_end = trim_end.map(|t| Seconds(t.max(0.0)));
metatrack.trim_end = trim_end.map(|t| Seconds(t.seconds_to_f64().max(0.0)));
}
}
Command::CreateAudioTrack(name, parent_id) => {
@@ -1115,9 +1115,13 @@ impl Engine {
// Send chunks via MPSC channel (will be forwarded by audio thread)
if !chunks.is_empty() {
println!("📤 [BACKGROUND] Generated {} chunks, sending to audio thread (pool {})", chunks.len(), pool_index);
let event_chunks: Vec<(u32, (f64, f64), Vec<crate::io::WaveformPeak>)> = chunks
let event_chunks: Vec<(u32, (Seconds, Seconds), Vec<crate::io::WaveformPeak>)> = chunks
.into_iter()
.map(|chunk| (chunk.chunk_index, chunk.time_range, chunk.peaks))
.map(|chunk| {
// A chunk's time_range is a wall-clock span into the audio file.
let (start, end) = chunk.time_range;
(chunk.chunk_index, (Seconds(start), Seconds(end)), chunk.peaks)
})
.collect();
match chunk_tx.send(AudioEvent::WaveformChunksReady {
@@ -1181,12 +1185,12 @@ impl Engine {
let clip_id = self.next_midi_clip_id_atomic.fetch_add(1, Ordering::Relaxed);
// Create clip content in the pool
let clip = MidiClip::empty(clip_id, Beats(duration), format!("MIDI Clip {}", clip_id));
let clip = MidiClip::empty(clip_id, duration, format!("MIDI Clip {}", clip_id));
self.project.midi_clip_pool.add_existing_clip(clip);
// Create an instance for this clip on the track
let instance_id = self.project.next_midi_clip_instance_id();
let instance = MidiClipInstance::from_full_clip(instance_id, clip_id, Beats(duration), Beats(start_time));
let instance = MidiClipInstance::from_full_clip(instance_id, clip_id, duration, start_time);
if let Some(crate::audio::track::TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
track.clip_instances.push(instance);
@@ -1201,11 +1205,11 @@ impl Engine {
// Note: clip_id here refers to the clip in the pool, not the instance
if let Some(clip) = self.project.midi_clip_pool.get_clip_mut(clip_id) {
// Timestamp is in beats (canonical)
let note_on = MidiEvent::note_on(Beats(time_offset), 0, note, velocity);
let note_on = MidiEvent::note_on(time_offset, 0, note, velocity);
clip.add_event(note_on);
// Add note off event
let note_off_time = Beats(time_offset + duration);
let note_off_time = time_offset + duration;
let note_off = MidiEvent::note_off(note_off_time, 0, note, 64);
clip.add_event(note_off);
} else {
@@ -1214,9 +1218,9 @@ impl Engine {
if let Some(instance) = track.clip_instances.iter().find(|c| c.clip_id == clip_id) {
let actual_clip_id = instance.clip_id;
if let Some(clip) = self.project.midi_clip_pool.get_clip_mut(actual_clip_id) {
let note_on = MidiEvent::note_on(Beats(time_offset), 0, note, velocity);
let note_on = MidiEvent::note_on(time_offset, 0, note, velocity);
clip.add_event(note_on);
let note_off_time = Beats(time_offset + duration);
let note_off_time = time_offset + duration;
let note_off = MidiEvent::note_off(note_off_time, 0, note, 64);
clip.add_event(note_off);
}
@@ -1226,7 +1230,7 @@ impl Engine {
}
Command::AddLoadedMidiClip(track_id, clip, start_time) => {
// Add a pre-loaded MIDI clip to the track with the given start time
if let Ok(_instance_id) = self.project.add_midi_clip_at(track_id, clip, crate::time::Beats(start_time)) {
if let Ok(_instance_id) = self.project.add_midi_clip_at(track_id, clip, start_time) {
// instance positions are already in beats; nothing to sync
}
self.refresh_clip_snapshot();
@@ -1240,11 +1244,11 @@ impl Engine {
// Add new events from the notes array
// Timestamps are in beats (canonical)
for (start_time, note, velocity, duration) in notes {
let note_on = MidiEvent::note_on(Beats(start_time), 0, note, velocity);
let note_on = MidiEvent::note_on(start_time, 0, note, velocity);
clip.events.push(note_on);
// Add note off event
let note_off_time = Beats(start_time + duration);
let note_off_time = start_time + duration;
let note_off = MidiEvent::note_off(note_off_time, 0, note, 64);
clip.events.push(note_off);
}
@@ -1306,7 +1310,7 @@ impl Engine {
}
Command::AddAutomationPoint(track_id, lane_id, time, value, curve) => {
// Add an automation point to the specified lane
let point = crate::audio::AutomationPoint::new(Beats(time), value, curve);
let point = crate::audio::AutomationPoint::new(time, value, curve);
match self.project.get_track_mut(track_id) {
Some(crate::audio::track::TrackNode::Audio(track)) => {
@@ -1332,17 +1336,17 @@ impl Engine {
match self.project.get_track_mut(track_id) {
Some(crate::audio::track::TrackNode::Audio(track)) => {
if let Some(lane) = track.get_automation_lane_mut(lane_id) {
lane.remove_point_at_time(Beats(time), Beats(tolerance));
lane.remove_point_at_time(time, tolerance);
}
}
Some(crate::audio::track::TrackNode::Midi(track)) => {
if let Some(lane) = track.get_automation_lane_mut(lane_id) {
lane.remove_point_at_time(Beats(time), Beats(tolerance));
lane.remove_point_at_time(time, tolerance);
}
}
Some(crate::audio::track::TrackNode::Group(group)) => {
if let Some(lane) = group.get_automation_lane_mut(lane_id) {
lane.remove_point_at_time(Beats(time), Beats(tolerance));
lane.remove_point_at_time(time, tolerance);
}
}
None => {}
@@ -2431,7 +2435,7 @@ impl Engine {
// Downcast to AutomationInputNode using as_any_mut
if let Some(auto_node) = graph_node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
let keyframe = AutomationKeyframe {
time: Beats(time),
time,
value,
interpolation,
ease_out,
@@ -2459,7 +2463,7 @@ impl Engine {
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
if let Some(auto_node) = graph_node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
auto_node.remove_keyframe_at_time(Beats(time), Beats(0.001)); // 1ms tolerance
auto_node.remove_keyframe_at_time(time, Beats(0.001)); // 1ms tolerance
} else {
eprintln!("Node {} is not an AutomationInputNode", node_id);
}
@@ -2528,9 +2532,12 @@ impl Engine {
// Send chunks via MPSC channel (will be forwarded by audio thread)
if !chunks.is_empty() {
let event_chunks: Vec<(u32, (f64, f64), Vec<crate::io::WaveformPeak>)> = chunks
let event_chunks: Vec<(u32, (Seconds, Seconds), Vec<crate::io::WaveformPeak>)> = chunks
.into_iter()
.map(|chunk| (chunk.chunk_index, chunk.time_range, chunk.peaks))
.map(|chunk| {
let (start, end) = chunk.time_range;
(chunk.chunk_index, (Seconds(start), Seconds(end)), chunk.peaks)
})
.collect();
let _ = chunk_tx.send(AudioEvent::WaveformChunksReady {
@@ -2694,7 +2701,7 @@ impl Engine {
path: path_str,
channels: metadata.channels,
sample_rate: metadata.sample_rate,
duration: metadata.duration,
duration: Seconds(metadata.duration),
format: metadata.format,
});
@@ -2802,7 +2809,7 @@ impl Engine {
if let Some(clip) = self.project.midi_clip_pool.get_clip(clip_id) {
use crate::command::MidiClipData;
QueryResponse::MidiClipData(Ok(MidiClipData {
duration: clip.duration.0,
duration: clip.duration,
events: clip.events.clone(),
}))
} else {
@@ -2834,7 +2841,7 @@ impl Engine {
InterpolationType::Hold => "hold",
}.to_string();
AutomationKeyframeData {
time: kf.time.0,
time: kf.time,
value: kf.value,
interpolation: interpolation_str,
ease_out: kf.ease_out,
@@ -3003,7 +3010,11 @@ impl Engine {
}
Query::GetPoolFileInfo(pool_index) => {
match self.audio_pool.get_file_info(pool_index) {
Some(info) => QueryResponse::PoolFileInfo(Ok(info)),
// The pool measures a file's length in wall-clock seconds; name it as such at
// the boundary rather than handing a bare f64 to the UI.
Some((duration, sample_rate, channels)) => {
QueryResponse::PoolFileInfo(Ok((Seconds(duration), sample_rate, channels)))
}
None => QueryResponse::PoolFileInfo(Err(format!("Pool index {} not found", pool_index))),
}
}
@@ -3050,7 +3061,7 @@ impl Engine {
}
Query::AddMidiClipSync(track_id, clip, start_time) => {
// Add MIDI clip to track and return the instance ID (positions already in beats)
let result = match self.project.add_midi_clip_at(track_id, clip, crate::time::Beats(start_time)) {
let result = match self.project.add_midi_clip_at(track_id, clip, start_time) {
Ok(instance_id) => QueryResponse::MidiClipInstanceAdded(Ok(instance_id)),
Err(e) => QueryResponse::MidiClipInstanceAdded(Err(e.to_string())),
};
@@ -3644,7 +3655,7 @@ impl EngineController {
/// Seek to a specific position in seconds
pub fn seek(&mut self, seconds: Seconds) {
let _ = self.command_tx.push(Command::Seek(seconds.seconds_to_f64()));
let _ = self.command_tx.push(Command::Seek(seconds));
}
/// Set track volume (0.0 = silence, 1.0 = unity gain)
@@ -3691,7 +3702,7 @@ impl EngineController {
/// Extend or shrink a clip's external duration (enables looping if > internal duration)
pub fn extend_clip(&mut self, track_id: TrackId, clip_id: ClipId, new_external_duration: Beats) {
let _ = self.command_tx.push(Command::ExtendClip(track_id, clip_id, new_external_duration.beats_to_f64()));
let _ = self.command_tx.push(Command::ExtendClip(track_id, clip_id, new_external_duration));
}
/// Send a generic command to the audio thread
@@ -3705,9 +3716,9 @@ impl EngineController {
}
/// Get current playhead position in seconds
pub fn get_playhead_seconds(&self) -> f64 {
pub fn get_playhead_seconds(&self) -> Seconds {
let frames = self.playhead.load(Ordering::Relaxed);
frames as f64 / self.sample_rate as f64
Seconds(frames as f64 / self.sample_rate as f64)
}
/// Get the shared clip snapshot. The UI can read this each frame to display
@@ -3740,7 +3751,7 @@ impl EngineController {
/// Set metatrack time offset in seconds
/// Positive = shift content later, negative = shift earlier
pub fn set_offset(&mut self, track_id: TrackId, offset: Seconds) {
let _ = self.command_tx.push(Command::SetOffset(track_id, offset.seconds_to_f64()));
let _ = self.command_tx.push(Command::SetOffset(track_id, offset));
}
/// Set metatrack pitch shift in semitones (for future use)
@@ -3750,12 +3761,12 @@ impl EngineController {
/// Set metatrack trim start in seconds
pub fn set_trim_start(&mut self, track_id: TrackId, trim_start: Seconds) {
let _ = self.command_tx.push(Command::SetTrimStart(track_id, trim_start.seconds_to_f64()));
let _ = self.command_tx.push(Command::SetTrimStart(track_id, trim_start));
}
/// Set metatrack trim end in seconds (None = no end trim)
pub fn set_trim_end(&mut self, track_id: TrackId, trim_end: Option<Seconds>) {
let _ = self.command_tx.push(Command::SetTrimEnd(track_id, trim_end.map(|s| s.seconds_to_f64())));
let _ = self.command_tx.push(Command::SetTrimEnd(track_id, trim_end));
}
/// Create a new audio track
@@ -3909,23 +3920,22 @@ impl EngineController {
pub fn create_midi_clip(&mut self, track_id: TrackId, start_time: Beats, duration: Beats) -> MidiClipId {
// Peek at the next clip ID that will be used
let clip_id = self.next_midi_clip_id.load(Ordering::Relaxed);
let _ = self.command_tx.push(Command::CreateMidiClip(track_id, start_time.beats_to_f64(), duration.beats_to_f64()));
let _ = self.command_tx.push(Command::CreateMidiClip(track_id, start_time, duration));
clip_id
}
/// Add a MIDI note to a clip
pub fn add_midi_note(&mut self, track_id: TrackId, clip_id: MidiClipId, time_offset: Beats, note: u8, velocity: u8, duration: Beats) {
let _ = self.command_tx.push(Command::AddMidiNote(track_id, clip_id, time_offset.beats_to_f64(), note, velocity, duration.beats_to_f64()));
let _ = self.command_tx.push(Command::AddMidiNote(track_id, clip_id, time_offset, note, velocity, duration));
}
/// Add a pre-loaded MIDI clip to a track at the given timeline position (beats)
pub fn add_loaded_midi_clip(&mut self, track_id: TrackId, clip: MidiClip, start_time: Beats) {
let _ = self.command_tx.push(Command::AddLoadedMidiClip(track_id, clip, start_time.beats_to_f64()));
let _ = self.command_tx.push(Command::AddLoadedMidiClip(track_id, clip, start_time));
}
/// Update all notes in a MIDI clip. Note tuples are (start [beats], note, velocity, duration [beats]).
pub fn update_midi_clip_notes(&mut self, track_id: TrackId, clip_id: MidiClipId, notes: Vec<(Beats, u8, u8, Beats)>) {
let notes = notes.into_iter().map(|(t, n, v, d)| (t.beats_to_f64(), n, v, d.beats_to_f64())).collect();
let _ = self.command_tx.push(Command::UpdateMidiClipNotes(track_id, clip_id, notes));
}
@@ -3966,7 +3976,7 @@ impl EngineController {
curve: crate::audio::CurveType,
) {
let _ = self.command_tx.push(Command::AddAutomationPoint(
track_id, lane_id, time.beats_to_f64(), value, curve,
track_id, lane_id, time, value, curve,
));
}
@@ -3979,7 +3989,7 @@ impl EngineController {
tolerance: Beats,
) {
let _ = self.command_tx.push(Command::RemoveAutomationPoint(
track_id, lane_id, time.beats_to_f64(), tolerance.beats_to_f64(),
track_id, lane_id, time, tolerance,
));
}
@@ -4018,13 +4028,13 @@ impl EngineController {
time: Beats, value: f32, interpolation: String,
ease_out: (f32, f32), ease_in: (f32, f32)) {
let _ = self.command_tx.push(Command::AutomationAddKeyframe(
track_id, node_id, time.beats_to_f64(), value, interpolation, ease_out, ease_in));
track_id, node_id, time, value, interpolation, ease_out, ease_in));
}
/// Remove a keyframe from an AutomationInput node
pub fn automation_remove_keyframe(&mut self, track_id: TrackId, node_id: u32, time: Beats) {
let _ = self.command_tx.push(Command::AutomationRemoveKeyframe(
track_id, node_id, time.beats_to_f64()));
track_id, node_id, time));
}
/// Set the display name of an AutomationInput node
@@ -4560,7 +4570,7 @@ impl EngineController {
}
/// Get file info from pool (duration, sample_rate, channels)
pub fn get_pool_file_info(&mut self, pool_index: usize) -> Result<(f64, u32, u32), String> {
pub fn get_pool_file_info(&mut self, pool_index: usize) -> Result<(Seconds, u32, u32), String> {
// Send query
if let Err(_) = self.query_tx.push(Query::GetPoolFileInfo(pool_index)) {
return Err("Failed to send query - queue full".to_string());
+25 -20
View File
@@ -34,7 +34,7 @@ pub enum Command {
/// Pause playback (maintains position)
Pause,
/// Seek to a specific position in seconds
Seek(f64),
Seek(Seconds),
// Track management commands
/// Set track volume (0.0 = silence, 1.0 = unity gain)
@@ -51,7 +51,7 @@ pub enum Command {
TrimClip(TrackId, ClipId, TrimRange),
/// Extend/shrink a clip's external duration (track_id, clip_id, new_external_duration)
/// If duration > internal duration, the clip will loop
ExtendClip(TrackId, ClipId, f64),
ExtendClip(TrackId, ClipId, Beats),
// Metatrack management commands
/// Create a new metatrack with a name and optional parent group
@@ -67,15 +67,15 @@ pub enum Command {
SetTimeStretch(TrackId, f32),
/// Set metatrack time offset in seconds (track_id, offset)
/// Positive = shift content later, negative = shift earlier
SetOffset(TrackId, f64),
SetOffset(TrackId, Seconds),
/// Set metatrack pitch shift in semitones (track_id, semitones) - for future use
SetPitchShift(TrackId, f32),
/// Set metatrack trim start in seconds (track_id, trim_start)
/// Children won't hear content before this point
SetTrimStart(TrackId, f64),
SetTrimStart(TrackId, Seconds),
/// Set metatrack trim end in seconds (track_id, trim_end)
/// None means no end trim
SetTrimEnd(TrackId, Option<f64>),
SetTrimEnd(TrackId, Option<Seconds>),
// Audio track commands
/// Create a new audio track with a name and optional parent group
@@ -94,14 +94,14 @@ pub enum Command {
/// Add a MIDI clip to the pool without placing it on a track
AddMidiClipToPool(MidiClip),
/// Create a new MIDI clip on a track (track_id, start_time, duration)
CreateMidiClip(TrackId, f64, f64),
CreateMidiClip(TrackId, Beats, Beats),
/// Add a MIDI note to a clip (track_id, clip_id, time_offset, note, velocity, duration)
AddMidiNote(TrackId, MidiClipId, f64, u8, u8, f64),
AddMidiNote(TrackId, MidiClipId, Beats, u8, u8, Beats),
/// Add a pre-loaded MIDI clip to a track (track_id, clip, start_time)
AddLoadedMidiClip(TrackId, MidiClip, f64),
AddLoadedMidiClip(TrackId, MidiClip, Beats),
/// Update MIDI clip notes (track_id, clip_id, notes: Vec<(start_time, note, velocity, duration)>)
/// NOTE: May need to switch to individual note operations if this becomes slow on clips with many notes
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(f64, u8, u8, f64)>),
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(Beats, u8, u8, Beats)>),
/// Replace all events in a MIDI clip (track_id, clip_id, events). Used for CC/pitch bend editing.
UpdateMidiClipEvents(TrackId, MidiClipId, Vec<MidiEvent>),
/// Remove a MIDI clip instance from a track (track_id, instance_id) - for undo/redo support
@@ -117,9 +117,9 @@ pub enum Command {
/// Create a new automation lane on a track (track_id, parameter_id)
CreateAutomationLane(TrackId, ParameterId),
/// Add an automation point to a lane (track_id, lane_id, time, value, curve)
AddAutomationPoint(TrackId, AutomationLaneId, f64, f32, CurveType),
AddAutomationPoint(TrackId, AutomationLaneId, Beats, f32, CurveType),
/// Remove an automation point at a specific time (track_id, lane_id, time, tolerance)
RemoveAutomationPoint(TrackId, AutomationLaneId, f64, f64),
RemoveAutomationPoint(TrackId, AutomationLaneId, Beats, Beats),
/// Clear all automation points from a lane (track_id, lane_id)
ClearAutomationLane(TrackId, AutomationLaneId),
/// Remove an automation lane (track_id, lane_id)
@@ -258,9 +258,9 @@ pub enum Command {
// Automation Input Node commands
/// Add or update a keyframe on an AutomationInput node (track_id, node_id, time, value, interpolation, ease_out, ease_in)
AutomationAddKeyframe(TrackId, u32, f64, f32, String, (f32, f32), (f32, f32)),
AutomationAddKeyframe(TrackId, u32, Beats, f32, String, (f32, f32), (f32, f32)),
/// Remove a keyframe from an AutomationInput node (track_id, node_id, time)
AutomationRemoveKeyframe(TrackId, u32, f64),
AutomationRemoveKeyframe(TrackId, u32, Beats),
/// Set the display name of an AutomationInput node (track_id, node_id, name)
AutomationSetName(TrackId, u32, String),
@@ -292,7 +292,7 @@ pub enum Command {
#[derive(Debug, Clone)]
pub enum AudioEvent {
/// Current playback position in seconds
PlaybackPosition(f64),
PlaybackPosition(Seconds),
/// Playback has stopped (reached end of audio)
PlaybackStopped,
/// Audio buffer underrun detected
@@ -379,7 +379,7 @@ pub enum AudioEvent {
WaveformChunksReady {
pool_index: usize,
detail_level: u8,
chunks: Vec<(u32, (f64, f64), Vec<WaveformPeak>)>,
chunks: Vec<(u32, (Seconds, Seconds), Vec<WaveformPeak>)>,
},
/// An audio file has been imported and is ready for playback.
@@ -390,7 +390,7 @@ pub enum AudioEvent {
path: String,
channels: u32,
sample_rate: u32,
duration: f64,
duration: Seconds,
format: crate::io::audio_file::AudioFormat,
},
@@ -464,7 +464,7 @@ pub enum Query {
/// Export audio to file (settings, output_path)
ExportAudio(crate::audio::ExportSettings, std::path::PathBuf),
/// Add a MIDI clip to a track synchronously (track_id, clip, start_time) - returns instance ID
AddMidiClipSync(TrackId, crate::audio::midi::MidiClip, f64),
AddMidiClipSync(TrackId, crate::audio::midi::MidiClip, Beats),
/// Add a MIDI clip instance to a track synchronously (track_id, instance) - returns instance ID
/// The clip must already exist in the MidiClipPool
AddMidiClipInstanceSync(TrackId, crate::audio::midi::MidiClipInstance),
@@ -509,16 +509,21 @@ pub struct OscilloscopeData {
}
/// MIDI clip data for serialization
///
/// `Beats`/`Seconds` are `#[serde(transparent)]`, so naming the domain here costs nothing on disk —
/// the `.beam` still holds a plain number.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MidiClipData {
pub duration: f64,
/// MIDI content length is musical, so beats.
pub duration: Beats,
pub events: Vec<crate::audio::midi::MidiEvent>,
}
/// Automation keyframe data for serialization
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AutomationKeyframeData {
pub time: f64,
/// Automation x-axes are all beats.
pub time: Beats,
pub value: f32,
pub interpolation: String,
pub ease_out: (f32, f32),
@@ -555,7 +560,7 @@ pub enum QueryResponse {
/// Pool waveform data
PoolWaveform(Result<Vec<crate::io::WaveformPeak>, String>),
/// Pool file info (duration, sample_rate, channels)
PoolFileInfo(Result<(f64, u32, u32), String>),
PoolFileInfo(Result<(Seconds, u32, u32), String>),
/// Audio exported
AudioExported(Result<(), String>),
/// MIDI clip instance added (returns instance ID)
+1 -1
View File
@@ -20,7 +20,7 @@ pub use audio::{
TrackNode,
};
pub use audio::node_graph::{GraphPreset, AudioGraph, PresetMetadata, SerializedConnection, SerializedNode};
pub use time::{Beats, Seconds};
pub use time::{Beats, ContentTime, Seconds};
pub use tempo_map::{TempoEntry, TempoInterpolation, TempoMap, beats_to_seconds_stack, seconds_to_beats_stack};
pub use command::{AudioEvent, Command, OscilloscopeData};
pub use command::types::AutomationKeyframeData;
+44
View File
@@ -16,6 +16,50 @@ pub struct Beats(pub f64);
#[serde(transparent)]
pub struct Seconds(pub f64);
/// A time *inside a clip's own content*, in whatever unit that clip measures content in.
///
/// Clip content time is domain-polymorphic: SECONDS for sampled audio, video and vector, but BEATS
/// for MIDI (musical, so it survives tempo changes). `ClipInstance::trim_start`/`trim_end` are
/// content times, and storing them as bare `f64`s is what let a seconds delta get added to a MIDI
/// clip's beats trim — splitting a MIDI clip at beat 4 landed at beat 2 at 120 BPM.
///
/// This type is deliberately a **dead end**: it has no `.to_seconds()`, no `.to_beats()`, and no
/// arithmetic with `Seconds` or `Beats`. Content times can be compared and combined with each other
/// (that's domain-safe — both operands are in the same clip's domain), but the only way to get a
/// real timeline duration out is to resolve it against the clip that knows the domain, via
/// `AudioClip::resolve_content_time` / `Document::resolve_content_time`. So a passthrough costs
/// nothing, and mixing domains won't compile.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ContentTime(pub f64);
impl ContentTime {
pub const ZERO: Self = Self(0.0);
pub fn max(self, other: Self) -> Self { Self(self.0.max(other.0)) }
pub fn min(self, other: Self) -> Self { Self(self.0.min(other.0)) }
/// The raw magnitude, with the domain discarded.
///
/// Only for code that is *already* working in this clip's content domain (trim arithmetic,
/// serialization, drawing a waveform whose x-axis is the clip's own content). If you are about
/// to combine this with a timeline position, resolve it against the clip instead.
pub fn raw(self) -> f64 { self.0 }
}
impl Add for ContentTime {
type Output = Self;
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
}
impl Sub for ContentTime {
type Output = Self;
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
}
impl Rem for ContentTime {
type Output = Self;
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
}
impl Beats {
pub const ZERO: Self = Self(0.0);
+1 -1
View File
@@ -556,7 +556,7 @@ pub fn run_tui(
while let Ok(event) = rx.pop() {
match event {
AudioEvent::PlaybackPosition(pos) => {
app.update_playback_position(pos);
app.update_playback_position(pos.seconds_to_f64());
}
AudioEvent::PlaybackStopped => {
app.set_playing(false);