use tauri events instead of polling to fix race condition in recording stop
This commit is contained in:
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user