🎥 Make videos programmatically with React
this is good progress
Jonny Burger03366b34894f
diff --git a/packages/compositor-darwin-arm64/remotion b/packages/compositor-darwin-arm64/remotionindex 2611aeba4b..c71107b23d 100755Binary files a/packages/compositor-darwin-arm64/remotion and b/packages/compositor-darwin-arm64/remotion differdiff --git a/packages/compositor-darwin-x64/remotion b/packages/compositor-darwin-x64/remotionindex deef76cc52..11f87d1a2b 100755Binary files a/packages/compositor-darwin-x64/remotion and b/packages/compositor-darwin-x64/remotion differdiff --git a/packages/compositor-linux-arm64-gnu/remotion b/packages/compositor-linux-arm64-gnu/remotionindex 66c51250d6..26846dbffd 100755Binary files a/packages/compositor-linux-arm64-gnu/remotion and b/packages/compositor-linux-arm64-gnu/remotion differdiff --git a/packages/compositor-linux-arm64-musl/remotion b/packages/compositor-linux-arm64-musl/remotionindex 3b98ff862f..246da49942 100755Binary files a/packages/compositor-linux-arm64-musl/remotion and b/packages/compositor-linux-arm64-musl/remotion differdiff --git a/packages/compositor-linux-x64-gnu/remotion b/packages/compositor-linux-x64-gnu/remotionindex afe4f4abf4..4e189e05c5 100755Binary files a/packages/compositor-linux-x64-gnu/remotion and b/packages/compositor-linux-x64-gnu/remotion differdiff --git a/packages/compositor-linux-x64-musl/remotion b/packages/compositor-linux-x64-musl/remotionindex d61802bf6d..64f31307a5 100755Binary files a/packages/compositor-linux-x64-musl/remotion and b/packages/compositor-linux-x64-musl/remotion differdiff --git a/packages/compositor-win32-x64-msvc/remotion.exe b/packages/compositor-win32-x64-msvc/remotion.exeindex 16b40733ab..496834d1f0 100755Binary files a/packages/compositor-win32-x64-msvc/remotion.exe and b/packages/compositor-win32-x64-msvc/remotion.exe differdiff --git a/packages/compositor/rust/commands/mod.rs b/packages/compositor/rust/commands/mod.rsindex 0c5ea4a33a..6e72f31d09 100644--- a/packages/compositor/rust/commands/mod.rs+++ b/packages/compositor/rust/commands/mod.rs@@ -1,47 +1,12 @@-use crate::errors::ErrorWithBacktrace;-use crate::frame_cache_manager::FrameCacheManager;-use crate::memory::is_about_to_run_out_of_memory;-use crate::opened_video_manager::OpenedVideoManager;-use crate::payloads::payloads::CliInputCommandPayload;-use crate::{ffmpeg, get_silent_parts, max_cache_size};+use crate::errors::{error_to_json, ErrorWithBacktrace};+use crate::payloads::payloads::{CliInputCommand, CliInputCommandPayload};+use crate::{ffmpeg, get_silent_parts, global_printer};use std::io::ErrorKind;-pub fn execute_command(+pub fn execute_command_on_thread(opts: CliInputCommandPayload,- thread_index: usize,- frame_cache_manager: &mut FrameCacheManager,- opened_video_manager: &mut OpenedVideoManager,) -> Result<Vec<u8>, ErrorWithBacktrace> {- let current_maximum_cache_size = max_cache_size::get_instance().lock().unwrap().get_value();-- if is_about_to_run_out_of_memory() && current_maximum_cache_size.is_some() {- ffmpeg::emergency_memory_free_up(frame_cache_manager, thread_index).unwrap();- max_cache_size::get_instance()- .lock()- .unwrap()- .set_value(Some(current_maximum_cache_size.unwrap() / 2));- }-let res = match opts {- CliInputCommandPayload::ExtractFrame(command) => {- let res = ffmpeg::extract_frame(- command.src,- command.original_src,- command.time,- command.transparent,- command.tone_mapped,- current_maximum_cache_size,- thread_index,- opened_video_manager,- frame_cache_manager,- )?;- Ok(res)- }- CliInputCommandPayload::GetOpenVideoStats(_) => {- let res = ffmpeg::get_open_video_stats(frame_cache_manager, opened_video_manager)?;- let str = serde_json::to_string(&res)?;- Ok(str.as_bytes().to_vec())- }CliInputCommandPayload::DeliberatePanic(_) => {// For testing purposeslet hi: Option<usize> = None;@@ -49,20 +14,6 @@ pub fn execute_command(Ok(vec![])}CliInputCommandPayload::Eof(_) => Ok(vec![]),- CliInputCommandPayload::FreeUpMemory(payload) => {- ffmpeg::keep_only_latest_frames_and_close_videos(- payload.remaining_bytes,- opened_video_manager,- frame_cache_manager,- thread_index,- )?;- Ok(vec![])- }- CliInputCommandPayload::CloseAllVideos(_) => {- opened_video_manager.close_all_videos(frame_cache_manager)?;-- Ok(vec![])- }CliInputCommandPayload::StartLongRunningProcess(_command) => Err(std::io::Error::new(ErrorKind::Other,"Cannot start long running process as command",@@ -89,16 +40,26 @@ pub fn execute_command(ffmpeg::extract_audio(&_command.input_path, &_command.output_path)?;Ok(vec![])}+ _ => {+ panic!("Command not implemented");+ }};- if current_maximum_cache_size.is_some() {- ffmpeg::keep_only_latest_frames_and_close_videos(- current_maximum_cache_size.unwrap(),- opened_video_manager,- frame_cache_manager,- thread_index,- )- .unwrap();- }return res;}++pub fn execute_command_and_print(message: CliInputCommand) -> Result<(), ErrorWithBacktrace> {+ match execute_command_on_thread(message.payload.clone()) {+ Ok(res) => {+ global_printer::synchronized_write_buf(0, &message.nonce, &res).unwrap()+ // TODO: Unwrap+ }+ Err(err) => global_printer::synchronized_write_buf(+ 1,+ &message.nonce,+ &error_to_json(err).unwrap().as_bytes(),+ )+ .unwrap(), // TODO: Unwrap+ };+ Ok(())+}diff --git a/packages/compositor/rust/errors.rs b/packages/compositor/rust/errors.rsindex a82027e1f0..7ea65c1559 100644--- a/packages/compositor/rust/errors.rs+++ b/packages/compositor/rust/errors.rs@@ -2,13 +2,15 @@ use crate::frame_cache::FrameCache;use crate::opened_stream::OpenedStream;use crate::opened_video::OpenedVideo;use crate::opened_video_manager::OpenedVideoManager;-use crate::payloads::payloads::ErrorPayload;+use crate::payloads::payloads::{CliInputCommand, ErrorPayload};use ffmpeg_next as remotionffmpeg;use png::EncodingError;use std::any::Any;use std::backtrace::Backtrace;use std::collections::HashMap;-use std::sync::{Mutex, MutexGuard, PoisonError, RwLockReadGuard, RwLockWriteGuard, TryLockError};+use std::sync::{+ mpsc, Mutex, MutexGuard, PoisonError, RwLockReadGuard, RwLockWriteGuard, TryLockError,+};pub fn error_to_string(err: &ErrorWithBacktrace) -> String {match &err.error {@@ -20,6 +22,7 @@ pub fn error_to_string(err: &ErrorWithBacktrace) -> String {PossibleErrors::WorkerError(err) => format!("{:?}", err),PossibleErrors::EncodingError(err) => err.to_string(),PossibleErrors::ThreadPoolBuilderError(err) => err.to_string(),+ PossibleErrors::SendError(err) => format!("{:?}", err),}}@@ -46,6 +49,7 @@ enum PossibleErrors {WorkerError(Box<dyn Any + Send>),EncodingError(EncodingError),ThreadPoolBuilderError(rayon_core::ThreadPoolBuildError),+ SendError(mpsc::SendError<CliInputCommand>),}pub struct ErrorWithBacktrace {@@ -125,6 +129,15 @@ impl From<rayon_core::ThreadPoolBuildError> for ErrorWithBacktrace {}}+impl From<mpsc::SendError<CliInputCommand>> for ErrorWithBacktrace {+ fn from(err: mpsc::SendError<CliInputCommand>) -> ErrorWithBacktrace {+ ErrorWithBacktrace {+ error: PossibleErrors::SendError(err),+ backtrace: Backtrace::force_capture().to_string(),+ }+ }+}+impl From<&str> for ErrorWithBacktrace {fn from(err: &str) -> ErrorWithBacktrace {ErrorWithBacktrace {@@ -232,6 +245,7 @@ impl std::fmt::Debug for ErrorWithBacktrace {PossibleErrors::ThreadPoolBuilderError(err) => {write!(f, "ThreadPoolBuilderError: {:?}", err)}+ PossibleErrors::SendError(err) => write!(f, "SendError: {:?}", err),}}}diff --git a/packages/compositor/rust/frame_cache_manager.rs b/packages/compositor/rust/frame_cache_manager.rsindex 0dd55efbb4..418f922348 100644--- a/packages/compositor/rust/frame_cache_manager.rs+++ b/packages/compositor/rust/frame_cache_manager.rs@@ -164,6 +164,10 @@ impl FrameCacheManager {.lock().unwrap().get_current_cache_size();+ _print_verbose(&format!(+ "cache size {} {}",+ current_cache_size_in_bytes, maximum_frame_cache_size_in_bytes+ ))?;if current_cache_size_in_bytes < maximum_frame_cache_size_in_bytes {break;}@@ -183,10 +187,10 @@ impl FrameCacheManager {if pruned > 0 {_print_verbose(&format!(- "Pruned {} to save memory, keeping {}. Cache size on thread {}: {}MB, total cache: {}MB",+ "Pruned {} on thread {} to save memory, keeping {}. Cache size on thread: {}MB, total cache: {}MB",pruned,- self.get_frames_in_cache()?,thread_index,+ self.get_frames_in_cache()?,self.get_total_size()? / 1024 / 1024,max_cache_size::get_instance().lock().unwrap().get_current_cache_size() / 1024 / 1024))?;diff --git a/packages/compositor/rust/main.rs b/packages/compositor/rust/main.rsindex a317efc6f3..fe95b7898f 100644--- a/packages/compositor/rust/main.rs+++ b/packages/compositor/rust/main.rs@@ -18,17 +18,17 @@ mod scalable_frame;mod select_right_thread;mod tone_map;-use commands::execute_command;-use errors::{error_to_json, ErrorWithBacktrace};+use commands::execute_command_and_print;+use errors::ErrorWithBacktrace;use frame_cache_manager::make_frame_cache_manager;use global_printer::{_print_verbose, set_verbose_logging};-use memory::get_ideal_maximum_frame_cache_size;+use memory::{get_ideal_maximum_frame_cache_size, is_about_to_run_out_of_memory};use opened_video_manager::make_opened_stream_manager;use std::env;use std::sync::mpsc;use std::thread;-use payloads::payloads::{parse_cli, CliInputCommand, CliInputCommandPayload, Eof};+use payloads::payloads::{parse_cli, CliInputCommand, CliInputCommandPayload, Eof, OpenVideoStats};extern crate png;@@ -45,9 +45,6 @@ fn mainfn() -> Result<(), ErrorWithBacktrace> {let opts: CliInputCommand = parse_init_command(&first_arg)?;- let mut frame_cache_manager = make_frame_cache_manager().unwrap();- let mut open_video_manager = make_opened_stream_manager().unwrap();-match opts.payload {CliInputCommandPayload::StartLongRunningProcess(payload) => {set_verbose_logging(payload.verbose);@@ -65,13 +62,7 @@ fn mainfn() -> Result<(), ErrorWithBacktrace> {start_long_running_process(payload.concurrency, max_video_cache_size)?;}_ => {- let data = execute_command(- opts.payload,- 0,- &mut frame_cache_manager,- &mut open_video_manager,- )?;- global_printer::synchronized_write_buf(0, &opts.nonce, &data)?;+ execute_command_and_print(opts)?;}}@@ -88,45 +79,111 @@ fn start_long_running_process(threads: usize,maximum_frame_cache_size_in_bytes: u64,) -> Result<(), ErrorWithBacktrace> {- let mut thread_handles = vec![];- let mut send_handles = vec![];+ let mut finish_thread_handles = vec![];+ let mut send_to_thread_handles = vec![];+ let mut receive_video_stats_in_main_thread_handles: Vec<mpsc::Receiver<OpenVideoStats>> =+ vec![];+ let mut receive_close_video_in_main_thread_handles: Vec<mpsc::Receiver<()>> = vec![];+ let mut receive_free_in_main_thread_handles: Vec<mpsc::Receiver<()>> = vec![];let mut thread_map = select_right_thread::ThreadMap::new(threads);+for thread_index in 0..threads {- let (tx, rx) = mpsc::channel::<CliInputCommand>();+ let (send_to_thread, receive_in_thread) = mpsc::channel::<CliInputCommand>();+ let (send_video_stats_to_main_thread, receive_video_stats_in_main_thread) =+ mpsc::channel::<OpenVideoStats>();+ let (send_free_to_main_thread, receive_free_in_main_thread) = mpsc::channel::<()>();+ let (send_close_video_to_main_thread, receive_close_video_in_main_thread) =+ mpsc::channel::<()>();- let handle = thread::spawn(move || {+ let wait_for_thread_finish = thread::spawn(move || {let mut frame_cache_manager = make_frame_cache_manager().unwrap();let mut opened_video_manager = make_opened_stream_manager().unwrap();- while let Ok(message) = rx.recv() {+ while let Ok(message) = receive_in_thread.recv() {+ let current_maximum_cache_size =+ max_cache_size::get_instance().lock().unwrap().get_value();++ if is_about_to_run_out_of_memory() && current_maximum_cache_size.is_some() {+ ffmpeg::emergency_memory_free_up(&mut frame_cache_manager, thread_index)+ .unwrap();+ max_cache_size::get_instance()+ .lock()+ .unwrap()+ .set_value(Some(current_maximum_cache_size.unwrap() / 2));+ }+match message.payload {CliInputCommandPayload::Eof(_) => {break;}+ CliInputCommandPayload::CloseAllVideos(_) => {+ opened_video_manager+ .close_all_videos(&mut frame_cache_manager)+ .unwrap(); // TODO: UNWRAP+ send_close_video_to_main_thread.send(()).unwrap();+ continue;+ }+ CliInputCommandPayload::ExtractFrame(command) => {+ let res = ffmpeg::extract_frame(+ command.src,+ command.original_src,+ command.time,+ command.transparent,+ command.tone_mapped,+ current_maximum_cache_size,+ thread_index,+ &mut opened_video_manager,+ &mut frame_cache_manager,+ )+ .unwrap(); // TODO: Unwrpa+ global_printer::synchronized_write_buf(0, &message.nonce, &res).unwrap();+ if current_maximum_cache_size.is_some() {+ ffmpeg::keep_only_latest_frames_and_close_videos(+ current_maximum_cache_size.unwrap(),+ &mut opened_video_manager,+ &mut frame_cache_manager,+ thread_index,+ )+ .unwrap(); // TODO: Unwrap+ }++ continue;+ }+ CliInputCommandPayload::FreeUpMemory(payload) => {+ _print_verbose(&format!("remaining {}", payload.remaining_bytes)).unwrap();+ ffmpeg::keep_only_latest_frames_and_close_videos(+ payload.remaining_bytes,+ &mut opened_video_manager,+ &mut frame_cache_manager,+ thread_index,+ )+ .unwrap(); // TODO: Unwrap++ send_free_to_main_thread.send(()).unwrap();+ continue;+ }+ CliInputCommandPayload::GetOpenVideoStats(_) => {+ let res = ffmpeg::get_open_video_stats(+ &mut frame_cache_manager,+ &mut opened_video_manager,+ )+ .unwrap();+ send_video_stats_to_main_thread.send(res.clone()).unwrap(); // TODO: unwrao+ continue;+ }_ => (),}- match execute_command(- message.payload,- thread_index,- &mut frame_cache_manager,- &mut opened_video_manager,- ) {- Ok(res) => {- global_printer::synchronized_write_buf(0, &message.nonce, &res).unwrap()- }- Err(err) => global_printer::synchronized_write_buf(- 1,- &message.nonce,- &error_to_json(err).unwrap().as_bytes(),- )- .unwrap(),- };++ execute_command_and_print(message).unwrap();}// Thread work here});- send_handles.push(tx);- thread_handles.push(handle);+ send_to_thread_handles.push(send_to_thread);+ receive_video_stats_in_main_thread_handles.push(receive_video_stats_in_main_thread);+ receive_close_video_in_main_thread_handles.push(receive_close_video_in_main_thread);+ receive_free_in_main_thread_handles.push(receive_free_in_main_thread);+ finish_thread_handles.push(wait_for_thread_finish);}max_cache_size::get_instance()@@ -145,8 +202,8 @@ fn start_long_running_process(input = matched.trim().to_string();if input == "EOF" {- for handle in send_handles {- handle+ for send_handle in send_to_thread_handles {+ send_handle.send(CliInputCommand {payload: CliInputCommandPayload::Eof(Eof {}),nonce: "".to_string(),@@ -157,17 +214,70 @@ fn start_long_running_process(}let opts: CliInputCommand = parse_cli(&input)?;- let opts_again: CliInputCommand = parse_cli(&input)?;- let thread_id = match opts.payload {- CliInputCommandPayload::ExtractFrame(command) => thread_map- .select_right_thread(&command.src, command.time)- .unwrap(),- _ => 0,+ let nonce = opts.nonce.clone();+ let _result: Result<(), ErrorWithBacktrace> = match opts.payload {+ CliInputCommandPayload::ExtractFrame(command) => {+ let thread_id = thread_map.select_right_thread(+ &command.src,+ command.time,+ command.transparent,+ )?;+ let input_to_send = parse_cli(&input)?;+ _print_verbose(&format!("sending {:?} {:?}", input, thread_id))?;+ send_to_thread_handles[thread_id].send(input_to_send)?;+ Ok(())+ }+ CliInputCommandPayload::GetOpenVideoStats(_) => {+ for handle in &send_to_thread_handles {+ handle.send(opts.clone()).unwrap();+ }++ let mut open_video_stats_all: Vec<OpenVideoStats> = vec![];+ for handle in &receive_video_stats_in_main_thread_handles {+ let data = handle.recv().unwrap();+ open_video_stats_all.push(data.clone());+ }+ let concated: OpenVideoStats = OpenVideoStats {+ frames_in_cache: open_video_stats_all.iter().map(|x| x.frames_in_cache).sum(),+ open_streams: open_video_stats_all.iter().map(|x| x.open_streams).sum(),+ open_videos: open_video_stats_all.iter().map(|x| x.open_videos).sum(),+ };+ let str = serde_json::to_string(&concated)?;+ global_printer::synchronized_write_buf(0, &nonce, &str.as_bytes())?;+ Ok(())+ }+ CliInputCommandPayload::FreeUpMemory(_) => {+ for handle in &send_to_thread_handles {+ handle.send(opts.clone()).unwrap();+ }++ for handle in &receive_free_in_main_thread_handles {+ handle.recv().unwrap();+ }+ // TODO: Is "Hi" right?+ global_printer::synchronized_write_buf(0, &nonce, &format!("hi").as_bytes())?;+ Ok(())+ }+ CliInputCommandPayload::CloseAllVideos(_) => {+ for handle in &send_to_thread_handles {+ handle.send(opts.clone()).unwrap();+ }++ for handle in &receive_close_video_in_main_thread_handles {+ handle.recv().unwrap();+ }+ // TODO: Is "Hi" right?+ global_printer::synchronized_write_buf(0, &nonce, &format!("hi").as_bytes())?;+ Ok(())+ }+ _ => {+ execute_command_and_print(opts).unwrap();+ Ok(())+ }};- send_handles[thread_id].send(opts_again).unwrap();}- for handle in thread_handles {+ for handle in finish_thread_handles {handle.join().unwrap();}diff --git a/packages/compositor/rust/payloads.rs b/packages/compositor/rust/payloads.rsindex ba1b37715a..c6c8126c3f 100644--- a/packages/compositor/rust/payloads.rs+++ b/packages/compositor/rust/payloads.rs@@ -37,7 +37,7 @@ pub mod payloads {Jpeg,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct ExtractFrameCommand {pub src: String,pub original_src: String,@@ -46,7 +46,7 @@ pub mod payloads {pub tone_mapped: bool,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]#[allow(non_snake_case)]pub struct GetSilences {pub src: String,@@ -54,23 +54,23 @@ pub mod payloads {pub minDurationInSeconds: f64,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct StartPayLoad {pub concurrency: usize,pub maximum_frame_cache_size_in_bytes: Option<u64>,pub verbose: bool,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct GetOpenVideoStats {}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct DeliberatePanic {}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct CloseAllVideos {}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct OpenVideoStats {pub open_videos: usize,pub open_streams: usize,@@ -223,31 +223,31 @@ pub mod payloads {pub durationInSeconds: f64,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct FreeUpMemory {pub remaining_bytes: u64,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct EchoPayload {pub message: String,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct GetVideoMetadata {pub src: String,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct ExtractAudio {pub input_path: String,pub output_path: String,}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct Eof {}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]#[serde(tag = "type", content = "params")]pub enum CliInputCommandPayload {ExtractFrame(ExtractFrameCommand),@@ -263,7 +263,7 @@ pub mod payloads {Eof(Eof),}- #[derive(Serialize, Deserialize, Debug)]+ #[derive(Serialize, Deserialize, Debug, Clone)]pub struct CliInputCommand {pub payload: CliInputCommandPayload,pub nonce: String,diff --git a/packages/compositor/rust/select_right_thread.rs b/packages/compositor/rust/select_right_thread.rsindex a1c482a55c..5969bcd37d 100644--- a/packages/compositor/rust/select_right_thread.rs+++ b/packages/compositor/rust/select_right_thread.rs@@ -3,6 +3,7 @@ use crate::{errors::ErrorWithBacktrace, global_printer::_print_verbose};struct OpenStream {src: String,last_time: f64,+ transparent: bool,}struct ThreadStreams {@@ -30,6 +31,7 @@ impl ThreadMap {&mut self,src: &String,time: f64,+ transparent: bool,) -> Result<usize, ErrorWithBacktrace> {for thread_id in 0..self.map.len() {let thread_streams = self.map[thread_id].as_mut();@@ -37,8 +39,8 @@ impl ThreadMap {continue;}for stream in &mut thread_streams.unwrap().streams {- if &stream.src == src {- if (stream.last_time - time).abs() <= 10.0 {+ if &stream.src == src && stream.transparent && transparent {+ if (stream.last_time - time).abs() < 5.0 {stream.last_time = time;_print_verbose(&format!("Reusing thread {} for stream {} at time {}",@@ -88,6 +90,7 @@ impl ThreadMap {new_thread_streams.streams.push(OpenStream {src: src.clone(),last_time: time,+ transparent,});_print_verbose(&format!(