Record audio tracks
This commit is contained in:
@@ -41,6 +41,7 @@ pub struct Engine {
|
||||
// Recording state
|
||||
recording_state: Option<RecordingState>,
|
||||
input_rx: Option<rtrb::Consumer<f32>>,
|
||||
recording_progress_counter: usize,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
@@ -74,6 +75,7 @@ impl Engine {
|
||||
next_clip_id: 0,
|
||||
recording_state: None,
|
||||
input_rx: None,
|
||||
recording_progress_counter: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,22 +219,24 @@ impl Engine {
|
||||
// Add samples to recording
|
||||
if !samples.is_empty() {
|
||||
match recording.add_samples(&samples) {
|
||||
Ok(flushed) => {
|
||||
if flushed {
|
||||
// A flush occurred, update clip duration and send progress event
|
||||
let duration = recording.duration();
|
||||
let clip_id = recording.clip_id;
|
||||
let track_id = recording.track_id;
|
||||
Ok(_flushed) => {
|
||||
// Update clip duration every callback for sample-accurate timing
|
||||
let duration = recording.duration();
|
||||
let clip_id = recording.clip_id;
|
||||
let track_id = recording.track_id;
|
||||
|
||||
// Update clip duration in project
|
||||
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.duration = duration;
|
||||
}
|
||||
// Update clip duration in project
|
||||
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.duration = duration;
|
||||
}
|
||||
}
|
||||
|
||||
// Send progress event
|
||||
// Send progress event periodically (every ~0.1 seconds)
|
||||
self.recording_progress_counter += samples.len();
|
||||
if self.recording_progress_counter >= (self.sample_rate as usize / 10) {
|
||||
let _ = self.event_tx.push(AudioEvent::RecordingProgress(clip_id, duration));
|
||||
self.recording_progress_counter = 0;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -708,7 +712,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
// Create recording state
|
||||
let flush_interval_seconds = 5.0; // Flush every 5 seconds
|
||||
let flush_interval_seconds = 1.0; // Flush every 1 second (safer than 5 seconds)
|
||||
let recording_state = RecordingState::new(
|
||||
track_id,
|
||||
clip_id,
|
||||
@@ -720,7 +724,23 @@ impl Engine {
|
||||
flush_interval_seconds,
|
||||
);
|
||||
|
||||
// Check how many samples are currently in the input buffer and mark them for skipping
|
||||
let samples_in_buffer = if let Some(input_rx) = &self.input_rx {
|
||||
input_rx.slots() // Number of samples currently in the buffer
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
self.recording_state = Some(recording_state);
|
||||
self.recording_progress_counter = 0; // Reset progress counter
|
||||
|
||||
// Set the number of samples to skip on the recording state
|
||||
if let Some(recording) = &mut self.recording_state {
|
||||
recording.samples_to_skip = samples_in_buffer;
|
||||
if samples_in_buffer > 0 {
|
||||
eprintln!("Will skip {} stale samples from input buffer", samples_in_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// Notify UI that recording has started
|
||||
let _ = self.event_tx.push(AudioEvent::RecordingStarted(track_id, clip_id));
|
||||
@@ -747,11 +767,19 @@ impl Engine {
|
||||
let track_id = recording.track_id;
|
||||
|
||||
// Finalize the recording and get temp file path
|
||||
let frames_recorded = recording.frames_written;
|
||||
match recording.finalize() {
|
||||
Ok(temp_file_path) => {
|
||||
eprintln!("Recording finalized: {} frames written to {:?}", frames_recorded, temp_file_path);
|
||||
|
||||
// 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
|
||||
let pool_file = crate::audio::pool::AudioFile::new(
|
||||
temp_file_path.clone(),
|
||||
@@ -772,8 +800,8 @@ impl Engine {
|
||||
// Delete temp file
|
||||
let _ = std::fs::remove_file(&temp_file_path);
|
||||
|
||||
// Notify UI that recording has stopped
|
||||
let _ = self.event_tx.push(AudioEvent::RecordingStopped(clip_id, pool_index));
|
||||
// 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
|
||||
|
||||
@@ -27,6 +27,8 @@ pub struct RecordingState {
|
||||
pub flush_interval_frames: usize,
|
||||
/// Whether recording is currently paused
|
||||
pub paused: bool,
|
||||
/// Number of samples remaining to skip (to discard stale buffer data)
|
||||
pub samples_to_skip: usize,
|
||||
}
|
||||
|
||||
impl RecordingState {
|
||||
@@ -55,6 +57,7 @@ impl RecordingState {
|
||||
buffer: Vec::new(),
|
||||
flush_interval_frames,
|
||||
paused: false,
|
||||
samples_to_skip: 0, // Will be set by engine when it knows buffer size
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +68,21 @@ impl RecordingState {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
self.buffer.extend_from_slice(samples);
|
||||
// Skip stale samples from the buffer
|
||||
if self.samples_to_skip > 0 {
|
||||
let to_skip = self.samples_to_skip.min(samples.len());
|
||||
self.samples_to_skip -= to_skip;
|
||||
|
||||
if to_skip == samples.len() {
|
||||
// Skip entire batch
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Skip partial batch and process the rest
|
||||
self.buffer.extend_from_slice(&samples[to_skip..]);
|
||||
} else {
|
||||
self.buffer.extend_from_slice(samples);
|
||||
}
|
||||
|
||||
// Check if we should flush
|
||||
let frames_in_buffer = self.buffer.len() / self.channels as usize;
|
||||
@@ -97,8 +114,11 @@ impl RecordingState {
|
||||
}
|
||||
|
||||
/// Get current recording duration in seconds
|
||||
/// Includes both flushed frames and buffered frames
|
||||
pub fn duration(&self) -> f64 {
|
||||
self.frames_written as f64 / self.sample_rate as f64
|
||||
let buffered_frames = self.buffer.len() / self.channels as usize;
|
||||
let total_frames = self.frames_written + buffered_frames;
|
||||
total_frames as f64 / self.sample_rate as f64
|
||||
}
|
||||
|
||||
/// Finalize the recording and return the temp file path
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::audio::{
|
||||
TrackId,
|
||||
};
|
||||
use crate::audio::buffer_pool::BufferPoolStats;
|
||||
use crate::io::WaveformPeak;
|
||||
|
||||
/// Commands sent from UI/control thread to audio thread
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -132,8 +133,8 @@ pub enum AudioEvent {
|
||||
RecordingStarted(TrackId, ClipId),
|
||||
/// Recording progress update (clip_id, current_duration)
|
||||
RecordingProgress(ClipId, f64),
|
||||
/// Recording stopped (clip_id, pool_index)
|
||||
RecordingStopped(ClipId, usize),
|
||||
/// Recording stopped (clip_id, pool_index, waveform)
|
||||
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
|
||||
/// Recording error (error_message)
|
||||
RecordingError(String),
|
||||
/// Project has been reset
|
||||
|
||||
@@ -64,17 +64,26 @@ impl WavWriter {
|
||||
|
||||
// Calculate total data size
|
||||
let data_size = self.frames_written * self.channels as usize * 2; // 2 bytes per sample (16-bit)
|
||||
let file_size = 36 + data_size; // 36 = size of header before data
|
||||
|
||||
// WAV file structure:
|
||||
// RIFF header (12 bytes): "RIFF" + size + "WAVE"
|
||||
// fmt chunk (24 bytes): "fmt " + size + format data
|
||||
// data chunk header (8 bytes): "data" + size
|
||||
// Total header = 44 bytes
|
||||
// RIFF chunk size = everything after offset 8 = 4 (WAVE) + 24 (fmt) + 8 (data header) + data_size
|
||||
let riff_chunk_size = 36 + data_size; // 36 = size from "WAVE" to end of data chunk header
|
||||
|
||||
// Seek to RIFF chunk size (offset 4)
|
||||
self.file.seek(SeekFrom::Start(4))?;
|
||||
self.file.write_all(&((file_size - 8) as u32).to_le_bytes())?;
|
||||
self.file.write_all(&(riff_chunk_size as u32).to_le_bytes())?;
|
||||
|
||||
// Seek to data chunk size (offset 40)
|
||||
self.file.seek(SeekFrom::Start(40))?;
|
||||
self.file.write_all(&(data_size as u32).to_le_bytes())?;
|
||||
|
||||
// Flush and sync to ensure all data is written to disk before file is closed
|
||||
self.file.flush()?;
|
||||
self.file.sync_all()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -84,11 +93,14 @@ impl WavWriter {
|
||||
fn write_wav_header(file: &mut File, sample_rate: u32, channels: u32, frames: usize) -> io::Result<()> {
|
||||
let bytes_per_sample = 2u16; // 16-bit PCM
|
||||
let data_size = (frames * channels as usize * bytes_per_sample as usize) as u32;
|
||||
let file_size = 36 + data_size;
|
||||
|
||||
// RIFF chunk size = everything after offset 8
|
||||
// = 4 (WAVE) + 24 (fmt chunk) + 8 (data chunk header) + data_size
|
||||
let riff_chunk_size = 36 + data_size;
|
||||
|
||||
// RIFF header
|
||||
file.write_all(b"RIFF")?;
|
||||
file.write_all(&(file_size - 8).to_le_bytes())?;
|
||||
file.write_all(&riff_chunk_size.to_le_bytes())?;
|
||||
file.write_all(b"WAVE")?;
|
||||
|
||||
// fmt chunk
|
||||
|
||||
+81
-14
@@ -32,48 +32,115 @@ pub struct AudioSystem {
|
||||
}
|
||||
|
||||
impl AudioSystem {
|
||||
/// Initialize the audio system with default device
|
||||
/// Initialize the audio system with default input and output devices
|
||||
pub fn new() -> Result<Self, String> {
|
||||
let host = cpal::default_host();
|
||||
let device = host
|
||||
|
||||
// Get output device
|
||||
let output_device = host
|
||||
.default_output_device()
|
||||
.ok_or("No output device available")?;
|
||||
|
||||
let default_config = device.default_output_config().map_err(|e| e.to_string())?;
|
||||
let sample_rate = default_config.sample_rate().0;
|
||||
let channels = default_config.channels() as u32;
|
||||
let default_output_config = output_device.default_output_config().map_err(|e| e.to_string())?;
|
||||
let sample_rate = default_output_config.sample_rate().0;
|
||||
let channels = default_output_config.channels() as u32;
|
||||
|
||||
// Create queues
|
||||
let (command_tx, command_rx) = rtrb::RingBuffer::new(256);
|
||||
let (event_tx, event_rx) = rtrb::RingBuffer::new(256);
|
||||
|
||||
// Create input ringbuffer for recording (large buffer for audio samples)
|
||||
// Buffer size: 10 seconds of audio at 48kHz stereo = 48000 * 2 * 10 = 960000 samples
|
||||
let input_buffer_size = (sample_rate * channels * 10) as usize;
|
||||
let (mut input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
|
||||
// Create engine
|
||||
let mut engine = Engine::new(sample_rate, channels, command_rx, event_tx);
|
||||
engine.set_input_rx(input_rx);
|
||||
let controller = engine.get_controller(command_tx);
|
||||
|
||||
// Build stream
|
||||
let config: cpal::StreamConfig = default_config.clone().into();
|
||||
let mut buffer = vec![0.0f32; 16384];
|
||||
// Build output stream
|
||||
let output_config: cpal::StreamConfig = default_output_config.clone().into();
|
||||
let mut output_buffer = vec![0.0f32; 16384];
|
||||
|
||||
let stream = device
|
||||
let output_stream = output_device
|
||||
.build_output_stream(
|
||||
&config,
|
||||
&output_config,
|
||||
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
||||
let buf = &mut buffer[..data.len()];
|
||||
let buf = &mut output_buffer[..data.len()];
|
||||
buf.fill(0.0);
|
||||
engine.process(buf);
|
||||
data.copy_from_slice(buf);
|
||||
},
|
||||
|err| eprintln!("Stream error: {}", err),
|
||||
|err| eprintln!("Output stream error: {}", err),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
stream.play().map_err(|e| e.to_string())?;
|
||||
// Get input device
|
||||
let input_device = match host.default_input_device() {
|
||||
Some(device) => device,
|
||||
None => {
|
||||
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())?;
|
||||
return Ok(Self {
|
||||
controller,
|
||||
stream: output_stream,
|
||||
event_rx,
|
||||
sample_rate,
|
||||
channels,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Get input config matching output sample rate and channels if possible
|
||||
let input_config = match input_device.default_input_config() {
|
||||
Ok(config) => {
|
||||
let mut cfg: cpal::StreamConfig = config.into();
|
||||
// Try to match output sample rate and channels
|
||||
cfg.sample_rate = cpal::SampleRate(sample_rate);
|
||||
cfg.channels = channels as u16;
|
||||
cfg
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Warning: Could not get input config: {}, recording will be disabled", e);
|
||||
output_stream.play().map_err(|e| e.to_string())?;
|
||||
return Ok(Self {
|
||||
controller,
|
||||
stream: output_stream,
|
||||
event_rx,
|
||||
sample_rate,
|
||||
channels,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Build input stream that feeds into the ringbuffer
|
||||
let input_stream = input_device
|
||||
.build_input_stream(
|
||||
&input_config,
|
||||
move |data: &[f32], _: &cpal::InputCallbackInfo| {
|
||||
// Push input samples to ringbuffer for recording
|
||||
for &sample in data {
|
||||
let _ = input_tx.push(sample);
|
||||
}
|
||||
},
|
||||
|err| eprintln!("Input stream error: {}", err),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Start both streams
|
||||
output_stream.play().map_err(|e| e.to_string())?;
|
||||
input_stream.play().map_err(|e| e.to_string())?;
|
||||
|
||||
// Leak the input stream to keep it alive
|
||||
Box::leak(Box::new(input_stream));
|
||||
|
||||
Ok(Self {
|
||||
controller,
|
||||
stream,
|
||||
stream: output_stream,
|
||||
event_rx,
|
||||
sample_rate,
|
||||
channels,
|
||||
|
||||
@@ -254,7 +254,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
print!("Recording clip {}: {:.2}s", clip_id, duration);
|
||||
io::stdout().flush().ok();
|
||||
}
|
||||
AudioEvent::RecordingStopped(clip_id, pool_index) => {
|
||||
AudioEvent::RecordingStopped(clip_id, pool_index, _waveform) => {
|
||||
print!("\r\x1b[K");
|
||||
println!("Recording stopped (clip {}, pool index {})", clip_id, pool_index);
|
||||
print!("> ");
|
||||
|
||||
Reference in New Issue
Block a user