Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
improve: stream MP4 export audio with bounded buffers and safe cancellation
Richie McIlroy07401a376545
diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rsindex 05d062323..908904dd8 100644--- a/apps/desktop-gpui/src/editor_export.rs+++ b/apps/desktop-gpui/src/editor_export.rs@@ -2171,8 +2171,22 @@ async fn run_export(builder = builder.with_output_path(path);}- let base = builder.build().await.map_err(|error| error.to_string())?;- let total = base.total_frames(fps);+ enum PreparedBase {+ Mp4(cap_export::Mp4ExporterBase),+ Other(ExporterBase),+ }+ let (base, total) = if !cursor_only && format != ExportFormatKind::Gif {+ let base = builder+ .build_for_mp4(cancel.clone())+ .await+ .map_err(|error| error.to_string())?;+ let total = base.total_frames(fps);+ (PreparedBase::Mp4(base), total)+ } else {+ let base = builder.build().await.map_err(|error| error.to_string())?;+ let total = base.total_frames(fps);+ (PreparedBase::Other(base), total)+ };let _ = progress_tx.send((0, total));let progress = {@@ -2189,33 +2203,37 @@ async fn run_export(};let resolution = XY::new(width, height);- if cursor_only {- MovExportSettings {- fps,- resolution_base: resolution,- cursor_only: true,+ match base {+ PreparedBase::Other(base) if cursor_only => {+ MovExportSettings {+ fps,+ resolution_base: resolution,+ cursor_only: true,+ }+ .export(base, progress)+ .await}- .export(base, progress)- .await- } else if format == ExportFormatKind::Gif {- GifExportSettings {- fps,- resolution_base: resolution,- quality: None,+ PreparedBase::Other(base) => {+ GifExportSettings {+ fps,+ resolution_base: resolution,+ quality: None,+ }+ .export(base, progress)+ .await}- .export(base, progress)- .await- } else {- Mp4ExportSettings {- fps,- resolution_base: resolution,- compression,- custom_bpp,- force_ffmpeg_decoder: force,- optimize_filesize: optimize,+ PreparedBase::Mp4(base) => {+ Mp4ExportSettings {+ fps,+ resolution_base: resolution,+ compression,+ custom_bpp,+ force_ffmpeg_decoder: force,+ optimize_filesize: optimize,+ }+ .export_prepared(base, progress)+ .await}- .export(base, progress)- .await}}diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rsindex 2a9c60e8b..f774c7252 100644--- a/crates/audio/src/lib.rs+++ b/crates/audio/src/lib.rs@@ -2,12 +2,14 @@ mod audio_data;mod calibration_store;mod latency;mod renderer;+mod streaming;mod sync_analysis;pub use audio_data::*;pub use calibration_store::*;pub use latency::*;pub use renderer::*;+pub use streaming::*;pub use sync_analysis::*;pub trait FromSampleBytes: cpal::SizedSample + std::fmt::Debug + Send + 'static {diff --git a/crates/audio/src/renderer.rs b/crates/audio/src/renderer.rsindex 89b935103..e6afb8230 100644--- a/crates/audio/src/renderer.rs+++ b/crates/audio/src/renderer.rs@@ -6,15 +6,35 @@ pub enum StereoMode {MonoR,}-pub struct AudioRendererTrack<'a> {- pub data: &'a AudioData,+pub trait AudioSampleSource {+ fn channels(&self) -> u16;+ fn sample_count(&self) -> usize;+ fn sample(&self, index: usize) -> Option<&f32>;+}++impl AudioSampleSource for AudioData {+ fn channels(&self) -> u16 {+ self.channels()+ }++ fn sample_count(&self) -> usize {+ self.samples().len() / self.channels() as usize+ }++ fn sample(&self, index: usize) -> Option<&f32> {+ self.samples().get(index)+ }+}++pub struct AudioRendererTrack<'a, T: AudioSampleSource = AudioData> {+ pub data: &'a T,pub gain: f32,pub stereo_mode: StereoMode,pub offset: isize,}-pub fn render_audio(- tracks: &[AudioRendererTrack],+pub fn render_audio<T: AudioSampleSource>(+ tracks: &[AudioRendererTrack<'_, T>],offset: usize,samples: usize,out_offset: usize,@@ -24,7 +44,7 @@ pub fn render_audio(tracks.iter().filter_map(|t| {- let track_samples = t.data.samples().len() / t.data.channels() as usize;+ let track_samples = t.data.sample_count();let available = track_samples as i128 - offset as i128 - t.offset as i128;if available > 0 {usize::try_from(available).ok()@@ -57,16 +77,16 @@ pub fn render_audio(}if data.channels() == 1 {- if let Some(sample) = data.samples().get(source_index) {+ if let Some(sample) = data.sample(source_index) {left += sample * 0.707 * gain;right += sample * 0.707 * gain;}} else if data.channels() == 2 {let base_idx = source_index.saturating_mul(2);- let Some(l_sample) = data.samples().get(base_idx) else {+ let Some(l_sample) = data.sample(base_idx) else {continue;};- let Some(r_sample) = data.samples().get(base_idx + 1) else {+ let Some(r_sample) = data.sample(base_idx + 1) else {continue;};diff --git a/crates/audio/src/streaming.rs b/crates/audio/src/streaming.rsnew file mode 100644index 000000000..39b0a73ea--- /dev/null+++ b/crates/audio/src/streaming.rs@@ -0,0 +1,693 @@+use ffmpeg::{ChannelLayout, Error, codec, format, frame::Audio, software::resampling};+use std::{+ ffi::{CString, c_int, c_void},+ fmt,+ path::Path,+ ptr,+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+};++const MAX_CHUNK_FRAMES: usize = 48_000;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AudioStreamError {+ pub stage: &'static str,+ pub detail: String,+ pub next_sample: u64,+}++impl AudioStreamError {+ pub fn is_cancelled(&self) -> bool {+ self.stage == "cancelled"+ }+}++impl fmt::Display for AudioStreamError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(+ formatter,+ "{} / {} / next={}",+ self.stage, self.detail, self.next_sample+ )+ }+}++impl std::error::Error for AudioStreamError {}++#[derive(Clone, Debug)]+struct Failure {+ stage: &'static str,+ detail: String,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Phase {+ NeedPacket,+ Receiving,+ Draining,+ Flushing,+ Complete,+}++#[derive(Debug)]+pub struct AudioChunk {+ pub source_start_sample: u64,+ pub channels: u16,+ pub samples: Vec<f32>,+}++#[derive(Debug)]+pub enum ChunkRead {+ Chunk(AudioChunk),+ Eof { next_sample: u64 },+}++pub struct AudioStream {+ input: format::context::Input,+ decoder: codec::decoder::Audio,+ resampler: resampling::Context,+ decoded_frame: Audio,+ stream_index: usize,+ channels: u16,+ phase: Phase,+ failure: Option<Failure>,+ pending: Vec<f32>,+ pending_offset: usize,+ position: u64,+ flush_iterations: usize,+ cancellation: Arc<StreamCancellation>,+}++struct StreamCancellation {+ user: Arc<AtomicBool>,+ abort: Option<Arc<AtomicBool>>,+}++impl StreamCancellation {+ fn is_cancelled(&self) -> bool {+ self.user.load(Ordering::Relaxed)+ || self+ .abort+ .as_ref()+ .is_some_and(|abort| abort.load(Ordering::Relaxed))+ }+}++impl AudioStream {+ pub fn open(path: &Path, cancellation: Arc<AtomicBool>) -> Result<Self, AudioStreamError> {+ Self::open_controlled(+ path,+ StreamCancellation {+ user: cancellation,+ abort: None,+ },+ )+ }++ pub fn open_with_abort(+ path: &Path,+ user: Arc<AtomicBool>,+ abort: Arc<AtomicBool>,+ ) -> Result<Self, AudioStreamError> {+ Self::open_controlled(+ path,+ StreamCancellation {+ user,+ abort: Some(abort),+ },+ )+ }++ fn open_controlled(+ path: &Path,+ cancellation: StreamCancellation,+ ) -> Result<Self, AudioStreamError> {+ let cancellation = Arc::new(cancellation);+ let at_open = |stage, detail: String| {+ if cancellation.is_cancelled() {+ cancelled_error(0)+ } else {+ AudioStreamError {+ stage,+ detail,+ next_sample: 0,+ }+ }+ };+ if cancellation.is_cancelled() {+ return Err(cancelled_error(0));+ }+ let input =+ open_input(path, &cancellation).map_err(|detail| at_open("input-open", detail))?;+ let stream = input+ .streams()+ .best(ffmpeg::media::Type::Audio)+ .ok_or_else(|| at_open("stream", "No Stream".to_string()))?;+ let stream_index = stream.index();+ let mut decoder = codec::Context::from_parameters(stream.parameters())+ .map_err(|e| at_open("decoder-parameters", e.to_string()))?+ .decoder()+ .audio()+ .map_err(|e| at_open("decoder-open", e.to_string()))?;+ let source_channels = decoder.channels().max(1);+ if decoder.channel_layout().is_empty() {+ decoder.set_channel_layout(ChannelLayout::default(source_channels as i32));+ }+ decoder.set_packet_time_base(stream.time_base());+ let channels = if source_channels <= 1 { 1 } else { 2 };+ let mut options = ffmpeg::Dictionary::new();+ options.set("filter_size", "128");+ options.set("cutoff", "0.97");+ let resampler = resampling::Context::get_with(+ decoder.format(),+ decoder.channel_layout(),+ decoder.rate(),+ crate::AudioData::SAMPLE_FORMAT,+ ChannelLayout::default(channels as i32),+ crate::AudioData::SAMPLE_RATE,+ options,+ )+ .map_err(|e| at_open("resampler-open", e.to_string()))?;+ if cancellation.is_cancelled() {+ return Err(cancelled_error(0));+ }+ Ok(Self {+ input,+ decoder,+ resampler,+ decoded_frame: Audio::empty(),+ stream_index,+ channels,+ phase: Phase::NeedPacket,+ failure: None,+ pending: Vec::new(),+ pending_offset: 0,+ position: 0,+ flush_iterations: 0,+ cancellation,+ })+ }++ pub fn channels(&self) -> u16 {+ self.channels+ }+ pub fn position(&self) -> u64 {+ self.position+ }++ pub fn read_chunk(&mut self, max_frames: usize) -> Result<ChunkRead, AudioStreamError> {+ if !(1..=MAX_CHUNK_FRAMES).contains(&max_frames) {+ return Err(AudioStreamError {+ stage: "request",+ detail: "Chunk size must be 1..=48000 frames".to_string(),+ next_sample: self.position,+ });+ }+ let max_samples = max_frames * self.channels as usize;+ let mut output = Vec::with_capacity(max_samples);+ while output.len() < max_samples {+ if self.failure.is_none() && self.cancellation.is_cancelled() {+ self.failure = Some(Failure {+ stage: "cancelled",+ detail: "Audio decoding cancelled".to_string(),+ });+ }+ if let Some(error) = self.failure.as_ref().filter(|e| e.stage == "cancelled") {+ return Err(AudioStreamError {+ stage: error.stage,+ detail: error.detail.clone(),+ next_sample: self.position,+ });+ }+ if self.pending_offset < self.pending.len() {+ let count =+ (max_samples - output.len()).min(self.pending.len() - self.pending_offset);+ output.extend_from_slice(+ &self.pending[self.pending_offset..self.pending_offset + count],+ );+ self.pending_offset += count;+ continue;+ }+ self.pending.clear();+ self.pending_offset = 0;+ if self.failure.is_some() || self.phase == Phase::Complete {+ break;+ }+ if let Err(error) = self.produce_pcm() {+ self.failure = Some(error);+ }+ }+ if !output.is_empty() {+ let source_start_sample = self.position;+ self.position += (output.len() / self.channels as usize) as u64;+ return Ok(ChunkRead::Chunk(AudioChunk {+ source_start_sample,+ channels: self.channels,+ samples: output,+ }));+ }+ if let Some(error) = &self.failure {+ return Err(AudioStreamError {+ stage: error.stage,+ detail: error.detail.clone(),+ next_sample: self.position,+ });+ }+ Ok(ChunkRead::Eof {+ next_sample: self.position,+ })+ }++ pub fn validate_to_end(&mut self) -> Result<u64, AudioStreamError> {+ loop {+ match self.read_chunk(MAX_CHUNK_FRAMES)? {+ ChunkRead::Chunk(_) => {}+ ChunkRead::Eof { next_sample } => return Ok(next_sample),+ }+ }+ }++ fn produce_pcm(&mut self) -> Result<(), Failure> {+ loop {+ if self.cancellation.is_cancelled() {+ return Err(Failure {+ stage: "cancelled",+ detail: "Audio decoding cancelled".to_string(),+ });+ }+ match self.phase {+ Phase::NeedPacket => {+ let mut packet = ffmpeg::Packet::empty();+ match packet.read(&mut self.input) {+ Ok(()) => {+ if packet.stream() != self.stream_index {+ continue;+ }+ self.decoder.send_packet(&packet).map_err(|e| Failure {+ stage: "send-packet",+ detail: e.to_string(),+ })?;+ self.phase = Phase::Receiving;+ }+ Err(Error::Eof) => {+ self.decoder.send_eof().map_err(|e| Failure {+ stage: "send-eof",+ detail: e.to_string(),+ })?;+ self.phase = Phase::Draining;+ }+ Err(_) => continue,+ }+ }+ Phase::Receiving | Phase::Draining => {+ match self.decoder.receive_frame(&mut self.decoded_frame) {+ Ok(()) => {+ run_resampler(+ &mut self.resampler,+ &self.decoded_frame,+ &mut self.pending,+ )+ .map_err(|e| Failure {+ stage: "resample",+ detail: e,+ })?;+ if !self.pending.is_empty() {+ return Ok(());+ }+ }+ Err(_) => {+ self.phase = if self.phase == Phase::Draining {+ Phase::Flushing+ } else {+ Phase::NeedPacket+ };+ }+ }+ }+ Phase::Flushing => {+ if self.flush_iterations == 64 {+ self.phase = Phase::Complete;+ return Ok(());+ }+ let Some(delay) = self.resampler.delay() else {+ self.phase = Phase::Complete;+ return Ok(());+ };+ let target = *self.resampler.output();+ let capacity = delay+ .output+ .max(1)+ .saturating_add(16)+ .min(i64::from(i32::MAX)) as usize;+ let mut frame = Audio::new(target.format, capacity, target.channel_layout);+ let remaining = self.resampler.flush(&mut frame).map_err(|error| Failure {+ stage: "flush",+ detail: format!("Flush Resampler / {error}"),+ })?;+ let output_samples = frame.samples();+ if output_samples > 0 {+ let byte_len = output_samples+ .saturating_mul(frame.channels() as usize)+ .saturating_mul(std::mem::size_of::<f32>());+ let bytes = frame.data(0).get(..byte_len).ok_or_else(|| Failure {+ stage: "flush",+ detail: "Resampled frame data shorter than expected".to_string(),+ })?;+ self.pending+ .extend(unsafe { crate::cast_bytes_to_f32_slice(bytes) });+ }+ self.flush_iterations += 1;+ if remaining.is_none() || output_samples == 0 {+ self.phase = Phase::Complete;+ }+ if !self.pending.is_empty() || self.phase == Phase::Complete {+ return Ok(());+ }+ }+ Phase::Complete => return Ok(()),+ }+ }+ }+}++fn cancelled_error(next_sample: u64) -> AudioStreamError {+ AudioStreamError {+ stage: "cancelled",+ detail: "Audio decoding cancelled".to_string(),+ next_sample,+ }+}++extern "C" fn interrupt_callback(opaque: *mut c_void) -> c_int {+ let cancellation = unsafe { &*opaque.cast::<StreamCancellation>() };+ c_int::from(cancellation.is_cancelled())+}++fn open_input(+ path: &Path,+ cancellation: &Arc<StreamCancellation>,+) -> Result<format::context::Input, String> {+ let path = path+ .to_str()+ .ok_or_else(|| "Input path is not UTF-8".to_string())?;+ let path = CString::new(path).map_err(|error| error.to_string())?;+ unsafe {+ let mut context = ffmpeg::ffi::avformat_alloc_context();+ if context.is_null() {+ return Err("Failed to allocate input context".to_string());+ }+ // The pinned input_with_interrupt leaks its boxed closure. This callback borrows+ // the stable Arc allocation, retained until after the input context is dropped.+ (*context).interrupt_callback = ffmpeg::ffi::AVIOInterruptCB {+ callback: Some(interrupt_callback),+ opaque: Arc::as_ptr(cancellation).cast_mut().cast(),+ };+ let opened = ffmpeg::ffi::avformat_open_input(+ &mut context,+ path.as_ptr(),+ ptr::null_mut(),+ ptr::null_mut(),+ );+ if opened < 0 {+ if !context.is_null() {+ ffmpeg::ffi::avformat_close_input(&mut context);+ }+ return Err(Error::from(opened).to_string());+ }+ let probed = ffmpeg::ffi::avformat_find_stream_info(context, ptr::null_mut());+ if probed < 0 {+ ffmpeg::ffi::avformat_close_input(&mut context);+ return Err(Error::from(probed).to_string());+ }+ Ok(format::context::Input::wrap(context))+ }+}++fn run_resampler(+ resampler: &mut resampling::Context,+ decoded_frame: &Audio,+ samples: &mut Vec<f32>,+) -> Result<(), String> {+ let target = *resampler.output();+ let capacity = resample_capacity(resampler, decoded_frame.samples());+ let mut frame = Audio::new(target.format, capacity, target.channel_layout);+ resampler+ .run(decoded_frame, &mut frame)+ .map_err(|error| format!("Run Resampler / {error}"))?;+ if frame.samples() == 0 {+ return Ok(());+ }+ let byte_len = frame+ .samples()+ .saturating_mul(frame.channels() as usize)+ .saturating_mul(std::mem::size_of::<f32>());+ let data = frame+ .data(0)+ .get(..byte_len)+ .ok_or_else(|| "Resampled frame data shorter than expected".to_string())?;+ samples.extend(unsafe { crate::cast_bytes_to_f32_slice(data) });+ Ok(())+}++fn resample_capacity(resampler: &resampling::Context, input_samples: usize) -> usize {+ let src_rate = resampler.input().rate.max(1) as u64;+ let dst_rate = resampler.output().rate.max(1) as u64;+ let pending_output_samples = resampler+ .delay()+ .map(|delay| delay.output.max(0) as u64)+ .unwrap_or(0);+ let resampled_from_input = (input_samples as u64)+ .saturating_mul(dst_rate)+ .div_ceil(src_rate);+ pending_output_samples+ .saturating_add(resampled_from_input)+ .saturating_add(16)+ .min(i32::MAX as u64) as usize+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ fn pcm_wav(rate: u32, channels: u16, frames: usize) -> tempfile::NamedTempFile {+ let data_size = (frames * usize::from(channels) * 2) as u32;+ let mut bytes = Vec::new();+ bytes.extend_from_slice(b"RIFF");+ bytes.extend_from_slice(&(36 + data_size).to_le_bytes());+ bytes.extend_from_slice(b"WAVEfmt ");+ bytes.extend_from_slice(&16u32.to_le_bytes());+ bytes.extend_from_slice(&1u16.to_le_bytes());+ bytes.extend_from_slice(&channels.to_le_bytes());+ bytes.extend_from_slice(&rate.to_le_bytes());+ bytes.extend_from_slice(&(rate * u32::from(channels) * 2).to_le_bytes());+ bytes.extend_from_slice(&(channels * 2).to_le_bytes());+ bytes.extend_from_slice(&16u16.to_le_bytes());+ bytes.extend_from_slice(b"data");+ bytes.extend_from_slice(&data_size.to_le_bytes());+ for index in 0..frames * usize::from(channels) {+ bytes.extend_from_slice(&((index % 20_001) as i16 - 10_000).to_le_bytes());+ }+ let mut file = tempfile::NamedTempFile::new().unwrap();+ file.write_all(&bytes).unwrap();+ file+ }++ #[test]+ fn chunks_preserve_full_decode_samples_and_repeated_eof() {+ fn assert_send<T: Send>() {}+ assert_send::<AudioStream>();+ for (rate, channels, frames) in [+ (8_000, 1, 1_201),+ (44_100, 2, 1_201),+ (96_000, 6, 1_201),+ (192_000, 2, 64),+ (48_000, 1, 0),+ ] {+ let file = pcm_wav(rate, channels, frames);+ let reference = crate::AudioData::from_file(file.path()).unwrap();+ for pattern in [+ &[1][..],+ &[7][..],+ &[997][..],+ &[12_000][..],+ &[48_000][..],+ &[1, 509, 12_000, 3, 47, 48_000][..],+ ] {+ let mut stream =+ AudioStream::open(file.path(), Arc::new(AtomicBool::new(false))).unwrap();+ let mut samples = Vec::new();+ let mut read_index = 0;+ loop {+ let max_frames = pattern[read_index % pattern.len()];+ read_index += 1;+ match stream.read_chunk(max_frames).unwrap() {+ ChunkRead::Chunk(chunk) => {+ assert_eq!(chunk.channels, reference.channels());+ assert_eq!(+ chunk.source_start_sample,+ (samples.len() / usize::from(chunk.channels)) as u64+ );+ assert!(+ chunk.samples.len() <= max_frames * usize::from(chunk.channels)+ );+ samples.extend(chunk.samples);+ assert_eq!(+ stream.position(),+ (samples.len() / usize::from(chunk.channels)) as u64+ );+ }+ ChunkRead::Eof { next_sample } => {+ assert_eq!(next_sample, reference.sample_count() as u64);+ assert_eq!(stream.validate_to_end().unwrap(), next_sample);+ assert!(+ matches!(stream.read_chunk(7).unwrap(), ChunkRead::Eof { next_sample: next } if next == next_sample)+ );+ break;+ }+ }+ }+ assert_eq!(samples.len(), reference.samples().len());+ assert!(+ samples+ .iter()+ .zip(reference.samples())+ .all(|(a, b)| a.to_bits() == b.to_bits())+ );+ }+ }+ }++ #[test]+ fn validation_drains_unread_tail() {+ let file = pcm_wav(44_100, 2, 10_001);+ let reference = crate::AudioData::from_file(file.path()).unwrap();+ let mut stream = AudioStream::open(file.path(), Arc::new(AtomicBool::new(false))).unwrap();+ assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));+ assert_eq!(stream.position(), 7);+ assert_eq!(+ stream.validate_to_end().unwrap(),+ reference.sample_count() as u64+ );+ assert_eq!(stream.position(), reference.sample_count() as u64);+ }++ #[test]+ fn cancellation_is_sticky_without_publishing_pending_samples() {+ let file = pcm_wav(48_000, 2, 10_001);+ let cancellation = Arc::new(AtomicBool::new(false));+ let mut stream = AudioStream::open(file.path(), cancellation.clone()).unwrap();+ assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));+ cancellation.store(true, Ordering::Relaxed);+ let error = stream.read_chunk(48_000).unwrap_err();+ assert!(error.is_cancelled());+ assert_eq!(error.next_sample, 7);+ assert_eq!(stream.position(), 7);+ cancellation.store(false, Ordering::Relaxed);+ assert_eq!(stream.read_chunk(1).unwrap_err(), error);+ assert_eq!(stream.validate_to_end().unwrap_err(), error);+ }++ #[test]+ fn terminal_failure_preserves_preceding_pcm() {+ let file = pcm_wav(48_000, 2, 10_001);+ let mut stream = AudioStream::open(file.path(), Arc::new(AtomicBool::new(false))).unwrap();+ stream.pending = vec![0.25, -0.25, 0.5, -0.5];+ stream.failure = Some(Failure {+ stage: "send-packet",+ detail: "injected failure".to_string(),+ });+ let ChunkRead::Chunk(chunk) = stream.read_chunk(48_000).unwrap() else {+ panic!("preceding PCM was discarded");+ };+ assert_eq!(chunk.source_start_sample, 0);+ assert_eq!(chunk.samples, [0.25, -0.25, 0.5, -0.5]);+ let error = stream.read_chunk(1).unwrap_err();+ assert_eq!(error.next_sample, 2);+ assert_eq!(stream.read_chunk(48_000).unwrap_err(), error);+ assert_eq!(stream.validate_to_end().unwrap_err(), error);+ }++ #[test]+ fn interrupt_ownership_releases_after_success_and_failure() {+ let file = pcm_wav(48_000, 1, 1_201);+ let cancellation = Arc::new(AtomicBool::new(false));+ for _ in 0..32 {+ let mut stream = AudioStream::open(file.path(), cancellation.clone()).unwrap();+ assert_eq!(Arc::strong_count(&cancellation), 2);+ let callback = unsafe { (*stream.input.as_mut_ptr()).interrupt_callback };+ assert_eq!(+ callback.opaque,+ Arc::as_ptr(&stream.cancellation).cast_mut().cast()+ );+ assert_eq!(unsafe { callback.callback.unwrap()(callback.opaque) }, 0);+ cancellation.store(true, Ordering::Relaxed);+ assert_eq!(unsafe { callback.callback.unwrap()(callback.opaque) }, 1);+ drop(stream);+ assert_eq!(Arc::strong_count(&cancellation), 1);+ cancellation.store(false, Ordering::Relaxed);+ let missing = file.path().with_extension("missing");+ assert!(AudioStream::open(&missing, cancellation.clone()).is_err());+ assert_eq!(Arc::strong_count(&cancellation), 1);+ }+ cancellation.store(true, Ordering::Relaxed);+ let error = AudioStream::open(file.path(), cancellation.clone())+ .err()+ .unwrap();+ assert!(error.is_cancelled());+ assert_eq!(Arc::strong_count(&cancellation), 1);+ }++ #[test]+ fn private_abort_needs_no_async_relay_and_preserves_user_flag() {+ let file = pcm_wav(48_000, 2, 10_001);+ let user = Arc::new(AtomicBool::new(false));+ let abort = Arc::new(AtomicBool::new(false));+ let runtime = tokio::runtime::Builder::new_current_thread()+ .build()+ .unwrap();+ runtime.block_on(async {+ let mut stream =+ AudioStream::open_with_abort(file.path(), user.clone(), abort.clone()).unwrap();+ assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));+ let callback = unsafe { (*stream.input.as_mut_ptr()).interrupt_callback };+ assert_eq!(unsafe { callback.callback.unwrap()(callback.opaque) }, 0);+ let worker_abort = abort.clone();+ std::thread::spawn(move || worker_abort.store(true, Ordering::Relaxed))+ .join()+ .unwrap();+ assert_eq!(unsafe { callback.callback.unwrap()(callback.opaque) }, 1);+ let error = stream.read_chunk(48_000).unwrap_err();+ assert!(error.is_cancelled());+ assert_eq!(error.next_sample, 7);+ assert!(!user.load(Ordering::Relaxed));+ abort.store(false, Ordering::Relaxed);+ assert_eq!(stream.read_chunk(1).unwrap_err(), error);+ drop(stream);+ assert_eq!(Arc::strong_count(&user), 1);+ assert_eq!(Arc::strong_count(&abort), 1);+ });+ abort.store(true, Ordering::Relaxed);+ let error = AudioStream::open_with_abort(file.path(), user.clone(), abort.clone())+ .err()+ .unwrap();+ assert!(error.is_cancelled());+ assert!(!user.load(Ordering::Relaxed));+ assert_eq!(Arc::strong_count(&user), 1);+ assert_eq!(Arc::strong_count(&abort), 1);+ }++ #[test]+ fn invalid_chunk_size_does_not_consume_audio() {+ let file = pcm_wav(48_000, 1, 1_201);+ let mut stream = AudioStream::open(file.path(), Arc::new(AtomicBool::new(false))).unwrap();+ for size in [0, 48_001, usize::MAX] {+ assert_eq!(stream.read_chunk(size).unwrap_err().stage, "request");+ assert_eq!(stream.position(), 0);+ }+ assert_eq!(stream.validate_to_end().unwrap(), 1_201);+ }+}diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rsindex 0a8ecdca8..8afa19927 100644--- a/crates/editor/src/audio.rs+++ b/crates/editor/src/audio.rs@@ -1,3 +1,4 @@+use crate::export_audio::{EXPORT_AUDIO_BLOCK_SAMPLES, ExportAudioError, ExportAudioSources};use cap_audio::{AudioData, AudioRendererTrack, FromSampleBytes, StereoMode, cast_bytes_to_f32_slice,cast_f32_slice_to_bytes,@@ -245,6 +246,182 @@ impl AudioRenderer {self.render_linear_frame_raw(samples, project)}+ pub(crate) fn render_export_chunks(+ &mut self,+ sources: &mut ExportAudioSources,+ samples: usize,+ project: &ProjectConfiguration,+ mut emit: impl FnMut(usize, &[f32]) -> Result<(), ExportAudioError>,+ ) -> Result<Option<usize>, ExportAudioError> {+ if samples == 0 {+ return Ok(None);+ }+ let mut output = [0.0; EXPORT_AUDIO_BLOCK_SAMPLES * 2];+ let mut outgoing_buffer = [0.0; EXPORT_AUDIO_BLOCK_SAMPLES * 2];+ let mut incoming_buffer = [0.0; EXPORT_AUDIO_BLOCK_SAMPLES * 2];+ let mut written = 0;+ let Some(timeline) = &project.timeline else {+ while written < samples {+ let count = (samples - written).min(EXPORT_AUDIO_BLOCK_SAMPLES);+ output[..count * 2].fill(0.0);+ let rendered = sources.render(+ project,+ self.cursor.clip_index,+ self.cursor.samples + written,+ count,+ &mut output[..count * 2],+ )?;+ if rendered == 0 {+ break;+ }+ emit(written, &output[..rendered * 2])?;+ written += rendered;+ if rendered < count {+ break;+ }+ }+ self.elapsed_samples += if written == 0 { samples } else { written };+ self.cursor.samples += written;+ return Ok((written != 0).then_some(written));+ };+ while written < samples {+ sources.check_cancelled()?;+ let (mapping, span) = if !timeline.transitions.is_empty()+ || !timeline.hold_windows().is_empty()+ {+ let Some((mapping, output_end_samples)) = self.next_transition_mapping(timeline)+ else {+ break;+ };+ (+ mapping,+ output_end_samples+ .saturating_sub(self.elapsed_samples)+ .min(samples - written),+ )+ } else {+ let Some(cursor) = self.timeline_cursor(timeline) else {+ break;+ };+ (+ TimelineFrameMapping::Single {+ source: TimelineSource {+ source_time: cursor.segment_time,+ segment_index: cursor.segment_index,+ segment: cursor.segment,+ },+ output_end: 0.0,+ },+ (cursor.segment_end_samples - self.elapsed_samples).min(samples - written),+ )+ };+ if span == 0 {+ break;+ }+ let mut span_offset = 0;+ while span_offset < span {+ sources.check_cancelled()?;+ let count = (span - span_offset).min(EXPORT_AUDIO_BLOCK_SAMPLES);+ let output = &mut output[..count * 2];+ output.fill(0.0);+ match mapping {+ TimelineFrameMapping::Single { source, .. } => {+ if source.segment.speed_audio_mode != Some(ClipSpeedAudioMode::Mute) {+ sources.render(+ project,+ source.segment.recording_clip,+ self.playhead_to_samples(source.source_time) + span_offset,+ count,+ output,+ )?;+ }+ }+ TimelineFrameMapping::Hold { .. } => {}+ TimelineFrameMapping::Transition {+ outgoing,+ incoming,+ kind,+ progress,+ duration,+ ..+ } => {+ let outgoing_buffer = &mut outgoing_buffer[..count * 2];+ let incoming_buffer = &mut incoming_buffer[..count * 2];+ outgoing_buffer.fill(0.0);+ incoming_buffer.fill(0.0);+ if outgoing.segment.speed_audio_mode != Some(ClipSpeedAudioMode::Mute) {+ sources.render(+ project,+ outgoing.segment.recording_clip,+ self.playhead_to_samples(outgoing.source_time) + span_offset,+ count,+ outgoing_buffer,+ )?;+ }+ if incoming.segment.speed_audio_mode != Some(ClipSpeedAudioMode::Mute) {+ sources.render(+ project,+ incoming.segment.recording_clip,+ self.playhead_to_samples(incoming.source_time) + span_offset,+ count,+ incoming_buffer,+ )?;+ }+ mix_transition_audio_at(+ outgoing_buffer,+ incoming_buffer,+ output,+ kind,+ progress,+ duration,+ span_offset,+ );+ }+ }+ emit(written + span_offset, output)?;+ span_offset += count;+ }+ self.cursor = match mapping {+ TimelineFrameMapping::Single { source, .. } => {+ source_cursor(source, self.playhead_to_samples(source.source_time) + span)+ }+ TimelineFrameMapping::Hold { source, .. } => {+ source_cursor(source, self.playhead_to_samples(source.source_time))+ }+ TimelineFrameMapping::Transition { incoming, .. } => source_cursor(+ incoming,+ self.playhead_to_samples(incoming.source_time) + span,+ ),+ };+ self.elapsed_samples += span;+ written += span;+ }+ Ok((written != 0).then_some(written))+ }++ fn next_transition_mapping<'a>(+ &self,+ timeline: &'a TimelineConfiguration,+ ) -> Option<(TimelineFrameMapping<'a>, usize)> {+ let mut mapping_time = self.elapsed_samples_to_playhead();+ loop {+ let mapping = timeline.get_frame_mapping(mapping_time)?;+ let output_end = match mapping {+ TimelineFrameMapping::Single { output_end, .. }+ | TimelineFrameMapping::Transition { output_end, .. }+ | TimelineFrameMapping::Hold { output_end, .. } => output_end,+ };+ let output_end_samples = self.playhead_to_samples(output_end);+ if output_end_samples > self.elapsed_samples {+ return Some((mapping, output_end_samples));+ }+ if output_end <= mapping_time {+ return None;+ }+ mapping_time = output_end;+ }+ }+fn render_timeline_frame_raw(&mut self,samples: usize,@@ -320,25 +497,9 @@ impl AudioRenderer {let mut output = vec![0.0; samples * 2];let mut written = 0usize;- 'render: while written < samples {- let mut mapping_time = self.elapsed_samples_to_playhead();- let (mapping, output_end_samples) = loop {- let Some(mapping) = timeline.get_frame_mapping(mapping_time) else {- break 'render;- };- let output_end = match mapping {- TimelineFrameMapping::Single { output_end, .. }- | TimelineFrameMapping::Transition { output_end, .. }- | TimelineFrameMapping::Hold { output_end, .. } => output_end,- };- let output_end_samples = self.playhead_to_samples(output_end);- if output_end_samples > self.elapsed_samples {- break (mapping, output_end_samples);- }- if output_end <= mapping_time {- break 'render;- }- mapping_time = output_end;+ while written < samples {+ let Some((mapping, output_end_samples)) = self.next_transition_mapping(timeline) else {+ break;};let chunk_samples = output_end_samples.saturating_sub(self.elapsed_samples)@@ -914,6 +1075,18 @@ fn mix_transition_audio(kind: ClipTransitionType,progress: f64,duration: f64,+) {+ mix_transition_audio_at(outgoing, incoming, output, kind, progress, duration, 0);+}++fn mix_transition_audio_at(+ outgoing: &[f32],+ incoming: &[f32],+ output: &mut [f32],+ kind: ClipTransitionType,+ progress: f64,+ duration: f64,+ sample_offset: usize,) {let progress_per_sample = 1.0 / (duration * AudioData::SAMPLE_RATE as f64);for (sample_index, ((outgoing_frame, incoming_frame), output_frame)) in outgoing@@ -922,7 +1095,8 @@ fn mix_transition_audio(.zip(output.chunks_exact_mut(2)).enumerate(){- let progress = (progress + sample_index as f64 * progress_per_sample).clamp(0.0, 1.0);+ let progress = (progress + (sample_offset + sample_index) as f64 * progress_per_sample)+ .clamp(0.0, 1.0);let (outgoing_gain, incoming_gain) = match kind {ClipTransitionType::CrossFade => {let angle = progress * std::f64::consts::FRAC_PI_2;diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 6552e83c5..f2fa632a0 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -1349,6 +1349,23 @@ pub async fn create_segments(recording_meta: &RecordingMeta,meta: &StudioRecordingMeta,force_ffmpeg: bool,+) -> Result<Vec<SegmentMedia>, String> {+ create_segments_with_audio(recording_meta, meta, force_ffmpeg, true).await+}++pub async fn create_segments_without_audio(+ recording_meta: &RecordingMeta,+ meta: &StudioRecordingMeta,+ force_ffmpeg: bool,+) -> Result<Vec<SegmentMedia>, String> {+ create_segments_with_audio(recording_meta, meta, force_ffmpeg, false).await+}++async fn create_segments_with_audio(+ recording_meta: &RecordingMeta,+ meta: &StudioRecordingMeta,+ force_ffmpeg: bool,+ load_audio: bool,) -> Result<Vec<SegmentMedia>, String> {let legacy_timing_repair = LegacyAudioTimingRepair::load(&recording_meta.project_path);let legacy_timing_repair = &legacy_timing_repair;@@ -1358,6 +1375,7 @@ pub async fn create_segments(let audio = s.audio.as_ref()+ .filter(|_| load_audio).map(|audio_meta| {AudioLoader::spawn(recording_meta.path(&audio_meta.path),@@ -1423,6 +1441,7 @@ pub async fn create_segments(let audio = s.mic.as_ref()+ .filter(|_| load_audio).map(|audio| {AudioLoader::spawn(recording_meta.path(&audio.path),@@ -1434,6 +1453,7 @@ pub async fn create_segments(let system_audio = s.system_audio.as_ref()+ .filter(|_| load_audio).map(|audio| {AudioLoader::spawn(recording_meta.path(&audio.path),diff --git a/crates/editor/src/export_audio.rs b/crates/editor/src/export_audio.rsnew file mode 100644index 000000000..98051b7ab--- /dev/null+++ b/crates/editor/src/export_audio.rs@@ -0,0 +1,1513 @@+use crate::{AudioRenderer, SegmentMedia};+use cap_audio::{+ AudioRendererTrack, AudioSampleSource, AudioStream, AudioStreamError, ChunkRead, StereoMode,+};+use cap_project::{ClipOffsets, ProjectConfiguration, RecordingMeta, StudioRecordingMeta};+use std::{+ collections::HashMap,+ fmt,+ path::{Path, PathBuf},+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+};++pub(crate) const EXPORT_AUDIO_BLOCK_SAMPLES: usize = 4_096;+const MAX_PARALLEL_AUDIO_SOURCES: usize = 4;++#[derive(Clone, Debug)]+pub enum ExportAudioError {+ Cancelled,+ Source {+ source_index: usize,+ path: PathBuf,+ source: AudioStreamError,+ },+ InvalidWindow,+ Sink(String),+ Worker {+ source_index: usize,+ message: String,+ },+}++impl fmt::Display for ExportAudioError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Cancelled => f.write_str("Export cancelled"),+ Self::Source { path, source, .. } => write!(f, "Audio at {}: {source}", path.display()),+ Self::InvalidWindow => f.write_str("Invalid sequential export audio window"),+ Self::Sink(error) => f.write_str(error),+ Self::Worker { message, .. } => write!(f, "Audio source worker failed: {message}"),+ }+ }+}++impl std::error::Error for ExportAudioError {}++impl ExportAudioError {+ pub fn source_index(&self) -> Option<usize> {+ match self {+ Self::Source { source_index, .. } | Self::Worker { source_index, .. } => {+ Some(*source_index)+ }+ _ => None,+ }+ }++ fn is_cancelled(&self) -> bool {+ matches!(self, Self::Cancelled)+ || matches!(self, Self::Source { source, .. } if source.is_cancelled())+ }+}++fn source_worker_panic(+ source_index: usize,+ panic: Box<dyn std::any::Any + Send>,+) -> ExportAudioError {+ ExportAudioError::Worker {+ source_index,+ message: panic+ .downcast_ref::<String>()+ .cloned()+ .or_else(|| {+ panic+ .downcast_ref::<&str>()+ .map(|message| (*message).into())+ })+ .unwrap_or_else(|| "worker panicked".into()),+ }+}++fn run_source_job<T, R>(+ source_index: usize,+ input: &mut T,+ operation: &impl Fn(usize, &mut T) -> Result<R, ExportAudioError>,+) -> Result<R, ExportAudioError> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ operation(source_index, input)+ }))+ .unwrap_or_else(|panic| Err(source_worker_panic(source_index, panic)))+}++fn run_source_jobs<T: Send, R: Send>(+ inputs: &mut [(usize, T)],+ abort: &AtomicBool,+ operation: impl Fn(usize, &mut T) -> Result<R, ExportAudioError> + Sync,+) -> Result<Vec<R>, ExportAudioError> {+ if inputs.len() <= 1 {+ let result = inputs+ .iter_mut()+ .map(|(index, input)| run_source_job(*index, input, &operation))+ .collect::<Result<_, _>>();+ if result.as_ref().is_err_and(|error| !error.is_cancelled()) {+ abort.store(true, Ordering::Relaxed);+ }+ return result;+ }++ let mut results = Vec::with_capacity(inputs.len());+ for batch in inputs.chunks_mut(MAX_PARALLEL_AUDIO_SOURCES) {+ let joined = std::thread::scope(|scope| {+ let operation = &operation;+ let handles = batch+ .iter_mut()+ .map(|(index, input)| {+ let index = *index;+ std::thread::Builder::new()+ .spawn_scoped(scope, move || run_source_job(index, input, operation))+ .ok()+ })+ .collect::<Vec<_>>();+ let mut earlier_source_not_started = false;+ handles+ .into_iter()+ .map(|handle| {+ let Some(handle) = handle else {+ earlier_source_not_started = true;+ return None;+ };+ let result = handle.join();+ if !earlier_source_not_started+ && match &result {+ Ok(Err(error)) => !error.is_cancelled(),+ Err(_) => true,+ _ => false,+ }+ {+ abort.store(true, Ordering::Relaxed);+ }+ Some(result)+ })+ .collect::<Vec<_>>()+ });+ for ((index, input), result) in batch.iter_mut().zip(joined) {+ let result = match result {+ Some(Ok(result)) => result,+ Some(Err(panic)) => Err(source_worker_panic(*index, panic)),+ None => run_source_job(*index, input, &operation),+ };+ if result.as_ref().is_err_and(|error| !error.is_cancelled()) {+ abort.store(true, Ordering::Relaxed);+ }+ results.push(result);+ }+ }++ let mut values = Vec::with_capacity(results.len());+ let mut first_error: Option<ExportAudioError> = None;+ for result in results {+ match result {+ Ok(value) => values.push(value),+ Err(error) => {+ if first_error+ .as_ref()+ .is_none_or(|previous| previous.is_cancelled() && !error.is_cancelled())+ {+ first_error = Some(error);+ }+ }+ }+ }+ match first_error {+ Some(error) => Err(error),+ None => Ok(values),+ }+}++pub struct ExportAudioRenderer {+ renderer: AudioRenderer,+ sources: ExportAudioSources,+ failure: Option<ExportAudioError>,+}++pub struct ExportAudioPreparation {+ sources: ExportAudioSources,+}++impl ExportAudioPreparation {+ fn segment_count(meta: &StudioRecordingMeta) -> usize {+ match meta {+ StudioRecordingMeta::SingleSegment { .. } => 1,+ StudioRecordingMeta::MultipleSegments { inner, .. } => inner.segments.len(),+ }+ }++ pub fn open(+ recording: &RecordingMeta,+ meta: &StudioRecordingMeta,+ cancellation: Arc<AtomicBool>,+ abort: Arc<AtomicBool>,+ ) -> Result<Self, ExportAudioError> {+ let mut inputs = Vec::new();+ match meta {+ StudioRecordingMeta::SingleSegment { segment } => {+ if let Some(audio) = &segment.audio {+ inputs.push((0, recording.path(&audio.path), true));+ }+ }+ StudioRecordingMeta::MultipleSegments { inner, .. } => {+ for (index, segment) in inner.segments.iter().enumerate() {+ if let Some(audio) = &segment.mic {+ inputs.push((index, recording.path(&audio.path), true));+ }+ if let Some(audio) = &segment.system_audio {+ inputs.push((index, recording.path(&audio.path), false));+ }+ }+ }+ }+ let mut inputs = inputs.into_iter().enumerate().collect::<Vec<_>>();+ let opened = run_source_jobs(&mut inputs, &abort, |source_index, (index, path, mic)| {+ ExportAudioTrack::open(path, source_index, *mic, 0.0, &cancellation, &abort)+ .map(|track| (*index, track))+ })?;+ let mut tracks = (0..Self::segment_count(meta))+ .map(|_| Vec::new())+ .collect::<Vec<_>>();+ for (index, track) in opened {+ tracks[index].push(track);+ }+ Ok(Self {+ sources: ExportAudioSources {+ tracks,+ cancellation,+ abort,+ },+ })+ }++ pub fn finish(+ self,+ segments: &[SegmentMedia],+ ) -> Result<ExportAudioRenderer, ExportAudioError> {+ self.finish_with_timing_repair(segments.iter().map(|segment| segment.audio_timing_repair))+ }++ fn finish_with_timing_repair(+ mut self,+ timing_repair: impl ExactSizeIterator<Item = crate::editor_instance::SegmentAudioTimingRepair>,+ ) -> Result<ExportAudioRenderer, ExportAudioError> {+ if timing_repair.len() != self.sources.tracks.len() {+ return Err(ExportAudioError::InvalidWindow);+ }+ for (tracks, repair) in self.sources.tracks.iter_mut().zip(timing_repair) {+ for track in tracks {+ track.timing_offset_secs = if track.mic {+ repair.mic_offset_secs+ } else {+ repair.system_audio_offset_secs+ };+ }+ }+ Ok(ExportAudioRenderer {+ renderer: AudioRenderer::new(Vec::new()),+ sources: self.sources,+ failure: None,+ })+ }+}++pub struct ExportAudioValidation {+ sources: ExportAudioSources,+}++impl ExportAudioValidation {+ pub fn validate_to_end(mut self) -> Result<(), ExportAudioError> {+ self.sources.validate_to_end()+ }+}++impl ExportAudioRenderer {+ pub fn eligible(project: &ProjectConfiguration, meta: &StudioRecordingMeta) -> bool {+ let source_count = match meta {+ StudioRecordingMeta::SingleSegment { segment } => usize::from(segment.audio.is_some()),+ StudioRecordingMeta::MultipleSegments { inner, .. } => inner+ .segments+ .iter()+ .map(|segment| {+ usize::from(segment.mic.is_some()) + usize::from(segment.system_audio.is_some())+ })+ .sum(),+ };+ Self::eligible_sources(project, source_count)+ }++ fn eligible_sources(project: &ProjectConfiguration, source_count: usize) -> bool {+ if !(1..=MAX_PARALLEL_AUDIO_SOURCES).contains(&source_count)+ || project.clips.iter().any(|clip| {+ [clip.offsets.mic, clip.offsets.system_audio]+ .iter()+ .any(|offset| {+ !offset.is_finite() || (offset * 48_000.0).abs() >= isize::MAX as f32 / 2.0+ })+ })+ {+ return false;+ }+ let Some(timeline) = &project.timeline else {+ return true;+ };+ if !timeline.audio_segments.is_empty() || !timeline.hold_windows().is_empty() {+ return false;+ }+ let mut ends = HashMap::new();+ let mut duration = 0.0;+ for segment in &timeline.segments {+ if segment.timescale != 1.0+ || !segment.start.is_finite()+ || !segment.end.is_finite()+ || segment.start < 0.0+ || segment.end <= segment.start+ || segment.end * 48_000.0 >= isize::MAX as f64 / 2.0+ {+ return false;+ }+ duration += segment.duration();+ if !duration.is_finite() || duration * 48_000.0 >= isize::MAX as f64 / 2.0 {+ return false;+ }+ if let Some(previous_end) = ends.insert(segment.recording_clip, segment.end)+ && (!timeline.transitions.is_empty() || segment.start < previous_end)+ {+ return false;+ }+ }+ true+ }++ pub fn open(+ recording: &RecordingMeta,+ meta: &StudioRecordingMeta,+ segments: &[SegmentMedia],+ cancellation: Arc<AtomicBool>,+ abort: Arc<AtomicBool>,+ ) -> Result<Self, ExportAudioError> {+ if segments.len() != ExportAudioPreparation::segment_count(meta) {+ return Err(ExportAudioError::InvalidWindow);+ }+ ExportAudioPreparation::open(recording, meta, cancellation, abort)?.finish(segments)+ }++ pub fn take_unused_sources(+ &mut self,+ project: &ProjectConfiguration,+ ) -> Option<ExportAudioValidation> {+ let timeline = project.timeline.as_ref()?;+ if self.sources.tracks.iter().flatten().count() > MAX_PARALLEL_AUDIO_SOURCES {+ return None;+ }+ let mut unused = Vec::new();+ for (clip_index, tracks) in self.sources.tracks.iter_mut().enumerate() {+ if !tracks.is_empty()+ && !timeline+ .segments+ .iter()+ .any(|segment| segment.recording_clip as usize == clip_index)+ {+ unused.push(std::mem::take(tracks));+ }+ }+ (!unused.is_empty()).then(|| ExportAudioValidation {+ sources: ExportAudioSources {+ tracks: unused,+ cancellation: self.sources.cancellation.clone(),+ abort: self.sources.abort.clone(),+ },+ })+ }++ pub fn render_chunks(+ &mut self,+ samples: usize,+ project: &ProjectConfiguration,+ emit: impl FnMut(usize, &[f32]) -> Result<(), ExportAudioError>,+ ) -> Result<Option<usize>, ExportAudioError> {+ if let Some(error) = &self.failure {+ return Err(error.clone());+ }+ let result = self+ .renderer+ .render_export_chunks(&mut self.sources, samples, project, emit);+ if let Err(error) = &result {+ self.failure = Some(error.clone());+ }+ result+ }++ pub fn validate_to_end(&mut self) -> Result<(), ExportAudioError> {+ if let Some(error) = &self.failure {+ return Err(error.clone());+ }+ let result = self.sources.validate_to_end();+ if let Err(error) = &result {+ self.failure = Some(error.clone());+ }+ result+ }+}++pub(crate) struct ExportAudioSources {+ tracks: Vec<Vec<ExportAudioTrack>>,+ cancellation: Arc<AtomicBool>,+ abort: Arc<AtomicBool>,+}++impl ExportAudioSources {+ pub(crate) fn check_cancelled(&self) -> Result<(), ExportAudioError> {+ if self.cancellation.load(Ordering::Relaxed) || self.abort.load(Ordering::Relaxed) {+ Err(ExportAudioError::Cancelled)+ } else {+ Ok(())+ }+ }++ fn validate_to_end(&mut self) -> Result<(), ExportAudioError> {+ self.check_cancelled()?;+ let mut tracks = self+ .tracks+ .iter_mut()+ .flatten()+ .map(|track| (track.source_index, track))+ .collect::<Vec<_>>();+ run_source_jobs(&mut tracks, &self.abort, |_, track| {+ track+ .source+ .validate_to_end()+ .map_err(|source| ExportAudioError::Source {+ source_index: track.source_index,+ path: track.path.clone(),+ source,+ })?;+ track.samples.clear();+ Ok(())+ })?;+ self.check_cancelled()+ }++ pub(crate) fn render(+ &mut self,+ project: &ProjectConfiguration,+ clip_index: u32,+ cursor: usize,+ samples: usize,+ output: &mut [f32],+ ) -> Result<usize, ExportAudioError> {+ self.check_cancelled()?;+ let Some(tracks) = self.tracks.get_mut(clip_index as usize) else {+ return Ok(0);+ };+ let offsets = project+ .clips+ .iter()+ .find(|clip| clip.index == clip_index)+ .map(|clip| clip.offsets)+ .unwrap_or_default();+ for track in tracks.iter_mut() {+ let start = cursor as i128 + track.offset(&offsets) as i128;+ track.prepare(start, start + samples as i128)?;+ }+ let views = tracks.iter().map(|track| track.view()).collect::<Vec<_>>();+ let max_samples = tracks+ .iter()+ .map(|track| (track.available_end as isize - track.offset(&offsets)).max(0) as usize)+ .max()+ .unwrap_or(0);+ if cursor >= max_samples {+ return Ok(0);+ }+ let tracks = tracks+ .iter()+ .zip(&views)+ .map(|(track, view)| {+ let gain = if track.mic {+ project.audio.mic_volume_db+ } else {+ project.audio.system_volume_db+ };+ AudioRendererTrack {+ data: view,+ gain: if project.audio.mute || gain < -30.0 {+ f32::NEG_INFINITY+ } else {+ gain+ },+ stereo_mode: if !track.mic {+ StereoMode::Stereo+ } else {+ match project.audio.mic_stereo_mode {+ cap_project::StereoMode::Stereo => StereoMode::Stereo,+ cap_project::StereoMode::MonoL => StereoMode::MonoL,+ cap_project::StereoMode::MonoR => StereoMode::MonoR,+ }+ },+ offset: track.offset(&offsets),+ }+ })+ .collect::<Vec<_>>();+ Ok(cap_audio::render_audio(+ &tracks,+ cursor,+ samples.min(max_samples - cursor),+ 0,+ output,+ ))+ }+}++struct ExportAudioTrack {+ source: AudioStream,+ source_index: usize,+ path: PathBuf,+ mic: bool,+ timing_offset_secs: f32,+ samples: Vec<f32>,+ source_start: usize,+ available_end: usize,+ eof: Option<usize>,+}++impl ExportAudioTrack {+ fn open(+ path: &Path,+ source_index: usize,+ mic: bool,+ timing_offset_secs: f32,+ cancellation: &Arc<AtomicBool>,+ abort: &Arc<AtomicBool>,+ ) -> Result<Self, ExportAudioError> {+ let source = AudioStream::open_with_abort(path, cancellation.clone(), abort.clone())+ .map_err(|source| ExportAudioError::Source {+ source_index,+ path: path.to_path_buf(),+ source,+ })?;+ Ok(Self {+ source,+ source_index,+ path: path.to_path_buf(),+ mic,+ timing_offset_secs,+ samples: Vec::new(),+ source_start: 0,+ available_end: 0,+ eof: None,+ })+ }++ fn offset(&self, offsets: &ClipOffsets) -> isize {+ let offset = if self.mic {+ offsets.mic+ } else {+ offsets.system_audio+ };+ ((offset + self.timing_offset_secs) * AudioRenderer::SAMPLE_RATE as f32).round() as isize+ }++ fn prepare(&mut self, start: i128, end: i128) -> Result<(), ExportAudioError> {+ let start = usize::try_from(start.max(0)).map_err(|_| ExportAudioError::InvalidWindow)?;+ let end = usize::try_from(end.max(0)).map_err(|_| ExportAudioError::InvalidWindow)?;+ if end < start || end - start > EXPORT_AUDIO_BLOCK_SAMPLES || start < self.source_start {+ return Err(ExportAudioError::InvalidWindow);+ }+ let channels = self.source.channels() as usize;+ let discard = start+ .saturating_sub(self.source_start)+ .min(self.samples.len() / channels)+ * channels;+ self.samples.copy_within(discard.., 0);+ self.samples.truncate(self.samples.len() - discard);+ self.source_start = start;+ while self.eof.is_none() && self.source.position() < end as u64 {+ let wanted = (end as u64 - self.source.position()).min(12_000) as usize;+ match self+ .source+ .read_chunk(wanted)+ .map_err(|source| ExportAudioError::Source {+ source_index: self.source_index,+ path: self.path.clone(),+ source,+ })? {+ ChunkRead::Chunk(chunk) => {+ let chunk_start = usize::try_from(chunk.source_start_sample)+ .map_err(|_| ExportAudioError::InvalidWindow)?;+ let discard = start+ .saturating_sub(chunk_start)+ .min(chunk.samples.len() / channels)+ * channels;+ self.samples.extend_from_slice(&chunk.samples[discard..]);+ }+ ChunkRead::Eof { next_sample } => {+ self.eof = Some(+ usize::try_from(next_sample)+ .map_err(|_| ExportAudioError::InvalidWindow)?,+ );+ }+ }+ }+ self.available_end = self.eof.unwrap_or(end.max(self.source.position() as usize));+ Ok(())+ }++ fn view(&self) -> ExportAudioView<'_> {+ ExportAudioView {+ samples: &self.samples,+ channels: self.source.channels(),+ source_start: self.source_start,+ available_end: self.available_end,+ }+ }+}++struct ExportAudioView<'a> {+ samples: &'a [f32],+ channels: u16,+ source_start: usize,+ available_end: usize,+}++impl AudioSampleSource for ExportAudioView<'_> {+ fn channels(&self) -> u16 {+ self.channels+ }+ fn sample_count(&self) -> usize {+ self.available_end+ }+ fn sample(&self, index: usize) -> Option<&f32> {+ index+ .checked_sub(self.source_start * self.channels as usize)+ .and_then(|index| self.samples.get(index))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::audio::{AudioSegment, AudioSegmentTrack};+ use cap_audio::AudioData;+ use cap_project::{+ ClipConfiguration, ClipSpeedAudioMode, ClipTransition, ClipTransitionType,+ TimelineConfiguration, TimelineSegment,+ };++ #[test]+ fn source_jobs_are_bounded_joined_and_ordered() {+ use std::{+ sync::{Condvar, Mutex, atomic::AtomicUsize},+ time::Duration,+ };++ let active = AtomicUsize::new(0);+ let peak = AtomicUsize::new(0);+ let completed = AtomicUsize::new(0);+ let arrived = Mutex::new(0);+ let changed = Condvar::new();+ let abort = AtomicBool::new(false);+ let mut inputs = (0..9).map(|value| (value, value)).collect::<Vec<_>>();+ let results = run_source_jobs(&mut inputs, &abort, |_, input| {+ let count = active.fetch_add(1, Ordering::SeqCst) + 1;+ peak.fetch_max(count, Ordering::SeqCst);+ if *input < 8 {+ let mut count = arrived.lock().unwrap();+ *count += 1;+ changed.notify_all();+ let (_guard, timed_out) = changed+ .wait_timeout_while(count, Duration::from_secs(2), |count| {+ *count+ < (*input / MAX_PARALLEL_AUDIO_SOURCES + 1) * MAX_PARALLEL_AUDIO_SOURCES+ })+ .unwrap();+ assert!(!timed_out.timed_out());+ }+ active.fetch_sub(1, Ordering::SeqCst);+ completed.fetch_add(1, Ordering::SeqCst);+ Ok(*input)+ })+ .unwrap();++ assert_eq!(results, (0..9).collect::<Vec<_>>());+ assert_eq!(peak.load(Ordering::SeqCst), MAX_PARALLEL_AUDIO_SOURCES);+ assert_eq!(active.load(Ordering::SeqCst), 0);+ assert_eq!(completed.load(Ordering::SeqCst), inputs.len());+ assert!(!abort.load(Ordering::Relaxed));+ }++ #[test]+ fn source_jobs_preserve_first_real_error_and_join_later_sources() {+ use std::sync::atomic::AtomicUsize;++ let completed = AtomicUsize::new(0);+ let abort = AtomicBool::new(false);+ let mut inputs = [(0, 0), (1, 1), (2, 2), (3, 3)];+ let error = run_source_jobs(&mut inputs, &abort, |_, input| {+ completed.fetch_add(1, Ordering::SeqCst);+ match input {+ 0 => Err(ExportAudioError::Cancelled),+ 1 => Err(ExportAudioError::Sink("first source error".into())),+ 2 => Err(ExportAudioError::Sink("later source error".into())),+ _ => Ok(()),+ }+ })+ .unwrap_err();++ assert_eq!(error.to_string(), "first source error");+ assert_eq!(completed.load(Ordering::SeqCst), inputs.len());+ assert!(abort.load(Ordering::Relaxed));+ }++ #[test]+ fn source_worker_panic_becomes_error_after_other_sources_join() {+ use std::sync::atomic::AtomicUsize;++ let completed = AtomicUsize::new(0);+ let abort = AtomicBool::new(false);+ let mut inputs = [(0, 0), (1, 1), (2, 2), (3, 3)];+ let error = run_source_jobs(&mut inputs, &abort, |_, input| {+ if *input == 1 {+ panic!("source worker test");+ }+ completed.fetch_add(1, Ordering::SeqCst);+ Ok(())+ })+ .unwrap_err();++ assert_eq!(+ error.to_string(),+ "Audio source worker failed: source worker test"+ );+ assert_eq!(completed.load(Ordering::SeqCst), inputs.len() - 1);+ assert_eq!(error.source_index(), Some(1));+ assert!(abort.load(Ordering::Relaxed));+ }++ #[test]+ fn failed_source_aborts_and_joins_waiting_peer_without_user_cancellation() {+ use std::time::{Duration, Instant};++ let user_cancellation = AtomicBool::new(false);+ let abort = AtomicBool::new(false);+ let peer_started = AtomicBool::new(false);+ let peer_observed_abort = AtomicBool::new(false);+ let peer_finished = AtomicBool::new(false);+ let error = run_source_jobs(&mut [(0, 0), (1, 1)], &abort, |_, input| {+ let started = Instant::now();+ if *input == 0 {+ while !peer_started.load(Ordering::Acquire)+ && started.elapsed() < Duration::from_secs(2)+ {+ std::thread::yield_now();+ }+ assert!(peer_started.load(Ordering::Acquire));+ return Err(ExportAudioError::Sink("first source failed".into()));+ }+ peer_started.store(true, Ordering::Release);+ while !abort.load(Ordering::Relaxed)+ && !user_cancellation.load(Ordering::Relaxed)+ && started.elapsed() < Duration::from_secs(2)+ {+ std::thread::yield_now();+ }+ peer_observed_abort.store(abort.load(Ordering::Relaxed), Ordering::Relaxed);+ peer_finished.store(true, Ordering::Release);+ Err::<(), _>(ExportAudioError::Cancelled)+ })+ .unwrap_err();++ assert_eq!(error.to_string(), "first source failed");+ assert!(peer_observed_abort.load(Ordering::Relaxed));+ assert!(peer_finished.load(Ordering::Acquire));+ assert!(!user_cancellation.load(Ordering::Relaxed));+ }++ #[test]+ fn single_source_job_stays_on_current_thread() {+ let current = std::thread::current().id();+ let results = run_source_jobs(&mut [(7, 0)], &AtomicBool::new(false), |index, value| {+ assert_eq!(std::thread::current().id(), current);+ assert_eq!(index, 7);+ *value += 1;+ Ok(*value)+ })+ .unwrap();+ assert_eq!(results, [1]);+ }++ #[test]+ fn inline_source_panic_preserves_original_source_index() {+ let abort = AtomicBool::new(false);+ let error = run_source_jobs::<_, ()>(&mut [(7, ())], &abort, |_, _| {+ panic!("inline source panic");+ })+ .unwrap_err();+ assert_eq!(error.source_index(), Some(7));+ assert_eq!(+ error.to_string(),+ "Audio source worker failed: inline source panic"+ );+ assert!(abort.load(Ordering::Relaxed));+ }++ fn write_wav(path: &Path, frames: usize, channels: u16) {+ let data_size = frames as u32 * u32::from(channels) * 2;+ let mut bytes = Vec::new();+ bytes.extend_from_slice(b"RIFF");+ bytes.extend_from_slice(&(36 + data_size).to_le_bytes());+ bytes.extend_from_slice(b"WAVEfmt ");+ bytes.extend_from_slice(&16u32.to_le_bytes());+ bytes.extend_from_slice(&1u16.to_le_bytes());+ bytes.extend_from_slice(&channels.to_le_bytes());+ bytes.extend_from_slice(&48_000u32.to_le_bytes());+ bytes.extend_from_slice(&(48_000u32 * u32::from(channels) * 2).to_le_bytes());+ bytes.extend_from_slice(&(channels * 2).to_le_bytes());+ bytes.extend_from_slice(&16u16.to_le_bytes());+ bytes.extend_from_slice(b"data");+ bytes.extend_from_slice(&data_size.to_le_bytes());+ for index in 0..frames * channels as usize {+ bytes.extend_from_slice(&(((index * 73) % 60_001) as i32 - 30_000).to_le_bytes()[..2]);+ }+ std::fs::write(path, bytes).unwrap();+ }++ fn preparation_recording(directory: &Path) -> RecordingMeta {+ std::fs::write(+ directory.join("recording-meta.json"),+ r#"{+ "pretty_name": "Audio preparation test",+ "segments": [+ {+ "display": { "path": "unused.mp4" },+ "mic": { "path": "mic.wav" },+ "system_audio": { "path": "system.wav" }+ },+ { "display": { "path": "unused.mp4" } },+ {+ "display": { "path": "unused.mp4" },+ "mic": { "path": "incoming.wav" }+ }+ ]+ }"#,+ )+ .unwrap();+ RecordingMeta::load_for_project(directory).unwrap()+ }++ #[test]+ fn preparation_preserves_readers_positions_and_timing_repair_bits() {+ use crate::editor_instance::SegmentAudioTimingRepair;++ let directory = tempfile::tempdir().unwrap();+ let recording = preparation_recording(directory.path());+ for (name, channels) in [("mic.wav", 1), ("system.wav", 2), ("incoming.wav", 2)] {+ write_wav(&directory.path().join(name), 17_003, channels);+ }+ let user = Arc::new(AtomicBool::new(false));+ let abort = Arc::new(AtomicBool::new(false));+ let prepared = ExportAudioPreparation::open(+ &recording,+ recording.studio_meta().unwrap(),+ user.clone(),+ abort.clone(),+ )+ .unwrap();+ let identity = |track: &ExportAudioTrack| {+ (+ std::ptr::from_ref(&track.source) as usize,+ track.source_index,+ track.path.clone(),+ track.mic,+ track.source.position(),+ )+ };+ let before = prepared+ .sources+ .tracks+ .iter()+ .flatten()+ .map(identity)+ .collect::<Vec<_>>();+ assert!(before.iter().all(|track| track.4 == 0));+ assert_eq!(+ prepared+ .sources+ .tracks+ .iter()+ .map(Vec::len)+ .collect::<Vec<_>>(),+ [2, 0, 1]+ );+ let repairs = [+ SegmentAudioTimingRepair {+ mic_offset_secs: -0.0,+ system_audio_offset_secs: f32::from_bits(0x7fc0_1234),+ },+ SegmentAudioTimingRepair::default(),+ SegmentAudioTimingRepair {+ mic_offset_secs: -0.137_125,+ system_audio_offset_secs: 0.0,+ },+ ];+ let mut renderer = prepared+ .finish_with_timing_repair(repairs.into_iter())+ .unwrap();+ let after = renderer+ .sources+ .tracks+ .iter()+ .flatten()+ .map(identity)+ .collect::<Vec<_>>();+ assert_eq!(before, after);+ assert_eq!(+ renderer+ .sources+ .tracks+ .iter()+ .flatten()+ .map(|track| track.timing_offset_secs.to_bits())+ .collect::<Vec<_>>(),+ [+ repairs[0].mic_offset_secs.to_bits(),+ repairs[0].system_audio_offset_secs.to_bits(),+ repairs[2].mic_offset_secs.to_bits()+ ],+ );+ for track in renderer.sources.tracks.iter_mut().flatten() {+ let reference = AudioData::from_file(&track.path).unwrap();+ let ChunkRead::Chunk(chunk) = track.source.read_chunk(257).unwrap() else {+ panic!("prepared source unexpectedly empty");+ };+ assert_eq!(chunk.source_start_sample, 0);+ assert_eq!(+ chunk+ .samples+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>(),+ reference.samples()[..chunk.samples.len()]+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>(),+ );+ }+ assert!(!user.load(Ordering::Relaxed));+ assert!(!abort.load(Ordering::Relaxed));+ }++ #[test]+ fn invalid_finish_drops_all_prepared_readers() {+ let directory = tempfile::tempdir().unwrap();+ let recording = preparation_recording(directory.path());+ for name in ["mic.wav", "system.wav", "incoming.wav"] {+ write_wav(&directory.path().join(name), 17_003, 1);+ }+ let user = Arc::new(AtomicBool::new(false));+ let abort = Arc::new(AtomicBool::new(false));+ let prepared = ExportAudioPreparation::open(+ &recording,+ recording.studio_meta().unwrap(),+ user.clone(),+ abort.clone(),+ )+ .unwrap();+ assert!(Arc::strong_count(&user) > 1);+ assert!(matches!(+ prepared.finish(&[]),+ Err(ExportAudioError::InvalidWindow)+ ));+ assert_eq!(Arc::strong_count(&user), 1);+ assert_eq!(Arc::strong_count(&abort), 1);+ assert!(!user.load(Ordering::Relaxed));+ assert!(!abort.load(Ordering::Relaxed));+ }++ #[test]+ fn open_rejects_segment_mismatch_before_missing_source_io() {+ let directory = tempfile::tempdir().unwrap();+ let recording = preparation_recording(directory.path());+ let user = Arc::new(AtomicBool::new(false));+ let abort = Arc::new(AtomicBool::new(false));+ assert!(matches!(+ ExportAudioRenderer::open(+ &recording,+ recording.studio_meta().unwrap(),+ &[],+ user.clone(),+ abort.clone(),+ ),+ Err(ExportAudioError::InvalidWindow),+ ));+ assert_eq!(Arc::strong_count(&user), 1);+ assert_eq!(Arc::strong_count(&abort), 1);+ assert!(!abort.load(Ordering::Relaxed));+ assert!(!directory.path().join("mic.wav").exists());+ }++ fn segment(index: u32, start: f64, end: f64) -> TimelineSegment {+ TimelineSegment {+ recording_clip: index,+ start,+ end,+ timescale: 1.0,+ name: None,+ speed_audio_mode: None,+ }+ }++ fn project() -> ProjectConfiguration {+ ProjectConfiguration {+ timeline: Some(TimelineConfiguration {+ segments: vec![segment(0, 0.001_01, 0.33), segment(1, 0.002_01, 0.29)],+ transitions: Vec::new(),+ zoom_segments: Vec::new(),+ scene_segments: Vec::new(),+ mask_segments: Vec::new(),+ text_segments: Vec::new(),+ caption_segments: Vec::new(),+ keyboard_segments: Vec::new(),+ audio_segments: Vec::new(),+ camera3d_segments: Vec::new(),+ }),+ clips: vec![+ ClipConfiguration {+ index: 0,+ offsets: ClipOffsets {+ mic: -0.003_13,+ system_audio: 0.001_33,+ ..Default::default()+ },+ ..Default::default()+ },+ ClipConfiguration {+ index: 1,+ ..Default::default()+ },+ ],+ ..Default::default()+ }+ }++ fn fixture(paths: &[PathBuf], data: &[Arc<AudioData>]) -> (AudioRenderer, ExportAudioRenderer) {+ let cancellation = Arc::new(AtomicBool::new(false));+ let full = vec![+ AudioSegment {+ tracks: vec![+ AudioSegmentTrack::new(+ data[0].clone(),+ |config| config.mic_volume_db,+ |config| match config.mic_stereo_mode {+ cap_project::StereoMode::Stereo => StereoMode::Stereo,+ cap_project::StereoMode::MonoL => StereoMode::MonoL,+ cap_project::StereoMode::MonoR => StereoMode::MonoR,+ },+ |offset| offset.mic,+ ),+ AudioSegmentTrack::new(+ data[1].clone(),+ |config| config.system_volume_db,+ |_| StereoMode::Stereo,+ |offset| offset.system_audio,+ ),+ ],+ },+ AudioSegment {+ tracks: vec![AudioSegmentTrack::new(+ data[2].clone(),+ |config| config.mic_volume_db,+ |config| match config.mic_stereo_mode {+ cap_project::StereoMode::Stereo => StereoMode::Stereo,+ cap_project::StereoMode::MonoL => StereoMode::MonoL,+ cap_project::StereoMode::MonoR => StereoMode::MonoR,+ },+ |offset| offset.mic,+ )],+ },+ ];+ let tracks = vec![+ vec![+ ExportAudioTrack::open(&paths[0], 0, true, 0.0, &cancellation, &cancellation)+ .unwrap(),+ ExportAudioTrack::open(&paths[1], 1, false, 0.0, &cancellation, &cancellation)+ .unwrap(),+ ],+ vec![+ ExportAudioTrack::open(&paths[2], 2, true, 0.0, &cancellation, &cancellation)+ .unwrap(),+ ],+ ];+ (+ AudioRenderer::new(full),+ ExportAudioRenderer {+ renderer: AudioRenderer::new(Vec::new()),+ sources: ExportAudioSources {+ tracks,+ abort: cancellation.clone(),+ cancellation,+ },+ failure: None,+ },+ )+ }++ #[test]+ fn unused_source_detachment_preserves_slots_identity_and_project() {+ let directory = tempfile::tempdir().unwrap();+ let paths =+ ["mic.wav", "system.wav", "incoming.wav"].map(|name| directory.path().join(name));+ for (path, channels) in paths.iter().zip([1, 2, 2]) {+ write_wav(path, 17_003, channels);+ }+ let data = paths+ .iter()+ .map(|path| Arc::new(AudioData::from_file(path).unwrap()))+ .collect::<Vec<_>>();+ for variant in 0..9 {+ let (_, mut candidate) = fixture(&paths, &data);+ candidate.sources.tracks[1].push(+ ExportAudioTrack::open(+ &paths[2],+ 3,+ false,+ 0.0,+ &candidate.sources.cancellation,+ &candidate.sources.abort,+ )+ .unwrap(),+ );+ for track in candidate.sources.tracks.iter_mut().flatten() {+ track.prepare(10, 100).unwrap();+ }+ let identity = |track: &ExportAudioTrack| {+ (+ track.source_index,+ track.path.clone(),+ track.source.position(),+ track.samples.as_ptr() as usize,+ track.samples.len(),+ )+ };+ let before = candidate+ .sources+ .tracks+ .iter()+ .flatten()+ .map(identity)+ .collect::<Vec<_>>();+ let mut project = project();+ let expected_unused = match variant {+ 0 => {+ project.timeline = None;+ vec![]+ }+ 1 => vec![],+ 2 => {+ project.audio.mute = true;+ for segment in &mut project.timeline.as_mut().unwrap().segments {+ segment.speed_audio_mode = Some(ClipSpeedAudioMode::Mute);+ }+ vec![]+ }+ 3 => {+ project+ .timeline+ .as_mut()+ .unwrap()+ .transitions+ .push(ClipTransition {+ segment_index: 1,+ kind: ClipTransitionType::CrossFade,+ duration: 0.13,+ });+ vec![]+ }+ 4 => {+ project.timeline.as_mut().unwrap().segments = vec![segment(0, 0.0, 0.1)];+ vec![2, 3]+ }+ 5 => {+ project.timeline.as_mut().unwrap().segments = vec![segment(1, 0.0, 0.1)];+ vec![0, 1]+ }+ 6 => {+ project.timeline.as_mut().unwrap().segments = vec![segment(9, 0.0, 0.1)];+ vec![0, 1, 2, 3]+ }+ 7 => {+ project.timeline.as_mut().unwrap().segments.clear();+ vec![0, 1, 2, 3]+ }+ 8 => {+ project.timeline.as_mut().unwrap().segments =+ vec![segment(0, 0.0, 0.1), segment(0, 0.2, 0.3)];+ vec![2, 3]+ }+ _ => unreachable!(),+ };+ let project_before = format!("{project:?}");+ let detached = candidate.take_unused_sources(&project);+ let unused_indices = detached+ .iter()+ .flat_map(|validation| validation.sources.tracks.iter().flatten())+ .map(|track| track.source_index)+ .collect::<Vec<_>>();+ assert_eq!(unused_indices, expected_unused, "variant {variant}");+ assert_eq!(candidate.sources.tracks.len(), 2);+ for (clip_index, tracks) in candidate.sources.tracks.iter().enumerate() {+ for track in tracks {+ assert_eq!(track.source_index / 2, clip_index);+ }+ }+ let mut after = candidate+ .sources+ .tracks+ .iter()+ .flatten()+ .chain(+ detached+ .iter()+ .flat_map(|validation| validation.sources.tracks.iter().flatten()),+ )+ .map(identity)+ .collect::<Vec<_>>();+ after.sort_by_key(|track| track.0);+ assert_eq!(after, before, "variant {variant}");+ assert_eq!(format!("{project:?}"), project_before);+ assert!(candidate.take_unused_sources(&project).is_none());+ if let Some(detached) = detached {+ detached.validate_to_end().unwrap();+ }+ candidate.validate_to_end().unwrap();+ }+ }++ #[test]+ fn detachment_does_not_split_more_than_four_readers() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("source.wav");+ write_wav(&path, 17_003, 2);+ let paths = vec![path.clone(); 3];+ let data = paths+ .iter()+ .map(|path| Arc::new(AudioData::from_file(path).unwrap()))+ .collect::<Vec<_>>();+ let (_, mut candidate) = fixture(&paths, &data);+ for index in 3..5 {+ candidate.sources.tracks[1].push(+ ExportAudioTrack::open(+ &path,+ index,+ false,+ 0.0,+ &candidate.sources.cancellation,+ &candidate.sources.abort,+ )+ .unwrap(),+ );+ }+ let mut project = project();+ project.timeline.as_mut().unwrap().segments.truncate(1);+ assert!(candidate.take_unused_sources(&project).is_none());+ assert_eq!(candidate.sources.tracks.iter().flatten().count(), 5);+ }++ #[test]+ fn bounded_sink_matches_full_renderer_at_original_request_boundaries() {+ ffmpeg::init().unwrap();+ let directory = tempfile::tempdir().unwrap();+ let paths =+ ["mic.wav", "system.wav", "incoming.wav"].map(|name| directory.path().join(name));+ for ((path, frames), channels) in paths.iter().zip([17_003, 9_007, 23_013]).zip([1, 2, 2]) {+ write_wav(path, frames, channels);+ }+ let data = paths+ .iter()+ .map(|path| Arc::new(AudioData::from_file(path).unwrap()))+ .collect::<Vec<_>>();+ for variant in 0..16 {+ let mut project = project();+ match variant {+ 0 => project.timeline = None,+ 1 => {}+ 2 | 3 => project+ .timeline+ .as_mut()+ .unwrap()+ .transitions+ .push(ClipTransition {+ segment_index: 1,+ kind: if variant == 2 {+ ClipTransitionType::CrossFade+ } else {+ ClipTransitionType::FadeThroughBlack+ },+ duration: 0.131_234_567,+ }),+ 4 => {+ project.timeline.as_mut().unwrap().segments[0].speed_audio_mode =+ Some(ClipSpeedAudioMode::Mute)+ }+ 5 => project.audio.mute = true,+ 6 => project.audio.mic_stereo_mode = cap_project::StereoMode::MonoL,+ 7 => project.audio.mic_stereo_mode = cap_project::StereoMode::MonoR,+ 8 => project.audio.mic_volume_db = f32::NAN,+ 9 => project.audio.mic_volume_db = f32::INFINITY,+ 10 => project.audio.system_volume_db = f32::NEG_INFINITY,+ 11 => project.clips[0].offsets.mic = 0.9,+ 12 => project.clips[0].offsets.system_audio = -0.9,+ 13 => project+ .timeline+ .as_mut()+ .unwrap()+ .segments+ .push(segment(0, 0.34, 0.36)),+ 14 => project.timeline.as_mut().unwrap().segments[1].recording_clip = 9,+ 15 => {+ project.audio.mic_volume_db = 4.0;+ project.audio.system_volume_db = -29.9;+ }+ _ => unreachable!(),+ }+ for request in [1, 7, 997, 4_096, 4_800, 48_001, 96_000, 384_000] {+ let (mut reference, mut candidate) = fixture(&paths, &data);+ reference.set_playhead(0.0, &project);+ loop {+ let expected = reference.render_frame_raw(request, &project);+ let mut actual = Vec::new();+ let written = candidate+ .render_chunks(request, &project, |offset, samples| {+ assert!(samples.len() <= EXPORT_AUDIO_BLOCK_SAMPLES * 2);+ assert_eq!(offset * 2, actual.len());+ actual.extend_from_slice(samples);+ Ok(())+ })+ .unwrap_or_else(|error| {+ panic!("variant {variant}, request {request}: {error}")+ });+ assert_eq!(+ written,+ expected.as_ref().map(|(count, _)| *count),+ "variant {variant}, request {request}"+ );+ assert_eq!(+ actual+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>(),+ expected+ .as_ref()+ .map(|(_, values)| values+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>())+ .unwrap_or_default(),+ "variant {variant}, request {request}"+ );+ assert_eq!(+ reference.elapsed_samples_to_playhead().to_bits(),+ candidate.renderer.elapsed_samples_to_playhead().to_bits()+ );+ for track in candidate.sources.tracks.iter().flatten() {+ assert!(+ track.samples.len()+ <= EXPORT_AUDIO_BLOCK_SAMPLES * track.source.channels() as usize+ );+ }+ if expected.is_none() {+ break;+ }+ }+ candidate.validate_to_end().unwrap();+ assert_eq!(+ candidate+ .sources+ .tracks+ .iter()+ .flatten()+ .map(|track| track.source.position())+ .collect::<Vec<_>>(),+ data.iter()+ .map(|data| data.sample_count() as u64)+ .collect::<Vec<_>>()+ );+ }+ }+ }++ #[test]+ fn eligibility_rejects_unbounded_or_nonsequential_shapes() {+ let original = project();+ assert!(ExportAudioRenderer::eligible_sources(&original, 3));+ assert!(!ExportAudioRenderer::eligible_sources(&original, 0));+ assert!(!ExportAudioRenderer::eligible_sources(&original, 5));+ for offset in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX] {+ let mut project = original.clone();+ project.clips[0].offsets.mic = offset;+ assert!(!ExportAudioRenderer::eligible_sources(&project, 3));+ }+ for (start, end, speed) in [+ (f64::NAN, 1.0, 1.0),+ (-0.1, 1.0, 1.0),+ (0.0, f64::INFINITY, 1.0),+ (0.0, 0.0, 1.0),+ (0.0, 1.0, 2.0),+ ] {+ let mut project = original.clone();+ let segment = &mut project.timeline.as_mut().unwrap().segments[0];+ segment.start = start;+ segment.end = end;+ segment.timescale = speed;+ assert!(!ExportAudioRenderer::eligible_sources(&project, 3));+ }+ let mut project = original.clone();+ project+ .timeline+ .as_mut()+ .unwrap()+ .segments+ .push(segment(0, 0.34, 0.4));+ assert!(ExportAudioRenderer::eligible_sources(&project, 3));+ project+ .timeline+ .as_mut()+ .unwrap()+ .transitions+ .push(ClipTransition {+ segment_index: 1,+ kind: ClipTransitionType::CrossFade,+ duration: 0.01,+ });+ assert!(!ExportAudioRenderer::eligible_sources(&project, 3));+ let mut project = original;+ project+ .timeline+ .as_mut()+ .unwrap()+ .segments+ .push(segment(0, 0.01, 0.1));+ assert!(!ExportAudioRenderer::eligible_sources(&project, 3));+ }++ #[test]+ fn source_windows_reject_backward_reads_and_keep_failures_sticky() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("source.wav");+ write_wav(&path, 17_003, 2);+ let cancellation = Arc::new(AtomicBool::new(false));+ let mut track =+ ExportAudioTrack::open(&path, 0, true, 0.0, &cancellation, &cancellation).unwrap();+ track.prepare(8_000, 9_000).unwrap();+ track.prepare(8_500, 9_501).unwrap();+ let full = AudioData::from_file(&path).unwrap();+ assert_eq!(track.samples, full.samples()[8_500 * 2..9_501 * 2]);+ assert!(matches!(+ track.prepare(0, 1),+ Err(ExportAudioError::InvalidWindow)+ ));+ let mut candidate = ExportAudioRenderer {+ renderer: AudioRenderer::new(Vec::new()),+ sources: ExportAudioSources {+ tracks: vec![vec![track]],+ cancellation: cancellation.clone(),+ abort: cancellation.clone(),+ },+ failure: None,+ };+ let error = candidate+ .render_chunks(1, &ProjectConfiguration::default(), |_, _| Ok(()))+ .unwrap_err()+ .to_string();+ assert_eq!(candidate.validate_to_end().unwrap_err().to_string(), error);+ cancellation.store(true, Ordering::Relaxed);+ assert_eq!(+ candidate+ .render_chunks(1, &ProjectConfiguration::default(), |_, _| Ok(()))+ .unwrap_err()+ .to_string(),+ error+ );+ }++ #[test]+ fn sink_failure_stops_before_later_source_reads() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("source.wav");+ write_wav(&path, 17_003, 2);+ let paths = vec![path; 3];+ let data = paths+ .iter()+ .map(|path| Arc::new(AudioData::from_file(path).unwrap()))+ .collect::<Vec<_>>();+ let (_, mut candidate) = fixture(&paths, &data);+ let error = candidate+ .render_chunks(96_000, &project(), |_, _| {+ Err(ExportAudioError::Sink("sink stopped".into()))+ })+ .unwrap_err();+ assert_eq!(error.to_string(), "sink stopped");+ assert_eq!(candidate.sources.tracks[1][0].source.position(), 0);+ assert_eq!(+ candidate.validate_to_end().unwrap_err().to_string(),+ "sink stopped"+ );+ }+}diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rsindex 228b230c6..745ae7818 100644--- a/crates/editor/src/lib.rs+++ b/crates/editor/src/lib.rs@@ -2,6 +2,7 @@ mod audio;mod audio_output;mod editor;mod editor_instance;+mod export_audio;mod playback;mod segments;mod telemetry;@@ -17,6 +18,10 @@ pub use editor::{};pub use editor_instance::{AudioLoader, EditorInstance, EditorState, SegmentMedia, create_segments,+ create_segments_without_audio,+};+pub use export_audio::{+ ExportAudioError, ExportAudioPreparation, ExportAudioRenderer, ExportAudioValidation,};pub use playback::{Playback, PlaybackEvent, PlaybackHandle, PlaybackStartError};pub use segments::{get_audio_segments, load_music_tracks, load_music_tracks_uncached};diff --git a/crates/enc-ffmpeg/src/audio/aac.rs b/crates/enc-ffmpeg/src/audio/aac.rsindex 85bcfd92c..fe80c3810 100644--- a/crates/enc-ffmpeg/src/audio/aac.rs+++ b/crates/enc-ffmpeg/src/audio/aac.rs@@ -114,7 +114,88 @@ impl AudioEncoder for AACEncoder {let _ = self.send_frame(frame, Duration::MAX, output);}+ fn try_send_frame(+ &mut self,+ frame: frame::Audio,+ output: &mut format::context::Output,+ ) -> Result<(), ffmpeg::Error> {+ self.send_frame(frame, Duration::MAX, output)+ }+fn flush(&mut self, output: &mut format::context::Output) -> Result<(), ffmpeg::Error> {self.flush(output)}}++#[cfg(test)]+mod tests {+ use super::*;+ use ffmpeg::ChannelLayout;++ fn input_frame(start: i64, samples: usize) -> frame::Audio {+ let mut audio =+ frame::Audio::new(Sample::F32(Type::Packed), samples, ChannelLayout::STEREO);+ audio.set_rate(48_000);+ audio.set_pts(Some(start));+ for (index, sample) in audio.data_mut(0)[..samples * 2 * size_of::<f32>()]+ .chunks_exact_mut(size_of::<f32>())+ .enumerate()+ {+ let value = ((index % 17) as f32 - 8.0) / 32.0;+ sample.copy_from_slice(&value.to_le_bytes());+ }+ audio+ }++ fn encode_audio(checked: bool) -> Vec<u8> {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("audio.mp4");+ let mut output = format::output(&path).unwrap();+ let mut encoder = AACEncoder::init(+ AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 2),+ &mut output,+ )+ .unwrap();+ output.write_header().unwrap();++ let mut position = 0;+ for samples in [1, 997, 4_096, 1_024, 37] {+ let audio = input_frame(position, samples);+ if checked {+ AudioEncoder::try_send_frame(&mut encoder, audio, &mut output).unwrap();+ } else {+ AudioEncoder::send_frame(&mut encoder, audio, &mut output);+ }+ position += samples as i64;+ }++ encoder.flush(&mut output).unwrap();+ output.write_trailer().unwrap();+ drop(encoder);+ drop(output);+ std::fs::read(path).unwrap()+ }++ #[test]+ fn checked_audio_submission_preserves_encoded_bytes() {+ assert_eq!(encode_audio(false), encode_audio(true));+ }++ #[test]+ fn checked_audio_submission_reports_a_closed_encoder() {+ let directory = tempfile::tempdir().unwrap();+ let mut output = format::output(&directory.path().join("closed.mp4")).unwrap();+ let mut encoder = AACEncoder::init(+ AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 2),+ &mut output,+ )+ .unwrap();+ output.write_header().unwrap();+ encoder.flush(&mut output).unwrap();++ assert_eq!(+ AudioEncoder::try_send_frame(&mut encoder, input_frame(0, 1_024), &mut output),+ Err(ffmpeg::Error::Eof)+ );+ }+}diff --git a/crates/enc-ffmpeg/src/audio/audio_encoder.rs b/crates/enc-ffmpeg/src/audio/audio_encoder.rsindex 118b8b512..a6ecf7c5a 100644--- a/crates/enc-ffmpeg/src/audio/audio_encoder.rs+++ b/crates/enc-ffmpeg/src/audio/audio_encoder.rs@@ -9,5 +9,10 @@ pub trait AudioEncoder {}fn send_frame(&mut self, frame: frame::Audio, output: &mut format::context::Output);+ fn try_send_frame(+ &mut self,+ frame: frame::Audio,+ output: &mut format::context::Output,+ ) -> Result<(), ffmpeg::Error>;fn flush(&mut self, output: &mut format::context::Output) -> Result<(), ffmpeg::Error>;}diff --git a/crates/enc-ffmpeg/src/audio/opus.rs b/crates/enc-ffmpeg/src/audio/opus.rsindex 34e1902da..3bcfb974c 100644--- a/crates/enc-ffmpeg/src/audio/opus.rs+++ b/crates/enc-ffmpeg/src/audio/opus.rs@@ -121,6 +121,14 @@ impl AudioEncoder for OpusEncoder {let _ = self.queue_frame(frame, Duration::MAX, output);}+ fn try_send_frame(+ &mut self,+ frame: frame::Audio,+ output: &mut format::context::Output,+ ) -> Result<(), ffmpeg::Error> {+ self.queue_frame(frame, Duration::MAX, output)+ }+fn flush(&mut self, output: &mut format::context::Output) -> Result<(), ffmpeg::Error> {self.flush(output)}diff --git a/crates/enc-ffmpeg/src/mux/mp4.rs b/crates/enc-ffmpeg/src/mux/mp4.rsindex ff6eee0ac..7338e423b 100644--- a/crates/enc-ffmpeg/src/mux/mp4.rs+++ b/crates/enc-ffmpeg/src/mux/mp4.rs@@ -135,6 +135,18 @@ impl MP4File {audio.send_frame(frame, &mut self.output);}+ pub fn try_queue_audio_frame(&mut self, frame: frame::Audio) -> Result<(), ffmpeg::Error> {+ if self.is_finished {+ return Err(ffmpeg::Error::Eof);+ }++ let Some(audio) = &mut self.audio else {+ return Err(ffmpeg::Error::StreamNotFound);+ };++ audio.try_send_frame(frame, &mut self.output)+ }+pub fn finish(&mut self) -> Result<FinishResult, FinishError> {if self.is_finished {return Err(FinishError::AlreadyFinished);diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex e6ec17d38..929e30a36 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -4,13 +4,19 @@ pub mod mp4;pub mod preview;pub mod settings;-use cap_editor::SegmentMedia;+use cap_editor::{ExportAudioPreparation, ExportAudioRenderer, SegmentMedia};use cap_project::{BackgroundSource, ProjectConfiguration, RecordingMeta, StudioRecordingMeta,TimelineConfiguration, TimelineSegment,};use cap_rendering::{ProjectRecordingsMeta, RenderVideoConstants};-use std::{path::PathBuf, sync::Arc};+use std::{+ path::PathBuf,+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+};#[derive(thiserror::Error, Debug)]pub enum ExportError {@@ -78,6 +84,22 @@ impl ExporterBuilder {}pub async fn build(self) -> Result<ExporterBase, ExporterBuildError> {+ self.build_inner(None).await+ }++ pub async fn build_for_mp4(+ self,+ cancellation: Arc<AtomicBool>,+ ) -> Result<Mp4ExporterBase, ExporterBuildError> {+ self.build_inner(Some(cancellation))+ .await+ .map(Mp4ExporterBase)+ }++ async fn build_inner(+ self,+ cancellation: Option<Arc<AtomicBool>>,+ ) -> Result<ExporterBase, ExporterBuildError> {type Error = ExporterBuildError;let mut project_config = if let Some(config) = self.config {@@ -137,6 +159,15 @@ impl ExporterBuilder {}}+ let output_path = self+ .output_path+ .unwrap_or_else(|| recording_meta.output_path());+ let streaming_output = prepare_streaming_output(+ &output_path,+ cancellation.is_some() && ExportAudioRenderer::eligible(&project_config, studio_meta),+ );+ let stream_audio = streaming_output.is_some();+let render_constants = Arc::new(RenderVideoConstants::new(&recordings.segments,@@ -147,21 +178,42 @@ impl ExporterBuilder {.map_err(Error::RendererSetup)?,);- let segments =- cap_editor::create_segments(&recording_meta, studio_meta, self.force_ffmpeg_decoder)- .await- .map_err(Error::MediaLoad)?;-- // Audio decodes in the background after create_segments; exports must- // not silently drop a track, so fail loudly if any decode failed.- for segment in &segments {- segment.audio.get().await.map_err(Error::MediaLoad)?;- segment.system_audio.get().await.map_err(Error::MediaLoad)?;- }-- let output_path = self- .output_path- .unwrap_or_else(|| recording_meta.output_path());+ let audio_cancellation = if stream_audio {+ cancellation.map(ExportAudioCancellation::new)+ } else {+ None+ };+ let (segments, streaming_audio) = if let Some(control) = &audio_cancellation {+ let recording = recording_meta.clone();+ let studio = studio_meta.clone();+ let cancellation = control.user.clone();+ let abort = control.stop.clone();+ let preparation = tokio::task::spawn_blocking(move || {+ ExportAudioPreparation::open(&recording, &studio, cancellation, abort)+ });+ let segments = cap_editor::create_segments_without_audio(+ &recording_meta,+ studio_meta,+ self.force_ffmpeg_decoder,+ )+ .await;+ let (segments, audio) =+ finish_audio_preparation(segments, preparation, &control.stop).await?;+ (segments, Some(audio))+ } else {+ let segments = cap_editor::create_segments(+ &recording_meta,+ studio_meta,+ self.force_ffmpeg_decoder,+ )+ .await+ .map_err(Error::MediaLoad)?;+ for segment in &segments {+ segment.audio.get().await.map_err(Error::MediaLoad)?;+ segment.system_audio.get().await.map_err(Error::MediaLoad)?;+ }+ (segments, None)+ };if let Some(parent) = output_path.parent() {std::fs::create_dir_all(parent)@@ -177,10 +229,33 @@ impl ExporterBuilder {recording_meta,project_config,project_path: self.project_path,+ streaming_audio,+ streaming_output,+ audio_cancellation,})}}+async fn finish_audio_preparation(+ segments: Result<Vec<SegmentMedia>, String>,+ preparation: tokio::task::JoinHandle<+ Result<ExportAudioPreparation, cap_editor::ExportAudioError>,+ >,+ abort: &AtomicBool,+) -> Result<(Vec<SegmentMedia>, ExportAudioRenderer), ExporterBuildError> {+ if segments.is_err() {+ abort.store(true, Ordering::Relaxed);+ }+ let preparation = preparation.await;+ let segments = segments.map_err(ExporterBuildError::MediaLoad)?;+ let audio = preparation+ .map_err(|error| ExporterBuildError::MediaLoad(error.to_string()))?+ .map_err(|error| ExporterBuildError::MediaLoad(error.to_string()))?+ .finish(&segments)+ .map_err(|error| ExporterBuildError::MediaLoad(error.to_string()))?;+ Ok((segments, audio))+}+pub fn make_cursor_only_project(mut project_config: ProjectConfiguration) -> ProjectConfiguration {project_config.background.source = BackgroundSource::Color {value: [0, 0, 0],@@ -211,6 +286,51 @@ pub fn make_cursor_only_project(mut project_config: ProjectConfiguration) -> Proproject_config}+fn prepare_streaming_output(+ output: &std::path::Path,+ eligible: bool,+) -> Option<tempfile::TempPath> {+ if !eligible+ || output.extension().and_then(|extension| extension.to_str()) != Some("mp4")+ || !matches!(std::fs::symlink_metadata(output), Err(error) if error.kind() == std::io::ErrorKind::NotFound)+ {+ return None;+ }+ mp4::temporary_mp4_output(output).ok()+}++struct ExportAudioCancellation {+ user: Arc<AtomicBool>,+ stop: Arc<AtomicBool>,+}++impl ExportAudioCancellation {+ fn new(user: Arc<AtomicBool>) -> Self {+ Self {+ user,+ stop: Arc::new(AtomicBool::new(false)),+ }+ }+}++impl Drop for ExportAudioCancellation {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Relaxed);+ }+}++pub struct Mp4ExporterBase(ExporterBase);++impl Mp4ExporterBase {+ pub fn total_frames(&self, fps: u32) -> u32 {+ self.0.total_frames(fps)+ }++ pub fn uses_streaming_audio(&self) -> bool {+ self.0.streaming_audio.is_some()+ }+}+pub struct ExporterBase {project_path: PathBuf,recording_meta: RecordingMeta,@@ -220,6 +340,9 @@ pub struct ExporterBase {render_constants: Arc<RenderVideoConstants>,segments: Vec<SegmentMedia>,output_path: PathBuf,+ streaming_audio: Option<ExportAudioRenderer>,+ streaming_output: Option<tempfile::TempPath>,+ audio_cancellation: Option<ExportAudioCancellation>,}impl ExporterBase {@@ -298,3 +421,150 @@ mod cursor_only_tests {}}}++#[cfg(test)]+mod cancellation_tests {+ use super::*;++ #[tokio::test(flavor = "current_thread")]+ async fn segment_failure_aborts_and_joins_preparation_before_returning() {+ use std::time::{Duration, Instant};++ let user = Arc::new(AtomicBool::new(false));+ let control = ExportAudioCancellation::new(user.clone());+ let abort = control.stop.clone();+ let completed = Arc::new(AtomicBool::new(false));+ let worker_completed = completed.clone();+ let (started, entered) = tokio::sync::oneshot::channel();+ let preparation = tokio::task::spawn_blocking(move || {+ started.send(()).unwrap();+ let start = Instant::now();+ while !abort.load(Ordering::Relaxed) && start.elapsed() < Duration::from_secs(2) {+ std::thread::yield_now();+ }+ assert!(abort.load(Ordering::Relaxed));+ worker_completed.store(true, Ordering::Release);+ Err(cap_editor::ExportAudioError::Sink(+ "audio preparation error".into(),+ ))+ });+ entered.await.unwrap();+ let result = finish_audio_preparation(+ Err("segment setup error".into()),+ preparation,+ &control.stop,+ )+ .await;+ assert!(+ matches!(result, Err(ExporterBuildError::MediaLoad(error)) if error == "segment setup error")+ );+ assert!(completed.load(Ordering::Acquire));+ assert!(!user.load(Ordering::Relaxed));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn preparation_error_or_panic_is_returned_after_successful_segment_setup() {+ let abort = AtomicBool::new(false);+ for panic in [false, true] {+ let preparation = tokio::task::spawn_blocking(move || {+ assert!(!panic, "preparation panic");+ Err(cap_editor::ExportAudioError::Sink(+ "preparation error".into(),+ ))+ });+ let result = finish_audio_preparation(Ok(Vec::new()), preparation, &abort).await;+ let Err(ExporterBuildError::MediaLoad(error)) = result else {+ panic!("preparation failure was lost");+ };+ assert!(error.contains(if panic {+ "preparation panic"+ } else {+ "preparation error"+ }));+ }+ }++ #[tokio::test(flavor = "current_thread")]+ async fn dropped_builder_aborts_preparation_without_user_cancellation() {+ use std::time::{Duration, Instant};++ let user = Arc::new(AtomicBool::new(false));+ let worker_user = user.clone();+ let (started, entered) = tokio::sync::oneshot::channel();+ let (finished, observed) = std::sync::mpsc::channel();+ let builder = tokio::spawn(async move {+ let control = ExportAudioCancellation::new(worker_user);+ let abort = control.stop.clone();+ let preparation = tokio::task::spawn_blocking(move || {+ started.send(()).unwrap();+ let start = Instant::now();+ while !abort.load(Ordering::Relaxed) && start.elapsed() < Duration::from_secs(2) {+ std::thread::yield_now();+ }+ finished.send(abort.load(Ordering::Relaxed)).unwrap();+ Err(cap_editor::ExportAudioError::Cancelled)+ });+ finish_audio_preparation(Ok(Vec::new()), preparation, &control.stop)+ .await+ .map(|_| ())+ .map_err(|error| error.to_string())+ });+ entered.await.unwrap();+ builder.abort();+ assert!(builder.await.is_err_and(|error| error.is_cancelled()));+ let stopped =+ tokio::task::spawn_blocking(move || observed.recv_timeout(Duration::from_secs(2)))+ .await+ .unwrap()+ .unwrap();+ assert!(stopped);+ assert!(!user.load(Ordering::Relaxed));+ assert_eq!(Arc::strong_count(&user), 1);+ }++ #[test]+ fn unavailable_streaming_destination_falls_back_without_creating_directories() {+ let directory = tempfile::tempdir().unwrap();+ let missing_parent = directory.path().join("missing");+ assert!(prepare_streaming_output(&missing_parent.join("export.mp4"), true).is_none());+ assert!(!missing_parent.exists());+ let existing = directory.path().join("existing.mp4");+ std::fs::write(&existing, b"existing").unwrap();+ assert!(prepare_streaming_output(&existing, true).is_none());+ assert_eq!(std::fs::read(existing).unwrap(), b"existing");+ }++ #[test]+ fn prepared_destination_is_removed_when_preparation_is_dropped() {+ let directory = tempfile::tempdir().unwrap();+ let output = directory.path().join("export.mp4");+ assert!(prepare_streaming_output(&output, false).is_none());+ assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);+ let prepared = prepare_streaming_output(&output, true).unwrap();+ let temporary_path = prepared.to_path_buf();+ assert!(temporary_path.exists());+ assert!(!output.exists());+ drop(prepared);+ assert!(!temporary_path.exists());+ assert!(!output.exists());+ }++ #[test]+ fn pipeline_stop_does_not_change_user_cancellation() {+ let user = Arc::new(AtomicBool::new(false));+ let cancellation = ExportAudioCancellation::new(user.clone());+ let stop = cancellation.stop.clone();+ drop(cancellation);+ assert!(stop.load(Ordering::Relaxed));+ assert!(!user.load(Ordering::Relaxed));+ }++ #[test]+ fn user_cancellation_does_not_change_pipeline_abort() {+ let user = Arc::new(AtomicBool::new(false));+ let cancellation = ExportAudioCancellation::new(user.clone());+ user.store(true, Ordering::Relaxed);+ assert!(cancellation.user.load(Ordering::Relaxed));+ assert!(!cancellation.stop.load(Ordering::Relaxed));+ }+}diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rsindex c972ed738..78a1b6696 100644--- a/crates/export/src/mp4.rs+++ b/crates/export/src/mp4.rs@@ -1,5 +1,5 @@-use crate::ExporterBase;-use cap_editor::{AudioRenderer, get_audio_segments, load_music_tracks_uncached};+use crate::{ExporterBase, Mp4ExporterBase};+use cap_editor::{AudioRenderer, ExportAudioError, get_audio_segments, load_music_tracks_uncached};use cap_enc_ffmpeg::{AudioEncoder, aac::AACEncoder, h264::H264Encoder, mp4::*};use cap_media_info::{RawVideoFormat, VideoInfo};use cap_project::XY;@@ -14,12 +14,127 @@ use std::{path::PathBuf,sync::{Arc, Mutex,- atomic::{AtomicU64, Ordering},+ atomic::{AtomicBool, AtomicU64, Ordering},},time::Duration,};+use tokio::sync::Notify;use tracing::{info, trace, warn};+enum Mp4PipelineError {+ Interrupted,+ Failure(String),+ AudioSourceFailure {+ source_index: usize,+ message: String,+ },+}++impl From<String> for Mp4PipelineError {+ fn from(error: String) -> Self {+ Self::Failure(error)+ }+}++impl From<ExportAudioError> for Mp4PipelineError {+ fn from(error: ExportAudioError) -> Self {+ match (&error, error.source_index()) {+ (ExportAudioError::Cancelled, _) => Self::Interrupted,+ (ExportAudioError::Source { source, .. }, _) if source.is_cancelled() => {+ Self::Interrupted+ }+ (_, Some(source_index)) => Self::AudioSourceFailure {+ source_index,+ message: error.to_string(),+ },+ _ => Self::Failure(error.to_string()),+ }+ }+}++impl Mp4PipelineError {+ fn message(self) -> String {+ match self {+ Self::Interrupted => "Export cancelled".to_string(),+ Self::Failure(error) | Self::AudioSourceFailure { message: error, .. } => error,+ }+ }+}++fn resolve_pipeline_results(+ encoder: Result<PathBuf, Mp4PipelineError>,+ renderer: Result<(), Mp4PipelineError>,+ validation: Result<(), Mp4PipelineError>,+) -> Result<(), String> {+ let mut first_source_failure: Option<(usize, String)> = None;+ let mut first_other_failure = None;+ let mut interrupted = false;+ for error in [encoder.err(), renderer.err(), validation.err()]+ .into_iter()+ .flatten()+ {+ match error {+ Mp4PipelineError::AudioSourceFailure {+ source_index,+ message,+ } => {+ if first_source_failure+ .as_ref()+ .is_none_or(|(previous, _)| source_index < *previous)+ {+ first_source_failure = Some((source_index, message));+ }+ }+ Mp4PipelineError::Failure(error) => {+ if first_other_failure.is_none() {+ first_other_failure = Some(error);+ }+ }+ Mp4PipelineError::Interrupted => interrupted = true,+ }+ }+ if let Some((_, error)) = first_source_failure {+ Err(error)+ } else if let Some(error) = first_other_failure {+ Err(error)+ } else if interrupted {+ Err("Export cancelled".to_string())+ } else {+ Ok(())+ }+}++async fn complete_audio_validation(+ task: tokio::task::JoinHandle<Result<(), Mp4PipelineError>>,+ abort: Arc<AtomicBool>,+ failure: Arc<Notify>,+) -> Result<(), Mp4PipelineError> {+ match task.await {+ Ok(result) => result,+ Err(error) => {+ abort.store(true, Ordering::Relaxed);+ failure.notify_one();+ Err(Mp4PipelineError::Failure(format!(+ "Audio validation worker failed: {error}"+ )))+ }+ }+}++async fn render_until_audio_failure(+ render: impl std::future::Future<Output = Result<(), Mp4PipelineError>>,+ failure: Option<Arc<Notify>>,+) -> Result<(), Mp4PipelineError> {+ let Some(failure) = failure else {+ return render.await;+ };+ tokio::select! {+ biased;+ _ = failure.notified() => Err(Mp4PipelineError::Interrupted),+ result = render => result,+ }+}+#[derive(Serialize, Deserialize, Type, Clone, Copy, Debug)]pub enum ExportCompression {Maximum,@@ -82,6 +197,14 @@ impl Mp4ExportSettings {}impl Mp4ExportSettings {+ pub fn export_prepared(+ self,+ base: Mp4ExporterBase,+ on_progress: impl FnMut(u32) -> bool + Send + 'static,+ ) -> impl std::future::Future<Output = Result<PathBuf, String>> {+ self.export(base.0, on_progress)+ }+pub async fn export(self,base: ExporterBase,@@ -162,7 +285,7 @@ impl Mp4ExportSettings {async fn export_nv12(self,- base: ExporterBase,+ mut base: ExporterBase,output_size: (u32, u32),fps: u32,on_progress: impl FnMut(u32) -> bool + Send + 'static,@@ -170,6 +293,36 @@ impl Mp4ExportSettings {) -> Result<PathBuf, String> {let pipeline_start = std::time::Instant::now();let output_path = base.output_path.clone();+ let mut streaming_audio = base.streaming_audio.take();+ let audio_control = base.audio_cancellation.take();+ let audio_cancellation = audio_control.as_ref().map(|control| control.stop.clone());+ let user_cancellation = audio_control.as_ref().map(|control| control.user.clone());+ let temporary_output = base.streaming_output.take().map(Arc::new);+ let unused_audio = streaming_audio+ .as_mut()+ .and_then(|audio| audio.take_unused_sources(&base.project_config));+ let validation_failure = unused_audio.as_ref().map(|_| Arc::new(Notify::new()));+ let audio_validation = unused_audio.map(|validation| {+ let abort = audio_cancellation.as_ref().unwrap().clone();+ let failure = validation_failure.as_ref().unwrap().clone();+ let worker_abort = abort.clone();+ let worker_failure = failure.clone();+ let temporary_output_guard = temporary_output.clone();+ let task = tokio::task::spawn_blocking(move || {+ let _temporary_output_guard = temporary_output_guard;+ let result = validation.validate_to_end().map_err(Mp4PipelineError::from);+ if result.is_err() {+ worker_abort.store(true, Ordering::Relaxed);+ worker_failure.notify_one();+ }+ result+ });+ (task, abort, failure)+ });+ let encoder_output_path = temporary_output+ .as_ref()+ .map(|path| path.to_path_buf())+ .unwrap_or_else(|| output_path.clone());let meta = &base.studio_meta;let (frame_tx, frame_rx) = std::sync::mpsc::sync_channel::<ExportFrame>(4);@@ -192,7 +345,12 @@ impl Mp4ExportSettings {let project_for_audio = base.project_config.clone();let pipeline_start_for_encoder = pipeline_start;+ let encoder_temporary_output = temporary_output.clone();+ let encoder_cancellation = audio_cancellation.clone();+ let encoder_user_cancellation = user_cancellation.clone();+ let encoder_result_cancellation = audio_cancellation.clone();let encoder_thread = tokio::task::spawn_blocking(move || {+ let _temporary_output_guard = encoder_temporary_output;trace!("Creating MP4File encoder (NV12 path)");// The encoder's input mode has to match what the renderer actually@@ -200,6 +358,9 @@ impl Mp4ExportSettings {// VideoToolbox for zero-copy hardware input (falling back to// software frames if that fails), CPU frames keep today's path.let first_frame = frame_rx.recv().ok();+ if encoder_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) || encoder_user_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {+ return Err(Mp4PipelineError::Interrupted);+ }#[cfg(target_os = "macos")]let want_hw_input = !self.optimize_filesize&& matches!(@@ -214,7 +375,7 @@ impl Mp4ExportSettings {let mut encoder = MP4File::init("output",- base.output_path.clone(),+ encoder_output_path.clone(),self.optimize_filesize,|o| {#[cfg(target_os = "macos")]@@ -262,7 +423,7 @@ impl Mp4ExportSettings {"Created MP4File encoder (NV12, export settings)");- let mut audio_renderer = if has_audio {+ let mut audio_renderer = if has_audio && streaming_audio.is_none() {Some(AudioRenderer::new(audio_segments).with_music(music))} else {None@@ -284,6 +445,9 @@ impl Mp4ExportSettings {.into_iter().chain(std::iter::from_fn(|| frame_rx.recv().ok()));for input in frames {+ if encoder_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) || encoder_user_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {+ return Err(Mp4PipelineError::Interrupted);+ }if encoded_frames == 0&& let Some(audio) = &mut audio_renderer{@@ -361,6 +525,30 @@ impl Mp4ExportSettings {if let Some(audio) = audio_frame {encoder.queue_audio_frame(audio);}+ if has_audio && let Some(audio) = &mut streaming_audio {+ let n = u64::from(input.frame_number);+ if let Some((pts, samples)) = audio_frame_budget(n, sample_rate, fps_u64, audio_sample_cursor) {+ audio_sample_cursor = pts as u64 + samples as u64;+ let rendered = audio.render_chunks(samples, &project_for_audio, |offset, data| {+ let mut frame = packed_audio_frame(data);+ frame.set_pts(Some(pts + offset as i64));+ encoder.try_queue_audio_frame(frame).map_err(|error| ExportAudioError::Sink(error.to_string()))+ }).map_err(Mp4PipelineError::from)?;+ if rendered.is_none() {+ let mut offset = 0;+ while offset < samples {+ if encoder_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) || encoder_user_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {+ return Err(Mp4PipelineError::Interrupted);+ }+ let count = (samples - offset).min(4_096);+ let mut frame = silent_audio_frame(count);+ frame.set_pts(Some(pts + offset as i64));+ encoder.try_queue_audio_frame(frame).map_err(|error| error.to_string())?;+ offset += count;+ }+ }+ }+ }encoded_frames += 1;if encoded_frames == 1&& let Some(atom) = record_first_queued_ms.as_ref()@@ -382,22 +570,52 @@ impl Mp4ExportSettings {);}+ if let Some(audio) = &mut streaming_audio {+ audio.validate_to_end().map_err(Mp4PipelineError::from)?;+ }+ if encoder_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) || encoder_user_cancellation.as_ref().is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {+ return Err(Mp4PipelineError::Interrupted);+ }+let res = encoder.finish().map_err(|e| format!("Failed to finish encoding: {e}"))?;if let Err(e) = res.video_finish {- return Err(format!("Video encoding failed: {e}"));+ return Err(Mp4PipelineError::Failure(format!("Video encoding failed: {e}")));}if let Err(e) = res.audio_finish {- return Err(format!("Audio encoding failed: {e}"));+ return Err(Mp4PipelineError::Failure(format!("Audio encoding failed: {e}")));}- Ok::<_, String>(base.output_path)+ Ok::<_, Mp4PipelineError>(encoder_output_path)})- .then(|r| async { r.map_err(|e| e.to_string()).and_then(|v| v) });+ .then(move |r| async move {+ let result = r.map_err(|e| Mp4PipelineError::Failure(e.to_string())).and_then(|v| v);+ if result.is_err() && let Some(cancel) = &encoder_result_cancellation {+ cancel.store(true, Ordering::Relaxed);+ }+ result+ });let stop_after_frames_sent = mode.stop_after_frames_sent;+ let render_result_cancellation = audio_cancellation.clone();+ let progress_cancellation = audio_cancellation.clone();+ let progress_user_cancellation = user_cancellation;+ let mut on_progress = on_progress;+ let on_progress = move |frame| {+ let keep_going = !progress_user_cancellation+ .as_ref()+ .is_some_and(|cancel| cancel.load(Ordering::Relaxed))+ && !progress_cancellation+ .as_ref()+ .is_some_and(|cancel| cancel.load(Ordering::Relaxed))+ && on_progress(frame);+ if !keep_going && let Some(cancel) = &progress_cancellation {+ cancel.store(true, Ordering::Relaxed);+ }+ keep_going+ };let render_video_task = export_render_to_channel(&base.render_constants,&base.project_config,@@ -418,12 +636,64 @@ impl Mp4ExportSettings {&base.recordings,stop_after_frames_sent,nv12_render_startup_breakdown_ms,+ audio_cancellation.is_some(),on_progress,base.project_path.clone(),)- .then(|v| async { v.map_err(|e| e.to_string()) });-- tokio::try_join!(encoder_thread, render_video_task)?;+ .then(move |v| async move {+ let result = v.map_err(|error| match &error {+ cap_rendering::RenderingError::ImageLoadError(message)+ if render_result_cancellation.is_some() && message == "Export cancelled" =>+ {+ Mp4PipelineError::Interrupted+ }+ _ => Mp4PipelineError::Failure(error.to_string()),+ });+ if result.is_err()+ && let Some(cancel) = &render_result_cancellation+ {+ cancel.store(true, Ordering::Relaxed);+ }+ result+ });++ if audio_cancellation.is_some() {+ let validation = async move {+ match audio_validation {+ Some((task, abort, failure)) => {+ complete_audio_validation(task, abort, failure).await+ }+ None => Ok(()),+ }+ };+ let (encoder_result, render_result, validation_result) = tokio::join!(+ encoder_thread,+ render_until_audio_failure(render_video_task, validation_failure),+ validation,+ );+ resolve_pipeline_results(encoder_result, render_result, validation_result)?;+ if audio_cancellation+ .as_ref()+ .is_some_and(|cancel| cancel.load(Ordering::Relaxed))+ {+ return Err("Export cancelled".to_string());+ }+ if audio_control+ .as_ref()+ .is_some_and(|control| control.user.load(Ordering::Relaxed))+ {+ return Err("Export cancelled".to_string());+ }+ if let Some(temporary_output) = temporary_output {+ Arc::try_unwrap(temporary_output)+ .map_err(|_| "Export output is still in use".to_string())?+ .persist_noclobber(&output_path)+ .map_err(|error| error.to_string())?;+ }+ } else {+ tokio::try_join!(encoder_thread, render_video_task)+ .map_err(Mp4PipelineError::message)?;+ }Ok(output_path)}@@ -603,6 +873,37 @@ fn audio_frame_budget(Some((cursor as i64, (end - cursor) as usize))}+pub(crate) fn temporary_mp4_output(output: &std::path::Path) -> Result<tempfile::TempPath, String> {+ let mut builder = tempfile::Builder::new();+ builder.prefix(".cap-export-").suffix(".mp4");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ builder.permissions(std::fs::Permissions::from_mode(0o666));+ }+ builder+ .tempfile_in(output.parent().unwrap_or_else(|| std::path::Path::new(".")))+ .map(tempfile::NamedTempFile::into_temp_path)+ .map_err(|error| error.to_string())+}++fn packed_audio_frame(data: &[f32]) -> ffmpeg::frame::Audio {+ let mut frame = ffmpeg::frame::Audio::new(+ AudioRenderer::SAMPLE_FORMAT,+ data.len() / 2,+ ffmpeg::ChannelLayout::STEREO,+ );+ frame.set_rate(AudioRenderer::SAMPLE_RATE);+ for (sample, bytes) in data.iter().zip(+ frame+ .data_mut(0)+ .chunks_exact_mut(std::mem::size_of::<f32>()),+ ) {+ bytes.copy_from_slice(&sample.to_ne_bytes());+ }+ frame+}+fn silent_audio_frame(samples: usize) -> ffmpeg::frame::Audio {let mut frame = ffmpeg::frame::Audio::new(AudioRenderer::SAMPLE_FORMAT,@@ -789,6 +1090,7 @@ async fn export_render_to_channel(recordings: &ProjectRecordingsMeta,stop_after_frames_sent: Option<u32>,startup_breakdown_ms: Option<Arc<Mutex<Option<cap_rendering::Nv12RenderStartupBreakdownMs>>>>,+ stop_on_encoder_drop: bool,mut on_progress: impl FnMut(u32) -> bool + Send + 'static,project_path: PathBuf,) -> Result<(), cap_rendering::RenderingError> {@@ -797,7 +1099,7 @@ async fn export_render_to_channel(let screenshot_project_path = project_path;let render_result = {- let render_future = cap_rendering::render_video_to_channel_nv12(+ let render_future = Box::pin(cap_rendering::render_video_to_channel_nv12(constants,project,tx_image_data,@@ -809,7 +1111,7 @@ async fn export_render_to_channel(recordings,stop_after_frames_sent,startup_breakdown_ms,- );+ ));let forward_future = async {let mut first_frame_data: Option<FirstFrameNv12> = None;@@ -875,6 +1177,11 @@ async fn export_render_to_channel(if sender.send(export_frame).is_err() {warn!("Encoder dropped, stopping render forwarding");+ if stop_on_encoder_drop {+ return Err(cap_rendering::RenderingError::ImageLoadError(+ "Export cancelled".to_string(),+ ));+ }break;}@@ -956,6 +1263,185 @@ mod tests {}}+ #[test]+ fn pipeline_interruption_preserves_the_peer_failure() {+ assert_eq!(+ resolve_pipeline_results(+ Err(Mp4PipelineError::Interrupted),+ Err(Mp4PipelineError::Failure("renderer failed".into())),+ Ok(()),+ ),+ Err("renderer failed".into())+ );+ assert_eq!(+ resolve_pipeline_results(+ Err(Mp4PipelineError::Failure("audio failed".into())),+ Err(Mp4PipelineError::Interrupted),+ Ok(()),+ ),+ Err("audio failed".into())+ );+ assert_eq!(+ resolve_pipeline_results(Err(Mp4PipelineError::Interrupted), Ok(()), Ok(())),+ Err("Export cancelled".into())+ );+ }++ #[test]+ fn detached_and_active_source_errors_keep_original_order() {+ for (active, detached) in [(1, 7), (7, 1)] {+ let error = resolve_pipeline_results(+ Err(Mp4PipelineError::AudioSourceFailure {+ source_index: active,+ message: format!("source {active}"),+ }),+ Err(Mp4PipelineError::Interrupted),+ Err(Mp4PipelineError::AudioSourceFailure {+ source_index: detached,+ message: format!("source {detached}"),+ }),+ );+ assert_eq!(error, Err("source 1".into()));+ }+ assert_eq!(+ resolve_pipeline_results(+ Err(Mp4PipelineError::Interrupted),+ Err(Mp4PipelineError::Interrupted),+ Err(Mp4PipelineError::from(ExportAudioError::Worker {+ source_index: 3,+ message: "decoder panicked".into(),+ })),+ ),+ Err("Audio source worker failed: decoder panicked".into()),+ );+ }++ #[tokio::test]+ async fn validation_failure_before_render_poll_skips_producer() {+ let failure = Arc::new(Notify::new());+ failure.notify_one();+ let polled = AtomicBool::new(false);+ let result = render_until_audio_failure(+ async {+ polled.store(true, Ordering::Relaxed);+ Ok(())+ },+ Some(failure),+ )+ .await;+ assert!(matches!(result, Err(Mp4PipelineError::Interrupted)));+ assert!(!polled.load(Ordering::Relaxed));+ }++ #[tokio::test]+ async fn validation_failure_releases_pending_producer_receiver_and_temp_owners() {+ let directory = tempfile::tempdir().unwrap();+ let output = directory.path().join("export.mp4");+ let temporary = Arc::new(temporary_mp4_output(&output).unwrap());+ let temporary_path = temporary.to_path_buf();+ let abort = Arc::new(AtomicBool::new(false));+ let user = AtomicBool::new(false);+ let failure = Arc::new(Notify::new());+ let (frame_tx, frame_rx) = std::sync::mpsc::sync_channel::<()>(1);+ let (receiver_started_tx, receiver_started_rx) = tokio::sync::oneshot::channel();+ let (producer_started_tx, producer_started_rx) = tokio::sync::oneshot::channel();+ let receiver_guard = temporary.clone();+ let receiver = tokio::task::spawn_blocking(move || {+ let _guard = receiver_guard;+ receiver_started_tx.send(()).unwrap();+ assert!(frame_rx.recv().is_err());+ Err::<PathBuf, _>(Mp4PipelineError::Interrupted)+ });+ receiver_started_rx.await.unwrap();+ let producer_guard = temporary.clone();+ let producer = async move {+ let _sender = frame_tx;+ let _guard = producer_guard;+ producer_started_tx.send(()).unwrap();+ std::future::pending::<Result<(), Mp4PipelineError>>().await+ };+ let validation_guard = temporary.clone();+ let worker_abort = abort.clone();+ let worker_failure = failure.clone();+ let validator = tokio::spawn(async move {+ let _guard = validation_guard;+ producer_started_rx.await.unwrap();+ worker_abort.store(true, Ordering::Relaxed);+ worker_failure.notify_one();+ Err(Mp4PipelineError::AudioSourceFailure {+ source_index: 0,+ message: "unused source failed".into(),+ })+ });+ let result = tokio::time::timeout(Duration::from_secs(2), async {+ let (encoder, render, validation) = tokio::join!(+ async { receiver.await.unwrap() },+ render_until_audio_failure(producer, Some(failure.clone())),+ complete_audio_validation(validator, abort.clone(), failure),+ );+ resolve_pipeline_results(encoder, render, validation)+ })+ .await+ .unwrap();+ assert_eq!(result, Err("unused source failed".into()));+ assert!(abort.load(Ordering::Relaxed));+ assert!(!user.load(Ordering::Relaxed));+ assert_eq!(Arc::strong_count(&temporary), 1);+ drop(Arc::try_unwrap(temporary).unwrap());+ assert!(!temporary_path.exists());+ assert!(!output.exists());+ }++ #[tokio::test]+ async fn validator_join_error_notifies_and_aborts() {+ let abort = Arc::new(AtomicBool::new(false));+ let failure = Arc::new(Notify::new());+ let task = tokio::task::spawn_blocking(|| -> Result<(), Mp4PipelineError> {+ panic!("validator wrapper panic");+ });+ let result = complete_audio_validation(task, abort.clone(), failure.clone()).await;+ assert!(matches!(result, Err(Mp4PipelineError::Failure(_))));+ assert!(abort.load(Ordering::Relaxed));+ tokio::time::timeout(Duration::from_secs(2), failure.notified())+ .await+ .unwrap();+ }++ #[test]+ fn temporary_output_is_removed_on_failure_and_never_overwrites() {+ let directory = tempfile::tempdir().unwrap();+ let output = directory.path().join("export.mp4");+ let temporary = temporary_mp4_output(&output).unwrap();+ let path = temporary.to_path_buf();+ std::fs::write(&path, b"partial").unwrap();+ drop(temporary);+ assert!(!path.exists());+ assert!(!output.exists());+ let temporary = temporary_mp4_output(&output).unwrap();+ std::fs::write(&temporary, b"completed").unwrap();+ std::fs::write(&output, b"existing").unwrap();+ drop(temporary.persist_noclobber(&output).unwrap_err());+ assert_eq!(std::fs::read(&output).unwrap(), b"existing");+ assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);+ }++ #[cfg(unix)]+ #[test]+ fn temporary_output_preserves_default_creation_permissions() {+ use std::os::unix::fs::PermissionsExt;+ let directory = tempfile::tempdir().unwrap();+ let output = directory.path().join("export.mp4");+ let reference = directory.path().join("reference.mp4");+ std::fs::write(&reference, b"reference").unwrap();+ let temporary = temporary_mp4_output(&output).unwrap();+ std::fs::write(&temporary, b"completed").unwrap();+ temporary.persist_noclobber(&output).unwrap();+ assert_eq!(+ std::fs::metadata(output).unwrap().permissions().mode() & 0o777,+ std::fs::metadata(reference).unwrap().permissions().mode() & 0o777+ );+ }+#[test]fn silent_audio_frame_matches_renderer_format() {ffmpeg::init().unwrap();