midi import in daw backend
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
/// Pool of reusable audio buffers for recursive group rendering
|
||||
///
|
||||
/// This pool allows groups to acquire temporary buffers for submixing
|
||||
/// child tracks without allocating memory in the audio thread.
|
||||
pub struct BufferPool {
|
||||
buffers: Vec<Vec<f32>>,
|
||||
available: Vec<usize>,
|
||||
buffer_size: usize,
|
||||
}
|
||||
|
||||
impl BufferPool {
|
||||
/// Create a new buffer pool
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `initial_capacity` - Number of buffers to pre-allocate
|
||||
/// * `buffer_size` - Size of each buffer in samples
|
||||
pub fn new(initial_capacity: usize, buffer_size: usize) -> Self {
|
||||
let mut buffers = Vec::with_capacity(initial_capacity);
|
||||
let mut available = Vec::with_capacity(initial_capacity);
|
||||
|
||||
// Pre-allocate buffers
|
||||
for i in 0..initial_capacity {
|
||||
buffers.push(vec![0.0; buffer_size]);
|
||||
available.push(i);
|
||||
}
|
||||
|
||||
Self {
|
||||
buffers,
|
||||
available,
|
||||
buffer_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire a buffer from the pool
|
||||
///
|
||||
/// Returns a zeroed buffer ready for use. If no buffers are available,
|
||||
/// allocates a new one (though this should be avoided in the audio thread).
|
||||
pub fn acquire(&mut self) -> Vec<f32> {
|
||||
if let Some(idx) = self.available.pop() {
|
||||
// Reuse an existing buffer
|
||||
let mut buf = std::mem::take(&mut self.buffers[idx]);
|
||||
buf.fill(0.0);
|
||||
buf
|
||||
} else {
|
||||
// No buffers available, allocate a new one
|
||||
// This should be rare if the pool is sized correctly
|
||||
vec![0.0; self.buffer_size]
|
||||
}
|
||||
}
|
||||
|
||||
/// Release a buffer back to the pool
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `buffer` - The buffer to return to the pool
|
||||
pub fn release(&mut self, buffer: Vec<f32>) {
|
||||
// Only add to pool if it's the correct size
|
||||
if buffer.len() == self.buffer_size {
|
||||
let idx = self.buffers.len();
|
||||
self.buffers.push(buffer);
|
||||
self.available.push(idx);
|
||||
}
|
||||
// Otherwise, drop the buffer (wrong size, shouldn't happen normally)
|
||||
}
|
||||
|
||||
/// Get the configured buffer size
|
||||
pub fn buffer_size(&self) -> usize {
|
||||
self.buffer_size
|
||||
}
|
||||
|
||||
/// Get the number of available buffers
|
||||
pub fn available_count(&self) -> usize {
|
||||
self.available.len()
|
||||
}
|
||||
|
||||
/// Get the total number of buffers in the pool
|
||||
pub fn total_count(&self) -> usize {
|
||||
self.buffers.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BufferPool {
|
||||
fn default() -> Self {
|
||||
// Default: 8 buffers of 4096 samples (enough for 85ms at 48kHz stereo)
|
||||
Self::new(8, 4096)
|
||||
}
|
||||
}
|
||||
+280
-29
@@ -1,14 +1,19 @@
|
||||
use crate::audio::buffer_pool::BufferPool;
|
||||
use crate::audio::clip::ClipId;
|
||||
use crate::audio::midi::{MidiClip, MidiClipId, MidiEvent};
|
||||
use crate::audio::pool::AudioPool;
|
||||
use crate::audio::project::Project;
|
||||
use crate::audio::track::{Track, TrackId};
|
||||
use crate::command::{AudioEvent, Command};
|
||||
use crate::effects::{Effect, GainEffect, PanEffect, SimpleEQ};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Audio engine for Phase 4: timeline with clips and audio pool
|
||||
/// Audio engine for Phase 6: hierarchical tracks with groups
|
||||
pub struct Engine {
|
||||
tracks: Vec<Track>,
|
||||
project: Project,
|
||||
audio_pool: AudioPool,
|
||||
buffer_pool: BufferPool,
|
||||
playhead: u64, // Playhead position in samples
|
||||
sample_rate: u32,
|
||||
playing: bool,
|
||||
@@ -25,8 +30,11 @@ pub struct Engine {
|
||||
frames_since_last_event: usize,
|
||||
event_interval_frames: usize,
|
||||
|
||||
// Mix buffer for combining tracks
|
||||
// Mix buffer for output
|
||||
mix_buffer: Vec<f32>,
|
||||
|
||||
// ID counters
|
||||
next_midi_clip_id: MidiClipId,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
@@ -39,9 +47,13 @@ impl Engine {
|
||||
) -> Self {
|
||||
let event_interval_frames = (sample_rate as usize * channels as usize) / 10; // Update 10 times per second
|
||||
|
||||
// Calculate a reasonable buffer size for the pool (typical audio callback size * channels)
|
||||
let buffer_size = 512 * channels as usize;
|
||||
|
||||
Self {
|
||||
tracks: Vec::new(),
|
||||
project: Project::new(),
|
||||
audio_pool: AudioPool::new(),
|
||||
buffer_pool: BufferPool::new(8, buffer_size), // 8 buffers should handle deep nesting
|
||||
playhead: 0,
|
||||
sample_rate,
|
||||
playing: false,
|
||||
@@ -52,16 +64,55 @@ impl Engine {
|
||||
frames_since_last_event: 0,
|
||||
event_interval_frames,
|
||||
mix_buffer: Vec::new(),
|
||||
next_midi_clip_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a track to the engine
|
||||
/// Add an audio track to the engine
|
||||
pub fn add_track(&mut self, track: Track) -> TrackId {
|
||||
let id = track.id;
|
||||
self.tracks.push(track);
|
||||
// For backwards compatibility, we'll extract the track data and add it to the project
|
||||
let name = track.name.clone();
|
||||
let id = self.project.add_audio_track(name, None);
|
||||
|
||||
// Copy over the track properties
|
||||
if let Some(node) = self.project.get_track_mut(id) {
|
||||
if let crate::audio::track::TrackNode::Audio(audio_track) = node {
|
||||
audio_track.clips = track.clips;
|
||||
audio_track.effects = track.effects;
|
||||
audio_track.volume = track.volume;
|
||||
audio_track.muted = track.muted;
|
||||
audio_track.solo = track.solo;
|
||||
}
|
||||
}
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Add an audio track by name
|
||||
pub fn add_audio_track(&mut self, name: String) -> TrackId {
|
||||
self.project.add_audio_track(name, None)
|
||||
}
|
||||
|
||||
/// Add a group track by name
|
||||
pub fn add_group_track(&mut self, name: String) -> TrackId {
|
||||
self.project.add_group_track(name, None)
|
||||
}
|
||||
|
||||
/// Add a MIDI track by name
|
||||
pub fn add_midi_track(&mut self, name: String) -> TrackId {
|
||||
self.project.add_midi_track(name, None)
|
||||
}
|
||||
|
||||
/// Get access to the project
|
||||
pub fn project(&self) -> &Project {
|
||||
&self.project
|
||||
}
|
||||
|
||||
/// Get mutable access to the project
|
||||
pub fn project_mut(&mut self) -> &mut Project {
|
||||
&mut self.project
|
||||
}
|
||||
|
||||
/// Get mutable reference to audio pool
|
||||
pub fn audio_pool_mut(&mut self) -> &mut AudioPool {
|
||||
&mut self.audio_pool
|
||||
@@ -95,27 +146,24 @@ impl Engine {
|
||||
self.mix_buffer.resize(output.len(), 0.0);
|
||||
}
|
||||
|
||||
// Clear mix buffer
|
||||
self.mix_buffer.fill(0.0);
|
||||
// Ensure buffer pool has the correct buffer size
|
||||
if self.buffer_pool.buffer_size() != output.len() {
|
||||
// Reallocate buffer pool with correct size if needed
|
||||
self.buffer_pool = BufferPool::new(8, output.len());
|
||||
}
|
||||
|
||||
// Convert playhead from samples to seconds for timeline-based rendering
|
||||
let playhead_seconds = self.playhead as f64 / (self.sample_rate as f64 * self.channels as f64);
|
||||
|
||||
// Check if any track is soloed
|
||||
let any_solo = self.tracks.iter().any(|t| t.solo);
|
||||
|
||||
// Mix all active tracks using timeline-based rendering
|
||||
for track in &self.tracks {
|
||||
if track.is_active(any_solo) {
|
||||
track.render(
|
||||
&mut self.mix_buffer,
|
||||
&self.audio_pool,
|
||||
playhead_seconds,
|
||||
self.sample_rate,
|
||||
self.channels,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Render the entire project hierarchy into the mix buffer
|
||||
self.project.render(
|
||||
&mut self.mix_buffer,
|
||||
&self.audio_pool,
|
||||
&mut self.buffer_pool,
|
||||
playhead_seconds,
|
||||
self.sample_rate,
|
||||
self.channels,
|
||||
);
|
||||
|
||||
// Copy mix to output
|
||||
output.copy_from_slice(&self.mix_buffer);
|
||||
@@ -165,27 +213,175 @@ impl Engine {
|
||||
.store(self.playhead, Ordering::Relaxed);
|
||||
}
|
||||
Command::SetTrackVolume(track_id, volume) => {
|
||||
if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
|
||||
if let Some(track) = self.project.get_track_mut(track_id) {
|
||||
track.set_volume(volume);
|
||||
}
|
||||
}
|
||||
Command::SetTrackMute(track_id, muted) => {
|
||||
if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
|
||||
if let Some(track) = self.project.get_track_mut(track_id) {
|
||||
track.set_muted(muted);
|
||||
}
|
||||
}
|
||||
Command::SetTrackSolo(track_id, solo) => {
|
||||
if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
|
||||
if let Some(track) = self.project.get_track_mut(track_id) {
|
||||
track.set_solo(solo);
|
||||
}
|
||||
}
|
||||
Command::MoveClip(track_id, clip_id, new_start_time) => {
|
||||
if let Some(track) = self.tracks.iter_mut().find(|t| t.id == track_id) {
|
||||
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.start_time = new_start_time;
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::AddGainEffect(track_id, gain_db) => {
|
||||
// Get the track node and handle audio tracks, MIDI tracks, and groups
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
if let Some(effect) = track.effects.iter_mut().find(|e| e.name() == "Gain") {
|
||||
effect.set_parameter(0, gain_db);
|
||||
} else {
|
||||
track.add_effect(Box::new(GainEffect::with_gain_db(gain_db)));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(effect) = track.effects.iter_mut().find(|e| e.name() == "Gain") {
|
||||
effect.set_parameter(0, gain_db);
|
||||
} else {
|
||||
track.add_effect(Box::new(GainEffect::with_gain_db(gain_db)));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Group(group)) => {
|
||||
if let Some(effect) = group.effects.iter_mut().find(|e| e.name() == "Gain") {
|
||||
effect.set_parameter(0, gain_db);
|
||||
} else {
|
||||
group.add_effect(Box::new(GainEffect::with_gain_db(gain_db)));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Command::AddPanEffect(track_id, pan) => {
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
if let Some(effect) = track.effects.iter_mut().find(|e| e.name() == "Pan") {
|
||||
effect.set_parameter(0, pan);
|
||||
} else {
|
||||
track.add_effect(Box::new(PanEffect::with_pan(pan)));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(effect) = track.effects.iter_mut().find(|e| e.name() == "Pan") {
|
||||
effect.set_parameter(0, pan);
|
||||
} else {
|
||||
track.add_effect(Box::new(PanEffect::with_pan(pan)));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Group(group)) => {
|
||||
if let Some(effect) = group.effects.iter_mut().find(|e| e.name() == "Pan") {
|
||||
effect.set_parameter(0, pan);
|
||||
} else {
|
||||
group.add_effect(Box::new(PanEffect::with_pan(pan)));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Command::AddEQEffect(track_id, low_db, mid_db, high_db) => {
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
if let Some(effect) = track.effects.iter_mut().find(|e| e.name() == "SimpleEQ") {
|
||||
effect.set_parameter(0, low_db);
|
||||
effect.set_parameter(1, mid_db);
|
||||
effect.set_parameter(2, high_db);
|
||||
} else {
|
||||
let mut eq = SimpleEQ::new();
|
||||
eq.set_parameter(0, low_db);
|
||||
eq.set_parameter(1, mid_db);
|
||||
eq.set_parameter(2, high_db);
|
||||
track.add_effect(Box::new(eq));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(effect) = track.effects.iter_mut().find(|e| e.name() == "SimpleEQ") {
|
||||
effect.set_parameter(0, low_db);
|
||||
effect.set_parameter(1, mid_db);
|
||||
effect.set_parameter(2, high_db);
|
||||
} else {
|
||||
let mut eq = SimpleEQ::new();
|
||||
eq.set_parameter(0, low_db);
|
||||
eq.set_parameter(1, mid_db);
|
||||
eq.set_parameter(2, high_db);
|
||||
track.add_effect(Box::new(eq));
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Group(group)) => {
|
||||
if let Some(effect) = group.effects.iter_mut().find(|e| e.name() == "SimpleEQ") {
|
||||
effect.set_parameter(0, low_db);
|
||||
effect.set_parameter(1, mid_db);
|
||||
effect.set_parameter(2, high_db);
|
||||
} else {
|
||||
let mut eq = SimpleEQ::new();
|
||||
eq.set_parameter(0, low_db);
|
||||
eq.set_parameter(1, mid_db);
|
||||
eq.set_parameter(2, high_db);
|
||||
group.add_effect(Box::new(eq));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Command::ClearEffects(track_id) => {
|
||||
let _ = self.project.clear_effects(track_id);
|
||||
}
|
||||
Command::CreateGroup(name) => {
|
||||
let track_id = self.project.add_group_track(name.clone(), None);
|
||||
// Notify UI about the new group
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, true, name));
|
||||
}
|
||||
Command::AddToGroup(track_id, group_id) => {
|
||||
// Move the track to the new group (Project handles removing from old parent)
|
||||
self.project.move_to_group(track_id, group_id);
|
||||
}
|
||||
Command::RemoveFromGroup(track_id) => {
|
||||
// Move to root level (None as parent)
|
||||
self.project.move_to_root(track_id);
|
||||
}
|
||||
Command::CreateMidiTrack(name) => {
|
||||
let track_id = self.project.add_midi_track(name.clone(), None);
|
||||
// Notify UI about the new MIDI track
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
}
|
||||
Command::CreateMidiClip(track_id, start_time, duration) => {
|
||||
// Create a new MIDI clip with unique ID
|
||||
let clip_id = self.next_midi_clip_id;
|
||||
self.next_midi_clip_id += 1;
|
||||
let clip = MidiClip::new(clip_id, start_time, duration);
|
||||
let _ = self.project.add_midi_clip(track_id, clip);
|
||||
}
|
||||
Command::AddMidiNote(track_id, clip_id, time_offset, note, velocity, duration) => {
|
||||
// Add a MIDI note event to the specified clip
|
||||
if let Some(crate::audio::track::TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
// Convert time to sample timestamp
|
||||
let timestamp = (time_offset * self.sample_rate as f64) as u64;
|
||||
let note_on = MidiEvent::note_on(timestamp, 0, note, velocity);
|
||||
clip.events.push(note_on);
|
||||
|
||||
// Add note off event
|
||||
let note_off_timestamp = ((time_offset + duration) * self.sample_rate as f64) as u64;
|
||||
let note_off = MidiEvent::note_off(note_off_timestamp, 0, note, 64);
|
||||
clip.events.push(note_off);
|
||||
|
||||
// Sort events by timestamp
|
||||
clip.events.sort_by_key(|e| e.timestamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::AddLoadedMidiClip(track_id, clip) => {
|
||||
// Add a pre-loaded MIDI clip to the track
|
||||
let _ = self.project.add_midi_clip(track_id, clip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +397,7 @@ impl Engine {
|
||||
|
||||
/// Get number of tracks
|
||||
pub fn track_count(&self) -> usize {
|
||||
self.tracks.len()
|
||||
self.project.track_count()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,6 +452,26 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::MoveClip(track_id, clip_id, new_start_time));
|
||||
}
|
||||
|
||||
/// Add or update gain effect on track
|
||||
pub fn add_gain_effect(&mut self, track_id: TrackId, gain_db: f32) {
|
||||
let _ = self.command_tx.push(Command::AddGainEffect(track_id, gain_db));
|
||||
}
|
||||
|
||||
/// Add or update pan effect on track
|
||||
pub fn add_pan_effect(&mut self, track_id: TrackId, pan: f32) {
|
||||
let _ = self.command_tx.push(Command::AddPanEffect(track_id, pan));
|
||||
}
|
||||
|
||||
/// Add or update EQ effect on track
|
||||
pub fn add_eq_effect(&mut self, track_id: TrackId, low_db: f32, mid_db: f32, high_db: f32) {
|
||||
let _ = self.command_tx.push(Command::AddEQEffect(track_id, low_db, mid_db, high_db));
|
||||
}
|
||||
|
||||
/// Clear all effects from a track
|
||||
pub fn clear_effects(&mut self, track_id: TrackId) {
|
||||
let _ = self.command_tx.push(Command::ClearEffects(track_id));
|
||||
}
|
||||
|
||||
/// Get current playhead position in samples
|
||||
pub fn get_playhead_samples(&self) -> u64 {
|
||||
self.playhead.load(Ordering::Relaxed)
|
||||
@@ -266,4 +482,39 @@ impl EngineController {
|
||||
let samples = self.playhead.load(Ordering::Relaxed);
|
||||
samples as f64 / (self.sample_rate as f64 * self.channels as f64)
|
||||
}
|
||||
|
||||
/// Create a new group track
|
||||
pub fn create_group(&mut self, name: String) {
|
||||
let _ = self.command_tx.push(Command::CreateGroup(name));
|
||||
}
|
||||
|
||||
/// Add a track to a group
|
||||
pub fn add_to_group(&mut self, track_id: TrackId, group_id: TrackId) {
|
||||
let _ = self.command_tx.push(Command::AddToGroup(track_id, group_id));
|
||||
}
|
||||
|
||||
/// Remove a track from its parent group
|
||||
pub fn remove_from_group(&mut self, track_id: TrackId) {
|
||||
let _ = self.command_tx.push(Command::RemoveFromGroup(track_id));
|
||||
}
|
||||
|
||||
/// Create a new MIDI track
|
||||
pub fn create_midi_track(&mut self, name: String) {
|
||||
let _ = self.command_tx.push(Command::CreateMidiTrack(name));
|
||||
}
|
||||
|
||||
/// Create a new MIDI clip on a track
|
||||
pub fn create_midi_clip(&mut self, track_id: TrackId, start_time: f64, duration: f64) {
|
||||
let _ = self.command_tx.push(Command::CreateMidiClip(track_id, start_time, duration));
|
||||
}
|
||||
|
||||
/// Add a MIDI note to a clip
|
||||
pub fn add_midi_note(&mut self, track_id: TrackId, clip_id: MidiClipId, time_offset: f64, note: u8, velocity: u8, duration: f64) {
|
||||
let _ = self.command_tx.push(Command::AddMidiNote(track_id, clip_id, time_offset, note, velocity, duration));
|
||||
}
|
||||
|
||||
/// Add a pre-loaded MIDI clip to a track
|
||||
pub fn add_loaded_midi_clip(&mut self, track_id: TrackId, clip: MidiClip) {
|
||||
let _ = self.command_tx.push(Command::AddLoadedMidiClip(track_id, clip));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/// MIDI event representing a single MIDI message
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct MidiEvent {
|
||||
/// Sample position within the clip
|
||||
pub timestamp: u64,
|
||||
/// MIDI status byte (includes channel)
|
||||
pub status: u8,
|
||||
/// First data byte (note number, CC number, etc.)
|
||||
pub data1: u8,
|
||||
/// Second data byte (velocity, CC value, etc.)
|
||||
pub data2: u8,
|
||||
}
|
||||
|
||||
impl MidiEvent {
|
||||
/// Create a new MIDI event
|
||||
pub fn new(timestamp: u64, status: u8, data1: u8, data2: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
status,
|
||||
data1,
|
||||
data2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a note on event
|
||||
pub fn note_on(timestamp: u64, 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: u64, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
status: 0x80 | (channel & 0x0F),
|
||||
data1: note,
|
||||
data2: velocity,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// MIDI clip ID type
|
||||
pub type MidiClipId = u32;
|
||||
|
||||
/// MIDI clip containing a sequence of MIDI events
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MidiClip {
|
||||
pub id: MidiClipId,
|
||||
pub events: Vec<MidiEvent>,
|
||||
pub start_time: f64, // Position on timeline in seconds
|
||||
pub duration: f64, // Clip duration in seconds
|
||||
pub loop_enabled: bool,
|
||||
}
|
||||
|
||||
impl MidiClip {
|
||||
/// Create a new MIDI clip
|
||||
pub fn new(id: MidiClipId, start_time: f64, duration: f64) -> Self {
|
||||
Self {
|
||||
id,
|
||||
events: Vec::new(),
|
||||
start_time,
|
||||
duration,
|
||||
loop_enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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_key(|e| e.timestamp);
|
||||
}
|
||||
|
||||
/// Get the end time of the clip
|
||||
pub fn end_time(&self) -> f64 {
|
||||
self.start_time + self.duration
|
||||
}
|
||||
|
||||
/// Get events that should be triggered in a given time range
|
||||
///
|
||||
/// Returns events along with their absolute timestamps in samples
|
||||
pub fn get_events_in_range(
|
||||
&self,
|
||||
range_start_seconds: f64,
|
||||
range_end_seconds: f64,
|
||||
sample_rate: u32,
|
||||
) -> Vec<(u64, MidiEvent)> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
// Check if clip overlaps with the range
|
||||
if range_start_seconds >= self.end_time() || range_end_seconds <= self.start_time {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Calculate the intersection
|
||||
let play_start = range_start_seconds.max(self.start_time);
|
||||
let play_end = range_end_seconds.min(self.end_time());
|
||||
|
||||
// Convert to samples
|
||||
let range_start_samples = (range_start_seconds * sample_rate as f64) as u64;
|
||||
|
||||
// Position within the clip
|
||||
let clip_position_seconds = play_start - self.start_time;
|
||||
let clip_position_samples = (clip_position_seconds * sample_rate as f64) as u64;
|
||||
let clip_end_samples = ((play_end - self.start_time) * sample_rate as f64) as u64;
|
||||
|
||||
// Find events in this range
|
||||
// Note: Using <= for the end boundary to include events exactly at the clip end
|
||||
for event in &self.events {
|
||||
if event.timestamp >= clip_position_samples && event.timestamp <= clip_end_samples {
|
||||
// Calculate absolute timestamp in the output buffer
|
||||
let absolute_timestamp = range_start_samples + (event.timestamp - clip_position_samples);
|
||||
result.push((absolute_timestamp, *event));
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
pub mod buffer_pool;
|
||||
pub mod clip;
|
||||
pub mod engine;
|
||||
pub mod midi;
|
||||
pub mod pool;
|
||||
pub mod project;
|
||||
pub mod track;
|
||||
|
||||
pub use buffer_pool::BufferPool;
|
||||
pub use clip::{Clip, ClipId};
|
||||
pub use engine::{Engine, EngineController};
|
||||
pub use midi::{MidiClip, MidiClipId, MidiEvent};
|
||||
pub use pool::{AudioFile as PoolAudioFile, AudioPool};
|
||||
pub use track::{Track, TrackId};
|
||||
pub use project::Project;
|
||||
pub use track::{AudioTrack, GroupTrack, MidiTrack, Track, TrackId, TrackNode};
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
use super::buffer_pool::BufferPool;
|
||||
use super::clip::Clip;
|
||||
use super::midi::MidiClip;
|
||||
use super::pool::AudioPool;
|
||||
use super::track::{AudioTrack, GroupTrack, MidiTrack, TrackId, TrackNode};
|
||||
use crate::effects::Effect;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Project manages the hierarchical track structure
|
||||
///
|
||||
/// Tracks are stored in a flat HashMap but can be organized into groups,
|
||||
/// forming a tree structure. Groups render their children recursively.
|
||||
pub struct Project {
|
||||
tracks: HashMap<TrackId, TrackNode>,
|
||||
next_track_id: TrackId,
|
||||
root_tracks: Vec<TrackId>, // Top-level tracks (not in any group)
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// Create a new empty project
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tracks: HashMap::new(),
|
||||
next_track_id: 0,
|
||||
root_tracks: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a new unique track ID
|
||||
fn next_id(&mut self) -> TrackId {
|
||||
let id = self.next_track_id;
|
||||
self.next_track_id += 1;
|
||||
id
|
||||
}
|
||||
|
||||
/// Add an audio track to the project
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `name` - Track name
|
||||
/// * `parent_id` - Optional parent group ID
|
||||
///
|
||||
/// # Returns
|
||||
/// The new track's ID
|
||||
pub fn add_audio_track(&mut self, name: String, parent_id: Option<TrackId>) -> TrackId {
|
||||
let id = self.next_id();
|
||||
let track = AudioTrack::new(id, name);
|
||||
self.tracks.insert(id, TrackNode::Audio(track));
|
||||
|
||||
if let Some(parent) = parent_id {
|
||||
// Add to parent group
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&parent) {
|
||||
group.add_child(id);
|
||||
}
|
||||
} else {
|
||||
// Add to root level
|
||||
self.root_tracks.push(id);
|
||||
}
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Add a group track to the project
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `name` - Group name
|
||||
/// * `parent_id` - Optional parent group ID
|
||||
///
|
||||
/// # Returns
|
||||
/// The new group's ID
|
||||
pub fn add_group_track(&mut self, name: String, parent_id: Option<TrackId>) -> TrackId {
|
||||
let id = self.next_id();
|
||||
let group = GroupTrack::new(id, name);
|
||||
self.tracks.insert(id, TrackNode::Group(group));
|
||||
|
||||
if let Some(parent) = parent_id {
|
||||
// Add to parent group
|
||||
if let Some(TrackNode::Group(parent_group)) = self.tracks.get_mut(&parent) {
|
||||
parent_group.add_child(id);
|
||||
}
|
||||
} else {
|
||||
// Add to root level
|
||||
self.root_tracks.push(id);
|
||||
}
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Add a MIDI track to the project
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `name` - Track name
|
||||
/// * `parent_id` - Optional parent group ID
|
||||
///
|
||||
/// # Returns
|
||||
/// The new track's ID
|
||||
pub fn add_midi_track(&mut self, name: String, parent_id: Option<TrackId>) -> TrackId {
|
||||
let id = self.next_id();
|
||||
let track = MidiTrack::new(id, name);
|
||||
self.tracks.insert(id, TrackNode::Midi(track));
|
||||
|
||||
if let Some(parent) = parent_id {
|
||||
// Add to parent group
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&parent) {
|
||||
group.add_child(id);
|
||||
}
|
||||
} else {
|
||||
// Add to root level
|
||||
self.root_tracks.push(id);
|
||||
}
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove a track from the project
|
||||
///
|
||||
/// If the track is a group, all children are moved to the parent (or root)
|
||||
pub fn remove_track(&mut self, track_id: TrackId) {
|
||||
if let Some(node) = self.tracks.remove(&track_id) {
|
||||
// If it's a group, handle its children
|
||||
if let TrackNode::Group(group) = node {
|
||||
// Find the parent of this group
|
||||
let parent_id = self.find_parent(track_id);
|
||||
|
||||
// Move children to parent or root
|
||||
for child_id in group.children {
|
||||
if let Some(parent) = parent_id {
|
||||
if let Some(TrackNode::Group(parent_group)) = self.tracks.get_mut(&parent) {
|
||||
parent_group.add_child(child_id);
|
||||
}
|
||||
} else {
|
||||
self.root_tracks.push(child_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove from parent or root
|
||||
if let Some(parent_id) = self.find_parent(track_id) {
|
||||
if let Some(TrackNode::Group(parent)) = self.tracks.get_mut(&parent_id) {
|
||||
parent.remove_child(track_id);
|
||||
}
|
||||
} else {
|
||||
self.root_tracks.retain(|&id| id != track_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the parent group of a track
|
||||
fn find_parent(&self, track_id: TrackId) -> Option<TrackId> {
|
||||
for (id, node) in &self.tracks {
|
||||
if let TrackNode::Group(group) = node {
|
||||
if group.children.contains(&track_id) {
|
||||
return Some(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Move a track to a different group
|
||||
pub fn move_to_group(&mut self, track_id: TrackId, new_parent_id: TrackId) {
|
||||
// First remove from current parent
|
||||
if let Some(old_parent_id) = self.find_parent(track_id) {
|
||||
if let Some(TrackNode::Group(parent)) = self.tracks.get_mut(&old_parent_id) {
|
||||
parent.remove_child(track_id);
|
||||
}
|
||||
} else {
|
||||
// Remove from root
|
||||
self.root_tracks.retain(|&id| id != track_id);
|
||||
}
|
||||
|
||||
// Add to new parent
|
||||
if let Some(TrackNode::Group(new_parent)) = self.tracks.get_mut(&new_parent_id) {
|
||||
new_parent.add_child(track_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Move a track to the root level (remove from any group)
|
||||
pub fn move_to_root(&mut self, track_id: TrackId) {
|
||||
// Remove from current parent if any
|
||||
if let Some(parent_id) = self.find_parent(track_id) {
|
||||
if let Some(TrackNode::Group(parent)) = self.tracks.get_mut(&parent_id) {
|
||||
parent.remove_child(track_id);
|
||||
}
|
||||
// Add to root if not already there
|
||||
if !self.root_tracks.contains(&track_id) {
|
||||
self.root_tracks.push(track_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a reference to a track node
|
||||
pub fn get_track(&self, track_id: TrackId) -> Option<&TrackNode> {
|
||||
self.tracks.get(&track_id)
|
||||
}
|
||||
|
||||
/// Get a mutable reference to a track node
|
||||
pub fn get_track_mut(&mut self, track_id: TrackId) -> Option<&mut TrackNode> {
|
||||
self.tracks.get_mut(&track_id)
|
||||
}
|
||||
|
||||
/// Get all root-level track IDs
|
||||
pub fn root_tracks(&self) -> &[TrackId] {
|
||||
&self.root_tracks
|
||||
}
|
||||
|
||||
/// Get the number of tracks in the project
|
||||
pub fn track_count(&self) -> usize {
|
||||
self.tracks.len()
|
||||
}
|
||||
|
||||
/// Check if any track is soloed
|
||||
pub fn any_solo(&self) -> bool {
|
||||
self.tracks.values().any(|node| node.is_solo())
|
||||
}
|
||||
|
||||
/// Add a clip to an audio track
|
||||
pub fn add_clip(&mut self, track_id: TrackId, clip: Clip) -> Result<(), &'static str> {
|
||||
if let Some(TrackNode::Audio(track)) = self.tracks.get_mut(&track_id) {
|
||||
track.add_clip(clip);
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Track not found or is not an audio track")
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a MIDI clip to a MIDI track
|
||||
pub fn add_midi_clip(&mut self, track_id: TrackId, clip: MidiClip) -> Result<(), &'static str> {
|
||||
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
|
||||
track.add_clip(clip);
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Track not found or is not a MIDI track")
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an effect to a track (audio, MIDI, or group)
|
||||
pub fn add_effect(&mut self, track_id: TrackId, effect: Box<dyn Effect>) -> Result<(), &'static str> {
|
||||
match self.tracks.get_mut(&track_id) {
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
track.add_effect(effect);
|
||||
Ok(())
|
||||
}
|
||||
Some(TrackNode::Midi(track)) => {
|
||||
track.add_effect(effect);
|
||||
Ok(())
|
||||
}
|
||||
Some(TrackNode::Group(group)) => {
|
||||
group.add_effect(effect);
|
||||
Ok(())
|
||||
}
|
||||
None => Err("Track not found"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear effects from a track
|
||||
pub fn clear_effects(&mut self, track_id: TrackId) -> Result<(), &'static str> {
|
||||
match self.tracks.get_mut(&track_id) {
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
track.clear_effects();
|
||||
Ok(())
|
||||
}
|
||||
Some(TrackNode::Midi(track)) => {
|
||||
track.clear_effects();
|
||||
Ok(())
|
||||
}
|
||||
Some(TrackNode::Group(group)) => {
|
||||
group.clear_effects();
|
||||
Ok(())
|
||||
}
|
||||
None => Err("Track not found"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render all root tracks into the output buffer
|
||||
pub fn render(
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
pool: &AudioPool,
|
||||
buffer_pool: &mut BufferPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
) {
|
||||
output.fill(0.0);
|
||||
|
||||
let any_solo = self.any_solo();
|
||||
|
||||
// Render each root track
|
||||
for &track_id in &self.root_tracks.clone() {
|
||||
self.render_track(
|
||||
track_id,
|
||||
output,
|
||||
pool,
|
||||
buffer_pool,
|
||||
playhead_seconds,
|
||||
sample_rate,
|
||||
channels,
|
||||
any_solo,
|
||||
false, // root tracks are not inside a soloed parent
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively render a track (audio or group) into the output buffer
|
||||
fn render_track(
|
||||
&mut self,
|
||||
track_id: TrackId,
|
||||
output: &mut [f32],
|
||||
pool: &AudioPool,
|
||||
buffer_pool: &mut BufferPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
any_solo: bool,
|
||||
parent_is_soloed: bool,
|
||||
) {
|
||||
// Check if track should be rendered based on mute/solo
|
||||
let should_render = match self.tracks.get(&track_id) {
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
// If parent is soloed, only check mute state
|
||||
// Otherwise, check normal solo logic
|
||||
if parent_is_soloed {
|
||||
!track.muted
|
||||
} else {
|
||||
track.is_active(any_solo)
|
||||
}
|
||||
}
|
||||
Some(TrackNode::Midi(track)) => {
|
||||
// Same logic for MIDI tracks
|
||||
if parent_is_soloed {
|
||||
!track.muted
|
||||
} else {
|
||||
track.is_active(any_solo)
|
||||
}
|
||||
}
|
||||
Some(TrackNode::Group(group)) => {
|
||||
// Same logic for groups
|
||||
if parent_is_soloed {
|
||||
!group.muted
|
||||
} else {
|
||||
group.is_active(any_solo)
|
||||
}
|
||||
}
|
||||
None => return,
|
||||
};
|
||||
|
||||
if !should_render {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle audio track vs MIDI track vs group track
|
||||
match self.tracks.get_mut(&track_id) {
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
// Render audio track directly into output
|
||||
track.render(output, pool, playhead_seconds, sample_rate, channels);
|
||||
}
|
||||
Some(TrackNode::Midi(track)) => {
|
||||
// Render MIDI track directly into output
|
||||
track.render(output, playhead_seconds, sample_rate, channels);
|
||||
}
|
||||
Some(TrackNode::Group(group)) => {
|
||||
// Get children IDs and check if this group is soloed
|
||||
let children: Vec<TrackId> = group.children.clone();
|
||||
let this_group_is_soloed = group.solo;
|
||||
|
||||
// Acquire a temporary buffer for the group mix
|
||||
let mut group_buffer = buffer_pool.acquire();
|
||||
group_buffer.resize(output.len(), 0.0);
|
||||
group_buffer.fill(0.0);
|
||||
|
||||
// Recursively render all children into the group buffer
|
||||
// If this group is soloed (or parent was soloed), children inherit that state
|
||||
let children_parent_soloed = parent_is_soloed || this_group_is_soloed;
|
||||
for &child_id in &children {
|
||||
self.render_track(
|
||||
child_id,
|
||||
&mut group_buffer,
|
||||
pool,
|
||||
buffer_pool,
|
||||
playhead_seconds,
|
||||
sample_rate,
|
||||
channels,
|
||||
any_solo,
|
||||
children_parent_soloed,
|
||||
);
|
||||
}
|
||||
|
||||
// Apply group effects
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
|
||||
for effect in &mut group.effects {
|
||||
effect.process(&mut group_buffer, channels as usize, sample_rate);
|
||||
}
|
||||
|
||||
// Apply group volume and mix into output
|
||||
for (out_sample, group_sample) in output.iter_mut().zip(group_buffer.iter()) {
|
||||
*out_sample += group_sample * group.volume;
|
||||
}
|
||||
}
|
||||
|
||||
// Release buffer back to pool
|
||||
buffer_pool.release(group_buffer);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Project {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,300 @@
|
||||
use super::clip::Clip;
|
||||
use super::midi::MidiClip;
|
||||
use super::pool::AudioPool;
|
||||
use crate::effects::{Effect, SimpleSynth};
|
||||
|
||||
/// Track ID type
|
||||
pub type TrackId = u32;
|
||||
|
||||
/// Audio track for Phase 4 with clips
|
||||
pub struct Track {
|
||||
/// Type alias for backwards compatibility
|
||||
pub type Track = AudioTrack;
|
||||
|
||||
/// Node in the track hierarchy - can be an audio track, MIDI track, or a group
|
||||
pub enum TrackNode {
|
||||
Audio(AudioTrack),
|
||||
Midi(MidiTrack),
|
||||
Group(GroupTrack),
|
||||
}
|
||||
|
||||
impl TrackNode {
|
||||
/// Get the track ID
|
||||
pub fn id(&self) -> TrackId {
|
||||
match self {
|
||||
TrackNode::Audio(track) => track.id,
|
||||
TrackNode::Midi(track) => track.id,
|
||||
TrackNode::Group(group) => group.id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the track name
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
TrackNode::Audio(track) => &track.name,
|
||||
TrackNode::Midi(track) => &track.name,
|
||||
TrackNode::Group(group) => &group.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get muted state
|
||||
pub fn is_muted(&self) -> bool {
|
||||
match self {
|
||||
TrackNode::Audio(track) => track.muted,
|
||||
TrackNode::Midi(track) => track.muted,
|
||||
TrackNode::Group(group) => group.muted,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get solo state
|
||||
pub fn is_solo(&self) -> bool {
|
||||
match self {
|
||||
TrackNode::Audio(track) => track.solo,
|
||||
TrackNode::Midi(track) => track.solo,
|
||||
TrackNode::Group(group) => group.solo,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set volume
|
||||
pub fn set_volume(&mut self, volume: f32) {
|
||||
match self {
|
||||
TrackNode::Audio(track) => track.set_volume(volume),
|
||||
TrackNode::Midi(track) => track.set_volume(volume),
|
||||
TrackNode::Group(group) => group.set_volume(volume),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set muted state
|
||||
pub fn set_muted(&mut self, muted: bool) {
|
||||
match self {
|
||||
TrackNode::Audio(track) => track.set_muted(muted),
|
||||
TrackNode::Midi(track) => track.set_muted(muted),
|
||||
TrackNode::Group(group) => group.set_muted(muted),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set solo state
|
||||
pub fn set_solo(&mut self, solo: bool) {
|
||||
match self {
|
||||
TrackNode::Audio(track) => track.set_solo(solo),
|
||||
TrackNode::Midi(track) => track.set_solo(solo),
|
||||
TrackNode::Group(group) => group.set_solo(solo),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Group track that contains other tracks (audio or groups)
|
||||
pub struct GroupTrack {
|
||||
pub id: TrackId,
|
||||
pub name: String,
|
||||
pub clips: Vec<Clip>,
|
||||
pub children: Vec<TrackId>,
|
||||
pub effects: Vec<Box<dyn Effect>>,
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
pub solo: bool,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
/// Create a new track with default settings
|
||||
impl GroupTrack {
|
||||
/// Create a new group track
|
||||
pub fn new(id: TrackId, name: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name,
|
||||
children: Vec::new(),
|
||||
effects: Vec::new(),
|
||||
volume: 1.0,
|
||||
muted: false,
|
||||
solo: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a child track to this group
|
||||
pub fn add_child(&mut self, track_id: TrackId) {
|
||||
if !self.children.contains(&track_id) {
|
||||
self.children.push(track_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a child track from this group
|
||||
pub fn remove_child(&mut self, track_id: TrackId) {
|
||||
self.children.retain(|&id| id != track_id);
|
||||
}
|
||||
|
||||
/// Add an effect to the group's effect chain
|
||||
pub fn add_effect(&mut self, effect: Box<dyn Effect>) {
|
||||
self.effects.push(effect);
|
||||
}
|
||||
|
||||
/// Clear all effects from the group
|
||||
pub fn clear_effects(&mut self) {
|
||||
self.effects.clear();
|
||||
}
|
||||
|
||||
/// Set group volume
|
||||
pub fn set_volume(&mut self, volume: f32) {
|
||||
self.volume = volume.max(0.0);
|
||||
}
|
||||
|
||||
/// Set mute state
|
||||
pub fn set_muted(&mut self, muted: bool) {
|
||||
self.muted = muted;
|
||||
}
|
||||
|
||||
/// Set solo state
|
||||
pub fn set_solo(&mut self, solo: bool) {
|
||||
self.solo = solo;
|
||||
}
|
||||
|
||||
/// Check if this group should be audible given the solo state
|
||||
pub fn is_active(&self, any_solo: bool) -> bool {
|
||||
!self.muted && (!any_solo || self.solo)
|
||||
}
|
||||
}
|
||||
|
||||
/// MIDI track with MIDI clips and a virtual instrument
|
||||
pub struct MidiTrack {
|
||||
pub id: TrackId,
|
||||
pub name: String,
|
||||
pub clips: Vec<MidiClip>,
|
||||
pub instrument: SimpleSynth,
|
||||
pub effects: Vec<Box<dyn Effect>>,
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
pub solo: bool,
|
||||
}
|
||||
|
||||
impl MidiTrack {
|
||||
/// Create a new MIDI track with default settings
|
||||
pub fn new(id: TrackId, name: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name,
|
||||
clips: Vec::new(),
|
||||
instrument: SimpleSynth::new(),
|
||||
effects: Vec::new(),
|
||||
volume: 1.0,
|
||||
muted: false,
|
||||
solo: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an effect to the track's effect chain
|
||||
pub fn add_effect(&mut self, effect: Box<dyn Effect>) {
|
||||
self.effects.push(effect);
|
||||
}
|
||||
|
||||
/// Clear all effects from the track
|
||||
pub fn clear_effects(&mut self) {
|
||||
self.effects.clear();
|
||||
}
|
||||
|
||||
/// Add a MIDI clip to this track
|
||||
pub fn add_clip(&mut self, clip: MidiClip) {
|
||||
self.clips.push(clip);
|
||||
}
|
||||
|
||||
/// Set track volume
|
||||
pub fn set_volume(&mut self, volume: f32) {
|
||||
self.volume = volume.max(0.0);
|
||||
}
|
||||
|
||||
/// Set mute state
|
||||
pub fn set_muted(&mut self, muted: bool) {
|
||||
self.muted = muted;
|
||||
}
|
||||
|
||||
/// Set solo state
|
||||
pub fn set_solo(&mut self, solo: bool) {
|
||||
self.solo = solo;
|
||||
}
|
||||
|
||||
/// Check if this track should be audible given the solo state
|
||||
pub fn is_active(&self, any_solo: bool) -> bool {
|
||||
!self.muted && (!any_solo || self.solo)
|
||||
}
|
||||
|
||||
/// Render this MIDI track into the output buffer
|
||||
pub fn render(
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
) {
|
||||
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
|
||||
|
||||
// Collect MIDI events from all clips that overlap with current time range
|
||||
for clip in &self.clips {
|
||||
let events = clip.get_events_in_range(
|
||||
playhead_seconds,
|
||||
buffer_end_seconds,
|
||||
sample_rate,
|
||||
);
|
||||
|
||||
// Queue events in the instrument
|
||||
for (_timestamp, event) in events {
|
||||
self.instrument.queue_event(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate audio from the instrument
|
||||
self.instrument.process(output, channels as usize, sample_rate);
|
||||
|
||||
// Apply effect chain
|
||||
for effect in &mut self.effects {
|
||||
effect.process(output, channels as usize, sample_rate);
|
||||
}
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
*sample *= self.volume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio track with clips and effect chain
|
||||
pub struct AudioTrack {
|
||||
pub id: TrackId,
|
||||
pub name: String,
|
||||
pub clips: Vec<Clip>,
|
||||
pub effects: Vec<Box<dyn Effect>>,
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
pub solo: bool,
|
||||
}
|
||||
|
||||
impl AudioTrack {
|
||||
/// Create a new audio track with default settings
|
||||
pub fn new(id: TrackId, name: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name,
|
||||
clips: Vec::new(),
|
||||
effects: Vec::new(),
|
||||
volume: 1.0,
|
||||
muted: false,
|
||||
solo: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an effect to the track's effect chain
|
||||
pub fn add_effect(&mut self, effect: Box<dyn Effect>) {
|
||||
self.effects.push(effect);
|
||||
}
|
||||
|
||||
/// Remove an effect from the chain by index
|
||||
pub fn remove_effect(&mut self, index: usize) -> Option<Box<dyn Effect>> {
|
||||
if index < self.effects.len() {
|
||||
Some(self.effects.remove(index))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear all effects from the track
|
||||
pub fn clear_effects(&mut self) {
|
||||
self.effects.clear();
|
||||
}
|
||||
|
||||
/// Add a clip to this track
|
||||
pub fn add_clip(&mut self, clip: Clip) {
|
||||
self.clips.push(clip);
|
||||
@@ -55,7 +323,7 @@ impl Track {
|
||||
/// Render this track into the output buffer at a given timeline position
|
||||
/// Returns the number of samples actually rendered
|
||||
pub fn render(
|
||||
&self,
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
pool: &AudioPool,
|
||||
playhead_seconds: f64,
|
||||
@@ -82,6 +350,16 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
// Apply effect chain
|
||||
for effect in &mut self.effects {
|
||||
effect.process(output, channels as usize, sample_rate);
|
||||
}
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
*sample *= self.volume;
|
||||
}
|
||||
|
||||
rendered
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user