diff --git a/apps/effectcraft-cli/src/main.rs b/apps/effectcraft-cli/src/main.rs index 4b78193ba..2678eaeff 100644 --- a/apps/effectcraft-cli/src/main.rs +++ b/apps/effectcraft-cli/src/main.rs @@ -1029,7 +1029,10 @@ fn render(args: &Args, json_out: bool) -> Result<(), Failure> { match &it.status { RenderStatus::Done => { note!("done: {name} → {} in {:.2}s", it.last_output.as_deref().unwrap_or("?"), it.render_time.unwrap_or(0.0)); - results.push(json!({"comp": name, "output": it.last_output, "seconds": it.render_time})); + if let Some(t) = &it.last_timing { + note!("timing: {}", t.summary()); + } + results.push(json!({"comp": name, "output": it.last_output, "seconds": it.render_time, "timing": it.last_timing, "timingSummary": it.last_timing.as_ref().map(|t| t.summary())})); } RenderStatus::Failed(e) => failed.push(format!("{name}: {e}")), other => failed.push(format!("{name}: {}", other.label())), diff --git a/crates/engine/src/background/offload.rs b/crates/engine/src/background/offload.rs index b28527f02..cf27a0a9c 100644 --- a/crates/engine/src/background/offload.rs +++ b/crates/engine/src/background/offload.rs @@ -913,6 +913,7 @@ impl Session { status: RenderStatus::Failed(error), seconds: 0.0, output: None, + timing: None, }); } } diff --git a/crates/engine/src/background/offload/tests.rs b/crates/engine/src/background/offload/tests.rs index c08623189..f30d1d384 100644 --- a/crates/engine/src/background/offload/tests.rs +++ b/crates/engine/src/background/offload/tests.rs @@ -136,7 +136,9 @@ fn protocol_round_trips() { for r in [ WorkerReply::Render { state: JobState { current: Some(3), done: 4, total: 10, items_total: 1, ..Default::default() } }, WorkerReply::Item { update: ItemUpdate::Started { id: 3, unix: 1_700_000_000 } }, - WorkerReply::Item { update: ItemUpdate::Finished { id: 3, status: RenderStatus::Failed("x".into()), seconds: 1.5, output: Some("/a.gif".into()) } }, + WorkerReply::Item { + update: ItemUpdate::Finished { id: 3, status: RenderStatus::Failed("x".into()), seconds: 1.5, output: Some("/a.gif".into()), timing: None }, + }, WorkerReply::Progress { done: 1, total: 2 }, WorkerReply::WarpPlan { key: [1, u64::MAX], @@ -285,6 +287,8 @@ fn cancelling_offloaded_jobs() { assert!(s.revision > rev); // Render: the queued items become User Stopped. s.execute("renderQueue.add", serde_json::json!({"output": "/a.gif"})).unwrap(); + // An earlier run's timing does not stay beside the stopped status (#3724) + Arc::make_mut(&mut s.project).render_queue.last_mut().unwrap().last_timing = Some(Default::default()); let ids = s.start_render(false).unwrap(); assert!(s.is_rendering()); assert!(s.stop_render()); @@ -293,6 +297,7 @@ fn cancelling_offloaded_jobs() { assert_eq!(off.0.lock().unwrap().len(), 2); let it = s.project.render_queue.iter().find(|i| i.id == ids[0]).unwrap(); assert_eq!(it.status, RenderStatus::UserStopped); + assert_eq!(it.last_timing, None); } #[test] diff --git a/crates/engine/src/cmd/render_queue.rs b/crates/engine/src/cmd/render_queue.rs index c45865c9e..5b2331d0b 100644 --- a/crates/engine/src/cmd/render_queue.rs +++ b/crates/engine/src/cmd/render_queue.rs @@ -697,6 +697,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { it.started = None; it.render_time = None; it.last_output = None; + it.last_timing = None; let id = it.id; proj.render_queue.insert(i + 1, it); Ok(id) diff --git a/crates/engine/src/render_queue.rs b/crates/engine/src/render_queue.rs index cacdd4410..7cd9c500a 100644 --- a/crates/engine/src/render_queue.rs +++ b/crates/engine/src/render_queue.rs @@ -10,7 +10,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use effectcraft_project::render_queue::{OutputFormat, OutputModule, PostRenderAction, RenderQueueItem, RenderStatus, TemplateVars, expand_template}; +use effectcraft_project::render_queue::{ + OutputFormat, OutputModule, PostRenderAction, RenderQueueItem, RenderStatus, RenderTiming, TemplateVars, expand_template, +}; use effectcraft_project::{ItemId, ItemKind, LayerSource, Project}; use effectcraft_render::{ExprHost, FootageSource}; use serde::{Deserialize, Serialize}; @@ -99,6 +101,9 @@ pub struct ExportResult { /// Files that went to storage overflow folders. #[serde(skip_serializing_if = "Vec::is_empty")] pub overflow: Vec, + /// Where the time went and what ran the job (the render log's summary line). + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, } /// Encodes render queue items (implemented by the export layer). @@ -152,8 +157,19 @@ pub struct JobState { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "event", rename_all = "camelCase")] pub enum ItemUpdate { - Started { id: u64, unix: u64 }, - Finished { id: u64, status: RenderStatus, seconds: f64, output: Option }, + Started { + id: u64, + unix: u64, + }, + Finished { + id: u64, + status: RenderStatus, + seconds: f64, + output: Option, + /// Where the time went (done items only). + #[serde(default)] + timing: Option, + }, } #[derive(Default)] @@ -205,8 +221,14 @@ impl JobShared { item.insert("statusLabel".into(), json!(RenderStatus::Rendering.label())); item.insert("started".into(), json!(unix)); item.insert("render_time".into(), Value::Null); + item.remove("last_timing"); } - ItemUpdate::Finished { status, seconds, output, .. } => { + ItemUpdate::Finished { status, seconds, output, timing, .. } => { + // Each finish reports its own run: an item stopped before it started has no timing + match timing { + Some(timing) => item.insert("last_timing".into(), json!(timing)), + None => item.remove("last_timing"), + }; item.insert("status".into(), json!(status)); item.insert("statusLabel".into(), json!(status.label())); item.insert("render_time".into(), json!(seconds)); @@ -375,7 +397,7 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared for (k, modules) in w.items.iter().enumerate() { let Some((item, _)) = modules.first() else { continue }; if shared.cancel.load(Ordering::Relaxed) { - lock(&shared.updates).push(ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds: 0.0, output: None }); + lock(&shared.updates).push(ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds: 0.0, output: None, timing: None }); continue; } let t1 = web_time::Instant::now(); @@ -426,6 +448,8 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared !shared.cancel.load(Ordering::Relaxed) }) .await; + // (the item's timing and output are those of the first output module's export; the + // others, and the later segments of a split output, are not part of it) match rr { Ok(res) if mi == 0 => r = Ok(res), Ok(_) => {} @@ -437,11 +461,11 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared } let seconds = t1.elapsed().as_secs_f64(); let up = match r { - Ok(res) => ItemUpdate::Finished { id: item.id, status: RenderStatus::Done, seconds, output: Some(res.path) }, - Err(e) if e == CANCELLED => ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds, output: None }, + Ok(res) => ItemUpdate::Finished { id: item.id, status: RenderStatus::Done, seconds, output: Some(res.path), timing: res.timing }, + Err(e) if e == CANCELLED => ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds, output: None, timing: None }, Err(e) => { log::warn!("render queue: item {} failed: {e}", item.id); - ItemUpdate::Finished { id: item.id, status: RenderStatus::Failed(e), seconds, output: None } + ItemUpdate::Finished { id: item.id, status: RenderStatus::Failed(e), seconds, output: None, timing: None } } }; lock(&shared.updates).push(up); @@ -691,7 +715,13 @@ impl Session { let mut updates = lock(&sh.updates); for id in pending.into_iter().skip(completed) { if !updates.iter().any(|u| matches!(u, ItemUpdate::Finished { id: done, .. } if *done == id)) { - updates.push(ItemUpdate::Finished { id, status: RenderStatus::Failed(error.to_string()), seconds: 0.0, output: None }); + updates.push(ItemUpdate::Finished { + id, + status: RenderStatus::Failed(error.to_string()), + seconds: 0.0, + output: None, + timing: None, + }); } } lock(&sh.state).finished = true; @@ -723,7 +753,13 @@ impl Session { let done = finished.contains(id) || self.project.render_queue.iter().any(|i| i.id == *id && matches!(i.status, RenderStatus::Done | RenderStatus::Failed(_))); if !done { - lock(&j.shared.updates).push(ItemUpdate::Finished { id: *id, status: RenderStatus::UserStopped, seconds: 0.0, output: None }); + lock(&j.shared.updates).push(ItemUpdate::Finished { + id: *id, + status: RenderStatus::UserStopped, + seconds: 0.0, + output: None, + timing: None, + }); } } lock(&j.shared.state).finished = true; @@ -755,15 +791,17 @@ impl Session { i.status = RenderStatus::Rendering; i.started = Some(*unix); i.render_time = None; + i.last_timing = None; } } - ItemUpdate::Finished { id, status, seconds, output } => { + ItemUpdate::Finished { id, status, seconds, output, timing } => { if let Some(i) = p.render_queue.iter_mut().find(|i| i.id == *id) { i.status = status.clone(); i.render_time = Some(*seconds); if output.is_some() { i.last_output = output.clone(); } + i.last_timing = timing.clone(); if let (RenderStatus::Done, Some(o)) = (status, output) && !i.post_render.is_none() { diff --git a/crates/export/src/encode.rs b/crates/export/src/encode.rs index 8caad8dea..1203c7ac6 100644 --- a/crates/export/src/encode.rs +++ b/crates/export/src/encode.rs @@ -9,7 +9,9 @@ use effectcraft_project::render_queue::{AudioFormat, Channels, OutputFormat, Pro use effectcraft_project::{Comp, ProjectSettings}; use effectcraft_time::{FrameRate, Tick}; use rayon::prelude::*; +use web_time::Instant; +use crate::pipeline::Stage; use crate::{Cx, ExportError, Report, Result, State, batch_size, wants_audio}; fn enc(e: impl std::fmt::Display) -> ExportError { @@ -295,6 +297,21 @@ enum Audio { Pcm, } +/// One encoded sample of a movie's audio track: its bytes and its duration in audio samples. +type AudioSample = (Vec, u32); + +/// One audio step of a movie: mixing and encoding count as audio, muxing the encoded samples as +/// writing, so a slow destination shows up as writing. Each part keeps its time on an error. +fn audio_step(job: &Cx, mux: &mut Mp4Writer, track: usize, encode: impl FnOnce() -> Result>) -> Result<()> { + let samples = job.timed(Stage::Audio, encode)?; + job.timed(Stage::Write, || -> Result<()> { + for (data, duration) in &samples { + mux.write_sample(track, WriteSample { data, duration: *duration, composition_offset: 0, is_sync: true }).map_err(mux_err)?; + } + Ok(()) + }) +} + fn deinterleave(buf: &[f32], channels: usize) -> Vec> { (0..channels).map(|c| buf.chunks_exact(channels).map(|p| p[c]).collect()).collect() } @@ -381,7 +398,7 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St .beside(beside, batch_frames((first_end..next_end).collect()), || -> Result> { let mut pending = Vec::new(); for (k, px) in first.iter().enumerate() { - pending.extend(encode(&mut venc, px, k as u64)?); + pending.extend(job.timed(Stage::Encode, || encode(&mut venc, px, k as u64))?); } Ok(pending) }) @@ -391,10 +408,13 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St st.advance(first_end)?; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; + let mut file = job.timed(Stage::Write, || job.create(&path))?; let opts = WriterOptions::new(brand); let movie_ts = opts.movie_timescale.max(1) as i128; - let mut mux: Writer = Mp4Writer::new(&mut file, opts).map_err(mux_err)?; + let t = Instant::now(); + let mux = Mp4Writer::new(&mut file, opts).map_err(mux_err); + job.add_time(Stage::Write, t); + let mut mux: Writer = mux?; let mut vcfg = TrackConfig::new(venc.sample_entry(), rate.num as u32); if let Some(start) = venc.media_start() { // An explicit edit: the convenience `media_start` edit would subtract the B-frame delay @@ -438,35 +458,31 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St } Ok(()) }; - let mut write_audio_until = |mux: &mut Writer, until: Tick, cursor: &mut i64| -> Result<()> { + let mut audio_until = |mux: &mut Writer, until: Tick, cursor: &mut i64| -> Result<()> { let Some((a, at)) = audio.as_mut() else { return Ok(()) }; let end = until.to_units_floor(sr as i64); if end <= *cursor { return Ok(()); } - let n = (end - *cursor) as usize; - let start = Tick::from_units(*cursor, i64::from(sr)); - let start = if start.to_units_floor(i64::from(sr)) < *cursor { Tick(start.0.saturating_add(1)) } else { start }; - let buf = mix(job, start, n, sr); - *cursor = end; - match a { - Audio::Aac(e) => { - let planar = deinterleave(&buf, chans as usize); - let refs: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect(); - for au in e.encode(&refs) { - mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; + audio_step(job, mux, *at, || { + let n = (end - *cursor) as usize; + let start = Tick::from_units(*cursor, i64::from(sr)); + let start = if start.to_units_floor(i64::from(sr)) < *cursor { Tick(start.0.saturating_add(1)) } else { start }; + let buf = mix(job, start, n, sr); + *cursor = end; + Ok(match a { + Audio::Aac(e) => { + let planar = deinterleave(&buf, chans as usize); + let refs: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect(); + e.encode(&refs).into_iter().map(|au| (au, 1024)).collect() } - } - Audio::Pcm => { - let pcm = pcm_bytes(&buf, afmt, false); - mux.write_sample(*at, WriteSample { data: &pcm, duration: n as u32, composition_offset: 0, is_sync: true }).map_err(mux_err)?; - } - } - Ok(()) + Audio::Pcm => vec![(pcm_bytes(&buf, afmt, false), n as u32)], + }) + }) }; let frame_end_time = |k: u64| -> Tick { if k >= total { span_end } else { job.settings.frame_time(comp, k) } }; - write_video(&mut mux, pending)?; - write_audio_until(&mut mux, frame_end_time(first_end), &mut cursor)?; + job.timed(Stage::Write, || write_video(&mut mux, pending))?; + audio_until(&mut mux, frame_end_time(first_end), &mut cursor)?; let mut i = first_end; while i < total { let end = (i + batch).min(total); @@ -475,10 +491,10 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St let (done, next) = job .beside(beside, batch_frames((end..next_end).collect()), || -> Result<()> { for (k, px) in frames.iter().enumerate() { - let ps = encode(&mut venc, px, i + k as u64)?; - write_video(&mut mux, ps)?; + let ps = job.timed(Stage::Encode, || encode(&mut venc, px, i + k as u64))?; + job.timed(Stage::Write, || write_video(&mut mux, ps))?; } - write_audio_until(&mut mux, frame_end_time(end), &mut cursor) + audio_until(&mut mux, frame_end_time(end), &mut cursor) }) .await?; done?; @@ -486,17 +502,19 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St st.advance(end - i)?; i = end; } - write_video(&mut mux, venc.flush()?)?; - write_audio_until(&mut mux, span_end, &mut cursor)?; + let tail = job.timed(Stage::Encode, || venc.flush())?; + job.timed(Stage::Write, || write_video(&mut mux, tail))?; + audio_until(&mut mux, span_end, &mut cursor)?; + // Each write is timed before its error is passed on: a failed export's line keeps the time. if let Some((Audio::Aac(e), at)) = audio.as_mut() { - for au in e.flush() { - mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; - } + audio_step(job, &mut mux, *at, || Ok(e.flush().into_iter().map(|au| (au, 1024)).collect()))?; } - let out = mux.finish().map_err(mux_err)?; - out.flush().map_err(mux_err)?; - let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] }) + let t = Instant::now(); + let finished = mux.finish().map_err(mux_err).and_then(|out| out.flush().map_err(mux_err)); + job.add_time(Stage::Write, t); + finished?; + let bytes = job.timed(Stage::Write, || file.finish())?; + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } #[cfg(test)] @@ -584,4 +602,76 @@ mod tests { assert_eq!(cb[0], 512); assert!(cr[2] > 900, "red has high Cr: {}", cr[2]); } + + /// A destination that takes the movie's header, then is slow on every write once `slow` is + /// set, and refuses the write after the delay when `fails` is set too. + struct SlowDestination { + data: std::io::Cursor>, + slow: std::rc::Rc>, + fails: bool, + delay: std::time::Duration, + } + + impl Write for SlowDestination { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.slow.get() { + std::thread::sleep(self.delay); + if self.fails { + return Err(std::io::Error::other("destination refused the write")); + } + } + self.data.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl std::io::Seek for SlowDestination { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.data.seek(pos) + } + } + + /// #3724 review: muxing an audio sample counts as writing, not as audio (mixing and + /// encoding), also when the destination refuses it. + #[test] + fn an_audio_mux_write_counts_as_writing() { + use effectcraft_project::render_queue::{OutputModule, RenderSettings}; + let (project, settings, output) = (effectcraft_project::Project::default(), RenderSettings::default(), OutputModule::for_format(OutputFormat::ProRes)); + let job = crate::Job { + project: &project, + footage: &effectcraft_render::NoFootage, + expr: None, + accel: None, + comp: effectcraft_project::ItemId(0), + settings: &settings, + output: &output, + path: "/a/movie.mov", + sink: None, + nested_switches: true, + options: Default::default(), + }; + let delay = std::time::Duration::from_millis(50); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48_000.0 }; + + for fails in [false, true] { + let cx = Cx::new(&job); + let slow = std::rc::Rc::new(std::cell::Cell::new(false)); + let destination = SlowDestination { data: Default::default(), slow: slow.clone(), fails, delay }; + let mut mux = Mp4Writer::new(destination, WriterOptions::new(Brand::Mov)).expect("movie header"); + let track = mux.add_track(TrackConfig::new(SampleEntry::pcm(pcm), 48_000)).expect("audio track"); + slow.set(true); + let started = Instant::now(); + let result = audio_step(&cx, &mut mux, track, || Ok(vec![(vec![0; 4], 1)])); + let wall = started.elapsed().as_secs_f64(); + + assert_eq!(result.is_err(), fails, "the refused write is passed on"); + let timing = cx.timing(wall, 0); + let write = timing.write_seconds.expect("the attempted mux write is timed as writing"); + let audio = timing.audio_seconds.expect("mixing and encoding are timed as audio"); + assert!(write >= delay.as_secs_f64(), "fails {fails}: the slow write is in writing: {timing:?}"); + assert!(audio + write <= wall, "fails {fails}: the write counts once, not in audio too: {timing:?}"); + } + } } diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index b89acbbab..5c9f452a6 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -44,7 +44,9 @@ mod webm_av1; use web_time::Instant; -use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, RenderLog, RenderQuality, RenderSettings, sequence_path}; +use effectcraft_project::render_queue::{ + AudioOutput, Channels, OutputFormat, OutputModule, RenderLog, RenderQuality, RenderSettings, RenderTiming, sequence_path, +}; use effectcraft_project::{Comp, ItemId, Project}; use effectcraft_raster::Image; use effectcraft_render::{ExprHost, FootageSource}; @@ -173,7 +175,7 @@ impl Progress { } /// What an export produced. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct Report { /// The movie file, or the first file of a sequence. pub path: String, @@ -187,6 +189,8 @@ pub struct Report { pub log: Option, /// Files that went to an overflow folder. pub overflow: Vec, + /// Where the time went and what ran the job; the same as the summary line in the render log. + pub timing: RenderTiming, } /// Formats this build can write (all of them; kept as the hook for optional encoders). @@ -225,12 +229,27 @@ pub async fn export_async(job: &Job<'_>, progress: &mut dyn FnMut(&Progress) -> let render = RenderEnd(job.accel.filter(|_| job.options.caches.is_none())); let mut r = export_with(&cx, progress, t0).await; drop(render); + let wall = t0.elapsed().as_secs_f64(); + // (what a failed export got done: its render log carries the line too, with the compositor) + let mut unfinished = None; + if let Err(e) = &r { + // A stopped or failed export gets its line too: slow ones are the ones people stop. + let how = if matches!(e, ExportError::Cancelled) { "stopped" } else { "failed" }; + let t = cx.timing(wall, 0); + log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, t.summary_of_unfinished(how)); + unfinished = Some(t); + } if matches!(r, Err(ExportError::Cancelled)) { cx.remove_cancelled_outputs()?; return r; } - let log = cx.write_log(&r, t0.elapsed().as_secs_f64()); + let timing = r.as_ref().ok().map(|rep| cx.timing(wall, rep.frames)); + if let Some(t) = &timing { + log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, t.summary()); + } + let log = cx.write_log(&r, wall, timing.as_ref().or(unfinished.as_ref())); if let Ok(rep) = &mut r { + rep.timing = timing.unwrap_or_default(); rep.log = log; rep.overflow = cx.overflowed.lock().unwrap_or_else(|e| e.into_inner()).clone(); } @@ -346,7 +365,18 @@ async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) st.advance(end - i)?; i = end; } - Ok(Report { path: sequence_path(cx.path, f0), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![] }) + Ok(Report { + path: sequence_path(cx.path, f0), + frames: 0, + width: w, + height: h, + seconds: 0.0, + bytes, + audio: false, + log: None, + overflow: vec![], + timing: Default::default(), + }) } struct StillOutput { @@ -437,8 +467,10 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ validate_gif_dimensions(w, h)?; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; - let mut enc = AnimationWriter::new( + // Each write is timed before its error is passed on: a failed export's line keeps the time. + let mut file = job.timed(pipeline::Stage::EncodeWrite, || job.create(&path))?; + let t = Instant::now(); + let enc = AnimationWriter::new( &mut file, w, h, @@ -448,7 +480,9 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ speed: 10, }, ) - .map_err(|e| ExportError::Encode(e.to_string()))?; + .map_err(|e| ExportError::Encode(e.to_string())); + job.add_time(pipeline::Stage::EncodeWrite, t); + let mut enc = enc?; let rate = job.settings.rate(comp); // GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing. let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64; @@ -461,19 +495,26 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ let frames: Vec> = job .frames(comp, (i..end).collect(), |_, img| craft_gif::write::prepare_frame(w, h, job.pixels_with(&img, comp, job.output.channels, w, h, false), 10)) .await; - for frame in frames { + let t = Instant::now(); + let wrote = frames.into_iter().try_for_each(|frame| { clock += cs_per_frame; let d = (clock.round() as u64).saturating_sub(emitted).max(1); emitted += d; let frame = frame.map_err(|e| ExportError::Encode(e.to_string()))?; - enc.write_prepared_frame(frame, d.min(u16::MAX as u64) as u16).map_err(|e| ExportError::Encode(e.to_string()))?; - } + enc.write_prepared_frame(frame, d.min(u16::MAX as u64) as u16).map_err(|e| ExportError::Encode(e.to_string())) + }); + // The GIF writer compresses as it writes: the two are not measured apart. + job.add_time(pipeline::Stage::EncodeWrite, t); + wrote?; st.advance(end - i)?; i = end; } - let _ = enc.finish().map_err(|e| ExportError::Encode(e.to_string()))?; - let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![] }) + let t = Instant::now(); + let finished = enc.finish().map(drop).map_err(|e| ExportError::Encode(e.to_string())); + job.add_time(pipeline::Stage::EncodeWrite, t); + finished?; + let bytes = job.timed(pipeline::Stage::EncodeWrite, || file.finish())?; + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![], timing: Default::default() }) } fn validate_gif_dimensions(w: u32, h: u32) -> Result<()> { diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index 1cba495f5..4f57d72ef 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -4,7 +4,9 @@ use std::sync::Mutex; -use effectcraft_project::render_queue::{AlphaMode, Channels, CurrentOrOff, EffectsMode, FrameSample, RenderLog, ResizeQuality, SwitchOverride, log_path}; +use effectcraft_project::render_queue::{ + AlphaMode, Channels, CurrentOrOff, EffectsMode, FrameSample, OutputFormat, OutputModule, RenderLog, RenderTiming, ResizeQuality, SwitchOverride, log_path, +}; use effectcraft_project::{BitDepth, Comp, Project}; use effectcraft_raster::Image; use effectcraft_render::{Backend, LayerCache, RenderOpts, Renderer}; @@ -273,6 +275,46 @@ pub(crate) struct Cx<'a> { /// Files written to an overflow folder. pub overflowed: Mutex>, written: Mutex>, + /// Busy time per stage, for the log's timing line (#3713). + phases: Phases, +} + +/// The stages of a job whose busy time is measured. +#[derive(Clone, Copy)] +pub(crate) enum Stage { + /// Rendering frames (and, for formats that encode and write inside the frame loop, that too). + Render, + Encode, + Write, + Audio, + /// An encoder that writes as it encodes (the GIF writer): the two are not apart. + EncodeWrite, +} + +/// Busy time per [`Stage`] in nanoseconds. The stages overlap (the encoder works on one batch +/// while the next renders), so each is its own total, not a share of the wall time. +#[derive(Default)] +struct Phases { + nanos: [std::sync::atomic::AtomicU64; 5], + /// Bit per stage that was timed: a stage a format doesn't have has no time, not zero. + used: std::sync::atomic::AtomicU8, +} + +impl Phases { + fn add(&self, stage: Stage, since: Instant) { + self.used.fetch_or(1 << stage as u8, std::sync::atomic::Ordering::Relaxed); + let n = u64::try_from(since.elapsed().as_nanos()).unwrap_or(u64::MAX); + if let Some(slot) = self.nanos.get(stage as usize) { + slot.fetch_add(n, std::sync::atomic::Ordering::Relaxed); + } + } + fn seconds(&self, stage: Stage) -> f64 { + self.nanos.get(stage as usize).map_or(0.0, |n| n.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e9) + } + /// The stage's busy time, or `None` when the format never timed it. + fn measured(&self, stage: Stage) -> Option { + (self.used.load(std::sync::atomic::Ordering::Relaxed) & (1 << stage as u8) != 0).then(|| self.seconds(stage)) + } } /// A job's layer caches: its own, or those of the Render Queue run it belongs to. @@ -366,6 +408,7 @@ impl<'a> Cx<'a> { frame_times, overflowed: Mutex::new(vec![]), written: Mutex::new(vec![]), + phases: Phases::default(), }; if let Some(c) = cx.fixed_choice(std::env::var(RENDERER_ENV).ok().as_deref()) { cx.decide(c); @@ -373,6 +416,42 @@ impl<'a> Cx<'a> { cx } + /// Run `f` and add its time to `stage`'s busy time. Formats that encode and write outside + /// the frame loop time those stages this way; a stage never timed is reported as measured + /// together with rendering. + pub(crate) fn timed(&self, stage: Stage, f: impl FnOnce() -> T) -> T { + let t = Instant::now(); + let out = f(); + self.add_time(stage, t); + out + } + + /// [`Cx::timed`] when `on`; otherwise just run `f` (a stage the job doesn't have). + pub(crate) fn timed_if(&self, on: bool, stage: Stage, f: impl FnOnce() -> T) -> T { + if on { self.timed(stage, f) } else { f() } + } + + /// Add the time since `since` to `stage`'s busy time (where a closure cannot wrap the work). + pub(crate) fn add_time(&self, stage: Stage, since: Instant) { + self.phases.add(stage, since); + } + + /// Where the job's time went, for the render log and the [`crate::Report`]. + pub(crate) fn timing(&self, wall: f64, frames: u64) -> RenderTiming { + RenderTiming { + wall_seconds: wall, + render_seconds: self.phases.seconds(Stage::Render), + encode_seconds: self.phases.measured(Stage::Encode), + write_seconds: self.phases.measured(Stage::Write), + encode_write_seconds: self.phases.measured(Stage::EncodeWrite), + audio_seconds: self.phases.measured(Stage::Audio), + frames, + frames_per_second: if wall > 0.0 { frames as f64 / wall } else { 0.0 }, + renderer: self.choice().map_or_else(|| "none was needed".to_string(), |c| describe_choice(&c)), + encoder: describe_encoder(self.job.output), + } + } + /// The project's compositor: the GPU's for GPU Acceleration with an accelerator. fn project_renderer(&self) -> crate::JobRenderer { if self.project.settings.gpu_acceleration && self.job.accel.is_some() { crate::JobRenderer::Gpu } else { crate::JobRenderer::Cpu } @@ -496,15 +575,19 @@ impl<'a> Cx<'a> { /// Output frames `ks`, each mapped by `f` (encoding): rendered in parallel batches, or one /// by one in passes when readbacks are deferred ([`Cx::deferred`]). pub async fn frames(&self, comp: &Comp, ks: Vec, f: impl Fn(u64, Image) -> T + Sync + Send) -> Vec { - if self.deferred() { + let t = Instant::now(); + let out = if self.deferred() { let mut out = Vec::with_capacity(ks.len()); for k in ks { let img = self.frame_async(comp, k).await; out.push(f(k, img)); } - return out; - } - self.render_frames(ks, |k, on| self.frame_on(comp, k, on), f) + out + } else { + self.render_frames(ks, |k, on| self.frame_on(comp, k, on), f) + }; + self.phases.add(Stage::Render, t); + out } /// `render` then `encode` over the frames `ks` on the job's compositor, results in `ks` @@ -818,14 +901,17 @@ impl<'a> Cx<'a> { fallback: impl Fn(u64, Image) -> T + Sync + Send, ) -> Vec { // As in `frames`: once the GPU has stopped for good, the rest render in parallel. - self.render_frames( + let t = Instant::now(); + let out = self.render_frames( ks, |k, on| self.yuv420_frame(comp, k, w, h, on).ok_or_else(|| self.frame_on(comp, k, on)), |k, r| match r { Ok(p) => planes(p), Err(img) => fallback(k, img), }, - ) + ); + self.phases.add(Stage::Render, t); + out } /// Output Module ▸ Crop, then Resize. @@ -938,7 +1024,7 @@ impl<'a> Cx<'a> { } /// Write the render log next to the output, as the Log setting asks. Returns its path. - pub fn write_log(&self, result: &Result, seconds: f64) -> Option { + pub fn write_log(&self, result: &Result, seconds: f64, timing: Option<&RenderTiming>) -> Option { let level = self.job.options.log; // Errors Only: a log for failures (a user stop is not an error). if level == RenderLog::ErrorsOnly && matches!(result, Ok(_) | Err(crate::ExportError::Cancelled)) { @@ -957,6 +1043,14 @@ impl<'a> Cx<'a> { if let Some(c) = self.choice() { s.push_str(&format!("Renderer: {}\n", describe_choice(&c))); } + if let Some(t) = timing { + // (a failed job has no frame count: the line says what ran before it stopped) + let line = if result.is_err() { t.summary_of_unfinished("failed") } else { t.summary() }; + s.push_str(&format!( + "Timing: {line} +" + )); + } if self.backend() == crate::JobRenderer::Gpu && let Some((n, why)) = &*self.gpu_frames.lock().unwrap_or_else(std::sync::PoisonError::into_inner) { @@ -993,6 +1087,34 @@ impl<'a> Cx<'a> { } } +/// The render log's account of the encoder: every encoder here is built in and runs on the +/// CPU (no hardware encoder is used), with the codec settings of the Output Module. +pub(crate) fn describe_encoder(om: &OutputModule) -> String { + use effectcraft_project::render_queue::{ProResProfile, WebmVideoCodec}; + let rate = |om: &OutputModule| match om.codec.rate_control { + effectcraft_project::render_queue::RateControlMode::Bitrate => format!("{} kbps", om.bitrate_kbps), + effectcraft_project::render_queue::RateControlMode::Quality => format!("constant quality {}", om.codec.quality), + }; + let mut label = om.format.label().to_string(); + let settings = match om.format { + OutputFormat::H264 => format!(", {} kbps", om.bitrate_kbps), + OutputFormat::Hevc | OutputFormat::Av1 => format!(", profile {}, {}", om.codec.profile.label(), rate(om)), + // (alpha needs a 4444 flavour: the encoder promotes the profile, so the log names that one) + OutputFormat::ProRes => { + let profile = if om.channels == Channels::Rgba && !om.prores_profile.is_4444() { ProResProfile::P4444 } else { om.prores_profile }; + format!(", profile {}", profile.label()) + } + // (WebM carries VP9 or AV1: the log names the one that is written) + OutputFormat::WebM if om.webm_codec == WebmVideoCodec::Av1 => { + label = "WebM (AV1 + Opus)".to_string(); + format!(", profile {}, {}", om.codec.profile.label(), rate(om)) + } + OutputFormat::WebM => format!(", {:?}{}", om.webm_codec, if om.webm_bitrate { format!(", {} kbps", om.bitrate_kbps) } else { String::new() }), + _ => String::new(), + }; + format!("{label}{settings}, built-in software encoder (not a hardware encoder)") +} + /// The render log's account of a job's compositor: which, why, and what was measured. pub(crate) fn describe_choice(c: &Choice) -> String { let name = match c.renderer { @@ -1088,6 +1210,25 @@ mod tests { use rayon::prelude::*; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + /// #3724 review: the log names the profile and codec that are written: alpha promotes ProRes + /// to 4444, and WebM with AV1 says AV1 (not VP9). + #[test] + fn the_encoder_description_names_what_is_written() { + use effectcraft_project::render_queue::{Channels, ProResProfile, WebmVideoCodec}; + let mut om = OutputModule { format: OutputFormat::ProRes, prores_profile: ProResProfile::Hq, channels: Channels::Rgb, ..OutputModule::default() }; + let hq = describe_encoder(&om); + assert!(hq.contains(ProResProfile::Hq.label()) && !hq.contains("4444"), "{hq}"); + om.channels = Channels::Rgba; + let alpha = describe_encoder(&om); + assert!(alpha.contains(ProResProfile::P4444.label()) && !alpha.contains(ProResProfile::Hq.label()), "{alpha}"); + let mut web = OutputModule { format: OutputFormat::WebM, webm_codec: WebmVideoCodec::Av1, ..OutputModule::default() }; + let av1 = describe_encoder(&web); + assert!(av1.starts_with("WebM (AV1 + Opus)") && !av1.contains("VP9") && av1.contains("profile"), "{av1}"); + web.webm_codec = WebmVideoCodec::Vp9; + let vp9 = describe_encoder(&web); + assert!(vp9.starts_with("WebM (VP9 + Opus)") && !vp9.contains("AV1"), "{vp9}"); + } + /// Dither may round a colour up while alpha rounds down; premultiplied colour stays at or /// below the written alpha at every pixel. #[test] diff --git a/crates/export/src/webm.rs b/crates/export/src/webm.rs index 3633728bf..b116ec198 100644 --- a/crates/export/src/webm.rs +++ b/crates/export/src/webm.rs @@ -18,8 +18,10 @@ use craft_audio::opus::encoder as opus; use effectcraft_project::Comp; use effectcraft_project::render_queue::{AudioFormat, Channels}; use effectcraft_time::{TICKS_PER_SECOND, Tick}; +use web_time::Instant; use crate::encode::{mix, pcm_bytes}; +use crate::pipeline::Stage; use crate::{Cx, ExportError, Report, Result, State, batch_size, io, wants_audio}; pub(crate) const OPUS_RATE: u32 = 48_000; @@ -168,7 +170,8 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta let duration_ms = frame_ms(total) as f64; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; + // Each write is timed before its error is passed on: a failed export's line keeps the time. + let mut file = job.timed(Stage::Write, || job.create(&path))?; // EBML header. let mut head = vec![]; let mut eb = vec![]; @@ -227,7 +230,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta el(&mut tracks, TRACK_ENTRY, &a); } el(&mut head, TRACKS, &tracks); - file.write_all(&head).map_err(io)?; + job.timed(Stage::Write, || file.write_all(&head).map_err(io))?; let mut seg_len = head.len() as u64 - seg_start; // Audio: mixed in blocks, encoded in 20 ms packets. @@ -270,6 +273,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta let pixels: Vec> = job.frames(comp, (i..end).collect(), |_, img| job.pixels(&img, comp, if alpha { Channels::Rgba } else { colour_channels }, w, h)).await; let mut frames: Vec = Vec::with_capacity(pixels.len()); + let t = Instant::now(); for (j, px) in pixels.iter().enumerate() { let (color, a) = rayon::join( || { @@ -287,32 +291,41 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta frames.push(Frame { ms: frame_ms(k), track: 1, key: color.key, prev_ms: (k > 0).then(|| frame_ms(k - 1)), data: color.data, alpha: a }); } drop(pixels); + job.add_time(Stage::Encode, t); let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) }; - audio_until(t_end, &mut frames, end >= total)?; - let c = cluster(&mut frames); - file.write_all(&c).map_err(io)?; - seg_len += c.len() as u64; + job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut frames, end >= total))?; + job.timed(Stage::Write, || -> Result<()> { + let c = cluster(&mut frames); + file.write_all(&c).map_err(io)?; + seg_len += c.len() as u64; + Ok(()) + })?; st.advance(end - i)?; i = end; } if total == 0 { let mut frames = vec![]; - audio_until(span_end, &mut frames, true)?; + job.timed_if(with_audio, Stage::Audio, || audio_until(span_end, &mut frames, true))?; if !frames.is_empty() { - let c = cluster(&mut frames); - file.write_all(&c).map_err(io)?; - seg_len += c.len() as u64; + job.timed(Stage::Write, || -> Result<()> { + let c = cluster(&mut frames); + file.write_all(&c).map_err(io)?; + seg_len += c.len() as u64; + Ok(()) + })?; } } // Patch the Segment size. let mut size = [0u8; 8]; size[0] = 0x01; size[1..].copy_from_slice(&seg_len.to_be_bytes()[1..]); - file.seek(SeekFrom::Start(size_pos)).map_err(io)?; - file.write_all(&size).map_err(io)?; - file.seek(SeekFrom::End(0)).map_err(io)?; - let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] }) + let bytes = job.timed(Stage::Write, || -> Result { + file.seek(SeekFrom::Start(size_pos)).map_err(io)?; + file.write_all(&size).map_err(io)?; + file.seek(SeekFrom::End(0)).map_err(io)?; + file.finish() + })?; + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } // ---------------------------------------------------------------- audio-only outputs @@ -356,7 +369,7 @@ pub(crate) fn audio_file(job: &Cx, comp: &Comp, aiff: bool, st: &mut State) -> R let sample = start + done as i64; let t = Tick::from_units(sample, i64::from(sr)); let t = if t.to_units_floor(i64::from(sr)) < sample { Tick(t.0.saturating_add(1)) } else { t }; - pcm.extend(pcm_bytes(&mix(job, t, k, sr), fmt, aiff)); + pcm.extend(job.timed(Stage::Audio, || pcm_bytes(&mix(job, t, k, sr), fmt, aiff))); done += k; let now = (done as u64 * total_frames / n.max(1) as u64).min(total_frames); if now > reported && st.total > 0 { @@ -428,11 +441,15 @@ pub(crate) fn audio_file(job: &Cx, comp: &Comp, aiff: bool, st: &mut State) -> R out.push(0); } } - let path = job.place(job.path, out.len() as u64); - let mut file = job.create(&path)?; - file.write_all(&out).map_err(io)?; - let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: 0, height: 0, seconds: 0.0, bytes, audio: true, log: None, overflow: vec![] }) + // Timed before the error is passed on: a failed export's line keeps the time. + let (path, bytes) = job.timed(Stage::Write, || -> Result<(String, u64)> { + let path = job.place(job.path, out.len() as u64); + let mut file = job.create(&path)?; + file.write_all(&out).map_err(io)?; + let bytes = file.finish()?; + Ok((path, bytes)) + })?; + Ok(Report { path, frames: 0, width: 0, height: 0, seconds: 0.0, bytes, audio: true, log: None, overflow: vec![], timing: Default::default() }) } #[cfg(test)] diff --git a/crates/export/src/webm_av1.rs b/crates/export/src/webm_av1.rs index fc9545a10..eb78af777 100644 --- a/crates/export/src/webm_av1.rs +++ b/crates/export/src/webm_av1.rs @@ -12,6 +12,7 @@ use effectcraft_time::{TICKS_PER_SECOND, Tick}; use crate::encode::VideoEncoder; use crate::encode::mix; +use crate::pipeline::Stage; use crate::webm::{CLUSTER, EBML, INFO, OPUS_RATE, SEGMENT, TRACK_ENTRY, TRACKS, el, el_float, el_str, el_uint, id_bytes, opus_encoder, vint}; use crate::{Cx, Report, Result, State, batch_size, io, wants_audio}; @@ -52,7 +53,8 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut let duration_ms = frame_ms(total) as f64; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; + // Each write is timed before its error is passed on: a failed export's line keeps the time. + let mut file = job.timed(Stage::Write, || job.create(&path))?; let mut head = vec![]; let mut eb = vec![]; el_uint(&mut eb, 0x4286, 1); @@ -104,7 +106,7 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut el(&mut tracks, TRACK_ENTRY, &a); } el(&mut head, TRACKS, &tracks); - file.write_all(&head).map_err(io)?; + job.timed(Stage::Write, || file.write_all(&head).map_err(io))?; let mut seg_len = head.len() as u64 - seg_start; let (span_start, span_end) = job.settings.span(comp); @@ -155,26 +157,28 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut let frames: Vec> = job.frames(comp, (i..end).collect(), |_, img| job.pixels(&img, comp, channels, w, h)).await; for (j, px) in frames.iter().enumerate() { let k = i + j as u64; - for p in venc.encode(px, k)? { + for p in job.timed(Stage::Encode, || venc.encode(px, k))? { blocks.push(Block { ms: frame_ms(k), track: 1, key: p.key, data: p.data }); } } let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) }; - audio_until(t_end, &mut blocks, end >= total)?; - flush_blocks(&mut blocks, &mut file, &mut seg_len)?; + job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut blocks, end >= total))?; + job.timed(Stage::Write, || flush_blocks(&mut blocks, &mut file, &mut seg_len))?; st.advance(end - i)?; i = end; } if total == 0 { - audio_until(span_end, &mut blocks, true)?; - flush_blocks(&mut blocks, &mut file, &mut seg_len)?; + job.timed_if(with_audio, Stage::Audio, || audio_until(span_end, &mut blocks, true))?; + job.timed(Stage::Write, || flush_blocks(&mut blocks, &mut file, &mut seg_len))?; } let mut size = [0u8; 8]; size[0] = 0x01; size[1..].copy_from_slice(&seg_len.to_be_bytes()[1..]); - file.seek(SeekFrom::Start(size_pos)).map_err(io)?; - file.write_all(&size).map_err(io)?; - file.seek(SeekFrom::End(0)).map_err(io)?; - let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] }) + let bytes = job.timed(Stage::Write, || -> Result { + file.seek(SeekFrom::Start(size_pos)).map_err(io)?; + file.write_all(&size).map_err(io)?; + file.seek(SeekFrom::End(0)).map_err(io)?; + file.finish() + })?; + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } diff --git a/crates/export/tests/it/export_timing.rs b/crates/export/tests/it/export_timing.rs new file mode 100644 index 000000000..7315e18c1 --- /dev/null +++ b/crates/export/tests/it/export_timing.rs @@ -0,0 +1,199 @@ +//! The summary line of an export (#3713): where the time went and what ran the job. + +use std::sync::{Arc, Mutex}; + +use effectcraft_color::Label; +use effectcraft_export::render_queue::{OutputFormat, OutputModule, RenderLog, RenderSettings, TimeSpan}; +use effectcraft_export::{Job, JobOptions, Sink, export}; +use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid, build}; +use effectcraft_render::NoFootage; +use effectcraft_time::{FrameRate, Tick}; + +fn project() -> (Project, ItemId) { + let mut p = Project::default(); + let comp = Comp::new(64, 48, FrameRate::new(30, 1), Tick::from_seconds_f64(1.0)); + let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color: [0.9, 0.5, 0.1], width: 64, height: 48, pixel_aspect: 1.0 })); + let layer = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (64, 48), None); + let mut comp = comp; + comp.layers = vec![layer].into(); + let cid = p.add_item("Comp 1", Label::Sandstone, None, ItemKind::Comp(comp.into())); + (p, cid) +} + +#[test] +fn a_movie_export_reports_where_the_time_went() { + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::H264); + let files: Arc)>>> = Arc::default(); + let sink_files = files.clone(); + let sink: &Sink = &move |path: &str, data: Vec| sink_files.lock().unwrap().push((path.to_string(), data)); + let job = Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings: &settings, + output: &om, + path: "/out/timing.mp4", + sink: Some(sink), + options: JobOptions { log: RenderLog::PlusSettings, label: "#1 Comp 1".into(), ..Default::default() }, + nested_switches: true, + }; + let r = export(&job, &mut |_| true).expect("export"); + let t = &r.timing; + assert_eq!(t.frames, 30); + assert!(t.wall_seconds > 0.0); + // The movie formats time encoding and writing apart from rendering. + let (encode, write) = (t.encode_seconds.expect("encode time"), t.write_seconds.expect("write time")); + for (name, secs) in [("render", t.render_seconds), ("encode", encode), ("write", write)] { + assert!(secs >= 0.0 && secs <= t.wall_seconds, "{name} {secs} s of {} s wall", t.wall_seconds); + } + assert!(t.render_seconds > 0.0 && encode > 0.0, "{t:?}"); + assert_eq!(t.audio_seconds, None); + assert!((t.frames_per_second - 30.0 / t.wall_seconds).abs() < 1e-9); + assert!(t.renderer.starts_with("Software Rendering"), "{}", t.renderer); + assert!(t.encoder.contains("H.264") && t.encoder.contains("software"), "{}", t.encoder); + + let line = t.summary(); + for part in + ["export took", "30 frames", "frames/s", "overlap", "rendering frames", "encoder", "writing output", "Compositor: Software Rendering", "Encoder: H.264"] + { + assert!(line.contains(part), "{part:?} missing from {line}"); + } + // The render log carries the same line. + let files = files.lock().unwrap(); + let log = files.iter().find(|(path, _)| path.ends_with(".txt")).map(|(_, d)| String::from_utf8_lossy(d).into_owned()).expect("render log"); + assert!(log.contains(&format!("Timing: {line}")), "{log}"); +} + +fn job_of<'a>(p: &'a Project, cid: ItemId, settings: &'a RenderSettings, om: &'a OutputModule, path: &'a str, sink: &'a Sink) -> Job<'a> { + Job { + project: p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings, + output: om, + path, + sink: Some(sink), + options: Default::default(), + nested_switches: true, + } +} + +#[test] +fn an_image_sequence_says_the_stages_are_measured_together() { + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::PngSequence); + let sink: &Sink = &|_: &str, _: Vec| {}; + let r = export(&job_of(&p, cid, &settings, &om, "/out/timing_[#####].png", sink), &mut |_| true).expect("export"); + let t = &r.timing; + assert_eq!((t.encode_seconds, t.write_seconds, t.encode_write_seconds), (None, None, None)); + assert!(t.render_seconds <= t.wall_seconds); + assert!(t.summary().contains("rendering, encoding and writing measured together"), "{}", t.summary()); +} + +#[test] +fn gif_and_webm_time_the_stages_they_have() { + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let sink: &Sink = &|_: &str, _: Vec| {}; + let gif = OutputModule::for_format(OutputFormat::Gif); + let t = export(&job_of(&p, cid, &settings, &gif, "/out/timing.gif", sink), &mut |_| true).expect("gif").timing; + assert_eq!((t.encode_seconds, t.write_seconds), (None, None)); + let both = t.encode_write_seconds.expect("encode and write time"); + assert!(both >= 0.0 && both <= t.wall_seconds && t.render_seconds <= t.wall_seconds); + assert!(t.summary().contains("encoding and writing output measured together"), "{}", t.summary()); + + let webm = OutputModule::for_format(OutputFormat::WebM); + let t = export(&job_of(&p, cid, &settings, &webm, "/out/timing.webm", sink), &mut |_| true).expect("webm").timing; + let (e, w) = (t.encode_seconds.expect("encode"), t.write_seconds.expect("write")); + assert!(e <= t.wall_seconds && w <= t.wall_seconds && t.render_seconds <= t.wall_seconds, "{t:?}"); +} + +/// #3724 review: a failed export's render log carries the timing line too (with the compositor +/// that ran), not only a finished one's. +#[test] +fn a_failed_export_logs_its_timing_line_too() { + let (p, _) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::H264); + let files: Arc)>>> = Arc::default(); + let sink_files = files.clone(); + let sink: &Sink = &move |path: &str, data: Vec| sink_files.lock().unwrap().push((path.to_string(), data)); + // A composition that is not there: the export fails before it renders anything. + let job = job_of(&p, ItemId(9999), &settings, &om, "/out/failed.mp4", sink); + assert!(export(&job, &mut |_| true).is_err(), "no such composition"); + let files = files.lock().unwrap(); + let log = files.iter().find(|(path, _)| path.ends_with(".txt")).map(|(_, d)| String::from_utf8_lossy(d).into_owned()).expect("a failed job writes its log"); + assert!(log.contains("Result: Failed"), "{log}"); + assert!(log.contains("Timing: export failed after"), "{log}"); +} + +/// #3724 review: a write that fails still counts in the failed job's line. The output path is a +/// folder, so opening the output file fails; the log next to it names the writing stage. +#[test] +fn a_failed_write_keeps_its_time_in_the_log() { + use effectcraft_export::render_queue::WebmVideoCodec; + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let dir = tempfile::tempdir().expect("temp dir"); + let vp9 = OutputModule::for_format(OutputFormat::WebM); + let av1 = OutputModule { webm_codec: WebmVideoCodec::Av1, ..OutputModule::for_format(OutputFormat::WebM) }; + let cases = [ + ("h264.mp4", OutputModule::for_format(OutputFormat::H264), "writing output"), + ("anim.gif", OutputModule::for_format(OutputFormat::Gif), "encoding and writing output measured together"), + ("vp9.webm", vp9, "writing output"), + ("av1.webm", av1, "writing output"), + ("wave.wav", OutputModule::for_format(OutputFormat::Wav), "writing output"), + ("aiff.aiff", OutputModule::for_format(OutputFormat::Aiff), "writing output"), + ]; + let mut misses = vec![]; + for (name, om, stage) in cases { + let out = dir.path().join(name); + std::fs::create_dir(&out).expect("a folder where the output should go"); + let path = out.to_string_lossy().into_owned(); + let job = Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings: &settings, + output: &om, + path: &path, + sink: None, + options: Default::default(), + nested_switches: true, + }; + if export(&job, &mut |_| true).is_ok() { + misses.push(format!("{name}: the export did not fail")); + continue; + } + let stem = name.split('.').next().unwrap_or(name); + let log = std::fs::read_to_string(dir.path().join(format!("{stem}_RenderLog.txt"))).unwrap_or_default(); + let line = log.lines().find(|l| l.starts_with("Timing: export failed after")).unwrap_or_default(); + if !line.contains(stage) || line.contains("rendering, encoding and writing measured together") { + misses.push(format!("{name}: {stage:?} missing from {line:?}")); + } + } + assert!(misses.is_empty(), "{misses:#?}"); +} + +#[test] +fn a_stopped_export_has_a_summary_without_a_frame_count() { + let t = effectcraft_export::render_queue::RenderTiming { + wall_seconds: 2.0, + render_seconds: 1.5, + renderer: "Software Rendering (x)".into(), + encoder: "H.264".into(), + ..Default::default() + }; + let line = t.summary_of_unfinished("stopped"); + assert!(line.starts_with("export stopped after 2.00 s. Busy time per stage"), "{line}"); + assert!(!line.contains("frames/s"), "{line}"); +} diff --git a/crates/export/tests/it/main.rs b/crates/export/tests/it/main.rs index 545181859..50b2f3bb9 100644 --- a/crates/export/tests/it/main.rs +++ b/crates/export/tests/it/main.rs @@ -3,6 +3,7 @@ mod audio_sample_positions; mod av1_encoder; mod banding; +mod export_timing; mod exr_scene_linear; mod h264_gpu_yuv; mod hevc_av1_roundtrip; diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 54386ccad..14b2e3bd8 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -84,6 +84,7 @@ impl Exporter for FileExporter { audio: r.audio, log: r.log, overflow: r.overflow, + timing: Some(r.timing), }), Err(effectcraft_export::ExportError::Cancelled) => Err(effectcraft_engine::render_queue::CANCELLED.into()), Err(e) => Err(e.to_string()), diff --git a/crates/project/src/render_queue.rs b/crates/project/src/render_queue.rs index b935c2fc8..cef9b6ec2 100644 --- a/crates/project/src/render_queue.rs +++ b/crates/project/src/render_queue.rs @@ -1473,6 +1473,76 @@ impl RenderStatus { } } +/// Where one export's time went, and what it ran on (the render log's summary line, #3713). +/// The stages overlap (the encoder works on one batch while the next renders), so the +/// `*_seconds` are each stage's busy time and not a sum; none of them is more than `wall_seconds`. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct RenderTiming { + /// The whole job, start to end. + pub wall_seconds: f64, + /// Time rendering frames (the compositor, including the conversion to the encoder's pixels). + /// For formats that encode and write inside the frame loop (image sequences) it also holds + /// the encoding and writing: `encode_seconds` and `write_seconds` are `None`. + pub render_seconds: f64, + /// Time in the video encoder (`None`: not measured apart from rendering). + #[serde(skip_serializing_if = "Option::is_none")] + pub encode_seconds: Option, + /// Time writing and muxing the output file (`None`: not measured apart from rendering). + #[serde(skip_serializing_if = "Option::is_none")] + pub write_seconds: Option, + /// Time in an encoder that writes as it encodes (GIF): encoding and writing are not apart. + #[serde(skip_serializing_if = "Option::is_none")] + pub encode_write_seconds: Option, + /// Time mixing and encoding the audio track (`None`: no separate audio stage). + #[serde(skip_serializing_if = "Option::is_none")] + pub audio_seconds: Option, + pub frames: u64, + /// Frames per second of wall time over the whole job. + pub frames_per_second: f64, + /// The compositor and why it was used. + pub renderer: String, + /// The encoder: name, software or hardware, codec settings. + pub encoder: String, +} + +impl RenderTiming { + /// The one-line summary for the render log. + pub fn summary(&self) -> String { + let head = format!("export took {:.2} s for {} frames ({:.2} frames/s)", self.wall_seconds, self.frames, self.frames_per_second); + self.line(&head) + } + + /// The summary of a job that was stopped or failed `how` (the frames done are not counted). + pub fn summary_of_unfinished(&self, how: &str) -> String { + self.line(&format!("export {how} after {:.2} s", self.wall_seconds)) + } + + fn line(&self, head: &str) -> String { + let (r, mut s) = (self.render_seconds, String::new()); + if self.encode_seconds.is_none() && self.write_seconds.is_none() && self.encode_write_seconds.is_none() { + s.push_str(&format!("rendering, encoding and writing measured together {r:.2} s")); + } else if self.encode_write_seconds.is_some() { + // The GIF palette is quantised on the render threads, so it counts as rendering. + s.push_str(&format!("rendering frames (GIF: including palette quantizing) {r:.2} s")); + } else if r > 0.0 { + s.push_str(&format!("rendering frames {r:.2} s")); + } + for (label, v) in [ + ("encoder", self.encode_seconds), + ("writing output", self.write_seconds), + ("encoding and writing output measured together", self.encode_write_seconds), + ("audio", self.audio_seconds), + ] { + if let Some(v) = v { + s.push_str(&format!("{}{label} {v:.2} s", if s.is_empty() { "" } else { ", " })); + } + } + let stages = s; + format!("{head}. Busy time per stage (the stages overlap, so this is not a sum): {stages}. Compositor: {}. Encoder: {}", self.renderer, self.encoder) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RenderQueueItem { /// Stable id (unique within the queue). @@ -1495,6 +1565,9 @@ pub struct RenderQueueItem { /// Resolved path of the last render (first file for sequences). #[serde(default)] pub last_output: Option, + /// Where the last render's time went (see [`RenderTiming`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_timing: Option, /// Further Output Modules (Composition ▸ Add Output Module): the same frames are encoded /// once per module. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -1624,6 +1697,7 @@ impl RenderQueueItem { started: None, render_time: None, last_output: None, + last_timing: None, extra_outputs: vec![], post_render: PostRenderAction::None, log: RenderLog::ErrorsOnly, diff --git a/docs/preferences.md b/docs/preferences.md index 04f1415f1..cb6bc6be9 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -111,6 +111,13 @@ Commands (CLI, MCP, control channel): names it and why). `EFFECTCRAFT_RQ_RENDERER` set to `gpu` or `cpu` skips it and renders on that compositor; `auto` (the default) measures. A queue item's later output modules reuse its first one's choice, and Software Rendering projects always render on the CPU. + When a job ends, the log target `effectcraft_export` gets one timing line, and the render log + gets it as a `Timing:` line when its Log setting writes a log for that outcome (under the + default Errors Only, failed jobs only; a failed job's line says how long it ran and what ran + before it stopped): the wall time, the busy time of rendering, the encoder and writing the file + (the stages overlap, so they are not a sum), the compositor and why, the encoder and its + settings, and frames per second ([#3713](https://github.com/storytold/effectcraft/issues/3713)). + `effectcraft-cli render --json` returns it as `timing` and `timingSummary`. - `threeD.defaultRenderer`: Default 3D Renderer - `labels.N.name` / `labels.N.color`: the 16 label names and colours, used by the Label menu, the timeline, project panel, render queue and viewer handles