Massive tempo refactor - make beats canonical time rep and allow them to be non constant
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
/// Automation system for parameter modulation over time
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::time::Beats;
|
||||
|
||||
/// Unique identifier for automation lanes
|
||||
pub type AutomationLaneId = u32;
|
||||
@@ -35,17 +36,13 @@ pub enum CurveType {
|
||||
/// A single automation point
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AutomationPoint {
|
||||
/// Time in seconds
|
||||
pub time: f64,
|
||||
/// Parameter value (normalized 0.0 to 1.0, or actual value depending on parameter)
|
||||
pub time: Beats,
|
||||
pub value: f32,
|
||||
/// Curve type to next point
|
||||
pub curve: CurveType,
|
||||
}
|
||||
|
||||
impl AutomationPoint {
|
||||
/// Create a new automation point
|
||||
pub fn new(time: f64, value: f32, curve: CurveType) -> Self {
|
||||
pub fn new(time: Beats, value: f32, curve: CurveType) -> Self {
|
||||
Self { time, value, curve }
|
||||
}
|
||||
}
|
||||
@@ -93,8 +90,7 @@ impl AutomationLane {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove point at specific time
|
||||
pub fn remove_point_at_time(&mut self, time: f64, tolerance: f64) -> bool {
|
||||
pub fn remove_point_at_time(&mut self, time: Beats, tolerance: Beats) -> bool {
|
||||
if let Some(idx) = self.points.iter().position(|p| (p.time - time).abs() < tolerance) {
|
||||
self.points.remove(idx);
|
||||
true
|
||||
@@ -113,8 +109,7 @@ impl AutomationLane {
|
||||
&self.points
|
||||
}
|
||||
|
||||
/// Get value at a specific time with interpolation
|
||||
pub fn evaluate(&self, time: f64) -> Option<f32> {
|
||||
pub fn evaluate(&self, time: Beats) -> Option<f32> {
|
||||
if !self.enabled || self.points.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -148,14 +143,12 @@ impl AutomationLane {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate between two automation points based on curve type
|
||||
fn interpolate(p1: &AutomationPoint, p2: &AutomationPoint, time: f64) -> f32 {
|
||||
// Calculate normalized position between points (0.0 to 1.0)
|
||||
fn interpolate(p1: &AutomationPoint, p2: &AutomationPoint, time: Beats) -> f32 {
|
||||
let t = if p2.time == p1.time {
|
||||
0.0
|
||||
0.0f64
|
||||
} else {
|
||||
((time - p1.time) / (p2.time - p1.time)) as f32
|
||||
};
|
||||
(time - p1.time) / (p2.time - p1.time)
|
||||
} as f32;
|
||||
|
||||
// Apply curve
|
||||
let curved_t = match p1.curve {
|
||||
|
||||
+40
-137
@@ -1,5 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use crate::time::{Beats, Seconds};
|
||||
use crate::tempo_map::TempoMap;
|
||||
|
||||
/// Audio clip instance ID type
|
||||
pub type AudioClipInstanceId = u32;
|
||||
@@ -9,47 +11,31 @@ pub type ClipId = AudioClipInstanceId;
|
||||
|
||||
/// Audio clip instance that references content in the AudioClipPool
|
||||
///
|
||||
/// This represents a placed instance of audio content on the timeline.
|
||||
/// The actual audio data is stored in the AudioClipPool and referenced by `audio_pool_index`.
|
||||
///
|
||||
/// ## Timing Model
|
||||
/// - `internal_start` / `internal_end`: Define the region of the source audio to play (trimming)
|
||||
/// - `external_start` / `external_duration`: Define where the clip appears on the timeline and how long
|
||||
/// - `*_beats` / `*_frames`: Derived representations for Measures/Frames mode display
|
||||
/// - `internal_start` / `internal_end`: Region of the source audio to play (seconds — audio file seek positions)
|
||||
/// - `external_start` / `external_duration`: Where the clip appears on the timeline (**beats**)
|
||||
///
|
||||
/// ## Looping
|
||||
/// If `external_duration` is greater than `internal_end - internal_start`,
|
||||
/// the clip will seamlessly loop back to `internal_start` when it reaches `internal_end`.
|
||||
/// If `external_duration_secs(bpm)` > `internal_end - internal_start`, the clip loops.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioClipInstance {
|
||||
pub id: AudioClipInstanceId,
|
||||
pub audio_pool_index: usize,
|
||||
|
||||
/// Start position within the audio content (seconds)
|
||||
pub internal_start: f64,
|
||||
#[serde(default)] pub internal_start_beats: f64,
|
||||
#[serde(default)] pub internal_start_frames: f64,
|
||||
/// End position within the audio content (seconds)
|
||||
pub internal_end: f64,
|
||||
#[serde(default)] pub internal_end_beats: f64,
|
||||
#[serde(default)] pub internal_end_frames: f64,
|
||||
/// Start position within the audio content
|
||||
pub internal_start: Seconds,
|
||||
/// End position within the audio content
|
||||
pub internal_end: Seconds,
|
||||
|
||||
/// Start position on the timeline (seconds)
|
||||
pub external_start: f64,
|
||||
#[serde(default)] pub external_start_beats: f64,
|
||||
#[serde(default)] pub external_start_frames: f64,
|
||||
/// Duration on the timeline (seconds) - can be longer than internal duration for looping
|
||||
pub external_duration: f64,
|
||||
#[serde(default)] pub external_duration_beats: f64,
|
||||
#[serde(default)] pub external_duration_frames: f64,
|
||||
/// Start position on the timeline
|
||||
pub external_start: Beats,
|
||||
/// Duration on the timeline
|
||||
pub external_duration: Beats,
|
||||
|
||||
/// Clip-level gain
|
||||
pub gain: f32,
|
||||
|
||||
/// Per-instance read-ahead buffer for compressed audio streaming.
|
||||
/// Each clip instance gets its own buffer so multiple instances of the
|
||||
/// same file (on different tracks or at different positions) don't fight
|
||||
/// over a single target_frame.
|
||||
#[serde(skip)]
|
||||
pub read_ahead: Option<Arc<super::disk_reader::ReadAheadBuffer>>,
|
||||
}
|
||||
@@ -58,154 +44,71 @@ pub struct AudioClipInstance {
|
||||
pub type Clip = AudioClipInstance;
|
||||
|
||||
impl AudioClipInstance {
|
||||
/// Create a new audio clip instance
|
||||
pub fn new(
|
||||
id: AudioClipInstanceId,
|
||||
audio_pool_index: usize,
|
||||
internal_start: f64,
|
||||
internal_end: f64,
|
||||
external_start: f64,
|
||||
external_duration: f64,
|
||||
internal_start: Seconds,
|
||||
internal_end: Seconds,
|
||||
external_start: Beats,
|
||||
external_duration: Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
audio_pool_index,
|
||||
internal_start,
|
||||
internal_start_beats: 0.0,
|
||||
internal_start_frames: 0.0,
|
||||
internal_end,
|
||||
internal_end_beats: 0.0,
|
||||
internal_end_frames: 0.0,
|
||||
external_start,
|
||||
external_start_beats: 0.0,
|
||||
external_start_frames: 0.0,
|
||||
external_duration,
|
||||
external_duration_beats: 0.0,
|
||||
external_duration_frames: 0.0,
|
||||
gain: 1.0,
|
||||
read_ahead: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a clip instance from legacy parameters (for backwards compatibility)
|
||||
/// Maps old start_time/duration/offset to new timing model
|
||||
pub fn from_legacy(
|
||||
id: AudioClipInstanceId,
|
||||
audio_pool_index: usize,
|
||||
start_time: f64,
|
||||
duration: f64,
|
||||
offset: f64,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
audio_pool_index,
|
||||
internal_start: offset,
|
||||
internal_start_beats: 0.0,
|
||||
internal_start_frames: 0.0,
|
||||
internal_end: offset + duration,
|
||||
internal_end_beats: 0.0,
|
||||
internal_end_frames: 0.0,
|
||||
external_start: start_time,
|
||||
external_start_beats: 0.0,
|
||||
external_start_frames: 0.0,
|
||||
external_duration: duration,
|
||||
external_duration_beats: 0.0,
|
||||
external_duration_frames: 0.0,
|
||||
gain: 1.0,
|
||||
read_ahead: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if this clip instance is active at a given timeline position
|
||||
pub fn is_active_at(&self, time_seconds: f64) -> bool {
|
||||
time_seconds >= self.external_start && time_seconds < self.external_end()
|
||||
}
|
||||
|
||||
/// Get the end time of this clip instance on the timeline
|
||||
pub fn external_end(&self) -> f64 {
|
||||
pub fn external_end(&self) -> Beats {
|
||||
self.external_start + self.external_duration
|
||||
}
|
||||
|
||||
/// Get the end time of this clip instance on the timeline
|
||||
/// (Alias for external_end(), for backwards compatibility)
|
||||
pub fn end_time(&self) -> f64 {
|
||||
self.external_end()
|
||||
pub fn external_start_secs(&self, tempo_map: &TempoMap) -> Seconds {
|
||||
tempo_map.beats_to_seconds(self.external_start)
|
||||
}
|
||||
|
||||
/// Get the start time on the timeline
|
||||
/// (Alias for external_start, for backwards compatibility)
|
||||
pub fn start_time(&self) -> f64 {
|
||||
self.external_start
|
||||
pub fn external_end_secs(&self, tempo_map: &TempoMap) -> Seconds {
|
||||
tempo_map.beats_to_seconds(self.external_end())
|
||||
}
|
||||
|
||||
/// Get the internal (content) duration
|
||||
pub fn internal_duration(&self) -> f64 {
|
||||
pub fn external_duration_secs(&self, tempo_map: &TempoMap) -> Seconds {
|
||||
tempo_map.beats_to_seconds(self.external_end()) - tempo_map.beats_to_seconds(self.external_start)
|
||||
}
|
||||
|
||||
pub fn is_active_at(&self, time: Seconds, tempo_map: &TempoMap) -> bool {
|
||||
time >= self.external_start_secs(tempo_map) && time < self.external_end_secs(tempo_map)
|
||||
}
|
||||
|
||||
pub fn internal_duration(&self) -> Seconds {
|
||||
self.internal_end - self.internal_start
|
||||
}
|
||||
|
||||
/// Check if this clip instance loops
|
||||
pub fn is_looping(&self) -> bool {
|
||||
self.external_duration > self.internal_duration()
|
||||
pub fn is_looping(&self, tempo_map: &TempoMap) -> bool {
|
||||
self.external_duration_secs(tempo_map) > self.internal_duration()
|
||||
}
|
||||
|
||||
/// Get the position within the audio content for a given timeline position
|
||||
/// Returns None if the timeline position is outside this clip instance
|
||||
/// Handles looping automatically
|
||||
pub fn get_content_position(&self, timeline_pos: f64) -> Option<f64> {
|
||||
if timeline_pos < self.external_start || timeline_pos >= self.external_end() {
|
||||
/// Get the audio content position for a given timeline position. Handles looping.
|
||||
pub fn get_content_position(&self, timeline_pos: Seconds, tempo_map: &TempoMap) -> Option<Seconds> {
|
||||
let start_secs = self.external_start_secs(tempo_map);
|
||||
let end_secs = self.external_end_secs(tempo_map);
|
||||
if timeline_pos < start_secs || timeline_pos >= end_secs {
|
||||
return None;
|
||||
}
|
||||
|
||||
let relative_pos = timeline_pos - self.external_start;
|
||||
let relative_pos = timeline_pos - start_secs;
|
||||
let internal_duration = self.internal_duration();
|
||||
|
||||
if internal_duration <= 0.0 {
|
||||
if internal_duration.0 <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Wrap around for looping
|
||||
let content_offset = relative_pos % internal_duration;
|
||||
Some(self.internal_start + content_offset)
|
||||
}
|
||||
|
||||
/// Set clip gain
|
||||
pub fn set_gain(&mut self, gain: f32) {
|
||||
self.gain = gain.max(0.0);
|
||||
}
|
||||
|
||||
/// Populate beats/frames from the current seconds values.
|
||||
pub fn sync_from_seconds(&mut self, bpm: f64, fps: f64) {
|
||||
self.external_start_beats = self.external_start * bpm / 60.0;
|
||||
self.external_start_frames = self.external_start * fps;
|
||||
self.external_duration_beats = self.external_duration * bpm / 60.0;
|
||||
self.external_duration_frames = self.external_duration * fps;
|
||||
self.internal_start_beats = self.internal_start * bpm / 60.0;
|
||||
self.internal_start_frames = self.internal_start * fps;
|
||||
self.internal_end_beats = self.internal_end * bpm / 60.0;
|
||||
self.internal_end_frames = self.internal_end * fps;
|
||||
}
|
||||
|
||||
/// BPM changed; recompute seconds/frames from the stored beats values.
|
||||
pub fn apply_beats(&mut self, bpm: f64, fps: f64) {
|
||||
self.external_start = self.external_start_beats * 60.0 / bpm;
|
||||
self.external_start_frames = self.external_start * fps;
|
||||
self.external_duration = self.external_duration_beats * 60.0 / bpm;
|
||||
self.external_duration_frames = self.external_duration * fps;
|
||||
self.internal_start = self.internal_start_beats * 60.0 / bpm;
|
||||
self.internal_start_frames = self.internal_start * fps;
|
||||
self.internal_end = self.internal_end_beats * 60.0 / bpm;
|
||||
self.internal_end_frames = self.internal_end * fps;
|
||||
}
|
||||
|
||||
/// FPS changed; recompute seconds/beats from the stored frames values.
|
||||
pub fn apply_frames(&mut self, fps: f64, bpm: f64) {
|
||||
self.external_start = self.external_start_frames / fps;
|
||||
self.external_start_beats = self.external_start * bpm / 60.0;
|
||||
self.external_duration = self.external_duration_frames / fps;
|
||||
self.external_duration_beats = self.external_duration * bpm / 60.0;
|
||||
self.internal_start = self.internal_start_frames / fps;
|
||||
self.internal_start_beats = self.internal_start * bpm / 60.0;
|
||||
self.internal_end = self.internal_end_frames / fps;
|
||||
self.internal_end_beats = self.internal_end * bpm / 60.0;
|
||||
}
|
||||
}
|
||||
|
||||
+97
-137
@@ -9,6 +9,7 @@ use crate::audio::recording::{MidiRecordingState, RecordingState};
|
||||
use crate::audio::track::{Track, TrackId, TrackNode};
|
||||
use crate::command::{AudioEvent, Command, Query, QueryResponse};
|
||||
use crate::io::MidiInputManager;
|
||||
use crate::time::{Beats, Seconds};
|
||||
use petgraph::stable_graph::NodeIndex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
@@ -109,9 +110,8 @@ pub struct Engine {
|
||||
timing_sum_total_us: u64,
|
||||
timing_overrun_count: u64,
|
||||
|
||||
// Current tempo/framerate — kept in sync with SetTempo/ApplyBpmChange so that
|
||||
// newly-created clip instances can be immediately synced via sync_from_seconds.
|
||||
current_bpm: f64,
|
||||
// Current tempo map — kept in sync with SetTempo/SetTempoMap commands.
|
||||
tempo_map: crate::TempoMap,
|
||||
current_fps: f64,
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ impl Engine {
|
||||
timing_worst_render_us: 0,
|
||||
timing_sum_total_us: 0,
|
||||
timing_overrun_count: 0,
|
||||
current_bpm: 120.0,
|
||||
tempo_map: crate::TempoMap::constant(120.0),
|
||||
current_fps: 30.0,
|
||||
}
|
||||
}
|
||||
@@ -379,7 +379,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
// Convert playhead from frames to seconds for timeline-based rendering
|
||||
let playhead_seconds = self.playhead as f64 / self.sample_rate as f64;
|
||||
let playhead_seconds = Seconds(self.playhead as f64 / self.sample_rate as f64);
|
||||
|
||||
// Reset per-clip read-ahead targets before rendering.
|
||||
self.project.reset_read_ahead_targets();
|
||||
@@ -390,6 +390,7 @@ impl Engine {
|
||||
&self.audio_pool,
|
||||
&mut self.buffer_pool,
|
||||
playhead_seconds,
|
||||
&self.tempo_map,
|
||||
self.sample_rate,
|
||||
self.channels,
|
||||
false,
|
||||
@@ -427,7 +428,8 @@ impl Engine {
|
||||
|
||||
// Send MIDI recording progress if active
|
||||
if let Some(recording) = &self.midi_recording_state {
|
||||
let current_time = self.playhead as f64 / self.sample_rate as f64;
|
||||
let current_time_secs = Seconds(self.playhead as f64 / self.sample_rate as f64);
|
||||
let current_time = self.tempo_map.seconds_to_beats(current_time_secs);
|
||||
let duration = current_time - recording.start_time;
|
||||
let notes = recording.get_notes_with_active(current_time);
|
||||
let _ = self.event_tx.push(AudioEvent::MidiRecordingProgress(
|
||||
@@ -451,7 +453,7 @@ impl Engine {
|
||||
} else {
|
||||
// Not playing: render live MIDI (keyboard input + note-off tails) through the
|
||||
// normal group hierarchy so mixer gain is correctly applied.
|
||||
let playhead_seconds = self.playhead as f64 / self.sample_rate as f64;
|
||||
let playhead_seconds = Seconds(self.playhead as f64 / self.sample_rate as f64);
|
||||
if self.mix_buffer.len() != output.len() {
|
||||
self.mix_buffer.resize(output.len(), 0.0);
|
||||
}
|
||||
@@ -463,6 +465,7 @@ impl Engine {
|
||||
&self.audio_pool,
|
||||
&mut self.buffer_pool,
|
||||
playhead_seconds,
|
||||
&self.tempo_map,
|
||||
self.sample_rate,
|
||||
self.channels,
|
||||
true, // live_only
|
||||
@@ -562,7 +565,8 @@ impl Engine {
|
||||
if let Some(crate::audio::track::TrackNode::Audio(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.internal_end = clip.internal_start + duration;
|
||||
clip.external_duration = duration;
|
||||
let duration_beats = self.tempo_map.seconds_to_beats(duration);
|
||||
clip.external_duration = duration_beats;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -734,20 +738,16 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
Command::MoveClip(track_id, clip_id, new_start_time) => {
|
||||
// Moving just changes external_start, external_duration stays the same
|
||||
let bpm = self.current_bpm;
|
||||
let fps = self.current_fps;
|
||||
// Moving just changes external_start (beats), external_duration stays the same
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.external_start = new_start_time;
|
||||
clip.sync_from_seconds(bpm, fps);
|
||||
clip.external_start = Beats(new_start_time);
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(instance) = track.clip_instances.iter_mut().find(|c| c.id == clip_id) {
|
||||
instance.external_start = new_start_time;
|
||||
instance.sync_from_seconds(bpm, fps);
|
||||
instance.external_start = Beats(new_start_time);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -757,24 +757,19 @@ impl Engine {
|
||||
Command::TrimClip(track_id, clip_id, new_internal_start, new_internal_end) => {
|
||||
// Trim changes which portion of the source content is used
|
||||
// Also updates external_duration to match internal duration (no looping after trim)
|
||||
let bpm = self.current_bpm;
|
||||
let fps = self.current_fps;
|
||||
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.internal_start = new_internal_start;
|
||||
clip.internal_end = new_internal_end;
|
||||
clip.external_duration = new_internal_end - new_internal_start;
|
||||
clip.sync_from_seconds(bpm, fps);
|
||||
clip.internal_start = Seconds(new_internal_start);
|
||||
clip.internal_end = Seconds(new_internal_end);
|
||||
clip.external_duration = Beats(new_internal_end - new_internal_start);
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
// Note: clip_id here is the pool clip ID, not instance ID
|
||||
if let Some(instance) = track.clip_instances.iter_mut().find(|c| c.clip_id == clip_id) {
|
||||
instance.internal_start = new_internal_start;
|
||||
instance.internal_end = new_internal_end;
|
||||
instance.external_duration = new_internal_end - new_internal_start;
|
||||
instance.sync_from_seconds(bpm, fps);
|
||||
instance.internal_start = Beats(new_internal_start);
|
||||
instance.internal_end = Beats(new_internal_end);
|
||||
instance.external_duration = Beats(new_internal_end - new_internal_start);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -782,21 +777,16 @@ impl Engine {
|
||||
self.refresh_clip_snapshot();
|
||||
}
|
||||
Command::ExtendClip(track_id, clip_id, new_external_duration) => {
|
||||
// Extend changes the external duration (enables looping if > internal duration)
|
||||
let bpm = self.current_bpm;
|
||||
let fps = self.current_fps;
|
||||
// Extend changes the external duration (beats; enables looping if > internal duration)
|
||||
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 = new_external_duration;
|
||||
clip.sync_from_seconds(bpm, fps);
|
||||
clip.external_duration = Beats(new_external_duration);
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
// Note: clip_id here is the pool clip ID, not instance ID
|
||||
if let Some(instance) = track.clip_instances.iter_mut().find(|c| c.clip_id == clip_id) {
|
||||
instance.external_duration = new_external_duration;
|
||||
instance.sync_from_seconds(bpm, fps);
|
||||
instance.external_duration = Beats(new_external_duration);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -823,7 +813,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 = offset;
|
||||
metatrack.offset = Seconds(offset);
|
||||
}
|
||||
}
|
||||
Command::SetPitchShift(track_id, semitones) => {
|
||||
@@ -833,12 +823,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 = trim_start.max(0.0);
|
||||
metatrack.trim_start = Seconds(trim_start.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| t.max(0.0));
|
||||
metatrack.trim_end = trim_end.map(|t| Seconds(t.max(0.0)));
|
||||
}
|
||||
}
|
||||
Command::CreateAudioTrack(name, parent_id) => {
|
||||
@@ -915,14 +905,20 @@ impl Engine {
|
||||
}
|
||||
Command::AddAudioClip(track_id, clip_id, pool_index, start_time, duration, offset) => {
|
||||
// Create a new clip instance with the pre-assigned clip_id
|
||||
let mut clip = AudioClipInstance::from_legacy(
|
||||
// start_time and duration are in beats; offset (internal_start) is seconds
|
||||
let start_beats = Beats(start_time);
|
||||
let end_beats = Beats(start_time + duration);
|
||||
let start_secs = self.tempo_map.beats_to_seconds(start_beats);
|
||||
let end_secs = self.tempo_map.beats_to_seconds(end_beats);
|
||||
let content_dur_secs = (end_secs - start_secs).seconds_to_f64();
|
||||
let clip = AudioClipInstance::new(
|
||||
clip_id,
|
||||
pool_index,
|
||||
start_time,
|
||||
duration,
|
||||
offset,
|
||||
Seconds(offset),
|
||||
Seconds(offset + content_dur_secs),
|
||||
start_beats,
|
||||
Beats(duration),
|
||||
);
|
||||
clip.sync_from_seconds(self.current_bpm, self.current_fps);
|
||||
|
||||
// Add clip to track
|
||||
if let Some(crate::audio::track::TrackNode::Audio(track)) = self.project.get_track_mut(track_id) {
|
||||
@@ -945,13 +941,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, duration, format!("MIDI Clip {}", clip_id));
|
||||
let clip = MidiClip::empty(clip_id, Beats(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 mut instance = MidiClipInstance::from_full_clip(instance_id, clip_id, duration, start_time);
|
||||
instance.sync_from_seconds(self.current_bpm, self.current_fps);
|
||||
let instance = MidiClipInstance::from_full_clip(instance_id, clip_id, Beats(duration), Beats(start_time));
|
||||
|
||||
if let Some(crate::audio::track::TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
track.clip_instances.push(instance);
|
||||
@@ -965,12 +960,12 @@ impl Engine {
|
||||
// Add a MIDI note event to the specified clip in the pool
|
||||
// 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 now in seconds (sample-rate independent)
|
||||
let note_on = MidiEvent::note_on(time_offset, 0, note, velocity);
|
||||
// Timestamp is in beats (canonical)
|
||||
let note_on = MidiEvent::note_on(Beats(time_offset), 0, note, velocity);
|
||||
clip.add_event(note_on);
|
||||
|
||||
// Add note off event
|
||||
let note_off_time = time_offset + duration;
|
||||
let note_off_time = Beats(time_offset + duration);
|
||||
let note_off = MidiEvent::note_off(note_off_time, 0, note, 64);
|
||||
clip.add_event(note_off);
|
||||
} else {
|
||||
@@ -979,9 +974,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(time_offset, 0, note, velocity);
|
||||
let note_on = MidiEvent::note_on(Beats(time_offset), 0, note, velocity);
|
||||
clip.add_event(note_on);
|
||||
let note_off_time = time_offset + duration;
|
||||
let note_off_time = Beats(time_offset + duration);
|
||||
let note_off = MidiEvent::note_off(note_off_time, 0, note, 64);
|
||||
clip.add_event(note_off);
|
||||
}
|
||||
@@ -991,14 +986,8 @@ impl Engine {
|
||||
}
|
||||
Command::AddLoadedMidiClip(track_id, clip, start_time) => {
|
||||
// Add a pre-loaded MIDI clip to the track with the given start time
|
||||
let bpm = self.current_bpm;
|
||||
let fps = self.current_fps;
|
||||
if let Ok(instance_id) = self.project.add_midi_clip_at(track_id, clip, start_time) {
|
||||
if let Some(crate::audio::track::TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(inst) = track.clip_instances.iter_mut().find(|i| i.id == instance_id) {
|
||||
inst.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
if let Ok(_instance_id) = self.project.add_midi_clip_at(track_id, clip, crate::time::Beats(start_time)) {
|
||||
// instance positions are already in beats; nothing to sync
|
||||
}
|
||||
self.refresh_clip_snapshot();
|
||||
}
|
||||
@@ -1009,13 +998,13 @@ impl Engine {
|
||||
clip.events.clear();
|
||||
|
||||
// Add new events from the notes array
|
||||
// Timestamps are now stored in seconds (sample-rate independent)
|
||||
// Timestamps are in beats (canonical)
|
||||
for (start_time, note, velocity, duration) in notes {
|
||||
let note_on = MidiEvent::note_on(start_time, 0, note, velocity);
|
||||
let note_on = MidiEvent::note_on(Beats(start_time), 0, note, velocity);
|
||||
clip.events.push(note_on);
|
||||
|
||||
// Add note off event
|
||||
let note_off_time = start_time + duration;
|
||||
let note_off_time = Beats(start_time + duration);
|
||||
let note_off = MidiEvent::note_off(note_off_time, 0, note, 64);
|
||||
clip.events.push(note_off);
|
||||
}
|
||||
@@ -1077,7 +1066,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(time, value, curve);
|
||||
let point = crate::audio::AutomationPoint::new(Beats(time), value, curve);
|
||||
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
@@ -1103,17 +1092,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(time, tolerance);
|
||||
lane.remove_point_at_time(Beats(time), Beats(tolerance));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(lane) = track.get_automation_lane_mut(lane_id) {
|
||||
lane.remove_point_at_time(time, tolerance);
|
||||
lane.remove_point_at_time(Beats(time), Beats(tolerance));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Group(group)) => {
|
||||
if let Some(lane) = group.get_automation_lane_mut(lane_id) {
|
||||
lane.remove_point_at_time(time, tolerance);
|
||||
lane.remove_point_at_time(Beats(time), Beats(tolerance));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
@@ -1250,9 +1239,9 @@ impl Engine {
|
||||
// If MIDI recording is active on this track, capture the event
|
||||
if let Some(recording) = &mut self.midi_recording_state {
|
||||
if recording.track_id == track_id {
|
||||
let absolute_time = self.playhead as f64 / self.sample_rate as f64;
|
||||
eprintln!("[MIDI_RECORDING] NoteOn captured: note={}, velocity={}, absolute_time={:.3}s, playhead={}, sample_rate={}",
|
||||
note, velocity, absolute_time, self.playhead, self.sample_rate);
|
||||
let absolute_time = self.tempo_map.seconds_to_beats(Seconds(self.playhead as f64 / self.sample_rate as f64));
|
||||
eprintln!("[MIDI_RECORDING] NoteOn captured: note={}, velocity={}, absolute_time={:.3} beats, playhead={}, sample_rate={}",
|
||||
note, velocity, absolute_time.0, self.playhead, self.sample_rate);
|
||||
recording.note_on(note, velocity, absolute_time);
|
||||
}
|
||||
}
|
||||
@@ -1273,9 +1262,9 @@ impl Engine {
|
||||
// If MIDI recording is active on this track, capture the event
|
||||
if let Some(recording) = &mut self.midi_recording_state {
|
||||
if recording.track_id == track_id {
|
||||
let absolute_time = self.playhead as f64 / self.sample_rate as f64;
|
||||
eprintln!("[MIDI_RECORDING] NoteOff captured: note={}, absolute_time={:.3}s, playhead={}, sample_rate={}",
|
||||
note, absolute_time, self.playhead, self.sample_rate);
|
||||
let absolute_time = self.tempo_map.seconds_to_beats(Seconds(self.playhead as f64 / self.sample_rate as f64));
|
||||
eprintln!("[MIDI_RECORDING] NoteOff captured: note={}, absolute_time={:.3} beats, playhead={}, sample_rate={}",
|
||||
note, absolute_time.0, self.playhead, self.sample_rate);
|
||||
recording.note_off(note, absolute_time);
|
||||
}
|
||||
}
|
||||
@@ -1303,14 +1292,7 @@ impl Engine {
|
||||
Command::SetTempo(bpm, time_sig) => {
|
||||
self.metronome.update_timing(bpm, time_sig);
|
||||
self.project.set_tempo(bpm, time_sig.0);
|
||||
self.current_bpm = bpm as f64;
|
||||
}
|
||||
|
||||
Command::ApplyBpmChange(from_bpm, to_bpm, fps, midi_durations) => {
|
||||
self.current_bpm = to_bpm;
|
||||
self.current_fps = fps;
|
||||
self.project.apply_bpm_change(from_bpm, to_bpm, fps, &midi_durations);
|
||||
self.refresh_clip_snapshot();
|
||||
self.tempo_map.set_global_bpm(bpm as f64);
|
||||
}
|
||||
|
||||
// Node graph commands
|
||||
@@ -2181,16 +2163,13 @@ impl Engine {
|
||||
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
|
||||
// Downcast to AutomationInputNode using as_any_mut
|
||||
if let Some(auto_node) = graph_node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
|
||||
let mut keyframe = AutomationKeyframe {
|
||||
time,
|
||||
time_beats: 0.0,
|
||||
time_frames: 0.0,
|
||||
let keyframe = AutomationKeyframe {
|
||||
time: Beats(time),
|
||||
value,
|
||||
interpolation,
|
||||
ease_out,
|
||||
ease_in,
|
||||
};
|
||||
keyframe.sync_from_seconds(self.current_bpm, self.current_fps);
|
||||
auto_node.add_keyframe(keyframe);
|
||||
} else {
|
||||
eprintln!("Node {} is not an AutomationInputNode", node_id);
|
||||
@@ -2208,7 +2187,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(time, 0.001); // 1ms tolerance
|
||||
auto_node.remove_keyframe_at_time(Beats(time), Beats(0.001)); // 1ms tolerance
|
||||
} else {
|
||||
eprintln!("Node {} is not an AutomationInputNode", node_id);
|
||||
}
|
||||
@@ -2517,7 +2496,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,
|
||||
duration: clip.duration.0,
|
||||
events: clip.events.clone(),
|
||||
}))
|
||||
} else {
|
||||
@@ -2547,7 +2526,7 @@ impl Engine {
|
||||
}.to_string();
|
||||
|
||||
AutomationKeyframeData {
|
||||
time: kf.time,
|
||||
time: kf.time.0,
|
||||
value: kf.value,
|
||||
interpolation: interpolation_str,
|
||||
ease_out: kf.ease_out,
|
||||
@@ -2752,19 +2731,9 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
Query::AddMidiClipSync(track_id, clip, start_time) => {
|
||||
// Add MIDI clip to track and return the instance ID
|
||||
let bpm = self.current_bpm;
|
||||
let fps = self.current_fps;
|
||||
let result = match self.project.add_midi_clip_at(track_id, clip, start_time) {
|
||||
Ok(instance_id) => {
|
||||
// Sync beats/frames on the newly created instance
|
||||
if let Some(crate::audio::track::TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(inst) = track.clip_instances.iter_mut().find(|i| i.id == instance_id) {
|
||||
inst.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
QueryResponse::MidiClipInstanceAdded(Ok(instance_id))
|
||||
}
|
||||
// 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)) {
|
||||
Ok(instance_id) => QueryResponse::MidiClipInstanceAdded(Ok(instance_id)),
|
||||
Err(e) => QueryResponse::MidiClipInstanceAdded(Err(e.to_string())),
|
||||
};
|
||||
self.refresh_clip_snapshot();
|
||||
@@ -2772,10 +2741,9 @@ impl Engine {
|
||||
}
|
||||
Query::AddMidiClipInstanceSync(track_id, mut instance) => {
|
||||
// Add MIDI clip instance to track (clip must already be in pool)
|
||||
// Assign instance ID
|
||||
// Assign instance ID; positions are already in beats
|
||||
let instance_id = self.project.next_midi_clip_instance_id();
|
||||
instance.id = instance_id;
|
||||
instance.sync_from_seconds(self.current_bpm, self.current_fps);
|
||||
|
||||
let result = match self.project.add_midi_clip_instance(track_id, instance) {
|
||||
Ok(_) => QueryResponse::MidiClipInstanceAdded(Ok(instance_id)),
|
||||
@@ -2943,7 +2911,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Handle starting a recording
|
||||
fn handle_start_recording(&mut self, track_id: TrackId, start_time: f64) {
|
||||
fn handle_start_recording(&mut self, track_id: TrackId, start_time: Beats) {
|
||||
use crate::io::WavWriter;
|
||||
use std::env;
|
||||
|
||||
@@ -2966,10 +2934,10 @@ impl Engine {
|
||||
let clip = crate::audio::clip::Clip::new(
|
||||
clip_id,
|
||||
0, // Temporary pool index, will be updated on finalization
|
||||
0.0, // internal_start
|
||||
0.0, // internal_end - Duration starts at 0, will be updated during recording
|
||||
start_time, // external_start (timeline position)
|
||||
start_time, // external_end - will be updated during recording
|
||||
Seconds(0.0), // internal_start
|
||||
Seconds(0.0), // internal_end - Duration starts at 0, will be updated during recording
|
||||
start_time, // external_start (timeline position, already Beats)
|
||||
Beats(0.0), // external_duration - will be updated during recording
|
||||
);
|
||||
|
||||
// Add clip to track
|
||||
@@ -3098,7 +3066,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Handle starting MIDI recording
|
||||
fn handle_start_midi_recording(&mut self, track_id: TrackId, clip_id: MidiClipId, start_time: f64) {
|
||||
fn handle_start_midi_recording(&mut self, track_id: TrackId, clip_id: MidiClipId, start_time: Beats) {
|
||||
// Check if track exists and is a MIDI track
|
||||
if let Some(crate::audio::track::TrackNode::Midi(_)) = self.project.get_track_mut(track_id) {
|
||||
// Create MIDI recording state
|
||||
@@ -3108,7 +3076,7 @@ impl Engine {
|
||||
// so they start at t=0 of the recording rather than being lost
|
||||
if let Some(held) = self.midi_held_notes.get(&track_id) {
|
||||
for (¬e, &velocity) in held {
|
||||
eprintln!("[MIDI_RECORDING] Injecting held note {} vel {} at start_time {:.3}s", note, velocity, start_time);
|
||||
eprintln!("[MIDI_RECORDING] Injecting held note {} vel {} at start_time {:.3}", note, velocity, start_time.0);
|
||||
recording_state.note_on(note, velocity, start_time);
|
||||
}
|
||||
}
|
||||
@@ -3135,8 +3103,8 @@ impl Engine {
|
||||
}
|
||||
|
||||
// Close out any active notes at the current playhead position
|
||||
let end_time = self.playhead as f64 / self.sample_rate as f64;
|
||||
eprintln!("[MIDI_RECORDING] Closing active notes at time {}", end_time);
|
||||
let end_time = self.tempo_map.seconds_to_beats(Seconds(self.playhead as f64 / self.sample_rate as f64));
|
||||
eprintln!("[MIDI_RECORDING] Closing active notes at time {}", end_time.0);
|
||||
recording.close_active_notes(end_time);
|
||||
|
||||
let clip_id = recording.clip_id;
|
||||
@@ -3145,8 +3113,8 @@ impl Engine {
|
||||
let note_count = notes.len();
|
||||
let recording_duration = end_time - recording.start_time;
|
||||
|
||||
eprintln!("[MIDI_RECORDING] Stopping MIDI recording for clip_id={}, track_id={}, captured {} notes, duration={:.3}s",
|
||||
clip_id, track_id, note_count, recording_duration);
|
||||
eprintln!("[MIDI_RECORDING] Stopping MIDI recording for clip_id={}, track_id={}, captured {} notes, duration={:.3} beats",
|
||||
clip_id, track_id, note_count, recording_duration.0);
|
||||
|
||||
// Update the MIDI clip in the pool (new model: clips are stored centrally in the pool)
|
||||
eprintln!("[MIDI_RECORDING] Looking for clip {} in midi_clip_pool", clip_id);
|
||||
@@ -3155,41 +3123,37 @@ impl Engine {
|
||||
// Clear existing events
|
||||
clip.events.clear();
|
||||
|
||||
// Update clip duration to match the actual recording time
|
||||
clip.duration = recording_duration;
|
||||
// Recording duration is already in beats (canonical)
|
||||
let duration_beats = recording_duration;
|
||||
clip.duration = duration_beats;
|
||||
|
||||
// Add new events from the recorded notes
|
||||
// Timestamps are now stored in seconds (sample-rate independent)
|
||||
let bpm = self.current_bpm;
|
||||
let fps = self.current_fps;
|
||||
// Add new events from the recorded notes.
|
||||
// Recorded timestamps are already in beats (canonical).
|
||||
for (start_time, note, velocity, duration) in notes.iter() {
|
||||
let mut note_on = MidiEvent::note_on(*start_time, 0, *note, *velocity);
|
||||
note_on.sync_from_seconds(bpm, fps);
|
||||
let note_on = MidiEvent::note_on(*start_time, 0, *note, *velocity);
|
||||
|
||||
eprintln!("[MIDI_RECORDING] Note {}: start_time={:.3}s, duration={:.3}s",
|
||||
note, start_time, duration);
|
||||
eprintln!("[MIDI_RECORDING] Note {}: start={:.3} beats, duration={:.3} beats",
|
||||
note, start_time.0, duration.0);
|
||||
|
||||
clip.events.push(note_on);
|
||||
|
||||
// Add note off event
|
||||
let note_off_time = *start_time + *duration;
|
||||
let mut note_off = MidiEvent::note_off(note_off_time, 0, *note, 64);
|
||||
note_off.sync_from_seconds(bpm, fps);
|
||||
let note_off = MidiEvent::note_off(note_off_time, 0, *note, 64);
|
||||
clip.events.push(note_off);
|
||||
}
|
||||
|
||||
// Sort events by timestamp (using partial_cmp for f64)
|
||||
// Sort events by timestamp (using partial_cmp for Beats)
|
||||
clip.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
|
||||
eprintln!("[MIDI_RECORDING] Updated clip {} with {} notes ({} events)", clip_id, note_count, clip.events.len());
|
||||
|
||||
// Also update the clip instance's internal_end and external_duration to match the recording duration
|
||||
if let Some(crate::audio::track::TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(instance) = track.clip_instances.iter_mut().find(|i| i.clip_id == clip_id) {
|
||||
instance.internal_end = recording_duration;
|
||||
instance.external_duration = recording_duration;
|
||||
instance.sync_from_seconds(bpm, fps);
|
||||
eprintln!("[MIDI_RECORDING] Updated clip instance timing: internal_end={:.3}s, external_duration={:.3}s",
|
||||
instance.internal_end, instance.external_duration);
|
||||
instance.internal_end = duration_beats;
|
||||
instance.external_duration = duration_beats;
|
||||
eprintln!("[MIDI_RECORDING] Updated clip instance timing: internal_end={:.3} beats, external_duration={:.3} beats",
|
||||
instance.internal_end.0, instance.external_duration.0);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -3643,7 +3607,7 @@ impl EngineController {
|
||||
|
||||
/// Start recording on a track
|
||||
pub fn start_recording(&mut self, track_id: TrackId, start_time: f64) {
|
||||
let _ = self.command_tx.push(Command::StartRecording(track_id, start_time));
|
||||
let _ = self.command_tx.push(Command::StartRecording(track_id, Beats(start_time)));
|
||||
}
|
||||
|
||||
/// Stop the current recording
|
||||
@@ -3663,7 +3627,7 @@ impl EngineController {
|
||||
|
||||
/// Start MIDI recording on a track
|
||||
pub fn start_midi_recording(&mut self, track_id: TrackId, clip_id: MidiClipId, start_time: f64) {
|
||||
let _ = self.command_tx.push(Command::StartMidiRecording(track_id, clip_id, start_time));
|
||||
let _ = self.command_tx.push(Command::StartMidiRecording(track_id, clip_id, Beats(start_time)));
|
||||
}
|
||||
|
||||
/// Stop the current MIDI recording
|
||||
@@ -3705,10 +3669,6 @@ impl EngineController {
|
||||
/// automation keyframe times to preserve beat positions.
|
||||
/// `from_bpm` is the BPM before the change; `to_bpm` is the new BPM.
|
||||
/// Call this after move_clip() has been called for all affected clips.
|
||||
pub fn apply_bpm_change(&mut self, from_bpm: f64, to_bpm: f64, fps: f64, midi_durations: Vec<(crate::audio::MidiClipId, f64)>) {
|
||||
let _ = self.command_tx.push(Command::ApplyBpmChange(from_bpm, to_bpm, fps, midi_durations));
|
||||
}
|
||||
|
||||
// Node graph operations
|
||||
|
||||
/// Add a node to a track's instrument graph
|
||||
|
||||
@@ -2,6 +2,8 @@ use super::buffer_pool::BufferPool;
|
||||
use super::pool::AudioPool;
|
||||
use super::project::Project;
|
||||
use crate::command::AudioEvent;
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::time::Seconds;
|
||||
use std::path::Path;
|
||||
|
||||
/// Render chunk size for offline export. Matches the real-time playback buffer size
|
||||
@@ -42,10 +44,12 @@ pub struct ExportSettings {
|
||||
pub bit_depth: u16,
|
||||
/// MP3 bitrate in kbps (128, 192, 256, 320)
|
||||
pub mp3_bitrate: u32,
|
||||
/// Start time in seconds
|
||||
pub start_time: f64,
|
||||
/// End time in seconds
|
||||
pub end_time: f64,
|
||||
/// Start time
|
||||
pub start_time: Seconds,
|
||||
/// End time
|
||||
pub end_time: Seconds,
|
||||
/// Tempo map for beat-position scheduling
|
||||
pub tempo_map: TempoMap,
|
||||
}
|
||||
|
||||
impl Default for ExportSettings {
|
||||
@@ -56,8 +60,9 @@ impl Default for ExportSettings {
|
||||
channels: 2,
|
||||
bit_depth: 16,
|
||||
mp3_bitrate: 320,
|
||||
start_time: 0.0,
|
||||
end_time: 60.0,
|
||||
start_time: Seconds::ZERO,
|
||||
end_time: Seconds(60.0),
|
||||
tempo_map: TempoMap::constant(120.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,15 +84,15 @@ pub fn export_audio<P: AsRef<Path>>(
|
||||
{
|
||||
// Validate duration
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
if duration <= 0.0 {
|
||||
if duration <= Seconds::ZERO {
|
||||
return Err(format!(
|
||||
"Export duration is zero or negative (start={:.3}s, end={:.3}s). \
|
||||
Check that the timeline has content.",
|
||||
settings.start_time, settings.end_time
|
||||
settings.start_time.seconds_to_f64(), settings.end_time.seconds_to_f64()
|
||||
));
|
||||
}
|
||||
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
if total_frames == 0 {
|
||||
return Err("Export would produce zero audio frames".to_string());
|
||||
}
|
||||
@@ -148,11 +153,11 @@ pub fn render_to_memory(
|
||||
{
|
||||
// Calculate total number of frames
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
let total_samples = total_frames * settings.channels as usize;
|
||||
|
||||
println!("Export: duration={:.3}s, total_frames={}, total_samples={}, channels={}",
|
||||
duration, total_frames, total_samples, settings.channels);
|
||||
duration.seconds_to_f64(), total_frames, total_samples, settings.channels);
|
||||
|
||||
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
|
||||
|
||||
@@ -178,6 +183,7 @@ pub fn render_to_memory(
|
||||
pool,
|
||||
&mut buffer_pool,
|
||||
playhead,
|
||||
&settings.tempo_map,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
@@ -185,9 +191,9 @@ pub fn render_to_memory(
|
||||
|
||||
// Calculate how many samples we actually need from this chunk
|
||||
let remaining_time = settings.end_time - playhead;
|
||||
let samples_needed = if remaining_time < chunk_duration {
|
||||
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
|
||||
// Calculate frames needed and ensure it's a whole number
|
||||
let frames_needed = (remaining_time * settings.sample_rate as f64).round() as usize;
|
||||
let frames_needed = (remaining_time.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
let samples = frames_needed * settings.channels as usize;
|
||||
// Ensure we don't exceed chunk size
|
||||
samples.min(chunk_samples)
|
||||
@@ -207,7 +213,7 @@ pub fn render_to_memory(
|
||||
});
|
||||
}
|
||||
|
||||
playhead += chunk_duration;
|
||||
playhead = playhead + Seconds(chunk_duration);
|
||||
}
|
||||
|
||||
println!("Export: rendered {} samples total", all_samples.len());
|
||||
@@ -361,7 +367,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
|
||||
// Calculate rendering parameters
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
|
||||
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
|
||||
let chunk_duration = EXPORT_CHUNK_FRAMES as f64 / settings.sample_rate as f64;
|
||||
@@ -396,6 +402,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
pool,
|
||||
&mut buffer_pool,
|
||||
playhead,
|
||||
&settings.tempo_map,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
@@ -403,8 +410,8 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
let remaining_time = settings.end_time - playhead;
|
||||
let samples_needed = if remaining_time < chunk_duration {
|
||||
((remaining_time * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
|
||||
((remaining_time.seconds_to_f64() * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
.min(chunk_samples)
|
||||
} else {
|
||||
chunk_samples
|
||||
@@ -445,7 +452,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
}
|
||||
}
|
||||
|
||||
playhead += chunk_duration;
|
||||
playhead = playhead + Seconds(chunk_duration);
|
||||
}
|
||||
|
||||
// Encode any remaining samples as the final frame
|
||||
@@ -529,7 +536,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
|
||||
// Calculate rendering parameters
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
|
||||
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
|
||||
let chunk_duration = EXPORT_CHUNK_FRAMES as f64 / settings.sample_rate as f64;
|
||||
@@ -564,6 +571,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
pool,
|
||||
&mut buffer_pool,
|
||||
playhead,
|
||||
&settings.tempo_map,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
@@ -571,8 +579,8 @@ fn export_aac<P: AsRef<Path>>(
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
let remaining_time = settings.end_time - playhead;
|
||||
let samples_needed = if remaining_time < chunk_duration {
|
||||
((remaining_time * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
|
||||
((remaining_time.seconds_to_f64() * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
.min(chunk_samples)
|
||||
} else {
|
||||
chunk_samples
|
||||
@@ -613,7 +621,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
}
|
||||
}
|
||||
|
||||
playhead += chunk_duration;
|
||||
playhead = playhead + Seconds(chunk_duration);
|
||||
}
|
||||
|
||||
// Encode any remaining samples as the final frame
|
||||
|
||||
+57
-240
@@ -1,14 +1,10 @@
|
||||
use crate::time::Beats;
|
||||
|
||||
/// MIDI event representing a single MIDI message
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiEvent {
|
||||
/// Time position within the clip in seconds (sample-rate independent)
|
||||
pub timestamp: f64,
|
||||
/// Time position in beats (quarter-note beats from clip start); derived from timestamp
|
||||
#[serde(default)]
|
||||
pub timestamp_beats: f64,
|
||||
/// Time position in frames; derived from timestamp
|
||||
#[serde(default)]
|
||||
pub timestamp_frames: f64,
|
||||
/// Time position in beats (quarter-note beats)
|
||||
pub timestamp: Beats,
|
||||
/// MIDI status byte (includes channel)
|
||||
pub status: u8,
|
||||
/// First data byte (note number, CC number, etc.)
|
||||
@@ -18,79 +14,28 @@ pub struct MidiEvent {
|
||||
}
|
||||
|
||||
impl MidiEvent {
|
||||
/// Create a new MIDI event
|
||||
pub fn new(timestamp: f64, status: u8, data1: u8, data2: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
timestamp_beats: 0.0,
|
||||
timestamp_frames: 0.0,
|
||||
status,
|
||||
data1,
|
||||
data2,
|
||||
}
|
||||
pub fn new(timestamp: Beats, status: u8, data1: u8, data2: u8) -> Self {
|
||||
Self { timestamp, status, data1, data2 }
|
||||
}
|
||||
|
||||
/// Create a note on event
|
||||
pub fn note_on(timestamp: f64, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
timestamp_beats: 0.0,
|
||||
timestamp_frames: 0.0,
|
||||
status: 0x90 | (channel & 0x0F),
|
||||
data1: note,
|
||||
data2: velocity,
|
||||
}
|
||||
pub fn note_on(timestamp: Beats, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self { timestamp, status: 0x90 | (channel & 0x0F), data1: note, data2: velocity }
|
||||
}
|
||||
|
||||
/// Create a note off event
|
||||
pub fn note_off(timestamp: f64, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
timestamp_beats: 0.0,
|
||||
timestamp_frames: 0.0,
|
||||
status: 0x80 | (channel & 0x0F),
|
||||
data1: note,
|
||||
data2: velocity,
|
||||
}
|
||||
pub fn note_off(timestamp: Beats, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self { timestamp, status: 0x80 | (channel & 0x0F), data1: note, data2: velocity }
|
||||
}
|
||||
|
||||
/// Sync beats and frames from seconds (call after constructing or when seconds is canonical)
|
||||
pub fn sync_from_seconds(&mut self, bpm: f64, fps: f64) {
|
||||
self.timestamp_beats = self.timestamp * bpm / 60.0;
|
||||
self.timestamp_frames = self.timestamp * 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.timestamp = self.timestamp_beats * 60.0 / bpm;
|
||||
self.timestamp_frames = self.timestamp * 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.timestamp = self.timestamp_frames / fps;
|
||||
self.timestamp_beats = self.timestamp * bpm / 60.0;
|
||||
}
|
||||
|
||||
/// Check if this is a note on event (with non-zero velocity)
|
||||
pub fn is_note_on(&self) -> bool {
|
||||
(self.status & 0xF0) == 0x90 && self.data2 > 0
|
||||
}
|
||||
|
||||
/// Check if this is a note off event (or note on with zero velocity)
|
||||
pub fn is_note_off(&self) -> bool {
|
||||
(self.status & 0xF0) == 0x80 || ((self.status & 0xF0) == 0x90 && self.data2 == 0)
|
||||
}
|
||||
|
||||
/// Get the MIDI channel (0-15)
|
||||
pub fn channel(&self) -> u8 {
|
||||
self.status & 0x0F
|
||||
}
|
||||
|
||||
/// Get the message type (upper 4 bits of status)
|
||||
pub fn message_type(&self) -> u8 {
|
||||
self.status & 0xF0
|
||||
}
|
||||
pub fn channel(&self) -> u8 { self.status & 0x0F }
|
||||
pub fn message_type(&self) -> u8 { self.status & 0xF0 }
|
||||
}
|
||||
|
||||
/// MIDI clip ID type (for clips stored in the pool)
|
||||
@@ -99,240 +44,118 @@ pub type MidiClipId = u32;
|
||||
/// MIDI clip instance ID type (for instances placed on tracks)
|
||||
pub type MidiClipInstanceId = u32;
|
||||
|
||||
/// MIDI clip content - stores the actual MIDI events
|
||||
///
|
||||
/// This represents the content data stored in the MidiClipPool.
|
||||
/// Events have timestamps relative to the start of the clip (0.0 = clip beginning).
|
||||
/// MIDI clip content — stores the actual MIDI events.
|
||||
/// `duration` is in beats.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiClip {
|
||||
pub id: MidiClipId,
|
||||
pub events: Vec<MidiEvent>,
|
||||
pub duration: f64, // Total content duration in seconds
|
||||
/// Total content duration in beats
|
||||
pub duration: Beats,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl MidiClip {
|
||||
/// Create a new MIDI clip with content
|
||||
pub fn new(id: MidiClipId, events: Vec<MidiEvent>, duration: f64, name: String) -> Self {
|
||||
let mut clip = Self {
|
||||
id,
|
||||
events,
|
||||
duration,
|
||||
name,
|
||||
};
|
||||
// Sort events by timestamp
|
||||
pub fn new(id: MidiClipId, events: Vec<MidiEvent>, duration: Beats, name: String) -> Self {
|
||||
let mut clip = Self { id, events, duration, name };
|
||||
clip.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
|
||||
clip
|
||||
}
|
||||
|
||||
/// Create an empty MIDI clip
|
||||
pub fn empty(id: MidiClipId, duration: f64, name: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
events: Vec::new(),
|
||||
duration,
|
||||
name,
|
||||
}
|
||||
pub fn empty(id: MidiClipId, duration: Beats, name: String) -> Self {
|
||||
Self { id, events: Vec::new(), duration, name }
|
||||
}
|
||||
|
||||
/// Add a MIDI event to the clip
|
||||
pub fn add_event(&mut self, event: MidiEvent) {
|
||||
self.events.push(event);
|
||||
// Keep events sorted by timestamp
|
||||
self.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
|
||||
}
|
||||
|
||||
/// Get events within a time range (relative to clip start)
|
||||
/// This is used by MidiClipInstance to fetch events for a given portion
|
||||
pub fn get_events_in_range(&self, start: f64, end: f64) -> Vec<MidiEvent> {
|
||||
self.events
|
||||
.iter()
|
||||
/// Get events within a beat range (relative to clip start)
|
||||
pub fn get_events_in_range(&self, start: Beats, end: Beats) -> Vec<MidiEvent> {
|
||||
self.events.iter()
|
||||
.filter(|e| e.timestamp >= start && e.timestamp < end)
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// MIDI clip instance - a reference to MidiClip content with timeline positioning
|
||||
/// MIDI clip instance — a reference to MidiClip content with timeline positioning.
|
||||
///
|
||||
/// ## Timing Model
|
||||
/// - `internal_start` / `internal_end`: Define the region of the source clip to play (trimming)
|
||||
/// - `external_start` / `external_duration`: Define where the instance appears on the timeline and how long
|
||||
/// - `*_beats` / `*_frames`: Derived representations for Measures/Frames mode display
|
||||
///
|
||||
/// ## Looping
|
||||
/// If `external_duration` is greater than `internal_end - internal_start`,
|
||||
/// the instance will seamlessly loop back to `internal_start` when it reaches `internal_end`.
|
||||
/// All timing fields are in beats.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiClipInstance {
|
||||
pub id: MidiClipInstanceId,
|
||||
pub clip_id: MidiClipId, // Reference to MidiClip in pool
|
||||
pub clip_id: MidiClipId,
|
||||
|
||||
/// Start position within the clip content (seconds)
|
||||
pub internal_start: f64,
|
||||
#[serde(default)] pub internal_start_beats: f64,
|
||||
#[serde(default)] pub internal_start_frames: f64,
|
||||
/// End position within the clip content (seconds)
|
||||
pub internal_end: f64,
|
||||
#[serde(default)] pub internal_end_beats: f64,
|
||||
#[serde(default)] pub internal_end_frames: f64,
|
||||
/// Start of the trimmed region within the clip content (beats)
|
||||
pub internal_start: Beats,
|
||||
/// End of the trimmed region within the clip content (beats)
|
||||
pub internal_end: Beats,
|
||||
|
||||
/// Start position on the timeline (seconds)
|
||||
pub external_start: f64,
|
||||
#[serde(default)] pub external_start_beats: f64,
|
||||
#[serde(default)] pub external_start_frames: f64,
|
||||
/// Duration on the timeline (seconds) - can be longer than internal duration for looping
|
||||
pub external_duration: f64,
|
||||
#[serde(default)] pub external_duration_beats: f64,
|
||||
#[serde(default)] pub external_duration_frames: f64,
|
||||
/// Start position on the timeline (beats)
|
||||
pub external_start: Beats,
|
||||
/// Duration on the timeline (beats); > internal duration = looping
|
||||
pub external_duration: Beats,
|
||||
}
|
||||
|
||||
impl MidiClipInstance {
|
||||
/// Create a new MIDI clip instance
|
||||
pub fn new(
|
||||
id: MidiClipInstanceId,
|
||||
clip_id: MidiClipId,
|
||||
internal_start: f64,
|
||||
internal_end: f64,
|
||||
external_start: f64,
|
||||
external_duration: f64,
|
||||
internal_start: Beats,
|
||||
internal_end: Beats,
|
||||
external_start: Beats,
|
||||
external_duration: Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
clip_id,
|
||||
internal_start,
|
||||
internal_start_beats: 0.0,
|
||||
internal_start_frames: 0.0,
|
||||
internal_end,
|
||||
internal_end_beats: 0.0,
|
||||
internal_end_frames: 0.0,
|
||||
external_start,
|
||||
external_start_beats: 0.0,
|
||||
external_start_frames: 0.0,
|
||||
external_duration,
|
||||
external_duration_beats: 0.0,
|
||||
external_duration_frames: 0.0,
|
||||
}
|
||||
Self { id, clip_id, internal_start, internal_end, external_start, external_duration }
|
||||
}
|
||||
|
||||
/// Create an instance that uses the full clip content (no trimming, no looping)
|
||||
/// Create an instance covering the full clip with no trim
|
||||
pub fn from_full_clip(
|
||||
id: MidiClipInstanceId,
|
||||
clip_id: MidiClipId,
|
||||
clip_duration: f64,
|
||||
external_start: f64,
|
||||
clip_duration: Beats,
|
||||
external_start: Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
clip_id,
|
||||
internal_start: 0.0,
|
||||
internal_start_beats: 0.0,
|
||||
internal_start_frames: 0.0,
|
||||
internal_start: Beats::ZERO,
|
||||
internal_end: clip_duration,
|
||||
internal_end_beats: 0.0,
|
||||
internal_end_frames: 0.0,
|
||||
external_start,
|
||||
external_start_beats: 0.0,
|
||||
external_start_frames: 0.0,
|
||||
external_duration: clip_duration,
|
||||
external_duration_beats: 0.0,
|
||||
external_duration_frames: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the internal (content) duration
|
||||
pub fn internal_duration(&self) -> f64 {
|
||||
self.internal_end - self.internal_start
|
||||
}
|
||||
pub fn internal_duration(&self) -> Beats { self.internal_end - self.internal_start }
|
||||
pub fn external_end(&self) -> Beats { self.external_start + self.external_duration }
|
||||
pub fn is_looping(&self) -> bool { self.external_duration > self.internal_duration() }
|
||||
|
||||
/// Get the end time on the timeline
|
||||
pub fn external_end(&self) -> f64 {
|
||||
self.external_start + self.external_duration
|
||||
}
|
||||
|
||||
/// Check if this instance loops
|
||||
pub fn is_looping(&self) -> bool {
|
||||
self.external_duration > self.internal_duration()
|
||||
}
|
||||
|
||||
/// Get the end time on the timeline (for backwards compatibility)
|
||||
pub fn end_time(&self) -> f64 {
|
||||
self.external_end()
|
||||
}
|
||||
|
||||
/// Get the start time on the timeline (for backwards compatibility)
|
||||
pub fn start_time(&self) -> f64 {
|
||||
self.external_start
|
||||
}
|
||||
|
||||
/// Check if this instance overlaps with a time range
|
||||
pub fn overlaps_range(&self, range_start: f64, range_end: f64) -> bool {
|
||||
/// Check if this instance overlaps with a beat range
|
||||
pub fn overlaps_range(&self, range_start: Beats, range_end: Beats) -> bool {
|
||||
self.external_start < range_end && self.external_end() > range_start
|
||||
}
|
||||
|
||||
/// Populate beats/frames from the current seconds values.
|
||||
pub fn sync_from_seconds(&mut self, bpm: f64, fps: f64) {
|
||||
self.external_start_beats = self.external_start * bpm / 60.0;
|
||||
self.external_start_frames = self.external_start * fps;
|
||||
self.external_duration_beats = self.external_duration * bpm / 60.0;
|
||||
self.external_duration_frames = self.external_duration * fps;
|
||||
self.internal_start_beats = self.internal_start * bpm / 60.0;
|
||||
self.internal_start_frames = self.internal_start * fps;
|
||||
self.internal_end_beats = self.internal_end * bpm / 60.0;
|
||||
self.internal_end_frames = self.internal_end * fps;
|
||||
}
|
||||
|
||||
/// BPM changed; recompute seconds/frames from the stored beats values.
|
||||
pub fn apply_beats(&mut self, bpm: f64, fps: f64) {
|
||||
self.external_start = self.external_start_beats * 60.0 / bpm;
|
||||
self.external_start_frames = self.external_start * fps;
|
||||
self.external_duration = self.external_duration_beats * 60.0 / bpm;
|
||||
self.external_duration_frames = self.external_duration * fps;
|
||||
self.internal_start = self.internal_start_beats * 60.0 / bpm;
|
||||
self.internal_start_frames = self.internal_start * fps;
|
||||
self.internal_end = self.internal_end_beats * 60.0 / bpm;
|
||||
self.internal_end_frames = self.internal_end * fps;
|
||||
}
|
||||
|
||||
/// FPS changed; recompute seconds/beats from the stored frames values.
|
||||
pub fn apply_frames(&mut self, fps: f64, bpm: f64) {
|
||||
self.external_start = self.external_start_frames / fps;
|
||||
self.external_start_beats = self.external_start * bpm / 60.0;
|
||||
self.external_duration = self.external_duration_frames / fps;
|
||||
self.external_duration_beats = self.external_duration * bpm / 60.0;
|
||||
self.internal_start = self.internal_start_frames / fps;
|
||||
self.internal_start_beats = self.internal_start * bpm / 60.0;
|
||||
self.internal_end = self.internal_end_frames / fps;
|
||||
self.internal_end_beats = self.internal_end * bpm / 60.0;
|
||||
}
|
||||
|
||||
/// Get events that should be triggered in a given timeline range
|
||||
///
|
||||
/// This handles:
|
||||
/// - Trimming (internal_start/internal_end)
|
||||
/// - Looping (when external duration > internal duration)
|
||||
/// - Time mapping from timeline to clip content
|
||||
///
|
||||
/// Returns events with timestamps adjusted to timeline time (not clip-relative)
|
||||
/// Get events that should fire in a given beat range on the timeline.
|
||||
/// Returns events with `timestamp` set to their global timeline beat position.
|
||||
pub fn get_events_in_range(
|
||||
&self,
|
||||
clip: &MidiClip,
|
||||
range_start_seconds: f64,
|
||||
range_end_seconds: f64,
|
||||
range_start: Beats,
|
||||
range_end: Beats,
|
||||
) -> Vec<MidiEvent> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
// Check if instance overlaps with the range
|
||||
if !self.overlaps_range(range_start_seconds, range_end_seconds) {
|
||||
if !self.overlaps_range(range_start, range_end) {
|
||||
return result;
|
||||
}
|
||||
|
||||
let internal_duration = self.internal_duration();
|
||||
if internal_duration <= 0.0 {
|
||||
if internal_duration <= Beats::ZERO {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Calculate how many complete loops fit in the external duration
|
||||
let num_loops = if self.external_duration > internal_duration {
|
||||
(self.external_duration / internal_duration).ceil() as usize
|
||||
} else {
|
||||
@@ -342,24 +165,18 @@ impl MidiClipInstance {
|
||||
let external_end = self.external_end();
|
||||
|
||||
for loop_idx in 0..num_loops {
|
||||
let loop_offset = loop_idx as f64 * internal_duration;
|
||||
let loop_offset = internal_duration * loop_idx as f64;
|
||||
|
||||
// Get events from the clip that fall within the internal range
|
||||
for event in &clip.events {
|
||||
// Skip events outside the trimmed region
|
||||
// Use > (not >=) for internal_end so note-offs at the clip boundary are included
|
||||
if event.timestamp < self.internal_start || event.timestamp > self.internal_end {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Convert to timeline time
|
||||
let relative_content_time = event.timestamp - self.internal_start;
|
||||
let timeline_time = self.external_start + loop_offset + relative_content_time;
|
||||
|
||||
// Check if within current buffer range and instance bounds
|
||||
// Use <= for external_end so note-offs at the clip boundary are included
|
||||
if timeline_time >= range_start_seconds
|
||||
&& timeline_time < range_end_seconds
|
||||
if timeline_time >= range_start
|
||||
&& timeline_time < range_end
|
||||
&& timeline_time <= external_end
|
||||
{
|
||||
let mut adjusted_event = *event;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::HashMap;
|
||||
use super::midi::{MidiClip, MidiClipId, MidiEvent};
|
||||
use crate::time::Beats;
|
||||
|
||||
/// Pool for storing MIDI clip content
|
||||
/// Similar to AudioClipPool but for MIDI data
|
||||
@@ -21,7 +22,7 @@ impl MidiClipPool {
|
||||
|
||||
/// Add a new clip to the pool with the given events and duration
|
||||
/// Returns the ID of the newly created clip
|
||||
pub fn add_clip(&mut self, events: Vec<MidiEvent>, duration: f64, name: String) -> MidiClipId {
|
||||
pub fn add_clip(&mut self, events: Vec<MidiEvent>, duration: Beats, name: String) -> MidiClipId {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::node_trait::AudioNode;
|
||||
use super::types::{ConnectionError, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
use petgraph::algo::has_path_connecting;
|
||||
use petgraph::stable_graph::{NodeIndex, StableGraph};
|
||||
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
|
||||
@@ -93,8 +94,8 @@ pub struct AudioGraph {
|
||||
/// UI positions for nodes (node_index -> (x, y))
|
||||
node_positions: std::collections::HashMap<u32, (f32, f32)>,
|
||||
|
||||
/// Current playback time (for automation nodes)
|
||||
playback_time: f64,
|
||||
/// Current playback time in beats (for automation nodes)
|
||||
playback_time: Beats,
|
||||
|
||||
/// Project tempo (synced from Engine via SetTempo)
|
||||
bpm: f32,
|
||||
@@ -123,7 +124,7 @@ impl AudioGraph {
|
||||
// Pre-allocate MIDI input buffers (max 128 events per port)
|
||||
midi_input_buffers: (0..16).map(|_| Vec::with_capacity(128)).collect(),
|
||||
node_positions: std::collections::HashMap::new(),
|
||||
playback_time: 0.0,
|
||||
playback_time: Beats::ZERO,
|
||||
bpm: 120.0,
|
||||
beats_per_bar: 4,
|
||||
topo_cache: None,
|
||||
@@ -475,7 +476,7 @@ impl AudioGraph {
|
||||
}
|
||||
|
||||
/// Process the graph and produce audio output
|
||||
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: f64) {
|
||||
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: Beats) {
|
||||
// Update playback time
|
||||
self.playback_time = playback_time;
|
||||
|
||||
@@ -484,6 +485,7 @@ impl AudioGraph {
|
||||
for node in self.graph.node_weights_mut() {
|
||||
if let Some(auto_node) = node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
|
||||
auto_node.set_playback_time(playback_time);
|
||||
auto_node.set_bpm(self.bpm as f64);
|
||||
} else if let Some(beat_node) = node.node.as_any_mut().downcast_mut::<BeatNode>() {
|
||||
beat_node.set_playback_time(playback_time);
|
||||
beat_node.set_tempo(self.bpm, self.beats_per_bar);
|
||||
@@ -737,18 +739,6 @@ impl AudioGraph {
|
||||
self.graph.node_indices()
|
||||
}
|
||||
|
||||
/// BPM changed: rescale all AutomationInput keyframe times to preserve beat positions.
|
||||
/// `from_bpm` is the BPM before the change (used to bootstrap beats if not yet populated).
|
||||
/// `to_bpm` is the new BPM (used to re-derive seconds from beats).
|
||||
pub fn apply_beats_to_automation_keyframes(&mut self, from_bpm: f64, to_bpm: f64, fps: f64) {
|
||||
use super::nodes::AutomationInputNode;
|
||||
for node in self.graph.node_weights_mut() {
|
||||
if let Some(auto_node) = node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
|
||||
auto_node.apply_beats_to_keyframes(from_bpm, to_bpm, fps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reallocate a node's output buffers to match its current port list.
|
||||
///
|
||||
/// Must be called after `SubtrackInputsNode::update_subtracks` changes the port count,
|
||||
@@ -1029,7 +1019,7 @@ impl AudioGraph {
|
||||
serialized.automation_display_name = Some(auto_node.display_name().to_string());
|
||||
serialized.automation_keyframes = auto_node.keyframes().iter().map(|kf| {
|
||||
SerializedKeyframe {
|
||||
time: kf.time,
|
||||
time: kf.time.0,
|
||||
value: kf.value,
|
||||
interpolation: match kf.interpolation {
|
||||
InterpolationType::Linear => "linear",
|
||||
@@ -1369,9 +1359,7 @@ impl AudioGraph {
|
||||
auto_node.clear_keyframes();
|
||||
for kf in &serialized_node.automation_keyframes {
|
||||
auto_node.add_keyframe(AutomationKeyframe {
|
||||
time: kf.time,
|
||||
time_beats: 0.0,
|
||||
time_frames: 0.0,
|
||||
time: crate::time::Beats(kf.time),
|
||||
value: kf.value,
|
||||
interpolation: match kf.interpolation.as_str() {
|
||||
"bezier" => InterpolationType::Bezier,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
@@ -16,14 +17,7 @@ pub enum InterpolationType {
|
||||
/// A single keyframe in an automation curve
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AutomationKeyframe {
|
||||
/// Time in seconds (absolute project time)
|
||||
pub time: f64,
|
||||
/// Time in beats (derived; canonical in Measures mode)
|
||||
#[serde(default)]
|
||||
pub time_beats: f64,
|
||||
/// Time in frames (derived; canonical in Frames mode)
|
||||
#[serde(default)]
|
||||
pub time_frames: f64,
|
||||
pub time: Beats,
|
||||
/// CV output value
|
||||
pub value: f32,
|
||||
/// Interpolation type to next keyframe
|
||||
@@ -35,35 +29,15 @@ pub struct AutomationKeyframe {
|
||||
}
|
||||
|
||||
impl AutomationKeyframe {
|
||||
pub fn new(time: f64, value: f32) -> Self {
|
||||
pub fn new(time: Beats, value: f32) -> Self {
|
||||
Self {
|
||||
time,
|
||||
time_beats: 0.0,
|
||||
time_frames: 0.0,
|
||||
value,
|
||||
interpolation: InterpolationType::Linear,
|
||||
ease_out: (0.58, 1.0),
|
||||
ease_in: (0.42, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Populate beats/frames from the current seconds value.
|
||||
pub fn sync_from_seconds(&mut self, bpm: f64, fps: f64) {
|
||||
self.time_beats = self.time * bpm / 60.0;
|
||||
self.time_frames = self.time * fps;
|
||||
}
|
||||
|
||||
/// BPM changed; beats are canonical → recompute seconds and frames.
|
||||
pub fn apply_beats(&mut self, bpm: f64, fps: f64) {
|
||||
self.time = self.time_beats * 60.0 / bpm;
|
||||
self.time_frames = self.time * fps;
|
||||
}
|
||||
|
||||
/// FPS changed; frames are canonical → recompute seconds and beats.
|
||||
pub fn apply_frames(&mut self, fps: f64, bpm: f64) {
|
||||
self.time = self.time_frames / fps;
|
||||
self.time_beats = self.time * bpm / 60.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Automation Input Node - outputs CV signal controlled by timeline curves
|
||||
@@ -73,8 +47,10 @@ pub struct AutomationInputNode {
|
||||
keyframes: Vec<AutomationKeyframe>,
|
||||
outputs: Vec<NodePort>,
|
||||
parameters: Vec<Parameter>,
|
||||
/// Shared playback time (set by the graph before processing)
|
||||
playback_time: Arc<RwLock<f64>>,
|
||||
/// Shared playback time in beats (set by the graph before processing)
|
||||
playback_time: Arc<RwLock<Beats>>,
|
||||
/// Current BPM (set by the graph before processing, used for per-sample beat advancement)
|
||||
bpm: f64,
|
||||
/// Minimum output value (for UI display range)
|
||||
pub value_min: f32,
|
||||
/// Maximum output value (for UI display range)
|
||||
@@ -97,22 +73,26 @@ impl AutomationInputNode {
|
||||
Self {
|
||||
name: name.clone(),
|
||||
display_name: "Automation".to_string(),
|
||||
keyframes: vec![AutomationKeyframe::new(0.0, 0.0)],
|
||||
keyframes: vec![AutomationKeyframe::new(Beats::ZERO, 0.0)],
|
||||
outputs,
|
||||
parameters,
|
||||
playback_time: Arc::new(RwLock::new(0.0)),
|
||||
playback_time: Arc::new(RwLock::new(Beats::ZERO)),
|
||||
bpm: 120.0,
|
||||
value_min: -1.0,
|
||||
value_max: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the playback time (called by graph before processing)
|
||||
pub fn set_playback_time(&mut self, time: f64) {
|
||||
pub fn set_playback_time(&mut self, time: Beats) {
|
||||
if let Ok(mut playback) = self.playback_time.write() {
|
||||
*playback = time;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_bpm(&mut self, bpm: f64) {
|
||||
self.bpm = bpm;
|
||||
}
|
||||
|
||||
/// Get the display name (shown in UI)
|
||||
pub fn display_name(&self) -> &str {
|
||||
&self.display_name
|
||||
@@ -142,8 +122,7 @@ impl AutomationInputNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove keyframe at specific time (with tolerance)
|
||||
pub fn remove_keyframe_at_time(&mut self, time: f64, tolerance: f64) -> bool {
|
||||
pub fn remove_keyframe_at_time(&mut self, time: Beats, tolerance: Beats) -> bool {
|
||||
if let Some(idx) = self.keyframes.iter().position(|kf| (kf.time - time).abs() < tolerance) {
|
||||
self.keyframes.remove(idx);
|
||||
true
|
||||
@@ -152,10 +131,8 @@ impl AutomationInputNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update an existing keyframe
|
||||
pub fn update_keyframe(&mut self, keyframe: AutomationKeyframe) {
|
||||
// Remove old keyframe at this time, then add new one
|
||||
self.remove_keyframe_at_time(keyframe.time, 0.001);
|
||||
self.remove_keyframe_at_time(keyframe.time, Beats(0.001));
|
||||
self.add_keyframe(keyframe);
|
||||
}
|
||||
|
||||
@@ -169,42 +146,20 @@ impl AutomationInputNode {
|
||||
self.keyframes.clear();
|
||||
}
|
||||
|
||||
/// Populate beats/frames on all keyframes from their current seconds values.
|
||||
pub fn sync_keyframes_from_seconds(&mut self, bpm: f64, fps: f64) {
|
||||
for kf in &mut self.keyframes {
|
||||
kf.sync_from_seconds(bpm, fps);
|
||||
}
|
||||
}
|
||||
|
||||
/// BPM changed: for each keyframe, bootstrap beats from seconds (using `from_bpm`) if not yet
|
||||
/// set, then re-derive seconds and frames from beats using `to_bpm`.
|
||||
pub fn apply_beats_to_keyframes(&mut self, from_bpm: f64, to_bpm: f64, fps: f64) {
|
||||
for kf in &mut self.keyframes {
|
||||
if kf.time_beats == 0.0 && kf.time.abs() > 1e-9 {
|
||||
kf.sync_from_seconds(from_bpm, fps);
|
||||
}
|
||||
kf.apply_beats(to_bpm, fps);
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate curve at a specific time
|
||||
fn evaluate_at_time(&self, time: f64) -> f32 {
|
||||
fn evaluate_at_time(&self, time: Beats) -> f32 {
|
||||
if self.keyframes.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
// Before first keyframe
|
||||
if time <= self.keyframes[0].time {
|
||||
return self.keyframes[0].value;
|
||||
}
|
||||
|
||||
// After last keyframe
|
||||
let last_idx = self.keyframes.len() - 1;
|
||||
if time >= self.keyframes[last_idx].time {
|
||||
return self.keyframes[last_idx].value;
|
||||
}
|
||||
|
||||
// Find bracketing keyframes
|
||||
for i in 0..self.keyframes.len() - 1 {
|
||||
let kf1 = &self.keyframes[i];
|
||||
let kf2 = &self.keyframes[i + 1];
|
||||
@@ -217,14 +172,12 @@ impl AutomationInputNode {
|
||||
0.0
|
||||
}
|
||||
|
||||
/// Interpolate between two keyframes
|
||||
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: f64) -> f32 {
|
||||
// Calculate normalized position between keyframes (0.0 to 1.0)
|
||||
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: Beats) -> f32 {
|
||||
let t = if kf2.time == kf1.time {
|
||||
0.0
|
||||
0.0f64
|
||||
} else {
|
||||
((time - kf1.time) / (kf2.time - kf1.time)) as f32
|
||||
};
|
||||
(time - kf1.time) / (kf2.time - kf1.time)
|
||||
} as f32;
|
||||
|
||||
match kf1.interpolation {
|
||||
InterpolationType::Linear => {
|
||||
@@ -301,19 +254,17 @@ impl AudioNode for AutomationInputNode {
|
||||
let output = &mut outputs[0];
|
||||
let length = output.len();
|
||||
|
||||
// Get the starting playback time
|
||||
let playhead = if let Ok(playback) = self.playback_time.read() {
|
||||
*playback
|
||||
} else {
|
||||
0.0
|
||||
Beats::ZERO
|
||||
};
|
||||
|
||||
// Calculate time per sample
|
||||
let sample_duration = 1.0 / sample_rate as f64;
|
||||
// Advance per sample in beats: beats_per_sample = bpm / 60 / sample_rate
|
||||
let beats_per_sample = self.bpm / 60.0 / sample_rate as f64;
|
||||
|
||||
// Evaluate curve for each sample
|
||||
for i in 0..length {
|
||||
let time = playhead + (i as f64 * sample_duration);
|
||||
let time = playhead + Beats(i as f64 * beats_per_sample);
|
||||
output[i] = self.evaluate_at_time(time);
|
||||
}
|
||||
}
|
||||
@@ -337,7 +288,8 @@ impl AudioNode for AutomationInputNode {
|
||||
keyframes: self.keyframes.clone(),
|
||||
outputs: self.outputs.clone(),
|
||||
parameters: self.parameters.clone(),
|
||||
playback_time: Arc::new(RwLock::new(0.0)),
|
||||
playback_time: Arc::new(RwLock::new(Beats::ZERO)),
|
||||
bpm: self.bpm,
|
||||
value_min: self.value_min,
|
||||
value_max: self.value_max,
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
|
||||
const PARAM_RESOLUTION: u32 = 0;
|
||||
|
||||
@@ -61,12 +62,12 @@ pub struct BeatNode {
|
||||
bpm: f32,
|
||||
beats_per_bar: u32,
|
||||
resolution: BeatResolution,
|
||||
/// Playback time in seconds, set by the graph before process()
|
||||
playback_time: f64,
|
||||
/// Playback time in beats, set by the graph before process()
|
||||
playback_time: Beats,
|
||||
/// Previous playback_time to detect paused state
|
||||
prev_playback_time: f64,
|
||||
/// Free-running time accumulator for when playback is stopped
|
||||
free_run_time: f64,
|
||||
prev_playback_time: Beats,
|
||||
/// Free-running beat accumulator for when playback is stopped
|
||||
free_run_time: Beats,
|
||||
inputs: Vec<NodePort>,
|
||||
outputs: Vec<NodePort>,
|
||||
parameters: Vec<Parameter>,
|
||||
@@ -92,16 +93,16 @@ impl BeatNode {
|
||||
bpm: DEFAULT_BPM,
|
||||
beats_per_bar: DEFAULT_BEATS_PER_BAR,
|
||||
resolution: BeatResolution::Quarter,
|
||||
playback_time: 0.0,
|
||||
prev_playback_time: -1.0,
|
||||
free_run_time: 0.0,
|
||||
playback_time: Beats::ZERO,
|
||||
prev_playback_time: Beats(-1.0),
|
||||
free_run_time: Beats::ZERO,
|
||||
inputs,
|
||||
outputs,
|
||||
parameters,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_playback_time(&mut self, time: f64) {
|
||||
pub fn set_playback_time(&mut self, time: Beats) {
|
||||
self.playback_time = time;
|
||||
}
|
||||
|
||||
@@ -169,8 +170,8 @@ impl AudioNode for BeatNode {
|
||||
let base_time = if paused { self.free_run_time } else { self.playback_time };
|
||||
|
||||
for i in 0..len {
|
||||
let time = base_time + i as f64 * sample_period;
|
||||
let beat_pos = time * beats_per_second;
|
||||
// base_time is already in beats; advance by beats_per_second per second
|
||||
let beat_pos = base_time.0 + i as f64 * beats_per_second * sample_period;
|
||||
|
||||
// Beat subdivision phase: 0→1 sawtooth
|
||||
let sub_phase = ((beat_pos * subs_per_beat) % 1.0) as f32;
|
||||
@@ -188,13 +189,13 @@ impl AudioNode for BeatNode {
|
||||
}
|
||||
|
||||
// Advance free-run time (always ticks, so it's ready when playback stops)
|
||||
self.free_run_time += len as f64 * sample_period;
|
||||
self.free_run_time += Beats(len as f64 * beats_per_second * sample_period);
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.playback_time = 0.0;
|
||||
self.prev_playback_time = -1.0;
|
||||
self.free_run_time = 0.0;
|
||||
self.playback_time = Beats::ZERO;
|
||||
self.prev_playback_time = Beats(-1.0);
|
||||
self.free_run_time = Beats::ZERO;
|
||||
}
|
||||
|
||||
fn node_type(&self) -> &str {
|
||||
@@ -211,9 +212,9 @@ impl AudioNode for BeatNode {
|
||||
bpm: self.bpm,
|
||||
beats_per_bar: self.beats_per_bar,
|
||||
resolution: self.resolution,
|
||||
playback_time: 0.0,
|
||||
prev_playback_time: -1.0,
|
||||
free_run_time: 0.0,
|
||||
playback_time: Beats::ZERO,
|
||||
prev_playback_time: Beats(-1.0),
|
||||
free_run_time: Beats::ZERO,
|
||||
inputs: self.inputs.clone(),
|
||||
outputs: self.outputs.clone(),
|
||||
parameters: self.parameters.clone(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType, cv_input_or_default};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
|
||||
const PARAM_MODE: u32 = 0;
|
||||
const PARAM_STEPS: u32 = 1;
|
||||
@@ -244,14 +245,14 @@ impl AudioNode for SequencerNode {
|
||||
// Note-off for notes no longer active
|
||||
for ¬e in &self.prev_active_notes {
|
||||
if !new_notes.contains(¬e) {
|
||||
midi_outputs[0].push(MidiEvent::note_off(0.0, 0, note, 0));
|
||||
midi_outputs[0].push(MidiEvent::note_off(Beats::ZERO, 0, note, 0));
|
||||
}
|
||||
}
|
||||
|
||||
// Note-on for newly active notes
|
||||
for ¬e in &new_notes {
|
||||
if !self.prev_active_notes.contains(¬e) {
|
||||
midi_outputs[0].push(MidiEvent::note_on(0.0, 0, note, self.velocity));
|
||||
midi_outputs[0].push(MidiEvent::note_on(Beats::ZERO, 0, note, self.velocity));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -348,7 +348,7 @@ impl AudioNode for VoiceAllocatorNode {
|
||||
|
||||
// Process this voice's graph with its MIDI events
|
||||
// Note: playback_time is 0.0 since voice allocator doesn't track time
|
||||
self.voice_instances[voice_idx].process(mix_slice, &midi_events, 0.0);
|
||||
self.voice_instances[voice_idx].process(mix_slice, &midi_events, crate::time::Beats::ZERO);
|
||||
|
||||
// Auto-deactivate releasing voices that have gone silent
|
||||
if voice_state.releasing {
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::f32::consts::PI;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::time::Seconds;
|
||||
|
||||
/// Windowed sinc interpolation for high-quality time stretching
|
||||
/// This is stateless and can handle arbitrary fractional positions
|
||||
@@ -442,19 +443,20 @@ impl AudioClipPool {
|
||||
}
|
||||
|
||||
/// Render audio from a file in the pool with high-quality windowed sinc interpolation
|
||||
/// start_time_seconds: position in the audio file to start reading from (in seconds)
|
||||
/// start_time: position in the audio file to start reading from (in seconds)
|
||||
/// clip_read_ahead: per-clip-instance read-ahead buffer for compressed audio streaming
|
||||
/// Returns the number of samples actually rendered
|
||||
pub fn render_from_file(
|
||||
&self,
|
||||
pool_index: usize,
|
||||
output: &mut [f32],
|
||||
start_time_seconds: f64,
|
||||
start_time: Seconds,
|
||||
gain: f32,
|
||||
engine_sample_rate: u32,
|
||||
engine_channels: u32,
|
||||
clip_read_ahead: Option<&super::disk_reader::ReadAheadBuffer>,
|
||||
) -> usize {
|
||||
let start_time_seconds = start_time.0;
|
||||
let Some(audio_file) = self.files.get(pool_index) else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
@@ -4,6 +4,8 @@ use super::midi::{MidiClip, MidiClipId, MidiClipInstance, MidiClipInstanceId, Mi
|
||||
use super::midi_pool::MidiClipPool;
|
||||
use super::pool::AudioClipPool;
|
||||
use super::track::{AudioTrack, Metatrack, MidiTrack, RenderContext, TrackId, TrackNode};
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::time::{Beats, Seconds};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -216,52 +218,6 @@ impl Project {
|
||||
self.tracks.iter().map(|(&id, node)| (id, node))
|
||||
}
|
||||
|
||||
/// After a BPM change, update MIDI clip durations, sync clip beats/frames, and rescale
|
||||
/// automation keyframe times to preserve beat positions.
|
||||
///
|
||||
/// `from_bpm` is the BPM before the change (used to bootstrap beats on legacy data).
|
||||
/// `to_bpm` is the new BPM.
|
||||
/// `midi_durations` maps each MidiClipId to its new content duration in seconds.
|
||||
/// Call this after the seconds positions have already been updated (e.g. via MoveClip).
|
||||
pub fn apply_bpm_change(&mut self, from_bpm: f64, to_bpm: f64, fps: f64, midi_durations: &[(crate::audio::midi::MidiClipId, f64)]) {
|
||||
for (_, track) in self.tracks.iter_mut() {
|
||||
match track {
|
||||
crate::audio::track::TrackNode::Audio(t) => {
|
||||
for clip in &mut t.clips {
|
||||
clip.sync_from_seconds(to_bpm, fps);
|
||||
}
|
||||
}
|
||||
crate::audio::track::TrackNode::Midi(t) => {
|
||||
// Rescale automation keyframe times in this track's graph
|
||||
t.instrument_graph.apply_beats_to_automation_keyframes(from_bpm, to_bpm, fps);
|
||||
|
||||
// Update content durations first so internal_end is correct before sync
|
||||
for instance in &mut t.clip_instances {
|
||||
if let Some(&new_dur) = midi_durations.iter()
|
||||
.find(|(id, _)| *id == instance.clip_id)
|
||||
.map(|(_, d)| d)
|
||||
{
|
||||
let old_internal_dur = instance.internal_duration();
|
||||
instance.internal_end = instance.internal_start + new_dur;
|
||||
// Scale external_duration by the same ratio (works for both looping and non-looping)
|
||||
if old_internal_dur > 1e-12 {
|
||||
instance.external_duration = instance.external_duration * new_dur / old_internal_dur;
|
||||
}
|
||||
}
|
||||
instance.sync_from_seconds(to_bpm, fps);
|
||||
}
|
||||
// Update pool clip durations
|
||||
for &(clip_id, new_dur) in midi_durations {
|
||||
if let Some(clip) = self.midi_clip_pool.get_clip_mut(clip_id) {
|
||||
clip.duration = new_dur;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get oscilloscope data from a node in a track's graph
|
||||
pub fn get_oscilloscope_data(&self, track_id: TrackId, node_id: u32, sample_count: usize) -> Option<(Vec<f32>, Vec<f32>)> {
|
||||
if let Some(TrackNode::Midi(track)) = self.tracks.get(&track_id) {
|
||||
@@ -334,9 +290,9 @@ impl Project {
|
||||
&mut self,
|
||||
track_id: TrackId,
|
||||
events: Vec<MidiEvent>,
|
||||
duration: f64,
|
||||
duration: Beats,
|
||||
name: String,
|
||||
external_start: f64,
|
||||
external_start: Beats,
|
||||
) -> Result<(MidiClipId, MidiClipInstanceId), &'static str> {
|
||||
// Verify track exists and is a MIDI track
|
||||
if !matches!(self.tracks.get(&track_id), Some(TrackNode::Midi(_))) {
|
||||
@@ -369,11 +325,11 @@ impl Project {
|
||||
|
||||
/// Legacy method for backwards compatibility - creates clip and instance from old MidiClip format
|
||||
pub fn add_midi_clip(&mut self, track_id: TrackId, clip: MidiClip) -> Result<MidiClipInstanceId, &'static str> {
|
||||
self.add_midi_clip_at(track_id, clip, 0.0)
|
||||
self.add_midi_clip_at(track_id, clip, Beats::ZERO)
|
||||
}
|
||||
|
||||
/// Add a MIDI clip to the pool and create an instance at the given timeline position
|
||||
pub fn add_midi_clip_at(&mut self, track_id: TrackId, clip: MidiClip, start_time: f64) -> Result<MidiClipInstanceId, &'static str> {
|
||||
pub fn add_midi_clip_at(&mut self, track_id: TrackId, clip: MidiClip, start_time: Beats) -> Result<MidiClipInstanceId, &'static str> {
|
||||
// Add the clip to the pool (it already has events and duration)
|
||||
let duration = clip.duration;
|
||||
let clip_id = clip.id;
|
||||
@@ -417,7 +373,8 @@ impl Project {
|
||||
output: &mut [f32],
|
||||
audio_pool: &AudioClipPool,
|
||||
buffer_pool: &mut BufferPool,
|
||||
playhead_seconds: f64,
|
||||
playhead_seconds: Seconds,
|
||||
tempo_map: &TempoMap,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
live_only: bool,
|
||||
@@ -429,7 +386,7 @@ impl Project {
|
||||
// Create initial render context
|
||||
let ctx = RenderContext {
|
||||
live_only,
|
||||
..RenderContext::new(playhead_seconds, sample_rate, channels, output.len())
|
||||
..RenderContext::new(playhead_seconds, tempo_map, sample_rate, channels, output.len())
|
||||
};
|
||||
|
||||
// Render each root track (index-based to avoid clone)
|
||||
@@ -503,7 +460,7 @@ impl Project {
|
||||
let mut track_buffer = buffer_pool.acquire();
|
||||
track_buffer.resize(output.len(), 0.0);
|
||||
track_buffer.fill(0.0);
|
||||
track.render(&mut track_buffer, audio_pool, ctx.playhead_seconds, ctx.sample_rate, ctx.channels);
|
||||
track.render(&mut track_buffer, audio_pool, ctx);
|
||||
// Accumulate peak level for VU metering (max over meter interval)
|
||||
let buffer_peak = track_buffer.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
|
||||
track.peak_level = track.peak_level.max(buffer_peak);
|
||||
@@ -591,7 +548,7 @@ impl Project {
|
||||
let mut graph_output = buffer_pool.acquire();
|
||||
graph_output.resize(output.len(), 0.0);
|
||||
graph_output.fill(0.0);
|
||||
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_seconds);
|
||||
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_beats());
|
||||
|
||||
for (out_sample, graph_sample) in output.iter_mut().zip(graph_output.iter()) {
|
||||
*out_sample += graph_sample * group.volume;
|
||||
@@ -686,7 +643,7 @@ impl Project {
|
||||
pub fn send_midi_note_on(&mut self, track_id: TrackId, note: u8, velocity: u8) {
|
||||
// Queue the MIDI note-on event to the track's live MIDI queue
|
||||
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
|
||||
let event = MidiEvent::note_on(0.0, 0, note, velocity);
|
||||
let event = MidiEvent::note_on(Beats::ZERO, 0, note, velocity);
|
||||
track.queue_live_midi(event);
|
||||
}
|
||||
}
|
||||
@@ -695,7 +652,7 @@ impl Project {
|
||||
pub fn send_midi_note_off(&mut self, track_id: TrackId, note: u8) {
|
||||
// Queue the MIDI note-off event to the track's live MIDI queue
|
||||
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
|
||||
let event = MidiEvent::note_off(0.0, 0, note, 0);
|
||||
let event = MidiEvent::note_off(Beats::ZERO, 0, note, 0);
|
||||
track.queue_live_midi(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/// Audio recording system for capturing microphone input
|
||||
use crate::audio::{ClipId, MidiClipId, TrackId};
|
||||
use crate::io::{WavWriter, WaveformPeak};
|
||||
use crate::time::{Beats, Seconds};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -18,8 +19,8 @@ pub struct RecordingState {
|
||||
pub sample_rate: u32,
|
||||
/// Number of channels
|
||||
pub channels: u32,
|
||||
/// Timeline start position in seconds
|
||||
pub start_time: f64,
|
||||
/// Timeline start position
|
||||
pub start_time: Beats,
|
||||
/// Total frames recorded
|
||||
pub frames_written: usize,
|
||||
/// Whether recording is currently paused
|
||||
@@ -45,7 +46,7 @@ impl RecordingState {
|
||||
writer: WavWriter,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
start_time: f64,
|
||||
start_time: Beats,
|
||||
_flush_interval_seconds: f64, // No longer used - kept for API compatibility
|
||||
) -> Self {
|
||||
// Calculate frames per waveform peak
|
||||
@@ -130,9 +131,9 @@ impl RecordingState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get current recording duration in seconds
|
||||
pub fn duration(&self) -> f64 {
|
||||
self.frames_written as f64 / self.sample_rate as f64
|
||||
/// Get current recording duration
|
||||
pub fn duration(&self) -> Seconds {
|
||||
Seconds(self.frames_written as f64 / self.sample_rate as f64)
|
||||
}
|
||||
|
||||
/// Finalize the recording and return the temp file path, waveform, and audio data
|
||||
@@ -175,33 +176,23 @@ impl RecordingState {
|
||||
/// Active MIDI note waiting for its noteOff event
|
||||
#[derive(Debug, Clone)]
|
||||
struct ActiveMidiNote {
|
||||
/// MIDI note number (0-127)
|
||||
note: u8,
|
||||
/// Velocity (0-127)
|
||||
velocity: u8,
|
||||
/// Absolute time when note started (seconds)
|
||||
start_time: f64,
|
||||
start_time: Beats,
|
||||
}
|
||||
|
||||
/// State of an active MIDI recording session
|
||||
/// State of an active MIDI recording session.
|
||||
pub struct MidiRecordingState {
|
||||
/// Track being recorded to
|
||||
pub track_id: TrackId,
|
||||
/// MIDI clip ID
|
||||
pub clip_id: MidiClipId,
|
||||
/// Timeline start position in seconds
|
||||
pub start_time: f64,
|
||||
/// Currently active notes (noteOn without matching noteOff)
|
||||
/// Maps note number to ActiveMidiNote
|
||||
pub start_time: Beats,
|
||||
active_notes: HashMap<u8, ActiveMidiNote>,
|
||||
/// Completed notes ready to be added to clip
|
||||
/// Format: (time_offset, note, velocity, duration)
|
||||
pub completed_notes: Vec<(f64, u8, u8, f64)>,
|
||||
/// Completed notes: (time_offset, note, velocity, duration) — all times in beats
|
||||
pub completed_notes: Vec<(Beats, u8, u8, Beats)>,
|
||||
}
|
||||
|
||||
impl MidiRecordingState {
|
||||
/// Create a new MIDI recording state
|
||||
pub fn new(track_id: TrackId, clip_id: MidiClipId, start_time: f64) -> Self {
|
||||
pub fn new(track_id: TrackId, clip_id: MidiClipId, start_time: Beats) -> Self {
|
||||
Self {
|
||||
track_id,
|
||||
clip_id,
|
||||
@@ -211,87 +202,62 @@ impl MidiRecordingState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a MIDI note on event
|
||||
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: f64) {
|
||||
self.active_notes.insert(note, ActiveMidiNote {
|
||||
note,
|
||||
velocity,
|
||||
start_time: absolute_time,
|
||||
});
|
||||
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: Beats) {
|
||||
self.active_notes.insert(note, ActiveMidiNote { note, velocity, start_time: absolute_time });
|
||||
}
|
||||
|
||||
/// Handle a MIDI note off event
|
||||
pub fn note_off(&mut self, note: u8, absolute_time: f64) {
|
||||
// Find the matching noteOn
|
||||
pub fn note_off(&mut self, note: u8, absolute_time: Beats) {
|
||||
if let Some(active_note) = self.active_notes.remove(¬e) {
|
||||
// If the note was fully released before the recording start (e.g. during count-in
|
||||
// pre-roll), discard it — only notes still held at the clip start are kept.
|
||||
if absolute_time <= self.start_time {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clamp note start to clip start: notes held across the recording boundary
|
||||
// are treated as starting at the clip position.
|
||||
let note_start = active_note.start_time.max(self.start_time);
|
||||
let time_offset = note_start - self.start_time;
|
||||
let duration = absolute_time - note_start;
|
||||
|
||||
eprintln!("[MIDI_RECORDING_STATE] Completing note {}: note_start={:.3}s, note_end={:.3}s, recording_start={:.3}s, time_offset={:.3}s, duration={:.3}s",
|
||||
note, note_start, absolute_time, self.start_time, time_offset, duration);
|
||||
|
||||
self.completed_notes.push((
|
||||
time_offset,
|
||||
note_start - self.start_time,
|
||||
active_note.note,
|
||||
active_note.velocity,
|
||||
duration,
|
||||
absolute_time - note_start,
|
||||
));
|
||||
}
|
||||
// If no matching noteOn found, ignore the noteOff
|
||||
}
|
||||
|
||||
/// Get all completed notes
|
||||
pub fn get_notes(&self) -> &[(f64, u8, u8, f64)] {
|
||||
pub fn get_notes(&self) -> &[(Beats, u8, u8, Beats)] {
|
||||
&self.completed_notes
|
||||
}
|
||||
|
||||
/// Get the number of completed notes
|
||||
pub fn note_count(&self) -> usize {
|
||||
self.completed_notes.len()
|
||||
}
|
||||
|
||||
/// Get all completed notes plus currently-held notes with a provisional duration.
|
||||
/// Used for live preview during recording so held notes appear immediately.
|
||||
pub fn get_notes_with_active(&self, current_time: f64) -> Vec<(f64, u8, u8, f64)> {
|
||||
pub fn get_notes_with_active(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
|
||||
let mut notes = self.completed_notes.clone();
|
||||
for active in self.active_notes.values() {
|
||||
let note_start = active.start_time.max(self.start_time);
|
||||
let time_offset = note_start - self.start_time;
|
||||
let provisional_dur = (current_time - note_start).max(0.0);
|
||||
notes.push((time_offset, active.note, active.velocity, provisional_dur));
|
||||
notes.push((
|
||||
note_start - self.start_time,
|
||||
active.note,
|
||||
active.velocity,
|
||||
(current_time - note_start).max(Beats::ZERO),
|
||||
));
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
/// Get the note numbers of all currently held (active) notes
|
||||
pub fn active_note_numbers(&self) -> Vec<u8> {
|
||||
self.active_notes.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Close out all active notes at the given time
|
||||
/// This should be called when stopping recording to end any held notes
|
||||
pub fn close_active_notes(&mut self, end_time: f64) {
|
||||
pub fn close_active_notes(&mut self, end_time: Beats) {
|
||||
let active_notes: Vec<_> = self.active_notes.drain().collect();
|
||||
|
||||
for (_note_num, active_note) in active_notes {
|
||||
let note_start = active_note.start_time.max(self.start_time);
|
||||
let time_offset = note_start - self.start_time;
|
||||
let duration = end_time - note_start;
|
||||
|
||||
self.completed_notes.push((
|
||||
time_offset,
|
||||
note_start - self.start_time,
|
||||
active_note.note,
|
||||
active_note.velocity,
|
||||
duration,
|
||||
end_time - note_start,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ use super::node_graph::AudioGraph;
|
||||
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
|
||||
use super::node_graph::preset::GraphPreset;
|
||||
use super::pool::AudioClipPool;
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::time::{Beats, Seconds};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
@@ -23,10 +25,12 @@ pub type Track = AudioTrack;
|
||||
/// Rendering context that carries timing information through the track hierarchy
|
||||
///
|
||||
/// This allows metatracks to transform time for their children (time stretch, offset, etc.)
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RenderContext {
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RenderContext<'a> {
|
||||
/// Current playhead position in seconds (in transformed time)
|
||||
pub playhead_seconds: f64,
|
||||
pub playhead_seconds: Seconds,
|
||||
/// Tempo map for beat ↔ second conversion
|
||||
pub tempo_map: &'a TempoMap,
|
||||
/// Audio sample rate
|
||||
pub sample_rate: u32,
|
||||
/// Number of channels
|
||||
@@ -41,16 +45,17 @@ pub struct RenderContext {
|
||||
pub live_only: bool,
|
||||
}
|
||||
|
||||
impl RenderContext {
|
||||
/// Create a new render context
|
||||
impl<'a> RenderContext<'a> {
|
||||
pub fn new(
|
||||
playhead_seconds: f64,
|
||||
playhead_seconds: Seconds,
|
||||
tempo_map: &'a TempoMap,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
buffer_size: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
playhead_seconds,
|
||||
tempo_map,
|
||||
sample_rate,
|
||||
channels,
|
||||
buffer_size,
|
||||
@@ -59,15 +64,21 @@ impl RenderContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the duration of the buffer in seconds
|
||||
pub fn buffer_duration(&self) -> f64 {
|
||||
self.buffer_size as f64 / (self.sample_rate as f64 * self.channels as f64)
|
||||
pub fn buffer_duration(&self) -> Seconds {
|
||||
Seconds(self.buffer_size as f64 / (self.sample_rate as f64 * self.channels as f64))
|
||||
}
|
||||
|
||||
/// Get the end time of the buffer
|
||||
pub fn buffer_end(&self) -> f64 {
|
||||
pub fn buffer_end(&self) -> Seconds {
|
||||
self.playhead_seconds + self.buffer_duration()
|
||||
}
|
||||
|
||||
pub fn playhead_beats(&self) -> Beats {
|
||||
self.tempo_map.seconds_to_beats(self.playhead_seconds)
|
||||
}
|
||||
|
||||
pub fn buffer_end_beats(&self) -> Beats {
|
||||
self.tempo_map.seconds_to_beats(self.buffer_end())
|
||||
}
|
||||
}
|
||||
|
||||
/// Node in the track hierarchy - can be an audio track, MIDI track, or a metatrack
|
||||
@@ -170,14 +181,14 @@ pub struct Metatrack {
|
||||
pub time_stretch: f32,
|
||||
/// Pitch shift in semitones (for future implementation)
|
||||
pub pitch_shift: f32,
|
||||
/// Time offset in seconds (shift content forward/backward in time)
|
||||
pub offset: f64,
|
||||
/// Trim start: offset into the metatrack's internal content (seconds)
|
||||
/// Time offset (shift content forward/backward in time)
|
||||
pub offset: Seconds,
|
||||
/// Trim start: offset into the metatrack's internal content
|
||||
/// Children will see time starting from this point
|
||||
pub trim_start: f64,
|
||||
/// Trim end: offset into the metatrack's internal content (seconds)
|
||||
pub trim_start: Seconds,
|
||||
/// Trim end: offset into the metatrack's internal content
|
||||
/// None means no end trim (play until content ends)
|
||||
pub trim_end: Option<f64>,
|
||||
pub trim_end: Option<Seconds>,
|
||||
/// Automation lanes for this metatrack
|
||||
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
|
||||
next_automation_id: AutomationLaneId,
|
||||
@@ -231,8 +242,8 @@ impl Metatrack {
|
||||
solo: false,
|
||||
time_stretch: 1.0,
|
||||
pitch_shift: 0.0,
|
||||
offset: 0.0,
|
||||
trim_start: 0.0,
|
||||
offset: Seconds::ZERO,
|
||||
trim_start: Seconds::ZERO,
|
||||
trim_end: None,
|
||||
automation_lanes: HashMap::new(),
|
||||
next_automation_id: 0,
|
||||
@@ -493,7 +504,7 @@ impl Metatrack {
|
||||
}
|
||||
|
||||
/// Evaluate automation at a specific time and return effective parameters
|
||||
pub fn evaluate_automation_at_time(&self, time: f64) -> (f32, f32, f64) {
|
||||
pub fn evaluate_automation_at_time(&self, time: Beats) -> (f32, f32, Seconds) {
|
||||
let mut volume = self.volume;
|
||||
let mut time_stretch = self.time_stretch;
|
||||
let mut offset = self.offset;
|
||||
@@ -517,7 +528,7 @@ impl Metatrack {
|
||||
}
|
||||
ParameterId::TimeOffset => {
|
||||
if let Some(automated_value) = lane.evaluate(time) {
|
||||
offset = automated_value as f64;
|
||||
offset = Seconds(automated_value as f64);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -561,7 +572,7 @@ impl Metatrack {
|
||||
|
||||
/// Check whether this metatrack should produce audio at the given parent time.
|
||||
/// Returns false if the playhead is outside the trim window.
|
||||
pub fn is_active_at_time(&self, parent_playhead: f64) -> bool {
|
||||
pub fn is_active_at_time(&self, parent_playhead: Seconds) -> bool {
|
||||
let local_time = (parent_playhead - self.offset) * self.time_stretch as f64;
|
||||
if local_time < self.trim_start {
|
||||
return false;
|
||||
@@ -580,7 +591,7 @@ impl Metatrack {
|
||||
/// Time stretch affects how fast content plays: 0.5 = half speed, 2.0 = double speed
|
||||
/// Offset shifts content forward/backward in time
|
||||
/// Trim start offsets into the internal content
|
||||
pub fn transform_context(&self, ctx: RenderContext) -> RenderContext {
|
||||
pub fn transform_context<'a>(&self, ctx: RenderContext<'a>) -> RenderContext<'a> {
|
||||
let mut transformed = ctx;
|
||||
|
||||
// Apply transformations in order:
|
||||
@@ -596,7 +607,7 @@ impl Metatrack {
|
||||
let stretched = adjusted_playhead * self.time_stretch as f64;
|
||||
|
||||
// 3. Add trim_start so children see time starting from the trim point
|
||||
// If trim_start=2.0, children start seeing time 2.0 when parent reaches offset
|
||||
// If trim_start=2.0s, children start seeing time 2.0s when parent reaches offset
|
||||
transformed.playhead_seconds = stretched + self.trim_start;
|
||||
|
||||
// Accumulate time stretch for nested metatracks
|
||||
@@ -772,13 +783,13 @@ impl MidiTrack {
|
||||
// Send note-off for all 128 possible MIDI notes to silence the instrument
|
||||
let mut note_offs = Vec::new();
|
||||
for note in 0..128 {
|
||||
note_offs.push(MidiEvent::note_off(0.0, 0, note, 0));
|
||||
note_offs.push(MidiEvent::note_off(Beats::ZERO, 0, note, 0));
|
||||
}
|
||||
|
||||
// Create a silent buffer to process the note-offs
|
||||
let buffer_size = 512 * 2; // stereo
|
||||
let mut silent_buffer = vec![0.0f32; buffer_size];
|
||||
self.instrument_graph.process(&mut silent_buffer, ¬e_offs, 0.0);
|
||||
self.instrument_graph.process(&mut silent_buffer, ¬e_offs, Beats::ZERO);
|
||||
}
|
||||
|
||||
/// Queue a live MIDI event (from virtual keyboard or MIDI controller)
|
||||
@@ -805,17 +816,17 @@ impl MidiTrack {
|
||||
let mut midi_events = Vec::new();
|
||||
|
||||
if !ctx.live_only {
|
||||
let buffer_duration_seconds = output.len() as f64 / (ctx.sample_rate as f64 * ctx.channels as f64);
|
||||
let buffer_end_seconds = ctx.playhead_seconds + buffer_duration_seconds;
|
||||
let playhead_beats = ctx.playhead_beats();
|
||||
let buffer_end_beats = ctx.buffer_end_beats();
|
||||
|
||||
// Collect MIDI events from all clip instances that overlap with current time range
|
||||
// Collect MIDI events from all clip instances that overlap with current beat range
|
||||
let mut currently_active = HashSet::new();
|
||||
for instance in &self.clip_instances {
|
||||
if instance.overlaps_range(ctx.playhead_seconds, buffer_end_seconds) {
|
||||
if instance.overlaps_range(playhead_beats, buffer_end_beats) {
|
||||
currently_active.insert(instance.id);
|
||||
}
|
||||
if let Some(clip) = midi_pool.get_clip(instance.clip_id) {
|
||||
let events = instance.get_events_in_range(clip, ctx.playhead_seconds, buffer_end_seconds);
|
||||
let events = instance.get_events_in_range(clip, playhead_beats, buffer_end_beats);
|
||||
midi_events.extend(events);
|
||||
}
|
||||
}
|
||||
@@ -824,7 +835,7 @@ impl MidiTrack {
|
||||
for prev_id in &self.prev_active_instances {
|
||||
if !currently_active.contains(prev_id) {
|
||||
for note in 0..128u8 {
|
||||
midi_events.push(MidiEvent::note_off(ctx.playhead_seconds, 0, note, 0));
|
||||
midi_events.push(MidiEvent::note_off(playhead_beats, 0, note, 0));
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -836,10 +847,10 @@ impl MidiTrack {
|
||||
midi_events.extend(self.live_midi_queue.drain(..));
|
||||
|
||||
// Generate audio using instrument graph
|
||||
self.instrument_graph.process(output, &midi_events, ctx.playhead_seconds);
|
||||
self.instrument_graph.process(output, &midi_events, ctx.playhead_beats());
|
||||
|
||||
// Evaluate and apply automation (skip automation in live_only mode — no playhead to evaluate at)
|
||||
let effective_volume = if ctx.live_only { self.volume } else { self.evaluate_automation_at_time(ctx.playhead_seconds) };
|
||||
let effective_volume = if ctx.live_only { self.volume } else { self.evaluate_automation_at_time(ctx.playhead_beats()) };
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
@@ -848,7 +859,7 @@ impl MidiTrack {
|
||||
}
|
||||
|
||||
/// Evaluate automation at a specific time and return the effective volume
|
||||
fn evaluate_automation_at_time(&self, time: f64) -> f32 {
|
||||
fn evaluate_automation_at_time(&self, time: Beats) -> f32 {
|
||||
let mut volume = self.volume;
|
||||
|
||||
// Check for volume automation
|
||||
@@ -1081,12 +1092,9 @@ impl AudioTrack {
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
pool: &AudioClipPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
ctx: RenderContext<'_>,
|
||||
) -> usize {
|
||||
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
|
||||
let buffer_end = ctx.buffer_end();
|
||||
|
||||
// Split borrow: take clip_render_buffer out to avoid borrow conflict with &self methods
|
||||
let mut clip_buffer = std::mem::take(&mut self.clip_render_buffer);
|
||||
@@ -1096,16 +1104,8 @@ impl AudioTrack {
|
||||
|
||||
// Render all active clip instances into the buffer
|
||||
for clip in &self.clips {
|
||||
// Check if clip overlaps with current buffer time range
|
||||
if clip.external_start < buffer_end_seconds && clip.external_end() > playhead_seconds {
|
||||
rendered += self.render_clip(
|
||||
clip,
|
||||
&mut clip_buffer,
|
||||
pool,
|
||||
playhead_seconds,
|
||||
sample_rate,
|
||||
channels,
|
||||
);
|
||||
if clip.external_start_secs(ctx.tempo_map) < buffer_end && clip.external_end_secs(ctx.tempo_map) > ctx.playhead_seconds {
|
||||
rendered += self.render_clip(clip, &mut clip_buffer, pool, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1123,13 +1123,13 @@ impl AudioTrack {
|
||||
}
|
||||
|
||||
// Process through the effects graph (this will write to output buffer)
|
||||
self.effects_graph.process(output, &[], playhead_seconds);
|
||||
self.effects_graph.process(output, &[], ctx.playhead_beats());
|
||||
|
||||
// Put the buffer back for reuse next callback
|
||||
self.clip_render_buffer = clip_buffer;
|
||||
|
||||
// Evaluate and apply automation
|
||||
let effective_volume = self.evaluate_automation_at_time(playhead_seconds);
|
||||
let effective_volume = self.evaluate_automation_at_time(ctx.playhead_beats());
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
@@ -1140,7 +1140,7 @@ impl AudioTrack {
|
||||
}
|
||||
|
||||
/// Evaluate automation at a specific time and return the effective volume
|
||||
fn evaluate_automation_at_time(&self, time: f64) -> f32 {
|
||||
fn evaluate_automation_at_time(&self, time: Beats) -> f32 {
|
||||
let mut volume = self.volume;
|
||||
|
||||
// Check for volume automation
|
||||
@@ -1169,49 +1169,40 @@ impl AudioTrack {
|
||||
clip: &AudioClipInstance,
|
||||
output: &mut [f32],
|
||||
pool: &AudioClipPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
ctx: RenderContext<'_>,
|
||||
) -> usize {
|
||||
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
|
||||
let playhead = ctx.playhead_seconds;
|
||||
let buffer_end = ctx.buffer_end();
|
||||
let tempo_map = ctx.tempo_map;
|
||||
let sample_rate = ctx.sample_rate;
|
||||
let channels = ctx.channels;
|
||||
|
||||
// Determine the time range we need to render (intersection of buffer and clip external bounds)
|
||||
let render_start_seconds = playhead_seconds.max(clip.external_start);
|
||||
let render_end_seconds = buffer_end_seconds.min(clip.external_end());
|
||||
let render_start = playhead.max(clip.external_start_secs(tempo_map));
|
||||
let render_end = buffer_end.min(clip.external_end_secs(tempo_map));
|
||||
|
||||
// If no overlap, return early
|
||||
if render_start_seconds >= render_end_seconds {
|
||||
if render_start >= render_end {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let internal_duration = clip.internal_duration();
|
||||
if internal_duration <= 0.0 {
|
||||
if internal_duration <= Seconds::ZERO {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Calculate combined gain
|
||||
let combined_gain = clip.gain;
|
||||
|
||||
let mut total_rendered = 0;
|
||||
|
||||
// Process the render range sample by sample (or in chunks for efficiency)
|
||||
// For looping clips, we need to handle wrap-around at the loop boundary
|
||||
let samples_per_second = sample_rate as f64 * channels as f64;
|
||||
|
||||
// For now, render in a simpler way - iterate through the timeline range
|
||||
// and use get_content_position for each sample position
|
||||
let output_start_offset = ((render_start_seconds - playhead_seconds) * samples_per_second + 0.5) as usize;
|
||||
let output_end_offset = ((render_end_seconds - playhead_seconds) * samples_per_second + 0.5) as usize;
|
||||
let output_start_offset = ((render_start - playhead).0 * samples_per_second + 0.5) as usize;
|
||||
let output_end_offset = ((render_end - playhead).0 * samples_per_second + 0.5) as usize;
|
||||
|
||||
if output_end_offset > output.len() || output_start_offset > output.len() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If not looping, we can render in one chunk (more efficient)
|
||||
if !clip.is_looping() {
|
||||
// Simple case: no looping
|
||||
let content_start = clip.get_content_position(render_start_seconds).unwrap_or(clip.internal_start);
|
||||
if !clip.is_looping(tempo_map) {
|
||||
let content_start = clip.get_content_position(render_start, tempo_map).unwrap_or(clip.internal_start);
|
||||
let output_len = output.len();
|
||||
let output_slice = &mut output[output_start_offset..output_end_offset.min(output_len)];
|
||||
|
||||
@@ -1225,23 +1216,20 @@ impl AudioTrack {
|
||||
clip.read_ahead.as_deref(),
|
||||
);
|
||||
} else {
|
||||
// Looping case: need to handle wrap-around at loop boundaries
|
||||
// Render in segments, one per loop iteration
|
||||
let mut timeline_pos = render_start_seconds;
|
||||
// Looping case: handle wrap-around at loop boundaries
|
||||
let mut timeline_pos = render_start;
|
||||
let mut output_offset = output_start_offset;
|
||||
|
||||
while timeline_pos < render_end_seconds && output_offset < output.len() {
|
||||
// Calculate position within the loop
|
||||
let relative_pos = timeline_pos - clip.external_start;
|
||||
let loop_offset = relative_pos % internal_duration;
|
||||
let content_pos = clip.internal_start + loop_offset;
|
||||
while timeline_pos < render_end && output_offset < output.len() {
|
||||
let relative_pos = timeline_pos - clip.external_start_secs(tempo_map);
|
||||
let loop_offset = relative_pos.0 % internal_duration.0;
|
||||
let content_pos = clip.internal_start + Seconds(loop_offset);
|
||||
|
||||
// Calculate how much we can render before hitting the loop boundary
|
||||
let time_to_loop_end = internal_duration - loop_offset;
|
||||
let time_to_render_end = render_end_seconds - timeline_pos;
|
||||
let time_to_loop_end = Seconds(internal_duration.0 - loop_offset);
|
||||
let time_to_render_end = render_end - timeline_pos;
|
||||
let chunk_duration = time_to_loop_end.min(time_to_render_end);
|
||||
|
||||
let chunk_samples = (chunk_duration * samples_per_second) as usize;
|
||||
let chunk_samples = (chunk_duration.0 * samples_per_second) as usize;
|
||||
let chunk_samples = chunk_samples.min(output.len() - output_offset);
|
||||
|
||||
if chunk_samples == 0 {
|
||||
@@ -1262,7 +1250,7 @@ impl AudioTrack {
|
||||
|
||||
total_rendered += rendered;
|
||||
output_offset += chunk_samples;
|
||||
timeline_pos += chunk_duration;
|
||||
timeline_pos = timeline_pos + chunk_duration;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::audio::midi::MidiEvent;
|
||||
use crate::audio::buffer_pool::BufferPoolStats;
|
||||
use crate::audio::node_graph::nodes::LoopMode;
|
||||
use crate::io::WaveformPeak;
|
||||
use crate::time::{Beats, Seconds};
|
||||
|
||||
/// Commands sent from UI/control thread to audio thread
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -113,7 +114,7 @@ pub enum Command {
|
||||
|
||||
// Recording commands
|
||||
/// Start recording on a track (track_id, start_time)
|
||||
StartRecording(TrackId, f64),
|
||||
StartRecording(TrackId, Beats),
|
||||
/// Stop the current recording
|
||||
StopRecording,
|
||||
/// Pause the current recording
|
||||
@@ -123,7 +124,7 @@ pub enum Command {
|
||||
|
||||
// MIDI Recording commands
|
||||
/// Start MIDI recording on a track (track_id, clip_id, start_time)
|
||||
StartMidiRecording(TrackId, MidiClipId, f64),
|
||||
StartMidiRecording(TrackId, MidiClipId, Beats),
|
||||
/// Stop the current MIDI recording
|
||||
StopMidiRecording,
|
||||
|
||||
@@ -144,11 +145,6 @@ pub enum Command {
|
||||
SetMetronomeEnabled(bool),
|
||||
/// Set project tempo and time signature (bpm, (numerator, denominator))
|
||||
SetTempo(f32, (u32, u32)),
|
||||
/// After a BPM change: update MIDI clip durations, sync clip beats/frames, and rescale
|
||||
/// automation keyframe times to preserve beat positions.
|
||||
/// (from_bpm, to_bpm, fps, midi_durations: Vec<(clip_id, new_duration_seconds)>)
|
||||
ApplyBpmChange(f64, f64, f64, Vec<(MidiClipId, f64)>),
|
||||
|
||||
// Node graph commands
|
||||
/// Add a node to a track's instrument graph (track_id, node_type, position_x, position_y)
|
||||
GraphAddNode(TrackId, String, f32, f32),
|
||||
@@ -290,7 +286,7 @@ pub enum AudioEvent {
|
||||
/// Recording started (track_id, clip_id, sample_rate, channels)
|
||||
RecordingStarted(TrackId, ClipId, u32, u32),
|
||||
/// Recording progress update (clip_id, current_duration)
|
||||
RecordingProgress(ClipId, f64),
|
||||
RecordingProgress(ClipId, Seconds),
|
||||
/// Recording stopped (clip_id, pool_index, waveform)
|
||||
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
|
||||
/// Recording error (error_message)
|
||||
@@ -298,8 +294,8 @@ pub enum AudioEvent {
|
||||
/// MIDI recording stopped (track_id, clip_id, note_count)
|
||||
MidiRecordingStopped(TrackId, MidiClipId, usize),
|
||||
/// MIDI recording progress (track_id, clip_id, duration, notes)
|
||||
/// Notes format: (start_time, note, velocity, duration)
|
||||
MidiRecordingProgress(TrackId, MidiClipId, f64, Vec<(f64, u8, u8, f64)>),
|
||||
/// Notes format: (start_time, note, velocity, duration) — all times in beats
|
||||
MidiRecordingProgress(TrackId, MidiClipId, Beats, Vec<(Beats, u8, u8, Beats)>),
|
||||
/// Project has been reset
|
||||
ProjectReset,
|
||||
/// MIDI note started playing (note, velocity)
|
||||
|
||||
+32
-127
@@ -1,164 +1,69 @@
|
||||
use crate::audio::midi::{MidiClip, MidiClipId, MidiEvent};
|
||||
use crate::time::Beats;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
/// Load a MIDI file and convert it to a MidiClip
|
||||
/// Load a MIDI file and convert it to a MidiClip.
|
||||
///
|
||||
/// Event timestamps are stored as beat positions: `tick / ticks_per_beat`.
|
||||
/// Tempo events in the MIDI file only affect wall-clock playback speed — not the
|
||||
/// beat grid — so they are ignored here.
|
||||
pub fn load_midi_file<P: AsRef<Path>>(
|
||||
path: P,
|
||||
clip_id: MidiClipId,
|
||||
_sample_rate: u32,
|
||||
) -> Result<MidiClip, String> {
|
||||
// Read the MIDI file
|
||||
let data = fs::read(path.as_ref()).map_err(|e| format!("Failed to read MIDI file: {}", e))?;
|
||||
|
||||
// Parse with midly
|
||||
let smf = midly::Smf::parse(&data).map_err(|e| format!("Failed to parse MIDI file: {}", e))?;
|
||||
|
||||
// Convert timing to ticks per second
|
||||
let ticks_per_beat = match smf.header.timing {
|
||||
midly::Timing::Metrical(tpb) => tpb.as_int() as f64,
|
||||
midly::Timing::Timecode(fps, subframe) => {
|
||||
// For timecode, calculate equivalent ticks per second
|
||||
// Timecode-based MIDI: treat subframes as ticks per beat
|
||||
(fps.as_f32() * subframe as f32) as f64
|
||||
}
|
||||
};
|
||||
|
||||
// First pass: collect all events with their tick positions and tempo changes
|
||||
#[derive(Debug)]
|
||||
enum RawEvent {
|
||||
Midi {
|
||||
tick: u64,
|
||||
channel: u8,
|
||||
message: midly::MidiMessage,
|
||||
},
|
||||
Tempo {
|
||||
tick: u64,
|
||||
microseconds_per_beat: f64,
|
||||
},
|
||||
}
|
||||
let mut events = Vec::new();
|
||||
let mut max_tick = 0u64;
|
||||
|
||||
let mut raw_events = Vec::new();
|
||||
let mut max_time_ticks = 0u64;
|
||||
|
||||
// Collect all events from all tracks with their absolute tick positions
|
||||
for track in &smf.tracks {
|
||||
let mut current_tick = 0u64;
|
||||
|
||||
for event in track {
|
||||
current_tick += event.delta.as_int() as u64;
|
||||
max_time_ticks = max_time_ticks.max(current_tick);
|
||||
max_tick = max_tick.max(current_tick);
|
||||
|
||||
let timestamp = Beats(current_tick as f64 / ticks_per_beat);
|
||||
|
||||
match event.kind {
|
||||
midly::TrackEventKind::Midi { channel, message } => {
|
||||
raw_events.push(RawEvent::Midi {
|
||||
tick: current_tick,
|
||||
channel: channel.as_int(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
midly::TrackEventKind::Meta(midly::MetaMessage::Tempo(tempo)) => {
|
||||
raw_events.push(RawEvent::Tempo {
|
||||
tick: current_tick,
|
||||
microseconds_per_beat: tempo.as_int() as f64,
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
// Ignore other meta events
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort all events by tick position
|
||||
raw_events.sort_by_key(|e| match e {
|
||||
RawEvent::Midi { tick, .. } => *tick,
|
||||
RawEvent::Tempo { tick, .. } => *tick,
|
||||
});
|
||||
|
||||
// Second pass: convert ticks to timestamps with proper tempo tracking
|
||||
let mut events = Vec::new();
|
||||
let mut microseconds_per_beat = 500000.0; // Default: 120 BPM
|
||||
let mut last_tick = 0u64;
|
||||
let mut accumulated_time = 0.0; // Time in seconds
|
||||
|
||||
for raw_event in raw_events {
|
||||
match raw_event {
|
||||
RawEvent::Tempo {
|
||||
tick,
|
||||
microseconds_per_beat: new_tempo,
|
||||
} => {
|
||||
// Update accumulated time up to this tempo change
|
||||
let delta_ticks = tick - last_tick;
|
||||
let delta_time = (delta_ticks as f64 / ticks_per_beat)
|
||||
* (microseconds_per_beat / 1_000_000.0);
|
||||
accumulated_time += delta_time;
|
||||
last_tick = tick;
|
||||
|
||||
// Update tempo for future events
|
||||
microseconds_per_beat = new_tempo;
|
||||
}
|
||||
RawEvent::Midi {
|
||||
tick,
|
||||
channel,
|
||||
message,
|
||||
} => {
|
||||
// Calculate time for this event
|
||||
let delta_ticks = tick - last_tick;
|
||||
let delta_time = (delta_ticks as f64 / ticks_per_beat)
|
||||
* (microseconds_per_beat / 1_000_000.0);
|
||||
accumulated_time += delta_time;
|
||||
last_tick = tick;
|
||||
|
||||
// Store timestamp in seconds (sample-rate independent)
|
||||
let timestamp = accumulated_time;
|
||||
|
||||
match message {
|
||||
midly::MidiMessage::NoteOn { key, vel } => {
|
||||
let velocity = vel.as_int();
|
||||
if velocity > 0 {
|
||||
events.push(MidiEvent::note_on(
|
||||
timestamp,
|
||||
channel,
|
||||
key.as_int(),
|
||||
velocity,
|
||||
));
|
||||
} else {
|
||||
events.push(MidiEvent::note_off(timestamp, channel, key.as_int(), 64));
|
||||
let ch = channel.as_int();
|
||||
match message {
|
||||
midly::MidiMessage::NoteOn { key, vel } => {
|
||||
let velocity = vel.as_int();
|
||||
if velocity > 0 {
|
||||
events.push(MidiEvent::note_on(timestamp, ch, key.as_int(), velocity));
|
||||
} else {
|
||||
events.push(MidiEvent::note_off(timestamp, ch, key.as_int(), 64));
|
||||
}
|
||||
}
|
||||
}
|
||||
midly::MidiMessage::NoteOff { key, vel } => {
|
||||
events.push(MidiEvent::note_off(
|
||||
timestamp,
|
||||
channel,
|
||||
key.as_int(),
|
||||
vel.as_int(),
|
||||
));
|
||||
}
|
||||
midly::MidiMessage::Controller { controller, value } => {
|
||||
let status = 0xB0 | channel;
|
||||
events.push(MidiEvent::new(
|
||||
timestamp,
|
||||
status,
|
||||
controller.as_int(),
|
||||
value.as_int(),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
// Ignore other MIDI messages
|
||||
midly::MidiMessage::NoteOff { key, vel } => {
|
||||
events.push(MidiEvent::note_off(timestamp, ch, key.as_int(), vel.as_int()));
|
||||
}
|
||||
midly::MidiMessage::Controller { controller, value } => {
|
||||
let status = 0xB0 | ch;
|
||||
events.push(MidiEvent::new(timestamp, status, controller.as_int(), value.as_int()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {} // Tempo and other meta events don't affect beat positions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate final clip duration
|
||||
let final_delta_ticks = max_time_ticks - last_tick;
|
||||
let final_delta_time =
|
||||
(final_delta_ticks as f64 / ticks_per_beat) * (microseconds_per_beat / 1_000_000.0);
|
||||
let duration_seconds = accumulated_time + final_delta_time;
|
||||
|
||||
// Create the MIDI clip (content only, positioning happens when creating instance)
|
||||
let clip = MidiClip::new(clip_id, events, duration_seconds, "Imported MIDI".to_string());
|
||||
|
||||
let duration = Beats(max_tick as f64 / ticks_per_beat);
|
||||
let clip = MidiClip::new(clip_id, events, duration, "Imported MIDI".to_string());
|
||||
Ok(clip)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
pub mod audio;
|
||||
pub mod command;
|
||||
pub mod time;
|
||||
pub mod tempo_map;
|
||||
pub mod dsp;
|
||||
pub mod effects;
|
||||
pub mod io;
|
||||
@@ -18,6 +20,8 @@ pub use audio::{
|
||||
TrackNode,
|
||||
};
|
||||
pub use audio::node_graph::{GraphPreset, AudioGraph, PresetMetadata, SerializedConnection, SerializedNode};
|
||||
pub use time::{Beats, Seconds};
|
||||
pub use tempo_map::{TempoEntry, TempoMap, beats_to_seconds_stack, seconds_to_beats_stack};
|
||||
pub use command::{AudioEvent, Command, OscilloscopeData};
|
||||
pub use command::types::AutomationKeyframeData;
|
||||
pub use io::{load_midi_file, AudioFile, WaveformChunk, WaveformChunkKey, WaveformPeak, WavWriter};
|
||||
@@ -90,7 +94,7 @@ impl AudioSystem {
|
||||
// Create input ringbuffer for recording (large buffer for audio samples)
|
||||
// Buffer size: 10 seconds of audio at 48kHz stereo = 48000 * 2 * 10 = 960000 samples
|
||||
let input_buffer_size = (sample_rate * channels * 10) as usize;
|
||||
let (mut input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
let (input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
|
||||
// Create mirror ringbuffer for streaming recorded audio to UI (live waveform)
|
||||
let (mirror_tx, mirror_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! TempoMap — beats ↔ seconds conversion with variable tempo support.
|
||||
//!
|
||||
//! Positions are stored in **beats** throughout the project; `TempoMap` converts
|
||||
//! between beats and seconds at render / scheduling time.
|
||||
//!
|
||||
//! # Format
|
||||
//! `entries` is a sorted `Vec<TempoEntry>` where each entry marks where a new
|
||||
//! constant BPM segment begins. Step interpolation is used: BPM is constant
|
||||
//! from `entry.beat` until the next entry. The first entry must always have
|
||||
//! `beat == 0.0`.
|
||||
//!
|
||||
//! # Sequential-access optimisation
|
||||
//! An `AtomicUsize` caches the index of the last segment visited by
|
||||
//! `beats_to_seconds`. When calls are in ascending order (the common case when
|
||||
//! walking events in order) the scan starts from the cached index instead of
|
||||
//! the beginning, giving amortised O(1) behaviour.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use crate::time::{Beats, Seconds};
|
||||
|
||||
/// A single tempo segment: from `beat` onwards the tempo is `bpm`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TempoEntry {
|
||||
/// Start of this tempo segment in beats (quarter-note beats).
|
||||
pub beat: f64,
|
||||
/// Tempo for this segment in beats per minute.
|
||||
pub bpm: f64,
|
||||
/// Cumulative seconds elapsed at the start of this segment.
|
||||
/// **Derived** — not serialised; call [`TempoMap::rebuild_seconds`] after any
|
||||
/// mutation or after deserialization.
|
||||
#[serde(skip, default)]
|
||||
pub seconds: f64,
|
||||
}
|
||||
|
||||
/// A piecewise-constant tempo map used to convert between beats and seconds.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct TempoMap {
|
||||
/// Sorted list of tempo segments. Must always have at least one entry at beat 0.
|
||||
pub entries: Vec<TempoEntry>,
|
||||
/// Sequential-access cache: index of the last segment used by `beats_to_seconds`.
|
||||
#[serde(skip, default)]
|
||||
last_index: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Clone for TempoMap {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
entries: self.entries.clone(),
|
||||
last_index: AtomicUsize::new(self.last_index.load(Ordering::Relaxed)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TempoMap {
|
||||
fn default() -> Self {
|
||||
Self::constant(120.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl TempoMap {
|
||||
/// Create a constant-tempo map.
|
||||
pub fn constant(bpm: f64) -> Self {
|
||||
Self {
|
||||
entries: vec![TempoEntry { beat: 0.0, bpm, seconds: 0.0 }],
|
||||
last_index: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the `seconds` field on every entry from scratch.
|
||||
/// **Must be called** after any mutation (add/remove/reorder entry) and
|
||||
/// after deserialization.
|
||||
pub fn rebuild_seconds(&mut self) {
|
||||
let mut cumulative = 0.0_f64;
|
||||
for i in 0..self.entries.len() {
|
||||
self.entries[i].seconds = cumulative;
|
||||
if i + 1 < self.entries.len() {
|
||||
let span_beats = self.entries[i + 1].beat - self.entries[i].beat;
|
||||
cumulative += span_beats * 60.0 / self.entries[i].bpm;
|
||||
}
|
||||
}
|
||||
self.last_index.store(0, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Return the BPM active at `beat`.
|
||||
pub fn bpm_at(&self, beat: Beats) -> f64 {
|
||||
let idx = self.entries.partition_point(|e| e.beat <= beat.0).saturating_sub(1);
|
||||
self.entries[idx.max(0)].bpm
|
||||
}
|
||||
|
||||
/// Convert beats to seconds using the tempo map.
|
||||
///
|
||||
/// Uses the sequential cache: if `beat` is at or after the last cached
|
||||
/// segment, the scan starts there instead of from the beginning.
|
||||
pub fn beats_to_seconds(&self, beat: Beats) -> Seconds {
|
||||
if beat.0 <= 0.0 {
|
||||
return Seconds::ZERO;
|
||||
}
|
||||
let n = self.entries.len();
|
||||
let cached = self.last_index.load(Ordering::Relaxed).min(n.saturating_sub(1));
|
||||
let start = if beat.0 >= self.entries[cached].beat { cached } else { 0 };
|
||||
|
||||
let mut idx = start;
|
||||
while idx + 1 < n && self.entries[idx + 1].beat <= beat.0 {
|
||||
idx += 1;
|
||||
}
|
||||
self.last_index.store(idx, Ordering::Relaxed);
|
||||
|
||||
let entry = &self.entries[idx];
|
||||
Seconds(entry.seconds + (beat.0 - entry.beat) * 60.0 / entry.bpm)
|
||||
}
|
||||
|
||||
/// Convert seconds to beats using binary search on the cached `seconds` offsets.
|
||||
pub fn seconds_to_beats(&self, seconds: Seconds) -> Beats {
|
||||
if seconds.0 <= 0.0 {
|
||||
return Beats::ZERO;
|
||||
}
|
||||
let n = self.entries.len();
|
||||
let idx = self.entries.partition_point(|e| e.seconds <= seconds.0).saturating_sub(1);
|
||||
let idx = idx.min(n - 1);
|
||||
let entry = &self.entries[idx];
|
||||
Beats(entry.beat + (seconds.0 - entry.seconds) * entry.bpm / 60.0)
|
||||
}
|
||||
|
||||
/// Global BPM — the BPM of the first entry (at beat 0).
|
||||
pub fn global_bpm(&self) -> f64 {
|
||||
self.entries[0].bpm
|
||||
}
|
||||
|
||||
/// Set the global BPM (first entry). Rebuilds seconds.
|
||||
pub fn set_global_bpm(&mut self, bpm: f64) {
|
||||
self.entries[0].bpm = bpm;
|
||||
self.rebuild_seconds();
|
||||
}
|
||||
|
||||
/// Convert local beats to parent time units (raw `f64`).
|
||||
///
|
||||
/// At the root level the result is absolute seconds. Inside a nested
|
||||
/// group the result is the *parent group's* beats — the caller is
|
||||
/// responsible for interpreting the units correctly.
|
||||
///
|
||||
/// This is the same arithmetic as `beats_to_seconds` but without the
|
||||
/// `Seconds` newtype so it can be composed across multiple levels.
|
||||
pub fn transform(&self, beat: f64) -> f64 {
|
||||
if beat <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let n = self.entries.len();
|
||||
let cached = self.last_index.load(Ordering::Relaxed).min(n.saturating_sub(1));
|
||||
let start = if beat >= self.entries[cached].beat { cached } else { 0 };
|
||||
let mut idx = start;
|
||||
while idx + 1 < n && self.entries[idx + 1].beat <= beat {
|
||||
idx += 1;
|
||||
}
|
||||
self.last_index.store(idx, Ordering::Relaxed);
|
||||
let entry = &self.entries[idx];
|
||||
entry.seconds + (beat - entry.beat) * 60.0 / entry.bpm
|
||||
}
|
||||
|
||||
/// Inverse of [`transform`]: convert parent time units back to local beats.
|
||||
pub fn inverse_transform(&self, parent_time: f64) -> f64 {
|
||||
if parent_time <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let n = self.entries.len();
|
||||
let idx = self.entries.partition_point(|e| e.seconds <= parent_time).saturating_sub(1);
|
||||
let idx = idx.min(n - 1);
|
||||
let entry = &self.entries[idx];
|
||||
entry.beat + (parent_time - entry.seconds) * entry.bpm / 60.0
|
||||
}
|
||||
|
||||
/// Build a `TempoMap` from a list of `(beat, bpm)` keyframes.
|
||||
/// Always inserts a beat-0 entry using the first keyframe's BPM (or 120.0 if empty).
|
||||
pub fn from_keyframes(keyframes: &[(f64, f64)]) -> Self {
|
||||
if keyframes.is_empty() {
|
||||
return Self::constant(120.0);
|
||||
}
|
||||
let mut entries: Vec<TempoEntry> = keyframes
|
||||
.iter()
|
||||
.map(|&(beat, bpm)| TempoEntry { beat, bpm, seconds: 0.0 })
|
||||
.collect();
|
||||
entries.sort_by(|a, b| a.beat.partial_cmp(&b.beat).unwrap());
|
||||
if entries[0].beat > 0.0 {
|
||||
entries.insert(0, TempoEntry { beat: 0.0, bpm: entries[0].bpm, seconds: 0.0 });
|
||||
}
|
||||
let mut map = Self { entries, last_index: AtomicUsize::new(0) };
|
||||
map.rebuild_seconds();
|
||||
map
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert local beats through a stack of tempo maps to absolute seconds.
|
||||
///
|
||||
/// `stack[0]` is the outermost map (root/master); `stack[last]` is the
|
||||
/// innermost (deepest group). Conversion applies maps from innermost to
|
||||
/// outermost — each map's output is the input to the next outer map.
|
||||
///
|
||||
/// ```text
|
||||
/// clip_beats → [stack[last]] → … → [stack[0]] → absolute seconds
|
||||
/// ```
|
||||
pub fn beats_to_seconds_stack(beat: f64, stack: &[&TempoMap]) -> f64 {
|
||||
let mut t = beat;
|
||||
for tm in stack.iter().rev() {
|
||||
t = tm.transform(t);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Inverse of [`beats_to_seconds_stack`]: absolute seconds → local beats.
|
||||
pub fn seconds_to_beats_stack(seconds: f64, stack: &[&TempoMap]) -> f64 {
|
||||
let mut t = seconds;
|
||||
for tm in stack.iter() {
|
||||
t = tm.inverse_transform(t);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constant_bpm_round_trip() {
|
||||
let m = TempoMap::constant(120.0);
|
||||
assert!((m.beats_to_seconds(Beats(2.0)).0 - 1.0).abs() < 1e-9);
|
||||
assert!((m.seconds_to_beats(Seconds(1.0)).0 - 2.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_tempo() {
|
||||
let m = TempoMap::from_keyframes(&[(0.0, 120.0), (4.0, 60.0)]);
|
||||
assert!((m.beats_to_seconds(Beats(4.0)).0 - 2.0).abs() < 1e-9);
|
||||
assert!((m.beats_to_seconds(Beats(5.0)).0 - 3.0).abs() < 1e-9);
|
||||
assert!((m.seconds_to_beats(Seconds(3.0)).0 - 5.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_composition() {
|
||||
// Root: 120 BPM (1 beat = 0.5s)
|
||||
// Group: 60 BPM (1 local beat = 1 "parent beat" worth of time)
|
||||
// Clip at local beat 2.0 → 2 parent beats → 1.0s absolute
|
||||
let root = TempoMap::constant(120.0);
|
||||
let group = TempoMap::constant(60.0);
|
||||
let stack: Vec<&TempoMap> = vec![&root, &group];
|
||||
let secs = beats_to_seconds_stack(2.0, &stack);
|
||||
// group.transform(2.0) = 2.0*60/60 = 2.0 parent_beats
|
||||
// root.transform(2.0) = 2.0*60/120 = 1.0s
|
||||
assert!((secs - 1.0).abs() < 1e-9, "got {secs}");
|
||||
|
||||
let beats = seconds_to_beats_stack(1.0, &stack);
|
||||
assert!((beats - 2.0).abs() < 1e-9, "got {beats}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequential_cache() {
|
||||
let m = TempoMap::constant(120.0);
|
||||
for i in 0..10 {
|
||||
let secs = m.beats_to_seconds(Beats(i as f64));
|
||||
assert!((secs.0 - i as f64 * 0.5).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/// Strongly-typed time units to prevent accidental beats/seconds confusion.
|
||||
///
|
||||
/// Convert between the two using `TempoMap::beats_to_seconds` / `TempoMap::seconds_to_beats`.
|
||||
/// All internal scheduling and clip positions use `Beats`; only audio rendering
|
||||
/// (sample offsets, file seeks) uses `Seconds`.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::{Add, AddAssign, Div, Mul, Neg, Rem, Sub, SubAssign};
|
||||
|
||||
/// A time position or duration expressed in **beats** (quarter-note beats).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Beats(pub f64);
|
||||
|
||||
/// A time position or duration expressed in **seconds**.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Seconds(pub f64);
|
||||
|
||||
impl Beats {
|
||||
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)) }
|
||||
pub fn abs(self) -> Self { Self(self.0.abs()) }
|
||||
pub fn ceil(self) -> Self { Self(self.0.ceil()) }
|
||||
pub fn floor(self) -> Self { Self(self.0.floor()) }
|
||||
pub fn beats_to_f64(self) -> f64 { self.0 }
|
||||
}
|
||||
|
||||
impl Seconds {
|
||||
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)) }
|
||||
pub fn abs(self) -> Self { Self(self.0.abs()) }
|
||||
pub fn seconds_to_f64(self) -> f64 { self.0 }
|
||||
}
|
||||
|
||||
// --- Beats arithmetic ---
|
||||
|
||||
impl Add for Beats {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
|
||||
}
|
||||
impl Sub for Beats {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
|
||||
}
|
||||
impl Mul<f64> for Beats {
|
||||
type Output = Self;
|
||||
fn mul(self, rhs: f64) -> Self { Self(self.0 * rhs) }
|
||||
}
|
||||
impl Div<f64> for Beats {
|
||||
type Output = Self;
|
||||
fn div(self, rhs: f64) -> Self { Self(self.0 / rhs) }
|
||||
}
|
||||
/// Beats / Beats = dimensionless ratio (f64)
|
||||
impl Div<Beats> for Beats {
|
||||
type Output = f64;
|
||||
fn div(self, rhs: Beats) -> f64 { self.0 / rhs.0 }
|
||||
}
|
||||
impl Rem for Beats {
|
||||
type Output = Self;
|
||||
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
|
||||
}
|
||||
impl Neg for Beats {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self { Self(-self.0) }
|
||||
}
|
||||
impl AddAssign for Beats {
|
||||
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
|
||||
}
|
||||
impl SubAssign for Beats {
|
||||
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
|
||||
}
|
||||
|
||||
// --- Seconds arithmetic ---
|
||||
|
||||
impl Add for Seconds {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
|
||||
}
|
||||
impl Sub for Seconds {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
|
||||
}
|
||||
impl Mul<f64> for Seconds {
|
||||
type Output = Self;
|
||||
fn mul(self, rhs: f64) -> Self { Self(self.0 * rhs) }
|
||||
}
|
||||
impl Div<f64> for Seconds {
|
||||
type Output = Self;
|
||||
fn div(self, rhs: f64) -> Self { Self(self.0 / rhs) }
|
||||
}
|
||||
/// Seconds / Seconds = dimensionless ratio (f64)
|
||||
impl Div<Seconds> for Seconds {
|
||||
type Output = f64;
|
||||
fn div(self, rhs: Seconds) -> f64 { self.0 / rhs.0 }
|
||||
}
|
||||
impl Rem for Seconds {
|
||||
type Output = Self;
|
||||
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
|
||||
}
|
||||
impl Neg for Seconds {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self { Self(-self.0) }
|
||||
}
|
||||
impl AddAssign for Seconds {
|
||||
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
|
||||
}
|
||||
impl SubAssign for Seconds {
|
||||
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Beats {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Seconds {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
@@ -859,7 +859,7 @@ fn execute_command(
|
||||
|
||||
for event in &midi_clip.events {
|
||||
let status = event.status & 0xF0;
|
||||
let time_seconds = event.timestamp as f64 / sample_rate;
|
||||
let time_seconds = event.timestamp.beats_to_f64() / sample_rate;
|
||||
|
||||
match status {
|
||||
0x90 if event.data2 > 0 => {
|
||||
@@ -878,7 +878,7 @@ fn execute_command(
|
||||
}
|
||||
|
||||
// Add to local UI state with note data
|
||||
app.add_clip(track_id, clip_id, start_time, duration, file_path.to_string(), notes);
|
||||
app.add_clip(track_id, clip_id, start_time, duration.beats_to_f64(), file_path.to_string(), notes);
|
||||
app.next_clip_id += 1;
|
||||
|
||||
// Send to audio engine with the start_time (clip content is separate from timeline position)
|
||||
|
||||
Reference in New Issue
Block a user