Work on daw backend

This commit is contained in:
Skyler Lehmkuhl
2025-10-18 18:09:07 -04:00
parent 87d2036f07
commit 9414bdcd74
758 changed files with 5749 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
/// Clip ID type
pub type ClipId = u32;
/// Audio clip that references data in the AudioPool
#[derive(Debug, Clone)]
pub struct Clip {
pub id: ClipId,
pub audio_pool_index: usize,
pub start_time: f64, // Position on timeline in seconds
pub duration: f64, // Clip duration in seconds
pub offset: f64, // Offset into audio file in seconds
pub gain: f32, // Clip-level gain
}
impl Clip {
/// Create a new clip
pub fn new(
id: ClipId,
audio_pool_index: usize,
start_time: f64,
duration: f64,
offset: f64,
) -> Self {
Self {
id,
audio_pool_index,
start_time,
duration,
offset,
gain: 1.0,
}
}
/// Check if this clip is active at a given timeline position
pub fn is_active_at(&self, time_seconds: f64) -> bool {
let clip_end = self.start_time + self.duration;
time_seconds >= self.start_time && time_seconds < clip_end
}
/// Get the end time of this clip on the timeline
pub fn end_time(&self) -> f64 {
self.start_time + self.duration
}
/// Set clip gain
pub fn set_gain(&mut self, gain: f32) {
self.gain = gain.max(0.0);
}
}
+269
View File
@@ -0,0 +1,269 @@
use crate::audio::clip::ClipId;
use crate::audio::pool::AudioPool;
use crate::audio::track::{Track, TrackId};
use crate::command::{AudioEvent, Command};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
/// Audio engine for Phase 4: timeline with clips and audio pool
pub struct Engine {
tracks: Vec<Track>,
audio_pool: AudioPool,
playhead: u64, // Playhead position in samples
sample_rate: u32,
playing: bool,
channels: u32,
// Lock-free communication
command_rx: rtrb::Consumer<Command>,
event_tx: rtrb::Producer<AudioEvent>,
// Shared playhead for UI reads
playhead_atomic: Arc<AtomicU64>,
// Event counter for periodic position updates
frames_since_last_event: usize,
event_interval_frames: usize,
// Mix buffer for combining tracks
mix_buffer: Vec<f32>,
}
impl Engine {
/// Create a new Engine with communication channels
pub fn new(
sample_rate: u32,
channels: u32,
command_rx: rtrb::Consumer<Command>,
event_tx: rtrb::Producer<AudioEvent>,
) -> Self {
let event_interval_frames = (sample_rate as usize * channels as usize) / 10; // Update 10 times per second
Self {
tracks: Vec::new(),
audio_pool: AudioPool::new(),
playhead: 0,
sample_rate,
playing: false,
channels,
command_rx,
event_tx,
playhead_atomic: Arc::new(AtomicU64::new(0)),
frames_since_last_event: 0,
event_interval_frames,
mix_buffer: Vec::new(),
}
}
/// Add a track to the engine
pub fn add_track(&mut self, track: Track) -> TrackId {
let id = track.id;
self.tracks.push(track);
id
}
/// Get mutable reference to audio pool
pub fn audio_pool_mut(&mut self) -> &mut AudioPool {
&mut self.audio_pool
}
/// Get reference to audio pool
pub fn audio_pool(&self) -> &AudioPool {
&self.audio_pool
}
/// Get a handle for controlling playback from the UI thread
pub fn get_controller(&self, command_tx: rtrb::Producer<Command>) -> EngineController {
EngineController {
command_tx,
playhead: Arc::clone(&self.playhead_atomic),
sample_rate: self.sample_rate,
channels: self.channels,
}
}
/// Process audio callback - called from the audio thread
pub fn process(&mut self, output: &mut [f32]) {
// Process all pending commands
while let Ok(cmd) = self.command_rx.pop() {
self.handle_command(cmd);
}
if self.playing {
// Ensure mix buffer is sized correctly
if self.mix_buffer.len() != output.len() {
self.mix_buffer.resize(output.len(), 0.0);
}
// Clear mix buffer
self.mix_buffer.fill(0.0);
// 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,
);
}
}
// Copy mix to output
output.copy_from_slice(&self.mix_buffer);
// Update playhead
self.playhead += output.len() as u64;
// Update atomic playhead for UI reads
self.playhead_atomic
.store(self.playhead, Ordering::Relaxed);
// Send periodic position updates
self.frames_since_last_event += output.len() / self.channels as usize;
if self.frames_since_last_event >= self.event_interval_frames / self.channels as usize
{
let position_seconds =
self.playhead as f64 / (self.sample_rate as f64 * self.channels as f64);
let _ = self
.event_tx
.push(AudioEvent::PlaybackPosition(position_seconds));
self.frames_since_last_event = 0;
}
} else {
// Not playing, output silence
output.fill(0.0);
}
}
/// Handle a command from the UI thread
fn handle_command(&mut self, cmd: Command) {
match cmd {
Command::Play => {
self.playing = true;
}
Command::Stop => {
self.playing = false;
self.playhead = 0;
self.playhead_atomic.store(0, Ordering::Relaxed);
}
Command::Pause => {
self.playing = false;
}
Command::Seek(seconds) => {
let samples = (seconds * self.sample_rate as f64 * self.channels as f64) as u64;
self.playhead = samples;
self.playhead_atomic
.store(self.playhead, Ordering::Relaxed);
}
Command::SetTrackVolume(track_id, volume) => {
if let Some(track) = self.tracks.iter_mut().find(|t| t.id == 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) {
track.set_muted(muted);
}
}
Command::SetTrackSolo(track_id, solo) => {
if let Some(track) = self.tracks.iter_mut().find(|t| t.id == 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(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
clip.start_time = new_start_time;
}
}
}
}
}
/// Get current sample rate
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
/// Get number of channels
pub fn channels(&self) -> u32 {
self.channels
}
/// Get number of tracks
pub fn track_count(&self) -> usize {
self.tracks.len()
}
}
/// Controller for the engine that can be used from the UI thread
pub struct EngineController {
command_tx: rtrb::Producer<Command>,
playhead: Arc<AtomicU64>,
sample_rate: u32,
channels: u32,
}
impl EngineController {
/// Start or resume playback
pub fn play(&mut self) {
let _ = self.command_tx.push(Command::Play);
}
/// Pause playback
pub fn pause(&mut self) {
let _ = self.command_tx.push(Command::Pause);
}
/// Stop playback and reset to beginning
pub fn stop(&mut self) {
let _ = self.command_tx.push(Command::Stop);
}
/// Seek to a specific position in seconds
pub fn seek(&mut self, seconds: f64) {
let _ = self.command_tx.push(Command::Seek(seconds));
}
/// Set track volume (0.0 = silence, 1.0 = unity gain)
pub fn set_track_volume(&mut self, track_id: TrackId, volume: f32) {
let _ = self
.command_tx
.push(Command::SetTrackVolume(track_id, volume));
}
/// Set track mute state
pub fn set_track_mute(&mut self, track_id: TrackId, muted: bool) {
let _ = self.command_tx.push(Command::SetTrackMute(track_id, muted));
}
/// Set track solo state
pub fn set_track_solo(&mut self, track_id: TrackId, solo: bool) {
let _ = self.command_tx.push(Command::SetTrackSolo(track_id, solo));
}
/// Move a clip to a new timeline position
pub fn move_clip(&mut self, track_id: TrackId, clip_id: ClipId, new_start_time: f64) {
let _ = self.command_tx.push(Command::MoveClip(track_id, clip_id, new_start_time));
}
/// Get current playhead position in samples
pub fn get_playhead_samples(&self) -> u64 {
self.playhead.load(Ordering::Relaxed)
}
/// Get current playhead position in seconds
pub fn get_playhead_seconds(&self) -> f64 {
let samples = self.playhead.load(Ordering::Relaxed);
samples as f64 / (self.sample_rate as f64 * self.channels as f64)
}
}
+9
View File
@@ -0,0 +1,9 @@
pub mod clip;
pub mod engine;
pub mod pool;
pub mod track;
pub use clip::{Clip, ClipId};
pub use engine::{Engine, EngineController};
pub use pool::{AudioFile as PoolAudioFile, AudioPool};
pub use track::{Track, TrackId};
+178
View File
@@ -0,0 +1,178 @@
use std::path::PathBuf;
/// Audio file stored in the pool
#[derive(Debug, Clone)]
pub struct AudioFile {
pub path: PathBuf,
pub data: Vec<f32>, // Interleaved samples
pub channels: u32,
pub sample_rate: u32,
pub frames: u64,
}
impl AudioFile {
/// Create a new AudioFile
pub fn new(path: PathBuf, data: Vec<f32>, channels: u32, sample_rate: u32) -> Self {
let frames = (data.len() / channels as usize) as u64;
Self {
path,
data,
channels,
sample_rate,
frames,
}
}
/// Get duration in seconds
pub fn duration_seconds(&self) -> f64 {
self.frames as f64 / self.sample_rate as f64
}
}
/// Pool of shared audio files
pub struct AudioPool {
files: Vec<AudioFile>,
}
impl AudioPool {
/// Create a new empty audio pool
pub fn new() -> Self {
Self {
files: Vec::new(),
}
}
/// Add an audio file to the pool and return its index
pub fn add_file(&mut self, file: AudioFile) -> usize {
let index = self.files.len();
self.files.push(file);
index
}
/// Get an audio file by index
pub fn get_file(&self, index: usize) -> Option<&AudioFile> {
self.files.get(index)
}
/// Get number of files in the pool
pub fn file_count(&self) -> usize {
self.files.len()
}
/// Render audio from a file in the pool with sample rate and channel conversion
/// start_time_seconds: position in the audio file to start reading from (in seconds)
/// Returns the number of samples actually rendered
pub fn render_from_file(
&self,
pool_index: usize,
output: &mut [f32],
start_time_seconds: f64,
gain: f32,
engine_sample_rate: u32,
engine_channels: u32,
) -> usize {
if let Some(audio_file) = self.files.get(pool_index) {
// Calculate starting frame position in the source file (frame = one sample per channel)
let src_start_frame = start_time_seconds * audio_file.sample_rate as f64;
// Calculate sample rate conversion ratio (frames)
let rate_ratio = audio_file.sample_rate as f64 / engine_sample_rate as f64;
let src_channels = audio_file.channels;
let dst_channels = engine_channels;
// Render frame by frame
let output_frames = output.len() / dst_channels as usize;
let mut rendered_frames = 0;
for frame_idx in 0..output_frames {
// Calculate the corresponding frame in the source file
let src_frame_pos = src_start_frame + (frame_idx as f64 * rate_ratio);
let src_frame_idx = src_frame_pos as usize;
// Check bounds
if src_frame_idx >= audio_file.frames as usize {
break;
}
// Calculate source sample index (interleaved)
let src_sample_idx = src_frame_idx * src_channels as usize;
// Check bounds for interpolation
if src_sample_idx + src_channels as usize > audio_file.data.len() {
break;
}
// Linear interpolation for better quality
let frac = src_frame_pos - src_frame_idx as f64;
let next_frame_idx = src_frame_idx + 1;
let next_sample_idx = next_frame_idx * src_channels as usize;
let can_interpolate = next_sample_idx + src_channels as usize <= audio_file.data.len() && frac > 0.0;
// Read and convert channels
for dst_ch in 0..dst_channels {
let sample = if src_channels == dst_channels {
// Same number of channels - direct mapping
let ch = dst_ch as usize;
let s0 = audio_file.data[src_sample_idx + ch];
if can_interpolate {
let s1 = audio_file.data[next_sample_idx + ch];
s0 + (s1 - s0) * frac as f32
} else {
s0
}
} else if src_channels == 1 && dst_channels > 1 {
// Mono to multi-channel - duplicate to all channels
let s0 = audio_file.data[src_sample_idx];
if can_interpolate {
let s1 = audio_file.data[next_sample_idx];
s0 + (s1 - s0) * frac as f32
} else {
s0
}
} else if src_channels > 1 && dst_channels == 1 {
// Multi-channel to mono - average all source channels
let mut sum = 0.0f32;
for src_ch in 0..src_channels {
let s0 = audio_file.data[src_sample_idx + src_ch as usize];
let s = if can_interpolate {
let s1 = audio_file.data[next_sample_idx + src_ch as usize];
s0 + (s1 - s0) * frac as f32
} else {
s0
};
sum += s;
}
sum / src_channels as f32
} else {
// Mismatched channels - use modulo for simple mapping
let src_ch = (dst_ch % src_channels) as usize;
let s0 = audio_file.data[src_sample_idx + src_ch];
if can_interpolate {
let s1 = audio_file.data[next_sample_idx + src_ch];
s0 + (s1 - s0) * frac as f32
} else {
s0
}
};
// Mix into output with gain
let output_idx = frame_idx * dst_channels as usize + dst_ch as usize;
output[output_idx] += sample * gain;
}
rendered_frames += 1;
}
rendered_frames * dst_channels as usize
} else {
0
}
}
}
impl Default for AudioPool {
fn default() -> Self {
Self::new()
}
}
+143
View File
@@ -0,0 +1,143 @@
use super::clip::Clip;
use super::pool::AudioPool;
/// Track ID type
pub type TrackId = u32;
/// Audio track for Phase 4 with clips
pub struct Track {
pub id: TrackId,
pub name: String,
pub clips: Vec<Clip>,
pub volume: f32,
pub muted: bool,
pub solo: bool,
}
impl Track {
/// Create a new track with default settings
pub fn new(id: TrackId, name: String) -> Self {
Self {
id,
name,
clips: Vec::new(),
volume: 1.0,
muted: false,
solo: false,
}
}
/// Add a clip to this track
pub fn add_clip(&mut self, clip: Clip) {
self.clips.push(clip);
}
/// Set track volume (0.0 = silence, 1.0 = unity gain, >1.0 = amplification)
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 of all tracks
pub fn is_active(&self, any_solo: bool) -> bool {
!self.muted && (!any_solo || self.solo)
}
/// Render this track into the output buffer at a given timeline position
/// Returns the number of samples actually rendered
pub fn render(
&self,
output: &mut [f32],
pool: &AudioPool,
playhead_seconds: f64,
sample_rate: u32,
channels: u32,
) -> 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 mut rendered = 0;
// Render all active clips
for clip in &self.clips {
// Check if clip overlaps with current buffer time range
if clip.start_time < buffer_end_seconds && clip.end_time() > playhead_seconds {
rendered += self.render_clip(
clip,
output,
pool,
playhead_seconds,
sample_rate,
channels,
);
}
}
rendered
}
/// Render a single clip into the output buffer
fn render_clip(
&self,
clip: &Clip,
output: &mut [f32],
pool: &AudioPool,
playhead_seconds: f64,
sample_rate: u32,
channels: u32,
) -> 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;
// Determine the time range we need to render (intersection of buffer and clip)
let render_start_seconds = playhead_seconds.max(clip.start_time);
let render_end_seconds = buffer_end_seconds.min(clip.end_time());
// If no overlap, return early
if render_start_seconds >= render_end_seconds {
return 0;
}
// Calculate offset into the output buffer (in interleaved samples)
let output_offset_seconds = render_start_seconds - playhead_seconds;
let output_offset_samples = (output_offset_seconds * sample_rate as f64 * channels as f64) as usize;
// Calculate position within the clip's audio file (in seconds)
let clip_position_seconds = render_start_seconds - clip.start_time + clip.offset;
// Calculate how many samples to render in the output
let render_duration_seconds = render_end_seconds - render_start_seconds;
let samples_to_render = (render_duration_seconds * sample_rate as f64 * channels as f64) as usize;
let samples_to_render = samples_to_render.min(output.len() - output_offset_samples);
// Get the slice of output buffer to write to
if output_offset_samples + samples_to_render > output.len() {
return 0;
}
let output_slice = &mut output[output_offset_samples..output_offset_samples + samples_to_render];
// Calculate combined gain
let combined_gain = clip.gain * self.volume;
// Render from pool with sample rate conversion
// Pass the time position in seconds, let the pool handle sample rate conversion
pool.render_from_file(
clip.audio_pool_index,
output_slice,
clip_position_seconds,
combined_gain,
sample_rate,
channels,
)
}
}