Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#1216: a cap on the CPU threads an export uses (ExportSettings::max_threads)

Guilherme Barbosa Ferrarezi32b857744094
diff --git a/crates/engine/src/export_tests.rs b/crates/engine/src/export_tests.rs
index d0cec7035..63cc218b7 100644
--- a/crates/engine/src/export_tests.rs
+++ b/crates/engine/src/export_tests.rs
@@ -815,3 +815,16 @@ fn caption_sidecars_keep_only_the_exported_interval() {
assert!(doc.cues.is_empty(), "half-open export excludes cues touching either boundary: {doc:?}");
}
}
+
+/// #1216: `maxThreads` reaches the export settings from the command parameters (CLI, MCP, control
+/// channel), as a flat parameter or inside `settings`.
+#[test]
+fn max_threads_reaches_the_export_settings() {
+ let session = Session::default();
+ let settings_of = |params: Value| crate::export_tools::settings_from_params(&session, &params, "file.exportMedia").map(|(_, s)| s);
+ assert_eq!(settings_of(json!({"format": "mjpeg", "path": "out.mov", "maxThreads": 2})).unwrap().max_threads, 2);
+ assert_eq!(settings_of(json!({"format": "mjpeg", "path": "out.mov", "settings": {"maxThreads": 3}})).unwrap().max_threads, 3);
+ assert_eq!(settings_of(json!({"format": "mjpeg", "path": "out.mov"})).unwrap().max_threads, 0, "all cores unless asked");
+ assert!(settings_of(json!({"format": "mjpeg", "path": "out.mov", "maxThreads": -1})).is_err(), "a negative count is refused");
+ assert!(settings_of(json!({"format": "mjpeg", "path": "out.mov", "settings": {"maxThread": 2}})).is_err(), "a misspelt setting is refused, not ignored");
+}
diff --git a/crates/engine/src/export_tools.rs b/crates/engine/src/export_tools.rs
index 2fd68925b..5511141c5 100644
--- a/crates/engine/src/export_tools.rs
+++ b/crates/engine/src/export_tools.rs
@@ -235,6 +235,9 @@ pub fn settings_from_params(s: &Session, p: &Value, cmd: &str) -> Result<(Option
settings.bitrate_kbps = v;
settings.adaptive_bitrate = None;
}
+ if let Some(v) = crate::commands::checked_u32_p(p, "maxThreads", cmd)? {
+ settings.max_threads = v;
+ }
if let Some(v) = crate::commands::checked_u32_p(p, "maxBitrateKbps", cmd)? {
settings.max_bitrate_kbps = Some(v);
}
diff --git a/crates/export/src/determinism_tests.rs b/crates/export/src/determinism_tests.rs
index 2866cb9d4..44ff76daa 100644
--- a/crates/export/src/determinism_tests.rs
+++ b/crates/export/src/determinism_tests.rs
@@ -308,3 +308,77 @@ fn a_panic_while_rendering_ahead_is_an_error() {
assert!(matches!(r, Err(ExportError::Encode(_))), "{:?}", r.map(|_| ()));
});
}
+
+// ------------------------------------------------------------------ max_threads
+
+/// A provider that notes how many threads the pool it is asked on has, and which threads ask.
+struct Noting<'a> {
+ inner: &'a SourceMap,
+ most: AtomicUsize,
+ threads: std::sync::Mutex<std::collections::HashSet<std::thread::ThreadId>>,
+}
+
+impl<'a> Noting<'a> {
+ fn new(inner: &'a SourceMap) -> Self {
+ Self { inner, most: AtomicUsize::new(0), threads: Default::default() }
+ }
+}
+
+impl SourceProvider for Noting<'_> {
+ fn source(&self, item: ItemId) -> Option<SharedSource> {
+ self.most.fetch_max(rayon::current_num_threads(), Ordering::SeqCst);
+ self.threads.lock().unwrap().insert(std::thread::current().id());
+ self.inner.source(item)
+ }
+}
+
+/// Export the test project from a pool of `outer` threads with `max_threads` set, and report the
+/// biggest pool a frame was asked on and how many different threads asked.
+fn threads_used(outer: usize, max_threads: u32, name: &str) -> (usize, usize) {
+ let (p, seq, m) = project();
+ let noting = Noting::new(&m);
+ let settings = ExportSettings { format: Format::Mjpeg, path: tmp(name), include_audio: false, max_threads, ..Default::default() };
+ pool(outer).install(|| export(&p, seq, &settings, &noting, &Progress::default())).unwrap();
+ (noting.most.load(Ordering::SeqCst), noting.threads.lock().unwrap().len())
+}
+
+#[test]
+fn max_threads_caps_the_threads_an_export_runs_on() {
+ // uncapped, it renders on the pool it is called in
+ let (most, threads) = threads_used(8, 0, "cap-0.mov");
+ assert_eq!(most, 8);
+ assert!(threads > 3, "{threads} threads asked for frames: the uncapped export should have used several");
+ // capped, on a pool of that size
+ for cap in [1u32, 3] {
+ let (most, threads) = threads_used(8, cap, &format!("cap-{cap}.mov"));
+ assert_eq!(most, cap as usize, "cap {cap}");
+ assert!(threads <= cap as usize, "cap {cap}: {threads} threads asked for frames");
+ }
+}
+
+#[test]
+fn max_threads_never_adds_threads() {
+ // a cap at or above the pool the export is called in changes nothing
+ assert_eq!(threads_used(4, 4, "cap-same.mov").0, 4);
+ assert_eq!(threads_used(4, 100, "cap-large.mov").0, 4);
+}
+
+#[test]
+fn max_threads_does_not_change_the_file() {
+ for (format, ext) in [(Format::ProRes, "mov"), (Format::H264, "mp4"), (Format::Mjpeg, "mov")] {
+ let settings = |name: &str, max_threads: u32| ExportSettings { format, path: tmp(&format!("{name}.{ext}")), max_threads, ..Default::default() };
+ let reference = export_with_cores(5, &settings(&format!("{}-uncapped", format.id()), 0));
+ for cap in [1u32, 3] {
+ let capped = export_with_cores(5, &settings(&format!("{}-cap{cap}", format.id()), cap));
+ assert!(reference == capped, "{}: a cap of {cap} thread(s) gives a different file", format.label());
+ }
+ }
+}
+
+#[test]
+fn max_threads_is_a_setting_of_the_json_interface() {
+ let s: ExportSettings = serde_json::from_str(r#"{"format":"mjpeg","maxThreads":2}"#).unwrap();
+ assert_eq!(s.max_threads, 2);
+ assert_eq!(ExportSettings::default().max_threads, 0, "all cores unless asked");
+ assert_eq!(serde_json::to_value(&s).unwrap()["maxThreads"], serde_json::json!(2));
+}
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index ebea2550e..54001cfa2 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -325,6 +325,13 @@ pub struct ExportSettings {
/// `progress.total`, `finished` and the final status; this call only adds to `done`.
#[serde(default)]
pub part_of_batch: bool,
+ /// Most CPU threads the export may use (0 = all of them, as before). Rendering, the software
+ /// encoders and the rest of the export's parallel work run on a pool of this size; a number
+ /// above what the machine has (or above the pool the export already runs in) changes nothing.
+ /// The output does not depend on it. Hardware encoders and the decoders' own threads are not
+ /// counted.
+ #[serde(default)]
+ pub max_threads: u32,
/// ProRes flavour: `proxy`, `lt`, `standard`, `hq`, `4444` or `4444xq` (empty = HQ).
#[serde(default)]
pub prores_profile: String,
@@ -558,6 +565,7 @@ impl Default for ExportSettings {
bitrate_kbps: 20_000,
burn_captions: false,
part_of_batch: false,
+ max_threads: 0,
prores_profile: String::new(),
dnx_profile: String::new(),
apv_profile: String::new(),
@@ -1837,8 +1845,28 @@ pub fn encode_still_with(format: Format, rgba: Vec<u8>, w: u32, h: u32, alpha: b
Ok(out.into_inner())
}
-/// Run an export (blocking; call from a worker thread).
+/// A pool of `max_threads` threads to run an export on, or `None` when it should run where it is:
+/// no cap (0), a cap that is not below the pool the caller is in already, or no threads to spare
+/// (the browser).
+fn capped_pool(max_threads: u32) -> Option<rayon::ThreadPool> {
+ let cap = max_threads as usize;
+ if cap == 0 || cap >= rayon::current_num_threads() || cfg!(target_arch = "wasm32") {
+ return None;
+ }
+ rayon::ThreadPoolBuilder::new().num_threads(cap).thread_name(|i| format!("filmcraft-export-{i}")).build().ok()
+}
+
+/// Run an export (blocking; call from a worker thread). With `settings.max_threads` set it runs on
+/// a pool of that many threads, so its rendering and software encoding use at most that many cores.
pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, sources: &dyn SourceProvider, progress: &Progress) -> Result<Report> {
+ match capped_pool(settings.max_threads) {
+ Some(pool) => pool.install(|| export_here(project, seq, settings, sources, progress)),
+ None => export_here(project, seq, settings, sources, progress),
+ }
+}
+
+/// [`export`] on the threads it is called from.
+fn export_here(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, sources: &dyn SourceProvider, progress: &Progress) -> Result<Report> {
settings.validate()?;
if stepped(settings.format) {
let mut ex = Exporter::new(project.clone(), seq, settings, progress)?;