use tauri events instead of polling to fix race condition in recording stop

This commit is contained in:
Skyler Lehmkuhl
2025-10-23 03:59:01 -04:00
parent 20c3b820a3
commit d2fa167179
6 changed files with 285 additions and 157 deletions
+36 -39
View File
@@ -762,62 +762,59 @@ impl Engine {
/// Handle stopping a recording
fn handle_stop_recording(&mut self) {
eprintln!("[STOP_RECORDING] handle_stop_recording called");
if let Some(recording) = self.recording_state.take() {
let clip_id = recording.clip_id;
let track_id = recording.track_id;
let sample_rate = recording.sample_rate;
let channels = recording.channels;
// Finalize the recording and get temp file path
eprintln!("[STOP_RECORDING] Stopping recording for clip_id={}, track_id={}", clip_id, track_id);
// Finalize the recording (flush buffers, close file, get waveform and audio data)
let frames_recorded = recording.frames_written;
eprintln!("[STOP_RECORDING] Calling finalize() - frames_recorded={}", frames_recorded);
match recording.finalize() {
Ok(temp_file_path) => {
eprintln!("Recording finalized: {} frames written to {:?}", frames_recorded, temp_file_path);
Ok((temp_file_path, waveform, audio_data)) => {
eprintln!("[STOP_RECORDING] Finalize succeeded: {} frames written to {:?}, {} waveform peaks generated, {} samples in memory",
frames_recorded, temp_file_path, waveform.len(), audio_data.len());
// Load the recorded audio file
match crate::io::AudioFile::load(&temp_file_path) {
Ok(audio_file) => {
// Generate waveform for UI
let duration = audio_file.duration();
let target_peaks = ((duration * 300.0) as usize).clamp(1000, 20000);
let waveform = audio_file.generate_waveform_overview(target_peaks);
// Add to pool using the in-memory audio data (no file loading needed!)
let pool_file = crate::audio::pool::AudioFile::new(
temp_file_path.clone(),
audio_data,
channels,
sample_rate,
);
let pool_index = self.audio_pool.add_file(pool_file);
eprintln!("[STOP_RECORDING] Added to pool at index {}", pool_index);
// Add to pool
let pool_file = crate::audio::pool::AudioFile::new(
temp_file_path.clone(),
audio_file.data,
audio_file.channels,
audio_file.sample_rate,
);
let pool_index = self.audio_pool.add_file(pool_file);
// Update the clip to reference the pool
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.audio_pool_index = pool_index;
// Duration should already be set during recording progress updates
}
}
// Delete temp file
let _ = std::fs::remove_file(&temp_file_path);
// Notify UI that recording has stopped (with waveform)
let _ = self.event_tx.push(AudioEvent::RecordingStopped(clip_id, pool_index, waveform));
}
Err(e) => {
// Send error event
let _ = self.event_tx.push(AudioEvent::RecordingError(
format!("Failed to load recorded audio: {}", e)
));
// Update the clip to reference the pool
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.audio_pool_index = pool_index;
eprintln!("[STOP_RECORDING] Updated clip {} with pool_index {}", clip_id, pool_index);
}
}
// Delete temp file
let _ = std::fs::remove_file(&temp_file_path);
// Send event with the incrementally-generated waveform
eprintln!("[STOP_RECORDING] Pushing RecordingStopped event for clip_id={}, pool_index={}, waveform_peaks={}",
clip_id, pool_index, waveform.len());
let _ = self.event_tx.push(AudioEvent::RecordingStopped(clip_id, pool_index, waveform));
eprintln!("[STOP_RECORDING] RecordingStopped event pushed successfully");
}
Err(e) => {
// Send error event
eprintln!("[STOP_RECORDING] Finalize failed: {}", e);
let _ = self.event_tx.push(AudioEvent::RecordingError(
format!("Failed to finalize recording: {}", e)
));
}
}
} else {
eprintln!("[STOP_RECORDING] No active recording to stop");
}
}
+73 -11
View File
@@ -1,6 +1,6 @@
/// Audio recording system for capturing microphone input
use crate::audio::{ClipId, TrackId};
use crate::io::WavWriter;
use crate::io::{WavWriter, WaveformPeak};
use std::path::PathBuf;
/// State of an active recording session
@@ -29,6 +29,14 @@ pub struct RecordingState {
pub paused: bool,
/// Number of samples remaining to skip (to discard stale buffer data)
pub samples_to_skip: usize,
/// Waveform peaks generated incrementally during recording
pub waveform: Vec<WaveformPeak>,
/// Temporary buffer for collecting samples for next waveform peak
pub waveform_buffer: Vec<f32>,
/// Number of frames per waveform peak
pub frames_per_peak: usize,
/// All recorded audio data accumulated in memory (for fast finalization)
pub audio_data: Vec<f32>,
}
impl RecordingState {
@@ -45,6 +53,11 @@ impl RecordingState {
) -> Self {
let flush_interval_frames = (sample_rate as f64 * flush_interval_seconds) as usize;
// Calculate frames per waveform peak
// Target ~300 peaks per second with minimum 1000 samples per peak
let target_peaks_per_second = 300;
let frames_per_peak = (sample_rate / target_peaks_per_second).max(1000) as usize;
Self {
track_id,
clip_id,
@@ -58,6 +71,10 @@ impl RecordingState {
flush_interval_frames,
paused: false,
samples_to_skip: 0, // Will be set by engine when it knows buffer size
waveform: Vec::new(),
waveform_buffer: Vec::new(),
frames_per_peak,
audio_data: Vec::new(),
}
}
@@ -68,8 +85,8 @@ impl RecordingState {
return Ok(false);
}
// Skip stale samples from the buffer
if self.samples_to_skip > 0 {
// Determine which samples to process
let samples_to_process = if self.samples_to_skip > 0 {
let to_skip = self.samples_to_skip.min(samples.len());
self.samples_to_skip -= to_skip;
@@ -79,12 +96,22 @@ impl RecordingState {
}
// Skip partial batch and process the rest
self.buffer.extend_from_slice(&samples[to_skip..]);
&samples[to_skip..]
} else {
self.buffer.extend_from_slice(samples);
}
samples
};
// Check if we should flush
// Add to disk buffer
self.buffer.extend_from_slice(samples_to_process);
// Add to audio data (accumulate in memory for fast finalization)
self.audio_data.extend_from_slice(samples_to_process);
// Add to waveform buffer and generate peaks incrementally
self.waveform_buffer.extend_from_slice(samples_to_process);
self.generate_waveform_peaks();
// Check if we should flush to disk
let frames_in_buffer = self.buffer.len() / self.channels as usize;
if frames_in_buffer >= self.flush_interval_frames {
self.flush()?;
@@ -94,6 +121,28 @@ impl RecordingState {
Ok(false)
}
/// Generate waveform peaks from accumulated samples
/// This is called incrementally as samples arrive
fn generate_waveform_peaks(&mut self) {
let samples_per_peak = self.frames_per_peak * self.channels as usize;
while self.waveform_buffer.len() >= samples_per_peak {
let mut min = 0.0f32;
let mut max = 0.0f32;
// Scan all samples for this peak
for sample in &self.waveform_buffer[..samples_per_peak] {
min = min.min(*sample);
max = max.max(*sample);
}
self.waveform.push(WaveformPeak { min, max });
// Remove processed samples from waveform buffer
self.waveform_buffer.drain(..samples_per_peak);
}
}
/// Flush accumulated samples to disk
pub fn flush(&mut self) -> Result<(), std::io::Error> {
if self.buffer.is_empty() {
@@ -121,15 +170,28 @@ impl RecordingState {
total_frames as f64 / self.sample_rate as f64
}
/// Finalize the recording and return the temp file path
pub fn finalize(mut self) -> Result<PathBuf, std::io::Error> {
// Flush any remaining samples
/// Finalize the recording and return the temp file path, waveform, and audio data
pub fn finalize(mut self) -> Result<(PathBuf, Vec<WaveformPeak>, Vec<f32>), std::io::Error> {
// Flush any remaining samples to disk
self.flush()?;
// Generate final waveform peak from any remaining samples
if !self.waveform_buffer.is_empty() {
let mut min = 0.0f32;
let mut max = 0.0f32;
for sample in &self.waveform_buffer {
min = min.min(*sample);
max = max.max(*sample);
}
self.waveform.push(WaveformPeak { min, max });
}
// Finalize the WAV file
self.writer.finalize()?;
Ok(self.temp_file_path)
Ok((self.temp_file_path, self.waveform, self.audio_data))
}
/// Pause recording
+43 -5
View File
@@ -22,18 +22,27 @@ pub use io::{load_midi_file, AudioFile, WaveformPeak, WavWriter};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
/// Trait for emitting audio events to external systems (UI, logging, etc.)
/// This allows the DAW backend to remain framework-agnostic
pub trait EventEmitter: Send + Sync {
/// Emit an audio event
fn emit(&self, event: AudioEvent);
}
/// Simple audio system that handles cpal initialization internally
pub struct AudioSystem {
pub controller: EngineController,
pub stream: cpal::Stream,
pub event_rx: rtrb::Consumer<AudioEvent>,
pub sample_rate: u32,
pub channels: u32,
}
impl AudioSystem {
/// Initialize the audio system with default input and output devices
pub fn new() -> Result<Self, String> {
///
/// # Arguments
/// * `event_emitter` - Optional event emitter for pushing events to external systems
pub fn new(event_emitter: Option<std::sync::Arc<dyn EventEmitter>>) -> Result<Self, String> {
let host = cpal::default_host();
// Get output device
@@ -84,10 +93,15 @@ impl AudioSystem {
eprintln!("Warning: No input device available, recording will be disabled");
// Start output stream and return without input
output_stream.play().map_err(|e| e.to_string())?;
// Spawn emitter thread if provided
if let Some(emitter) = event_emitter {
Self::spawn_emitter_thread(event_rx, emitter);
}
return Ok(Self {
controller,
stream: output_stream,
event_rx,
sample_rate,
channels,
});
@@ -106,10 +120,15 @@ impl AudioSystem {
Err(e) => {
eprintln!("Warning: Could not get input config: {}, recording will be disabled", e);
output_stream.play().map_err(|e| e.to_string())?;
// Spawn emitter thread if provided
if let Some(emitter) = event_emitter {
Self::spawn_emitter_thread(event_rx, emitter);
}
return Ok(Self {
controller,
stream: output_stream,
event_rx,
sample_rate,
channels,
});
@@ -138,12 +157,31 @@ impl AudioSystem {
// Leak the input stream to keep it alive
Box::leak(Box::new(input_stream));
// Spawn emitter thread if provided
if let Some(emitter) = event_emitter {
Self::spawn_emitter_thread(event_rx, emitter);
}
Ok(Self {
controller,
stream: output_stream,
event_rx,
sample_rate,
channels,
})
}
/// Spawn a background thread to emit events from the ringbuffer
fn spawn_emitter_thread(mut event_rx: rtrb::Consumer<AudioEvent>, emitter: std::sync::Arc<dyn EventEmitter>) {
std::thread::spawn(move || {
loop {
// Wait for events and emit them
if let Ok(event) = event_rx.pop() {
emitter.emit(event);
} else {
// No events available, sleep briefly to avoid busy-waiting
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
});
}
}