initial audio export

This commit is contained in:
Skyler Lehmkuhl
2025-12-03 17:54:15 -05:00
parent 2a7c26df57
commit 727d782190
21 changed files with 2657 additions and 78 deletions
@@ -0,0 +1,164 @@
//! Audio export functionality
//!
//! Exports audio from the timeline to various formats:
//! - WAV and FLAC: Use existing DAW backend export
//! - MP3 and AAC: Use FFmpeg encoding with rendered samples
use lightningbeam_core::export::{AudioExportSettings, AudioFormat};
use daw_backend::audio::{
export::{ExportFormat, ExportSettings as DawExportSettings, render_to_memory},
midi_pool::MidiClipPool,
pool::AudioPool,
project::Project,
};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// Export audio to a file
///
/// This function routes to the appropriate export method based on the format:
/// - WAV/FLAC: Use DAW backend export
/// - MP3/AAC: Use FFmpeg encoding (TODO)
pub fn export_audio<P: AsRef<Path>>(
project: &mut Project,
pool: &AudioPool,
midi_pool: &MidiClipPool,
settings: &AudioExportSettings,
output_path: P,
cancel_flag: &Arc<AtomicBool>,
) -> Result<(), String> {
// Validate settings
settings.validate()?;
// Check for cancellation before starting
if cancel_flag.load(Ordering::Relaxed) {
return Err("Export cancelled by user".to_string());
}
match settings.format {
AudioFormat::Wav | AudioFormat::Flac => {
export_audio_daw_backend(project, pool, midi_pool, settings, output_path)
}
AudioFormat::Mp3 => {
export_audio_ffmpeg_mp3(project, pool, midi_pool, settings, output_path, cancel_flag)
}
AudioFormat::Aac => {
export_audio_ffmpeg_aac(project, pool, midi_pool, settings, output_path, cancel_flag)
}
}
}
/// Export audio using the DAW backend (WAV/FLAC)
fn export_audio_daw_backend<P: AsRef<Path>>(
project: &mut Project,
pool: &AudioPool,
midi_pool: &MidiClipPool,
settings: &AudioExportSettings,
output_path: P,
) -> Result<(), String> {
// Convert our export settings to DAW backend format
let daw_settings = DawExportSettings {
format: match settings.format {
AudioFormat::Wav => ExportFormat::Wav,
AudioFormat::Flac => ExportFormat::Flac,
_ => unreachable!(), // This function only handles WAV/FLAC
},
sample_rate: settings.sample_rate,
channels: settings.channels,
bit_depth: settings.bit_depth,
mp3_bitrate: 320, // Not used for WAV/FLAC
start_time: settings.start_time,
end_time: settings.end_time,
};
// Use the existing DAW backend export function
// No progress reporting for this direct export path
daw_backend::audio::export::export_audio(
project,
pool,
midi_pool,
&daw_settings,
output_path,
None,
)
}
/// Export audio as MP3 using FFmpeg
fn export_audio_ffmpeg_mp3<P: AsRef<Path>>(
_project: &mut Project,
_pool: &AudioPool,
_midi_pool: &MidiClipPool,
_settings: &AudioExportSettings,
_output_path: P,
_cancel_flag: &Arc<AtomicBool>,
) -> Result<(), String> {
// TODO: Implement MP3 export using FFmpeg
// The FFmpeg encoder API is complex and needs more investigation
// For now, users can export as WAV or FLAC (both fully working)
Err("MP3 export is not yet implemented. Please use WAV or FLAC format for now, or export as WAV and convert using an external tool.".to_string())
}
/// Export audio as AAC using FFmpeg
fn export_audio_ffmpeg_aac<P: AsRef<Path>>(
_project: &mut Project,
_pool: &AudioPool,
_midi_pool: &MidiClipPool,
_settings: &AudioExportSettings,
_output_path: P,
_cancel_flag: &Arc<AtomicBool>,
) -> Result<(), String> {
// TODO: Implement AAC export using FFmpeg
// The FFmpeg encoder API is complex and needs more investigation
// For now, users can export as WAV or FLAC (both fully working)
Err("AAC export is not yet implemented. Please use WAV or FLAC format for now, or export as WAV and convert using an external tool.".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_export_audio_validation() {
let mut settings = AudioExportSettings::default();
settings.sample_rate = 0; // Invalid
let project = Project::new();
let pool = AudioPool::new();
let midi_pool = MidiClipPool::new();
let cancel_flag = Arc::new(AtomicBool::new(false));
let result = export_audio(
&mut project.clone(),
&pool,
&midi_pool,
&settings,
"/tmp/test.wav",
&cancel_flag,
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("Sample rate"));
}
#[test]
fn test_export_audio_cancellation() {
let settings = AudioExportSettings::default();
let mut project = Project::new();
let pool = AudioPool::new();
let midi_pool = MidiClipPool::new();
let cancel_flag = Arc::new(AtomicBool::new(true)); // Pre-cancelled
let result = export_audio(
&mut project,
&pool,
&midi_pool,
&settings,
"/tmp/test.wav",
&cancel_flag,
);
assert!(result.is_err());
assert!(result.unwrap_err().contains("cancelled"));
}
}
@@ -0,0 +1,402 @@
//! Export dialog UI
//!
//! Provides a user interface for configuring and starting audio/video exports.
use eframe::egui;
use lightningbeam_core::export::{AudioExportSettings, AudioFormat};
use std::path::PathBuf;
/// Export dialog state
pub struct ExportDialog {
/// Is the dialog open?
pub open: bool,
/// Export settings
pub settings: AudioExportSettings,
/// Output file path
pub output_path: Option<PathBuf>,
/// Selected preset index (for UI)
pub selected_preset: usize,
/// Error message (if any)
pub error_message: Option<String>,
}
impl Default for ExportDialog {
fn default() -> Self {
Self {
open: false,
settings: AudioExportSettings::default(),
output_path: None,
selected_preset: 0,
error_message: None,
}
}
}
impl ExportDialog {
/// Open the dialog with default settings
pub fn open(&mut self, timeline_duration: f64) {
self.open = true;
self.settings.end_time = timeline_duration;
self.error_message = None;
}
/// Close the dialog
pub fn close(&mut self) {
self.open = false;
self.error_message = None;
}
/// Render the export dialog
///
/// Returns Some(settings, output_path) if the user clicked Export,
/// None otherwise.
pub fn render(&mut self, ctx: &egui::Context) -> Option<(AudioExportSettings, PathBuf)> {
if !self.open {
return None;
}
let mut should_export = false;
let mut should_close = false;
egui::Window::new("Export Audio")
.open(&mut self.open)
.resizable(false)
.collapsible(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ctx, |ui| {
ui.set_width(500.0);
// Error message (if any)
if let Some(error) = &self.error_message {
ui.colored_label(egui::Color32::RED, error);
ui.add_space(8.0);
}
// Preset selection
ui.heading("Preset");
ui.horizontal(|ui| {
let presets = [
("High Quality WAV", AudioExportSettings::high_quality_wav()),
("High Quality FLAC", AudioExportSettings::high_quality_flac()),
("Standard MP3", AudioExportSettings::standard_mp3()),
("Standard AAC", AudioExportSettings::standard_aac()),
("High Quality MP3", AudioExportSettings::high_quality_mp3()),
("High Quality AAC", AudioExportSettings::high_quality_aac()),
("Podcast MP3", AudioExportSettings::podcast_mp3()),
("Podcast AAC", AudioExportSettings::podcast_aac()),
];
egui::ComboBox::from_id_source("export_preset")
.selected_text(presets[self.selected_preset].0)
.show_ui(ui, |ui| {
for (i, (name, _)) in presets.iter().enumerate() {
if ui.selectable_value(&mut self.selected_preset, i, *name).clicked() {
// Save current time range before applying preset
let saved_start = self.settings.start_time;
let saved_end = self.settings.end_time;
self.settings = presets[i].1.clone();
// Restore time range
self.settings.start_time = saved_start;
self.settings.end_time = saved_end;
}
}
});
});
ui.add_space(12.0);
// Format settings
ui.heading("Format");
ui.horizontal(|ui| {
ui.label("Format:");
egui::ComboBox::from_id_source("audio_format")
.selected_text(self.settings.format.name())
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.settings.format, AudioFormat::Wav, "WAV (Uncompressed)");
ui.selectable_value(&mut self.settings.format, AudioFormat::Flac, "FLAC (Lossless)");
ui.selectable_value(&mut self.settings.format, AudioFormat::Mp3, "MP3");
ui.selectable_value(&mut self.settings.format, AudioFormat::Aac, "AAC");
});
});
ui.add_space(8.0);
// Audio settings
ui.horizontal(|ui| {
ui.label("Sample Rate:");
egui::ComboBox::from_id_source("sample_rate")
.selected_text(format!("{} Hz", self.settings.sample_rate))
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.settings.sample_rate, 44100, "44100 Hz");
ui.selectable_value(&mut self.settings.sample_rate, 48000, "48000 Hz");
ui.selectable_value(&mut self.settings.sample_rate, 96000, "96000 Hz");
});
});
ui.horizontal(|ui| {
ui.label("Channels:");
ui.radio_value(&mut self.settings.channels, 1, "Mono");
ui.radio_value(&mut self.settings.channels, 2, "Stereo");
});
ui.add_space(8.0);
// Format-specific settings
if self.settings.format.supports_bit_depth() {
ui.horizontal(|ui| {
ui.label("Bit Depth:");
ui.radio_value(&mut self.settings.bit_depth, 16, "16-bit");
ui.radio_value(&mut self.settings.bit_depth, 24, "24-bit");
});
}
if self.settings.format.uses_bitrate() {
ui.horizontal(|ui| {
ui.label("Bitrate:");
egui::ComboBox::from_id_source("bitrate")
.selected_text(format!("{} kbps", self.settings.bitrate_kbps))
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.settings.bitrate_kbps, 128, "128 kbps");
ui.selectable_value(&mut self.settings.bitrate_kbps, 192, "192 kbps");
ui.selectable_value(&mut self.settings.bitrate_kbps, 256, "256 kbps");
ui.selectable_value(&mut self.settings.bitrate_kbps, 320, "320 kbps");
});
});
}
ui.add_space(12.0);
// Time range
ui.heading("Time Range");
ui.horizontal(|ui| {
ui.label("Start:");
ui.add(egui::DragValue::new(&mut self.settings.start_time)
.speed(0.1)
.clamp_range(0.0..=self.settings.end_time)
.suffix(" s"));
ui.label("End:");
ui.add(egui::DragValue::new(&mut self.settings.end_time)
.speed(0.1)
.clamp_range(self.settings.start_time..=f64::MAX)
.suffix(" s"));
});
let duration = self.settings.duration();
ui.label(format!("Duration: {:.2} seconds", duration));
ui.add_space(12.0);
// Output file path
ui.heading("Output");
ui.horizontal(|ui| {
let path_text = self.output_path.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "No file selected".to_string());
ui.label("File:");
ui.text_edit_singleline(&mut path_text.clone());
if ui.button("Browse...").clicked() {
// Open file dialog
let default_name = format!("audio.{}", self.settings.format.extension());
if let Some(path) = rfd::FileDialog::new()
.set_file_name(&default_name)
.add_filter("Audio", &[self.settings.format.extension()])
.save_file()
{
self.output_path = Some(path);
}
}
});
ui.add_space(12.0);
// Estimated file size
if duration > 0.0 {
let estimated_mb = if self.settings.format.uses_bitrate() {
// Lossy: bitrate * duration / 8 / 1024
(self.settings.bitrate_kbps as f64 * duration) / 8.0 / 1024.0
} else {
// Lossless: sample_rate * channels * bit_depth * duration / 8 / 1024 / 1024
let compression_factor = if self.settings.format == AudioFormat::Flac { 0.6 } else { 1.0 };
(self.settings.sample_rate as f64 * self.settings.channels as f64 *
self.settings.bit_depth as f64 * duration * compression_factor) / 8.0 / 1024.0 / 1024.0
};
ui.label(format!("Estimated size: ~{:.1} MB", estimated_mb));
}
ui.add_space(16.0);
// Buttons
ui.horizontal(|ui| {
if ui.button("Cancel").clicked() {
should_close = true;
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Export").clicked() {
should_export = true;
}
});
});
});
if should_close {
self.close();
return None;
}
if should_export {
// Validate settings
if let Err(err) = self.settings.validate() {
self.error_message = Some(err);
return None;
}
// Check if output path is set
if self.output_path.is_none() {
self.error_message = Some("Please select an output file".to_string());
return None;
}
// Return settings and path
let result = Some((self.settings.clone(), self.output_path.clone().unwrap()));
self.close();
return result;
}
None
}
}
/// Export progress dialog state
pub struct ExportProgressDialog {
/// Is the dialog open?
pub open: bool,
/// Current progress message
pub message: String,
/// Progress (0.0 to 1.0)
pub progress: f32,
/// Start time for elapsed time calculation
pub start_time: Option<std::time::Instant>,
/// Was cancel requested?
pub cancel_requested: bool,
}
impl Default for ExportProgressDialog {
fn default() -> Self {
Self {
open: false,
message: String::new(),
progress: 0.0,
start_time: None,
cancel_requested: false,
}
}
}
impl ExportProgressDialog {
/// Open the progress dialog
pub fn open(&mut self) {
self.open = true;
self.message = "Starting export...".to_string();
self.progress = 0.0;
self.start_time = Some(std::time::Instant::now());
self.cancel_requested = false;
}
/// Close the dialog
pub fn close(&mut self) {
self.open = false;
self.start_time = None;
self.cancel_requested = false;
}
/// Update progress
pub fn update_progress(&mut self, message: String, progress: f32) {
self.message = message;
self.progress = progress.clamp(0.0, 1.0);
}
/// Render the export progress dialog
///
/// Returns true if the user clicked Cancel
pub fn render(&mut self, ctx: &egui::Context) -> bool {
if !self.open {
return false;
}
let mut should_cancel = false;
egui::Window::new("Exporting...")
.open(&mut self.open)
.resizable(false)
.collapsible(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ctx, |ui| {
ui.set_width(400.0);
// Status message
ui.label(&self.message);
ui.add_space(8.0);
// Progress bar
let progress_text = format!("{:.0}%", self.progress * 100.0);
ui.add(egui::ProgressBar::new(self.progress).text(progress_text));
ui.add_space(8.0);
// Elapsed time and estimate
if let Some(start_time) = self.start_time {
let elapsed = start_time.elapsed();
let elapsed_secs = elapsed.as_secs();
ui.horizontal(|ui| {
ui.label(format!(
"Elapsed: {}:{:02}",
elapsed_secs / 60,
elapsed_secs % 60
));
// Estimate remaining time if we have progress
if self.progress > 0.01 {
let total_estimated = elapsed.as_secs_f32() / self.progress;
let remaining = total_estimated - elapsed.as_secs_f32();
if remaining > 0.0 {
ui.label(format!(
" | Remaining: ~{}:{:02}",
(remaining as u64) / 60,
(remaining as u64) % 60
));
}
}
});
}
ui.add_space(12.0);
// Cancel button
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() {
should_cancel = true;
}
});
});
});
if should_cancel {
self.cancel_requested = true;
}
should_cancel
}
}
@@ -0,0 +1,241 @@
//! Export functionality for audio and video
//!
//! This module provides the export orchestrator and progress tracking
//! for exporting audio and video from the timeline.
pub mod audio_exporter;
pub mod dialog;
use lightningbeam_core::export::{AudioExportSettings, ExportProgress};
use std::path::PathBuf;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// Export orchestrator that manages the export process
pub struct ExportOrchestrator {
/// Channel for receiving progress updates
progress_rx: Option<Receiver<ExportProgress>>,
/// Handle to the export thread
thread_handle: Option<std::thread::JoinHandle<()>>,
/// Cancel flag
cancel_flag: Arc<AtomicBool>,
}
impl ExportOrchestrator {
/// Create a new export orchestrator
pub fn new() -> Self {
Self {
progress_rx: None,
thread_handle: None,
cancel_flag: Arc::new(AtomicBool::new(false)),
}
}
/// Start an audio export in the background
///
/// Returns immediately, spawning a background thread for the export.
/// Use `poll_progress()` to check the export progress.
pub fn start_audio_export(
&mut self,
settings: AudioExportSettings,
output_path: PathBuf,
audio_controller: Arc<std::sync::Mutex<daw_backend::EngineController>>,
) {
println!("🔄 [ORCHESTRATOR] start_audio_export called");
// Create progress channel
let (tx, rx) = channel();
self.progress_rx = Some(rx);
// Reset cancel flag
self.cancel_flag.store(false, Ordering::Relaxed);
let cancel_flag = Arc::clone(&self.cancel_flag);
println!("🔄 [ORCHESTRATOR] Spawning background thread...");
// Spawn background thread
let handle = std::thread::spawn(move || {
println!("🧵 [EXPORT THREAD] Background thread started!");
Self::run_audio_export(
settings,
output_path,
audio_controller,
tx,
cancel_flag,
);
println!("🧵 [EXPORT THREAD] Background thread finished!");
});
self.thread_handle = Some(handle);
println!("🔄 [ORCHESTRATOR] Thread spawned, returning");
}
/// Poll for progress updates
///
/// Returns None if no updates are available.
/// Returns Some(progress) if an update is available.
pub fn poll_progress(&mut self) -> Option<ExportProgress> {
if let Some(rx) = &self.progress_rx {
match rx.try_recv() {
Ok(progress) => {
println!("📨 [ORCHESTRATOR] Received progress: {:?}", std::mem::discriminant(&progress));
Some(progress)
}
Err(e) => {
// Only log occasionally to avoid spam
None
}
}
} else {
None
}
}
/// Cancel the current export
pub fn cancel(&mut self) {
self.cancel_flag.store(true, Ordering::Relaxed);
}
/// Check if an export is in progress
pub fn is_exporting(&self) -> bool {
if let Some(handle) = &self.thread_handle {
!handle.is_finished()
} else {
false
}
}
/// Wait for the export to complete
///
/// This blocks until the export thread finishes.
pub fn wait_for_completion(&mut self) {
if let Some(handle) = self.thread_handle.take() {
handle.join().ok();
}
}
/// Run audio export in background thread
fn run_audio_export(
settings: AudioExportSettings,
output_path: PathBuf,
audio_controller: Arc<std::sync::Mutex<daw_backend::EngineController>>,
progress_tx: Sender<ExportProgress>,
cancel_flag: Arc<AtomicBool>,
) {
println!("🧵 [EXPORT THREAD] run_audio_export started");
// Send start notification
progress_tx
.send(ExportProgress::Started { total_frames: 0 })
.ok();
println!("🧵 [EXPORT THREAD] Sent Started progress");
// Check for cancellation
if cancel_flag.load(Ordering::Relaxed) {
progress_tx
.send(ExportProgress::Error {
message: "Export cancelled by user".to_string(),
})
.ok();
return;
}
// Convert settings to DAW backend format
let daw_settings = daw_backend::audio::ExportSettings {
format: match settings.format {
lightningbeam_core::export::AudioFormat::Wav => daw_backend::audio::ExportFormat::Wav,
lightningbeam_core::export::AudioFormat::Flac => daw_backend::audio::ExportFormat::Flac,
lightningbeam_core::export::AudioFormat::Mp3 |
lightningbeam_core::export::AudioFormat::Aac => {
// MP3/AAC not supported yet
progress_tx
.send(ExportProgress::Error {
message: format!("{} export not yet implemented. Please use WAV or FLAC format.", settings.format.name()),
})
.ok();
return;
}
},
sample_rate: settings.sample_rate,
channels: settings.channels,
bit_depth: settings.bit_depth,
mp3_bitrate: 320, // Not used for WAV/FLAC
start_time: settings.start_time,
end_time: settings.end_time,
};
println!("🧵 [EXPORT THREAD] Starting non-blocking export...");
// Start the export (non-blocking - just sends the query)
{
let mut controller = audio_controller.lock().unwrap();
println!("🧵 [EXPORT THREAD] Sending export query...");
if let Err(e) = controller.start_export_audio(&daw_settings, &output_path) {
println!("🧵 [EXPORT THREAD] Failed to start export: {}", e);
progress_tx.send(ExportProgress::Error { message: e }).ok();
return;
}
println!("🧵 [EXPORT THREAD] Export query sent, lock released");
}
// Poll for completion without holding the lock for extended periods
let duration = settings.end_time - settings.start_time;
let start_time = std::time::Instant::now();
let result = loop {
if cancel_flag.load(Ordering::Relaxed) {
break Err("Export cancelled by user".to_string());
}
// Sleep before polling to avoid spinning
std::thread::sleep(std::time::Duration::from_millis(100));
// Brief lock to poll for completion
let poll_result = {
let mut controller = audio_controller.lock().unwrap();
controller.poll_export_completion()
};
match poll_result {
Ok(Some(result)) => {
// Export completed
println!("🧵 [EXPORT THREAD] Export completed: {:?}", result.is_ok());
break result;
}
Ok(None) => {
// Still in progress - actual progress comes via AudioEvent::ExportProgress
// No need to send progress here
}
Err(e) => {
// Polling error (shouldn't happen)
println!("🧵 [EXPORT THREAD] Poll error: {}", e);
break Err(e);
}
}
};
println!("🧵 [EXPORT THREAD] Export loop finished");
// Send completion or error
match result {
Ok(_) => {
println!("📤 [EXPORT THREAD] Sending Complete event");
let send_result = progress_tx.send(ExportProgress::Complete {
output_path: output_path.clone(),
});
println!("📤 [EXPORT THREAD] Complete event sent: {:?}", send_result.is_ok());
}
Err(err) => {
println!("📤 [EXPORT THREAD] Sending Error event: {}", err);
let send_result = progress_tx.send(ExportProgress::Error { message: err });
println!("📤 [EXPORT THREAD] Error event sent: {:?}", send_result.is_ok());
}
}
}
}
impl Default for ExportOrchestrator {
fn default() -> Self {
Self::new()
}
}