Skip to content

🎥 Make videos programmatically with React

golden master

Jonny Burger6087b9f1f738
diff --git a/packages/compositor/rust/cache_references.rs b/packages/compositor/rust/cache_references.rs
index f7acc9e64e..b610b59c81 100644
--- a/packages/compositor/rust/cache_references.rs
+++ b/packages/compositor/rust/cache_references.rs
@@ -50,18 +50,18 @@ impl CacheReferences {
.lock()
.unwrap()
.get_current_cache_size();
+ let mut to_remove: Vec<Vec<FrameCacheReference>> = vec![Vec::new(); self.map.len()];
+
let bytes_to_free = match current_cache_size_in_bytes > maximum_frame_cache_size_in_bytes {
true => current_cache_size_in_bytes - maximum_frame_cache_size_in_bytes,
false => {
- return Ok(Vec::new());
+ return Ok(to_remove);
}
};
let mut removed = 0;
let mut removed_count = 0;
- let mut to_remove: Vec<Vec<FrameCacheReference>> = vec![Vec::new(); self.map.len()];
-
for removal in sorted {
if scope_to_thread_index.is_some()
&& removal.thread_index != scope_to_thread_index.unwrap()
diff --git a/packages/compositor/rust/errors.rs b/packages/compositor/rust/errors.rs
index 7e35350d2f..e9b34b97ab 100644
--- a/packages/compositor/rust/errors.rs
+++ b/packages/compositor/rust/errors.rs
@@ -1,7 +1,7 @@
use crate::frame_cache::FrameCache;
use crate::opened_stream::OpenedStream;
use crate::opened_video_manager::OpenedVideoManager;
-use crate::payloads::payloads::{CliInputCommand, ErrorPayload};
+use crate::payloads::payloads::{CliInputAndMaxCacheSize, ErrorPayload};
use ffmpeg_next as remotionffmpeg;
use png::EncodingError;
use std::any::Any;
@@ -47,7 +47,7 @@ enum PossibleErrors {
WorkerError(Box<dyn Any + Send>),
EncodingError(EncodingError),
ThreadPoolBuilderError(rayon_core::ThreadPoolBuildError),
- SendError(mpsc::SendError<CliInputCommand>),
+ SendError(mpsc::SendError<CliInputAndMaxCacheSize>),
RecvError(mpsc::RecvError),
}
@@ -128,8 +128,8 @@ impl From<rayon_core::ThreadPoolBuildError> for ErrorWithBacktrace {
}
}
-impl From<mpsc::SendError<CliInputCommand>> for ErrorWithBacktrace {
- fn from(err: mpsc::SendError<CliInputCommand>) -> ErrorWithBacktrace {
+impl From<mpsc::SendError<CliInputAndMaxCacheSize>> for ErrorWithBacktrace {
+ fn from(err: mpsc::SendError<CliInputAndMaxCacheSize>) -> ErrorWithBacktrace {
ErrorWithBacktrace {
error: PossibleErrors::SendError(err),
backtrace: Backtrace::force_capture().to_string(),
diff --git a/packages/compositor/rust/ffmpeg.rs b/packages/compositor/rust/ffmpeg.rs
index fbd684f237..cff9425bb9 100644
--- a/packages/compositor/rust/ffmpeg.rs
+++ b/packages/compositor/rust/ffmpeg.rs
@@ -28,6 +28,7 @@ pub fn extract_frame(
thread_index: usize,
manager: &mut OpenedVideoManager,
frame_cache_manager: &mut FrameCacheManager,
+ max_cache_size: u64,
) -> Result<Vec<u8>, ErrorWithBacktrace> {
// Don't allow previous frame, but allow for some flexibility
let cache_item = match manager.get_position_and_threshold_of_video(time, &src) {
@@ -83,6 +84,7 @@ pub fn extract_frame(
tone_mapped,
frame_cache_manager,
thread_index,
+ max_cache_size,
)?;
let from_cache = frame_cache_manager.get_item_from_id(
diff --git a/packages/compositor/rust/frame_cache_manager.rs b/packages/compositor/rust/frame_cache_manager.rs
index b07ab8103b..5248694d08 100644
--- a/packages/compositor/rust/frame_cache_manager.rs
+++ b/packages/compositor/rust/frame_cache_manager.rs
@@ -34,16 +34,22 @@ impl FrameCacheManager {
self.cache.clear();
}
- pub fn prune_on_thread(&mut self) -> Result<(), ErrorWithBacktrace> {
- let to_prune = FRAME_CACHE_REFERENCES.lock().unwrap().get_frames_to_prune(
- max_cache_size::get_instance()
+ pub fn get_to_prune_local(
+ &mut self,
+ max_cache_size: u64,
+ ) -> Result<Vec<FrameCacheReference>, ErrorWithBacktrace> {
+ let to_prune = {
+ FRAME_CACHE_REFERENCES
.lock()
.unwrap()
- .get_value()
- .unwrap(),
- Some(self.thread_index),
- )?;
- let of_thread: Vec<FrameCacheReference> = to_prune.get(self.thread_index).unwrap().to_vec();
+ .get_frames_to_prune(max_cache_size, Some(self.thread_index))?
+ };
+ let of_thread: Vec<FrameCacheReference> = to_prune[self.thread_index].clone();
+ Ok(of_thread)
+ }
+
+ pub fn prune_on_thread(&mut self, max_cache_size: u64) -> Result<(), ErrorWithBacktrace> {
+ let of_thread = self.get_to_prune_local(max_cache_size)?;
self.execute_prune(of_thread, self.thread_index)?;
Ok(())
}
@@ -273,14 +279,16 @@ impl FrameCacheManager {
self.remove_item_by_id(removal)?;
pruned += 1;
}
- _print_verbose(&format!(
- "Pruned {} on thread {} to save memory, keeping {}. Cache size on thread: {}MB, total cache: {}MB",
- pruned,
- 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
- ))?;
+ if pruned > 0 {
+ _print_verbose(&format!(
+ "Pruned {} on thread {} to save memory, keeping {}. Cache size on thread: {}MB, total cache: {}MB",
+ pruned,
+ 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
+ ))?;
+ }
Ok(())
}
diff --git a/packages/compositor/rust/long_running_process.rs b/packages/compositor/rust/long_running_process.rs
index 580e84e352..022318fcd9 100644
--- a/packages/compositor/rust/long_running_process.rs
+++ b/packages/compositor/rust/long_running_process.rs
@@ -11,11 +11,10 @@ use crate::{
commands::execute_command_and_print,
errors::ErrorWithBacktrace,
global_printer::{self, print_error},
- max_cache_size,
memory::is_about_to_run_out_of_memory,
payloads::payloads::{
- parse_cli, CliInputCommand, CliInputCommandPayload, DeleteFramesFromCache, Eof,
- ExtractFrameCommand, FreeUpMemory, OpenVideoStats,
+ parse_cli, CliInputAndMaxCacheSize, CliInputCommand, CliInputCommandPayload,
+ DeleteFramesFromCache, Eof, ExtractFrameCommand, FreeUpMemory, OpenVideoStats,
},
select_right_thread::THREAD_MAP,
thread::WorkerThread,
@@ -23,7 +22,7 @@ use crate::{
pub struct LongRunningProcess {
maximum_frame_cache_size_in_bytes: u64,
- send_to_thread_handles: Vec<Sender<CliInputCommand>>,
+ send_to_thread_handles: Vec<Sender<CliInputAndMaxCacheSize>>,
receive_video_stats_in_main_thread_handles: Vec<mpsc::Receiver<OpenVideoStats>>,
receive_close_video_in_main_thread_handles: Vec<mpsc::Receiver<()>>,
finish_thread_handles: Mutex<Vec<JoinHandle<()>>>,
@@ -49,7 +48,7 @@ impl LongRunningProcess {
}
fn start_thread(&mut self, thread_index: usize) -> JoinHandle<()> {
- let (send_to_thread, receive_in_thread) = mpsc::channel::<CliInputCommand>();
+ let (send_to_thread, receive_in_thread) = mpsc::channel::<CliInputAndMaxCacheSize>();
let (send_video_stats_to_main_thread, receive_video_stats_in_main_thread) =
mpsc::channel::<OpenVideoStats>();
let (send_close_video_to_main_thread, receive_close_video_in_main_thread) =
@@ -82,11 +81,6 @@ impl LongRunningProcess {
}
pub fn start(&mut self) -> Result<(), ErrorWithBacktrace> {
- max_cache_size::get_instance()
- .lock()
- .unwrap()
- .set_value(Some(self.maximum_frame_cache_size_in_bytes));
-
loop {
let mut input = String::new();
let matched = match std::io::stdin().read_line(&mut input) {
@@ -99,9 +93,12 @@ impl LongRunningProcess {
input = matched.trim().to_string();
if input == "EOF" {
for i in 0..self.send_to_thread_handles.len() {
- self.send_to_thread_handles[i].send(CliInputCommand {
- payload: CliInputCommandPayload::Eof(Eof {}),
- nonce: "".to_string(),
+ self.send_to_thread_handles[i].send(CliInputAndMaxCacheSize {
+ cli_input: CliInputCommand {
+ payload: CliInputCommandPayload::Eof(Eof {}),
+ nonce: "".to_string(),
+ },
+ max_cache_size: self.maximum_frame_cache_size_in_bytes,
})?;
}
break;
@@ -135,7 +132,10 @@ impl LongRunningProcess {
}
let input_to_send = parse_cli(&input)?;
- self.send_to_thread_handles[thread_to_use.thread_id].send(input_to_send)?;
+ self.send_to_thread_handles[thread_to_use.thread_id].send(CliInputAndMaxCacheSize {
+ cli_input: input_to_send,
+ max_cache_size: self.maximum_frame_cache_size_in_bytes,
+ })?;
Ok(())
}
@@ -145,7 +145,10 @@ impl LongRunningProcess {
nonce: String,
) -> Result<(), ErrorWithBacktrace> {
for handle in &self.send_to_thread_handles {
- handle.send(opts.clone())?;
+ handle.send(CliInputAndMaxCacheSize {
+ cli_input: opts.clone(),
+ max_cache_size: self.maximum_frame_cache_size_in_bytes,
+ })?;
}
let mut open_video_stats_all: Vec<OpenVideoStats> = vec![];
@@ -179,7 +182,10 @@ impl LongRunningProcess {
nonce: String,
) -> Result<(), ErrorWithBacktrace> {
for handle in &self.send_to_thread_handles {
- handle.send(opts.clone())?;
+ handle.send(CliInputAndMaxCacheSize {
+ cli_input: opts.clone(),
+ max_cache_size: self.maximum_frame_cache_size_in_bytes,
+ })?;
}
for handle in &self.receive_close_video_in_main_thread_handles {
@@ -200,11 +206,14 @@ impl LongRunningProcess {
continue;
}
let first_item = thread.get(0).unwrap();
- self.send_to_thread_handles[first_item.thread_index].send(CliInputCommand {
- payload: CliInputCommandPayload::DeleteFramesFromCache(DeleteFramesFromCache {
- cache_references: thread,
- }),
- nonce: "".to_string(),
+ self.send_to_thread_handles[first_item.thread_index].send(CliInputAndMaxCacheSize {
+ cli_input: CliInputCommand {
+ payload: CliInputCommandPayload::DeleteFramesFromCache(DeleteFramesFromCache {
+ cache_references: thread,
+ }),
+ nonce: "".to_string(),
+ },
+ max_cache_size: self.maximum_frame_cache_size_in_bytes,
})?;
}
Ok(())
@@ -212,10 +221,7 @@ impl LongRunningProcess {
fn emergency_memory_free_up(&mut self) -> Result<(), ErrorWithBacktrace> {
self.prune(self.maximum_frame_cache_size_in_bytes / 2)?;
- max_cache_size::get_instance()
- .lock()
- .unwrap()
- .set_value(Some(self.maximum_frame_cache_size_in_bytes / 2));
+ self.maximum_frame_cache_size_in_bytes /= 2;
Ok(())
}
fn keep_only_latest_frames(&mut self) -> Result<(), ErrorWithBacktrace> {
@@ -253,9 +259,7 @@ impl LongRunningProcess {
print_error(&nonce, _result.err().unwrap())
}
- 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() {
+ if is_about_to_run_out_of_memory() {
self.emergency_memory_free_up()?;
}
diff --git a/packages/compositor/rust/max_cache_size.rs b/packages/compositor/rust/max_cache_size.rs
index 7c1683a30a..16020859e5 100644
--- a/packages/compositor/rust/max_cache_size.rs
+++ b/packages/compositor/rust/max_cache_size.rs
@@ -2,7 +2,6 @@ use lazy_static::lazy_static;
use std::sync::Mutex;
pub struct MaxCacheSize {
- max_cache_size: Option<u64>,
current_cache_size: u64,
}
@@ -10,21 +9,10 @@ impl MaxCacheSize {
// Private constructor
fn new() -> Self {
MaxCacheSize {
- max_cache_size: None,
current_cache_size: 0,
}
}
- // Getter for the value
- pub fn get_value(&self) -> Option<u64> {
- self.max_cache_size
- }
-
- // Setter for the value
- pub fn set_value(&mut self, value: Option<u64>) {
- self.max_cache_size = value;
- }
-
pub fn add_to_current_cache_size(&mut self, value: i128) {
self.current_cache_size += value as u64;
}
diff --git a/packages/compositor/rust/opened_stream.rs b/packages/compositor/rust/opened_stream.rs
index df5698d8ec..e788718e39 100644
--- a/packages/compositor/rust/opened_stream.rs
+++ b/packages/compositor/rust/opened_stream.rs
@@ -6,7 +6,7 @@ extern crate ffmpeg_next as remotionffmpeg;
use std::time::UNIX_EPOCH;
use crate::{
- errors::ErrorWithBacktrace, frame_cache::{get_frame_cache_id, FrameCacheItem}, frame_cache_manager::FrameCacheManager, global_printer::_print_verbose, rotation, scalable_frame::{NotRgbFrame, Rotate, ScalableFrame}, tone_map::FilterGraph
+ errors::ErrorWithBacktrace, frame_cache::{get_frame_cache_id, FrameCacheItem}, frame_cache_manager::FrameCacheManager, global_printer::_print_verbose, rotation, scalable_frame::{NotRgbFrame, Rotate, ScalableFrame}, tone_map::FilterGraph
};
pub struct OpenedStream {
@@ -163,6 +163,7 @@ impl OpenedStream {
tone_mapped: bool,
frame_cache_manager: &mut FrameCacheManager,
thread_index: usize,
+ max_cache_size: u64
) -> Result<usize, ErrorWithBacktrace> {
let mut freshly_seeked = false;
let position_to_seek_to = match self.duration_or_zero {
@@ -379,7 +380,7 @@ impl OpenedStream {
items_in_loop += 1;
if items_in_loop % 10 == 0 {
- frame_cache_manager.prune_on_thread()?;
+ frame_cache_manager.prune_on_thread(max_cache_size)?;
}
match stop_after_n_diverging_pts {
diff --git a/packages/compositor/rust/opened_video_manager.rs b/packages/compositor/rust/opened_video_manager.rs
index 15981f6373..370c1b20a0 100644
--- a/packages/compositor/rust/opened_video_manager.rs
+++ b/packages/compositor/rust/opened_video_manager.rs
@@ -126,6 +126,7 @@ impl OpenedVideoManager {
tone_mapped: bool,
frame_cache_manager: &mut FrameCacheManager,
thread_index: usize,
+ max_cache_size: u64,
) -> Result<usize, ErrorWithBacktrace> {
let video = self.streams.get_mut(stream_index).unwrap();
let frame = video.get_frame(
@@ -138,6 +139,7 @@ impl OpenedVideoManager {
tone_mapped,
frame_cache_manager,
thread_index,
+ max_cache_size,
)?;
THREAD_MAP.lock().unwrap().update_stream(
thread_index,
diff --git a/packages/compositor/rust/payloads.rs b/packages/compositor/rust/payloads.rs
index 1e529ba24c..4a71c806c4 100644
--- a/packages/compositor/rust/payloads.rs
+++ b/packages/compositor/rust/payloads.rs
@@ -274,6 +274,12 @@ pub mod payloads {
pub nonce: String,
}
+ #[derive(Serialize, Deserialize, Debug, Clone)]
+ pub struct CliInputAndMaxCacheSize {
+ pub cli_input: CliInputCommand,
+ pub max_cache_size: u64,
+ }
+
pub fn parse_cli(json: &str) -> Result<CliInputCommand, ErrorWithBacktrace> {
let cli_input: CliInputCommand = serde_json::from_str(json)?;
diff --git a/packages/compositor/rust/thread.rs b/packages/compositor/rust/thread.rs
index 50e56296f1..838fe8646a 100644
--- a/packages/compositor/rust/thread.rs
+++ b/packages/compositor/rust/thread.rs
@@ -7,8 +7,8 @@ use crate::{
global_printer::{self, print_error},
opened_video_manager::{make_opened_stream_manager, OpenedVideoManager},
payloads::payloads::{
- CliInputCommand, CliInputCommandPayload, DeleteFramesFromCache, ExtractFrameCommand,
- OpenVideoStats,
+ CliInputAndMaxCacheSize, CliInputCommandPayload, DeleteFramesFromCache,
+ ExtractFrameCommand, OpenVideoStats,
},
};
@@ -17,7 +17,7 @@ pub struct WorkerThread {
frame_cache_manager: FrameCacheManager,
opened_video_manager: OpenedVideoManager,
send_close_video_to_main_thread: Sender<()>,
- receive_in_thread: Receiver<CliInputCommand>,
+ receive_in_thread: Receiver<CliInputAndMaxCacheSize>,
send_video_stats_to_main_thread: Sender<OpenVideoStats>,
}
@@ -25,7 +25,7 @@ impl WorkerThread {
pub fn new(
thread_index: usize,
send_close_video_to_main_thread: Sender<()>,
- receive_in_thread: Receiver<CliInputCommand>,
+ receive_in_thread: Receiver<CliInputAndMaxCacheSize>,
send_video_stats_to_main_thread: Sender<OpenVideoStats>,
) -> Self {
let frame_cache_manager = make_frame_cache_manager(thread_index).unwrap();
@@ -57,6 +57,7 @@ impl WorkerThread {
&mut self,
command: ExtractFrameCommand,
nonce: String,
+ max_cache_size: u64,
) -> Result<(), ErrorWithBacktrace> {
let res = ffmpeg::extract_frame(
command.src,
@@ -67,6 +68,7 @@ impl WorkerThread {
self.thread_index,
&mut self.opened_video_manager,
&mut self.frame_cache_manager,
+ max_cache_size,
)?;
global_printer::synchronized_write_buf(0, &nonce, &res)?;
@@ -105,7 +107,8 @@ impl WorkerThread {
if _message.is_err() {
break;
}
- let message = _message.unwrap();
+ let msg = _message.unwrap();
+ let message = msg.cli_input;
match message.payload {
CliInputCommandPayload::Eof(_) => {
@@ -117,9 +120,11 @@ impl WorkerThread {
let res = (|| -> Result<(), ErrorWithBacktrace> {
match message.payload {
CliInputCommandPayload::CloseAllVideos(_) => self.close_all_videos(),
- CliInputCommandPayload::ExtractFrame(command) => {
- self.handle_extract_frame(command, message.nonce.clone())
- }
+ CliInputCommandPayload::ExtractFrame(command) => self.handle_extract_frame(
+ command,
+ message.nonce.clone(),
+ msg.max_cache_size,
+ ),
CliInputCommandPayload::GetOpenVideoStats(_) => {
self.handle_get_open_video_stats()
}