Make beats canonical representation rather than seconds
This commit is contained in:
@@ -113,6 +113,8 @@ pub struct Engine {
|
||||
// Current tempo map — kept in sync with SetTempo/SetTempoMap commands.
|
||||
tempo_map: crate::TempoMap,
|
||||
current_fps: f64,
|
||||
// Current time signature — updated by SetTempo, used when SetTempoMap fires.
|
||||
time_sig: (u32, u32),
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
@@ -191,6 +193,7 @@ impl Engine {
|
||||
timing_overrun_count: 0,
|
||||
tempo_map: crate::TempoMap::constant(120.0),
|
||||
current_fps: 30.0,
|
||||
time_sig: (4, 4),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1290,11 +1293,19 @@ impl Engine {
|
||||
}
|
||||
|
||||
Command::SetTempo(bpm, time_sig) => {
|
||||
self.time_sig = time_sig;
|
||||
self.metronome.update_timing(bpm, time_sig);
|
||||
self.project.set_tempo(bpm, time_sig.0);
|
||||
self.tempo_map.set_global_bpm(bpm as f64);
|
||||
}
|
||||
|
||||
Command::SetTempoMap(map) => {
|
||||
let bpm0 = map.global_bpm() as f32;
|
||||
self.metronome.update_timing(bpm0, self.time_sig);
|
||||
self.project.set_tempo(bpm0, self.time_sig.0);
|
||||
self.tempo_map = map;
|
||||
}
|
||||
|
||||
// Node graph commands
|
||||
Command::GraphAddNode(track_id, node_type, x, y) => {
|
||||
eprintln!("[DEBUG] GraphAddNode received: track_id={}, node_type={}, x={}, y={}", track_id, node_type, x, y);
|
||||
@@ -1846,9 +1857,17 @@ impl Engine {
|
||||
let buffer_size = self.buffer_pool.buffer_size();
|
||||
if let Some(TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
let current = metatrack.current_subtracks();
|
||||
let has_subtrack_node = metatrack.audio_graph.node_indices().any(|idx| {
|
||||
metatrack.audio_graph.get_graph_node(idx)
|
||||
.map(|n| n.node.node_type() == "SubtrackInputs")
|
||||
.unwrap_or(false)
|
||||
});
|
||||
|
||||
// No-op if subtrack list is unchanged (prevents every-frame graph rebuilds)
|
||||
if current == subtracks {
|
||||
// No-op if subtrack list is unchanged AND the graph is already initialised.
|
||||
// Without the `has_subtrack_node` guard a freshly-created metatrack
|
||||
// (empty graph, no SubtrackInputs) with zero subtracks would never get
|
||||
// its default Volume automation node.
|
||||
if current == subtracks && has_subtrack_node {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2156,8 +2175,13 @@ impl Engine {
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
let graph = &mut track.instrument_graph;
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(t)) => Some(&mut t.instrument_graph),
|
||||
Some(TrackNode::Audio(t)) => Some(&mut t.effects_graph),
|
||||
Some(TrackNode::Group(t)) => Some(&mut t.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
|
||||
@@ -2181,8 +2205,13 @@ impl Engine {
|
||||
Command::AutomationRemoveKeyframe(track_id, node_id, time) => {
|
||||
use crate::audio::node_graph::nodes::AutomationInputNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
let graph = &mut track.instrument_graph;
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(t)) => Some(&mut t.instrument_graph),
|
||||
Some(TrackNode::Audio(t)) => Some(&mut t.effects_graph),
|
||||
Some(TrackNode::Group(t)) => Some(&mut t.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
|
||||
@@ -2198,8 +2227,13 @@ impl Engine {
|
||||
Command::AutomationSetName(track_id, node_id, name) => {
|
||||
use crate::audio::node_graph::nodes::AutomationInputNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
let graph = &mut track.instrument_graph;
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(t)) => Some(&mut t.instrument_graph),
|
||||
Some(TrackNode::Audio(t)) => Some(&mut t.effects_graph),
|
||||
Some(TrackNode::Group(t)) => Some(&mut t.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
|
||||
@@ -2508,12 +2542,15 @@ impl Engine {
|
||||
use crate::audio::node_graph::nodes::{AutomationInputNode, InterpolationType};
|
||||
use crate::command::types::AutomationKeyframeData;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track(track_id) {
|
||||
let graph = &track.instrument_graph;
|
||||
let graph = match self.project.get_track(track_id) {
|
||||
Some(TrackNode::Midi(t)) => Some(&t.instrument_graph),
|
||||
Some(TrackNode::Audio(t)) => Some(&t.effects_graph),
|
||||
Some(TrackNode::Group(t)) => Some(&t.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node(node_idx) {
|
||||
// Downcast to AutomationInputNode
|
||||
if let Some(auto_node) = graph_node.node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
let keyframes: Vec<AutomationKeyframeData> = auto_node.keyframes()
|
||||
.iter()
|
||||
@@ -2524,7 +2561,6 @@ impl Engine {
|
||||
InterpolationType::Step => "step",
|
||||
InterpolationType::Hold => "hold",
|
||||
}.to_string();
|
||||
|
||||
AutomationKeyframeData {
|
||||
time: kf.time.0,
|
||||
value: kf.value,
|
||||
@@ -2534,7 +2570,6 @@ impl Engine {
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
QueryResponse::AutomationKeyframes(Ok(keyframes))
|
||||
} else {
|
||||
QueryResponse::AutomationKeyframes(Err(format!("Node {} is not an AutomationInputNode", node_id)))
|
||||
@@ -2543,19 +2578,22 @@ impl Engine {
|
||||
QueryResponse::AutomationKeyframes(Err(format!("Node {} not found in track {}", node_id, track_id)))
|
||||
}
|
||||
} else {
|
||||
QueryResponse::AutomationKeyframes(Err(format!("Track {} not found or is not a MIDI track", track_id)))
|
||||
QueryResponse::AutomationKeyframes(Err(format!("Track {} not found", track_id)))
|
||||
}
|
||||
}
|
||||
|
||||
Query::GetAutomationName(track_id, node_id) => {
|
||||
use crate::audio::node_graph::nodes::AutomationInputNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track(track_id) {
|
||||
let graph = &track.instrument_graph;
|
||||
let graph = match self.project.get_track(track_id) {
|
||||
Some(TrackNode::Midi(t)) => Some(&t.instrument_graph),
|
||||
Some(TrackNode::Audio(t)) => Some(&t.effects_graph),
|
||||
Some(TrackNode::Group(t)) => Some(&t.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node(node_idx) {
|
||||
// Downcast to AutomationInputNode
|
||||
if let Some(auto_node) = graph_node.node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
QueryResponse::AutomationName(Ok(auto_node.display_name().to_string()))
|
||||
} else {
|
||||
@@ -2565,17 +2603,21 @@ impl Engine {
|
||||
QueryResponse::AutomationName(Err(format!("Node {} not found in track {}", node_id, track_id)))
|
||||
}
|
||||
} else {
|
||||
QueryResponse::AutomationName(Err(format!("Track {} not found or is not a MIDI track", track_id)))
|
||||
QueryResponse::AutomationName(Err(format!("Track {} not found", track_id)))
|
||||
}
|
||||
}
|
||||
|
||||
Query::GetAutomationRange(track_id, node_id) => {
|
||||
use crate::audio::node_graph::nodes::AutomationInputNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track(track_id) {
|
||||
let graph = &track.instrument_graph;
|
||||
let graph = match self.project.get_track(track_id) {
|
||||
Some(TrackNode::Midi(t)) => Some(&t.instrument_graph),
|
||||
Some(TrackNode::Audio(t)) => Some(&t.effects_graph),
|
||||
Some(TrackNode::Group(t)) => Some(&t.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node(node_idx) {
|
||||
if let Some(auto_node) = graph_node.node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
QueryResponse::AutomationRange(Ok((auto_node.value_min, auto_node.value_max)))
|
||||
@@ -2586,7 +2628,7 @@ impl Engine {
|
||||
QueryResponse::AutomationRange(Err(format!("Node {} not found", node_id)))
|
||||
}
|
||||
} else {
|
||||
QueryResponse::AutomationRange(Err(format!("Track {} not found or is not a MIDI track", track_id)))
|
||||
QueryResponse::AutomationRange(Err(format!("Track {} not found", track_id)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3665,6 +3707,11 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::SetTempo(bpm, time_signature));
|
||||
}
|
||||
|
||||
/// Replace the full tempo map (multi-entry variable tempo)
|
||||
pub fn set_tempo_map(&mut self, map: crate::TempoMap) {
|
||||
let _ = self.command_tx.push(Command::SetTempoMap(map));
|
||||
}
|
||||
|
||||
/// 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; `to_bpm` is the new BPM.
|
||||
|
||||
@@ -263,7 +263,11 @@ impl Metatrack {
|
||||
graph
|
||||
}
|
||||
|
||||
/// Build the explicit subtrack mixing graph: SubtrackInputs → Mixer → AudioOutput.
|
||||
/// Build the default subtrack mixing graph: SubtrackInputs → Mixer → Gain → AudioOutput,
|
||||
/// with an AutomationInput ("Volume", range 0..2) feeding the Gain's CV port.
|
||||
///
|
||||
/// Existing Volume keyframes are preserved across rebuilds so that adding/removing
|
||||
/// a child track doesn't reset the automation.
|
||||
///
|
||||
/// `subtracks` is an ordered list of (backend TrackId, display name) for each child.
|
||||
/// Replaces the current graph and marks `graph_is_default = true`.
|
||||
@@ -273,35 +277,60 @@ impl Metatrack {
|
||||
sample_rate: u32,
|
||||
buffer_size: usize,
|
||||
) {
|
||||
use super::node_graph::nodes::{SubtrackInputsNode, MixerNode};
|
||||
use super::node_graph::nodes::{SubtrackInputsNode, MixerNode, GainNode, AutomationInputNode};
|
||||
use super::node_graph::nodes::AutomationKeyframe;
|
||||
use crate::time::Beats;
|
||||
|
||||
// Preserve existing Volume keyframes before rebuilding.
|
||||
let existing_volume_kfs = self.get_volume_automation_keyframes();
|
||||
|
||||
let n = subtracks.len();
|
||||
let mut graph = AudioGraph::new(sample_rate, buffer_size);
|
||||
|
||||
// SubtrackInputs node (N outputs, one per child)
|
||||
// NOTE: `new()` initialises buffers as zero-length; call `update_subtracks` immediately
|
||||
// to allocate stereo interleaved buffers (buffer_size * 2 samples each).
|
||||
let mut inputs_node = SubtrackInputsNode::new("Subtrack Inputs", subtracks);
|
||||
let subtracks_copy = inputs_node.subtracks().to_vec();
|
||||
inputs_node.update_subtracks(subtracks_copy, buffer_size);
|
||||
let inputs_id = graph.add_node(Box::new(inputs_node));
|
||||
graph.set_node_position(inputs_id, 100.0, 150.0);
|
||||
|
||||
// Mixer node (starts with 1 spare; grows as connections are made)
|
||||
// Mixer node
|
||||
let mixer_node = Box::new(MixerNode::new("Mixer"));
|
||||
let mixer_id = graph.add_node(mixer_node);
|
||||
graph.set_node_position(mixer_id, 350.0, 150.0);
|
||||
graph.set_node_position(mixer_id, 330.0, 150.0);
|
||||
|
||||
// Gain node — group volume control
|
||||
let gain_id = graph.add_node(Box::new(GainNode::new("Volume")));
|
||||
graph.set_node_position(gain_id, 520.0, 150.0);
|
||||
|
||||
// AutomationInput — drives the Gain's CV port
|
||||
let mut auto_node = AutomationInputNode::new("Volume CV");
|
||||
auto_node.set_display_name("Volume".to_string());
|
||||
auto_node.value_min = 0.0;
|
||||
auto_node.value_max = 2.0;
|
||||
auto_node.clear_keyframes();
|
||||
if existing_volume_kfs.is_empty() {
|
||||
auto_node.add_keyframe(AutomationKeyframe::new(Beats::ZERO, 1.0));
|
||||
} else {
|
||||
for kf in existing_volume_kfs {
|
||||
auto_node.add_keyframe(kf);
|
||||
}
|
||||
}
|
||||
let auto_id = graph.add_node(Box::new(auto_node));
|
||||
graph.set_node_position(auto_id, 520.0, 320.0);
|
||||
|
||||
// AudioOutput node
|
||||
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
|
||||
let output_id = graph.add_node(output_node);
|
||||
graph.set_node_position(output_id, 600.0, 150.0);
|
||||
graph.set_node_position(output_id, 720.0, 150.0);
|
||||
|
||||
// Connect SubtrackInputs[i] → Mixer[i] for each subtrack
|
||||
for i in 0..n {
|
||||
let _ = graph.connect(inputs_id, i, mixer_id, i);
|
||||
}
|
||||
let _ = graph.connect(mixer_id, 0, output_id, 0);
|
||||
let _ = graph.connect(mixer_id, 0, gain_id, 0); // Mixer → Gain audio
|
||||
let _ = graph.connect(auto_id, 0, gain_id, 1); // AutomationInput → Gain CV
|
||||
let _ = graph.connect(gain_id, 0, output_id, 0); // Gain → Audio Out
|
||||
graph.set_output_node(Some(output_id));
|
||||
|
||||
self.audio_graph = graph;
|
||||
@@ -309,6 +338,22 @@ impl Metatrack {
|
||||
self.graph_is_default = true;
|
||||
}
|
||||
|
||||
/// Extract Volume AutomationInput keyframes from the current graph (if any),
|
||||
/// so they can be preserved across `set_subtrack_graph` rebuilds.
|
||||
fn get_volume_automation_keyframes(&self) -> Vec<super::node_graph::nodes::AutomationKeyframe> {
|
||||
use super::node_graph::nodes::AutomationInputNode;
|
||||
for idx in self.audio_graph.node_indices() {
|
||||
if let Some(node) = self.audio_graph.get_graph_node(idx) {
|
||||
if node.node.node_type() == "AutomationInput" {
|
||||
if let Some(auto_node) = node.node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
return auto_node.keyframes().to_vec();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Add a new subtrack port to the existing graph.
|
||||
///
|
||||
/// If `graph_is_default`: also connects the new port to a new Mixer input.
|
||||
|
||||
@@ -145,6 +145,8 @@ pub enum Command {
|
||||
SetMetronomeEnabled(bool),
|
||||
/// Set project tempo and time signature (bpm, (numerator, denominator))
|
||||
SetTempo(f32, (u32, u32)),
|
||||
/// Replace the entire tempo map (multi-entry variable tempo support)
|
||||
SetTempoMap(crate::TempoMap),
|
||||
// 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),
|
||||
|
||||
@@ -21,7 +21,7 @@ pub use audio::{
|
||||
};
|
||||
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 tempo_map::{TempoEntry, TempoInterpolation, 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};
|
||||
|
||||
+133
-63
@@ -3,11 +3,17 @@
|
||||
//! Positions are stored in **beats** throughout the project; `TempoMap` converts
|
||||
//! between beats and seconds at render / scheduling time.
|
||||
//!
|
||||
//! # Interpolation
|
||||
//! Each `TempoEntry` has an `interpolation` field that controls how the BPM
|
||||
//! changes between that entry and the next:
|
||||
//! - `Step`: BPM is constant from this entry's beat until the next entry. Instant change.
|
||||
//! - `Linear`: BPM linearly interpolates from this entry's BPM to the next entry's BPM
|
||||
//! over the beat range. The seconds calculation uses the exact integral:
|
||||
//! `Δt = (60 / slope) * ln(bpm_end / bpm_start)` where slope = (bpm_end - bpm_start) / span_beats.
|
||||
//!
|
||||
//! # 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`.
|
||||
//! `entries` is a sorted `Vec<TempoEntry>` where the first entry must always
|
||||
//! have `beat == 0.0`.
|
||||
//!
|
||||
//! # Sequential-access optimisation
|
||||
//! An `AtomicUsize` caches the index of the last segment visited by
|
||||
@@ -19,21 +25,35 @@ 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`.
|
||||
/// How the BPM transitions from one `TempoEntry` to the next.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
|
||||
pub enum TempoInterpolation {
|
||||
/// BPM stays constant from this entry's beat until the next entry (instant change).
|
||||
#[default]
|
||||
Step,
|
||||
/// BPM linearly interpolates from this entry's BPM to the next entry's BPM
|
||||
/// over the beat span between the two entries.
|
||||
Linear,
|
||||
}
|
||||
|
||||
/// A single tempo segment: from `beat` onwards the tempo changes according to `interpolation`.
|
||||
#[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.
|
||||
/// Tempo at the start of 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,
|
||||
/// How the BPM transitions from this entry to the next.
|
||||
#[serde(default)]
|
||||
pub interpolation: TempoInterpolation,
|
||||
}
|
||||
|
||||
/// A piecewise-constant tempo map used to convert between beats and seconds.
|
||||
/// A piecewise 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.
|
||||
@@ -58,11 +78,49 @@ impl Default for TempoMap {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Seconds elapsed traversing `span_beats` starting at `bpm_start`.
|
||||
/// If `bpm_end` is `Some` (linear segment) and differs from `bpm_start`,
|
||||
/// uses the exact logarithmic integral.
|
||||
#[inline]
|
||||
fn segment_duration(span_beats: f64, bpm_start: f64, bpm_end: Option<f64>) -> f64 {
|
||||
match bpm_end {
|
||||
None => span_beats * 60.0 / bpm_start,
|
||||
Some(b1) if (b1 - bpm_start).abs() < 1e-9 => span_beats * 60.0 / bpm_start,
|
||||
Some(b1) => {
|
||||
// Linear BPM: BPM(b) = bpm_start + slope * (b - b_start)
|
||||
// Δt = ∫₀^span 60 / BPM(b) db = (60/slope) * ln(b1/bpm_start)
|
||||
let slope = (b1 - bpm_start) / span_beats;
|
||||
(60.0 / slope) * (b1 / bpm_start).ln()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Beats elapsed given `delta_seconds` starting at `bpm_start`.
|
||||
/// If `bpm_end` is `Some` (linear segment) and differs from `bpm_start`,
|
||||
/// uses the exact exponential inverse.
|
||||
#[inline]
|
||||
fn segment_beats(delta_seconds: f64, span_beats: f64, bpm_start: f64, bpm_end: Option<f64>) -> f64 {
|
||||
match bpm_end {
|
||||
None => delta_seconds * bpm_start / 60.0,
|
||||
Some(b1) if (b1 - bpm_start).abs() < 1e-9 => delta_seconds * bpm_start / 60.0,
|
||||
Some(b1) => {
|
||||
// Inverse of the logarithmic integral:
|
||||
// b = b_start + (bpm_start / slope) * (exp(delta_t * slope / 60) - 1)
|
||||
let slope = (b1 - bpm_start) / span_beats;
|
||||
(bpm_start / slope) * ((delta_seconds * slope / 60.0).exp() - 1.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 }],
|
||||
entries: vec![TempoEntry { beat: 0.0, bpm, seconds: 0.0, interpolation: TempoInterpolation::Step }],
|
||||
last_index: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
@@ -72,20 +130,36 @@ impl TempoMap {
|
||||
/// after deserialization.
|
||||
pub fn rebuild_seconds(&mut self) {
|
||||
let mut cumulative = 0.0_f64;
|
||||
for i in 0..self.entries.len() {
|
||||
let n = self.entries.len();
|
||||
for i in 0..n {
|
||||
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;
|
||||
if i + 1 < n {
|
||||
let span = self.entries[i + 1].beat - self.entries[i].beat;
|
||||
let bpm_end = if self.entries[i].interpolation == TempoInterpolation::Linear {
|
||||
Some(self.entries[i + 1].bpm)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
cumulative += segment_duration(span, self.entries[i].bpm, bpm_end);
|
||||
}
|
||||
}
|
||||
self.last_index.store(0, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Return the BPM active at `beat`.
|
||||
/// Return the instantaneous BPM active at `beat`.
|
||||
/// For linear segments, returns the interpolated value at that beat.
|
||||
pub fn bpm_at(&self, beat: Beats) -> f64 {
|
||||
let n = self.entries.len();
|
||||
let idx = self.entries.partition_point(|e| e.beat <= beat.0).saturating_sub(1);
|
||||
self.entries[idx.max(0)].bpm
|
||||
let idx = idx.min(n - 1);
|
||||
let entry = &self.entries[idx];
|
||||
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
|
||||
let next = &self.entries[idx + 1];
|
||||
let t = (beat.0 - entry.beat) / (next.beat - entry.beat);
|
||||
entry.bpm + (next.bpm - entry.bpm) * t
|
||||
} else {
|
||||
entry.bpm
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert beats to seconds using the tempo map.
|
||||
@@ -93,33 +167,12 @@ impl TempoMap {
|
||||
/// 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)
|
||||
Seconds(self.transform(beat.0))
|
||||
}
|
||||
|
||||
/// 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)
|
||||
Beats(self.inverse_transform(seconds.0))
|
||||
}
|
||||
|
||||
/// Global BPM — the BPM of the first entry (at beat 0).
|
||||
@@ -136,11 +189,7 @@ impl TempoMap {
|
||||
/// 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.
|
||||
/// group the result is the *parent group's* beats.
|
||||
pub fn transform(&self, beat: f64) -> f64 {
|
||||
if beat <= 0.0 {
|
||||
return 0.0;
|
||||
@@ -153,8 +202,16 @@ impl TempoMap {
|
||||
idx += 1;
|
||||
}
|
||||
self.last_index.store(idx, Ordering::Relaxed);
|
||||
|
||||
let entry = &self.entries[idx];
|
||||
entry.seconds + (beat - entry.beat) * 60.0 / entry.bpm
|
||||
let beat_in_seg = beat - entry.beat;
|
||||
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
|
||||
let next = &self.entries[idx + 1];
|
||||
let span = next.beat - entry.beat;
|
||||
entry.seconds + segment_duration(beat_in_seg, entry.bpm, Some(entry.bpm + (next.bpm - entry.bpm) * beat_in_seg / span))
|
||||
} else {
|
||||
entry.seconds + beat_in_seg * 60.0 / entry.bpm
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of [`transform`]: convert parent time units back to local beats.
|
||||
@@ -166,10 +223,17 @@ impl TempoMap {
|
||||
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
|
||||
let delta_t = parent_time - entry.seconds;
|
||||
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
|
||||
let next = &self.entries[idx + 1];
|
||||
let span = next.beat - entry.beat;
|
||||
entry.beat + segment_beats(delta_t, span, entry.bpm, Some(next.bpm))
|
||||
} else {
|
||||
entry.beat + delta_t * entry.bpm / 60.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a `TempoMap` from a list of `(beat, bpm)` keyframes.
|
||||
/// Build a `TempoMap` from a list of `(beat, bpm)` keyframes (step interpolation).
|
||||
/// 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() {
|
||||
@@ -177,11 +241,11 @@ impl TempoMap {
|
||||
}
|
||||
let mut entries: Vec<TempoEntry> = keyframes
|
||||
.iter()
|
||||
.map(|&(beat, bpm)| TempoEntry { beat, bpm, seconds: 0.0 })
|
||||
.map(|&(beat, bpm)| TempoEntry { beat, bpm, seconds: 0.0, interpolation: TempoInterpolation::Step })
|
||||
.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 });
|
||||
entries.insert(0, TempoEntry { beat: 0.0, bpm: entries[0].bpm, seconds: 0.0, interpolation: TempoInterpolation::Step });
|
||||
}
|
||||
let mut map = Self { entries, last_index: AtomicUsize::new(0) };
|
||||
map.rebuild_seconds();
|
||||
@@ -190,14 +254,6 @@ impl TempoMap {
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -227,26 +283,40 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_tempo() {
|
||||
fn variable_tempo_step() {
|
||||
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);
|
||||
// Beat 0-4: 120 BPM → 4 beats = 2 seconds
|
||||
assert!((m.beats_to_seconds(Beats(4.0)).0 - 2.0).abs() < 1e-9, "got {}", m.beats_to_seconds(Beats(4.0)).0);
|
||||
// Beat 4-5: 60 BPM → 1 beat = 1 second
|
||||
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 linear_interpolation_round_trip() {
|
||||
// 120→240 BPM over 4 beats: slope = (240-120)/4 = 30 BPM/beat
|
||||
// Δt = (60/30) * ln(240/120) = 2 * ln(2) ≈ 1.386s for beats 0-4
|
||||
let mut m = TempoMap::constant(120.0);
|
||||
m.entries.push(TempoEntry { beat: 4.0, bpm: 240.0, seconds: 0.0, interpolation: TempoInterpolation::Step });
|
||||
m.entries[0].interpolation = TempoInterpolation::Linear;
|
||||
m.rebuild_seconds();
|
||||
|
||||
let expected = 2.0 * std::f64::consts::LN_2;
|
||||
let got = m.beats_to_seconds(Beats(4.0)).0;
|
||||
assert!((got - expected).abs() < 1e-9, "got {got}, expected {expected}");
|
||||
|
||||
// Round-trip
|
||||
let beats_back = m.seconds_to_beats(Seconds(expected)).0;
|
||||
assert!((beats_back - 4.0).abs() < 1e-9, "round-trip got {beats_back}");
|
||||
}
|
||||
|
||||
#[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}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user