🎥 Make videos programmatically with React
feat(packages/renderer/ffmpeg): better error handling for extract audio function
josefeliuf17cc3135efe1
diff --cc packages/cloudrun/src/gcpInstaller/gcpInstaller.tarindex 998f48b72b,d221ca9448..b3bc46eb12Binary files differdiff --cc packages/compositor-darwin-arm64/compositorindex c0b532aab4,77c87098b1..03959abf9dBinary files differdiff --cc packages/example/public/bigbuckbunny.aacindex 0000000000,0000000000..b88a2d542bnew file mode 100644Binary files differdiff --cc packages/example/public/webcam.aacindex 0000000000,0000000000..e69de29bb2new file mode 100644--- /dev/null+++ b/packages/example/public/webcam.aacdiff --cc packages/example/public/webcam.opusindex 0000000000,0000000000..807b793a99new file mode 100644Binary files differdiff --cc packages/renderer/rust/ffmpeg.rsindex e527e336ad,ac31c4823b..596af38208--- a/packages/renderer/rust/ffmpeg.rs+++ b/packages/renderer/rust/ffmpeg.rs@@@ -276,10 -276,14 +276,26 @@@ pub fn get_video_metadata(file_path: &s}pub fn extract_audio(input_path: &str, output_path: &str) -> Result<(), ErrorWithBacktrace> {-- remotionffmpeg::init().map_err(|e| e.to_string())?;-- let mut ictx = format::input(&input_path).unwrap();- let mut octx = format::output(&output_path).unwrap();++ remotionffmpeg::init().map_err(|e| format!("Initialization error: {}", e))?;++ _print_verbose(&format!(+ "Extracting audio from {} {}",+ input_path, output_path+ ))?;- let mut ictx = format::input(&input_path).unwrap();- let mut octx = format::output(&output_path).unwrap();++++ let mut ictx = format::input(&input_path).map_err(|e| format!("Error reading input from '{}': {}", input_path, e))?;++ let mut octx = format::output(&output_path).map_err(|e| format!("Error setting up output to '{}': {}", output_path, e))?;++++ // Determine the audio codec of the input file++ let audio_stream = match ictx.streams().best(remotionffmpeg::media::Type::Audio) {++ Some(audio_stream) => audio_stream,++ None => Err(std::io::Error::new(++ ErrorKind::Other,++ format!("No audio stream found in '{}'. Ensure the video contains an audio track.", input_path),++ ))?,++ };++++ let audio_codec_id = unsafe { (*(*(audio_stream).as_ptr()).codecpar).codec_id };let mut stream_mapping = vec![-1; ictx.nb_streams() as _];let mut ist_time_bases = vec![Rational(0, 1); ictx.nb_streams() as _];@@@ -291,14 -295,14 +307,20 @@@stream_mapping[ist_index] = ost_index;ist_time_bases[ist_index] = ist.time_base();ost_index += 1;-- let mut ost = octx.add_stream(encoder::find(codec::Id::None)).unwrap();++ let mut ost = octx.add_stream(encoder::find(codec::Id::None)).map_err(|e| format!("Error adding stream: {}", e))?;ost.set_parameters(ist.parameters());unsafe {(*ost.parameters().as_mut_ptr()).codec_tag = 0;}}- octx.write_header()?;- octx.write_header().unwrap();++ octx.write_header().map_err(|e| {++ if e.to_string().contains("ADTS muxer") && audio_codec_id != remotionffmpeg::ffi::AVCodecID::AV_CODEC_ID_AAC {++ format!("Error: The audio format in '{}' is not AAC, and cannot be saved as an .aac file.", input_path)++ } else {++ format!("Error writing header to '{}'. Input audio codec: '{:?}'. Error: {}", output_path, audio_codec_id, e)++ }++ })?;loop {match ictx.get_next_packet() {@@@ -308,17 -312,17 +330,18 @@@if ost_index < 0 {continue;}-- let ost = octx.stream(ost_index as _).unwrap();++ let ost = octx.stream(ost_index as _).unwrap(); // This unwrap can be left as is, since we've ensured the stream existspacket.rescale_ts(ist_time_bases[ist_index], ost.time_base());packet.set_position(-1);packet.set_stream(ost_index as _);-- packet.write_interleaved(&mut octx)?;++ packet.write_interleaved(&mut octx).map_err(|e| format!("Error writing packet: {}", e))?;}Err(remotionffmpeg::Error::Eof) => break, // Break on end of file.-- Err(err) => Err(std::io::Error::new(ErrorKind::Other, err.to_string()))?,++ Err(err) => return Err(ErrorWithBacktrace::from(format!("Error processing packet: {}", err))),};}-- octx.write_trailer()?;++ octx.write_trailer().map_err(|e| format!("Error writing trailer: {}", e))?;Ok(())}++diff --cc packages/renderer/src/compositor/payloads.tsindex 1e68d4e241,6116e83b2b..a1ecb05522--- a/packages/renderer/src/compositor/payloads.ts+++ b/packages/renderer/src/compositor/payloads.ts@@@ -112,8 -112,11 +112,8 @@@ export type CompositorCommand =remaining_bytes: number;};GetVideoMetadata: {src: string};- ExtractAudio: {src: string; outputPath: string};++ ExtractAudio: {input_path: string; output_path: string};VideoMetadata: VideoMetadata;- ExtractAudio: {- input_path: string;- output_path: string;- };};export type CompositorCommandSerialized<T extends keyof CompositorCommand> = {diff --cc packages/renderer/src/extract-audio.tsindex 56e6226a32,40764500c6..2ca810a61f--- a/packages/renderer/src/extract-audio.ts+++ b/packages/renderer/src/extract-audio.ts@@@ -1,19 -1,20 +1,19 @@@import {startLongRunningCompositor} from './compositor/compositor';-import type {VideoMetadata} from './compositor/payloads';import type {LogLevel} from './log-level';- export const extractAudio = async (- videoSourcePath: string,- outputPath: string,- options?: {logLevel?: LogLevel},- ) => {+ export const extractAudio = async (options: {+ videoSource: string;+ audioOutput: string;+ logLevel?: LogLevel;-}): Promise<VideoMetadata> => {++}) => {const compositor = startLongRunningCompositor({maximumFrameCacheItemsInBytes: null,logLevel: options?.logLevel ?? 'info',indent: false,});- const metadataResponse = await compositor.executeCommand('ExtractAudio', {+ await compositor.executeCommand('ExtractAudio', {- src: videoSourcePath,- outputPath,+ input_path: options.videoSource,+ output_path: options.audioOutput,});compositor.finishCommands();await compositor.waitForDone();diff --cc packages/renderer/src/test/extract-audio.test.tsindex 0000000000,f253408b97..b5e47f310fmode 000000,100644..100644--- a/packages/renderer/src/test/extract-audio.test.ts+++ b/packages/renderer/src/test/extract-audio.test.ts@@@ -1,0 -1,11 +1,22 @@@+ import {test} from 'vitest';+ import {extractAudio} from '../extract-audio';+ import {exampleVideos} from './example-videos';+-test('Should be able to extract the audio from a video', async () => {++test('Should be able to extract the audio from a mp4 format video', async () => {++ await extractAudio({++ videoSource: exampleVideos.bigBuckBunny,++ audioOutput: exampleVideos.bigBuckBunny.replace(++ 'bigbuckbunny.mp4',++ 'bigbuckbunny.aac',++ ),++ logLevel: 'verbose',++ });++});++++test('Should be able to extract the audio from a webm format video', async () => {+ await extractAudio({+ videoSource: exampleVideos.webcam,+ audioOutput: exampleVideos.webcam.replace('webcam.webm', 'webcam.aac'),+ logLevel: 'verbose',+ });+ });