Skip to content

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

M13.1: wasm groundwork: range readers, pending reads, cooperative frames, stepped export

Brandon Thomas243e95ab2492
diff --git a/Cargo.lock b/Cargo.lock
index b7f19ff6f..5caa45174 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1476,6 +1476,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
+ "web-time",
]
[[package]]
@@ -1500,6 +1501,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
+ "web-time",
]
[[package]]
@@ -1748,6 +1750,7 @@ dependencies = [
"rustix 1.1.5",
"serde",
"serde_json",
+ "web-time",
]
[[package]]
@@ -1759,6 +1762,30 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "filmcraft-web"
+version = "0.1.0"
+dependencies = [
+ "eframe",
+ "egui",
+ "filmcraft-codecs",
+ "filmcraft-color",
+ "filmcraft-engine",
+ "filmcraft-format",
+ "filmcraft-frame",
+ "filmcraft-isobmff",
+ "filmcraft-media",
+ "filmcraft-time",
+ "filmcraft-ui-egui",
+ "js-sys",
+ "log",
+ "serde_json",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "web-time",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 6d61bb75c..fe280f55a 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -88,6 +88,48 @@ pub fn openers() -> Vec<filmcraft_media::Opener> {
vec![mp4::opener, mkv::opener, audio::opener]
}
+fn reader_registry() -> &'static RwLock<Vec<filmcraft_media::ReaderOpener>> {
+ static R: std::sync::OnceLock<RwLock<Vec<filmcraft_media::ReaderOpener>>> = std::sync::OnceLock::new();
+ R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener]))
+}
+
+/// Openers that read containers through a [`filmcraft_media::ByteReader`] (index now, samples on
+/// demand) instead of the whole file, in the order they are tried.
+pub fn reader_openers() -> Vec<filmcraft_media::ReaderOpener> {
+ reader_registry().read().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+/// Register a reader opener tried before the built-in ones (platform media sources such as the
+/// web app's WebCodecs-decoded MP4).
+pub fn register_reader_opener(f: filmcraft_media::ReaderOpener) {
+ let mut g = reader_registry().write().unwrap_or_else(|e| e.into_inner());
+ if !g.iter().any(|x| std::ptr::fn_addr_eq(*x, f)) {
+ g.insert(0, f);
+ }
+}
+
+/// A media reader as the demuxers' byte source.
+#[derive(Clone)]
+pub(crate) struct Src(pub filmcraft_media::SharedReader);
+
+impl filmcraft_isobmff::ByteSource for Src {
+ fn len(&self) -> u64 {
+ self.0.len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
+ self.0.read_at(offset, buf)
+ }
+}
+
+impl filmcraft_matroska::ByteSource for Src {
+ fn len(&self) -> u64 {
+ self.0.len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
+ self.0.read_at(offset, buf)
+ }
+}
+
/// Convenience: an `Arc` media source from bytes (tries MP4/MOV then audio files).
pub fn open_bytes(name: &str, bytes: Arc<[u8]>) -> std::result::Result<filmcraft_media::SharedSource, filmcraft_media::MediaError> {
filmcraft_media::open_bytes(name, bytes, &openers())
diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rs
index 339ebb981..492047232 100644
--- a/crates/codecs/src/mkv.rs
+++ b/crates/codecs/src/mkv.rs
@@ -37,7 +37,7 @@ struct AudioState {
pub struct MkvSource {
info: MediaInfo,
- bytes: Arc<[u8]>,
+ bytes: crate::Src,
file: MkvFile,
vtrack: Option<usize>,
atrack: Option<usize>,
@@ -57,7 +57,7 @@ pub struct MkvSource {
/// rounded `CodecDelay`, so they are only accurate to a tick. Starts are therefore accumulated from
/// each packet's TOC duration, resynchronising to the timestamp only across real gaps (more than
/// two ticks off). Pre-skip is the exact `CodecDelay` (or the header's pre-skip when it is absent).
-fn opus_starts(file: &MkvFile, bytes: &[u8], ti: usize, head: &filmcraft_opus::OpusHead, rate: i64) -> Vec<i64> {
+fn opus_starts(file: &MkvFile, bytes: &crate::Src, ti: usize, head: &filmcraft_opus::OpusHead, rate: i64) -> Vec<i64> {
let t = &file.tracks[ti];
let (n, d) = tb(t);
let scale_ns = (n as i128 * 1_000_000_000 / d as i128).max(1);
@@ -199,7 +199,13 @@ fn codec_label(c: &Codec) -> String {
impl MkvSource {
pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {
- let file = filmcraft_matroska::open(&bytes[..]).map_err(|e| CodecError::Container(e.to_string()))?;
+ Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))
+ }
+
+ /// Open from a random-access reader: only the index is read now, samples on demand.
+ pub fn open_reader(name: &str, reader: filmcraft_media::SharedReader) -> crate::Result<Self> {
+ let bytes = crate::Src(reader);
+ let file = filmcraft_matroska::open(&bytes).map_err(|e| CodecError::Container(e.to_string()))?;
let vtrack = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty());
let atrack = file.tracks.iter().position(|t| t.kind == TrackKind::Audio && !t.samples.is_empty());
if vtrack.is_none() && atrack.is_none() {
@@ -270,7 +276,7 @@ impl MkvSource {
audio,
container: if file.is_webm() { "WebM".into() } else { "Matroska".into() },
start_timecode: None,
- file_size: Some(bytes.len() as u64),
+ file_size: Some(bytes.0.len()),
};
let audio_starts = atrack
.map(|i| {
@@ -312,7 +318,7 @@ impl MkvSource {
}
fn read(&self, track: usize, i: usize) -> crate::Result<Vec<u8>> {
- self.file.read_sample(&self.bytes[..], track, i).map_err(|e| CodecError::Container(e.to_string()))
+ self.file.read_sample(&self.bytes, track, i).map_err(|e| CodecError::Container(e.to_string()))
}
fn audio_decoder(&self, c: &Codec, rate: u32) -> crate::Result<PacketDecoder> {
@@ -481,3 +487,11 @@ pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, Media
}
Some(MkvSource::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
}
+
+/// [`filmcraft_media::ReaderOpener`] for Matroska/WebM.
+pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {
+ if !sniff(head) {
+ return None;
+ }
+ Some(MkvSource::open_reader(name, reader.clone()).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
+}
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 7c156f0ef..f940c1e7e 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -28,7 +28,7 @@ struct AudioState {
pub struct Mp4Source {
info: MediaInfo,
- bytes: Arc<[u8]>,
+ bytes: crate::Src,
file: Mp4File,
vtrack: Option<usize>,
atrack: Option<usize>,
@@ -86,7 +86,13 @@ fn color_from(entry: &filmcraft_isobmff::SampleEntry, w: u32, h: u32) -> ColorIn
impl Mp4Source {
pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {
- let file = filmcraft_isobmff::open(&bytes[..]).map_err(|e| CodecError::Container(e.to_string()))?;
+ Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))
+ }
+
+ /// Open from a random-access reader: only the index is read now, samples on demand.
+ pub fn open_reader(name: &str, reader: filmcraft_media::SharedReader) -> crate::Result<Self> {
+ let bytes = crate::Src(reader);
+ let file = filmcraft_isobmff::open(&bytes).map_err(|e| CodecError::Container(e.to_string()))?;
let vtrack = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty());
let atrack = file.tracks.iter().position(|t| t.kind == TrackKind::Audio && !t.samples.is_empty());
if vtrack.is_none() && atrack.is_none() {
@@ -127,8 +133,7 @@ impl Mp4Source {
if matches!(entry.codec, CodecConfig::Dnx { .. }) {
// the sample entry doesn't say which VC-3 compression ID it is: read the first frame header
let s0 = &t.samples[0];
- if let Some(h) = bytes.get(s0.offset as usize..(s0.offset as usize).saturating_add(s0.size as usize)).and_then(|d| filmcraft_dnx::probe(d).ok())
- {
+ if let Some(h) = filmcraft_media::reader::read_range(&*bytes.0, s0.offset, s0.size as usize).ok().and_then(|d| filmcraft_dnx::probe(&d).ok()) {
info.codec = filmcraft_dnx::cid_name(h.cid);
let sub = match h.chroma {
filmcraft_dnx::ChromaFormat::Yuv420 => "YUV 4:2:0",
@@ -180,7 +185,7 @@ impl Mp4Source {
audio,
container: if file.is_quicktime { "QuickTime".into() } else { "MPEG-4".into() },
start_timecode,
- file_size: Some(bytes.len() as u64),
+ file_size: Some(bytes.0.len()),
};
let audio_starts = atrack
.map(|i| {
@@ -224,7 +229,7 @@ impl Mp4Source {
}
fn read(&self, track: usize, i: usize) -> crate::Result<Vec<u8>> {
- self.file.read_sample(&self.bytes[..], track, i).map_err(|e| CodecError::Container(e.to_string()))
+ self.file.read_sample(&self.bytes, track, i).map_err(|e| CodecError::Container(e.to_string()))
}
fn video_at(&self, t: Tick) -> crate::Result<Arc<VideoFrame>> {
@@ -448,3 +453,11 @@ pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, Media
}
Some(Mp4Source::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
}
+
+/// [`filmcraft_media::ReaderOpener`] for MP4/MOV.
+pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {
+ if !sniff(head) {
+ return None;
+ }
+ Some(Mp4Source::open_reader(name, reader.clone()).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index d3f2293d5..d38870dfd 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -29,6 +29,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
+web-time = "1"
[dev-dependencies]
filmcraft-testkit = { workspace = true }
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index d7919b166..ef5978117 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -211,6 +211,26 @@ pub fn import_bytes(s: &mut Session, path: &str, bytes: std::sync::Arc<[u8]>, bi
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
let identity = crate::relink::identity_of_bytes(&bytes);
let src = s.media.open_bytes(&name, bytes)?;
+ import_source(s, path, name, src, identity, bin)
+}
+
+/// Import a media file through the host's random-access reader ([`crate::Services::reader`]):
+/// only the container index is read now (web `Blob`s are never copied whole for containers).
+pub fn import_streamed(s: &mut Session, path: &str, bin: Option<filmcraft_project::BinId>) -> Result<ItemId> {
+ let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
+ let identity = crate::relink::identity_of(&*s.services, path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ let src = s.media.open_file(path, &*s.services)?;
+ import_source(s, path, name, src, identity, bin)
+}
+
+fn import_source(
+ s: &mut Session,
+ path: &str,
+ name: String,
+ src: filmcraft_media::SharedSource,
+ identity: filmcraft_project::MediaIdentity,
+ bin: Option<filmcraft_project::BinId>,
+) -> Result<ItemId> {
let info = src.info().clone();
let label = match info.kind {
filmcraft_media::MediaKind::AudioOnly => Label::Caribbean,
@@ -516,7 +536,14 @@ fn build() -> Vec<CommandSpec> {
let mut sequences = Vec::new();
let mut reports = Vec::new();
for path in paths {
- match s.services.read_file(&path) {
+ // Media files through the host's reader (no whole-file read) when it has one.
+ let streamed = filmcraft_media::is_importable(std::path::Path::new(&path)) && s.services.reader(&path).is_some();
+ let read = if streamed { Ok(Vec::new()) } else { s.services.read_file(&path) };
+ match read {
+ Ok(_) if streamed => match import_streamed(s, &path, bin) {
+ Ok(id) => ids.push(id.0),
+ Err(e) => errors.push(format!("{path}: {e}")),
+ },
Ok(b) if crate::captions::detect(&path, &b).is_some() => {
let fmt = crate::captions::detect(&path, &b).expect("detected");
match crate::captions::import(s, &path, &b, fmt, None) {
@@ -1927,6 +1954,10 @@ fn export_media(s: &mut Session, p: &Value) -> Result<Value> {
prores_profile: str_p(p, "proresProfile").unwrap_or_default().to_string(),
dnx_profile: str_p(p, "dnxProfile").unwrap_or_default().to_string(),
sdr: bool_p(p, "sdr").unwrap_or(false),
+ sink: s.services.export_in_memory().then(|| {
+ let services = s.services.clone();
+ filmcraft_export::OutputSink(std::sync::Arc::new(move |path: &str, data: Vec<u8>| services.write_file(path, &data)))
+ }),
..Default::default()
};
let id = s.jobs.len() as u64 + 1;
@@ -1940,6 +1971,15 @@ fn export_media(s: &mut Session, p: &Value) -> Result<Value> {
// Export always renders full-resolution media, whatever the proxy toggle says.
let provider = s.media.full_res_provider(project.clone(), s.services.clone());
let (prog, res) = (job.progress.clone(), job.result.clone());
+ let wait = bool_p(p, "wait").unwrap_or(false);
+ if cfg!(target_arch = "wasm32") && !wait && filmcraft_export::stepped(format) {
+ // No threads: the host advances the export between UI frames (`Session::pump_jobs`).
+ let mut exporter = filmcraft_export::Exporter::new(project, seq, &settings, &prog).map_err(|e| EngineError::Other(e.to_string()))?;
+ exporter.set_batch(1);
+ s.jobs.push(job);
+ s.stepped.push(crate::SteppedJob { job: id, exporter, provider, progress: prog, result: res });
+ return Ok(json!({"job": id}));
+ }
let run = move || {
let r = filmcraft_export::export(&project, seq, &settings, &provider, &prog).map_err(|e| e.to_string());
if let Err(e) = &r {
@@ -1948,7 +1988,7 @@ fn export_media(s: &mut Session, p: &Value) -> Result<Value> {
*res.lock().unwrap_or_else(|x| x.into_inner()) = Some(r);
};
s.jobs.push(job);
- if bool_p(p, "wait").unwrap_or(false) || cfg!(target_arch = "wasm32") {
+ if wait || cfg!(target_arch = "wasm32") {
run();
} else {
std::thread::Builder::new().name("filmcraft-export".into()).spawn(run).map_err(|e| EngineError::Other(e.to_string()))?;
@@ -2342,7 +2382,7 @@ fn name_project(p: &mut filmcraft_project::Project, name: String) {
}
fn write_project(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
- let t0 = std::time::Instant::now();
+ let t0 = web_time::Instant::now();
// Save As renames the project after its new file (not an edit: no undo step, not dirty).
if adopt
&& let Some(name) = project_name_for(path)
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 91fc6e348..aa29c872a 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -80,6 +80,17 @@ pub trait Services: Send + Sync {
let a = (offset as usize).min(b.len());
Ok(b[a..(a + len).min(b.len())].to_vec())
}
+ /// A random-access reader for a media file, so containers are opened without reading the
+ /// whole file (web: `Blob` range reads). `None`: the host has none; media are read whole.
+ fn reader(&self, _path: &str) -> Option<std::io::Result<filmcraft_media::SharedReader>> {
+ None
+ }
+ /// Exports are encoded in memory and handed to [`Services::write_file`] (hosts without a
+ /// filesystem, e.g. the web: the file is then offered as a download). Otherwise they stream
+ /// to the output path.
+ fn export_in_memory(&self) -> bool {
+ false
+ }
}
/// Native filesystem services.
@@ -230,10 +241,21 @@ pub struct Session {
pub mask_jobs: Vec<masks::PendingTrack>,
/// Effect presets (built-in + the user's, persisted in the data directory).
pub presets: presets::PresetLibrary,
+ /// Exports run a batch at a time by [`Session::pump_jobs`] (hosts without threads: web).
+ pub stepped: Vec<SteppedJob>,
/// Nesting depth of [`Session::execute`] (commands that run other commands).
exec_depth: u32,
}
+/// An export advanced a batch at a time on the host's thread ([`Session::pump_jobs`]).
+pub struct SteppedJob {
+ pub job: u64,
+ pub exporter: filmcraft_export::Exporter,
+ pub provider: media_pool::PoolProvider,
+ pub progress: Arc<filmcraft_export::Progress>,
+ pub result: Arc<std::sync::Mutex<Option<std::result::Result<filmcraft_export::Report, String>>>>,
+}
+
/// A background job with shared progress.
#[derive(Clone)]
pub struct Job {
@@ -299,10 +321,38 @@ impl Session {
media_jobs: Vec::new(),
mask_jobs: Vec::new(),
presets: Default::default(),
+ stepped: Vec::new(),
exec_depth: 0,
}
}
+ /// Advance stepped jobs ([`SteppedJob`]) for up to `budget` (at least one step). Returns
+ /// whether jobs remain. A job whose media is still loading waits for the next call.
+ pub fn pump_jobs(&mut self, budget: std::time::Duration) -> bool {
+ let t0 = web_time::Instant::now();
+ while let Some(j) = self.stepped.first_mut() {
+ match j.exporter.step(&j.provider, &j.progress) {
+ Ok(filmcraft_export::Step::Progress) => {}
+ Ok(filmcraft_export::Step::Pending) => return true,
+ Ok(filmcraft_export::Step::Done(r)) => {
+ *j.result.lock().unwrap_or_else(|e| e.into_inner()) = Some(Ok(r));
+ self.stepped.remove(0);
+ }
+ Err(e) => {
+ let e = e.to_string();
+ *j.progress.error.lock().unwrap_or_else(|x| x.into_inner()) = Some(e.clone());
+ j.progress.finished.store(true, std::sync::atomic::Ordering::Relaxed);
+ *j.result.lock().unwrap_or_else(|x| x.into_inner()) = Some(Err(e));
+ self.stepped.remove(0);
+ }
+ }
+ if t0.elapsed() >= budget {
+ break;
+ }
+ }
+ !self.stepped.is_empty()
+ }
+
/// Start auto-save and the crash-recovery journal (native frontends). Loads preferences from
/// the data directory and finds unsaved changes left by sessions that died
/// ([`Session::recovery_candidates`]).
diff --git a/crates/engine/src/media_pool.rs b/crates/engine/src/media_pool.rs
index 5b4a587fd..118f51f98 100644
--- a/crates/engine/src/media_pool.rs
+++ b/crates/engine/src/media_pool.rs
@@ -119,11 +119,15 @@ impl MediaPool {
filmcraft_media::open_bytes(name, bytes, &openers)
}
- /// Read and open a file through `services`.
+ /// Read and open a file through `services` (through its random-access reader when the host
+ /// has one: containers then read only their index now and samples on demand).
pub fn open_file(&self, path: &str, services: &dyn Services) -> Result<SharedSource, MediaError> {
- let bytes = services
- .read_file(path)
- .map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(e.to_string()) } else { MediaError::Io(e.to_string()) })?;
+ let io = |e: std::io::Error| if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(e.to_string()) } else { MediaError::Io(e.to_string()) };
+ if let Some(r) = services.reader(path) {
+ let openers = self.openers.read().unwrap_or_else(|e| e.into_inner()).clone();
+ return filmcraft_media::reader::open_reader(&file_name(path), r.map_err(io)?, &filmcraft_codecs::reader_openers(), &openers);
+ }
+ let bytes = services.read_file(path).map_err(io)?;
self.open_bytes(&file_name(path), bytes.into())
}
@@ -172,6 +176,10 @@ impl MediaPool {
self.offline.write().unwrap_or_else(|e| e.into_inner()).remove(&item);
s
}
+ Err(_) if filmcraft_media::pending::is_set() => {
+ // the host is still fetching the file's bytes: show the slate for now, retry later
+ return Some(Arc::new(SlateSource::new(m.info.clone(), &file_name(path), OfflineReason::Missing)));
+ }
Err(e) => {
log::warn!("media offline: {path}: {e}");
let reason = if matches!(e, MediaError::Offline(_)) { OfflineReason::Missing } else { OfflineReason::Unreadable };
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 9307c89e5..aa7a713ad 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -25,6 +25,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
rayon = { workspace = true }
+web-time = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif"] }
[dev-dependencies]
diff --git a/crates/export/src/job.rs b/crates/export/src/job.rs
new file mode 100644
index 000000000..78f773b7b
--- /dev/null
+++ b/crates/export/src/job.rs
@@ -0,0 +1,316 @@
+//! Step-wise export of the encoded-video formats (H.264 MP4, ProRes / DNxHR / Motion-JPEG MOV).
+//!
+//! [`Exporter::step`] renders, encodes and muxes one batch of frames (plus the audio up to its
+//! end) per call, so a host without threads (the web app) can run an export a slice at a time
+//! between UI frames; [`crate::export`] simply loops it on a worker thread.
+//!
+//! When a source's bytes are not available yet (asynchronous web reads mark
+//! [`filmcraft_media::pending`]), the batch is rendered again on the next call: nothing is encoded
+//! from frames or audio with missing media.
+
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+
+use filmcraft_frame::AudioBuffer;
+use filmcraft_isobmff::{Brand, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
+use filmcraft_project::{ItemId, Project};
+use filmcraft_render::{RenderOptions, SourceProvider};
+use filmcraft_time::{FrameRate, Tick, TimeRange};
+use rayon::prelude::*;
+
+use crate::{
+ AudioEncoder, ColorSignal, EncodedPacket, EncoderFrame, ExportError, ExportSettings, Format, Out, Progress, Report, Result, VideoEncoder, audio_factories,
+ export_range, video_factories,
+};
+
+/// What one [`Exporter::step`] did.
+#[derive(Debug)]
+pub enum Step {
+ /// A batch was encoded; call again.
+ Progress,
+ /// Media bytes are still loading: nothing was encoded, call again later.
+ Pending,
+ /// The file is complete.
+ Done(Report),
+}
+
+/// The immutable part of an export (rendering a frame needs only this).
+struct Plan {
+ project: Arc<Project>,
+ seq: ItemId,
+ rate: FrameRate,
+ w: u32,
+ h: u32,
+ opts: RenderOptions,
+ hdr_out: bool,
+ out_tf: Option<filmcraft_color::OutputTransform>,
+}
+
+impl Plan {
+ /// Straight sRGB RGBA8 at the (even) output size, or for HDR exports the encoded R'G'B'.
+ fn frame(&self, f: i64, sources: &dyn SourceProvider) -> (Vec<u8>, Vec<f32>) {
+ let (w, h) = (self.w, self.h);
+ let img = filmcraft_render::render_sequence(&self.project, self.seq, self.rate.tick_of(f), self.opts, sources);
+ if let Some(tf) = self.out_tf.as_ref().filter(|_| self.hdr_out) {
+ // HDR: encoded R'G'B' floats over black, padded/cropped to the even output size
+ let mut out = vec![0f32; (w * h * 3) as usize];
+ let black = tf.encode([0.0; 3]);
+ for (y, row) in out.chunks_exact_mut(w as usize * 3).enumerate() {
+ for (x, o) in row.chunks_exact_mut(3).enumerate() {
+ let c = if x < img.w && y < img.h {
+ let i = (y * img.w + x) * 4;
+ tf.encode([img.px[i], img.px[i + 1], img.px[i + 2]])
+ } else {
+ black
+ };
+ o.copy_from_slice(&c);
+ }
+ }
+ return (Vec::new(), out);
+ }
+ let mut rgba = img.over_black_rgba8();
+ if img.w as u32 != w || img.h as u32 != h {
+ // even-size crop/pad
+ let mut out = vec![0u8; (w * h * 4) as usize];
+ for y in 0..(h as usize).min(img.h) {
+ let n = (w as usize).min(img.w) * 4;
+ out[y * w as usize * 4..y * w as usize * 4 + n].copy_from_slice(&rgba[y * img.w * 4..y * img.w * 4 + n]);
+ }
+ rgba = out;
+ }
+ (rgba, Vec::new())
+ }
+}
+
+/// An export of an encoded-video format, advanced one batch at a time.
+pub struct Exporter {
+ plan: Plan,
+ settings: ExportSettings,
+ range: TimeRange,
+ f0: i64,
+ f1: i64,
+ /// Next frame to render.
+ next: i64,
+ batch: i64,
+ sr: u32,
+ brand: Brand,
+ venc: Box<dyn VideoEncoder>,
+ aenc: Option<Box<dyn AudioEncoder>>,
+ /// Created after the first batch (encoders may finalise their codec config then).
+ mux: Option<Mp4Writer<Out>>,
+ vt: usize,
+ at: Option<usize>,
+ audio_cursor: i64,
+ t0: web_time::Instant,
+}
+
+/// Whether [`Exporter`] handles a format.
+pub fn stepped(format: Format) -> bool {
+ matches!(format, Format::H264 | Format::ProRes | Format::DnxHr | Format::Mjpeg)
+}
+
+impl Exporter {
+ /// Set up an export (encoder, output size, colour signalling); sets `progress.total`.
+ pub fn new(project: Arc<Project>, seq: ItemId, settings: &ExportSettings, progress: &Progress) -> Result<Self> {
+ if !stepped(settings.format) {
+ return Err(ExportError::Unsupported(format!("{} is not a stepped export", settings.format.label())));
+ }
+ let q = project.sequence(seq).ok_or(ExportError::NoSequence)?;
+ // HDR sequences export HDR (H.264 / ProRes) unless SDR is asked for
+ let pipe = q.settings.color;
+ let hdr_out = pipe.working.is_hdr() && !settings.sdr && matches!(settings.format, Format::H264 | Format::ProRes | Format::DnxHr);
+ let mut settings = settings.clone();
+ settings.signal = match (hdr_out, pipe.working) {
+ (true, filmcraft_color::WorkingSpace::Rec2100Pq) => ColorSignal::PQ,
+ (true, _) => ColorSignal::HLG,
+ _ => ColorSignal::default(),
+ };
+ let out_tf = hdr_out.then(|| filmcraft_color::OutputTransform::new(&pipe, pipe.working.output_space()));
+ let rate = q.settings.frame_rate;
+ let range = export_range(&project, seq, &settings)?;
+ let f0 = rate.frame_at(range.start);
+ let f1 = rate.frame_at(range.end() - Tick(1)) + 1;
+ let nframes = (f1 - f0).max(0) as u64;
+ let w = (((q.settings.width as f32 * settings.scale).round() as u32).max(2)) & !1;
+ let h = (((q.settings.height as f32 * settings.scale).round() as u32).max(2)) & !1;
+ if !settings.part_of_batch {
+ progress.total.store(nframes, Ordering::Relaxed);
+ progress.set_status(format!("Exporting {} frames ({})", nframes, settings.format.label()));
+ }
+ let opts = RenderOptions { scale: w as f32 / q.settings.width as f32, captions: settings.burn_captions, working_output: hdr_out, ..Default::default() };
+ let sr = q.settings.sample_rate;
+ let venc = video_factories()
+ .read()
+ .unwrap_or_else(|e| e.into_inner())
+ .iter()
+ .find_map(|fac| fac(settings.format, w, h, rate, &settings))
+ .ok_or_else(|| ExportError::Unsupported(format!("{} encoder not available yet", settings.format.label())))??;
+ let brand = if settings.format == Format::H264 { Brand::Mp4 } else { Brand::Mov };
+ // audio: AAC for MP4 when available, PCM otherwise (MOV)
+ let aenc: Option<Box<dyn AudioEncoder>> = if settings.include_audio && brand == Brand::Mp4 {
+ audio_factories().read().unwrap_or_else(|e| e.into_inner()).iter().find_map(|f| f(settings.format, sr, 2, &settings)).transpose()?
+ } else {
+ None
+ };
+ Ok(Self {
+ plan: Plan { project, seq, rate, w, h, opts, hdr_out, out_tf },
+ range,
+ f0,
+ f1,
+ next: f0,
+ batch: rayon::current_num_threads().clamp(2, 16) as i64,
+ sr,
+ brand,
+ venc,
+ aenc,
+ mux: None,
+ vt: 0,
+ at: None,
+ audio_cursor: range.start.to_units_floor(sr as i64),
+ t0: web_time::Instant::now(),
+ settings,
+ })
+ }
+
+ /// Frames in the export.
+ pub fn frames(&self) -> u64 {
+ (self.f1 - self.f0).max(0) as u64
+ }
+
+ /// Frames per [`Self::step`] (default: one per core); 1 keeps web UI frames short.
+ pub fn set_batch(&mut self, n: i64) {
+ self.batch = n.max(1);
+ }
+
+ /// Mix the sequence audio from the cursor up to `until` (None: no audio track or nothing to mix).
+ fn mix_until(&self, until: Tick, sources: &dyn SourceProvider) -> Option<(AudioBuffer, i64)> {
+ self.settings.include_audio.then_some(())?;
+ let end = until.to_units_floor(self.sr as i64);
+ if end <= self.audio_cursor {
+ return None;
+ }
+ let q = self.plan.project.sequence(self.plan.seq)?;
+ let n = (end - self.audio_cursor) as usize;
+ Some((filmcraft_render::audio::mix_sequence(&self.plan.project, q, self.audio_cursor, n, sources), end))
+ }
+
+ fn write_audio(&mut self, mixed: Option<(AudioBuffer, i64)>) -> Result<()> {
+ let (Some(at), Some((buf, end))) = (self.at, mixed) else { return Ok(()) };
+ let n = (end - self.audio_cursor) as usize;
+ self.audio_cursor = end;
+ let mux = self.mux.as_mut().expect("mux created");
+ match self.aenc.as_mut() {
+ Some(a) => {
+ for au in a.encode(&buf.channels)? {
+ mux.write_sample(at, WriteSample { data: &au, duration: a.frame_size(), composition_offset: 0, is_sync: true })
+ .map_err(|e| ExportError::Io(e.to_string()))?;
+ }
+ }
+ None => {
+ let mut pcm = Vec::with_capacity(n * 4);
+ for s in buf.interleaved() {
+ pcm.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
+ }
+ mux.write_sample(at, WriteSample { data: &pcm, duration: n as u32, composition_offset: 0, is_sync: true })
+ .map_err(|e| ExportError::Io(e.to_string()))?;
+ }
+ }
+ Ok(())
+ }
+
+ fn write_video(&mut self, packets: Vec<EncodedPacket>) -> Result<()> {
+ let mux = self.mux.as_mut().expect("mux created");
+ for p in packets {
+ mux.write_sample(self.vt, WriteSample { data: &p.data, duration: p.duration, composition_offset: p.composition_offset, is_sync: p.key })
+ .map_err(|e| ExportError::Io(e.to_string()))?;
+ }
+ Ok(())
+ }
+
+ /// Create the muxer and its tracks (after the first batch was encoded).
+ fn open_mux(&mut self) -> Result<()> {
+ let file = Out::create(&self.settings)?;
+ let mut mux = Mp4Writer::new(file, WriterOptions::new(self.brand)).map_err(|e| ExportError::Io(e.to_string()))?;
+ let mut vcfg = TrackConfig::new(self.venc.sample_entry(), self.venc.timescale());
+ vcfg.media_start = self.venc.media_start();
+ self.vt = mux.add_track(vcfg).map_err(|e| ExportError::Io(e.to_string()))?;
+ self.at = if !self.settings.include_audio {
+ None
+ } else if let Some(a) = &self.aenc {
+ let mut c = TrackConfig::new(a.sample_entry(), self.sr);
+ c.media_start = Some(a.priming() as i64);
+ Some(mux.add_track(c).map_err(|e| ExportError::Io(e.to_string()))?)
+ } else if self.brand == Brand::Mov {
+ let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: self.sr as f64 };
+ Some(mux.add_track(TrackConfig::new(SampleEntry::pcm(pcm), self.sr)).map_err(|e| ExportError::Io(e.to_string()))?)
+ } else {
+ None
+ };
+ self.mux = Some(mux);
+ Ok(())
+ }
+
+ /// Render, encode and mux the next batch (or finish the file).
+ pub fn step(&mut self, sources: &dyn SourceProvider, progress: &Progress) -> Result<Step> {
+ if progress.cancel.load(Ordering::Relaxed) {
+ return Err(ExportError::Cancelled);
+ }
+ let _ = filmcraft_media::pending::take();
+ if self.next < self.f1 {
+ let (f, end) = (self.next, (self.next + self.batch).min(self.f1));
+ let plan = &self.plan;
+ let frames: Vec<(Vec<u8>, Vec<f32>)> = (f..end).into_par_iter().map(|fi| plan.frame(fi, sources)).collect();
+ let has_audio = self.mux.is_none() || self.at.is_some();
+ let mixed = if has_audio { self.mix_until(self.plan.rate.tick_of(end), sources) } else { None };
+ if filmcraft_media::pending::take() {
+ return Ok(Step::Pending);
+ }
+ let mut packets = Vec::new();
+ for (k, (rgba, hdr)) in frames.iter().enumerate() {
+ let fr = EncoderFrame {
+ width: self.plan.w,
+ height: self.plan.h,
+ rgba,
+ hdr: self.plan.hdr_out.then_some(hdr.as_slice()),
+ index: (f - self.f0) as u64 + k as u64,
+ };
+ packets.extend(self.venc.encode(&fr)?);
+ }
+ if self.mux.is_none() {
+ self.open_mux()?;
+ }
+ self.write_video(packets)?;
+ self.write_audio(mixed)?;
+ progress.done.fetch_add((end - f) as u64, Ordering::Relaxed);
+ self.next = end;
+ return Ok(Step::Progress);
+ }
+ let mixed = self.mix_until(self.range.end(), sources);
+ if filmcraft_media::pending::take() {
+ return Ok(Step::Pending);
+ }
+ if self.mux.is_none() {
+ self.open_mux()?;
+ }
+ let tail = self.venc.flush()?;
+ self.write_video(tail)?;
+ self.write_audio(mixed)?;
+ if let (Some(at), Some(a)) = (self.at, self.aenc.as_mut()) {
+ let fs = a.frame_size();
+ let mux = self.mux.as_mut().expect("mux created");
+ for au in a.flush()? {
+ mux.write_sample(at, WriteSample { data: &au, duration: fs, composition_offset: 0, is_sync: true })
+ .map_err(|e| ExportError::Io(e.to_string()))?;
+ }
+ }
+ let w = self.mux.take().expect("mux created").finish().map_err(|e| ExportError::Io(e.to_string()))?;
+ let bytes = w.finish(&self.settings)?;
+ let secs = self.t0.elapsed().as_secs_f64();
+ let nframes = self.frames();
+ if !self.settings.part_of_batch {
+ progress.finished.store(true, Ordering::Relaxed);
+ progress.set_status(format!("Done in {secs:.1}s"));
+ }
+ Ok(Step::Done(Report { path: self.settings.path.clone(), frames: nframes, seconds: secs, bytes, render_fps: nframes as f64 / secs.max(1e-6) }))
+ }
+}
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 12f329ee1..d5bebcf34 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -8,10 +8,13 @@
//! [`register_encoder`] (H.264, ProRes …). Built in: Motion-JPEG (MOV), PNG sequence, GIF, WAV.
use std::io::Write;
+
+mod job;
+pub use job::{Exporter, Step, stepped};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};
-use filmcraft_isobmff::{Brand, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
+use filmcraft_isobmff::SampleEntry;
use filmcraft_project::{ItemId, Project};
use filmcraft_render::{RenderOptions, SourceProvider};
use filmcraft_time::{FrameRate, Tick, TimeRange};
@@ -119,6 +122,82 @@ pub struct ExportSettings {
/// Colour signalling chosen by [`export`] for the encoders (not set by callers).
#[serde(skip)]
pub signal: ColorSignal,
+ /// Encode into memory and hand each finished file (path, bytes) to this sink instead of
+ /// writing `path` (hosts without a filesystem: the web app offers the file as a download).
+ #[serde(skip)]
+ pub sink: Option<OutputSink>,
+}
+
+/// Receives in-memory export output: `(path, bytes)` per finished file.
+#[derive(Clone)]
+pub struct OutputSink(pub Arc<dyn Fn(&str, Vec<u8>) -> std::io::Result<()> + Send + Sync>);
+
+impl std::fmt::Debug for OutputSink {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("OutputSink")
+ }
+}
+
+/// An export's output file: on disk, or in memory for an [`OutputSink`].
+enum Out {
+ File(std::io::BufWriter<std::fs::File>),
+ Mem(std::io::Cursor<Vec<u8>>),
+}
+
+impl Out {
+ fn create(settings: &ExportSettings) -> Result<Out> {
+ if settings.sink.is_some() {
+ return Ok(Out::Mem(std::io::Cursor::new(Vec::new())));
+ }
+ let f = std::fs::File::create(&settings.path).map_err(|e| ExportError::Io(e.to_string()))?;
+ Ok(Out::File(std::io::BufWriter::new(f)))
+ }
+
+ /// Flush (and hand in-memory output to the sink); returns the file size.
+ fn finish(self, settings: &ExportSettings) -> Result<u64> {
+ match self {
+ Out::File(mut w) => {
+ w.flush().map_err(|e| ExportError::Io(e.to_string()))?;
+ Ok(std::fs::metadata(&settings.path).map(|m| m.len()).unwrap_or(0))
+ }
+ Out::Mem(c) => write_output(settings, &settings.path, c.into_inner()),
+ }
+ }
+}
+
+/// Write one finished output file (to the sink when there is one); returns its size.
+fn write_output(settings: &ExportSettings, path: &str, data: Vec<u8>) -> Result<u64> {
+ let n = data.len() as u64;
+ match &settings.sink {
+ Some(sink) => (sink.0)(path, data),
+ None => std::fs::write(path, &data),
+ }
+ .map_err(|e| ExportError::Io(e.to_string()))?;
+ Ok(n)
+}
+
+impl Write for Out {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ match self {
+ Out::File(w) => w.write(buf),
+ Out::Mem(w) => w.write(buf),
+ }
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ match self {
+ Out::File(w) => w.flush(),
+ Out::Mem(w) => w.flush(),
+ }
+ }
+}
+
+impl std::io::Seek for Out {
+ fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
+ match self {
+ Out::File(w) => w.seek(pos),
+ Out::Mem(w) => w.seek(pos),
+ }
+ }
}
/// Colour description of the encoded stream (ITU-T H.273 code points).
@@ -182,6 +261,7 @@ impl Default for ExportSettings {
dnx_profile: String::new(),
sdr: false,
signal: ColorSignal::default(),
+ sink: None,
}
}
}
@@ -679,19 +759,19 @@ pub fn export_range(project: &Project, seq: ItemId, settings: &ExportSettings) -
/// Run an export (blocking; call from a worker thread).
pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, sources: &dyn SourceProvider, progress: &Progress) -> Result<Report> {
- let t0 = std::time::Instant::now();
+ if stepped(settings.format) {
+ let mut ex = Exporter::new(project.clone(), seq, settings, progress)?;
+ loop {
+ match ex.step(sources, progress)? {
+ Step::Progress => {}
+ Step::Done(r) => return Ok(r),
+ // only asynchronous (web) sources defer; a blocking export cannot wait for them
+ Step::Pending => return Err(ExportError::Io("media data is still loading; run the export as a stepped job".into())),
+ }
+ }
+ }
+ let t0 = web_time::Instant::now();
let q = project.sequence(seq).ok_or(ExportError::NoSequence)?;
- // HDR sequences export HDR (H.264 / ProRes) unless SDR is asked for
- let pipe = q.settings.color;
- let hdr_out = pipe.working.is_hdr() && !settings.sdr && matches!(settings.format, Format::H264 | Format::ProRes | Format::DnxHr);
- let mut settings = settings.clone();
- settings.signal = match (hdr_out, pipe.working) {
- (true, filmcraft_color::WorkingSpace::Rec2100Pq) => ColorSignal::PQ,
- (true, _) => ColorSignal::HLG,
- _ => ColorSignal::default(),
- };
- let settings = &settings;
- let out_tf = hdr_out.then(|| filmcraft_color::OutputTransform::new(&pipe, pipe.working.output_space()));
let rate = q.settings.frame_rate;
let range = export_range(project, seq, settings)?;
let f0 = rate.frame_at(range.start);
@@ -703,26 +783,7 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
progress.total.store(if settings.format == Format::Wav { 1 } else { nframes }, Ordering::Relaxed);
progress.set_status(format!("Exporting {} frames ({})", nframes, settings.format.label()));
}
- let opts = RenderOptions { scale: w as f32 / q.settings.width as f32, captions: settings.burn_captions, working_output: hdr_out, ..Default::default() };
- // HDR: encoded R'G'B' floats over black, padded/cropped to the even output size
- let render_hdr = |f: i64| -> Vec<f32> {
- let img = filmcraft_render::render_sequence(project, seq, rate.tick_of(f), opts, sources);
- let tf = out_tf.as_ref().expect("hdr transform");
- let mut out = vec![0f32; (w * h * 3) as usize];
- let black = tf.encode([0.0; 3]);
- for (y, row) in out.chunks_exact_mut(w as usize * 3).enumerate() {
- for (x, o) in row.chunks_exact_mut(3).enumerate() {
- let c = if x < img.w && y < img.h {
- let i = (y * img.w + x) * 4;
- tf.encode([img.px[i], img.px[i + 1], img.px[i + 2]])
- } else {
- black
- };
- o.copy_from_slice(&c);
- }
- }
- out
- };
+ let opts = RenderOptions { scale: w as f32 / q.settings.width as f32, captions: settings.burn_captions, ..Default::default() };
let render = |f: i64| -> Vec<u8> {
let img = filmcraft_render::render_sequence(project, seq, rate.tick_of(f), opts, sources);
let mut rgba = img.over_black_rgba8();
@@ -744,9 +805,9 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
let n = range.duration.to_units_floor(sr as i64) as usize;
let buf = filmcraft_render::audio::mix_sequence(project, q, range.start.to_units_floor(sr as i64), n, sources);
let data = filmcraft_media::wav::write_wav16(&buf.interleaved(), 2, sr);
- std::fs::write(&settings.path, &data).map_err(|e| ExportError::Io(e.to_string()))?;
+ let n = write_output(settings, &settings.path, data)?;
progress.done.store(1, Ordering::Relaxed);
- data.len() as u64
+ n
}
Format::PngSequence => {
let base = settings.path.trim_end_matches(".png").to_string();
@@ -762,6 +823,12 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
.map(|fi| {
let rgba = render(fi);
let path = format!("{base}_{:05}.png", fi - f0);
+ if settings.sink.is_some() {
+ let mut png = Vec::new();
+ image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut png), &rgba, w, h, image::ExtendedColorType::Rgba8)
+ .map_err(|e| ExportError::Encode(e.to_string()))?;
+ return write_output(settings, &path, png);
+ }
image::save_buffer(&path, &rgba, w, h, image::ExtendedColorType::Rgba8).map_err(|e| ExportError::Io(e.to_string()))?;
Ok(std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0))
})
@@ -775,8 +842,8 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
total
}
Format::Gif => {
- let file = std::fs::File::create(&settings.path).map_err(|e| ExportError::Io(e.to_string()))?;
- let mut enc = image::codecs::gif::GifEncoder::new_with_speed(std::io::BufWriter::new(file), 10);
+ let mut out = Out::create(settings)?;
+ let mut enc = image::codecs::gif::GifEncoder::new_with_speed(&mut out, 10);
enc.set_repeat(image::codecs::gif::Repeat::Infinite).map_err(|e| ExportError::Encode(e.to_string()))?;
let delay = image::Delay::from_numer_denom_ms((1000 * rate.den) as u32, rate.num as u32);
let mut f = f0;
@@ -794,119 +861,9 @@ pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, so
f = end;
}
drop(enc);
- std::fs::metadata(&settings.path).map(|m| m.len()).unwrap_or(0)
- }
- Format::H264 | Format::ProRes | Format::DnxHr | Format::Mjpeg => {
- let mut venc = video_factories()
- .read()
- .unwrap_or_else(|e| e.into_inner())
- .iter()
- .find_map(|fac| fac(settings.format, w, h, rate, settings))
- .ok_or_else(|| ExportError::Unsupported(format!("{} encoder not available yet", settings.format.label())))??;
- let brand = if settings.format == Format::H264 { Brand::Mp4 } else { Brand::Mov };
- let file = std::fs::File::create(&settings.path).map_err(|e| ExportError::Io(e.to_string()))?;
- // Encode the first batch before creating tracks (encoders may finalise codec config then).
- let mut pending: Vec<EncodedPacket> = Vec::new();
- let first_end = (f0 + batch).min(f1);
- let frame = |fi: i64| -> (Vec<u8>, Vec<f32>) { if hdr_out { (Vec::new(), render_hdr(fi)) } else { (render(fi), Vec::new()) } };
- let first: Vec<(Vec<u8>, Vec<f32>)> = (f0..first_end).into_par_iter().map(frame).collect();
- for (k, (rgba, hdr)) in first.iter().enumerate() {
- pending.extend(venc.encode(&EncoderFrame { width: w, height: h, rgba, hdr: hdr_out.then_some(hdr.as_slice()), index: k as u64 })?);
- }
- progress.done.fetch_add((first_end - f0) as u64, Ordering::Relaxed);
- let mut mux = Mp4Writer::new(std::io::BufWriter::new(file), WriterOptions::new(brand)).map_err(|e| ExportError::Io(e.to_string()))?;
- let mut vcfg = TrackConfig::new(venc.sample_entry(), venc.timescale());
- vcfg.media_start = venc.media_start();
- let vt = mux.add_track(vcfg).map_err(|e| ExportError::Io(e.to_string()))?;
- // audio: AAC for MP4 when available, PCM otherwise (MOV)
- let mut aenc: Option<Box<dyn AudioEncoder>> = if settings.include_audio && brand == Brand::Mp4 {
- audio_factories().read().unwrap_or_else(|e| e.into_inner()).iter().find_map(|f| f(settings.format, sr, 2, settings)).transpose()?
- } else {
- None
- };
- let at = if !settings.include_audio {
- None
- } else if let Some(a) = &aenc {
- let mut c = TrackConfig::new(a.sample_entry(), sr);
- c.media_start = Some(a.priming() as i64);
- Some(mux.add_track(c).map_err(|e| ExportError::Io(e.to_string()))?)
- } else if brand == Brand::Mov {
- let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: sr as f64 };
- Some(mux.add_track(TrackConfig::new(SampleEntry::pcm(pcm), sr)).map_err(|e| ExportError::Io(e.to_string()))?)
- } else {
- None
- };
- let mut audio_cursor = range.start.to_units_floor(sr as i64);
- let write_audio_until = |mux: &mut Mp4Writer<std::io::BufWriter<std::fs::File>>,
- until: Tick,
- cursor: &mut i64,
- aenc: &mut Option<Box<dyn AudioEncoder>>|
- -> Result<()> {
- let Some(at) = at else { return Ok(()) };
- let end = until.to_units_floor(sr as i64);
- if end <= *cursor {
- return Ok(());
- }
- let n = (end - *cursor) as usize;
- let buf = filmcraft_render::audio::mix_sequence(project, q, *cursor, n, sources);
- *cursor = end;
- match aenc {
- Some(a) => {
- for au in a.encode(&buf.channels)? {
- mux.write_sample(at, WriteSample { data: &au, duration: a.frame_size(), composition_offset: 0, is_sync: true })
- .map_err(|e| ExportError::Io(e.to_string()))?;
- }
- }
- None => {
- let mut pcm = Vec::with_capacity(n * 4);
- for s in buf.interleaved() {
- pcm.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
- }
- mux.write_sample(at, WriteSample { data: &pcm, duration: n as u32, composition_offset: 0, is_sync: true })
- .map_err(|e| ExportError::Io(e.to_string()))?;
- }
- }
- Ok(())
- };
- for p in pending.drain(..) {
- mux.write_sample(vt, WriteSample { data: &p.data, duration: p.duration, composition_offset: p.composition_offset, is_sync: p.key })
- .map_err(|e| ExportError::Io(e.to_string()))?;
- }
- write_audio_until(&mut mux, rate.tick_of(first_end), &mut audio_cursor, &mut aenc)?;
- let mut f = first_end;
- while f < f1 {
- if progress.cancel.load(Ordering::Relaxed) {
- return Err(ExportError::Cancelled);
- }
- let end = (f + batch).min(f1);
- let frames: Vec<(Vec<u8>, Vec<f32>)> = (f..end).into_par_iter().map(frame).collect();
- for (k, (rgba, hdr)) in frames.iter().enumerate() {
- for p in
- venc.encode(&EncoderFrame { width: w, height: h, rgba, hdr: hdr_out.then_some(hdr.as_slice()), index: (f - f0) as u64 + k as u64 })?
- {
- mux.write_sample(vt, WriteSample { data: &p.data, duration: p.duration, composition_offset: p.composition_offset, is_sync: p.key })
- .map_err(|e| ExportError::Io(e.to_string()))?;
- }
- }
- write_audio_until(&mut mux, rate.tick_of(end), &mut audio_cursor, &mut aenc)?;
- progress.done.fetch_add((end - f) as u64, Ordering::Relaxed);
- f = end;
- }
- for p in venc.flush()? {
- mux.write_sample(vt, WriteSample { data: &p.data, duration: p.duration, composition_offset: p.composition_offset, is_sync: p.key })
- .map_err(|e| ExportError::Io(e.to_string()))?;
- }
- write_audio_until(&mut mux, range.end(), &mut audio_cursor, &mut aenc)?;
- if let (Some(a), Some(at)) = (aenc.as_mut(), at) {
- for au in a.flush()? {
- mux.write_sample(at, WriteSample { data: &au, duration: a.frame_size(), composition_offset: 0, is_sync: true })
- .map_err(|e| ExportError::Io(e.to_string()))?;
- }
- }
- let mut w = mux.finish().map_err(|e| ExportError::Io(e.to_string()))?;
- w.flush().map_err(|e| ExportError::Io(e.to_string()))?;
- std::fs::metadata(&settings.path).map(|m| m.len()).unwrap_or(0)
+ out.finish(settings)?
}
+ Format::H264 | Format::ProRes | Format::DnxHr | Format::Mjpeg => unreachable!("stepped export"),
};
let secs = t0.elapsed().as_secs_f64();
if !settings.part_of_batch {
diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs
index 312710877..0f1044ca6 100644
--- a/crates/format/src/atomic.rs
+++ b/crates/format/src/atomic.rs
@@ -30,10 +30,12 @@ fn parent_dir(path: &Path) -> PathBuf {
pub fn atomic_write(path: &Path, data: &[u8]) -> io::Result<()> {
let tmp = temp_path(path);
let r = (|| {
- let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
- f.write_all(data)?;
- f.sync_all()?;
- drop(f);
+ {
+ // closed before the rename
+ let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
+ f.write_all(data)?;
+ f.sync_all()?;
+ }
fs::rename(&tmp, path)
})();
if let Err(e) = r {
diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs
index cd79fa28d..691929fad 100644
--- a/crates/media/src/lib.rs
+++ b/crates/media/src/lib.rs
@@ -11,6 +11,8 @@ pub mod cache;
pub mod cancel;
pub mod digits;
pub mod generators;
+pub mod pending;
+pub mod reader;
pub mod still;
pub mod wav;
@@ -24,6 +26,7 @@ use serde::{Deserialize, Serialize};
pub use cache::FrameCache;
pub use generators::{DemoScene, Generator};
+pub use reader::{ByteReader, ReaderOpener, SharedReader};
#[derive(Debug, thiserror::Error)]
pub enum MediaError {
diff --git a/crates/media/src/pending.rs b/crates/media/src/pending.rs
new file mode 100644
index 000000000..eaf19d83e
--- /dev/null
+++ b/crates/media/src/pending.rs
@@ -0,0 +1,53 @@
+//! "Data not here yet" signalling for asynchronous byte sources (web Blob reads).
+//!
+//! On the web, media bytes are read from a `File`/`Blob` asynchronously. A [`ByteReader`] that
+//! does not have the requested range yet starts fetching it, calls [`mark`] and fails the read
+//! with [`std::io::ErrorKind::WouldBlock`]. Whoever asked for the frame (the frame server, an
+//! import) checks [`take`] afterwards: when set, the result is incomplete and the request should
+//! be retried once the data has arrived, instead of being cached as a decode error or offline
+//! media. The flag travels through a thread-local (like [`crate::cancel`]), so the
+//! [`MediaSource`](crate::MediaSource) API is unchanged. Native file reads never set it.
+//!
+//! [`ByteReader`]: crate::reader::ByteReader
+
+use std::cell::Cell;
+
+thread_local! {
+ static PENDING: Cell<bool> = const { Cell::new(false) };
+}
+
+/// Record that a read on this thread could not be served yet (its data is being fetched).
+pub fn mark() {
+ PENDING.with(|p| p.set(true));
+}
+
+/// Whether a read on this thread was deferred since the last [`take`].
+pub fn is_set() -> bool {
+ PENDING.with(Cell::get)
+}
+
+/// Return and clear the flag.
+pub fn take() -> bool {
+ PENDING.with(|p| p.replace(false))
+}
+
+/// The error a deferring reader returns.
+pub fn would_block() -> std::io::Error {
+ mark();
+ std::io::Error::new(std::io::ErrorKind::WouldBlock, "media data is still loading")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn take_clears_the_flag() {
+ assert!(!take());
+ let e = would_block();
+ assert_eq!(e.kind(), std::io::ErrorKind::WouldBlock);
+ assert!(is_set());
+ assert!(take());
+ assert!(!is_set());
+ }
+}
diff --git a/crates/media/src/reader.rs b/crates/media/src/reader.rs
new file mode 100644
index 000000000..1fbbac76f
--- /dev/null
+++ b/crates/media/src/reader.rs
@@ -0,0 +1,96 @@
+//! Random-access byte readers: open media without loading the whole file.
+//!
+//! A [`ByteReader`] serves reads at any offset (a native file, a web `Blob` read in chunks, an
+//! in-memory buffer). Container openers that only need the index and then single samples (MP4/MOV,
+//! Matroska) open from a reader ([`ReaderOpener`]); formats decoded in one go (stills, WAV,
+//! standalone compressed audio) fall back to reading the whole file through it.
+
+use std::io;
+use std::sync::Arc;
+
+use crate::{MediaError, Opener, Result, SharedSource};
+
+/// Random-access, read-only bytes.
+pub trait ByteReader: Send + Sync {
+ /// Total length in bytes.
+ fn len(&self) -> u64;
+ /// Fill `buf` entirely from `offset`; `UnexpectedEof` past the end. Asynchronous readers fail
+ /// with `WouldBlock` (and set [`crate::pending`]) while the range is being fetched.
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>;
+ fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+}
+
+pub type SharedReader = Arc<dyn ByteReader>;
+
+fn eof() -> io::Error {
+ io::Error::new(io::ErrorKind::UnexpectedEof, "read past end of byte source")
+}
+
+/// An in-memory reader.
+pub struct MemReader(pub Arc<[u8]>);
+
+impl ByteReader for MemReader {
+ fn len(&self) -> u64 {
+ self.0.len() as u64
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ let a = usize::try_from(offset).map_err(|_| eof())?;
+ let src = self.0.get(a..a.checked_add(buf.len()).ok_or_else(eof)?).ok_or_else(eof)?;
+ buf.copy_from_slice(src);
+ Ok(())
+ }
+}
+
+/// Read `len` bytes at `offset` (fewer at the end of the reader).
+pub fn read_range(r: &dyn ByteReader, offset: u64, len: usize) -> io::Result<Vec<u8>> {
+ let n = (r.len().saturating_sub(offset)).min(len as u64) as usize;
+ let mut v = vec![0u8; n];
+ r.read_at(offset, &mut v)?;
+ Ok(v)
+}
+
+/// Opens a container from a reader: `head` is the first bytes of the file (for sniffing).
+/// Returns `None` when the format is not this opener's.
+pub type ReaderOpener = fn(name: &str, head: &[u8], reader: &SharedReader) -> Option<Result<SharedSource>>;
+
+/// Bytes sniffed by [`open_reader`].
+pub const HEAD_LEN: usize = 64 * 1024;
+
+/// Open media from a reader: reader openers first; otherwise read the whole file and use the
+/// byte openers (`extra`, then stills / WAV).
+pub fn open_reader(name: &str, reader: SharedReader, reader_openers: &[ReaderOpener], extra: &[Opener]) -> Result<SharedSource> {
+ let head = read_range(&*reader, 0, HEAD_LEN).map_err(|e| MediaError::Io(format!("{name}: {e}")))?;
+ for o in reader_openers {
+ if let Some(r) = o(name, &head, &reader) {
+ return r;
+ }
+ }
+ let all = read_range(&*reader, 0, usize::try_from(reader.len()).unwrap_or(usize::MAX)).map_err(|e| MediaError::Io(format!("{name}: {e}")))?;
+ crate::open_bytes(name, all.into(), extra)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mem_reader_reads_ranges_and_reports_eof() {
+ let r = MemReader(Arc::from(&b"0123456789"[..]));
+ let mut b = [0u8; 3];
+ r.read_at(4, &mut b).unwrap();
+ assert_eq!(&b, b"456");
+ assert_eq!(r.read_at(8, &mut b).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
+ assert_eq!(read_range(&r, 8, 100).unwrap(), b"89");
+ }
+
+ #[test]
+ fn falls_back_to_byte_openers() {
+ // a WAV is opened through the whole-file path
+ let wav = crate::wav::write_wav16(&[0.0, 0.5, -0.5, 0.25], 2, 48_000);
+ let r: SharedReader = Arc::new(MemReader(wav.into()));
+ let s = open_reader("a.wav", r, &[], &[]).unwrap();
+ assert!(s.info().has_audio());
+ }
+}
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index bba3e4ed7..948f922e6 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -28,6 +28,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
rayon = { workspace = true }
+web-time = "1"
# Thread/process CPU clocks for frame-job profiling (safe wrappers; see frames.rs).
[target.'cfg(unix)'.dependencies]
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 17bc54903..e7f7ade10 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -329,6 +329,13 @@ pub fn save_screenshot(ctx: &egui::Context, image: &egui::ColorImage, path: Opti
rgba.extend_from_slice(&[c.r(), c.g(), c.b(), 255]);
}
}
+ if cfg!(target_arch = "wasm32") {
+ // No filesystem on the web: the PNG comes back in the reply.
+ return match encode_png(&rgba, cw as u32, ch as u32) {
+ Ok(png) => json!({"ok": true, "result": {"pngBase64": base64(&png), "width": cw, "height": ch}}),
+ Err(e) => json!({"ok": false, "error": e}),
+ };
+ }
let path = path.map(str::to_string).unwrap_or_else(|| std::env::temp_dir().join("filmcraft-screenshot.png").to_string_lossy().to_string());
match encode_png(&rgba, cw as u32, ch as u32) {
Ok(png) => match std::fs::write(&path, png) {
@@ -339,6 +346,23 @@ pub fn save_screenshot(ctx: &egui::Context, image: &egui::ColorImage, path: Opti
}
}
+/// Standard base64 (RFC 4648, with padding).
+pub fn base64(data: &[u8]) -> String {
+ const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
+ for c in data.chunks(3) {
+ let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
+ for k in 0..4 {
+ if k <= c.len() {
+ out.push(A[(n >> (18 - 6 * k) & 63) as usize] as char);
+ } else {
+ out.push('=');
+ }
+ }
+ }
+ out
+}
+
/// Minimal PNG encoder (stored deflate blocks, no compression dependency).
pub fn encode_png(rgba: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
fn chunk(out: &mut Vec<u8>, ty: &[u8], data: &[u8]) {
@@ -389,3 +413,13 @@ pub fn encode_png(rgba: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
chunk(&mut out, b"IEND", &[]);
Ok(out)
}
+
+#[cfg(test)]
+mod base64_tests {
+ #[test]
+ fn rfc4648_vectors() {
+ for (i, o) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] {
+ assert_eq!(super::base64(i.as_bytes()), o);
+ }
+ }
+}
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs
index fcdc471af..254709d0f 100644
--- a/crates/ui-egui/src/frames.rs
+++ b/crates/ui-egui/src/frames.rs
@@ -11,7 +11,9 @@ use std::cell::Cell;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
-use std::time::{Duration, Instant};
+use std::time::Duration;
+
+use web_time::Instant;
use filmcraft_engine::previews::PreviewStore;
use filmcraft_engine::{MediaPool, Services};
@@ -409,8 +411,6 @@ impl FrameServer {
q.push_back(Job { key, queued: Instant::now(), cancel: Default::default(), prefetch, time, scale, project: project.clone(), prio });
drop(q);
self.shared.cv.notify_one();
- #[cfg(target_arch = "wasm32")]
- self.run_one_sync();
}
/// Playback scheduling for the monitor showing `key` (the frame due now): request it first,
@@ -489,19 +489,43 @@ impl FrameServer {
None
}
- #[cfg(target_arch = "wasm32")]
- fn run_one_sync(&self) {
- let job = { self.shared.queue.lock().unwrap_or_else(|e| e.into_inner()).pop_front() };
- if let Some(job) = job {
- if let Target::SequencePlan(seq) = job.key.target {
- let (plan, _) = plan_job(&job, seq, &self.pool, &self.services, &self.previews);
- let prepared = filmcraft_gpu::prepare(&plan);
- self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });
+ /// Without worker threads (wasm32): run queued jobs on the calling (UI) thread, highest
+ /// priority first, until `budget` has passed (at least one job). Jobs whose media is still
+ /// loading go back to the queue. Returns the number of jobs finished. A no-op with workers.
+ pub fn pump(&self, budget: Duration) -> usize {
+ if cfg!(not(target_arch = "wasm32")) {
+ return 0;
+ }
+ let t0 = Instant::now();
+ let mut done = 0;
+ let mut retry = Vec::new();
+ loop {
+ let job = {
+ let mut q = self.shared.queue.lock().unwrap_or_else(|e| e.into_inner());
+ if q.is_empty() {
+ break;
+ }
+ let best = q.iter().enumerate().min_by_key(|(i, j)| (j.prio, *i)).map(|(i, _)| i).unwrap_or(0);
+ q.remove(best).expect("index valid")
+ };
+ if run_job(&self.shared, &job, &self.pool, &self.services, &self.previews) {
+ done += 1;
} else {
- let (img, _) = render_job(&job, &self.pool, &self.services, &self.previews);
- self.shared.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));
+ retry.push(job);
+ }
+ if t0.elapsed() >= budget {
+ break;
}
}
+ if !retry.is_empty() {
+ let mut q = self.shared.queue.lock().unwrap_or_else(|e| e.into_inner());
+ for j in retry.into_iter().rev() {
+ if !q.iter().any(|x| x.key == j.key) {
+ q.push_front(j);
+ }
+ }
+ }
+ done
}
}
@@ -595,61 +619,74 @@ fn worker(
q = sh.cv.wait(q).unwrap_or_else(|e| e.into_inner());
}
};
- sh.in_flight.lock().unwrap_or_else(|e| e.into_inner()).push((job.key, job.cancel.clone(), job.prefetch));
- let profiling = sh.profiling.load(Ordering::Relaxed);
- let (started, cpu0) = (Instant::now(), if profiling { thread_cpu_time().unwrap_or_default() } else { Duration::ZERO });
- SOURCE_TIME.with(|s| s.set((Duration::ZERO, Duration::ZERO)));
- PROFILING.with(|p| p.set(profiling));
- // A cancelled job may have missed layers (its source gave up): its result is not cached.
- let preview = filmcraft_media::cancel::with_cancel(&job.cancel, || {
- if let Target::SequencePlan(seq) = job.key.target {
- let (plan, pv) = plan_job(&job, seq, &pool, &services, &previews);
- if !job.cancel.load(Ordering::Relaxed) {
- // Convert texels for upload here, not on the UI thread when the frame is shown.
- let prepared = filmcraft_gpu::prepare(&plan);
- sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });
- }
- pv
- } else {
- let (img, pv) = render_job(&job, &pool, &services, &previews);
- if !job.cancel.load(Ordering::Relaxed) {
- sh.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));
- }
- pv
+ run_job(&sh, &job, &pool, &services, &previews);
+ if let Some(f) = repaint.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
+ f();
+ }
+ }
+}
+
+/// Run one job and cache its result. Returns false when the job's media was still loading (an
+/// asynchronous web read): nothing was cached and the job should be retried.
+fn run_job(sh: &Shared, job: &Job, pool: &Arc<MediaPool>, services: &Arc<dyn Services>, previews: &PreviewStore) -> bool {
+ sh.in_flight.lock().unwrap_or_else(|e| e.into_inner()).push((job.key, job.cancel.clone(), job.prefetch));
+ let profiling = sh.profiling.load(Ordering::Relaxed);
+ let (started, cpu0) = (Instant::now(), if profiling { thread_cpu_time().unwrap_or_default() } else { Duration::ZERO });
+ SOURCE_TIME.with(|s| s.set((Duration::ZERO, Duration::ZERO)));
+ PROFILING.with(|p| p.set(profiling));
+ // A cancelled job may have missed layers (its source gave up): its result is not cached.
+ // A job whose media bytes were still loading (web) rendered with missing layers: like a
+ // cancelled one, its result is not cached (the caller retries it).
+ let _ = filmcraft_media::pending::take();
+ let mut loading = false;
+ let preview = filmcraft_media::cancel::with_cancel(&job.cancel, || {
+ if let Target::SequencePlan(seq) = job.key.target {
+ let (plan, pv) = plan_job(job, seq, pool, services, previews);
+ loading = filmcraft_media::pending::take();
+ if !job.cancel.load(Ordering::Relaxed) && !loading {
+ // Convert texels for upload here, not on the UI thread when the frame is shown.
+ let prepared = filmcraft_gpu::prepare(&plan);
+ sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });
}
- });
- let cancelled = job.cancel.load(Ordering::Relaxed);
- sh.in_flight.lock().unwrap_or_else(|e| e.into_inner()).retain(|(k, c, _)| !(*k == job.key && Arc::ptr_eq(c, &job.cancel)));
- if job.prefetch {
- // Work beyond fetching source frames (decoding is sequential per source and is
- // not saved by skipping frames, so it is left out of the estimate). A cancelled job
- // only tells that the work takes at least this long.
- let cost = started.elapsed().saturating_sub(SOURCE_TIME.with(|s| s.get()).0).as_secs_f64();
- let mut c = sh.render_cost.lock().unwrap_or_else(|e| e.into_inner());
- if !cancelled || cost > *c {
- *c = if *c == 0.0 { cost } else { *c * 0.8 + cost * 0.2 };
+ pv
+ } else {
+ let (img, pv) = render_job(job, pool, services, previews);
+ loading = filmcraft_media::pending::take();
+ if !job.cancel.load(Ordering::Relaxed) && !loading {
+ sh.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));
}
+ pv
}
- if profiling {
- let (source_wall, source_cpu) = SOURCE_TIME.with(|s| s.get());
- let rec = JobRecord {
- key: job.key,
- prio: job.prio,
- queued: job.queued,
- started,
- finished: Instant::now(),
- cpu: thread_cpu_time().unwrap_or_default().saturating_sub(cpu0),
- source_wall,
- source_cpu,
- preview,
- cancelled,
- };
- sh.records.lock().unwrap_or_else(|e| e.into_inner()).push(rec);
- }
- if let Some(f) = repaint.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
- f();
+ });
+ let cancelled = job.cancel.load(Ordering::Relaxed);
+ sh.in_flight.lock().unwrap_or_else(|e| e.into_inner()).retain(|(k, c, _)| !(*k == job.key && Arc::ptr_eq(c, &job.cancel)));
+ if job.prefetch {
+ // Work beyond fetching source frames (decoding is sequential per source and is
+ // not saved by skipping frames, so it is left out of the estimate). A cancelled job
+ // only tells that the work takes at least this long.
+ let cost = started.elapsed().saturating_sub(SOURCE_TIME.with(|s| s.get()).0).as_secs_f64();
+ let mut c = sh.render_cost.lock().unwrap_or_else(|e| e.into_inner());
+ if !cancelled || cost > *c {
+ *c = if *c == 0.0 { cost } else { *c * 0.8 + cost * 0.2 };
}
}
+ if profiling {
+ let (source_wall, source_cpu) = SOURCE_TIME.with(|s| s.get());
+ let rec = JobRecord {
+ key: job.key,
+ prio: job.prio,
+ queued: job.queued,
+ started,
+ finished: Instant::now(),
+ cpu: thread_cpu_time().unwrap_or_default().saturating_sub(cpu0),
+ source_wall,
+ source_cpu,
+ preview,
+ cancelled,
+ };
+ sh.records.lock().unwrap_or_else(|e| e.into_inner()).push(rec);
+ }
+ !loading
}
/// The preview frame for a sequence job, when its segment has been rendered.
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8b2c24388..a65522861 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -173,7 +173,7 @@ impl FilmcraftApp {
{
return Some((t, g.size));
}
- let t0 = std::time::Instant::now();
+ let t0 = web_time::Instant::now();
let (view, size) = g.compositor.composite_prepared(&plan.plan, Some(&plan.prepared));
let view = view.clone();
g.last_ms = t0.elapsed().as_secs_f32() * 1000.0;
@@ -989,6 +989,9 @@ impl eframe::App for FilmcraftApp {
ui.ctx().request_repaint();
return;
}
+ // No frame worker threads on the web: render queued frames here, within a time budget
+ // that leaves room for the UI pass (a no-op where workers run).
+ self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 }));
self.frame(ui);
let ctx = ui.ctx().clone();
self.last_ui_time = ctx.input(|i| i.time);
diff --git a/crates/ui-egui/src/panels/misc.rs b/crates/ui-egui/src/panels/misc.rs
index 53659aa0e..dc3e347fc 100644
--- a/crates/ui-egui/src/panels/misc.rs
+++ b/crates/ui-egui/src/panels/misc.rs
@@ -2,7 +2,6 @@
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
use filmcraft_time::{TimeDisplay, format_time};
-use serde_json::json;
use crate::FilmcraftApp;
use crate::frames::{FrameKey, Target};
@@ -183,7 +182,7 @@ pub fn media_browser(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
});
ui.data_mut(|d| d.insert_temp(dir_id, dir));
if !import.is_empty() {
- let r = app.session.execute("file.import", json!({"paths": import}));
+ let r = app.session.execute("file.import", serde_json::json!({"paths": import}));
if let Err(e) = r {
app.ui.status = e.to_string();
}
@@ -192,7 +191,7 @@ pub fn media_browser(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
#[cfg(target_arch = "wasm32")]
{
let _ = dir_id;
- ui.label(egui::RichText::new("Use File ▸ Import to pick files.").color(t.text_dim));
+ ui.label(egui::RichText::new("Use File ▸ Import, or drop files on the window.").color(t.text_dim));
}
let _ = t;
}