Skip to content

🎥 Make videos programmatically with React

`@remotion/compositor`: Use 3 threads by default, better memory management

Jonny Burger44516714a4e8
diff --git a/packages/compositor-darwin-arm64/remotion b/packages/compositor-darwin-arm64/remotion
index c17a35d207..5535d8c49c 100755
Binary files a/packages/compositor-darwin-arm64/remotion and b/packages/compositor-darwin-arm64/remotion differ
diff --git a/packages/compositor/rust/cache_references.rs b/packages/compositor/rust/cache_references.rs
index b610b59c81..e71549bb17 100644
--- a/packages/compositor/rust/cache_references.rs
+++ b/packages/compositor/rust/cache_references.rs
@@ -46,14 +46,25 @@ impl CacheReferences {
let mut sorted = references.clone();
sorted.sort_by(|a, b| a.last_used.cmp(&b.last_used));
- let current_cache_size_in_bytes = max_cache_size::get_instance()
- .lock()
- .unwrap()
- .get_current_cache_size();
+ let max_cache_size = max_cache_size::get_instance().lock().unwrap();
+
+ let current_cache_size_in_bytes = match scope_to_thread_index {
+ Some(index) => max_cache_size.get_cache_size_for_thread(index),
+ None => max_cache_size.get_current_cache_size(),
+ };
+ let max_allowed_cache_size = match scope_to_thread_index {
+ Some(_) => maximum_frame_cache_size_in_bytes / max_cache_size.thread_count() as u64,
+ None => maximum_frame_cache_size_in_bytes,
+ };
+ _print_verbose(&format!(
+ "max allowed cache size {}, thread {:?}",
+ max_allowed_cache_size, scope_to_thread_index
+ ));
+
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,
+ let bytes_to_free = match current_cache_size_in_bytes > max_allowed_cache_size {
+ true => current_cache_size_in_bytes - max_allowed_cache_size,
false => {
return Ok(to_remove);
}
diff --git a/packages/compositor/rust/ffmpeg.rs b/packages/compositor/rust/ffmpeg.rs
index 69ffae1088..f46f3260b4 100644
--- a/packages/compositor/rust/ffmpeg.rs
+++ b/packages/compositor/rust/ffmpeg.rs
@@ -53,7 +53,8 @@ pub fn extract_frame(
)?);
}
- let vid_index = manager.get_video_index(&src, &original_src, transparent, time)?;
+ let vid_index =
+ manager.get_video_index(&src, &original_src, transparent, time, thread_index)?;
let vid = manager.get_video(vid_index)?;
// The requested position in the video.
let position = calc_position(time, vid.time_base);
diff --git a/packages/compositor/rust/frame_cache.rs b/packages/compositor/rust/frame_cache.rs
index 1bb076b78b..4ce29e541b 100644
--- a/packages/compositor/rust/frame_cache.rs
+++ b/packages/compositor/rust/frame_cache.rs
@@ -82,11 +82,11 @@ impl FrameCache {
Ok(references)
}
- pub fn add_item(&mut self, item: FrameCacheItem) {
+ pub fn add_item(&mut self, item: FrameCacheItem, thread_index: usize) {
max_cache_size::get_instance()
.lock()
.unwrap()
- .add_to_current_cache_size(item.frame.get_size().into());
+ .add_to_current_cache_size(thread_index, item.frame.get_size().into());
self.items.push(item);
}
@@ -138,11 +138,15 @@ impl FrameCache {
}
}
- pub fn get_item_from_id(&mut self, id: usize) -> Result<Option<Vec<u8>>, ErrorWithBacktrace> {
+ pub fn get_item_from_id(
+ &mut self,
+ id: usize,
+ thread_index: usize,
+ ) -> Result<Option<Vec<u8>>, ErrorWithBacktrace> {
let mut data: Option<Vec<u8>> = None;
for i in 0..self.items.len() {
if self.items[i].id == id {
- self.items[i].frame.ensure_data()?;
+ self.items[i].frame.ensure_data(thread_index)?;
self.items[i].last_used = get_time();
data = Some(self.items[i].frame.get_data()?);
break;
@@ -151,7 +155,11 @@ impl FrameCache {
Ok(data)
}
- pub fn remove_item_by_id(&mut self, id: usize) -> Result<(), ErrorWithBacktrace> {
+ pub fn remove_item_by_id(
+ &mut self,
+ id: usize,
+ thread_index: usize,
+ ) -> Result<(), ErrorWithBacktrace> {
for i in 0..self.items.len() {
if self.items[i].id == id {
if self.last_frame.is_some() && id == self.last_frame.expect("last_frame") {
@@ -161,7 +169,7 @@ impl FrameCache {
max_cache_size::get_instance()
.lock()
.unwrap()
- .remove_from_cache_size(self.items[i].frame.get_size().into());
+ .remove_from_cache_size(thread_index, self.items[i].frame.get_size().into());
self.items.remove(i);
break;
@@ -190,6 +198,7 @@ impl FrameCache {
&mut self,
time: i64,
threshold: i64,
+ thread_index: usize,
) -> Result<Option<usize>, ErrorWithBacktrace> {
let mut best_item: Option<usize> = None;
let mut best_distance = std::i64::MAX;
@@ -199,7 +208,7 @@ impl FrameCache {
match self.last_frame {
Some(last_frame_id) => {
if self.items[i].id == last_frame_id && self.items[i].resolved_pts < time {
- self.items[i].frame.ensure_data()?;
+ self.items[i].frame.ensure_data(thread_index)?;
return Ok(Some(self.items[i].id));
}
@@ -211,7 +220,7 @@ impl FrameCache {
// Exact same time as requested
for i in 0..self.items.len() {
if self.items[i].resolved_pts == time {
- self.items[i].frame.ensure_data()?;
+ self.items[i].frame.ensure_data(thread_index)?;
return Ok(Some(self.items[i].id));
}
}
@@ -298,7 +307,7 @@ impl FrameCache {
match best_item {
Some(best_item) => {
- self.items[best_item].frame.ensure_data()?;
+ self.items[best_item].frame.ensure_data(thread_index)?;
Ok(Some(self.items[best_item].id))
}
None => Ok(None),
diff --git a/packages/compositor/rust/frame_cache_manager.rs b/packages/compositor/rust/frame_cache_manager.rs
index d61bc9f4d2..dca889fafa 100644
--- a/packages/compositor/rust/frame_cache_manager.rs
+++ b/packages/compositor/rust/frame_cache_manager.rs
@@ -99,11 +99,12 @@ impl FrameCacheManager {
transparent: bool,
tone_mapped: bool,
item: FrameCacheItem,
+ thread_index: usize,
) {
self.get_frame_cache(src, original_src, transparent, tone_mapped)
.lock()
.unwrap()
- .add_item(item)
+ .add_item(item, thread_index)
}
pub fn get_item_from_id(
@@ -114,10 +115,11 @@ impl FrameCacheManager {
tone_mapped: bool,
frame_id: usize,
) -> Result<Option<Vec<u8>>, ErrorWithBacktrace> {
+ let thread_index = self.thread_index.clone();
self.get_frame_cache(src, original_src, transparent, tone_mapped)
.lock()
.unwrap()
- .get_item_from_id(frame_id)
+ .get_item_from_id(frame_id, thread_index)
}
pub fn set_last_frame(
@@ -168,10 +170,11 @@ impl FrameCacheManager {
time: i64,
threshold: i64,
) -> Result<Option<usize>, ErrorWithBacktrace> {
+ let thread_index = self.thread_index.clone();
Ok(self
.get_frame_cache(src, original_src, transparent, tone_mapped)
.lock()?
- .get_item_id(time, threshold)?)
+ .get_item_id(time, threshold, thread_index)?)
}
pub fn get_cache_item_from_id(
@@ -182,10 +185,11 @@ impl FrameCacheManager {
tone_mapped: bool,
frame_id: usize,
) -> Result<Vec<u8>, ErrorWithBacktrace> {
+ let thread_index = self.thread_index.clone();
match self
.get_frame_cache(src, original_src, transparent, tone_mapped)
.lock()?
- .get_item_from_id(frame_id)?
+ .get_item_from_id(frame_id, thread_index)?
{
Some(item) => Ok(item),
None => Err(ErrorWithBacktrace::from("No item found in cache")),
@@ -280,7 +284,7 @@ impl FrameCacheManager {
removal.tone_mapped,
)
.lock()?
- .remove_item_by_id(removal.id)?;
+ .remove_item_by_id(removal.id, removal.thread_index)?;
Ok(())
}
diff --git a/packages/compositor/rust/long_running_process.rs b/packages/compositor/rust/long_running_process.rs
index 022318fcd9..18872143b5 100644
--- a/packages/compositor/rust/long_running_process.rs
+++ b/packages/compositor/rust/long_running_process.rs
@@ -124,9 +124,18 @@ impl LongRunningProcess {
) -> Result<(), ErrorWithBacktrace> {
let thread_to_use = THREAD_MAP.lock().unwrap().select_right_thread(
&command.src,
+ &command.original_src,
command.time,
command.transparent,
)?;
+ THREAD_MAP.lock().unwrap().update_thread_map(
+ thread_to_use.thread_id,
+ thread_to_use.stream_id,
+ command.src,
+ command.time,
+ command.transparent,
+ );
+
if thread_to_use.thread_id == self.send_to_thread_handles.len() {
self.start_new_thread(thread_to_use.thread_id)?;
}
diff --git a/packages/compositor/rust/max_cache_size.rs b/packages/compositor/rust/max_cache_size.rs
index 16020859e5..167bd11b39 100644
--- a/packages/compositor/rust/max_cache_size.rs
+++ b/packages/compositor/rust/max_cache_size.rs
@@ -1,26 +1,42 @@
use lazy_static::lazy_static;
+use std::collections::HashMap;
use std::sync::Mutex;
pub struct MaxCacheSize {
- current_cache_size: u64,
+ thread_cache_sizes: HashMap<usize, u64>,
}
impl MaxCacheSize {
// Private constructor
fn new() -> Self {
MaxCacheSize {
- current_cache_size: 0,
+ thread_cache_sizes: HashMap::new(),
}
}
- pub fn add_to_current_cache_size(&mut self, value: i128) {
- self.current_cache_size += value as u64;
+ pub fn add_to_current_cache_size(&mut self, thread_index: usize, value: i128) {
+ let entry = self.thread_cache_sizes.entry(thread_index).or_insert(0);
+ *entry += value as u64;
}
- pub fn remove_from_cache_size(&mut self, value: i128) {
- self.current_cache_size -= value as u64;
+
+ pub fn remove_from_cache_size(&mut self, thread_index: usize, value: i128) {
+ let entry = self.thread_cache_sizes.entry(thread_index).or_insert(0);
+ *entry -= value as u64;
}
+
pub fn get_current_cache_size(&self) -> u64 {
- self.current_cache_size
+ self.thread_cache_sizes.values().sum()
+ }
+
+ pub fn get_cache_size_for_thread(&self, thread_index: usize) -> u64 {
+ match self.thread_cache_sizes.get(&thread_index) {
+ Some(size) => *size,
+ None => 0,
+ }
+ }
+
+ pub fn thread_count(&self) -> usize {
+ self.thread_cache_sizes.len()
}
}
diff --git a/packages/compositor/rust/opened_stream.rs b/packages/compositor/rust/opened_stream.rs
index 33270228e1..e2cc0c399d 100644
--- a/packages/compositor/rust/opened_stream.rs
+++ b/packages/compositor/rust/opened_stream.rs
@@ -77,6 +77,7 @@ impl OpenedStream {
previous_pts: Option<i64>,
tone_mapped: bool,
frame_cache_manager: &mut FrameCacheManager,
+ thread_index: usize
) -> Result<Option<LastFrameInfo>, ErrorWithBacktrace> {
self.video.send_eof()?;
@@ -131,7 +132,8 @@ impl OpenedStream {
&self.original_src,
self.transparent,
tone_mapped,
- item
+ item,
+ thread_index
);
latest_frame = Some(LastFrameInfo {
index: frame_cache_id,
@@ -242,7 +244,8 @@ impl OpenedStream {
false => Some(self.last_position.unwrap()),
},
tone_mapped,
- frame_cache_manager
+ frame_cache_manager,
+ thread_index
)?;
if data.is_some() {
last_frame_received = data;
@@ -373,7 +376,8 @@ impl OpenedStream {
&self.original_src,
self.transparent,
tone_mapped,
- item
+ item,
+ thread_index
);
frame_cache_manager.copy_to_global().unwrap();
diff --git a/packages/compositor/rust/opened_video_manager.rs b/packages/compositor/rust/opened_video_manager.rs
index 99cf0d58e3..ba04471ca9 100644
--- a/packages/compositor/rust/opened_video_manager.rs
+++ b/packages/compositor/rust/opened_video_manager.rs
@@ -76,6 +76,7 @@ impl OpenedVideoManager {
original_src: &str,
transparent: bool,
time: f64,
+ thread_index: usize,
) -> Result<usize, ErrorWithBacktrace> {
for i in 0..self.streams.len() {
let stream = self.streams.get(i).unwrap();
@@ -104,8 +105,8 @@ impl OpenedVideoManager {
self.streams.push(stream);
let stream_index = self.streams.len() - 1;
_print_debug(&format!(
- "Opening new stream, src = {}, index = {}, desired time = {}",
- src, stream_index, time
+ "Opening new stream on thread {}, src = {}, index = {}, desired time = {}",
+ thread_index, original_src, stream_index, time
))?;
Ok(stream_index)
diff --git a/packages/compositor/rust/scalable_frame.rs b/packages/compositor/rust/scalable_frame.rs
index 0e77eeaba6..a3d387b861 100644
--- a/packages/compositor/rust/scalable_frame.rs
+++ b/packages/compositor/rust/scalable_frame.rs
@@ -67,7 +67,7 @@ impl ScalableFrame {
}
}
- pub fn ensure_data(&mut self) -> Result<(), ErrorWithBacktrace> {
+ pub fn ensure_data(&mut self, thread_index: usize) -> Result<(), ErrorWithBacktrace> {
if self.rgb_frame.is_some() {
return Ok(());
}
@@ -132,12 +132,15 @@ impl ScalableFrame {
max_cache_size::get_instance()
.lock()
.unwrap()
- .add_to_current_cache_size((size_after - size_before) as i128);
+ .add_to_current_cache_size(
+ thread_index,
+ (size_after - size_before) as i128,
+ );
} else {
max_cache_size::get_instance()
.lock()
.unwrap()
- .remove_from_cache_size((size_before - size_after) as i128);
+ .remove_from_cache_size(thread_index, (size_before - size_after) as i128);
}
Ok(())
}
diff --git a/packages/compositor/rust/select_right_thread.rs b/packages/compositor/rust/select_right_thread.rs
index 3d62b2a4e5..b75657236c 100644
--- a/packages/compositor/rust/select_right_thread.rs
+++ b/packages/compositor/rust/select_right_thread.rs
@@ -23,7 +23,7 @@ pub struct ThreadMap {
#[derive(PartialEq, Debug, Clone)]
pub struct UseThisThread {
pub thread_id: usize,
- pub stream_id: Option<usize>,
+ pub stream_id: usize,
}
impl ThreadMap {
@@ -55,7 +55,12 @@ impl ThreadMap {
// Update stream if it exists
for stream in self.map[thread_index].streams.iter_mut() {
if stream.id == stream_index {
+ let duration_before = stream.duration_in_seconds;
self.map[thread_index].streams[stream_index] = stream_to_set;
+ if duration_before.is_some() {
+ self.map[thread_index].streams[stream_index].duration_in_seconds =
+ duration_before;
+ }
return;
}
}
@@ -64,9 +69,31 @@ impl ThreadMap {
self.map[thread_index].streams.push(stream_to_set);
}
+ pub fn update_thread_map(
+ &mut self,
+ thread_index: usize,
+ stream_index: usize,
+ src: String,
+ last_time: f64,
+ transparent: bool,
+ ) {
+ self.update_stream(
+ thread_index,
+ stream_index,
+ OpenStream {
+ src,
+ last_time,
+ id: stream_index,
+ transparent,
+ duration_in_seconds: None,
+ },
+ );
+ }
+
pub fn select_right_thread(
&mut self,
src: &String,
+ original_src: &String,
time: f64,
transparent: bool,
) -> Result<UseThisThread, ErrorWithBacktrace> {
@@ -88,11 +115,11 @@ impl ThreadMap {
}
_print_verbose(&format!(
"Reusing thread {} for stream {} at time {}",
- thread_id, src, time
+ thread_id, original_src, time
))?;
return Ok(UseThisThread {
thread_id,
- stream_id: Some(stream.id),
+ stream_id: stream.id,
});
}
}
@@ -102,7 +129,7 @@ impl ThreadMap {
if self.map.len() < max_thread {
return Ok(UseThisThread {
thread_id: self.map.len(),
- stream_id: None,
+ stream_id: 0,
});
}
@@ -117,7 +144,7 @@ impl ThreadMap {
return Ok(UseThisThread {
thread_id: least_amount_of_threads,
- stream_id: None,
+ stream_id: self.map[least_amount_of_threads].streams.len(),
});
}
}
diff --git a/packages/core/src/watch-static-file.ts b/packages/core/src/watch-static-file.ts
index 5c14bdb054..6002d7bd3c 100644
--- a/packages/core/src/watch-static-file.ts
+++ b/packages/core/src/watch-static-file.ts
@@ -27,7 +27,9 @@ export const watchStaticFile = (
// Check if function is called in Remotion Studio
if (!getRemotionEnvironment().isStudio) {
// eslint-disable-next-line no-console
- console.warn('The API is only available while using the Remotion Studio.');
+ console.warn(
+ 'The watchStaticFile() API is only available while using the Remotion Studio.',
+ );
return {cancel: () => undefined};
}
diff --git a/packages/renderer/src/options/offthreadvideo-threads.tsx b/packages/renderer/src/options/offthreadvideo-threads.tsx
index 6c565c73d7..f3832441c2 100644
--- a/packages/renderer/src/options/offthreadvideo-threads.tsx
+++ b/packages/renderer/src/options/offthreadvideo-threads.tsx
@@ -17,8 +17,9 @@ export const offthreadVideoThreadsOption = {
<a href="https://remotion.dev/docs/offthreadvideo">
<code>&lt;OffthreadVideo&gt;</code>
</a>{' '}
- can start to extract frames. frames. The default is 2. Increase carefully,
- as too much threads may cause instability.
+ can start to extract frames. frames. The default is{' '}
+ {DEFAULT_RENDER_FRAMES_OFFTHREAD_VIDEO_THREADS}. Increase carefully, as
+ too much threads may cause instability.
</>
),
ssrName: 'offthreadVideoThreads' as const,
@@ -49,4 +50,4 @@ export const offthreadVideoThreadsOption = {
},
} satisfies AnyRemotionOption<number | null>;
-export const DEFAULT_RENDER_FRAMES_OFFTHREAD_VIDEO_THREADS = 2;
+export const DEFAULT_RENDER_FRAMES_OFFTHREAD_VIDEO_THREADS = 3;
diff --git a/packages/studio/src/api/watch-public-folder.ts b/packages/studio/src/api/watch-public-folder.ts
index d4972725b7..09e08d2f50 100644
--- a/packages/studio/src/api/watch-public-folder.ts
+++ b/packages/studio/src/api/watch-public-folder.ts
@@ -14,7 +14,9 @@ export const watchPublicFolder = (
): {cancel: () => void} => {
if (!getRemotionEnvironment().isStudio) {
// eslint-disable-next-line no-console
- console.warn('The API is only available while using the Remotion Studio.');
+ console.warn(
+ 'The watchPublicFolder() API is only available while using the Remotion Studio.',
+ );
return {cancel: () => undefined};
}